From 13ae7a7050538e589596bed1484b1b6fea17fe06 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:50:06 +0100 Subject: [PATCH 001/568] Add local Gmail storage and reduce repeated UI and backend work --- .github/workflows/ci.yml | 1 + .../workflows/performance-verification.yml | 76 +++ AGENTS.md | 4 + Cargo.lock | 8 +- Cargo.toml | 2 +- Makefile | 25 +- app/CMakeLists.txt | 11 +- app/qml/StandaloneShell.qml | 1 + app/src/application_host.cpp | 11 + app/src/application_host.h | 2 + app/src/backend_contract.h.in | 6 + app/src/resource_check.cpp | 6 +- app/tests/native/tst_resources.cpp | 25 +- app/tests/qml/HostFixture.qml | 1 + .../qml/imports/Omamail/Native/NativeHost.qml | 1 + app/tests/qml/tst_standalone_composition.qml | 2 +- backend-api.json | 199 ++++++- benchmarks/mail/README.md | 16 + benchmarks/mail/compare_ui.py | 215 ++++++++ benchmarks/mail/compiler_profiles.py | 50 ++ benchmarks/mail/reader_concurrency.py | 4 +- benchmarks/mail/reader_pipeline.py | 4 +- benchmarks/mail/roundtrip.py | 4 +- benchmarks/mail/ui_latency.py | 112 ++++ docs/BACKEND-RUNTIME.md | 8 + docs/BACKEND.md | 6 +- docs/KEYS.md | 13 +- docs/LOCAL-MAIL.md | 43 ++ docs/PERFORMANCE-VALIDATION.md | 67 +++ scripts/backend-runtime.py | 6 +- scripts/diagnostics.py | 53 +- scripts/verify-performance.py | 257 +++++++++ src/attachment/mod.rs | 1 + src/attachment/vault.rs | 186 +++++++ src/backend/attachments.rs | 144 +++++ src/backend/diagnostics.rs | 227 ++++++++ src/backend/methods.rs | 21 + src/backend/mod.rs | 243 ++++++++- src/backend/protocol.rs | 10 + src/backend/reader.rs | 127 ++++- src/backend/rpc.rs | 55 +- src/cache/render.rs | 2 +- src/cache/resource.rs | 47 ++ src/cache/store.rs | 15 +- src/calendar/mod.rs | 2 + src/calendar/parse/dates.rs | 262 ++++++++++ src/calendar/parse/ics.rs | 273 ++++++++++ src/calendar/parse/mod.rs | 297 +++++++++++ src/calendar/parse/recurrence.rs | 201 +++++++ src/calendar/reads.rs | 99 ++++ src/compose/mod.rs | 10 + src/lib.rs | 1 + src/local_mail/content.rs | 80 +++ src/local_mail/ipc.rs | 214 ++++++++ src/local_mail/mod.rs | 386 ++++++++++++++ src/local_mail/recovery_tests.rs | 290 +++++++++++ src/local_mail/schema.sql | 57 ++ src/local_mail/search.rs | 225 ++++++++ src/local_mail/store.rs | 485 +++++++++++++++++ src/local_mail/sync.rs | 493 ++++++++++++++++++ src/local_mail/tests.rs | 399 ++++++++++++++ src/local_mail/vfs.rs | 471 +++++++++++++++++ src/message/compose.rs | 42 ++ src/outbox/mod.rs | 148 +++++- src/outbox/tests.rs | 67 +++ src/platform/ipc/unix.rs | 3 + src/platform/ipc/windows.rs | 3 + src/platform/private_fs/unix.rs | 27 + src/platform/private_fs/windows.rs | 22 + src/process/async_run.rs | 91 +++- src/providers/gmail.rs | 73 +++ src/providers/gmail_diagnostics.rs | 96 +++- src/providers/gmail_http.rs | 31 +- src/providers/gmail_http_runtime_tests.rs | 1 + src/sync/preload.rs | 3 + tests/calendar_parse_oracle.js | 24 + tests/run_qml_components.py | 45 ++ tests/test_app_make.py | 6 +- tests/test_backend_api.py | 1 + tests/test_backend_runtime.py | 2 +- tests/test_diagnostics.py | 39 ++ tests/test_gmail_backend.js | 30 ++ tests/test_performance_verification.py | 92 ++++ tests/test_source.sh | 12 +- ui/App.qml | 60 +-- ui/Service.qml | 26 +- ui/account/AccountResources.qml | 76 +++ ui/account/LocalMailbox.qml | 159 ++++++ ui/account/MailAccount.qml | 120 +++-- ui/account/SendQueue.qml | 11 +- ui/backend/Backend.qml | 16 +- ui/backend/Compatibility.js | 15 + ui/backend/Runtime.js | 4 +- ui/backend/Runtime.qml | 8 +- ui/backend/Wire.js | 5 +- ui/calendar/Cache.js | 83 ++- ui/calendar/Calendar.js | 20 + ui/calendar/CalendarCache.qml | 12 +- ui/calendar/CalendarController.qml | 134 +++-- ui/components/CalendarView.qml | 25 +- ui/components/ComposeView.qml | 21 +- ui/components/IconButton.qml | 17 +- ui/components/LocalMailStatus.qml | 106 ++++ ui/components/MessageList.qml | 86 ++- ui/components/UndoSendToast.qml | 12 +- ui/components/WeekCalendarView.qml | 19 +- ui/compose/Recipients.js | 41 +- ui/controls/Button.qml | 21 +- ui/controls/PanelActionButton.qml | 21 +- ui/inbox/InboxTools.qml | 10 +- ui/providers/GmailApi.js | 19 + ui/providers/GmailApiClient.qml | 33 ++ ui/tests/qml/tst_app_navigation.qml | 48 +- ui/tests/qml/tst_attachment_preview.qml | 35 +- ui/tests/qml/tst_backend.qml | 34 +- ui/tests/qml/tst_backend_runtime.qml | 12 +- ui/tests/qml/tst_calendar_controller.qml | 10 +- ui/tests/qml/tst_composer_sender_name.qml | 3 +- ui/tests/qml/tst_event_suggestions.qml | 5 +- ui/tests/qml/tst_inbox_tools.qml | 18 +- ui/tests/qml/tst_keyrouter.qml | 42 ++ ui/tests/qml/tst_load_more.qml | 52 +- ui/tests/qml/tst_local_mail_status.qml | 88 ++++ ui/tests/qml/tst_message_list_press.qml | 4 +- ui/tests/qml/tst_service_backend_path.qml | 6 + ui/tests/qml/tst_undo_send_toast.qml | 19 + ui/tests/test_backend_compatibility.js | 20 + ui/tests/test_backend_queue.js | 18 +- ui/tests/test_backend_runtime.js | 5 + ui/tests/test_calendar_cache.js | 18 + ui/tests/test_calendar_feed.js | 7 + ui/tests/test_gmail_api.js | 10 + 132 files changed, 8576 insertions(+), 478 deletions(-) create mode 100644 .github/workflows/performance-verification.yml create mode 100644 app/src/backend_contract.h.in create mode 100644 benchmarks/mail/compare_ui.py create mode 100644 benchmarks/mail/compiler_profiles.py create mode 100644 benchmarks/mail/ui_latency.py create mode 100644 docs/LOCAL-MAIL.md create mode 100644 docs/PERFORMANCE-VALIDATION.md create mode 100644 scripts/verify-performance.py create mode 100644 src/attachment/vault.rs create mode 100644 src/backend/attachments.rs create mode 100644 src/backend/diagnostics.rs create mode 100644 src/calendar/parse/dates.rs create mode 100644 src/calendar/parse/ics.rs create mode 100644 src/calendar/parse/mod.rs create mode 100644 src/calendar/parse/recurrence.rs create mode 100644 src/calendar/reads.rs create mode 100644 src/local_mail/content.rs create mode 100644 src/local_mail/ipc.rs create mode 100644 src/local_mail/mod.rs create mode 100644 src/local_mail/recovery_tests.rs create mode 100644 src/local_mail/schema.sql create mode 100644 src/local_mail/search.rs create mode 100644 src/local_mail/store.rs create mode 100644 src/local_mail/sync.rs create mode 100644 src/local_mail/tests.rs create mode 100644 src/local_mail/vfs.rs create mode 100644 tests/calendar_parse_oracle.js create mode 100644 tests/run_qml_components.py create mode 100644 tests/test_performance_verification.py create mode 100644 ui/account/AccountResources.qml create mode 100644 ui/account/LocalMailbox.qml create mode 100644 ui/components/LocalMailStatus.qml create mode 100644 ui/tests/qml/tst_local_mail_status.qml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 133d7d93e..6dc986e7b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -325,6 +325,7 @@ jobs: - name: Require exact pin and verify the released API against the published binary env: GH_TOKEN: ${{ github.token }} + GH_REPO: huacnlee/omamail ARCH: ${{ matrix.arch }} SOURCE_BRANCH: ${{ github.head_ref || github.ref_name }} run: | diff --git a/.github/workflows/performance-verification.yml b/.github/workflows/performance-verification.yml new file mode 100644 index 000000000..c02dd6901 --- /dev/null +++ b/.github/workflows/performance-verification.yml @@ -0,0 +1,76 @@ +name: Performance verification + +on: + pull_request: + paths: + - "src/**" + - "ui/**" + - "app/**" + - "tests/**" + - "scripts/**" + - "benchmarks/**" + - "Cargo.*" + - "backend-api.json" + - "Makefile" + - ".github/workflows/performance-verification.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: performance-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + name: Synthetic verification (${{ matrix.profile }}) + runs-on: ubuntu-24.04 + timeout-minutes: 90 + strategy: + fail-fast: false + max-parallel: 1 + matrix: + profile: [ci, benchmarks] + steps: + - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + with: + fetch-depth: 0 + persist-credentials: false + - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 + with: + toolchain: "1.98.1" + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.13.5" + - uses: actions/setup-node@v4 + with: + node-version: "20" + - uses: jurplel/install-qt-action/action@d325aaf2a8baeeda41ad0b5d39f84a6af9bcf005 # v4.3.0 + with: + version: "6.8.3" + cache: true + aqtversion: "==3.3.0" + py7zrversion: "==1.0.0" + - name: Install test dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends cmake ninja-build dbus-daemon bubblewrap poppler-utils libdbus-1-3 libegl1 libgl1 libxkbcommon-x11-0 libxcb-cursor0 + - name: Run gates and retain all failures + env: + PROFILE: ${{ matrix.profile }} + run: python3 scripts/verify-performance.py --profile "$PROFILE" --output "$RUNNER_TEMP/magpie-verification" + - name: Summarize + if: always() + run: | + if test -f "$RUNNER_TEMP/magpie-verification/summary.md"; then + cat "$RUNNER_TEMP/magpie-verification/summary.md" >> "$GITHUB_STEP_SUMMARY" + fi + - uses: actions/upload-artifact@v4 + if: always() + with: + name: magpie-verification-${{ matrix.profile }} + path: ${{ runner.temp }}/magpie-verification + if-no-files-found: error + retention-days: 14 diff --git a/AGENTS.md b/AGENTS.md index f553b61ae..e9a35e697 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,9 @@ # Repository working agreements +## Showing Dave completed work + +Read and follow the canonical Peacock guide, including “Noting a small finished thing”, when delivering completed work. Keep publishing policy in that guide and link to it here instead of copying it. + ## Required reading by task Read the relevant document before changing its area; these contain constraints that are easy to miss in the code. diff --git a/Cargo.lock b/Cargo.lock index 8d5715d0f..4ca743045 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1214,9 +1214,9 @@ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "libsqlite3-sys" -version = "0.36.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" dependencies = [ "cc", "pkg-config", @@ -1932,9 +1932,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" dependencies = [ "bitflags", "fallible-iterator", diff --git a/Cargo.toml b/Cargo.toml index 11ce3f0ba..6c71498fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ tokio-rustls = { version = "0.26", default-features = false, features = ["ring", rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } webpki-roots = "1" hickory-resolver = "0.25" -rusqlite = { version = "0.38", features = ["bundled"] } +rusqlite = { version = "0.39", features = ["bundled"] } sha2 = "0.10" unicode-normalization = "0.1" futures-util = "0.3" diff --git a/Makefile b/Makefile index 389c7b1c7..2c430c3f3 100644 --- a/Makefile +++ b/Makefile @@ -4,9 +4,10 @@ QML_FILES := ui/tests/qml/tst_attachment_preview.qml ui/tests/qml/tst_inbox_tool ui/tests/compatibility/tst_published_agent.qml \ ui/tests/qml/tst_unified_batch.qml ui/tests/qml/tst_clipboard_arguments.qml \ ui/tests/qml/tst_reader_subject_menu.qml \ + ui/tests/qml/tst_local_mail_status.qml \ ui/backend/Backend.qml ui/backend/Runtime.qml ui/diagnostics/Diagnostics.qml \ - ui/components/BackendSetup.qml ui/components/MagpieLogo.qml ui/components/DisplaySettings.qml ui/settings/MailStyle.qml \ - ui/account/MailAccount.qml ui/account/BackendSync.qml ui/account/SendQueue.qml ui/account/Intents.qml ui/account/BatchAction.qml ui/account/UnifiedBatchAction.qml ui/account/UnifiedBatchSelection.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \ + ui/components/BackendSetup.qml ui/components/LocalMailStatus.qml ui/components/MagpieLogo.qml ui/components/DisplaySettings.qml ui/settings/MailStyle.qml \ + ui/account/MailAccount.qml ui/account/LocalMailbox.qml ui/account/AccountResources.qml ui/account/BackendSync.qml ui/account/SendQueue.qml ui/account/Intents.qml ui/account/BatchAction.qml ui/account/UnifiedBatchAction.qml ui/account/UnifiedBatchSelection.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \ ui/cache/CacheStore.qml ui/cache/BodyCache.qml \ ui/providers/AuthManager.qml ui/providers/GmailApiClient.qml \ ui/providers/OutlookAuth.qml \ @@ -86,7 +87,7 @@ APP_TARGET_DIR ?= $(CURDIR)/target/standalone APP_BACKEND := $(APP_TARGET_DIR)/debug/omamail$(APP_EXEEXT) APP_EXECUTABLE := $(CURDIR)/$(APP_BUILD_DIR)/omamail-app$(APP_EXEEXT) -.PHONY: test test-js test-shell test-shell-portable test-shell-libcurl \ +.PHONY: test test-js test-shell test-shell-portable test-shell-independent test-shell-libcurl \ test-qml test-app-qml test-local test-backend-process qml-check validate bench install \ app-build app-run help @@ -180,8 +181,14 @@ test-shell: test-shell-portable test-shell-libcurl # Everything here drives one of our own scripts against a fake server and # asserts what the script did with the answer, so any libcurl can run it. -test-shell-portable: +test-shell-portable: test-shell-independent + python3 tests/test_calendar_notifications.py + python3 tests/test_curl_config.py + python3 tests/test_public_http.py + +test-shell-independent: python3 tests/test_app_make.py + python3 tests/test_performance_verification.py python3 tests/test_diagnostics.py python3 tests/test_network_migration.py python3 tests/test_plugin_workflow.py @@ -191,9 +198,7 @@ test-shell-portable: sh tests/test_dev.sh python3 tests/test_attachment_common.py python3 tests/test_notification.py - python3 tests/test_calendar_notifications.py - python3 tests/test_curl_config.py - python3 tests/test_public_http.py + python3 tests/test_public_http.py Policy python3 tests/test_contacts.py python3 tests/test_qml_names.py python3 tests/test_qml_text_format.py @@ -295,6 +300,12 @@ validate: test test-app-qml qml-check omarchy plugin validate . git diff --check +.PHONY: verify-performance +VERIFY_PROFILE ?= ci +VERIFY_OUTPUT ?= /tmp/magpie-verification-$(shell date +%Y%m%d-%H%M%S) +verify-performance: + python3 scripts/verify-performance.py --profile "$(VERIFY_PROFILE)" --output "$(VERIFY_OUTPUT)" + # Development only: the Marketplace installs the plugin for ordinary users. .PHONY: install-backend-local install-plugin install-backend-local: backend diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 68a3e5fb6..be12ef64d 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -10,6 +10,15 @@ set(CMAKE_AUTOMOC ON) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(backend_contract_path "${CMAKE_CURRENT_SOURCE_DIR}/../backend-api.json") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${backend_contract_path}") +file(READ "${backend_contract_path}" backend_contract) +file(SHA256 "${backend_contract_path}" OMAMAIL_BACKEND_CONTRACT_HASH) +string(JSON OMAMAIL_BACKEND_API_VERSION GET "${backend_contract}" apiVersion) +string(JSON OMAMAIL_RELEASED_API_VERSION GET "${backend_contract}" releasedApiVersion) +string(JSON OMAMAIL_UNRELEASED_METHODS GET "${backend_contract}" unreleased methods) +configure_file(src/backend_contract.h.in backend_contract.h @ONLY) + find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Qml Quick QuickControls2 Network Test) @@ -64,7 +73,7 @@ if(WIN32) target_compile_definitions(omamail_native PRIVATE _WIN32_WINNT=0x0A00 WINVER=0x0A00) endif() -target_include_directories(omamail_native PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_include_directories(omamail_native PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_BINARY_DIR}") target_compile_definitions(omamail_native PUBLIC OMAMAIL_APP_VERSION="${PROJECT_VERSION}" OMAMAIL_SOURCE_ROOT="${CMAKE_CURRENT_SOURCE_DIR}/.." diff --git a/app/qml/StandaloneShell.qml b/app/qml/StandaloneShell.qml index f3c32f35a..87225c283 100644 --- a/app/qml/StandaloneShell.qml +++ b/app/qml/StandaloneShell.qml @@ -14,6 +14,7 @@ QtObject { readonly property bool standalone: true readonly property string backendPath: String(host && host.backendPath || "") + readonly property var backendContract: host && host.backendContract || ({}) readonly property string calendarPalettePath: "" readonly property string notificationError: String(host && host.notificationError || "") readonly property var capabilities: ({ diff --git a/app/src/application_host.cpp b/app/src/application_host.cpp index fc7e215af..ae5fd71ce 100644 --- a/app/src/application_host.cpp +++ b/app/src/application_host.cpp @@ -1,4 +1,5 @@ #include "application_host.h" +#include "backend_contract.h" #include "resource_check.h" @@ -10,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -83,6 +85,15 @@ void ApplicationHost::loadManifest(const QString &path) if (document.isObject()) m_manifest = document.object().toVariantMap(); } +QVariantMap ApplicationHost::backendContract() const +{ + return {{QStringLiteral("apiVersion"), OMAMAIL_BACKEND_API_VERSION}, + {QStringLiteral("releasedApiVersion"), OMAMAIL_RELEASED_API_VERSION}, + {QStringLiteral("contractHash"), QStringLiteral(OMAMAIL_BACKEND_CONTRACT_HASH)}, + {QStringLiteral("unreleasedMethods"), QJsonDocument::fromJson( + OMAMAIL_UNRELEASED_METHODS).array().toVariantList()}}; +} + bool ApplicationHost::openExternal(const QString &urlOrPath) { if (urlOrPath.contains(QChar::Null) || urlOrPath.contains('\n') diff --git a/app/src/application_host.h b/app/src/application_host.h index 2d011547a..4803790f7 100644 --- a/app/src/application_host.h +++ b/app/src/application_host.h @@ -19,6 +19,7 @@ class ApplicationHost : public QObject { Q_PROPERTY(QVariantMap capabilities READ capabilities CONSTANT) Q_PROPERTY(QVariantMap settings READ settings NOTIFY settingsChanged) Q_PROPERTY(QString backendPath READ backendPath CONSTANT) + Q_PROPERTY(QVariantMap backendContract READ backendContract CONSTANT) Q_PROPERTY(QString notificationError READ notificationError NOTIFY notificationErrorChanged) Q_PROPERTY(QVariantMap pendingNotificationActivation @@ -38,6 +39,7 @@ class ApplicationHost : public QObject { QVariantMap capabilities() const { return m_capabilities; } QVariantMap settings() const { return m_settings; } QString backendPath() const { return m_backendPath; } + QVariantMap backendContract() const; QString notificationError() const; QVariantMap pendingNotificationActivation() const { diff --git a/app/src/backend_contract.h.in b/app/src/backend_contract.h.in new file mode 100644 index 000000000..2858f7886 --- /dev/null +++ b/app/src/backend_contract.h.in @@ -0,0 +1,6 @@ +#pragma once + +#define OMAMAIL_BACKEND_API_VERSION @OMAMAIL_BACKEND_API_VERSION@ +#define OMAMAIL_RELEASED_API_VERSION @OMAMAIL_RELEASED_API_VERSION@ +#define OMAMAIL_BACKEND_CONTRACT_HASH "@OMAMAIL_BACKEND_CONTRACT_HASH@" +#define OMAMAIL_UNRELEASED_METHODS R"methods(@OMAMAIL_UNRELEASED_METHODS@)methods" diff --git a/app/src/resource_check.cpp b/app/src/resource_check.cpp index b5f3e7b46..d846fd280 100644 --- a/app/src/resource_check.cpp +++ b/app/src/resource_check.cpp @@ -1,4 +1,5 @@ #include "resource_check.h" +#include "backend_contract.h" #include #include @@ -365,7 +366,10 @@ bool runSmokeTest(const ResourcePaths &paths, const QString &readyFile, QString || !protocol.isDouble() || protocol.toInt() != 1 || !apiVersion.isDouble() || apiVersion.toDouble() != static_cast(apiVersion.toInt()) - || apiVersion.toInt() != 7) { + || apiVersion.toInt() != OMAMAIL_BACKEND_API_VERSION + || (OMAMAIL_BACKEND_API_VERSION > OMAMAIL_RELEASED_API_VERSION + && info.value(QStringLiteral("contractHash")).toString() + != QStringLiteral(OMAMAIL_BACKEND_CONTRACT_HASH))) { if (error) *error = QStringLiteral("Bundled backend system.info does not match this app"); stopProcess(backend); return false; diff --git a/app/tests/native/tst_resources.cpp b/app/tests/native/tst_resources.cpp index ba9c30a8e..48c72239d 100644 --- a/app/tests/native/tst_resources.cpp +++ b/app/tests/native/tst_resources.cpp @@ -1,5 +1,6 @@ #include "app_icon.h" #include "resource_check.h" +#include "backend_contract.h" #include #include @@ -59,6 +60,7 @@ private slots: void rejectsInvalidManifest(); void smokeTestLoadsQmlHandshakesAndWritesReadyFile(); void smokeRejectsMismatchedBackendApi(); + void smokeRejectsMismatchedBackendContract(); void smokeRejectsOversizedStdoutFrame(); void smokeDrainsLargeStderr(); void smokeBoundsBothChannelsAfterQuitReply(); @@ -164,7 +166,7 @@ void ResourcesTest::smokeTestLoadsQmlHandshakesAndWritesReadyFile() QVERIFY(ready.open(QIODevice::ReadOnly)); const QJsonObject value = QJsonDocument::fromJson(ready.readAll()).object(); QCOMPARE(value.value(QStringLiteral("version")).toString(), QStringLiteral(OMAMAIL_APP_VERSION)); - QCOMPARE(value.value(QStringLiteral("apiVersion")).toInt(), 7); + QCOMPARE(value.value(QStringLiteral("apiVersion")).toInt(), OMAMAIL_BACKEND_API_VERSION); } void ResourcesTest::smokeRejectsMismatchedBackendApi() @@ -180,6 +182,23 @@ void ResourcesTest::smokeRejectsMismatchedBackendApi() QVERIFY(!QFile::exists(directory.filePath(QStringLiteral("ready.json")))); } +void ResourcesTest::smokeRejectsMismatchedBackendContract() +{ + if (OMAMAIL_BACKEND_API_VERSION == OMAMAIL_RELEASED_API_VERSION) + QSKIP("Released API compatibility uses the stable revision"); + QTemporaryDir directory; + ResourcePaths paths = completeLayout(directory); + paths.backend = QCoreApplication::applicationFilePath(); + const QString readyPath = directory.filePath(QStringLiteral("ready.json")); + qputenv("OMAMAIL_SMOKE_FIXTURE", "stale-contract"); + QString error; + const bool ready = runSmokeTest(paths, readyPath, &error); + qunsetenv("OMAMAIL_SMOKE_FIXTURE"); + QVERIFY(!ready); + QVERIFY(!QFileInfo::exists(readyPath)); + QVERIFY(error.contains(QStringLiteral("does not match"))); +} + void ResourcesTest::smokeRejectsOversizedStdoutFrame() { QTemporaryDir directory; @@ -344,7 +363,9 @@ int main(int argc, char *argv[]) result = {{QStringLiteral("name"), QStringLiteral("omamail")}, {QStringLiteral("version"), QStringLiteral(OMAMAIL_APP_VERSION)}, {QStringLiteral("protocol"), 1}, - {QStringLiteral("apiVersion"), fixture == QByteArrayLiteral("stale-api") ? 6 : 7}}; + {QStringLiteral("apiVersion"), fixture == QByteArrayLiteral("stale-api") ? 6 : OMAMAIL_BACKEND_API_VERSION}, + {QStringLiteral("contractHash"), fixture == QByteArrayLiteral("stale-contract") + ? QString(64, QLatin1Char('0')) : QStringLiteral(OMAMAIL_BACKEND_CONTRACT_HASH)}}; } else { result = {{QStringLiteral("quitReady"), true}}; } diff --git a/app/tests/qml/HostFixture.qml b/app/tests/qml/HostFixture.qml index 2ef83e344..7c793837f 100644 --- a/app/tests/qml/HostFixture.qml +++ b/app/tests/qml/HostFixture.qml @@ -8,6 +8,7 @@ QtObject { property var capabilities: ({agent:false,tray:false,mailto:false,notifications:true}) property var settings: ({refreshIntervalSec:333,maxMessages:17,notifyNewMail:"Off"}) property string backendPath: "/fixture/bin/omamail" + property var backendContract: ({apiVersion:8, releasedApiVersion:7, contractHash:"", unreleasedMethods:[]}) property string notificationError: "" property bool hidden: false property bool quitCalled: false diff --git a/app/tests/qml/imports/Omamail/Native/NativeHost.qml b/app/tests/qml/imports/Omamail/Native/NativeHost.qml index c4fc24d71..c98e126e2 100644 --- a/app/tests/qml/imports/Omamail/Native/NativeHost.qml +++ b/app/tests/qml/imports/Omamail/Native/NativeHost.qml @@ -5,4 +5,5 @@ QtObject { property var manifest: ({}) property var settings: ({}) property string backendPath: "" + property var backendContract: ({apiVersion:8, releasedApiVersion:7, contractHash:"", unreleasedMethods:[]}) } diff --git a/app/tests/qml/tst_standalone_composition.qml b/app/tests/qml/tst_standalone_composition.qml index 5966879c6..0c4ed4e0e 100644 --- a/app/tests/qml/tst_standalone_composition.qml +++ b/app/tests/qml/tst_standalone_composition.qml @@ -300,7 +300,7 @@ TestCase { compare(composition.service.settings.maxMessages, 17) compare(composition.service.notifyNewMail, false) compare(composition.service.backendRuntime.bundled, true) - compare(composition.service.backendRuntime.requiredApiVersion, 6, + compare(composition.service.backendRuntime.requiredApiVersion, 7, "the bundled handshake must require this checkout's API") compare(composition.service.backendRuntime.canInstall, false) compare(composition.service.backendRuntime.executable, host.backendPath) diff --git a/backend-api.json b/backend-api.json index 977b9954a..a85a8e7c2 100644 --- a/backend-api.json +++ b/backend-api.json @@ -190,7 +190,28 @@ "jmap.request", "jmap.stream.open", "jmap.stream.poll", - "jmap.stream.close" + "jmap.stream.close", + "reader.prefetch", + "local.list", + "local.status", + "local.overview", + "local.edits", + "local.edit", + "local.pause", + "local.cancelEdit", + "local.dismissConflict", + "local.watch", + "local.unwatch", + "local.refresh", + "attachment.import", + "attachment.preview", + "attachment.download", + "attachment.retain", + "outbox.compose", + "draft.compose", + "calendar.read", + "calendar.parse", + "local.labelCounts" ], "contractCases": [ { @@ -1432,6 +1453,145 @@ "equals": { "hasAttachments": false } + }, + { + "name": "Local list rejects unsupported search before opening storage", + "method": "local.list", + "params": { + "accountId": "missing@example.org", + "query": "larger:1M" + }, + "errorCode": -32000, + "equals": { + "message": "local_search_unsupported" + } + }, + { + "name": "Local edits reject duplicated frozen message IDs before storage", + "method": "local.edit", + "params": { + "accountId": "missing@example.org", + "ticket": "same", + "ids": [ + "one", + "one" + ], + "addLabelIds": [ + "STARRED" + ], + "removeLabelIds": [] + }, + "errorCode": -32602 + }, + { + "name": "Local edits refuse immutable Gmail labels", + "method": "local.edit", + "params": { + "accountId": "missing@example.org", + "ticket": "bad", + "ids": [ + "one" + ], + "addLabelIds": [ + "SENT" + ], + "removeLabelIds": [] + }, + "errorCode": -32602 + }, + { + "name": "Local pause rejects untyped controls before storage", + "method": "local.pause", + "params": { + "accountId": "missing@example.org", + "paused": "yes" + }, + "errorCode": -32602 + }, + { + "name": "Native attachments refuse arbitrary resource URLs", + "method": "attachment.preview", + "params": { + "accountId": "missing@example.org", + "url": "https://example.invalid/file" + }, + "errorCode": -32602 + }, + { + "name": "Native draft composition rejects unknown controls", + "method": "draft.compose", + "params": { + "accountId": "missing@example.org", + "fields": {}, + "send": true + }, + "errorCode": -32602 + }, + { + "name": "Native outbox composition requires structured fields", + "method": "outbox.compose", + "params": { + "fields": "raw" + }, + "errorCode": -32602 + }, + { + "name": "Calendar reads refuse mutations", + "method": "calendar.read", + "params": { + "operation": "delete" + }, + "errorCode": -32602 + }, + { + "name": "Native Google calendar parsing retains display data", + "method": "calendar.parse", + "params": { + "kind": "google", + "sourceId": "synthetic", + "body": "{\"items\": [{\"id\": \"one\", \"summary\": \"Meeting\", \"start\": {\"dateTime\": \"2026-10-20T12:00:00Z\"}, \"end\": {\"dateTime\": \"2026-10-20T13:00:00Z\"}}]}" + }, + "equals": { + "events.length": 1, + "events.0.googleId": "one", + "events.0.summary": "Meeting", + "events.0.sourceId": "synthetic", + "events.0.start.ms": 1792497600000 + } + }, + { + "name": "Native calendar parser refuses document type expansion", + "method": "calendar.parse", + "params": { + "kind": "caldav", + "sourceId": "synthetic", + "body": "]>&s;" + }, + "errorCode": -32000, + "equals": { + "message": "calendar_invalid_response" + } + }, + { + "name": "Shared calendar ranges have an independent namespace", + "method": "cache.calendarRead", + "params": { + "name": "calendar-shared" + }, + "equals": { + "version": 3 + }, + "types": { + "ranges": "object" + } + }, + { + "name": "Unreleased handshake identifies its exact API contract", + "method": "system.info", + "params": {}, + "types": { + "contractHash": "string" + } } ], "unreleased": { @@ -1442,7 +1602,28 @@ "inbox.snooze", "inbox.wake", "inbox.tick", - "attachment.thumbnail" + "attachment.thumbnail", + "reader.prefetch", + "local.list", + "local.status", + "local.overview", + "local.edits", + "local.edit", + "local.pause", + "local.cancelEdit", + "local.dismissConflict", + "local.watch", + "local.unwatch", + "local.refresh", + "attachment.import", + "attachment.preview", + "attachment.download", + "attachment.retain", + "outbox.compose", + "draft.compose", + "calendar.read", + "calendar.parse", + "local.labelCounts" ], "cases": [ "Inbox snapshot refuses unknown accounts", @@ -1455,7 +1636,19 @@ "Attachment thumbnail rejects resource URLs before rendering", "Attachment thumbnail prepares only raster PNG data", "Message summaries identify explicit file attachments without body bytes", - "Message summaries do not count inline sender logos as attachments" + "Message summaries do not count inline sender logos as attachments", + "Local list rejects unsupported search before opening storage", + "Local edits reject duplicated frozen message IDs before storage", + "Local edits refuse immutable Gmail labels", + "Local pause rejects untyped controls before storage", + "Native attachments refuse arbitrary resource URLs", + "Native draft composition rejects unknown controls", + "Native outbox composition requires structured fields", + "Calendar reads refuse mutations", + "Native Google calendar parsing retains display data", + "Native calendar parser refuses document type expansion", + "Shared calendar ranges have an independent namespace", + "Unreleased handshake identifies its exact API contract" ] } } diff --git a/benchmarks/mail/README.md b/benchmarks/mail/README.md index 9ed0ae3f3..a5f45460b 100644 --- a/benchmarks/mail/README.md +++ b/benchmarks/mail/README.md @@ -1,5 +1,21 @@ # Synthetic mail performance benchmarks +## Original implementation versus current code + +`python3 benchmarks/mail/compare_ui.py --output /tmp/magpie-before-after.json` extracts the committed UI at `aeac13160f70a86f6419eaf2ceb1695fad078c7c` without changing the checkout, then exercises both versions with identical synthetic 100-row and 1,000-row lists. It times empty-to-populated completed frames, selection/reveal between opposite ends, and an unread-state update. Three fresh processes per version alternate order; each measures 31 samples after three warmups. Results retain each run's raw samples and source/harness hashes; the table uses the median of the three p95 values. Live row component counts are recorded separately. `--baseline COMMIT`, `--counts 100 1000`, `--repetitions 3` and `--runner /path/to/Qt6/qmltestrunner` make the inputs explicit. + +This is a comparison of actual old and new QML components, not a comparison of two compiler flags or two stages within the new implementation. The list starts with in-memory summaries and an already-running QML engine. It excludes network, disk, RPC, application startup and compositor presentation. Small completed-frame differences near Qt's frame interval are not evidence of a general application speedup. Local full-text search has no equivalent offline full-text baseline in the original implementation; do not invent one by comparing it with an assumed Gmail response time. + +`make verify-performance VERIFY_PROFILE=benchmarks` collects this comparison and the database cases below into a fresh result directory. The GitHub Actions `Performance verification` workflow runs the same profile and saves its logs and JSON as artifacts. + +## Local replica and completed Qt frames + +`cargo test --release --lib local_mail::tests::benchmark_local_queries -- --ignored --nocapture` creates a synthetic 100,000-message database and measures five searches returning 50 summaries. Set `MAGPIE_BENCH_MESSAGES=1000000` for the separate scale case or `MAGPIE_BENCH_BACKGROUND=1` to run concurrent durable body writes at a 25 ms minimum interval. Results include median/p95 and the actual background write count. Fixture import is a bulk transaction, not a Gmail download simulation. These measurements exclude UI, RPC and network latency. + +`python3 benchmarks/mail/ui_latency.py --output /tmp/magpie-paint.json` exercises the production list and reader components with Qt's offscreen software renderer at 1x scale. It measures completed render frames after switching between the ends of 10,000 loaded summaries and between two natively prepared HTML documents. It excludes RPC, disk, network, compositor presentation and application startup. Run without builds or other benchmarks to obtain a useful baseline. + +`python3 benchmarks/mail/compiler_profiles.py --size /path/to/size/mail_bench --speed /path/to/speed/mail_bench --output /tmp/magpie-profiles.json` compares two `mail_bench` examples with identical synthetic inputs and semantic outputs. Build one with the normal release profile and the other with `cargo build --release --config profile.release.opt-level=3 --example mail_bench --target-dir /tmp/magpie-speed-build`. It measures CPU processing only; retain current release settings unless an end-to-end comparison justifies changing them. + ## Cached reader including QML transport [reader-pipeline-results.md](reader-pipeline-results.md) measures the current diff --git a/benchmarks/mail/compare_ui.py b/benchmarks/mail/compare_ui.py new file mode 100644 index 000000000..cdebc15ae --- /dev/null +++ b/benchmarks/mail/compare_ui.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Compare committed and working-tree QML with identical synthetic fixtures.""" +import argparse +import hashlib +import io +import json +import os +from pathlib import Path +import platform +import re +import shutil +import statistics +import subprocess +import tarfile +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[2] +BASELINE = "aeac13160f70a86f6419eaf2ceb1695fad078c7c" + +QML = r''' +import QtQuick +import QtTest +import __COMPONENTS__ as Mail +import __MODEL__ as Model +import __RECIPIENTS__ as Recipients +Item { + width: 720; height: 600 + QtObject { + id: service + property var messages: [] + property bool hasMore: false + property bool listLoading: false + property bool listLoaded: true + property string searchQuery: "" + property string selectedId: "" + property bool canArchive: true + property string contentDirection: "auto" + property var agentJobs: ({}) + property var agentAttentionByMessage: ({}) + property var inboxTools: null + property var backend: null + function loadMore() { throw new Error("benchmark must not fetch") } + } + __LIST__ + TestCase { + name: "BeforeAfter" + when: windowShown + function sample(operation, reset) { + var times=[] + for (var n=-3;n<31;n++) { + if (reset) reset() + var began=Date.now() + operation(n) + verify(waitForRendering(viewport,5000),"a completed frame is required") + if (n>=0) times.push(Date.now()-began) + } + var sorted=times.slice().sort(function(a,b){return a-b}) + return {medianMs:sorted[15],p95Ms:sorted[29],samplesMs:times} + } + function delegates(item) { + var count=typeof item.summary!=="undefined" && typeof item.hasCursor!=="undefined" ? 1 : 0 + for (var i=0;i=viewport.contentY && bounds.y<=viewport.contentY+viewport.height, + "the selected row must be visible") + var updated=sample(function(n){ + var replacement=rows.slice() + replacement[__COUNT__-1]=Object.assign({},rows[__COUNT__-1],{unread:n%2===0}) + service.messages=replacement + }) + console.log("COMPARISON "+JSON.stringify({ + populate:populated,navigate:navigation,update:updated,liveRows:count,count:rows.length + })) + } + } +} +''' +FIELDS = ''' + id: list + service: service + textColor: "#eeeeee"; accentColor: "#88aadd" + dimColor: "#aaaaaa"; urgentColor: "#ff5555" + panelFontFamily: "monospace" +''' + + +def source(root, count): + virtual = (root / "ui/components/MessageList.qml").read_text().split("ListView {", 1) + if len(virtual) == 2: + listing = "Mail.MessageList { anchors.fill: parent;" + FIELDS + " }\n property var viewport: list" + reveal = "list.reveal(id)" + else: + listing = ("Flickable { id: viewport; anchors.fill: parent; clip: true;" + "contentWidth: width; contentHeight: list.implicitHeight+16;" + "Mail.MessageList { width: viewport.width; scroller: viewport;" + FIELDS + "}}") + reveal = ("var bounds=list.boundsFor(id);verify(bounds!==null);" + "viewport.contentY=Model.contentYToReveal(viewport.contentY,viewport.height," + "list.y+bounds.y,bounds.height,viewport.contentHeight,8)") + return (QML.replace("__COMPONENTS__", json.dumps((root / "ui/components").as_uri())) + .replace("__MODEL__", json.dumps((root / "ui/account/Model.js").as_uri())) + .replace("__RECIPIENTS__", json.dumps((root / "ui/compose/Recipients.js").as_uri())) + .replace("__LIST__", listing).replace("__REVEAL__", reveal) + .replace("__COUNT__", str(count))) + + +def tree_hash(root): + digest = hashlib.sha256() + for path in sorted((root / "ui").rglob("*")): + if path.is_file() and path.suffix in (".qml", ".js"): + digest.update(str(path.relative_to(root)).encode() + b"\0" + path.read_bytes()) + return digest.hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", default=BASELINE) + parser.add_argument("--counts", nargs="+", type=int, default=[100, 1000]) + parser.add_argument("--repetitions", type=int, default=3) + parser.add_argument("--runner", default=shutil.which("qmltestrunner6") or ( + "/usr/lib/qt6/bin/qmltestrunner" if Path("/usr/lib/qt6/bin/qmltestrunner").exists() + else shutil.which("qmltestrunner"))) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if not 1 <= args.repetitions <= 10 or any(n < 2 or n > 10000 for n in args.counts): + parser.error("use 1–10 repetitions and 2–10000 rows") + revision = subprocess.check_output( + ["git", "rev-parse", "--verify", args.baseline + "^{commit}"], cwd=ROOT, text=True).strip() + archive = subprocess.check_output(["git", "archive", revision, "ui"], cwd=ROOT) + args.output.parent.mkdir(parents=True, exist_ok=True) + logs = args.output.parent / (args.output.stem + "-logs") + logs.mkdir(exist_ok=True) + results = [] + qt_versions = set() + started = os.getloadavg() + with tempfile.TemporaryDirectory(prefix="magpie-compare-") as temp: + baseline = Path(temp) / "before" + baseline.mkdir() + with tarfile.open(fileobj=io.BytesIO(archive)) as tree: + tree.extractall(baseline, filter="data") + hashes = {"before": tree_hash(baseline), "after": tree_hash(ROOT)} + for count in args.counts: + for repetition in range(args.repetitions): + order = [("before", baseline), ("after", ROOT)] + if repetition % 2: + order.reverse() + for label, root in order: + name = f"{count}-{repetition}-{label}" + qml = Path(temp) / ("tst_" + name + ".qml") + qml.write_text(source(root, count)) + result = subprocess.run( + [args.runner, "-input", str(qml), "-import", str(root / "ui/tests/qml/imports")], + text=True, capture_output=True, timeout=300, + env=dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software", + QT_QPA_PLATFORMTHEME="", QT_SCALE_FACTOR="1")) + (logs / (name + ".log")).write_text(result.stdout + result.stderr) + match = re.search(r"COMPARISON (\{[^\n]+\})", result.stdout) + if result.returncode or not match: + raise RuntimeError("Qt comparison failed; see " + str(logs / (name + ".log"))) + measurement = json.loads(match[1]) + qt_versions.update(line for line in result.stdout.splitlines() if line.startswith("Config:")) + results.append(dict(label=label, repetition=repetition, **measurement)) + print(name, json.dumps({k: v["p95Ms"] if isinstance(v, dict) else v + for k, v in measurement.items()}), flush=True) + comparisons = [] + for count in args.counts: + for metric in ("populate", "navigate", "update"): + medians = {label: statistics.median( + row[metric]["p95Ms"] for row in results if row["label"] == label and row["count"] == count) + for label in ("before", "after")} + comparisons.append(dict(rows=count, metric=metric, **medians, + speedup=medians["before"] / medians["after"] if medians["after"] else None, + reductionPercent=(1 - medians["after"] / medians["before"]) * 100 + if medians["before"] else None)) + report = dict( + measuredAt=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), baselineCommit=revision, + sourceHashes=hashes, harnessSha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + platform=platform.platform(), cpu=platform.processor(), logicalCpus=os.cpu_count(), + loadBefore=started, loadAfter=os.getloadavg(), qt=sorted(qt_versions), + conditions="720×600, monospace, fixed synthetic colours, Qt offscreen software renderer at 1x. " + "Three warmups and 31 completed frames per operation per run. Alternating version order. " + "Tables use median of each run's p95; raw samples retained. Population starts with an empty, " + "already-running component and in-memory summaries; navigation selects/reveals opposite ends; " + "update replaces the array and toggles unread on the visible last row. Real production components " + "and each revision's shell test imports. Excludes provider, disk, RPC, startup and compositor. " + "No claim about whole-app speed or fresh OS caches. Shared machine, no CPU isolation.", + comparisons=comparisons, runs=results) + args.output.write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/mail/compiler_profiles.py b/benchmarks/mail/compiler_profiles.py new file mode 100644 index 000000000..8db5b7801 --- /dev/null +++ b/benchmarks/mail/compiler_profiles.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Compare two release mail_bench executables without changing release settings.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import time + +from corpus import corpus +from run import html_semantics, mime_semantics, stats + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--size", type=Path, required=True) + parser.add_argument("--speed", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + payload = json.dumps(dict(cases=corpus(), samples=31, batch=3, phases=["mime", "readprep"])) + outputs = {} + binaries = {} + load = os.getloadavg() + for name, path in [("size", args.size), ("speed", args.speed)]: + result = subprocess.run([str(path.resolve())], input=payload, text=True, + capture_output=True, check=True, timeout=180) + outputs[name] = json.loads(result.stdout)["cases"] + binaries[name] = dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + bytes=path.stat().st_size) + rows = [] + for size, speed in zip(outputs["size"], outputs["speed"], strict=True): + assert (size["name"], size["phase"]) == (speed["name"], speed["phase"]) + normalize = mime_semantics if size["phase"] == "mime" else html_semantics + assert normalize(size["result"]) == normalize(speed["result"]) + rows.append(dict(name=size["name"], phase=size["phase"], + size=stats(size), speed=stats(speed))) + report = dict(measuredAt=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + conditions="CPU-only diagnostic; 31 samples after five warmups, three operations per sample. " + "Identical synthetic input and semantic output. No network, RPC or painting. " + "Shared desktop, no CPU isolation. This alone does not justify changing release flags.", + loadBefore=load, loadAfter=os.getloadavg(), binaries=binaries, results=rows) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps([{k: v for k, v in row.items() if k not in ("size", "speed")} | + {"sizeP95Us": row["size"]["p95Us"], "speedP95Us": row["speed"]["p95Us"]} + for row in rows], indent=2)) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/mail/reader_concurrency.py b/benchmarks/mail/reader_concurrency.py index 33d60175d..ec70c8147 100644 --- a/benchmarks/mail/reader_concurrency.py +++ b/benchmarks/mail/reader_concurrency.py @@ -108,7 +108,7 @@ id:backend executable:BINARY expectedVersion:VERSION - expectedApiVersion: 1 + expectedApiVersion: API_REVISION onReadyChanged:if(ready&&!root.began){root.began=true;Qt.callLater(root.nextCase)} onFailureChanged:if(failure!=="")root.fail(failure) } @@ -170,7 +170,7 @@ def main(): path=temp/key.lower();path.mkdir(mode=0o700);env[key]=str(path) config=Path(env['XDG_CONFIG_HOME'])/'omamail';config.mkdir(mode=0o700) registry=config/'accounts.json';registry.write_text(json.dumps({'version':1,'accounts':[{'provider':'gmail','email':'concurrency-benchmark@example.test'}],'activeId':'concurrency-benchmark@example.test'}));registry.chmod(0o600) - qml=QML.replace('PAYLOAD',json.dumps(cases)).replace('ROUNDS',str(args.rounds)).replace('OPERATIONS',str(args.operations)).replace('BINARY',json.dumps(str(binary))).replace('VERSION',json.dumps(version)) + qml=QML.replace('API_REVISION',str(json.loads((ROOT/'backend-api.json').read_text())['apiVersion'])).replace('PAYLOAD',json.dumps(cases)).replace('ROUNDS',str(args.rounds)).replace('OPERATIONS',str(args.operations)).replace('BINARY',json.dumps(str(binary))).replace('VERSION',json.dumps(version)) (temp/'shell.qml').write_text(qml) start=time.perf_counter();load=os.getloadavg() child=subprocess.Popen([shutil.which('qs'),'--no-color','--path',str(temp/'shell.qml')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True) diff --git a/benchmarks/mail/reader_pipeline.py b/benchmarks/mail/reader_pipeline.py index e7d0da3af..2fea0161b 100644 --- a/benchmarks/mail/reader_pipeline.py +++ b/benchmarks/mail/reader_pipeline.py @@ -109,7 +109,7 @@ id:backend executable:BINARY expectedVersion:VERSION - expectedApiVersion: 1 + expectedApiVersion: API_REVISION onReadyChanged:if(ready&&!root.began){root.began=true;Qt.callLater(root.nextCase)} onFailureChanged:if(failure!=="")root.fail(failure) } @@ -196,7 +196,7 @@ def main(): config=Path(env['XDG_CONFIG_HOME'])/'omamail';config.mkdir(mode=0o700) registry=config/'accounts.json';registry.write_text(json.dumps({'version':1,'accounts':[{'provider':'gmail','email':'reader-benchmark@example.test'}],'activeId':'reader-benchmark@example.test'}));registry.chmod(0o600) for engine in ENGINES: - text=QML.replace('PAYLOAD',json.dumps(cases)).replace('SAMPLES',str(args.samples)).replace('ENGINE',json.dumps(engine)).replace('BINARY',json.dumps(str(frozen))).replace('VERSION',json.dumps(version)) + text=QML.replace('API_REVISION',str(json.loads((ROOT/'backend-api.json').read_text())['apiVersion'])).replace('PAYLOAD',json.dumps(cases)).replace('SAMPLES',str(args.samples)).replace('ENGINE',json.dumps(engine)).replace('BINARY',json.dumps(str(frozen))).replace('VERSION',json.dumps(version)) (temp/'shell.qml').write_text(text) child=subprocess.Popen([shutil.which('qs'),'--no-color','--path',str(temp/'shell.qml')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True) try:output,_=child.communicate(timeout=920) diff --git a/benchmarks/mail/roundtrip.py b/benchmarks/mail/roundtrip.py index 4ab21a885..a0ef84f07 100644 --- a/benchmarks/mail/roundtrip.py +++ b/benchmarks/mail/roundtrip.py @@ -99,7 +99,7 @@ id: backend executable: BINARY expectedVersion: VERSION - expectedApiVersion: 1 + expectedApiVersion: API_REVISION onReadyChanged:if(ready&&!root.began){root.began=true;Qt.callLater(root.beginCase)} onFailureChanged:if(failure!=="")root.fail(failure) } @@ -146,7 +146,7 @@ def main(): path=temp/key.lower();path.mkdir(mode=0o700);env[key]=str(path) for module in ['backend','message']:shutil.copytree(ROOT/'ui'/module,temp/module) shutil.copytree(HERE/'baseline/ui',temp/'baseline') - qml=QML.replace('PAYLOAD',json.dumps(cases)).replace('SAMPLES',str(args.samples)).replace('BINARY',json.dumps(str(binary))).replace('VERSION',json.dumps(version)) + qml=QML.replace('API_REVISION',str(json.loads((ROOT/'backend-api.json').read_text())['apiVersion'])).replace('PAYLOAD',json.dumps(cases)).replace('SAMPLES',str(args.samples)).replace('BINARY',json.dumps(str(binary))).replace('VERSION',json.dumps(version)) (temp/'shell.qml').write_text(qml) load_before=os.getloadavg();start=time.perf_counter() process=subprocess.Popen([shutil.which('qs'),'--no-color','--path',str(temp/'shell.qml')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True) diff --git a/benchmarks/mail/ui_latency.py b/benchmarks/mail/ui_latency.py new file mode 100644 index 000000000..31fdf0614 --- /dev/null +++ b/benchmarks/mail/ui_latency.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Measure production component updates through Qt's completed render frame.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[2] + + +def absolute_imports(source): + return source.replace('"../../', '"' + (ROOT / "ui").as_uri() + "/") + + +def run(runner, source, directory, name): + path = directory / ("tst_" + name + ".qml") + path.write_text(source) + result = subprocess.run( + [runner, "-input", str(path), "-import", str(ROOT / "ui/tests/qml/imports")], + env=dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software", + QT_QPA_PLATFORMTHEME="", QT_SCALE_FACTOR="1"), + text=True, capture_output=True, timeout=120) + (directory / (name + ".log")).write_text(result.stdout + result.stderr) + if result.returncode: + raise RuntimeError(result.stdout + result.stderr) + match = re.search(r"PAINT_RESULT (\{[^\n]+\})", result.stdout) + if not match: + raise RuntimeError("No completed-frame measurement: " + result.stdout) + return json.loads(match[1]) + + +def measurements(item, operation, setup=""): + return """ + TestCase { + name: "PaintLatency" + when: windowShown + function test_completed_frames() { + SETUP + verify(waitForRendering(ITEM,2000)) + var samples=[] + for (var n=-5;n<31;n++) { + var began=Date.now() + OPERATION + verify(waitForRendering(ITEM,2000),"a completed render frame is required") + if (n>=0) samples.push(Date.now()-began) + } + var sorted=samples.slice().sort(function(a,b){return a-b}) + console.log("PAINT_RESULT "+JSON.stringify({medianMs:sorted[15],p95Ms:sorted[29],samplesMs:samples})) + } + } +} +""".replace("SETUP", setup).replace("ITEM", item).replace("OPERATION", operation) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", type=Path, default=ROOT / "target/debug/omamail") + parser.add_argument("--runner", default="/usr/lib/qt6/bin/qmltestrunner") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="magpie-paint-") as temp: + directory = Path(temp) + source = (ROOT / "ui/tests/qml/tst_load_more.qml").read_text().split(" TestCase {")[0] + setup = """fakeService.hasMore=false + var rows=[] + for (var i=0;i<10000;i++) rows.push({id:"synthetic-"+i,from:{display:"Synthetic sender",email:"sender@example.test"}, + subject:"Synthetic message "+i,snippet:"Mailbox performance fixture",labelIds:["INBOX"],unread:false}) + fakeService.messages=rows""" + listing = run(args.runner, absolute_imports(source) + measurements( + "list", 'list.reveal(n%2===0 ? "synthetic-9999" : "synthetic-0")', setup), + directory, "list") + html = "" + "".join( + "

Section %d. Synthetic newsletter text with no remote resources.

" % n + for n in range(700)) + "" + inputs = [{"jsonrpc": "2.0", "id": n, "method": "message.render", + "params": {"html": html.replace("Section", "Part" if n else "Section"), + "options": {"withReader": True, "withPlainText": True}}} + for n in range(2)] + backend = subprocess.run([str(args.binary.resolve()), "serve"], + input="\n".join(json.dumps(v) for v in inputs) + "\n", + capture_output=True, text=True, timeout=30) + resources = [json.loads(line)["result"] for line in backend.stdout.splitlines() + if json.loads(line).get("id") in (0, 1)] + if len(resources) != 2: + raise RuntimeError("Native fixture preparation failed: " + backend.stdout[:1000]) + source = (ROOT / "ui/tests/qml/tst_reader_mode.qml").read_text().split(" TestCase {")[0] + source = source.replace('readonly property var rendered: Html.sanitize(senderHtml, ({ withReader: true }))', + "property var fixtures: " + json.dumps(resources) + + "\n property var rendered: fixtures[0]") + source = source.replace('bodyMode: "reader"', 'bodyMode: "original"') + reader = run(args.runner, absolute_imports(source) + measurements( + "reader", "rendered=fixtures[Math.abs(n)%2]"), directory, "reader") + report = { + "measuredAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "conditions": "Qt software renderer, offscreen 1x. Five warmups, 31 completed frames. Synthetic data. " + "List navigation starts with 10,000 summaries in memory. The large HTML starts with native prepared data. " + "This includes QML layout/rendering; it excludes RPC, disk, network and compositor presentation.", + "list": listing, "largeHtml": reader, "htmlBytes": len(html.encode()), + "backendSha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/BACKEND-RUNTIME.md b/docs/BACKEND-RUNTIME.md index 82e55aecf..d96f65b4f 100644 --- a/docs/BACKEND-RUNTIME.md +++ b/docs/BACKEND-RUNTIME.md @@ -88,6 +88,10 @@ meaning require contract review, updated fixtures and a higher API revision. predates this field; only that exact version is recognized as legacy API 1. Missing revision information from any other version is refused. +Development builds sharing the same unreleased API revision can implement different contracts. `system.info.contractHash` identifies the SHA-256 of the contract compiled into the backend; the plugin runtime independently hashes its own `backend-api.json`. The UI enables the unreleased revision only when those hashes match. A missing or different hash keeps the released features available and refuses unreleased calls before sending a frame or uploading a payload. The bridge also refuses methods absent from the backend's advertised inventory. Released revisions retain their stable version semantics; the exact binary pin and protocol/API checks still apply. Contract identity is a compatibility check, not a replacement for behavioral tests or release verification. + +The standalone host derives its released revision, current revision and contract hash from `backend-api.json` at configuration time. CMake reconfigures when that contract changes. Its smoke check rejects an unmatched development contract before writing a readiness file, and QML receives the same compiled metadata instead of a hard-coded API revision. + ## Native AI conversations (API 6) Settings → AI follows the Omarchy system default or selects Claude, Codex or OpenCode V2, with an optional model override. `agent.providerStatus` resolves the supported provider without starting an agent or creating a job. An unsupported default leaves the AI action visible but disabled; Settings explains the supported choices. Availability checks require API 6 and are repeated while following the system default. Explicit choices bypass the system-default lookup. CLI installation and authentication are still checked when a request starts. Standalone Linux/macOS builds default to OpenCode; Windows does not advertise AI. @@ -130,6 +134,10 @@ Search includes aggregate All Mail destinations and excludes Trash/Junk membersh `attachment.thumbnail` accepts attachment bytes and a supported MIME type and returns prepared PNG data only. The reader fetches visible attachments through their owning account, serializes preview requests, limits each input to 8 MiB and reserves at most 16 MiB per selected message. Raster decoding is bounded to 4096×4096 and 64 MiB; output fits a 384-pixel square and 512 KiB. On Linux, optional `/usr/bin/bwrap`, `/usr/bin/prlimit` and `/usr/bin/pdftoppm` render the first PDF page with no host home or network access, a read-only system mount, CPU/memory/output limits and a six-second deadline. No unsandboxed PDF fallback runs. Other hosts and missing/refused workers retain the file tile; raster previews and Open/Save remain available. QML gates previews on connected API 8 and refuses remote, local-file, SVG and non-PNG preview sources at the image consumer. This is part of the unreleased API step; it does not change the binary release pin. +## Local mail and native performance paths (API 8) + +The unreleased API 8 contract also includes `local.*` replica/watch/intent methods, `reader.prefetch`, account-scoped attachment import/preview/download/retain, `outbox.compose`, `draft.compose`, `calendar.read` and `calendar.parse`. Current QML gates these dependencies on revision 8; the pinned release continues to use its existing paths. `calendar-shared` is a separate cache namespace. See [local mail](LOCAL-MAIL.md) for durable-data and retry semantics. These changes do not update `backend-version` or install a development binary. + ## Released and unreleased: one step ahead of the pin Backends ship in batches, not per merge, so `main` may implement an API the pinned diff --git a/docs/BACKEND.md b/docs/BACKEND.md index 1bf43f1c4..f8d2f24f0 100644 --- a/docs/BACKEND.md +++ b/docs/BACKEND.md @@ -323,6 +323,8 @@ not authorize a production fallback. The immutable benchmark oracle is under ## Cached reader data and disk limits +API 8 adds a durable Gmail replica and account/draft-scoped attachment handles. See [local mail and responsiveness](LOCAL-MAIL.md) for ownership, coverage, offline edits, recovery and measurement boundaries. The disposable cache below remains the fallback for older backends and other providers. + `cache.resourceRead`, `cache.resourcePut` and `cache.resourceClear` manage full provider message resources. Parsed body files and these resources share a 256 MiB quota across all accounts; LRU eviction and entry-count limits bound @@ -352,7 +354,7 @@ Approved image bytes survive revalidation of the same selected message, and image completions are coalesced before rerendering. Changing the selection invalidates pending image callbacks and clears those bytes. -The native source store has a 64 MiB serialized-payload budget, with at most 64 +The native source store has a 64 MiB serialized-payload budget, with at most 32 entries overall and 12 per account; this is not a total heap/RSS limit. Existing interactive message limits are unchanged. A cache hit can paint before live revalidation; a failed refresh retains the displayed @@ -381,6 +383,8 @@ public answers into private storage. ## Automatic mailbox checks +API 8 Gmail accounts use the local replica watch instead of this summary poll/preloader; the paths below remain in use for other providers and compatible older backends. + `mail.watch` registers one background task per account with a query, page size (default 25, UI supplies its configured page size), and interval between 30 and 3600 seconds. `mail.check` triggers an immediate check, diff --git a/docs/KEYS.md b/docs/KEYS.md index d7b9285fc..7d69fb3a1 100644 --- a/docs/KEYS.md +++ b/docs/KEYS.md @@ -50,6 +50,8 @@ readonly property string keyContext: `Ctrl+,` opens Settings from every context, including a focused draft field. Back returns to the previous screen with the draft intact. +When a button has keyboard focus, unmodified Return, keypad Enter and Space activate that button. The shared button controls accept `ShortcutOverride` for those keys so mailbox open/selection shortcuts cannot intercept them. Modified application shortcuts and Escape retain their normal routing. + While an AI request is running, Escape interrupts it and keeps the dock open; otherwise Escape closes the dock. An open command suggestion or history view is left first. The AI input uses `assistant`: Return/Enter sends and Shift+Return/Enter inserts a newline. Ctrl+Return/Enter also sends for compatibility. Typing `/` offers `/clear` (new chat), `/history` (conversation history), and `/diagnose` (diagnostics). Up/Down selects a suggestion; Return/Enter completes a partial command or executes an exact command immediately; choosing `/history` always opens the history at once. Commands stay local. Outside suggestions, Up/Down retain normal text navigation. @@ -255,7 +257,7 @@ message list clamps. ## The cursor -Hover must not write `cursorId`: Qt re-reports hover as content scrolls beneath a stationary pointer. Reveal keyboard selection with `Model.contentYToReveal`; the list is a `Column`, not a view with `positionViewAtIndex`. +Hover must not write `cursorId`: Qt re-reports hover as content scrolls beneath a stationary pointer. Reveal keyboard selection with `MessageList.reveal`, which calls `positionViewAtIndex` with `ListView.Contain`. `cursorId` is where the keyboard is. `selectedId` is what the reader shows. They are two different things, and conflating them was the first bug in this @@ -290,14 +292,7 @@ The last two exist because a cursor pointing at a message that is not listed cannot be found, and `cursorAfterOffset` restarts at the top from there. Every "the cursor jumped back to the first row" report is that. -The list is a `Column` of rows inside a `Flickable`, not a `ListView` — the -panel already owns a scroller, and nesting a second gives every wheel event two -plausible targets. So there is no `positionViewAtIndex`, and keyboard movement -has to scroll the list itself: **`Model.contentYToReveal`** decides where the -scroller goes, leaving it alone while the row is already visible so stepping one -row does not drag the list under someone reading it. It is called from -`moveCursor`, not from `cursorId` changing. Hover never changes the cursor, and -scrolling under the pointer would fight the mouse. +The message list owns the panel's only scroller. Its `ListView` creates visible rows and a small surrounding buffer, preserving delegates during summary-only refreshes. `revealCursorRow` calls `MessageList.reveal` only during keyboard movement; pointer hover never moves the cursor. Selection and checked IDs belong to the window, so delegate reuse cannot change them. ## The mouse diff --git a/docs/LOCAL-MAIL.md b/docs/LOCAL-MAIL.md new file mode 100644 index 000000000..5a4c432c4 --- /dev/null +++ b/docs/LOCAL-MAIL.md @@ -0,0 +1,43 @@ +# Local mail and responsiveness (API 8) + +The Gmail account keeps an account-owned local replica. Inbox lists, supported searches, labels, unread counts and saved message bodies can load without Gmail. Coverage is shown while mail downloads, so a partial search is never presented as a complete mailbox search. Spam, Trash, user labels and every inline plain-text/HTML body are included. Named file attachments download on demand and remain saved afterward. Existing provider limits on individual messages and attachments still apply. + +## Storage and synchronization + +`src/local_mail` owns one SQLite database per registered Gmail account beneath the platform state directory, at `omamail/mail//`. SQLite 3.51.3 or newer is required. The custom VFS accepts only the database and its journal/WAL filenames relative to a pinned private directory. It refuses links, arbitrary attached paths and unsafe ownership. An exclusive owner lease protects one writer and two readers; WAL uses FULL synchronization and private process memory for shared-memory pages. A second process uses the authenticated owner IPC endpoint instead of opening SQLite itself. + +Content-addressed JSON blobs live below the same directory. Reads verify their digest and message identity. SQL stores summaries, effective labels, FTS5 text, sync coverage, retry jobs and edit intents. The existing bounded resource cache is imported incrementally without replacing newer local resources. Replica bodies and retained attachments are durable data, outside the legacy disposable cache quota. New body and attachment storage requires 1 GiB of remaining space plus the new payload size. Existing saved mail remains readable when storage is low. + +A persisted Gmail history checkpoint is taken before inventory. Inventory includes Spam and Trash, saves page tokens and generations, and resumes after restart. History pages commit queued work, deletions and the next checkpoint in one transaction. Repeated or malformed pagination is refused. Expired history starts a new inventory generation; old rows are removed only after inventory has finished and intervening history has been reconciled. Missing inline text remains an explicit, retryable job instead of silently completing coverage. Incomplete resources cannot suppress a foreground retry; opening one hydrates its missing text with interactive request priority. The worker shares per-message fetch locks with foreground reads and queued label edits. It reports changes at most once per second during successful downloads. + +API 8 QML uses `local.watch`, `local.refresh` and `local.unwatch`; Gmail's earlier summary poll/preloader is disabled for those accounts. Other providers retain their existing native watches. The Gmail request scheduler, quota accounting and server retry delays continue to apply to all replica requests. The replica performs no send, read-marker or remote-image action merely to preload content. + +## Search and mailbox edits + +`local.list` returns summaries, a query-bound keyset cursor and coverage. A response also caps retained summary JSON at 16 MiB and returns a continuation rather than accumulating an unbounded page; an individually oversized row is refused. Supported operators are words, quoted phrases, trailing word prefixes, `OR`, negation, `from:`, `to:`, `cc:`, `subject:`, `filename:`, `label:`, supported `in:`/`is:` labels, `category:`, `has:attachment`, `before:` and `after:`. FTS5 handles Unicode body tokens; dates use local midnight. Spam and Trash are excluded unless explicitly included. This is a defined local subset of Gmail search: unsupported syntax returns `local_search_unsupported`, and **Search online** explicitly switches that query to Gmail. + +FTS predicates use parameterized SQL. Selective matches use indexed result sets; very broad matches use row-constrained FTS checks while SQLite walks date order, avoiding materializing and sorting an entire mailbox merely to return its newest page. + +`local.edit` freezes message IDs and persists label additions/removals under an idempotency ticket. UI reads use server labels plus pending intent. Repeated changes to one message coalesce to the final label state; later edits remain separate from an in-flight confirmation. Sync reads the current labels, applies any needed change and confirms the result before marking it done. Authentication/network failures leave edits pending. A deleted message or refused mutation becomes a visible conflict. Undo cancels a queued ticket before it is claimed; once started, the UI asks the user to use the opposite mailbox action. No arbitrary model text can supply a target account or send authorization. + +## Reading, composition and calendar + +The mailbox uses a recycled `ListView`; loaded summary count no longer determines the number of live row components. Ordinary provider summaries appear progressively. Avatars and overviews are enriched for the visible rows and their immediate neighbours. Reader body adoption precedes secondary metadata/model callbacks. The source and render caches each hold at most 32 entries, 12 per account and 64 MiB of serialized data: together at most 64 entries, 24 per account and 128 MiB. These are cache-payload limits, not total process RSS limits. One prefetch worker prepares up to two cached neighbours on each side without fetching remote images or marking them read. + +API 8 compose sends structured fields to `outbox.compose` and `draft.compose`. Attachment imports return opaque handles scoped to the registered account and draft. Native code resolves those handles and builds MIME; file bytes need not make a round trip through QML. Attachment previews and exports fetch provider locators through the backend and reuse retained bytes. Recipient matching reuses an index until the contact set changes. + +An explicit Send can authorize `resumeUnsent` for mail that has never started delivery. Such mail survives restart and waits for connectivity; Undo remains available. A preflight runs outside the outbox state lock and rechecks cancellation before delivery. The outbox persists `sending` before the send call. A process interruption during delivery becomes `unknown` and is never retried automatically. Legacy queued entries without this authorization still cancel on restart. Server draft saves and calendar/label management writes remain online operations. + +Calendar list responses are parsed in Rust. XML/ICS input is bounded; document types are refused. Visible, bar and reminder controllers share source/range caches and coalesce identical native reads. At most two list requests run concurrently. Selecting a date range displays its cached events immediately; late replies may fill their own cache but cannot replace the selected view. Per-source request timestamps prevent stale responses from restoring deleted events. Adjacent ranges warm only while the calendar remains visible. Day indexes avoid repeatedly filtering every event for every visible day. Reminder checks remain every 60 seconds; bar checks remain every 10 minutes. + +## Diagnostics and recovery + +Gmail and RPC diagnostic producers enqueue into bounded channels without waiting for disk writes. Dedicated writers flush batches of up to 64 or every two seconds. Overflow/persistence failures increment dropped-record counters. RPC records contain only an allowlisted method, process/generated correlation numbers, queue and elapsed time, request size and success. Gmail records link to the originating RPC when available; background work has no caller correlation. Caller request IDs, account addresses, credentials, message IDs, subjects, bodies and raw server errors are excluded. Diagnostic report generation validates these records again and retains the existing private-file and report-size limits. + +A failed local read does not delete or rebuild data. Keep the database, WAL, blobs and edit intents together for diagnosis. Do not delete the WAL, clear the owner lock, or open the database through another SQLite VFS while its owner is running. Automatic destructive rebuilds are deliberately absent because pending edits may be the only record of an offline action. Account removal and credential cleanup retain their existing explicit workflows. + +## Verification + +Run `make validate` in an environment that permits local sockets, DBus and the repository's private-directory checks. The focused suites cover search/paging, WAL restart recovery, edit coalescing/undo, malformed history rollback, storage link refusal, attachment-handle ownership, diagnostic redaction, native calendar parity, stale range responses, row recycling and keyboard Undo. Full provider/IPC/security tests require their controlled local servers; blocked setup is not a security pass. + +Run the synthetic database benchmark with `MAGPIE_BENCH_MESSAGES=100000 cargo test --release --lib local_mail::tests::benchmark_local_queries -- --ignored --nocapture`; use `1000000` for the separate scale case. It measures database queries returning 50 summaries, not application startup or Gmail throughput. `python3 benchmarks/mail/ui_latency.py --output /tmp/magpie-paint.json` measures completed Qt frames for loaded-list navigation and prepared HTML. It excludes RPC, disk, network and compositor presentation. End-to-end startup, live-provider contention, HTTP/2/compression and release compiler comparisons require separate measurements before changing transport or release settings. diff --git a/docs/PERFORMANCE-VALIDATION.md b/docs/PERFORMANCE-VALIDATION.md new file mode 100644 index 000000000..9a9a0e383 --- /dev/null +++ b/docs/PERFORMANCE-VALIDATION.md @@ -0,0 +1,67 @@ +# Performance and offline-mail release checks + +The local implementation is described in [LOCAL-MAIL.md](LOCAL-MAIL.md). API 8 remains unreleased; do not replace the pinned binary or publish a release until these checks pass. Use synthetic mail and controlled provider endpoints for mutation/send tests. + +## Ownership and automation + +This is an agent verification runbook, not a checklist for Dave. The performance implementation and this automation stay in a draft PR until the required results are available. Agents investigate failures, repair the fixtures or implementation as appropriate, rerun the affected gates and publish the evidence. Do not transfer ordinary test execution or benchmark analysis to Legwork. + +The `Performance verification` GitHub Actions workflow runs on relevant PR changes and supports manual dispatch. It uses ephemeral hosted Linux runners, synthetic data, a private test HOME/XDG tree and private DBus sessions, with read-only repository permissions and no production secrets. The `ci` job runs Rust, JavaScript, source, portable shell, native QML security, standalone composition/native host and actual backend API checks. Offline storage recovery and subprocess cancellation also run as independent gates without sockets or DBus, so a blocked integration environment still collects those results. Every gate has a separate log and status; failures do not prevent later independent gates from running. JSON results and a summary are retained as workflow artifacts even on failure. The existing CI `Released backend gate` verifies the actual exact pinned release separately. + +The `benchmarks` job builds first, then runs measurements sequentially: original-commit versus working-tree list population/navigation/update, 100,000-message database search with and without background writes, and the separate million-message scale case. It retains raw samples, source hashes, runtime details and the measurement boundaries. Hosted timings describe that runner; they are not desktop acceptance evidence. + +The same runner works locally with `make verify-performance`. Use `VERIFY_PROFILE=desktop` on an authorized Omarchy development runner to include the full `make validate` and real Quickshell process bridge, or `VERIFY_PROFILE=benchmarks` for the measurements. `VERIFY_OUTPUT=/absolute/new/directory` chooses a fresh report directory. `python3 scripts/verify-performance.py --profile desktop --preflight-only --output /tmp/magpie-preflight` checks sockets, ownership, private DBus and installed tools without running the suite. Missing capabilities are recorded as blocked and return nonzero; no security check is disabled to obtain a pass. + +The desktop/recovery scenarios below are the agent's acceptance work. Existing unit/component fixtures cover parts of them; the runner does not claim that those fixtures establish complete provider recovery, physical compositor timing or screen-reader usability. Any missing scenario requires an automated fixture or an agent-operated synthetic desktop session before its gate can be marked passed. HTTP/2/gzip and compiler tuning are separate experiments for a future settings change, not requirements for shipping the unchanged transport/compiler configuration. + +The independent `qml-components` gate runs each QML fixture that does not import the native model bridge, retaining its own process result and log. Fixtures that import `NativeIntentFixture.js` are listed explicitly under `nativeBridgeRequired`; they remain covered by the complete `test-qml` gate and are not counted as component passes. This allows interaction regressions to run when local sockets are unavailable without replacing provider or resource-security tests. Rust and full desktop validation also require a working PDF sandbox: the workflow installs Bubblewrap and Poppler, and preflight checks that the isolated worker can start so missing tools cannot make conditional PDF tests look like complete security evidence. + +The independent `shell-independent` gate runs the 35 shell/Python files that need no listeners or DBus, plus the seven public-HTTP policy cases. The complete `test-shell-portable` target still includes all 38 original files, including notification routing, real curl refusal and HTTP/TLS integration. A passing independent gate cannot establish those network or DBus boundaries. Both targets use the same maintained commands; the runner confines their state to temporary HOME/XDG directories. + +## Required automated gates + +On 2026-10-21, the installed interface was found to call `local.edit`, `local.watch` and `calendar.read` against a backend that advertised API 8 but did not implement those methods. Isolated probes reproduced the `Invalid params` response. The UI now verifies the unreleased contract hash, retains the released API for an older development build, and refuses unsupported methods before dispatch. Regression tests cover the real production delete adapter, queued and oversized requests, Qt handshake behavior, and native bundle readiness. RPC diagnostics now retain bounded timestamps and allowlisted failure reasons; the diagnostic export preserves those facts while stripping private text. Installation and release remain separate acceptance steps. + +The 2026-10-21 native build and all seven CTest groups passed in an isolated offscreen environment, including the standalone composition and backend resource checks. Those groups do not require the provider suite's TCP/DBus fixtures, so their automation gates now run independently; QML lint is also an independent gate. The corresponding CI-profile run has ten passing gates and five blocked gates. The final full Rust run remains 477 passed, 195 failed and 14 ignored under the restricted runtime, with exactly the same failed-test names as the previous run; this is not a passing `make validate` result. Physical desktop, provider integration and published-release verification remain outstanding. + +Focused compatibility checks pass: 38 runtime tests, 17 diagnostic/privacy tests, 5 automation tests, the production Gmail adapter JavaScript tests, and Qt backend/runtime/Gmail-queue groups with 25/18/8 passes. The production error-notice block was rendered in 56 synthetic before/after states covering seven failure categories at wide, narrow and enlarged text sizes, plus standalone without the AI diagnostics button. All tested text fits; an initial height-binding warning also occurs with the old message. These captures do not certify desktop themes or screen-reader behavior. The installed plugin/backend pair remains unchanged by this fix. + +A further 2026-10-21 interaction run reproduced and fixed that height-binding cycle by leaving the notice text's height intrinsic. A regression fails on the original warning and passes after the change; all 28 updated notice captures are pixel-identical to the previous layouts. Keyboard tests also showed that mailbox shortcuts intercepted focused buttons. Shared icon, text and panel action buttons now reserve unmodified Return, keypad Enter and Space, while modified shortcuts and Escape keep their normal routing. Focus shows the tooltip label; text and panel action buttons expose accessible names and press actions. The full application fixture has 33 passes, and the keyboard-router fixture has 32, covering three control types and proving that activation does not open or select an underlying message. + +The independent component run passes all 111 selected files with 1,078 test cases plus 222 setup/cleanup pass records; 11 files still require the native bridge. Four stale fixtures were updated to exercise the current native attachment path, complete runtime metadata and visible-row inbox admission; account isolation, cancellation and refusal checks remain. That interaction-stage automation recorded 11 passing gates and 5 blocked gates. The latest full `make validate` still fails with 477 passes, the same 195 failures and 14 ignored tests. Failure-stage triage identifies denied OS operations, remapped private-path ownership, unavailable TLS fixtures and the PDF worker's denied socket setup; it does not establish that integration behavior is correct. Complete integration, release and desktop acceptance remain open. + +The subsequent shell audit ran all 38 portable test files separately in isolated state: 35 passed, and three failed when their socket/DBus fixtures were refused. The new combined independent target also passes all 35 files plus the seven HTTP policy cases. This combined run exposed a fixture isolation error: the default standalone-target test inherited the runner's explicit backend-path override. Its nested Make invocations now clear inherited Make flags and standalone path overrides while retaining the original default-path assertions. Those assertions pass both normally and with synthetic inherited overrides. All original shell commands remain in the full portable target; neither a partial hostile-input run nor the independent target establishes the real network boundary tests. The final CI-profile rerun has 12 passing gates, no failed runnable gates and 5 blocked gates; full validation and desktop acceptance remain incomplete. + +The `desktop` profile runs `make validate` from a repository checkout with local TCP/Unix sockets, DBus and ordinary filesystem ownership available. In the restricted implementation environment, the initial implementation run had 471 Rust passes, 196 failures and 14 ignored tests. Failures included denied local server/IPC/DBus setup and private-directory ownership checks. The pre-existing subprocess cancellation failure was subsequently reproduced: the child was terminated but remained a zombie because its exit status was not collected promptly. The async transport now retains an explicit child reaper on cancellation; all 19 focused subprocess tests pass, including a control-backed regression that asserts a cancelled descendant cannot write a file. The source, JavaScript, QML lint, diagnostic privacy and focused UI gates passed independently. A failed full gate remains a failed gate. + +The follow-up isolated `make validate` run on 2026-10-20 recorded 477 Rust passes, 195 failures and 14 ignored tests, then stopped at the Rust gate. Its failed-test names are exactly the earlier set minus the corrected cancellation case; no new failed test appeared. This is still a failed full gate, and later Makefile targets were not reached by that invocation. + +Four additional storage recovery tests exercise the production inventory/history transaction functions and the rooted SQLite store. Child processes exit without destructors after an inventory page and a history page; reopening retains the checkpoints, pending downloads and edit intents. Unvisited mail is removed only after reconciliation, pending bodies prevent complete coverage, and a deleted message turns its queued edit into a conflict. The other cases verify atomic rollback for malformed/cyclic inventory pages, preservation through expired history, and availability of saved bodies/counts/Undo while a sync authentication error is recorded. These tests pass alongside the nine existing local-store correctness tests. They establish durable storage behavior; the provider transport, credential lifecycle and full UI flows below still require integration evidence. + +Run the native QML security tests, including the message renderer and attachment preview workers, through the Makefile targets. Do not skip them merely because the focused component tests pass. New local-store tests cover WAL recovery, link refusal, paging, edit coalescing, history rollback and IPC dispatch isolation. The authenticated owner socket test and actual provider recovery flows still need their unrestricted runtime. + +Run `python3 tests/test_backend_api.py --binary target/debug/omamail` after a fresh build. The ten new validation/parser cases can run without storage; the complete contract requires the private filesystem fixtures. Also run the Published backend gate with the checksum-verified executable from the exact `backend-version` release. The already installed executable reported API 8 while the repository's released contract declares API 7, so it is not valid evidence for this gate. Keep the release download separate from the installed executable; follow [BACKEND-RUNTIME.md](BACKEND-RUNTIME.md). No installation or pin change was made by the performance implementation. + +## Desktop and recovery checks + +Exercise a development instance through the documented development launch flow. Preserve real accounts and stored data. Prefer dedicated test accounts or synthetic fixtures for every destructive action. + +1. Open a previously synchronized inbox with networking unavailable. Verify lists, bodies, labels and counts appear from local state and that cached mail remains readable after authorization expires. +2. Stop the test backend during inventory, a history page and a body download. Restart it and verify it resumes without declaring incomplete coverage complete or deleting unvisited rows. Exercise expired history and low-space refusal using controlled fixtures. +3. Queue read/unread, star/unstar and folder changes offline. Check immediate local state, queued Undo, rapid reversals, reconnect reconciliation and visible conflicts after a server-side deletion. +4. With a controlled send recorder, explicitly press Send offline, restart before transmission, then reconnect. Verify one delivery. Interrupt a send after transmission begins and verify the recovered state is unknown with no automatic retry. Cancel during preflight and verify the recorder receives nothing. +5. Restore a draft with retained file handles, switch accounts and attempt foreign-draft handle reuse. Confirm the wrong account/draft cannot obtain the bytes and that the owning draft still works. +6. Switch calendar months and accounts while responses are pending. Confirm the selected range stays visible, newer empty ranges do not resurrect removed events, and bar/reminder reads reuse cached ranges. Check recurrence and DST cases across Google, Graph and CalDAV. +7. Use the new status and send controls by keyboard, screen reader and enlarged text. The synthetic Qt screenshots establish component layout at one scale; they do not establish whole-desktop accessibility or every active Omarchy theme. + +## End-to-end performance acceptance + +Measure input acknowledgement, completed visible paint and cold local inbox startup separately. Record hardware, Qt/backend versions, viewport/theme/scale, corpus sizes, binary/source hashes and whether OS caches were warm. The targets remain p95 ≤50 ms input acknowledgement, ≤100 ms warm navigation, ≤200 ms large HTML, ≤200 ms 100,000-message local search, ≤1 s cold local inbox, and ≤20% foreground degradation during background work. Measure one million messages as a separate scale case. Database-only and offscreen-frame results do not certify all these targets. + +The reproducible component harnesses are in [benchmarks/mail/README.md](../benchmarks/mail/README.md). Run them after builds have stopped. Include input handling, RPC and actual window painting in the desktop run, and compare foreground latency with background sync idle and active. Report a miss rather than substituting callback completion for visible paint. + +## HTTP transport experiments + +Current reqwest features do not opt into HTTP/2 or gzip. Leave the release settings unchanged until representative controlled-server measurements compare the existing client with each feature independently and together. Record connection reuse, negotiated protocol, wire bytes, concurrency, p50/p95 and total throughput. Repeat on a constrained connection and with background sync active. Verify deadlines, decompressed-size bounds, credential origin confinement, TLS and redirects before accepting a change. Do not infer a gain from protocol support alone. + +The compiler-profile harness compares current size optimization with `opt-level=3` using identical synthetic parsing/rendering inputs. It checks semantic equivalence and records binary hashes. Treat it as a CPU diagnostic; repeat the complete desktop path before changing the release profile. The implementation keeps the existing compiler and transport settings. diff --git a/scripts/backend-runtime.py b/scripts/backend-runtime.py index 8e1f79b6b..53e3d1e9f 100755 --- a/scripts/backend-runtime.py +++ b/scripts/backend-runtime.py @@ -67,7 +67,7 @@ def api_pin(): require(latest - released in (0, 1), "Invalid backend API version.") unreleased = contract.get("unreleased", {}).get("methods", []) if isinstance(contract.get("unreleased"), dict) else None require(isinstance(unreleased, list) and all(isinstance(m, str) for m in unreleased), "Invalid backend API contract.") - return released, latest, unreleased + return released, latest, unreleased, hashlib.sha256(raw).hexdigest() def safe_path(path, directory=False, create=False): @@ -374,11 +374,11 @@ def cli_installed(): def run(command): - result = dict(state="error", requiredVersion="", requiredApiVersion=0, latestApiVersion=0, unreleasedMethods=[], installedVersion="", executable=str(BINARY), error="", cliInstalled=False) + result = dict(state="error", requiredVersion="", requiredApiVersion=0, latestApiVersion=0, unreleasedMethods=[], contractHash="", installedVersion="", executable=str(BINARY), error="", cliInstalled=False) try: required = pin() result["requiredVersion"] = required - result["requiredApiVersion"], result["latestApiVersion"], result["unreleasedMethods"] = api_pin() + result["requiredApiVersion"], result["latestApiVersion"], result["unreleasedMethods"], result["contractHash"] = api_pin() development = os.environ.get("OMAMAIL_BIN", "") executable = Path(development) if development else BINARY result["executable"] = str(executable) diff --git a/scripts/diagnostics.py b/scripts/diagnostics.py index bbe874a93..fd63f44c3 100644 --- a/scripts/diagnostics.py +++ b/scripts/diagnostics.py @@ -18,7 +18,14 @@ # An exact, reviewed vocabulary, never a pattern that could admit a credential or # server text. tests/test_diagnostics.py flags new static backend identifiers; # review their source before adding them here, never derive this set at runtime. -MESSAGES = set('''permission_required contacts_invalid contacts_permission_required contacts_response_limit contacts_unavailable inbox_gmail_required inbox_storage_invalid inbox_storage_unavailable inbox_unavailable overview_ai_unavailable overview_input_invalid overview_invalid_response overview_start_failed overview_unsupported_claim snooze_invalid_folder snooze_invalid_thread snooze_invalid_time snooze_limit snooze_missing snooze_pending_retry +MESSAGES = set('''attachment_handle_invalid attachment_handle_unavailable attachment_provider_unsupported +calendar_busy calendar_recurrence_too_large calendar_recurrence_unsupported gmail_not_found +local_account_unknown local_content_invalid local_content_missing local_content_too_large +local_disk_full local_disk_low local_edit_already_started local_edit_id_conflict local_edit_not_confirmed +local_message_unavailable local_owner_unavailable local_schema_newer local_search_unsupported +local_sqlite_update_required local_storage_corrupt local_storage_unavailable local_text_incomplete +outbox_awaiting_connection outbox_connection_unavailable +permission_required contacts_invalid contacts_permission_required contacts_response_limit contacts_unavailable inbox_gmail_required inbox_storage_invalid inbox_storage_unavailable inbox_unavailable overview_ai_unavailable overview_input_invalid overview_invalid_response overview_start_failed overview_unsupported_claim snooze_invalid_folder snooze_invalid_thread snooze_invalid_time snooze_limit snooze_missing snooze_pending_retry accounts_busy accounts_conflict accounts_invalid accounts_setup_replacement accounts_too_large accounts_unexpected_removal accounts_unreadable accounts_version_unsupported accounts_write_failed agent_active_limit agent_cancel_failed agent_choose_claude @@ -166,7 +173,7 @@ def clean(event, existing=False): 'message': message if isinstance(message, str) and message in MESSAGES else 'unknown_error'} -GMAIL_OPERATIONS = set('''getProfile labels.list labels.get settings.sendAs.list +GMAIL_OPERATIONS = set('''history.list getProfile labels.list labels.get settings.sendAs.list messages.list messages.get.full messages.get.metadata messages.attachments.get threads.get.full threads.get.metadata drafts.list messages.send messages.batchModify messages.modify messages.trash messages.untrash labels.create labels.update labels.delete @@ -175,6 +182,27 @@ def clean(event, existing=False): 'dailyLimitExceeded', 'insufficientPermissions', 'domainPolicy', 'authError', 'sessionInvalidated'} +def clean_rpc(event): + if (not isinstance(event, dict) or not isinstance(event.get('method'), str) + or event['method'] not in METHODS or type(event.get('success')) is not bool): + return None + result = {'method': event['method'], 'success': event['success']} + for key in ('process', 'request', 'queueUs', 'elapsedUs', 'requestBytes'): + value = event.get(key) + if type(value) is not int or not 0 <= value < 2**64: + return None + result[key] = value + if 'timeMs' in event: + value = event['timeMs'] + if type(value) is not int or not 0 <= value < 2**64: + return None + result['timeMs'] = value + error = event.get('error') + if error is not None: + result['error'] = error if isinstance(error, str) and error in MESSAGES else 'unknown_error' + return result + + def clean_gmail(event): if not isinstance(event, dict): return None @@ -182,7 +210,7 @@ def clean_gmail(event): vocabularies = {'operation': GMAIL_OPERATIONS, 'reason': GMAIL_REASONS, 'lane': {'interactive', 'background', 'poll', 'queue', 'auth'}, - 'outcome': {'ok', 'gmail_rate_limited', 'gmail_unauthorized', + 'outcome': {'ok', 'gmail_not_found', 'gmail_rate_limited', 'gmail_unauthorized', 'gmail_forbidden', 'gmail_length_required', 'gmail_http_failed', 'gmail_timeout', 'gmail_response_too_large', 'gmail_invalid_response', 'gmail_session_invalidated'}} for key, allowed in vocabularies.items(): @@ -206,6 +234,8 @@ def clean_gmail(event): if value is not None and (type(value) is not int or not 0 <= value <= maximum): return None result[key] = value + if type(event.get('rpc')) is int and 0 <= event['rpc'] < 2**64: + result['rpc'] = event['rpc'] return result @@ -318,6 +348,23 @@ def main(mode): if gmail: report += '\n\nRecent Gmail attempts (session numbers are process-local, not addresses):\n' report += '\n'.join(json.dumps(event, ensure_ascii=True) for event in gmail) + try: + timings = json.loads(read(fd, 'rpc.json') or b'[]') + except (ValueError, OSError): + timings = [] + if isinstance(timings, list): + timings = [safe for event in timings[-256:] if (safe := clean_rpc(event)) is not None] + if timings: + report += '\n\nRecent RPC timings (microseconds; generated request numbers):\n' + report += '\n'.join(json.dumps(event, ensure_ascii=True) for event in timings) + for filename in ('gmail-writer.json', 'rpc-writer.json'): + try: + writer = json.loads(read(fd, filename) or b'{}') + dropped = writer.get('dropped') if isinstance(writer, dict) else None + if type(dropped) is int and 0 <= dropped < 2**64: + report += '\n' + filename + ': dropped records=' + str(dropped) + except (ValueError, OSError): + pass # Preserve the existing bounded report when the transport history is full. while len(report.encode('utf-8')) + 1 > LIMIT: lines = report.splitlines() diff --git a/scripts/verify-performance.py b/scripts/verify-performance.py new file mode 100644 index 000000000..daaf7c4e6 --- /dev/null +++ b/scripts/verify-performance.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Run isolated verification gates and retain every result, including blocked gates.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +BASELINE = "aeac13160f70a86f6419eaf2ceb1695fad078c7c" + + +def qt_tool(name): + return shutil.which(name + "6") or ( + str(Path("/usr/lib/qt6/bin") / name) if (Path("/usr/lib/qt6/bin") / name).is_file() + else shutil.which(name)) + + +def private_ancestors(path): + for ancestor in (path, *path.parents): + info = ancestor.stat() + if info.st_uid not in (0, os.geteuid()): + raise RuntimeError(f"{ancestor} has a foreign owner ({info.st_uid})") + if info.st_mode & 0o022 and not (info.st_uid == 0 and info.st_mode & stat.S_ISVTX): + raise RuntimeError(f"{ancestor} permits unsafe writes") + + +def thumbnail_sandbox(): + for program in ("bwrap", "pdftoppm", "prlimit"): + if not Path("/usr/bin", program).is_file(): + raise RuntimeError(f"PDF sandbox dependency is missing: /usr/bin/{program}") + result = subprocess.run([ + "/usr/bin/bwrap", "--unshare-all", "--die-with-parent", "--new-session", + "--cap-drop", "ALL", "--clearenv", "--ro-bind", "/usr", "/usr", + "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib", "/lib64", + "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--chdir", "/tmp", + "/usr/bin/true"], capture_output=True, text=True, timeout=10) + if result.returncode: + raise RuntimeError("PDF sandbox cannot start: " + result.stderr.strip()[:500]) + + +def capabilities(directory): + result = {} + + def check(name, operation): + try: + operation() + result[name] = {"status": "pass"} + except (OSError, RuntimeError, subprocess.SubprocessError) as error: + result[name] = {"status": "blocked", "reason": str(error)} + + def listener(family): + with socket.socket(family, socket.SOCK_STREAM) as server: + server.bind(("127.0.0.1", 0) if family == socket.AF_INET else str(directory / "probe.sock")) + server.listen(1) + + check("tcp", lambda: listener(socket.AF_INET)) + check("unix", lambda: listener(socket.AF_UNIX)) + check("ownership", lambda: private_ancestors(directory)) + check("dbus", lambda: subprocess.run(["dbus-run-session", "--", "true"], check=True, + capture_output=True, timeout=10)) + check("pdf-sandbox", thumbnail_sandbox) + for name in ("cargo", "node", "make", "cmake", "omarchy", "qs"): + result[name] = {"status": "pass"} if shutil.which(name) else { + "status": "blocked", "reason": name + " is not installed"} + for name in ("qmltestrunner", "qmllint"): + result[name] = {"status": "pass"} if qt_tool(name) else { + "status": "blocked", "reason": name + " is not installed"} + return result + + +def test_environment(directory): + keep = ("PATH", "LANG", "LC_ALL", "CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN", + "CARGO_NET_OFFLINE", "PKG_CONFIG_PATH", "LD_LIBRARY_PATH", "CMAKE_PREFIX_PATH", + "QT_PLUGIN_PATH", "QML2_IMPORT_PATH", "QML_IMPORT_PATH", "SSL_CERT_FILE", + "SSL_CERT_DIR", "CARGO_BUILD_JOBS") + env = {key: os.environ[key] for key in keep if key in os.environ} + env.setdefault("CARGO_HOME", str(Path.home() / ".cargo")) + env.setdefault("RUSTUP_HOME", str(Path.home() / ".rustup")) + for key in ("HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", + "XDG_STATE_HOME", "XDG_RUNTIME_DIR"): + path = directory / key.lower() + path.mkdir(mode=0o700) + env[key] = str(path) + env.update(QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software", + QT_QPA_PLATFORMTHEME="", GSETTINGS_BACKEND="memory", QT_SCALE_FACTOR="1", + CARGO_TARGET_DIR=str(ROOT / "target")) + return env + + +def stages(profile, output, baseline): + qml = qt_tool("qmltestrunner") or "qmltestrunner" + lint = qt_tool("qmllint") or "qmllint" + make = ["make", "QMLTESTRUNNER=" + qml, "QMLLINT=" + lint, + "APP_BACKEND=" + str(ROOT / "target/debug/omamail")] + isolated = ["dbus-run-session", "--"] + runtime = ["tcp", "unix", "ownership", "dbus"] + gate = lambda name, command, needs=(): (name, command, list(needs)) + if profile == "benchmarks": + return [ + gate("build-benchmarks", ["cargo", "test", "--release", "--locked", "--lib", "--no-run"], ["cargo"]), + gate("list-before-after", [sys.executable, "benchmarks/mail/compare_ui.py", + "--baseline", baseline, "--runner", qml, + "--output", str(output / "before-after.json")], ["qmltestrunner"]), + *[gate(name, ["cargo", "test", "--release", "--locked", "--lib", + "local_mail::tests::benchmark_local_queries", "--", "--ignored", "--nocapture"], + ["cargo"]) for name in ("database-idle", "database-background", "database-million")], + ] + gates = [ + gate("build", ["cargo", "build", "--locked", "--bin", "omamail"], ["cargo"]), + gate("offline-recovery", ["cargo", "test", "--locked", "--lib", "local_mail::recovery_tests"], ["cargo"]), + gate("subprocess", ["cargo", "test", "--locked", "--lib", "process::"], ["cargo"]), + gate("rust", isolated + make + ["test-rust"], ["cargo", "pdf-sandbox"] + runtime), + gate("javascript", make + ["test-js"], ["node"]), + gate("source", ["bash", "tests/test_source.sh"]), + gate("shell-independent", make + ["test-shell-independent"], ["node"]), + gate("shell", isolated + make + ["test-shell-portable"], ["node"] + runtime), + gate("qml", isolated + make + ["test-qml"], ["cargo", "qmltestrunner"] + runtime), + gate("qml-components", [sys.executable, "tests/run_qml_components.py", "--runner", qml, + "--output", str(output / "qml-components")], ["qmltestrunner"]), + gate("standalone-qml", make + ["test-app-qml"], ["cmake", "qmltestrunner"]), + gate("native-host", ["ctest", "--test-dir", "app/build", + "--output-on-failure", "--no-tests=error"], ["cmake"]), + gate("qml-lint", make + ["qml-check"], ["qmllint"]), + gate("api-inventory", [sys.executable, "scripts/package-backend.py", "check-api"]), + gate("api-contract", isolated + [sys.executable, "tests/test_backend_api.py", + "--binary", "target/debug/omamail"], runtime), + gate("native-agent", isolated + [sys.executable, "tests/test_agent_native_bridge.py"], runtime), + gate("diff", ["git", "diff", "--check"]), + ] + if profile == "desktop": + gates.extend([ + gate("validate", isolated + make + ["validate"], ["cargo", "cmake", "qmltestrunner", + "qmllint", "omarchy", "pdf-sandbox"] + runtime), + gate("quickshell-bridge", isolated + make + ["test-backend-process"], ["qs", "cargo"] + runtime), + ]) + return gates + + +def prerequisites(name): + if name in ("qml", "api-contract", "native-agent", "standalone-qml"): + return ["build"] + if name == "native-host": + return ["standalone-qml"] + if name.startswith("database-"): + return ["build-benchmarks"] + return [] + + +def execute(command, environment, log, timeout): + started = time.monotonic() + with log.open("w") as stream: + try: + process = subprocess.Popen(command, cwd=ROOT, env=environment, stdout=stream, + stderr=subprocess.STDOUT, start_new_session=True) + except OSError as error: + stream.write(str(error) + "\n") + return {"status": "blocked", "reason": str(error)} + try: + while True: + try: + code = process.wait(timeout=min(30, max(.1, timeout - (time.monotonic() - started)))) + return {"status": "pass" if code == 0 else "fail", "exitCode": code, + "seconds": round(time.monotonic() - started, 3)} + except subprocess.TimeoutExpired: + if time.monotonic() - started >= timeout: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"status": "fail", "reason": "deadline exceeded", "seconds": timeout} + print(" still running:", log.stem, flush=True) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + +def save(output, report): + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + lines = ["# Magpie verification", "", f"Profile: `{report['profile']}`. Result: **{report['status']}**.", + "", "| Gate | Result | Detail |", "| --- | --- | --- |"] + for gate in report["gates"]: + detail = gate.get("reason", gate.get("log", "")) + lines.append(f"| {gate['name']} | {gate['status']} | {detail.replace('|', '/')} |") + lines += ["", "These are synthetic, isolated checks. Hosted/offscreen results do not certify physical " + "compositor latency, real mailbox compatibility, or assistive-technology usability.", + "Published-binary compatibility is provided separately by the existing CI Released backend gate.", + "HTTP/2, gzip and compiler-profile changes are not enabled by this work."] + (output / "summary.md").write_text("\n".join(lines) + "\n") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--profile", choices=["ci", "desktop", "benchmarks"], default="ci") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--baseline", default=BASELINE) + parser.add_argument("--preflight-only", action="store_true") + parser.add_argument("--timeout", type=int, default=1800) + args = parser.parse_args() + if args.timeout < 1: + parser.error("timeout must be positive") + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False, mode=0o700) + source_files = subprocess.check_output(["git", "ls-files", "-co", "--exclude-standard", "-z"], cwd=ROOT) + digest = hashlib.sha256() + for name in sorted(set(source_files.decode().split("\0")) - {""}): + path = ROOT / name + if path.is_file() and not path.is_symlink(): + digest.update(name.encode() + b"\0" + path.read_bytes()) + report = dict(profile=args.profile, startedAt=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + platform=platform.platform(), sourceSha256=digest.hexdigest(), + commit=subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), + status="running", gates=[]) + with tempfile.TemporaryDirectory(prefix="magpie-verification-") as temporary: + directory = Path(temporary) + environment = test_environment(directory) + available = capabilities(directory) + report["capabilities"] = available + for name, command, needs in stages(args.profile, output, args.baseline): + missing = [need for need in needs if available[need]["status"] != "pass"] + prior = {gate["name"]: gate["status"] for gate in report["gates"]} + failed_dependencies = [item for item in prerequisites(name) if prior.get(item) != "pass"] + result = dict(name=name, command=command) + if missing: + result.update(status="blocked", reason="; ".join(need + ": " + available[need]["reason"] + for need in missing)) + elif args.preflight_only: + result.update(status="not-run", reason="preflight only") + elif failed_dependencies: + result.update(status="blocked", reason="prerequisite did not pass: " + ", ".join(failed_dependencies)) + else: + print("Running", name, flush=True) + env = dict(environment, MAGPIE_BENCH_MESSAGES="1000000" if name == "database-million" else "100000", + MAGPIE_BENCH_BACKGROUND="1" if name == "database-background" else "0") + result.update(execute(command, env, output / (name + ".log"), args.timeout), + log=name + ".log") + report["gates"].append(result) + print(name + ": " + result["status"], flush=True) + save(output, report) + statuses = {gate["status"] for gate in report["gates"]} + report["status"] = "fail" if "fail" in statuses else "blocked" if "blocked" in statuses else ( + "not-run" if "not-run" in statuses else "pass") + save(output, report) + print("Results:", output / "summary.md") + return 0 if report["status"] == "pass" else 2 if report["status"] in ("blocked", "not-run") else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/attachment/mod.rs b/src/attachment/mod.rs index db02879f0..263aba5ba 100644 --- a/src/attachment/mod.rs +++ b/src/attachment/mod.rs @@ -12,6 +12,7 @@ use std::{ use unicode_normalization::UnicodeNormalization; mod pdf; pub mod thumbnail; +pub(crate) mod vault; pub const MAX_BYTES: usize = 20 * 1024 * 1024; const ACTIVE_TEXT_MARKERS: &[&str] = &[ " = std::result::Result; +const LIMIT: u64 = 29 * 1024 * 1024; + +fn text<'a>(params: &'a Value, key: &str) -> Result<&'a str> { + params[key] + .as_str() + .filter(|v| !v.is_empty() && v.len() <= 4096 && !v.chars().any(char::is_control)) + .ok_or("invalid_params") +} +fn hash(value: &str) -> String { + format!("{:x}", Sha256::digest(value.as_bytes())) +} +fn directory(account: &str, scope: &str, create: bool) -> Result> { + let root = AppDirs::discover()?.state; + let Some(root) = private_fs::directories(&root, &["omamail", "attachments"], create)? else { + return Ok(None); + }; + scoped_directory(&root, account, scope, create) +} +fn scoped_directory(root: &File, account: &str, scope: &str, create: bool) -> Result> { + let Some(account) = private_fs::open_dir(root, hash(account).as_ref(), create, true)? else { + return Ok(None); + }; + private_fs::open_dir(&account, hash(scope).as_ref(), create, true) +} +fn save(directory: &File, name: &str, value: &Value) -> Result<()> { + let bytes = serde_json::to_vec(value).map_err(|_| "attachment_data_invalid")?; + if private_fs::available_bytes(directory)? < 1024 * 1024 * 1024 + bytes.len() as u64 { + return Err("local_disk_low"); + } + private_fs::atomic_replace(directory, name, &bytes) +} +fn load(directory: &File, name: &str) -> Result> { + let Some(file) = private_fs::regular(directory, name, false)? else { + return Ok(None); + }; + let mut bytes = Vec::new(); + file.take(LIMIT + 1) + .read_to_end(&mut bytes) + .map_err(|_| "attachment_unreadable")?; + if bytes.len() as u64 > LIMIT { + return Err("attachment_too_large"); + } + let record: Value = serde_json::from_slice(&bytes).map_err(|_| "attachment_unreadable")?; + super::decode(record["data"].as_str().ok_or("attachment_unreadable")?)?; + Ok(Some(record)) +} +pub(crate) fn cached(account: &str, id: &str, part: &str) -> Result> { + let Some(dir) = directory(account, "received", false)? else { + return Ok(None); + }; + load(&dir, &hash(&json!([id, part]).to_string())) +} +pub(crate) fn cache(account: &str, id: &str, part: &str, value: &Value) -> Result<()> { + super::decode(value["data"].as_str().ok_or("attachment_data_invalid")?)?; + let dir = directory(account, "received", true)?.ok_or("attachment_unreadable")?; + save(&dir, &hash(&json!([id, part]).to_string()), value) +} +pub(crate) fn import(params: &Value) -> Result { + let account = text(params, "accountId")?; + let draft = text(params, "draftKey")?; + let value = super::read(&json!({"path":text(params,"path")?}))?; + retain(account, draft, &value) +} +pub(crate) fn retain(account: &str, draft: &str, value: &Value) -> Result { + let dir = directory(account, draft, true)?.ok_or("attachment_unreadable")?; + retain_at(&dir, value) +} +fn retain_at(dir: &File, value: &Value) -> Result { + let bytes = super::decode(value["data"].as_str().ok_or("attachment_data_invalid")?)?; + let mut random = [0; 32]; + rustls::crypto::ring::default_provider() + .secure_random + .fill(&mut random) + .map_err(|_| "random_unavailable")?; + let handle = format!("{:x}", Sha256::digest(random)); + let record = json!({"filename":super::safe_filename(value["filename"].as_str().unwrap_or("attachment")), + "mimeType":value["mimeType"].as_str().unwrap_or("application/octet-stream"), + "size":bytes.len(),"data":value["data"]}); + save(dir, &handle, &record)?; + Ok( + json!({"ok":true,"filename":record["filename"],"mimeType":record["mimeType"],"size":record["size"],"handle":handle}), + ) +} +pub(crate) fn hydrate(account: &str, fields: &mut Value) -> Result<()> { + hydrate_with(account, fields, |account, draft| { + directory(account, draft, false) + }) +} +fn hydrate_with( + account: &str, + fields: &mut Value, + directory: impl Fn(&str, &str) -> Result>, +) -> Result<()> { + let draft = fields["draftKey"].as_str().unwrap_or("").to_owned(); + let Some(files) = fields["attachments"].as_array_mut() else { + return Ok(()); + }; + for file in files { + let Some(handle) = file + .get("handle") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + else { + continue; + }; + if draft.is_empty() || handle.len() != 64 || !handle.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err("attachment_handle_invalid"); + } + let dir = directory(account, &draft)?.ok_or("attachment_handle_unavailable")?; + *file = load(&dir, handle)?.ok_or("attachment_handle_unavailable")?; + } + Ok(()) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::{PermissionsExt, symlink}; + + #[test] + fn handles_are_scoped_to_account_and_draft_and_links_never_load_content() { + let path = std::env::temp_dir().join(format!( + "magpie-vault-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&path).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); + let root = File::open(&path).unwrap(); + let draft = scoped_directory(&root, "owner@example.test", "draft-a", true) + .unwrap() + .unwrap(); + let saved = retain_at( + &draft, + &json!({"filename":"example.txt","mimeType":"text/plain","data":"c2VjcmV0"}), + ) + .unwrap(); + assert!(saved.get("data").is_none()); + let fields = json!({"draftKey":"draft-a","attachments":[saved.clone()]}); + let resolve = |account: &str, scope: &str| scoped_directory(&root, account, scope, false); + let mut owner = fields.clone(); + hydrate_with("owner@example.test", &mut owner, resolve).unwrap(); + assert_eq!(owner["attachments"][0]["data"], "c2VjcmV0"); + let mut foreign = fields.clone(); + assert_eq!( + hydrate_with("other@example.test", &mut foreign, resolve), + Err("attachment_handle_unavailable") + ); + assert!(foreign["attachments"][0].get("data").is_none()); + foreign["draftKey"] = json!("draft-b"); + assert_eq!( + hydrate_with("owner@example.test", &mut foreign, resolve), + Err("attachment_handle_unavailable") + ); + assert!(foreign["attachments"][0].get("data").is_none()); + let outside = path.join("outside"); + let sentinel = br#"{"data":"c2VudGluZWw="}"#; + std::fs::write(&outside, sentinel).unwrap(); + let handle = saved["handle"].as_str().unwrap(); + let target = path + .join(hash("owner@example.test")) + .join(hash("draft-a")) + .join(handle); + std::fs::remove_file(&target).unwrap(); + symlink(&outside, &target).unwrap(); + let mut linked = fields.clone(); + assert!(hydrate_with("owner@example.test", &mut linked, resolve).is_err()); + assert!(linked["attachments"][0].get("data").is_none()); + assert_eq!(std::fs::read(&outside).unwrap(), sentinel); + std::fs::remove_file(&target).unwrap(); + std::fs::hard_link(&outside, &target).unwrap(); + assert!(hydrate_with("owner@example.test", &mut linked, resolve).is_err()); + assert!(linked["attachments"][0].get("data").is_none()); + assert_eq!(std::fs::read(&outside).unwrap(), sentinel); + std::fs::remove_dir_all(path).unwrap(); + } +} diff --git a/src/backend/attachments.rs b/src/backend/attachments.rs new file mode 100644 index 000000000..784cccd11 --- /dev/null +++ b/src/backend/attachments.rs @@ -0,0 +1,144 @@ +use super::Session; +use crate::attachment::{self, vault}; +use serde_json::{Value, json}; + +impl Session { + async fn attachment_data( + &self, + account: &str, + id: &str, + part: &str, + ) -> Result { + crate::cache::validate_params(&json!({"accountId":account,"id":id}), true)?; + if part.is_empty() || part.len() > 16384 || part.chars().any(char::is_control) { + return Err("invalid_params"); + } + let provider = super::reader::registered(account).await?; + let (a, m, p) = (account.to_owned(), id.to_owned(), part.to_owned()); + if let Some(value) = tokio::task::spawn_blocking(move || vault::cached(&a, &m, &p)) + .await + .map_err(|_| "worker_failed")?? + { + return Ok(value); + } + let params = json!({"accountId":account,"messageId":id,"attachmentId":part}); + let value = match provider.as_str() { + "gmail" => self.gmail.call("gmail.attachment", ¶ms).await?, + "jmap" => { + self.jmap + .call( + "jmap.attachment", + &json!({"accountId":account,"attachmentId":part}), + ) + .await? + } + "imap" | "outlook" => crate::providers::imap::call("imap.attachment", ¶ms).await?, + _ => return Err("attachment_provider_unsupported"), + }; + let (a, m, p, saved) = ( + account.to_owned(), + id.to_owned(), + part.to_owned(), + value.clone(), + ); + tokio::task::spawn_blocking(move || vault::cache(&a, &m, &p, &saved)) + .await + .map_err(|_| "worker_failed")??; + Ok(value) + } + pub(super) async fn attachment_request( + &self, + method: &str, + params: &Value, + ) -> Result { + let allowed: &[&str] = match method { + "attachment.import" => &["accountId", "draftKey", "path"], + "attachment.preview" => &[ + "accountId", + "messageId", + "attachmentId", + "filename", + "mimeType", + ], + "attachment.download" => &[ + "accountId", + "messageId", + "attachmentId", + "filename", + "mimeType", + "open", + ], + "attachment.retain" => &[ + "accountId", + "messageId", + "attachmentId", + "filename", + "mimeType", + "draftKey", + ], + _ => return Err("unknown_method"), + }; + if params + .as_object() + .is_none_or(|p| p.keys().any(|key| !allowed.contains(&key.as_str()))) + { + return Err("invalid_params"); + } + if method == "attachment.download" && !params["open"].is_boolean() { + return Err("invalid_params"); + } + if method == "attachment.retain" + && params["draftKey"] + .as_str() + .is_none_or(|v| v.is_empty() || v.len() > 4096 || v.chars().any(char::is_control)) + { + return Err("invalid_params"); + } + let account = params["accountId"] + .as_str() + .ok_or("invalid_params")? + .to_owned(); + super::reader::registered(&account).await?; + if method == "attachment.import" { + let params = params.clone(); + return tokio::task::spawn_blocking(move || vault::import(¶ms)) + .await + .map_err(|_| "worker_failed")?; + } + let id = params["messageId"].as_str().ok_or("invalid_params")?; + let part = params["attachmentId"].as_str().ok_or("invalid_params")?; + let mut value = self.attachment_data(&account, id, part).await?; + value["filename"] = params["filename"].clone(); + value["mimeType"] = params["mimeType"].clone(); + match method { + "attachment.preview" => { + attachment::thumbnail::prepare( + &json!({"data":value["data"],"mimeType":value["mimeType"]}), + ) + .await + } + "attachment.download" => { + value["open"] = json!(params["open"].as_bool().ok_or("invalid_params")?); + tokio::task::spawn_blocking(move || { + let bytes = attachment::decode( + value["data"].as_str().ok_or("attachment_data_invalid")?, + )?; + attachment::store(&value, &bytes) + }) + .await + .map_err(|_| "worker_failed")? + } + "attachment.retain" => { + let draft = params["draftKey"] + .as_str() + .filter(|s| !s.is_empty() && s.len() < 4096 && !s.chars().any(char::is_control)) + .ok_or("invalid_params")? + .to_owned(); + tokio::task::spawn_blocking(move || vault::retain(&account, &draft, &value)) + .await + .map_err(|_| "worker_failed")? + } + _ => Err("unknown_method"), + } + } +} diff --git a/src/backend/diagnostics.rs b/src/backend/diagnostics.rs new file mode 100644 index 000000000..aae667532 --- /dev/null +++ b/src/backend/diagnostics.rs @@ -0,0 +1,227 @@ +use serde::{Deserialize, Serialize}; +use std::{ + collections::VecDeque, + io::Read, + sync::{ + OnceLock, + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::{Duration, Instant}, +}; + +const CAPACITY: usize = 512; +static WRITER: OnceLock> = OnceLock::new(); +static SERIAL: AtomicU64 = AtomicU64::new(1); +static DROPPED: AtomicU64 = AtomicU64::new(0); +tokio::task_local! {pub(crate) static CORRELATION:u64;} +pub(crate) fn next() -> u64 { + SERIAL.fetch_add(1, Ordering::Relaxed) +} +pub(crate) fn current() -> u64 { + CORRELATION.try_with(|value| *value).unwrap_or(0) +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct Event { + #[serde(default)] + time_ms: u64, + process: u32, + request: u64, + method: String, + queue_us: u64, + elapsed_us: u64, + request_bytes: usize, + success: bool, + #[serde(default)] + error: Option, +} + +fn error_code(error: &str) -> &str { + match error { + "invalid_params" + | "unknown_method" + | "request_timed_out" + | "local_account_unknown" + | "local_disk_full" + | "local_disk_low" + | "local_storage_corrupt" + | "local_storage_unavailable" + | "local_schema_newer" + | "local_sqlite_update_required" + | "local_owner_unavailable" + | "local_edit_id_conflict" + | "local_edit_already_started" + | "cache_unsafe_path" + | "cache_unavailable" + | "private_fs_busy" + | "auth_signed_out" + | "gmail_rate_limited" + | "gmail_timeout" => error, + _ => "unknown_error", + } +} +enum Command { + Event(Event), + Flush(mpsc::SyncSender<()>), +} +fn valid(event: &Event) -> bool { + super::methods::ALL.contains(&event.method.as_str()) + && event + .error + .as_deref() + .is_none_or(|error| error_code(error) == error) +} +pub(super) fn record( + request: u64, + method: &str, + queue_us: u64, + elapsed: Duration, + request_bytes: usize, + error: Option<&str>, +) { + let event = Event { + time_ms: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64, + process: std::process::id(), + request, + method: method.into(), + queue_us, + elapsed_us: elapsed.as_micros().min(u64::MAX as u128) as u64, + request_bytes, + success: error.is_none(), + error: error.map(|error| error_code(error).to_owned()), + }; + if !valid(&event) { + return; + } + #[cfg(test)] + return; + #[allow(unreachable_code)] + let writer = WRITER.get_or_init(|| { + let (sender, receiver) = mpsc::sync_channel(CAPACITY); + let _ = std::thread::Builder::new() + .name("rpc-diagnostics".into()) + .spawn(move || { + let mut pending = Vec::new(); + let mut deadline = Instant::now() + Duration::from_secs(2); + loop { + match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) + { + Ok(Command::Event(event)) => pending.push(event), + Ok(Command::Flush(done)) => { + persist(&mut pending); + let _ = done.send(()); + } + Err(mpsc::RecvTimeoutError::Timeout) => (), + Err(mpsc::RecvTimeoutError::Disconnected) => { + persist(&mut pending); + break; + } + } + if pending.len() >= 64 || Instant::now() >= deadline { + persist(&mut pending); + deadline = Instant::now() + Duration::from_secs(2); + } + } + }); + sender + }); + if writer.try_send(Command::Event(event)).is_err() { + DROPPED.fetch_add(1, Ordering::Relaxed); + } +} +fn persist(batch: &mut Vec) { + use crate::platform::{dirs::AppDirs, private_fs as fs}; + if batch.is_empty() { + return; + } + let pending = std::mem::take(batch); + let count = pending.len() as u64; + let write = || -> Result<(), &'static str> { + let dirs = AppDirs::discover()?; + let dir = fs::directories(&dirs.state, &["omamail", "diagnostics"], true)? + .ok_or("cache_unavailable")?; + let _lock = fs::lock_exclusive(&dir, ".rpc.lock")?; + let mut events = VecDeque::new(); + if let Some(file) = fs::regular(&dir, "rpc.json", false)? { + let mut bytes = Vec::new(); + file.take(131073) + .read_to_end(&mut bytes) + .map_err(|_| "cache_unavailable")?; + if bytes.len() <= 131072 { + events = serde_json::from_slice(&bytes).unwrap_or_default(); + } + } + events.retain(valid); + events.extend(pending); + while events.len() > 256 { + events.pop_front(); + } + let bytes = serde_json::to_vec(&events).map_err(|_| "cache_unavailable")?; + fs::atomic_replace(&dir, "rpc.json", &bytes)?; + fs::atomic_replace( + &dir, + "rpc-writer.json", + serde_json::json!({"dropped":DROPPED.load(Ordering::Relaxed)}) + .to_string() + .as_bytes(), + ) + }; + if write().is_err() { + DROPPED.fetch_add(count, Ordering::Relaxed); + } +} +pub(super) async fn flush() { + let Some(writer) = WRITER.get() else { return }; + let writer = writer.clone(); + let _ = tokio::time::timeout( + Duration::from_secs(3), + tokio::task::spawn_blocking(move || { + let (sender, receiver) = mpsc::sync_channel(1); + if writer.try_send(Command::Flush(sender)).is_ok() { + let _ = receiver.recv_timeout(Duration::from_secs(2)); + } + }), + ) + .await; +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn records_have_no_caller_supplied_content_and_a_full_queue_never_waits() { + let event = Event { + time_ms: 1, + process: 1, + request: 1, + method: "reader.open".into(), + queue_us: 0, + elapsed_us: 1, + request_bytes: 1, + success: true, + error: None, + }; + let value = serde_json::to_value(&event).unwrap(); + assert_eq!(value.as_object().unwrap().len(), 9); + assert_eq!(error_code("local_disk_full"), "local_disk_full"); + assert_eq!( + error_code("secret@example.org\nBearer private"), + "unknown_error" + ); + assert!(valid(&event)); + assert!(!valid(&Event { + method: "secret@example.org".into(), + ..event + })); + let (sender, _receiver) = mpsc::sync_channel(1); + sender.try_send(1).unwrap(); + assert!(matches!( + sender.try_send(2), + Err(mpsc::TrySendError::Full(2)) + )); + } +} diff --git a/src/backend/methods.rs b/src/backend/methods.rs index 3f53730d9..404e72507 100644 --- a/src/backend/methods.rs +++ b/src/backend/methods.rs @@ -188,6 +188,27 @@ pub const ALL: &[&str] = &[ "jmap.stream.open", "jmap.stream.poll", "jmap.stream.close", + "reader.prefetch", + "local.list", + "local.status", + "local.overview", + "local.edits", + "local.edit", + "local.pause", + "local.cancelEdit", + "local.dismissConflict", + "local.watch", + "local.unwatch", + "local.refresh", + "attachment.import", + "attachment.preview", + "attachment.download", + "attachment.retain", + "outbox.compose", + "draft.compose", + "calendar.read", + "calendar.parse", + "local.labelCounts", ]; pub fn available() -> Vec<&'static str> { diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 2bf0a7f8f..9e5fc3bad 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1,4 +1,6 @@ +mod attachments; mod content; +pub(crate) mod diagnostics; pub(crate) mod mail; mod methods; pub mod protocol; @@ -9,6 +11,9 @@ pub mod upload; use crate::{account, message}; pub struct Session { + calendar_reads: crate::calendar::reads::Reads, + local_mail: crate::local_mail::LocalMail, + reader_prefetch: tokio::sync::Semaphore, inbox: crate::inbox::Inbox, uploads: std::sync::Mutex, reader: std::sync::Arc>, @@ -36,8 +41,31 @@ impl Default for Session { let jmap = sender_jmap.clone(); Box::pin(async move { crate::outbox::delivery::send(&job, &gmail, &jmap).await }) })); + let check_gmail = gmail.clone(); + let check_jmap = jmap.clone(); + let outbox=outbox.with_readiness(std::sync::Arc::new(move|account,provider| { + let gmail=check_gmail.clone(); + let jmap=check_jmap.clone(); + Box::pin(async move { + let params=serde_json::json!({"accountId":account}); + match provider.as_str() { + "gmail"=>{gmail.call("gmail.profile",¶ms).await?;} + "jmap"=>{jmap.call("jmap.profile",¶ms).await?;} + "imap"|"outlook"=>{crate::providers::imap::call("imap.check",¶ms).await?;} + "hey"=>{ + let checked=crate::providers::hey_access::checked_params(&serde_json::json!({"accountId":account,"program":crate::providers::hey_access::program()?})).await?; + crate::providers::hey::call("hey.profile",&checked).await?; + } + _=>return Err("outbox_invalid_provider"), + } + Ok(()) + }) + })); let queries = std::sync::Arc::new(crate::cache::query::QueryCache::default()); Self { + calendar_reads: crate::calendar::reads::Reads::default(), + local_mail: Default::default(), + reader_prefetch: tokio::sync::Semaphore::new(1), inbox: Default::default(), uploads: Default::default(), reader: Default::default(), @@ -61,6 +89,27 @@ impl Session { // re-enter this dispatcher; embedding every provider future here overflowed // the worker stack in the real Quickshell large-request integration test. pub async fn dispatch(&self, method: &str, params: &Value) -> Result { + if matches!(method, "local.watch" | "local.unwatch" | "local.refresh") { + if params.as_object().is_none_or(|p| p.len() != 1) { + return Err("invalid_params"); + } + let account = params["accountId"].as_str().ok_or("invalid_params")?; + if reader::registered(account).await? != "gmail" { + return Err("local_account_unknown"); + } + if method == "local.unwatch" { + self.local_mail.stop(account); + return Ok(json!({"unwatched":true})); + } + self.local_mail.start(account, self.gmail.clone()).await?; + if method == "local.refresh" { + self.local_mail.refresh(account).await?; + } + return self.local_mail.call("local.overview", params).await; + } + if method.starts_with("local.") { + return self.local_mail.call(method, params).await; + } #[cfg(not(all(feature = "agent", unix)))] if method.starts_with("agent.") { return Err("unknown_method"); @@ -77,7 +126,10 @@ impl Session { if method.starts_with("credentials.") { return crate::credentials::rpc::call(method, params).await; } - if matches!(method, "reader.open" | "reader.render" | "reader.cancel") { + if matches!( + method, + "reader.open" | "reader.render" | "reader.cancel" | "reader.prefetch" + ) { return Box::pin(self.reader_call(method, params)).await; } #[cfg(all(feature = "agent", unix))] @@ -119,6 +171,126 @@ impl Session { ) { return Box::pin(crate::agent::jobs::call(method, params)).await; } + if method == "draft.compose" { + if params.as_object().is_none_or(|p| { + p.keys() + .any(|key| !["accountId", "fields"].contains(&key.as_str())) + }) { + return Err("invalid_params"); + } + let account = params["accountId"] + .as_str() + .ok_or("invalid_params")? + .to_owned(); + let provider = reader::registered(&account).await?; + let mut fields = params["fields"].clone(); + if !fields.is_object() { + return Err("invalid_params"); + } + let draft = fields["draftId"].as_str().unwrap_or("").to_owned(); + let owner = account.clone(); + let mut payload = tokio::task::spawn_blocking(move || { + crate::attachment::vault::hydrate(&owner, &mut fields)?; + crate::message::compose::build(&fields) + }) + .await + .map_err(|_| "worker_failed")??; + payload["accountId"] = json!(account); + return match provider.as_str() { + "gmail" => { + let mut gmail = json!({"accountId":account,"raw":payload["raw"]}); + if let Some(thread) = payload.get("threadId") { + gmail["threadId"] = thread.clone(); + } + if !draft.is_empty() { + gmail["id"] = json!(draft); + } + self.gmail + .call_settled( + if draft.is_empty() { + "gmail.saveDraft" + } else { + "gmail.updateDraft" + }, + &gmail, + ) + .await + } + "jmap" => { + payload["draftId"] = json!(draft); + self.jmap.call("jmap.saveDraft", &payload).await + } + "imap" | "outlook" => { + crate::providers::imap::call( + "imap.saveDraft", + &json!({"accountId":account,"raw":payload["raw"],"draftId":draft}), + ) + .await + } + _ => Err("attachment_provider_unsupported"), + }; + } + if method == "outbox.compose" { + let allowed = [ + "accountId", + "provider", + "fields", + "sendId", + "order", + "delaySeconds", + "resumeUnsent", + ]; + if params + .as_object() + .is_none_or(|p| p.keys().any(|key| !allowed.contains(&key.as_str()))) + || !params["fields"].is_object() + { + return Err("invalid_params"); + } + let account = params["accountId"] + .as_str() + .ok_or("invalid_params")? + .to_owned(); + let provider = params["provider"] + .as_str() + .ok_or("invalid_params")? + .to_owned(); + let accounts = tokio::task::spawn_blocking(crate::account::list_readonly) + .await + .map_err(|_| "worker_failed")??; + if !accounts["accounts"] + .as_array() + .into_iter() + .flatten() + .any(|row| row["id"] == account && row["provider"] == provider) + { + return Err("outbox_account_unavailable"); + } + let mut fields = params["fields"].clone(); + let draft = fields["draftId"].as_str().unwrap_or("").to_owned(); + let stamp = params["order"].as_u64().ok_or("invalid_params")?; + let seed = params["sendId"] + .as_str() + .filter(|v| !v.is_empty() && v.len() <= 1024 && !v.chars().any(char::is_control)) + .ok_or("invalid_params")? + .to_owned(); + let owner = account.clone(); + let mut payload = tokio::task::spawn_blocking(move || { + crate::attachment::vault::hydrate(&owner, &mut fields)?; + crate::message::compose::submission(&fields, stamp, &seed) + }) + .await + .map_err(|_| "worker_failed")??; + payload["draftId"] = json!(draft); + payload["sendId"] = params["sendId"].clone(); + let mut queued = params.clone(); + queued + .as_object_mut() + .ok_or("invalid_params")? + .remove("fields"); + queued["payload"] = payload; + return Box::pin(self.outbox.call("outbox.enqueue", &queued)).await; + } if method.starts_with("outbox.") { return Box::pin(self.outbox.call(method, params)).await; } @@ -210,7 +382,9 @@ impl Session { let value = Box::pin(self.auth.call(method, params)).await?; if method == "auth.poll" { if let Some(account) = value["profile"]["emailAddress"].as_str() { - self.gmail.call("gmail.invalidate", &json!({"accountId":account})).await?; + self.gmail + .call("gmail.invalidate", &json!({"accountId":account})) + .await?; } } return Ok(value); @@ -227,6 +401,15 @@ impl Session { if method == "outlook.connectionCheck" { return Box::pin(crate::providers::outlook::connection_check(params)).await; } + if matches!( + method, + "attachment.import" + | "attachment.preview" + | "attachment.download" + | "attachment.retain" + ) { + return self.attachment_request(method, params).await; + } if method == "attachment.thumbnail" { return crate::attachment::thumbnail::prepare(params).await; } @@ -292,7 +475,19 @@ impl Session { return Box::pin(self.gmail.call(method, params)).await; } if method.starts_with("mail.") { - return Box::pin(self.mail.call(method, params)).await; + let result = Box::pin(self.mail.call(method, params)).await?; + if let Some(account) = params["accountId"] + .as_str() + .filter(|id| id.contains('@') && !id.contains(':')) + { + if method == "mail.watch" { + let _ = self.local_mail.start(account, self.gmail.clone()).await; + } + if method == "mail.unwatch" { + self.local_mail.stop(account); + } + } + return Ok(result); } if method == "request.upload" { let fields = params.as_object().ok_or("invalid_params")?; @@ -323,6 +518,37 @@ impl Session { let params: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid_params")?; return Box::pin(self.dispatch(target, ¶ms)).await; } + if method == "calendar.parse" { + let params = params.clone(); + return tokio::task::spawn_blocking(move || crate::calendar::parse::parse(¶ms)) + .await + .map_err(|_| "worker_failed")?; + } + if method == "calendar.read" { + if params["operation"] != "list" { + return Err("invalid_params"); + } + crate::calendar::validate(params)?; + if matches!( + params["source"]["kind"].as_str(), + Some("google" | "microsoft" | "icloud") + ) { + reader::registered( + params["source"]["accountId"] + .as_str() + .ok_or("invalid_params")?, + ) + .await?; + } + return self.calendar_reads.get(params,||async { + let response=Box::pin(self.dispatch("calendar.request",params)).await?; + let parse=serde_json::json!({"kind":params["source"]["kind"],"sourceId":params["source"]["id"], + "body":response["body"], + "startMs":chrono::DateTime::parse_from_rfc3339(params["start"].as_str().ok_or("invalid_params")?).map_err(|_|"invalid_params")?.timestamp_millis(), + "endMs":chrono::DateTime::parse_from_rfc3339(params["end"].as_str().ok_or("invalid_params")?).map_err(|_|"invalid_params")?.timestamp_millis()}); + tokio::task::spawn_blocking(move||crate::calendar::parse::parse(&parse)).await.map_err(|_|"worker_failed")? + }).await; + } if method == "calendar.request" { crate::calendar::validate(params)?; let token = match params["source"]["kind"].as_str() { @@ -348,7 +574,14 @@ impl Session { Some("caldav") => None, _ => None, }; - return Box::pin(crate::calendar::call(params, token.as_deref())).await; + let answer = Box::pin(crate::calendar::call(params, token.as_deref())).await; + if !matches!( + params["operation"].as_str(), + Some("list" | "get" | "lookup" | "instances") + ) { + self.calendar_reads.invalidate(); + } + return answer; } if method == "calendar.attendance" { crate::calendar::attendance::validate(params)?; @@ -481,6 +714,7 @@ pub(crate) fn runtime() -> std::io::Result { } use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; /// Both frontends use this dispatcher. Add domain operations here, never in CLI parsing. pub fn dispatch(method: &str, params: &Value) -> Result { @@ -494,6 +728,7 @@ pub fn dispatch(method: &str, params: &Value) -> Result { "system.info" => Ok(json!({ "name": "omamail", "version": env!("CARGO_PKG_VERSION"), "protocol": 1, "apiVersion": 8, "methods": methods::available(), + "contractHash": format!("{:x}", Sha256::digest(include_bytes!("../../backend-api.json"))), "capabilities": {"agent": cfg!(all(feature = "agent", unix))} })), "system.quit" => Ok(json!({"quitReady": true})), diff --git a/src/backend/protocol.rs b/src/backend/protocol.rs index 9067e6fe8..596893f1f 100644 --- a/src/backend/protocol.rs +++ b/src/backend/protocol.rs @@ -80,6 +80,7 @@ async fn process_frames( let mut notifications = session.mail.subscribe(); let mut outbox_notifications = session.outbox.subscribe(); let mut gmail_notifications = session.gmail.subscribe(); + let mut local_notifications = session.local_mail.subscribe(); let scheduler = schedule(receiver, responses.clone(), |frame| async move { super::rpc::handle(&frame.bytes, session, frame.deadline) .await @@ -89,6 +90,12 @@ async fn process_frames( let result = loop { tokio::select! { result = &mut scheduler => break result, + event = local_notifications.recv() => { + if let Ok(event) = event + && responses.send(event).await.is_err() { + break Err(io::Error::other("output closed")); + } + } event = outbox_notifications.recv() => { if let Ok(event) = event && responses.send(event).await.is_err() { @@ -112,7 +119,10 @@ async fn process_frames( }; // No watch can write after the accepted requests drain or after quit. session.mail.shutdown().await; + session.local_mail.shutdown().await; session.gmail.shutdown(); + crate::providers::gmail_http::flush_diagnostics().await; + super::diagnostics::flush().await; let outbox_result = session.outbox.shutdown().await; let cache_result = session.queries.shutdown().await; outbox_result.map_err(io::Error::other)?; diff --git a/src/backend/reader.rs b/src/backend/reader.rs index d8814fd9a..62ac2b4ab 100644 --- a/src/backend/reader.rs +++ b/src/backend/reader.rs @@ -28,6 +28,7 @@ struct Entry { key: String, prepared: Arc, bytes: usize, + revision: String, } struct Prepared { source: String, @@ -63,18 +64,35 @@ impl Job { } } impl ReaderStore { + #[cfg(test)] fn put( &mut self, account: &str, id: &str, prepared: Arc, ) -> Result { + self.put_revision(account, id, prepared, "") + } + fn put_revision( + &mut self, + account: &str, + id: &str, + prepared: Arc, + revision: &str, + ) -> Result { + for index in (0..self.entries.len()).rev() { + if self.entries[index].account == account && self.entries[index].id == id { + if let Some(old) = self.entries.remove(index) { + self.bytes -= old.bytes; + } + } + } let bytes = prepared.bytes()?; if bytes > MAX_BYTES { return Err("reader_resource_too_large"); } while self.bytes + bytes > MAX_BYTES - || self.entries.len() >= 64 + || self.entries.len() >= 32 || self.entries.iter().filter(|v| v.account == account).count() >= 12 { let at = self @@ -97,9 +115,25 @@ impl ReaderStore { key: key.clone(), prepared, bytes, + revision: revision.into(), }); Ok(key) } + fn prepared( + &mut self, + account: &str, + id: &str, + revision: &str, + ) -> Option<(String, Arc)> { + let index = self + .entries + .iter() + .position(|e| e.account == account && e.id == id && e.revision == revision)?; + let entry = self.entries.remove(index)?; + let value = (entry.key.clone(), entry.prepared.clone()); + self.entries.push_back(entry); + Some(value) + } fn get(&mut self, account: &str, id: &str, key: &str) -> Result, &'static str> { let at = self .entries @@ -133,7 +167,7 @@ fn field<'a>(p: &'a Value, key: &str) -> Result<&'a str, &'static str> { .filter(|s| !s.is_empty() && s.len() <= 4096 && !s.chars().any(char::is_control)) .ok_or("invalid_params") } -async fn registered(account: &str) -> Result { +pub(super) async fn registered(account: &str) -> Result { let list = tokio::task::spawn_blocking(crate::account::list_readonly) .await .map_err(|_| "worker_failed")??; @@ -154,14 +188,7 @@ impl Session { cache::validate_params(&json!({"accountId":account,"id":id}), true)?; let provider = registered(account).await?; let value = match provider.as_str() { - "gmail" => { - self.gmail - .call( - "gmail.read", - &json!({"accountId":account,"id":id,"full":true}), - ) - .await? - } + "gmail" => self.local_mail.read(account, id, &self.gmail).await?, "jmap" => self .jmap .call( @@ -203,6 +230,32 @@ impl Session { params: &Value, ) -> Result { let account = field(params, "accountId")?.to_lowercase(); + if method == "reader.prefetch" { + let ids = params["ids"] + .as_array() + .filter(|ids| ids.len() <= 4) + .ok_or("invalid_params")?; + let now = params["now"].as_i64().ok_or("invalid_params")?; + let options = params["options"].as_object().ok_or("invalid_params")?; + if options.get("allowRemoteImages") == Some(&Value::Bool(true)) { + return Err("invalid_params"); + } + for id in ids { + cache::validate_params(&json!({"accountId":account,"id":id}), true)?; + } + let Ok(_permit) = self.reader_prefetch.try_acquire() else { + return Ok(json!({"warmed":0})); + }; + let mut warmed = 0; + for (index, id) in ids.iter().enumerate() { + let result=Box::pin(self.reader_call("reader.open",&json!({"accountId":account,"id":id, + "requestId":format!("prefetch-{now}-{index}"),"cacheOnly":true,"now":now,"options":options}))).await; + if result.is_ok_and(|v| !v.is_null()) { + warmed += 1; + } + } + return Ok(json!({"warmed":warmed})); + } if method == "reader.cancel" { let request = field(params, "requestId")?; let mut store = self.reader.lock().map_err(|_| "session_failed")?; @@ -292,10 +345,51 @@ impl Session { live: job.live.clone(), }; let operation = async { - registered(&account).await?; + let provider = registered(&account).await?; job.current()?; + let revision = if provider == "gmail" { + self.local_mail.revision(&account, &id).await? + } else { + None + }; + if let Some(revision) = revision.as_deref() { + let prepared = self + .reader + .lock() + .map_err(|_| "session_failed")? + .prepared(&account, &id, revision); + if let Some((key, prepared)) = prepared { + let renders = self.renders.clone(); + let account = account.clone(); + let id = id.clone(); + let job = job.clone(); + return tokio::task::spawn_blocking(move || { + job.current()?; + render_prepared( + &prepared, + &account, + &id, + &key, + options, + &renders, + Some(&job.live), + ) + }) + .await + .map_err(|_| "worker_failed")?; + } + } let resource = if cache_only { - cache::resource::read(&account, &id).await? + if provider == "gmail" { + match self.local_mail.resource(&account, &id).await? { + Some(resource) => Some(resource), + None => cache::resource::read(&account, &id) + .await? + .filter(crate::local_mail::text_complete), + } + } else { + cache::resource::read(&account, &id).await? + } } else { Some(self.fetch_resource(&account, &id).await?) }; @@ -303,7 +397,7 @@ impl Session { let Some(resource) = resource else { return Ok(Value::Null); }; - if !cache_only { + if !cache_only && provider != "gmail" { // Persistence failure does not discard a valid live read. Guarded // writes cannot land after an explicit reader cancellation. let _ = @@ -321,7 +415,12 @@ impl Session { if !*live_guard { return Err("reader_cancelled"); } - let key = store_guard.put(&account, &id, prepared.clone())?; + let key = store_guard.put_revision( + &account, + &id, + prepared.clone(), + revision.as_deref().unwrap_or(""), + )?; drop(live_guard); drop(store_guard); let result = render_prepared( diff --git a/src/backend/rpc.rs b/src/backend/rpc.rs index df9f6eb68..1f49d0a16 100644 --- a/src/backend/rpc.rs +++ b/src/backend/rpc.rs @@ -110,23 +110,44 @@ async fn one( } // An expired queued request must not start a side effect: timeout_at polls // its future before checking the clock. - let result = if tokio::time::Instant::now() >= deadline { - Err("request_timed_out") - } else if request.method.starts_with("gmail.") - || (request.method == "request.upload" - && request.params["method"] - .as_str() - .is_some_and(|method| method.starts_with("gmail."))) - { - tokio::time::timeout_at(deadline, session.dispatch(&request.method, &request.params)) - .await - .unwrap_or(Err("request_timed_out")) - } else { - // Legacy process operations have their own deadlines. Dropping a - // spawn_blocking join cannot cancel a running send; await it so quit - // remains a completion barrier and never reports a false cancellation. - session.dispatch(&request.method, &request.params).await - }; + let began = std::time::Instant::now(); + let request_number = super::diagnostics::next(); + let queued = tokio::time::Instant::now() + .saturating_duration_since(deadline - std::time::Duration::from_secs(25)) + .as_micros() + .min(u64::MAX as u128) as u64; + let result = super::diagnostics::CORRELATION + .scope(request_number, async { + if tokio::time::Instant::now() >= deadline { + Err("request_timed_out") + } else if request.method.starts_with("gmail.") + || (request.method == "request.upload" + && request.params["method"] + .as_str() + .is_some_and(|method| method.starts_with("gmail."))) + { + tokio::time::timeout_at( + deadline, + session.dispatch(&request.method, &request.params), + ) + .await + .unwrap_or(Err("request_timed_out")) + } else { + // Legacy process operations have their own deadlines. Dropping a + // spawn_blocking join cannot cancel a running send; await it so quit + // remains a completion barrier and never reports a false cancellation. + session.dispatch(&request.method, &request.params).await + } + }) + .await; + super::diagnostics::record( + request_number, + &request.method, + queued, + began.elapsed(), + raw.len(), + result.as_ref().err().copied(), + ); let quit = request.method == "system.quit" && result.is_ok(); let Id::Present(id) = request.id else { return (None, quit); diff --git a/src/cache/render.rs b/src/cache/render.rs index 9d7efa242..c6ae33b15 100644 --- a/src/cache/render.rs +++ b/src/cache/render.rs @@ -4,7 +4,7 @@ use serde_json::Value; use std::collections::VecDeque; const MAX_BYTES: usize = 64 * 1024 * 1024; const MAX_PER_ACCOUNT: usize = 12; -const MAX_ENTRIES: usize = 96; +const MAX_ENTRIES: usize = 32; #[derive(Default)] pub struct RenderCache { entries: VecDeque, diff --git a/src/cache/resource.rs b/src/cache/resource.rs index 2ec8bc8dc..2196fe575 100644 --- a/src/cache/resource.rs +++ b/src/cache/resource.rs @@ -3,6 +3,53 @@ use super::*; use std::sync::Arc; +pub(crate) async fn legacy_next( + account: &str, + cursor: &str, +) -> Result)>> { + let account = account.to_owned(); + let cursor = cursor.to_owned(); + tokio::task::spawn_blocking(move || { + let root = cache_home()?; + let name = account_name(&account)?; + let Some(dir) = directories(&root, &["omamail", "resources", &name], false)? else { + return Ok(None); + }; + let mut names = entries(&dir)? + .into_iter() + .map(|(_, name)| name) + .filter(|name| name > &cursor) + .collect::>(); + names.sort(); + let Some(name) = names.into_iter().next() else { + return Ok(None); + }; + let mut value = None; + if let Some(file) = regular(&dir, &name, false)? { + let mut bytes = Vec::new(); + file.take(MAX_BODY as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "cache_unavailable")?; + if bytes.len() <= MAX_BODY { + if let Ok(record) = serde_json::from_slice::(&bytes) { + let resource = &record["resource"]; + let id = resource["id"].as_str().unwrap_or(""); + if record["version"] == 1 + && record["accountId"] == account.to_lowercase() + && valid(resource, id) + && body_name(id)? == name + { + value = Some(resource.clone()); + } + } + } + } + Ok(Some((name, value))) + }) + .await + .map_err(|_| "cache_unavailable")? +} + pub async fn read(account: &str, id: &str) -> Result> { let params = json!({"accountId":account,"id":id}); let value = tokio::task::spawn_blocking(move || call("cache.resourceRead", ¶ms)) diff --git a/src/cache/store.rs b/src/cache/store.rs index 154505574..98ddcdb6e 100644 --- a/src/cache/store.rs +++ b/src/cache/store.rs @@ -50,7 +50,10 @@ pub(super) fn call_at(root: &Path, method: &str, params: &Value) -> Result Value { .unwrap_or(0.0) .total_cmp(&a.1["at"].as_f64().unwrap_or(0.0)) }); - for (key, entry) in entries.into_iter().take(8) { + for (key, entry) in entries.into_iter().take(32) { let mut entry = entry.clone(); if !entry.is_object() { continue; @@ -118,9 +121,15 @@ fn normalize_calendar(value: &Value) -> Value { entry["events"] = json!( entry["events"] .as_array() - .map(|v| v.iter().take(2500).cloned().collect::>()) + .map(|v| v.iter().take(25000).cloned().collect::>()) .unwrap_or_default() ); + if value["ranges"][key]["events"] + .as_array() + .is_some_and(|v| v.len() > 25000) + { + entry["sources"] = json!([]); + } out["ranges"][key] = entry; } } diff --git a/src/calendar/mod.rs b/src/calendar/mod.rs index 4bf97d0a0..1f93fc4fb 100644 --- a/src/calendar/mod.rs +++ b/src/calendar/mod.rs @@ -5,6 +5,8 @@ use std::{sync::OnceLock, time::Duration}; pub mod attendance; mod discovery; +pub(crate) mod parse; +pub(crate) mod reads; pub mod reminders; pub use discovery::discover; pub use discovery::google as discover_google; diff --git a/src/calendar/parse/dates.rs b/src/calendar/parse/dates.rs new file mode 100644 index 000000000..5ed678827 --- /dev/null +++ b/src/calendar/parse/dates.rs @@ -0,0 +1,262 @@ +use super::ics::{Component, Property}; +use chrono::{Datelike, Local, NaiveDate, NaiveDateTime, TimeZone}; +use serde_json::{Value, json}; +use std::collections::HashMap; + +pub(super) fn rules(text: &str) -> HashMap { + text.split(';') + .filter_map(|s| s.split_once('=')) + .map(|(k, v)| (k.trim().to_uppercase(), v.trim().to_owned())) + .collect() +} +pub(super) fn date(text: &str) -> Option { + let text = text.trim().trim_end_matches('Z'); + if text.len() == 8 { + NaiveDate::parse_from_str(text, "%Y%m%d") + .ok()? + .and_hms_opt(0, 0, 0) + } else { + NaiveDateTime::parse_from_str(text, "%Y%m%dT%H%M%S").ok() + } +} +pub(super) fn local(date: NaiveDateTime) -> Option { + Local + .from_local_datetime(&date) + .earliest() + .map(|d| d.timestamp_millis()) +} +fn offset(text: &str) -> Option { + if !matches!(text.len(), 5 | 7) || !text.is_ascii() { + return None; + } + let sign = match &text[..1] { + "+" => 1, + "-" => -1, + _ => return None, + }; + Some(sign * (text[1..3].parse::().ok()? * 60 + text[3..5].parse::().ok()?)) +} +pub(super) fn month_days(year: i32, month: u32) -> u32 { + (28..=31) + .rev() + .find(|&day| NaiveDate::from_ymd_opt(year, month, day).is_some()) + .unwrap_or(0) +} +pub(super) fn weekday(text: &str) -> Option<(i32, u32)> { + if text.len() < 2 || !text.is_ascii() { + return None; + } + let at = text.len() - 2; + let day = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"] + .iter() + .position(|v| *v == &text[at..])? as u32; + let ordinal = if at == 0 { 0 } else { text[..at].parse().ok()? }; + Some((ordinal, day)) +} +fn transition(rule: &Component, year: i32) -> Option { + let start = date(rule.text("DTSTART"))?; + let parts = rules(rule.text("RRULE")); + if parts.get("FREQ").map(String::as_str) != Some("YEARLY") { + return None; + } + let month = parts + .get("BYMONTH") + .and_then(|s| s.parse().ok()) + .unwrap_or(start.month()); + let total = month_days(year, month); + let day = if let Some(by) = parts.get("BYDAY") { + let (ordinal, day) = weekday(by.split(',').next()?)?; + let choices: Vec<_> = (1..=total) + .filter(|d| { + NaiveDate::from_ymd_opt(year, month, *d) + .is_some_and(|d| d.weekday().num_days_from_sunday() == day) + }) + .collect(); + let index = if ordinal < 0 { + choices.len() as i32 + ordinal + } else { + ordinal.max(1) - 1 + }; + *choices.get(usize::try_from(index).ok()?)? + } else if let Some(by) = parts.get("BYMONTHDAY") { + let d = by.split(',').next()?.parse::().ok()?; + if d < 0 { + (total as i32 + d + 1) as u32 + } else { + d as u32 + } + } else { + start.day() + }; + let found = NaiveDate::from_ymd_opt(year, month, day)? + .and_time(start.time()) + .and_utc() + .timestamp_millis(); + if let Some(until) = parts.get("UNTIL") { + let limit = date(until)?.and_utc().timestamp_millis() + + if until.len() == 8 { 86_399_999 } else { 0 }; + let reading = found + - if until.ends_with('Z') { + offset(rule.text("TZOFFSETFROM")).unwrap_or(0) * 60_000 + } else { + 0 + }; + if reading > limit { + return None; + } + } + Some(found) +} +fn dated(rule: &Component) -> Vec { + std::iter::once(rule.text("DTSTART")) + .chain( + rule.properties + .iter() + .filter(|p| p.name == "RDATE") + .map(|p| p.value.as_str()), + ) + .flat_map(|s| s.split(',')) + .filter_map(date) + .collect() +} +pub(super) fn zone(calendar: &Component, tzid: &str, reading: NaiveDateTime) -> Option { + let zone = calendar + .children + .iter() + .find(|c| c.name == "VTIMEZONE" && c.text("TZID") == tzid)?; + let ordered: Vec<_> = ["STANDARD", "DAYLIGHT"] + .iter() + .flat_map(|kind| zone.children.iter().filter(move |c| c.name == *kind)) + .filter_map(|c| Some((c, offset(c.text("TZOFFSETTO"))?))) + .collect(); + if ordered.len() == 1 { + return Some(ordered[0].1); + } + let history = ordered.len() > 2 + || ordered + .iter() + .any(|(r, _)| r.text("RRULE").contains("UNTIL=") || r.property("RDATE").is_some()); + let mut candidates = Vec::new(); + let year = reading.year(); + for (rule, to) in &ordered { + if rule.property("RRULE").is_some() { + let mut years = vec![year - 1, year]; + if history { + if let Some(last) = rules(rule.text("RRULE")) + .get("UNTIL") + .and_then(|s| date(s)) + .map(|d| d.year()) + { + if last < year - 1 { + years.extend([last - 1, last, last + 1]); + } + } + } + for y in years { + if let Some(at) = transition(rule, y) { + candidates.push((at, *to)); + } + } + } else { + for d in dated(rule) { + if d.year() == year || d.year() == year - 1 || (history && d.year() < year) { + candidates.push((d.and_utc().timestamp_millis(), *to)); + } + } + } + } + let wanted = reading.and_utc().timestamp_millis(); + if let Some((_, to)) = candidates + .into_iter() + .filter(|(at, _)| *at <= wanted) + .max_by_key(|(at, _)| *at) + { + return Some(to); + } + let earliest = ordered + .iter() + .filter_map(|(r, _)| { + let at = if r.property("RRULE").is_some() { + transition(r, year - 1) + } else { + dated(r) + .into_iter() + .filter(|d| d.year() == year - 1) + .map(|d| d.and_utc().timestamp_millis()) + .min() + }?; + Some((at, offset(r.text("TZOFFSETFROM"))?)) + }) + .min_by_key(|(at, _)| *at); + earliest + .map(|(_, offset)| offset) + .or_else(|| ordered.first().map(|(_, offset)| *offset)) +} +pub(super) fn moment(property: Option<&Property>, calendar: &Component) -> Value { + let Some(p) = property else { + return Value::Null; + }; + let Some(value) = date(&p.value) else { + return Value::Null; + }; + let tz = p.params.get("TZID").map(String::as_str).unwrap_or(""); + let all_day = p.value.len() == 8; + let universal = p.value.ends_with('Z') + || ["UTC", "GMT", "Z", "ETC/UTC", "ETC/GMT"].contains(&tz.to_uppercase().as_str()); + let (ms, resolved, tz) = if all_day { + (local(value), true, "") + } else if universal { + (Some(value.and_utc().timestamp_millis()), true, "") + } else if !tz.is_empty() { + let offset = zone(calendar, tz, value); + ( + Some(value.and_utc().timestamp_millis() - offset.unwrap_or(0) * 60_000), + offset.is_some(), + tz, + ) + } else { + (local(value), true, "") + }; + ms.map(|ms| json!({"ms":ms,"allDay":all_day,"tzid":tz,"resolved":resolved})) + .unwrap_or(Value::Null) +} +pub(super) fn duration(text: &str) -> i64 { + let mut text = text.trim().to_uppercase(); + let sign = if text.starts_with('-') { -1 } else { 1 }; + text = text.trim_start_matches(['-', '+']).to_owned(); + let Some(text) = text.strip_prefix('P') else { + return 0; + }; + let mut total = 0i64; + let mut number = String::new(); + let mut timed = false; + for c in text.chars() { + if c == 'T' { + timed = true; + continue; + } + if c.is_ascii_digit() { + number.push(c); + continue; + } + let multiplier = match c { + 'W' => 604800000, + 'D' => 86400000, + 'H' if timed => 3600000, + 'M' if timed => 60000, + 'S' if timed => 1000, + _ => return 0, + }; + let Some(value) = number + .parse::() + .ok() + .and_then(|v| v.checked_mul(multiplier)) + .and_then(|v| total.checked_add(v)) + else { + return 0; + }; + total = value; + number.clear(); + } + if number.is_empty() { sign * total } else { 0 } +} diff --git a/src/calendar/parse/ics.rs b/src/calendar/parse/ics.rs new file mode 100644 index 000000000..db129c100 --- /dev/null +++ b/src/calendar/parse/ics.rs @@ -0,0 +1,273 @@ +use super::dates; +use serde_json::{Value, json}; +use std::collections::HashMap; + +#[derive(Clone, Default)] +pub(super) struct Property { + pub name: String, + pub value: String, + pub params: HashMap, + pub raw: String, +} +#[derive(Clone, Default)] +pub(super) struct Component { + pub name: String, + pub properties: Vec, + pub children: Vec, + pub lines: Vec, +} +impl Component { + pub fn property(&self, name: &str) -> Option<&Property> { + self.properties.iter().find(|p| p.name == name) + } + pub fn text(&self, name: &str) -> &str { + self.property(name).map(|p| p.value.as_str()).unwrap_or("") + } + pub fn raw(&self, name: &str) -> &str { + self.property(name).map(|p| p.raw.as_str()).unwrap_or("") + } +} +fn split(text: &str, separator: char) -> Vec<&str> { + let mut quoted = false; + let mut at = 0; + let mut parts = Vec::new(); + for (index, c) in text.char_indices() { + if c == '"' { + quoted = !quoted; + } + if c == separator && !quoted { + parts.push(&text[at..index]); + at = index + c.len_utf8(); + } + } + parts.push(&text[at..]); + parts +} +pub(super) fn property(line: &str) -> Option { + let chunks = split(line, ':'); + if chunks.len() < 2 { + return None; + } + let mut names = split(chunks[0], ';').into_iter(); + let name = names.next()?.to_uppercase(); + let params = names + .filter_map(|s| s.split_once('=')) + .map(|(k, v)| (k.to_uppercase(), v.trim_matches('"').to_owned())) + .collect(); + Some(Property { + name, + value: line[chunks[0].len() + 1..].to_owned(), + params, + raw: line.to_owned(), + }) +} +pub(super) fn parse(text: &str) -> Result { + if text.len() > 512 * 1024 { + return Err("calendar_response_too_large"); + } + let mut lines: Vec = Vec::new(); + let normalized = text.replace("\r\n", "\n").replace('\r', "\n"); + for line in normalized.split('\n') { + if (line.starts_with(' ') || line.starts_with('\t')) && !lines.is_empty() { + lines.last_mut().unwrap().push_str(&line[1..]); + } else if !line.trim().is_empty() { + lines.push(line.to_owned()); + } + } + let mut stack: Vec = Vec::new(); + let mut root = None; + for line in lines { + let Some(p) = property(&line) else { continue }; + if p.name == "BEGIN" { + if stack.len() >= 8 { + return Err("calendar_response_too_large"); + } + stack.push(Component { + name: p.value.to_uppercase(), + ..Default::default() + }); + } else if p.name == "END" { + let Some(child) = stack.pop() else { + return Err("calendar_invalid_response"); + }; + if child.name != p.value.to_uppercase() { + return Err("calendar_invalid_response"); + } + if let Some(parent) = stack.last_mut() { + parent.lines.push(format!("BEGIN:{}", child.name)); + parent.lines.extend(child.lines.clone()); + parent.lines.push(format!("END:{}", child.name)); + parent.children.push(child); + } else if root.replace(child).is_some() { + return Err("calendar_invalid_response"); + } + } else if let Some(current) = stack.last_mut() { + current.lines.push(line); + current.properties.push(p); + } + } + if !stack.is_empty() { + return Err("calendar_invalid_response"); + } + root.filter(|c| c.name == "VCALENDAR") + .ok_or("calendar_invalid_response") +} +fn unescape(text: &str) -> String { + let mut result = String::new(); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + result.push(c); + continue; + } + if let Some(c) = chars.next() { + result.push(if c == 'n' || c == 'N' { '\n' } else { c }); + } + } + result +} +fn address(property: Option<&Property>) -> Value { + let Some(p) = property else { + return Value::Null; + }; + let email = if p.value.to_lowercase().starts_with("mailto:") { + &p.value[7..] + } else { + &p.value + } + .trim(); + let name = unescape(p.params.get("CN").map(String::as_str).unwrap_or("")) + .trim() + .to_owned(); + let role = p + .params + .get("ROLE") + .cloned() + .unwrap_or_default() + .to_uppercase(); + json!({"name":if name.is_empty(){email}else{&name},"email":email, + "role":role,"optional":role=="OPT-PARTICIPANT", + "resource":p.params.get("CUTYPE").is_some_and(|s|s.eq_ignore_ascii_case("RESOURCE")), + "partstat":p.params.get("PARTSTAT").cloned().unwrap_or_default().to_uppercase()}) +} +fn recurrence(rule: &str) -> String { + if rule.is_empty() { + return String::new(); + } + let parts = dates::rules(rule); + let frequency = parts.get("FREQ").map(String::as_str).unwrap_or(""); + let (one, many) = match frequency { + "DAILY" => ("Daily", "days"), + "WEEKLY" => ("Weekly", "weeks"), + "MONTHLY" => ("Monthly", "months"), + "YEARLY" => ("Yearly", "years"), + _ => return "Repeats".into(), + }; + let interval = parts + .get("INTERVAL") + .and_then(|s| s.parse::().ok()) + .unwrap_or(1); + let mut text = if interval > 1 { + format!("Every {interval} {many}") + } else { + one.into() + }; + if matches!(frequency, "WEEKLY" | "MONTHLY") { + let names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + let days: Vec<_> = parts + .get("BYDAY") + .into_iter() + .flat_map(|s| s.split(',')) + .filter_map(|s| dates::weekday(s).map(|(_, day)| names[day as usize])) + .collect(); + if !days.is_empty() { + text.push_str(&format!(" on {}", days.join(", "))); + } + } + if let Some(count) = parts + .get("COUNT") + .and_then(|s| s.parse::().ok()) + .filter(|n| *n > 0) + { + text.push_str(&format!(", {count} times")); + } else if let Some(until) = parts.get("UNTIL").and_then(|s| dates::date(s)) { + text.push_str(&until.format(", until %b %-d, %Y").to_string()); + } + text +} +fn conference(event: &Component) -> String { + static MEET: std::sync::OnceLock = std::sync::OnceLock::new(); + static OTHER: std::sync::OnceLock = std::sync::OnceLock::new(); + let meet = + MEET.get_or_init(|| regex::Regex::new(r"https://meet\.google\.com/[a-z0-9-]+").unwrap()); + let other=OTHER.get_or_init(||regex::Regex::new(r#"https://(?:[a-z0-9-]+\.)*(?:zoom\.us|teams\.microsoft\.com|teams\.live\.com|meet\.google\.com|whereby\.com|webex\.com|chime\.aws)/[^\s<>"]+"#).unwrap()); + for key in ["X-GOOGLE-CONFERENCE", "LOCATION", "DESCRIPTION"] { + if let Some(found) = meet.find(event.text(key)) { + return found.as_str().into(); + } + } + for key in ["LOCATION", "DESCRIPTION"] { + if let Some(found) = other.find(event.text(key)) { + return found.as_str().into(); + } + } + String::new() +} +pub(super) fn events(calendar: &Component) -> Vec { + let zones: Vec<_> = calendar + .children + .iter() + .filter(|c| c.name == "VTIMEZONE") + .map(|c| { + format!( + "BEGIN:VTIMEZONE\r\n{}\r\nEND:VTIMEZONE", + c.lines.join("\r\n") + ) + }) + .collect(); + let mut events = Vec::new(); + for event in calendar + .children + .iter() + .filter(|c| c.name == "VEVENT" && !c.text("UID").is_empty()) + { + let start = dates::moment(event.property("DTSTART"), calendar); + let mut end = dates::moment(event.property("DTEND"), calendar); + let duration = dates::duration(event.text("DURATION")); + if end.is_null() && start.is_object() && duration > 0 { + end = start.clone(); + end["ms"] = json!(start["ms"].as_i64().unwrap_or(0).saturating_add(duration)); + } + let excluded: Vec<_> = event + .properties + .iter() + .filter(|p| p.name == "EXDATE") + .flat_map(|p| { + p.value.split(',').map(|value| Property { + value: value.into(), + ..p.clone() + }) + }) + .filter_map(|p| dates::moment(Some(&p), calendar)["ms"].as_i64()) + .collect(); + let attendees: Vec<_> = event + .properties + .iter() + .filter(|p| p.name == "ATTENDEE") + .map(|p| address(Some(p))) + .filter(|p| p["email"] != "") + .collect(); + let rule = event.text("RRULE"); + let method = calendar.text("METHOD").trim().to_uppercase(); + events.push(json!({"method":if ["REQUEST","REPLY","CANCEL","PUBLISH","COUNTER","REFRESH","ADD","DECLINECOUNTER"].contains(&method.as_str()){method}else{String::new()}, + "uid":unescape(event.text("UID")),"sequence":event.text("SEQUENCE").parse::().unwrap_or(0), + "summary":unescape(event.text("SUMMARY")),"description":unescape(event.text("DESCRIPTION")),"location":unescape(event.text("LOCATION")), + "status":event.text("STATUS").to_uppercase(),"organizer":address(event.property("ORGANIZER")),"attendees":attendees, + "start":start,"end":end,"recurrence":recurrence(rule),"recurrenceRule":rule, + "recurrenceIdMs":dates::moment(event.property("RECURRENCE-ID"),calendar)["ms"].as_i64().unwrap_or(0), + "excludedMs":excluded,"meetLink":conference(event), + "source":{"dtstart":event.raw("DTSTART"),"dtend":event.raw("DTEND"),"duration":event.raw("DURATION"), + "recurrenceId":event.raw("RECURRENCE-ID"),"timezones":zones}})); + } + events +} diff --git a/src/calendar/parse/mod.rs b/src/calendar/parse/mod.rs new file mode 100644 index 000000000..a1660eaf6 --- /dev/null +++ b/src/calendar/parse/mod.rs @@ -0,0 +1,297 @@ +mod dates; +mod ics; +mod recurrence; +use chrono::{DateTime, NaiveDate, NaiveDateTime}; +use serde_json::{Value, json}; +type Result = std::result::Result; +fn text<'a>(value: &'a Value, key: &str) -> &'a str { + value[key].as_str().unwrap_or("") +} +fn default<'a>(value: &'a Value, key: &str, fallback: &'a str) -> &'a str { + value[key] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(fallback) +} +fn sort(events: &mut [Value]) { + events.sort_by(|a, b| { + a["start"]["ms"] + .as_i64() + .unwrap_or(0) + .cmp(&b["start"]["ms"].as_i64().unwrap_or(0)) + .then_with(|| { + text(a, "summary") + .to_lowercase() + .cmp(&text(b, "summary").to_lowercase()) + }) + }); +} +fn moment(text: &str, all_day: bool, graph: bool) -> Value { + let ms = if all_day { + text.get(..10) + .and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok()) + .and_then(|d| d.and_hms_opt(0, 0, 0)) + .and_then(dates::local) + } else if graph { + NaiveDateTime::parse_from_str(text.trim_end_matches('Z'), "%Y-%m-%dT%H:%M:%S%.f") + .ok() + .map(|d| d.and_utc().timestamp_millis()) + } else { + DateTime::parse_from_rfc3339(text) + .ok() + .map(|d| d.timestamp_millis()) + }; + ms.map(|ms| json!({"ms":ms,"allDay":all_day,"tzid":"","resolved":true})) + .unwrap_or(Value::Null) +} +fn google(payload: &Value, source: &str) -> Vec { + let mut events = Vec::new(); + for item in payload["items"].as_array().into_iter().flatten() { + if text(item, "status").eq_ignore_ascii_case("cancelled") { + continue; + } + let at = |key: &str| { + moment( + default(&item[key], "dateTime", text(&item[key], "date")), + text(&item[key], "dateTime").is_empty() && !text(&item[key], "date").is_empty(), + false, + ) + }; + let start = at("start"); + if start.is_null() { + continue; + } + let mut row = json!({"method":"","uid":default(item,"iCalUID",text(item,"id")),"googleId":text(item,"id"), + "etag":text(item,"etag"),"recurringEventId":text(item,"recurringEventId"),"originalStartTime":item["originalStartTime"], + "timeZone":default(&item["start"],"timeZone",text(payload,"timeZone")),"reminders":item.get("reminders").cloned().unwrap_or(json!({"useDefault":true})), + "conferenceData":item["conferenceData"],"eventType":default(item,"eventType","default"),"guestsCanModify":item["guestsCanModify"]==true, + "transparency":default(item,"transparency","opaque"),"visibility":default(item,"visibility","default"),"sequence":item["sequence"].as_u64().unwrap_or(0), + "summary":default(item,"summary","Untitled event"),"description":text(item,"description"),"location":text(item,"location"), + "status":text(item,"status").to_uppercase(),"organizer":item["organizer"],"attendees":item["attendees"].as_array().cloned().unwrap_or_default(), + "recurrenceLines":item["recurrence"].as_array().cloned().unwrap_or_default(),"start":start,"end":at("end"), + "recurrence":"","meetLink":text(item,"hangoutLink"),"sourceId":source,"href":text(item,"htmlLink"),"source":null}); + row["recurrence"] = json!( + item["recurrence"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join("; ") + ); + events.push(row); + } + sort(&mut events); + events +} +fn graph(payload: &Value, source: &str) -> Vec { + let person = |p: &Value| json!({"email":text(&p["emailAddress"],"address"),"displayName":text(&p["emailAddress"],"name")}); + let mut events = Vec::new(); + for item in payload["value"].as_array().into_iter().flatten() { + if item["isCancelled"] == true { + continue; + } + let at = |key: &str| moment(text(&item[key], "dateTime"), item["isAllDay"] == true, true); + let start = at("start"); + if start.is_null() { + continue; + } + events.push(json!({"method":"","uid":default(item,"iCalUId",text(item,"id")),"graphId":text(item,"id"),"sequence":0, + "summary":default(item,"subject","Untitled event"),"description":text(item,"bodyPreview"),"location":text(&item["location"],"displayName"), + "status":"CONFIRMED","organizer":if item["organizer"].is_object(){person(&item["organizer"])}else{Value::Null}, + "attendees":item["attendees"].as_array().into_iter().flatten().map(person).collect::>(),"start":start,"end":at("end"), + "recurrence":"","meetLink":text(&item["onlineMeeting"],"joinUrl"),"sourceId":source,"href":text(item,"webLink"),"source":null})); + } + sort(&mut events); + events +} +fn caldav(xml: &str, source: &str, start: i64, end: i64) -> Result> { + use quick_xml::{Reader, events::Event}; + let mut reader = Reader::from_str(xml); + let mut tags: Vec = Vec::new(); + let mut href = String::new(); + let mut data = String::new(); + let mut events = Vec::new(); + loop { + match reader + .read_event() + .map_err(|_| "calendar_invalid_response")? + { + Event::Start(e) => { + if tags.len() > 64 { + return Err("calendar_response_too_large"); + } + let tag = String::from_utf8_lossy(e.local_name().as_ref()).into_owned(); + if tag == "response" { + href.clear(); + data.clear(); + } + tags.push(tag); + } + Event::Text(e) => { + let decoded = e.decode().map_err(|_| "calendar_invalid_response")?; + let value = quick_xml::escape::unescape(&decoded) + .map_err(|_| "calendar_invalid_response")?; + match tags.last().map(String::as_str) { + Some("href") => href.push_str(&value), + Some("calendar-data") => data.push_str(&value), + _ => (), + } + } + Event::CData(e) => { + let value = e.decode().map_err(|_| "calendar_invalid_response")?; + match tags.last().map(String::as_str) { + Some("href") => href.push_str(&value), + Some("calendar-data") => data.push_str(&value), + _ => (), + } + } + Event::GeneralRef(e) => { + let name = e.decode().map_err(|_| "calendar_invalid_response")?; + let encoded = format!("&{name};"); + let value = quick_xml::escape::unescape(&encoded) + .map_err(|_| "calendar_invalid_response")?; + match tags.last().map(String::as_str) { + Some("href") => href.push_str(&value), + Some("calendar-data") => data.push_str(&value), + _ => (), + } + } + Event::End(_) => { + if tags.pop().as_deref() == Some("response") && !data.is_empty() { + let calendar = ics::parse(&data)?; + for mut event in ics::events(&calendar) { + event["sourceId"] = json!(source); + event["href"] = json!(href); + event["calendarData"] = json!(data); + events.push(event); + } + if events.len() > 25000 { + return Err("calendar_response_too_large"); + } + } + } + Event::DocType(_) => return Err("calendar_invalid_response"), + Event::Eof => break, + _ => (), + } + } + if !tags.is_empty() { + return Err("calendar_invalid_response"); + } + if start != 0 && end != 0 { + recurrence::expand(events, start, end) + } else { + events.retain(|e| e["status"] != "CANCELLED"); + sort(&mut events); + Ok(events) + } +} +pub(crate) fn parse(params: &Value) -> Result { + if params.as_object().is_none_or(|p| { + p.keys() + .any(|k| !["body", "kind", "sourceId", "startMs", "endMs"].contains(&k.as_str())) + }) { + return Err("invalid_params"); + } + let body = params["body"].as_str().ok_or("invalid_params")?; + if body.len() > 16 * 1024 * 1024 { + return Err("calendar_response_too_large"); + } + let source = text(params, "sourceId"); + let events = match text(params, "kind") { + "google" | "microsoft" => { + let payload: Value = + serde_json::from_str(body).map_err(|_| "calendar_invalid_response")?; + let items = if text(params, "kind") == "google" { + "items" + } else { + "value" + }; + if !payload.is_object() + || payload.get(items).is_some_and(|v| !v.is_array()) + || payload.get("error").is_some() + { + return Err("calendar_invalid_response"); + } + if text(params, "kind") == "google" { + google(&payload, source) + } else { + graph(&payload, source) + } + } + "caldav" | "icloud" => caldav( + body, + source, + params["startMs"].as_i64().unwrap_or(0), + params["endMs"].as_i64().unwrap_or(0), + )?, + _ => return Err("invalid_params"), + }; + Ok(json!({"events":events})) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn existing_calendar_regressions_match_native_parsing() { + let output = std::process::Command::new("node") + .arg("tests/calendar_parse_oracle.js") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let cases: Vec = serde_json::from_slice(&output.stdout).unwrap(); + assert!(cases.len() > 20); + for (index, case) in cases.into_iter().enumerate() { + let args = &case["args"]; + let name = text(&case, "name"); + if matches!(name, "eventsFrom" | "invitationFrom") + && args[0] + .as_str() + .is_some_and(|s| !s.trim_end().ends_with("END:VCALENDAR")) + { + assert!( + ics::parse(args[0].as_str().unwrap()).is_err(), + "truncated calendars must not replace a complete saved range" + ); + continue; + } + let got = if matches!(name, "eventsFrom" | "invitationFrom") { + let mut events = ics::parse(args[0].as_str().unwrap()) + .map(|c| ics::events(&c)) + .unwrap_or_default(); + if let Some(fallback) = args[1].as_str() { + for event in &mut events { + if event["method"] == "" { + event["method"] = json!(fallback.to_uppercase()); + } + } + } + if name == "invitationFrom" { + events.into_iter().next().unwrap_or(Value::Null) + } else { + json!(events) + } + } else { + let kind = match name { + "eventsFromGoogle" => "google", + "eventsFromGraph" => "microsoft", + _ => "caldav", + }; + parse(&json!({"kind":kind,"sourceId":args[1],"body":if kind=="caldav"{args[0].as_str().unwrap().to_owned()}else{args[0].to_string()}, + "startMs":args[2],"endMs":args[3]})).unwrap_or_else(|error|panic!("case {index} {name}: {error}"))["events"].clone() + }; + assert_eq!(got, case["result"], "case {index} {name}"); + } + } + #[test] + fn xml_entities_cannot_read_external_files() { + let payload = json!({"kind":"caldav","body":"]>&x;"}); + assert_eq!(parse(&payload), Err("calendar_invalid_response")); + } +} diff --git a/src/calendar/parse/recurrence.rs b/src/calendar/parse/recurrence.rs new file mode 100644 index 000000000..fd6d6d3ed --- /dev/null +++ b/src/calendar/parse/recurrence.rs @@ -0,0 +1,201 @@ +use super::{dates, ics, sort}; +use chrono::{Datelike, Duration}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; +type Result = std::result::Result; +fn ms(event: &Value) -> i64 { + event["start"]["ms"].as_i64().unwrap_or(0) +} +fn in_range(event: &Value, start: i64, end: i64) -> bool { + ms(event) < end && event["end"]["ms"].as_i64().unwrap_or(ms(event) + 1) > start +} +fn listed(value: i32, text: &str) -> bool { + text.split(',') + .any(|s| s.parse::().ok() == Some(value)) +} +fn by_day(day: chrono::NaiveDate, text: &str) -> bool { + text.split(',') + .filter_map(dates::weekday) + .any(|(ordinal, weekday)| { + if day.weekday().num_days_from_sunday() != weekday { + return false; + } + ordinal == 0 + || ordinal == (day.day() as i32 - 1) / 7 + 1 + || ordinal + == -((dates::month_days(day.year(), day.month()) - day.day()) as i32 / 7) - 1 + }) +} +fn week(day: chrono::NaiveDate) -> i64 { + (day.signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()) + .num_days() + - day.weekday().num_days_from_monday() as i64) + .div_euclid(7) +} +fn starts(event: &Value, from: i64, to: i64) -> Result> { + let parts = dates::rules(event["recurrenceRule"].as_str().unwrap_or("")); + let frequency = parts.get("FREQ").map(String::as_str).unwrap_or(""); + if !matches!(frequency, "DAILY" | "WEEKLY" | "MONTHLY" | "YEARLY") { + return Err("calendar_recurrence_unsupported"); + } + let interval = parts + .get("INTERVAL") + .and_then(|s| s.parse::().ok()) + .unwrap_or(1) + .max(1); + let count = parts + .get("COUNT") + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let until = parts + .get("UNTIL") + .and_then(|s| { + dates::date(s).map(|d| { + if s.ends_with('Z') { + d.and_utc().timestamp_millis() + } else { + dates::local(d).unwrap_or(0) + } + }) + }) + .unwrap_or(0); + let property = ics::property(event["source"]["dtstart"].as_str().unwrap_or("")) + .ok_or("calendar_invalid_response")?; + let base = dates::date(&property.value).ok_or("calendar_invalid_response")?; + let zones = event["source"]["timezones"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join("\r\n"); + let calendar = ics::parse(&format!("BEGIN:VCALENDAR\r\n{zones}\r\nEND:VCALENDAR"))?; + let mut current = base; + if count == 0 { + let skip = (from.saturating_sub(172_800_000) - base.and_utc().timestamp_millis()) + .div_euclid(86_400_000) + .max(0); + current = current + .checked_add_signed(Duration::days(skip)) + .ok_or("calendar_invalid_response")?; + } + let mut out = Vec::new(); + let mut emitted = 0; + for _ in 0..10000 { + if current.and_utc().timestamp_millis() >= to.saturating_add(86_400_000) { + return Ok(out); + } + let delta = current.date().signed_duration_since(base.date()).num_days(); + let month_delta = (current.year() - base.year()) as i64 * 12 + current.month() as i64 + - base.month() as i64; + let year_delta = (current.year() - base.year()) as i64; + let month_day = parts + .get("BYMONTHDAY") + .map(|s| listed(current.day() as i32, s)) + .unwrap_or_else(|| { + parts + .get("BYDAY") + .map(|s| by_day(current.date(), s)) + .unwrap_or(current.day() == base.day()) + }); + let matches = match frequency { + "DAILY" => delta >= 0 && delta % interval == 0, + "WEEKLY" => { + parts + .get("BYDAY") + .map(|s| by_day(current.date(), s)) + .unwrap_or(current.weekday() == base.weekday()) + && (week(current.date()) - week(base.date())) % interval == 0 + } + "MONTHLY" => month_delta >= 0 && month_delta % interval == 0 && month_day, + "YEARLY" => { + year_delta >= 0 + && year_delta % interval == 0 + && month_day + && parts + .get("BYMONTH") + .map(|s| listed(current.month() as i32, s)) + .unwrap_or(current.month() == base.month()) + } + _ => false, + }; + let mut occurrence = property.clone(); + occurrence.value = current + .format(if property.value.len() == 8 { + "%Y%m%d" + } else if property.value.ends_with('Z') { + "%Y%m%dT%H%M%SZ" + } else { + "%Y%m%dT%H%M%S" + }) + .to_string(); + let at = dates::moment(Some(&occurrence), &calendar)["ms"] + .as_i64() + .ok_or("calendar_invalid_response")?; + if until > 0 && at > until { + return Ok(out); + } + if matches && at >= ms(event) { + emitted += 1; + if count > 0 && emitted > count { + return Ok(out); + } + out.push(at); + } + current = current + .checked_add_signed(Duration::days(1)) + .ok_or("calendar_invalid_response")?; + } + Err("calendar_recurrence_too_large") +} +pub(super) fn expand(events: Vec, from: i64, to: i64) -> Result> { + let mut overrides = HashMap::new(); + let mut masters = Vec::new(); + let mut out = Vec::new(); + for event in events { + let at = event["recurrenceIdMs"].as_i64().unwrap_or(0); + if at != 0 { + overrides.insert((event["uid"].as_str().unwrap_or("").to_owned(), at), event); + } else if !event["recurrenceRule"].as_str().unwrap_or("").is_empty() { + masters.push(event); + } else if event["status"] != "CANCELLED" && in_range(&event, from, to) { + out.push(event); + } + } + for master in masters { + let excluded: HashSet<_> = master["excludedMs"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_i64) + .collect(); + for at in starts(&master, from, to)? { + let key = (master["uid"].as_str().unwrap_or("").to_owned(), at); + if let Some(replacement) = overrides.remove(&key) { + if replacement["status"] != "CANCELLED" && in_range(&replacement, from, to) { + out.push(replacement); + } + } else if !excluded.contains(&at) && master["status"] != "CANCELLED" { + let mut event = master.clone(); + event["start"]["ms"] = json!(at); + if let Some(end) = master["end"]["ms"].as_i64() { + event["end"]["ms"] = json!(end.saturating_add(at - ms(&master))); + } + event["recurrenceIdMs"] = json!(at); + if in_range(&event, from, to) { + out.push(event); + } + } + if out.len() > 25000 { + return Err("calendar_response_too_large"); + } + } + } + out.extend( + overrides + .into_values() + .filter(|e| e["status"] != "CANCELLED" && in_range(e, from, to)), + ); + sort(&mut out); + Ok(out) +} diff --git a/src/calendar/reads.rs b/src/calendar/reads.rs new file mode 100644 index 000000000..2d1497eb3 --- /dev/null +++ b/src/calendar/reads.rs @@ -0,0 +1,99 @@ +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::{ + collections::VecDeque, + future::Future, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; +struct Entry { + key: [u8; 32], + value: tokio::sync::Mutex>, +} +pub(crate) struct Reads { + entries: Mutex>>, + slots: tokio::sync::Semaphore, +} +impl Default for Reads { + fn default() -> Self { + Self { + entries: Mutex::new(VecDeque::new()), + slots: tokio::sync::Semaphore::new(2), + } + } +} +impl Reads { + pub(crate) fn invalidate(&self) { + if let Ok(mut entries) = self.entries.lock() { + entries.clear(); + } + } + pub(crate) async fn get(&self, params: &Value, fetch: F) -> Result + where + F: FnOnce() -> Fut, + Fut: Future>, + { + let key: [u8; 32] = + Sha256::digest(serde_json::to_vec(params).map_err(|_| "invalid_params")?).into(); + let entry = { + let mut entries = self.entries.lock().map_err(|_| "session_failed")?; + if let Some(index) = entries.iter().position(|e| e.key == key) { + let entry = entries.remove(index).unwrap(); + entries.push_back(entry.clone()); + entry + } else { + while entries.len() >= 16 { + let index = entries + .iter() + .position(|entry| Arc::strong_count(entry) == 1) + .ok_or("calendar_busy")?; + entries.remove(index); + } + let entry = Arc::new(Entry { + key, + value: tokio::sync::Mutex::new(None), + }); + entries.push_back(entry.clone()); + entry + } + }; + let mut saved = entry.value.lock().await; + if let Some((at, value, _)) = saved.as_ref() { + if at.elapsed() < Duration::from_secs(5) { + return Ok(value.clone()); + } + } + let _permit = self.slots.acquire().await.map_err(|_| "session_failed")?; + let value = fetch().await?; + let bytes = serde_json::to_vec(&value) + .map_err(|_| "calendar_invalid_response")? + .len(); + if bytes <= 4 * 1024 * 1024 { + *saved = Some((Instant::now(), value.clone(), bytes)); + } + Ok(value) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn identical_reads_share_work_and_writes_invalidate() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let reads = Reads::default(); + let calls = AtomicUsize::new(0); + let params = serde_json::json!({"source":"one","range":[1,2]}); + let fetch = || async { + calls.fetch_add(1, Ordering::Relaxed); + tokio::task::yield_now().await; + Ok(serde_json::json!({"events":[]})) + }; + let (first, second) = tokio::join!(reads.get(¶ms, fetch), reads.get(¶ms, fetch)); + assert_eq!(first, second); + assert_eq!(calls.load(Ordering::Relaxed), 1); + reads.invalidate(); + reads.get(¶ms, fetch).await.unwrap(); + assert_eq!(calls.load(Ordering::Relaxed), 2); + } +} diff --git a/src/compose/mod.rs b/src/compose/mod.rs index 24db94297..dd9fe9eb2 100644 --- a/src/compose/mod.rs +++ b/src/compose/mod.rs @@ -156,6 +156,16 @@ fn draft(value: &Value) -> Result { json!(size) }; attachments.push(json!({"filename":text(&row["filename"]),"mimeType":text(&row["mimeType"]),"size":size,"data":if path.is_empty(){text(&row["data"])}else{String::new()},"path":path,"owned":row["owned"]==true,"attachmentId":text(&row["attachmentId"]),"partId":text(&row["partId"])})); + if let Some(handle) = row + .get("handle") + .and_then(Value::as_str) + .filter(|h| !h.is_empty()) + { + if handle.len() != 64 || !handle.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("invalid_params"); + } + attachments.last_mut().unwrap()["handle"] = json!(handle); + } } out[key] = json!(attachments); } diff --git a/src/lib.rs b/src/lib.rs index f686fa674..952a9c0ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod compose; pub mod contacts; pub mod credentials; pub mod inbox; +pub mod local_mail; pub mod mail; pub mod message; pub mod outbox; diff --git a/src/local_mail/content.rs b/src/local_mail/content.rs new file mode 100644 index 000000000..8b4669dae --- /dev/null +++ b/src/local_mail/content.rs @@ -0,0 +1,80 @@ +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use serde_json::Value; + +pub(super) struct Text { + pub body: String, + pub filenames: String, + pub complete: bool, +} +pub(super) fn extract(resource: &Value) -> Text { + let mut output = Text { + body: String::new(), + filenames: String::new(), + complete: true, + }; + let mut pending = vec![&resource["payload"]]; + while let Some(part) = pending.pop() { + if let Some(parts) = part["parts"].as_array() { + pending.extend(parts.iter().rev()); + } + let filename = part["filename"].as_str().unwrap_or(""); + let attachment = part["headers"].as_array().into_iter().flatten().any(|h| { + h["name"] + .as_str() + .is_some_and(|s| s.eq_ignore_ascii_case("Content-Disposition")) + && h["value"] + .as_str() + .is_some_and(|s| s.to_lowercase().starts_with("attachment")) + }); + if !filename.is_empty() { + output.filenames.push_str(filename); + output.filenames.push('\n'); + } + if !filename.is_empty() || attachment { + continue; + } + let mime = part["mimeType"].as_str().unwrap_or(""); + if !matches!(mime, "text/plain" | "text/html") { + continue; + } + let Some(data) = part["body"]["data"].as_str() else { + if part["body"]["size"].as_u64().unwrap_or(0) > 0 + || part["body"]["attachmentId"].is_string() + { + output.complete = false; + } + continue; + }; + let Ok(bytes) = URL_SAFE_NO_PAD.decode(data.trim_end_matches('=')) else { + output.complete = false; + continue; + }; + let charset = part["headers"] + .as_array() + .into_iter() + .flatten() + .find(|h| { + h["name"] + .as_str() + .is_some_and(|s| s.eq_ignore_ascii_case("Content-Type")) + }) + .and_then(|h| h["value"].as_str()) + .and_then(|s| mailparse::parse_content_type(s).charset.into()); + let encoding = charset + .as_deref() + .and_then(|s| encoding_rs::Encoding::for_label(s.as_bytes())) + .unwrap_or(encoding_rs::UTF_8); + let (text, _, errors) = encoding.decode(&bytes); + if errors { + output.complete = false; + } + let text = if mime == "text/html" { + crate::message::content::html_to_text(&text) + } else { + text.into_owned() + }; + output.body.push_str(&text); + output.body.push('\n'); + } + output +} diff --git a/src/local_mail/ipc.rs b/src/local_mail/ipc.rs new file mode 100644 index 000000000..a2fb7c247 --- /dev/null +++ b/src/local_mail/ipc.rs @@ -0,0 +1,214 @@ +use super::{Store, execute, sync}; +use crate::platform::{ + dirs::AppDirs, + ipc::{LocalEndpoint, authenticate}, + private_fs, +}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{sync::Arc, time::Duration}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +const INPUT: usize = 1024 * 1024; +const OUTPUT: usize = 128 * 1024 * 1024 + 4096; +const TIMEOUT: Duration = Duration::from_secs(20); +type Result = std::result::Result; + +pub(super) fn listen(store: &Arc, account: &str) -> Result<()> { + let mut task = store + .listener + .lock() + .map_err(|_| "local_storage_unavailable")?; + if task.as_ref().is_some_and(|task| !task.is_finished()) { + return Ok(()); + } + let endpoint = LocalEndpoint::directory( + store + .directory() + .try_clone() + .map_err(|_| "local_storage_unavailable")?, + )?; + let listener = endpoint.listen()?; + let weak = Arc::downgrade(store); + let account = account.to_owned(); + *task = Some(tokio::spawn(async move { + let mut requests = tokio::task::JoinSet::new(); + loop { + tokio::select! { + connection=listener.accept(), if requests.len()<2 => { + let Ok((mut stream,_))=connection else {break}; + let Some(store)=weak.upgrade() else {break}; + let account=account.clone(); + requests.spawn(async move { + let _=tokio::time::timeout(TIMEOUT,async { + authenticate(&mut stream).await?; + let request=read(&mut stream,INPUT).await?; + let answer=serve(&store,&account,request).await; + let answer=match answer {Ok(value)=>json!({"result":value}),Err(error)=>json!({"error":error})}; + write(&mut stream,&answer,OUTPUT).await + }).await; + }); + } + _=requests.join_next(), if !requests.is_empty()=>(), + } + } + })); + Ok(()) +} + +async fn serve(store: &Arc, account: &str, request: Value) -> Result { + if request["params"]["accountId"] != account { + return Err("local_account_unknown"); + } + let method = request["method"] + .as_str() + .ok_or("invalid_params")? + .to_owned(); + if !matches!( + method.as_str(), + "local.list" + | "local.status" + | "local.edits" + | "local.pause" + | "local.edit" + | "local.cancelEdit" + | "local.resource" + | "local.revision" + | "local.overview" + | "local.labelCounts" + | "local.dismissConflict" + ) { + return Err("unknown_method"); + } + let params = request["params"].clone(); + sync::disk(store, move |s| execute(s, &method, ¶ms)).await +} + +pub(super) async fn request(account: &str, method: &str, params: &Value) -> Result { + let dirs = AppDirs::discover()?; + let hash = format!("{:x}", Sha256::digest(account.as_bytes())); + let directory = private_fs::directories_readonly(&dirs.state, &["omamail", "mail", &hash])? + .ok_or("local_owner_unavailable")?; + let endpoint = LocalEndpoint::directory(directory)?; + exchange(&endpoint, method, params).await +} + +async fn exchange(endpoint: &LocalEndpoint, method: &str, params: &Value) -> Result { + tokio::time::timeout(TIMEOUT, async { + let mut stream = endpoint.connect().await?; + write( + &mut stream, + &json!({"method":method,"params":params}), + INPUT, + ) + .await?; + let response = read(&mut stream, OUTPUT).await?; + if let Some(error) = response["error"].as_str() { + return Err(match error { + "invalid_params" => "invalid_params", + "local_search_unsupported" => "local_search_unsupported", + "local_edit_already_started" => "local_edit_already_started", + "local_edit_id_conflict" => "local_edit_id_conflict", + "local_message_unavailable" => "local_message_unavailable", + "local_storage_corrupt" => "local_storage_corrupt", + "local_content_invalid" => "local_content_invalid", + "local_content_missing" => "local_content_missing", + _ => "local_storage_unavailable", + }); + } + response + .get("result") + .cloned() + .ok_or("local_owner_unavailable") + }) + .await + .unwrap_or(Err("local_owner_unavailable")) +} + +async fn read(stream: &mut S, limit: usize) -> Result { + let length = stream + .read_u32() + .await + .map_err(|_| "local_owner_unavailable")? as usize; + if length > limit { + return Err("invalid_params"); + } + let mut bytes = vec![0; length]; + stream + .read_exact(&mut bytes) + .await + .map_err(|_| "local_owner_unavailable")?; + serde_json::from_slice(&bytes).map_err(|_| "invalid_params") +} +async fn write(stream: &mut S, value: &Value, limit: usize) -> Result<()> { + let bytes = serde_json::to_vec(value).map_err(|_| "invalid_params")?; + if bytes.len() > limit { + return Err("invalid_params"); + } + stream + .write_u32(bytes.len() as u32) + .await + .map_err(|_| "local_owner_unavailable")?; + stream + .write_all(&bytes) + .await + .map_err(|_| "local_owner_unavailable") +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn dispatcher_rejects_foreign_accounts_and_unknown_parameters_without_writes() { + let path = super::super::tests::directory(); + let store = Store::open(std::fs::File::open(&path).unwrap()).unwrap(); + let params = json!({"accountId":"other@example.org","ticket":"bad","ids":["one"], + "addLabelIds":["STARRED"],"removeLabelIds":[]}); + assert_eq!( + serve( + &store, + "owner@example.org", + json!({"method":"local.edit","params":params}) + ) + .await, + Err("local_account_unknown") + ); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + let mut params = params; + params["accountId"] = json!("owner@example.org"); + params["path"] = json!("/tmp/forbidden"); + assert_eq!( + serve( + &store, + "owner@example.org", + json!({"method":"local.edit","params":params}) + ) + .await, + Err("invalid_params") + ); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + drop(store); + std::fs::remove_dir_all(path).unwrap(); + } + #[tokio::test] + async fn owner_serves_authenticated_reads_and_refuses_another_account() { + let path = super::super::tests::directory(); + let store = Store::open(std::fs::File::open(&path).unwrap()).unwrap(); + listen(&store, "owner@example.org").unwrap(); + let endpoint = LocalEndpoint::directory(std::fs::File::open(&path).unwrap()).unwrap(); + assert_eq!( + exchange( + &endpoint, + "local.status", + &json!({"accountId":"owner@example.org"}) + ) + .await + .unwrap()["stored"], + 0 + ); + assert!(exchange(&endpoint,"local.edit",&json!({"accountId":"other@example.org","ticket":"bad","ids":["one"],"addLabelIds":["STARRED"],"removeLabelIds":[]})).await.is_err()); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + drop(store); + std::fs::remove_dir_all(path).unwrap(); + } +} diff --git a/src/local_mail/mod.rs b/src/local_mail/mod.rs new file mode 100644 index 000000000..66e7656f3 --- /dev/null +++ b/src/local_mail/mod.rs @@ -0,0 +1,386 @@ +mod content; +mod ipc; +#[cfg(test)] +mod recovery_tests; +mod search; +mod store; +mod sync; +#[cfg(test)] +mod tests; +mod vfs; + +use crate::platform::{dirs::AppDirs, private_fs}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; +use store::Store; + +pub(crate) fn text_complete(resource: &Value) -> bool { + content::extract(resource).complete +} + +#[derive(Default)] +pub struct LocalMail { + stores: Arc>>>, + jobs: Mutex>>, + events: std::sync::OnceLock>, +} +impl LocalMail { + pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver { + self.events + .get_or_init(|| tokio::sync::broadcast::channel(128).0) + .subscribe() + } + pub async fn start( + &self, + account: &str, + gmail: Arc, + ) -> Result<(), &'static str> { + let store = self.store(account).await?; + let mut jobs = self.jobs.lock().map_err(|_| "local_storage_unavailable")?; + if jobs.get(account).is_some_and(|job| !job.is_finished()) { + return Ok(()); + } + let account = account.to_owned(); + let worker_account = account.clone(); + let events = self + .events + .get_or_init(|| tokio::sync::broadcast::channel(128).0) + .clone(); + jobs.insert(account,tokio::spawn(async move { + let mut tick = 0u64; + let mut reported = std::time::Instant::now()-std::time::Duration::from_secs(2); + let mut changed = false; + loop { + let answer = sync::step(&store,&gmail,&worker_account,tick).await; + changed |= answer==Ok(true); + if reported.elapsed() >= std::time::Duration::from_secs(1) || answer.is_err() { + let error = answer.as_ref().err().copied().unwrap_or(""); + let _ = sync::disk(&store,move|s|s.write(|db| { + store::set_state(db,"error",error)?; + if error.is_empty() && changed { store::set_state(db,"updated",&chrono::Utc::now().timestamp_millis().to_string())?; } + Ok(()) + })).await; + if let Ok(status) = sync::disk(&store,|s|s.status()).await { + let _ = events.send(json!({"jsonrpc":"2.0","method":"local.changed","params":{"accountId":worker_account,"status":status,"changed":changed}})); + } + reported = std::time::Instant::now(); + changed = false; + } + tick += 1; + tokio::time::sleep(std::time::Duration::from_millis(if answer.is_err() {30_000} else if answer==Ok(false) {5_000} else {25})).await; + } + })); + Ok(()) + } + pub async fn refresh(&self, account: &str) -> Result<(), &'static str> { + let store = self.store(account).await?; + sync::disk(&store, |s| { + s.write(|db| store::set_state(db, "lastHistory", "0")) + }) + .await + } + pub fn stop(&self, account: &str) { + if let Ok(mut jobs) = self.jobs.lock() { + if let Some(job) = jobs.remove(account) { + job.abort(); + } + } + } + pub async fn shutdown(&self) { + let jobs: Vec<_> = self + .jobs + .lock() + .map(|mut jobs| jobs.drain().map(|(_, job)| job).collect()) + .unwrap_or_default(); + for job in jobs { + job.abort(); + let _ = job.await; + } + } + async fn store(&self, account: &str) -> Result, &'static str> { + let account = account.to_owned(); + let stores = self.stores.clone(); + let identity = account.clone(); + let store = tokio::task::spawn_blocking(move || { + let accounts = crate::account::list_readonly()?; + if !accounts["accounts"] + .as_array() + .into_iter() + .flatten() + .any(|entry| entry["id"] == account && entry["provider"] == "gmail") + { + return Err("local_account_unknown"); + } + let mut stores = stores.lock().map_err(|_| "local_storage_unavailable")?; + if let Some(store) = stores.get(&account) { + return Ok(store.clone()); + } + let dirs = AppDirs::discover()?; + let hash = format!("{:x}", Sha256::digest(account.as_bytes())); + let directory = + private_fs::directories(&dirs.state, &["omamail", "mail", &hash], true)? + .ok_or("local_storage_unavailable")?; + let store = Store::open(directory)?; + stores.insert(account, store.clone()); + Ok(store) + }) + .await + .map_err(|_| "local_storage_unavailable")??; + ipc::listen(&store, &identity)?; + Ok(store) + } + pub(crate) async fn resource( + &self, + account: &str, + id: &str, + ) -> Result, &'static str> { + let store = match self.store(account).await { + Err("private_fs_busy") => { + return ipc::request( + account, + "local.resource", + &json!({"accountId":account,"id":id}), + ) + .await + .map(|v| if v.is_null() { None } else { Some(v) }); + } + answer => answer?, + }; + let id = id.to_owned(); + tokio::task::spawn_blocking(move || store.complete_resource(&id)) + .await + .map_err(|_| "local_storage_unavailable")? + } + pub(crate) async fn revision( + &self, + account: &str, + id: &str, + ) -> Result, &'static str> { + let store = match self.store(account).await { + Err("private_fs_busy") => { + return ipc::request( + account, + "local.revision", + &json!({"accountId":account,"id":id}), + ) + .await + .map(|v| v.as_str().map(str::to_owned)); + } + answer => answer?, + }; + let id = id.to_owned(); + sync::disk(&store, move |s| s.revision(&id)).await + } + pub(crate) async fn read( + &self, + account: &str, + id: &str, + gmail: &crate::providers::gmail::Session, + ) -> Result { + let store = match self.store(account).await { + Err("private_fs_busy") => { + if let Some(value) = self.resource(account, id).await? { + return Ok(value); + } + return gmail + .call( + "gmail.read", + &json!({"accountId":account,"id":id,"full":true}), + ) + .await; + } + answer => answer?, + }; + let gate = store.fetch_gate(id)?; + let _guard = gate.lock().await; + let message = id.to_owned(); + if let Some(resource) = sync::disk(&store, move |s| s.complete_resource(&message)).await? { + return Ok(resource); + } + let message = id.to_owned(); + let partial = sync::disk(&store, move |s| s.resource(&message)).await?; + let cached = match partial { + Some(resource) => Some(resource), + None => crate::cache::resource::read(account, id) + .await + .ok() + .flatten(), + }; + let mut resource = match cached { + Some(resource) => resource, + None => { + gmail + .call( + "gmail.read", + &json!({"accountId":account,"id":id,"full":true}), + ) + .await? + } + }; + sync::hydrate_text(gmail, account, id, &mut resource, true).await?; + let saved = resource.clone(); + let saved = sync::disk(&store, move |s| { + let generation = + s.read(|db| Ok(store::state(db, "generation")?.parse().unwrap_or(1)))?; + s.put(&saved, generation) + }) + .await; + match saved { + Ok(()) | Err("local_disk_low" | "local_disk_full") => (), + Err(error) => return Err(error), + } + Ok(resource) + } + pub async fn call(&self, method: &str, params: &Value) -> Result { + let account = params["accountId"] + .as_str() + .filter(|s| !s.is_empty() && s.len() < 1024 && !s.chars().any(char::is_control)) + .ok_or("invalid_params")?; + validate(method, params, false)?; + let store = match self.store(account).await { + Err("private_fs_busy") => return ipc::request(account, method, params).await, + answer => answer?, + }; + let method = method.to_owned(); + let params = params.clone(); + sync::disk(&store, move |s| execute(s, &method, ¶ms)).await + } +} +impl Drop for LocalMail { + fn drop(&mut self) { + if let Ok(jobs) = self.jobs.lock() { + for job in jobs.values() { + job.abort(); + } + } + } +} +fn field<'a>(params: &'a Value, key: &str) -> Result<&'a str, &'static str> { + params[key] + .as_str() + .filter(|s| !s.is_empty() && s.len() <= 1024 && !s.chars().any(char::is_control)) + .ok_or("invalid_params") +} +fn strings(params: &Value, key: &str, limit: usize) -> Result, &'static str> { + let values = params[key] + .as_array() + .filter(|v| v.len() <= limit) + .ok_or("invalid_params")?; + values + .iter() + .map(|v| { + v.as_str() + .filter(|s| !s.is_empty() && s.len() <= 1024 && !s.chars().any(char::is_control)) + .map(str::to_owned) + .ok_or("invalid_params") + }) + .collect() +} + +fn validate(method: &str, params: &Value, internal: bool) -> Result<(), &'static str> { + let allowed: &[&str] = match method { + "local.list" => &["accountId", "query", "limit", "pageToken"], + "local.status" | "local.edits" | "local.overview" => &["accountId"], + "local.labelCounts" => &["accountId", "id"], + "local.pause" => &["accountId", "paused"], + "local.edit" => &[ + "accountId", + "ticket", + "ids", + "addLabelIds", + "removeLabelIds", + ], + "local.cancelEdit" | "local.dismissConflict" => &["accountId", "ticket"], + "local.resource" | "local.revision" if internal => &["accountId", "id"], + _ => return Err("unknown_method"), + }; + if params + .as_object() + .is_none_or(|p| p.keys().any(|key| !allowed.contains(&key.as_str()))) + { + return Err("invalid_params"); + } + field(params, "accountId")?; + if method == "local.list" { + super::local_mail::search::parse(params["query"].as_str().ok_or("invalid_params")?)?; + } + if method == "local.pause" && !params["paused"].is_boolean() { + return Err("invalid_params"); + } + if method == "local.edit" { + field(params, "ticket")?; + let ids = strings(params, "ids", 1000)?; + let add = strings(params, "addLabelIds", 100)?; + let remove = strings(params, "removeLabelIds", 100)?; + if ids.is_empty() + || ids.iter().collect::>().len() != ids.len() + || add.iter().any(|v| remove.contains(v)) + || add.iter().chain(&remove).any(|v| { + !matches!( + v.as_str(), + "UNREAD" | "STARRED" | "INBOX" | "TRASH" | "SPAM" | "IMPORTANT" + ) && !v.starts_with("Label_") + }) + { + return Err("invalid_params"); + } + } + Ok(()) +} + +fn execute(store: &Store, method: &str, params: &Value) -> Result { + validate(method, params, true)?; + match method { + "local.overview" => store.overview(), + "local.labelCounts" => store.label_counts(field(params, "id")?), + "local.dismissConflict" => { + store.dismiss_conflict(field(params, "ticket")?)?; + Ok(json!({"dismissed":true})) + } + "local.list" => { + let query = params["query"].as_str().ok_or("invalid_params")?; + let limit = params + .get("limit") + .map_or(Some(50), Value::as_u64) + .filter(|n| (1..=100000).contains(n)) + .ok_or("invalid_params")? as usize; + let cursor = params + .get("pageToken") + .map_or(Some(""), Value::as_str) + .ok_or("invalid_params")?; + store.list(query, limit, cursor) + } + "local.resource" => Ok(store + .complete_resource(field(params, "id")?)? + .unwrap_or(Value::Null)), + "local.revision" => Ok(json!(store.revision(field(params, "id")?)?)), + "local.status" => store.status(), + "local.edits" => store.edits(), + "local.pause" => { + let paused = params["paused"].as_bool().ok_or("invalid_params")?; + store.write(|db| { + store::set_state(db, "paused", if paused { "true" } else { "false" }) + })?; + store.status() + } + "local.edit" => { + let ticket = field(¶ms, "ticket")?; + let ids = strings(¶ms, "ids", 1000)?; + let add = strings(¶ms, "addLabelIds", 100)?; + let remove = strings(¶ms, "removeLabelIds", 100)?; + if ids.is_empty() || add.iter().any(|label| remove.contains(label)) { + return Err("invalid_params"); + } + store.edit(ticket, &ids, &add, &remove) + } + "local.cancelEdit" => { + store.cancel_edit(field(¶ms, "ticket")?)?; + Ok(json!({"cancelled":true})) + } + _ => Err("unknown_method"), + } +} diff --git a/src/local_mail/recovery_tests.rs b/src/local_mail/recovery_tests.rs new file mode 100644 index 000000000..d4ebabbd6 --- /dev/null +++ b/src/local_mail/recovery_tests.rs @@ -0,0 +1,290 @@ +use super::{ + store::{self, Store}, + sync, + tests::{directory, message}, +}; +use serde_json::json; +use std::{fs::File, path::PathBuf, sync::Arc}; + +struct Mailbox(PathBuf); +impl Mailbox { + fn new() -> Self { + Self(directory()) + } + fn open(&self) -> Arc { + Store::open(File::open(&self.0).unwrap()).unwrap() + } +} +impl Drop for Mailbox { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } +} +fn checkpoint(store: &Store, key: &str) -> String { + store.read(|db| store::state(db, key)).unwrap() +} +fn set(store: &Store, key: &str, value: &str) { + store.write(|db| store::set_state(db, key, value)).unwrap(); +} + +#[test] +fn inventory_and_history_checkpoints_survive_process_exit() { + if let Some(path) = std::env::var_os("MAGPIE_RECOVERY_CHILD") { + let store = Store::open(File::open(path).unwrap()).unwrap(); + match std::env::var("MAGPIE_RECOVERY_PHASE").unwrap().as_str() { + "inventory" => { + store.put(&message("seen", "cached body"), 1).unwrap(); + store + .put(&message("unvisited", "kept until reconciliation"), 1) + .unwrap(); + store + .edit("pending", &["unvisited".into()], &["STARRED".into()], &[]) + .unwrap(); + set(&store, "generation", "2"); + set(&store, "history", "100"); + sync::apply_inventory( + &store, + &json!({"messages":[{"id":"seen"},{"id":"download"}],"nextPageToken":"page-2"}), + "", + 2, + ) + .unwrap(); + } + "history" => { + assert_eq!(checkpoint(&store, "page"), "page-2"); + sync::apply_inventory(&store, &json!({"messages":[]}), "page-2", 2).unwrap(); + sync::apply_history( + &store, + &json!({"historyId":"200","nextPageToken":"history-2","history":[ + {"messagesAdded":[{"message":{"id":"arrived"}}]} + ]}), + "", + ) + .unwrap(); + } + _ => panic!("unknown recovery phase"), + } + std::process::exit(73); + } + let mailbox = Mailbox::new(); + for phase in ["inventory", "history"] { + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "local_mail::recovery_tests::inventory_and_history_checkpoints_survive_process_exit", "--nocapture"]) + .env("MAGPIE_RECOVERY_CHILD", &mailbox.0) + .env("MAGPIE_RECOVERY_PHASE", phase) + .output().unwrap(); + assert_eq!( + child.status.code(), + Some(73), + "{}\n{}", + String::from_utf8_lossy(&child.stdout), + String::from_utf8_lossy(&child.stderr) + ); + let store = mailbox.open(); + assert_eq!(checkpoint(&store, "history"), "100"); + assert!(store.resource("unvisited").unwrap().is_some()); + assert_eq!(store.status().unwrap()["inventoryComplete"], false); + assert_eq!(store.status().unwrap()["complete"], false); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + assert_eq!( + checkpoint(&store, "page"), + if phase == "inventory" { "page-2" } else { "" } + ); + assert_eq!( + checkpoint(&store, "historyPage"), + if phase == "history" { "history-2" } else { "" } + ); + assert_eq!( + store.status().unwrap()["pending"], + if phase == "inventory" { 1 } else { 2 } + ); + } + let store = mailbox.open(); + sync::apply_history(&store, &json!({"historyId":"200"}), "history-2").unwrap(); + assert_eq!(checkpoint(&store, "history"), "200"); + assert_eq!(store.status().unwrap()["inventoryComplete"], true); + assert_eq!( + store.status().unwrap()["complete"], + false, + "pending bodies prevent complete coverage" + ); + assert!(store.resource("seen").unwrap().is_some()); + assert!(store.resource("unvisited").unwrap().is_none()); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + assert_eq!( + store.edits().unwrap(), + json!([{"ticket":"pending","state":"conflict","error":"message_deleted","count":1}]) + ); + for id in ["download", "arrived"] { + store.put(&message(id, "download completed"), 2).unwrap(); + } + assert_eq!(store.status().unwrap()["complete"], true); + drop(store); + let reopened = mailbox.open(); + assert_eq!(reopened.status().unwrap()["complete"], true); + assert_eq!(reopened.status().unwrap()["editConflicts"], 1); + assert_eq!( + reopened.label_counts("INBOX").unwrap(), + json!({"total":3,"unread":3}) + ); +} + +#[test] +fn malformed_and_cyclic_inventory_pages_commit_nothing() { + let mailbox = Mailbox::new(); + let store = mailbox.open(); + store.put(&message("cached", "sentinel"), 1).unwrap(); + let invalid = + json!({"messages":[{"id":"cached"},{"id":"new-job"},{"id":""}],"nextPageToken":"next"}); + assert_eq!( + sync::apply_inventory(&store, &invalid, "", 2), + Err("gmail_invalid_response") + ); + assert_eq!(checkpoint(&store, "page"), ""); + assert_eq!(store.status().unwrap()["pending"], 0); + assert_eq!( + store + .read(|db| store::sql(db.query_row( + "SELECT generation FROM messages WHERE id='cached'", + [], + |row| row.get::<_, i64>(0) + ))) + .unwrap(), + 1 + ); + sync::apply_inventory( + &store, + &json!({"messages":[{"id":"cached"}],"nextPageToken":"next"}), + "", + 2, + ) + .unwrap(); + sync::apply_inventory( + &store, + &json!({"messages":[],"nextPageToken":"last"}), + "next", + 2, + ) + .unwrap(); + assert_eq!( + sync::apply_inventory( + &store, + &json!({"messages":[{"id":"forbidden"}],"nextPageToken":"next"}), + "last", + 2 + ), + Err("gmail_invalid_response") + ); + assert_eq!(checkpoint(&store, "page"), "last"); + assert_eq!( + store.status().unwrap()["pending"], + 0, + "refused page must not enqueue its messages" + ); + assert_eq!(store.status().unwrap()["inventoryComplete"], false); +} + +#[test] +fn expired_history_preserves_mail_and_intents_until_new_inventory_finishes() { + let mailbox = Mailbox::new(); + { + let store = mailbox.open(); + store + .put(&message("retained", "offline needle"), 7) + .unwrap(); + store + .edit( + "offline-star", + &["retained".into()], + &["STARRED".into()], + &[], + ) + .unwrap(); + for (key, value) in [ + ("generation", "7"), + ("history", "expired"), + ("historyPage", "old-history-page"), + ("page", "old-inventory-page"), + ("inventoryListed", "true"), + ("inventoryComplete", "true"), + ] { + set(&store, key, value); + } + store + .write(|db| { + store::sql(db.execute("INSERT INTO history_pages VALUES('old-history-page')", []))?; + store::sql(db.execute( + "INSERT INTO inventory_pages VALUES(7,'old-inventory-page')", + [], + ))?; + Ok(()) + }) + .unwrap(); + sync::restart_inventory(&store).unwrap(); + } + let store = mailbox.open(); + assert_eq!(checkpoint(&store, "generation"), "8"); + for key in ["history", "historyPage", "page"] { + assert_eq!(checkpoint(&store, key), ""); + } + assert_eq!(store.status().unwrap()["complete"], false); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + assert_eq!( + store.list("needle is:starred", 50, "").unwrap()["summaries"][0]["id"], + "retained" + ); + sync::apply_inventory( + &store, + &json!({"messages":[{"id":"retained"}],"nextPageToken":"old-inventory-page"}), + "", + 8, + ) + .unwrap(); + sync::apply_inventory(&store, &json!({"messages":[]}), "old-inventory-page", 8).unwrap(); + sync::apply_history( + &store, + &json!({"historyId":"new","nextPageToken":"old-history-page"}), + "", + ) + .unwrap(); + assert_eq!(store.status().unwrap()["inventoryComplete"], false); + sync::apply_history(&store, &json!({"historyId":"new"}), "old-history-page").unwrap(); + assert_eq!(store.status().unwrap()["complete"], true); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + store.cancel_edit("offline-star").unwrap(); + assert_eq!( + store.list("is:starred", 50, "").unwrap()["summaries"], + json!([]) + ); + assert!(store.complete_resource("retained").unwrap().is_some()); +} + +#[test] +fn saved_bodies_counts_and_undo_remain_available_after_sync_auth_failure() { + let mailbox = Mailbox::new(); + { + let store = mailbox.open(); + store.put(&message("saved", "offline needle"), 1).unwrap(); + store + .edit("read-offline", &["saved".into()], &[], &["UNREAD".into()]) + .unwrap(); + set(&store, "error", "gmail_auth_required"); + } + let store = mailbox.open(); + assert_eq!(store.status().unwrap()["error"], "gmail_auth_required"); + assert!(store.complete_resource("saved").unwrap().is_some()); + assert_eq!( + store.list("needle", 50, "").unwrap()["summaries"][0]["unread"], + false + ); + assert_eq!( + store.label_counts("INBOX").unwrap(), + json!({"total":1,"unread":0}) + ); + store.cancel_edit("read-offline").unwrap(); + assert_eq!( + store.label_counts("INBOX").unwrap(), + json!({"total":1,"unread":1}) + ); + assert_eq!(store.overview().unwrap()["unread"], 1); +} diff --git a/src/local_mail/schema.sql b/src/local_mail/schema.sql new file mode 100644 index 000000000..c2e59acad --- /dev/null +++ b/src/local_mail/schema.sql @@ -0,0 +1,57 @@ +CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + date INTEGER NOT NULL, + summary TEXT NOT NULL, + blob TEXT NOT NULL, + server_labels TEXT NOT NULL, + sender TEXT NOT NULL, + recipients TEXT NOT NULL, + copied TEXT NOT NULL, + subject TEXT NOT NULL, + filenames TEXT NOT NULL, + has_attachment INTEGER NOT NULL, + text_complete INTEGER NOT NULL, + generation INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS message_date ON messages(date DESC, id DESC); +CREATE TABLE IF NOT EXISTS labels ( + message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + label TEXT NOT NULL, + PRIMARY KEY(message_id, label) +); +CREATE INDEX IF NOT EXISTS label_messages ON labels(label, message_id); +CREATE TABLE IF NOT EXISTS label_names (id TEXT PRIMARY KEY, name TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS jobs ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL DEFAULT 'content', + priority INTEGER NOT NULL DEFAULT 0, + error TEXT NOT NULL DEFAULT '', + retry_at INTEGER NOT NULL DEFAULT 0, + generation INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS job_priority ON jobs(priority DESC, retry_at); +CREATE TABLE IF NOT EXISTS edits ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + ticket TEXT NOT NULL, + id TEXT NOT NULL, + additions TEXT NOT NULL, + removals TEXT NOT NULL, + before_labels TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'queued', + error TEXT NOT NULL DEFAULT '' +); +CREATE INDEX IF NOT EXISTS edit_message ON edits(id, sequence); +CREATE INDEX IF NOT EXISTS edit_ticket ON edits(ticket); +CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5( + id UNINDEXED, subject, sender, recipients, copied, filenames, body, + tokenize='unicode61 remove_diacritics 2', prefix='2 3 4' +); +PRAGMA user_version=1; + +CREATE TABLE IF NOT EXISTS inventory_pages(generation INTEGER NOT NULL,token TEXT NOT NULL,PRIMARY KEY(generation,token)); + +CREATE INDEX IF NOT EXISTS complete_messages ON messages(text_complete); + +CREATE TABLE IF NOT EXISTS history_pages(token TEXT PRIMARY KEY); diff --git a/src/local_mail/search.rs b/src/local_mail/search.rs new file mode 100644 index 000000000..c43b5fd9f --- /dev/null +++ b/src/local_mail/search.rs @@ -0,0 +1,225 @@ +use chrono::{Local, NaiveDate, TimeZone}; +use rusqlite::types::Value; + +pub(super) struct Query { + pub sql: String, + pub values: Vec, + matches: Vec, +} +impl Query { + pub(super) fn choose_plan(&mut self, db: &rusqlite::Connection) -> Result<(), &'static str> { + for index in &self.matches { + let count: i64 = super::store::sql(db.query_row( + "SELECT count(*) FROM (SELECT rowid FROM search WHERE search MATCH ?1 LIMIT 10001)", + [&self.values[index - 1]], + |r| r.get(0), + ))?; + if count > 10000 { + self.sql = self.sql.replace( + &format!("m.rowid IN (SELECT rowid FROM search WHERE search MATCH ?{index})"), + &format!( + "EXISTS(SELECT 1 FROM search WHERE rowid=m.rowid AND search MATCH ?{index})" + ), + ); + } + } + Ok(()) + } +} +pub(super) fn parse(input: &str) -> Result { + if input.len() > 32768 || input.chars().any(char::is_control) { + return Err("local_search_unsupported"); + } + let mut tokens = Vec::new(); + let mut word = String::new(); + let mut quoted = false; + for ch in input.chars() { + if ch == '"' { + quoted = !quoted; + word.push(ch); + } else if ch.is_whitespace() && !quoted { + if !word.is_empty() { + tokens.push(std::mem::take(&mut word)); + } + } else { + word.push(ch); + } + } + if quoted { + return Err("local_search_unsupported"); + } + if !word.is_empty() { + tokens.push(word); + } + if tokens.len() > 128 { + return Err("local_search_unsupported"); + } + let mut query = Query { + sql: String::new(), + values: Vec::new(), + matches: Vec::new(), + }; + let mut groups = Vec::new(); + let mut terms = Vec::new(); + let mut anywhere = false; + for token in tokens { + if token == "OR" { + if terms.is_empty() { + return Err("local_search_unsupported"); + } + groups.push(format!("({})", terms.join(" AND "))); + terms.clear(); + continue; + } + let negative = token.starts_with('-'); + let token = token.strip_prefix('-').unwrap_or(&token); + if token.is_empty() || token.contains(['(', ')', '{', '}']) { + return Err("local_search_unsupported"); + } + let (field, text) = if token.starts_with('"') { + ("", token) + } else { + token.split_once(':').unwrap_or(("", token)) + }; + let text = text.trim_matches('"'); + if text.is_empty() { + return Err("local_search_unsupported"); + } + let predicate = match field { + "in" if matches!(text, "anywhere" | "all") => { + anywhere = true; + "1".into() + } + "in" | "label" | "is" => { + let label = match text.to_lowercase().as_str() { + "inbox" => "INBOX", + "sent" => "SENT", + "draft" | "drafts" => "DRAFT", + "trash" => "TRASH", + "spam" => "SPAM", + "unread" => "UNREAD", + "starred" => "STARRED", + "important" => "IMPORTANT", + _ if field == "label" => text, + _ => return Err("local_search_unsupported"), + }; + if matches!(label, "SPAM" | "TRASH") && !negative { + anywhere = true; + } + query.values.push(Value::Text(label.into())); + let n = query.values.len(); + format!( + "EXISTS(SELECT 1 FROM labels l WHERE l.message_id=m.id AND (l.label=?{n} OR l.label IN (SELECT id FROM label_names WHERE name=?{n} COLLATE NOCASE)))" + ) + } + "has" if text == "attachment" => "m.has_attachment=1".into(), + "category" + if matches!( + text, + "personal" | "social" | "promotions" | "updates" | "forums" + ) => + { + query + .values + .push(Value::Text(format!("CATEGORY_{}", text.to_uppercase()))); + format!( + "EXISTS(SELECT 1 FROM labels l WHERE l.message_id=m.id AND l.label=?{})", + query.values.len() + ) + } + "before" | "after" => { + let date = NaiveDate::parse_from_str(&text.replace('/', "-"), "%Y-%m-%d") + .map_err(|_| "local_search_unsupported")?; + let date = Local + .from_local_datetime( + &date + .and_hms_opt(0, 0, 0) + .ok_or("local_search_unsupported")?, + ) + .earliest() + .ok_or("local_search_unsupported")?; + query.values.push(Value::Integer(date.timestamp_millis())); + format!( + "m.date{}?{}", + if field == "before" { "<" } else { ">=" }, + query.values.len() + ) + } + "from" | "to" | "cc" | "filename" => { + let column = match field { + "from" => "sender", + "to" => "recipients", + "cc" => "copied", + _ => "filenames", + }; + let value = text + .to_lowercase() + .replace('\\', "\\\\") + .replace('%', "\\%") + .replace('_', "\\_"); + query.values.push(Value::Text(format!("%{value}%"))); + format!("m.{column} LIKE ?{} ESCAPE '\\'", query.values.len()) + } + "" | "subject" => { + let prefix = text.ends_with('*') && !token.ends_with('"'); + let text = if prefix { + &text[..text.len() - 1] + } else { + text + }; + if text.contains('*') || text.is_empty() { + return Err("local_search_unsupported"); + } + let term = format!( + "{}\"{}\"{}", + if field == "subject" { "subject:" } else { "" }, + text.replace('"', "\"\""), + if prefix { "*" } else { "" } + ); + query.values.push(Value::Text(term)); + query.matches.push(query.values.len()); + format!( + "m.rowid IN (SELECT rowid FROM search WHERE search MATCH ?{})", + query.values.len() + ) + } + _ => return Err("local_search_unsupported"), + }; + terms.push(if negative { + format!("NOT ({predicate})") + } else { + format!("({predicate})") + }); + } + if terms.is_empty() && !groups.is_empty() { + return Err("local_search_unsupported"); + } + if !terms.is_empty() { + groups.push(format!("({})", terms.join(" AND "))); + } + query.sql = if groups.is_empty() { + "1".into() + } else { + format!("({})", groups.join(" OR ")) + }; + if !anywhere { + query.sql.push_str(" AND NOT EXISTS(SELECT 1 FROM labels l WHERE l.message_id=m.id AND l.label IN ('SPAM','TRASH'))"); + } + Ok(query) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn search_values_never_become_sql() { + let query = parse("from:\"x' OR 1=1 --\" subject:\"a b\" -is:unread OR café*").unwrap(); + assert!(!query.sql.contains("x'")); + assert_eq!(query.values.len(), 4); + assert!(query.sql.contains("NOT (")); + assert!(parse("larger:1M").is_err()); + assert!(parse("\"unclosed").is_err()); + assert!(parse("a OR").is_err()); + assert!(parse("a*b").is_err()); + } +} diff --git a/src/local_mail/store.rs b/src/local_mail/store.rs new file mode 100644 index 000000000..5fe38761a --- /dev/null +++ b/src/local_mail/store.rs @@ -0,0 +1,485 @@ +use super::{content, search, vfs}; +use crate::{message::content::header, platform::private_fs as fs}; +use rusqlite::{Connection, OptionalExtension, params, params_from_iter}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::{ + fs::File, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, +}; +type Result = std::result::Result; + +pub(super) struct Store { + writer: Mutex, + readers: Vec>, + next_reader: AtomicUsize, + vfs: Arc, + pub(super) listener: Mutex>>, + fetches: Mutex>>>, +} +pub(super) fn sql(value: rusqlite::Result) -> Result { + value.map_err(|error| match error.sqlite_error_code() { + Some(rusqlite::ErrorCode::DiskFull) => "local_disk_full", + Some(rusqlite::ErrorCode::DatabaseCorrupt | rusqlite::ErrorCode::NotADatabase) => { + "local_storage_corrupt" + } + _ => "local_storage_unavailable", + }) +} +pub(super) fn state(db: &Connection, key: &str) -> Result { + Ok(sql(db + .query_row("SELECT value FROM state WHERE key=?1", [key], |row| { + row.get(0) + }) + .optional())? + .unwrap_or_default()) +} +pub(super) fn set_state(db: &Connection, key: &str, value: &str) -> Result<()> { + sql(db.execute("INSERT INTO state VALUES(?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE state.value!=excluded.value", [key, value]))?; + Ok(()) +} +fn decode(value: &str) -> Result { + serde_json::from_str(value).map_err(|_| "local_storage_corrupt") +} +fn labels(value: &Value) -> Vec { + value + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() +} +pub(super) fn replace_labels(db: &Connection, id: &str, base: &Value) -> Result<()> { + let mut effective = labels(base); + let mut edits = sql(db.prepare("SELECT additions,removals FROM edits WHERE id=?1 AND state IN ('queued','sending') ORDER BY sequence"))?; + let changes = sql(edits.query_map([id], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }))?; + for change in changes { + let (add, remove) = sql(change)?; + let remove = labels(&decode(&remove)?); + effective.retain(|label| !remove.contains(label)); + for label in labels(&decode(&add)?) { + if !effective.contains(&label) { + effective.push(label); + } + } + } + sql(db.execute("DELETE FROM labels WHERE message_id=?1", [id]))?; + for label in effective { + sql(db.execute("INSERT INTO labels VALUES(?1,?2)", params![id, label]))?; + } + Ok(()) +} +fn current_labels(db: &Connection, id: &str) -> Result { + let mut statement = + sql(db.prepare("SELECT label FROM labels WHERE message_id=?1 ORDER BY label"))?; + let rows = sql(statement.query_map([id], |row| row.get::<_, String>(0)))?; + Ok(json!(sql(rows.collect::>>())?)) +} +fn update_summary(mut summary: Value, labels: Value) -> Value { + let ids = super::store::labels(&labels); + summary["labelIds"] = labels; + summary["unread"] = json!(ids.iter().any(|l| l == "UNREAD")); + summary["starred"] = json!(ids.iter().any(|l| l == "STARRED")); + summary["inInbox"] = json!(ids.iter().any(|l| l == "INBOX")); + summary +} +impl Store { + pub(super) fn open(directory: File) -> Result> { + if rusqlite::version_number() < 3_051_003 { + return Err("local_sqlite_update_required"); + } + let vfs = vfs::Vfs::new(directory)?; + let mut writer = vfs.connect()?; + let version: i64 = sql(writer + .connection + .pragma_query_value(None, "user_version", |r| r.get(0)))?; + if version > 1 { + return Err("local_schema_newer"); + } + let transaction = sql(writer.connection.transaction())?; + sql(transaction.execute_batch(include_str!("schema.sql")))?; + sql(transaction.commit())?; + let readers = (0..2) + .map(|_| vfs.connect().map(Mutex::new)) + .collect::>>()?; + Ok(Arc::new(Self { + writer: Mutex::new(writer), + readers, + next_reader: AtomicUsize::new(0), + vfs, + listener: Mutex::new(None), + fetches: Mutex::new(Default::default()), + })) + } + pub(super) fn fetch_gate(&self, id: &str) -> Result>> { + let mut fetches = self + .fetches + .lock() + .map_err(|_| "local_storage_unavailable")?; + fetches.retain(|_, gate| gate.strong_count() > 0); + if let Some(gate) = fetches.get(id).and_then(std::sync::Weak::upgrade) { + return Ok(gate); + } + let gate = Arc::new(tokio::sync::Mutex::new(())); + fetches.insert(id.to_owned(), Arc::downgrade(&gate)); + Ok(gate) + } + pub(super) fn read(&self, call: impl FnOnce(&Connection) -> Result) -> Result { + let reader = self.next_reader.fetch_add(1, Ordering::Relaxed) % self.readers.len(); + let reader = self.readers[reader] + .lock() + .map_err(|_| "local_storage_unavailable")?; + call(&reader.connection) + } + pub(super) fn write(&self, call: impl FnOnce(&Connection) -> Result) -> Result { + let mut writer = self + .writer + .lock() + .map_err(|_| "local_storage_unavailable")?; + let tx = sql(writer.connection.transaction())?; + let answer = call(&tx)?; + sql(tx.commit())?; + Ok(answer) + } + pub(super) fn directory(&self) -> &File { + self.vfs.directory() + } + pub(super) fn status(&self) -> Result { + self.read(|db| { + let (stored, complete): (i64,i64) = sql(db.query_row("SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM messages WHERE text_complete=1)", [], |r| Ok((r.get(0)?,r.get(1)?))))?; + let pending: i64 = sql(db.query_row("SELECT count(*) FROM jobs", [], |r| r.get(0)))?; + let failed: i64 = sql(db.query_row("SELECT count(*) FROM jobs WHERE error!=''", [], |r| r.get(0)))?; + let edits: i64 = sql(db.query_row("SELECT count(DISTINCT ticket) FROM edits WHERE state IN ('queued','sending')", [], |r| r.get(0)))?; + let conflicts: i64 = sql(db.query_row("SELECT count(DISTINCT ticket) FROM edits WHERE state='conflict'",[],|r|r.get(0)))?; + let inventory = state(db,"inventoryComplete")? == "true"; + Ok(json!({"stored":stored,"textComplete":complete,"pending":pending,"failed":failed, + "pendingEdits":edits,"editConflicts":conflicts,"inventoryComplete":inventory,"complete":inventory && pending==0 && stored==complete, + "paused":state(db,"paused")?=="true","error":state(db,"error")?,"updated":state(db,"updated")?, + "estimatedTotal":state(db,"estimate")?.parse::().unwrap_or(0)})) + }) + } + pub(super) fn label_counts(&self, id: &str) -> Result { + self.read(|db| { + let total:i64=sql(db.query_row("SELECT count(*) FROM labels WHERE label=?1",[id],|r|r.get(0)))?; + let unread:i64=sql(db.query_row("SELECT count(*) FROM labels a JOIN labels b ON a.message_id=b.message_id AND b.label='UNREAD' WHERE a.label=?1",[id],|r|r.get(0)))?; + Ok(json!({"total":total,"unread":unread})) + }) + } + pub(super) fn overview(&self) -> Result { + let mut result = self.list( + "in:inbox is:unread -category:social -category:promotions -category:forums", + 3, + "", + )?; + let query = search::parse( + "in:inbox is:unread -category:social -category:promotions -category:forums", + )?; + self.read(|db| { + result["unread"] = json!(sql(db.query_row( + &format!("SELECT count(*) FROM messages m WHERE {}", query.sql), + params_from_iter(query.values.iter()), + |r| r.get::<_, i64>(0) + ))?); + result["labels"] = + serde_json::from_str::(&state(db, "labels")?).unwrap_or(json!([])); + result["profile"] = + serde_json::from_str::(&state(db, "profile")?).unwrap_or(Value::Null); + Ok(()) + })?; + Ok(result) + } + pub(super) fn dismiss_conflict(&self, ticket: &str) -> Result<()> { + self.write(|db| { + sql(db.execute( + "UPDATE edits SET state='dismissed' WHERE ticket=?1 AND state='conflict'", + [ticket], + ))?; + Ok(()) + }) + } + pub(super) fn list(&self, input: &str, limit: usize, cursor: &str) -> Result { + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + let fingerprint = format!("{:x}", Sha256::digest(input.as_bytes())); + let mut query = search::parse(input)?; + if !cursor.is_empty() { + if cursor.len() > 4096 { + return Err("invalid_params"); + } + let bytes = URL_SAFE_NO_PAD + .decode(cursor) + .map_err(|_| "invalid_params")?; + let (date, id, owner): (i64, String, String) = + serde_json::from_slice(&bytes).map_err(|_| "invalid_params")?; + if owner != fingerprint { + return Err("invalid_params"); + } + query.values.push(rusqlite::types::Value::Integer(date)); + let n = query.values.len(); + query.values.push(rusqlite::types::Value::Text(id)); + query + .sql + .push_str(&format!(" AND (m.date,m.id)<(?{n},?{})", n + 1)); + } + let (rows, more) = self.read(|db| { + query.choose_plan(db)?; + let statement = format!("SELECT m.id,m.summary,m.date FROM messages m WHERE {} ORDER BY m.date DESC,m.id DESC LIMIT {}", query.sql, limit+1); + let mut statement = sql(db.prepare(&statement))?; + let rows = sql(statement.query_map(params_from_iter(query.values.iter()), |r| Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,i64>(2)?))))?; + let mut values = Vec::new(); + let mut size = 0; + let mut more = false; + for row in rows { + let (id, summary, date) = sql(row)?; + if values.len() == limit || size + summary.len() > 16 * 1024 * 1024 { + if values.is_empty() { return Err("local_content_too_large"); } + more = true; + break; + } + size += summary.len(); + values.push((update_summary(decode(&summary)?, current_labels(db, &id)?),date,id)); + } + Ok((values, more)) + })?; + let next = if more { + let (_, date, id) = rows.last().ok_or("local_content_invalid")?; + URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&(date, id, &fingerprint)).map_err(|_| "invalid_params")?, + ) + } else { + String::new() + }; + Ok( + json!({"summaries":rows.into_iter().take(limit).map(|(summary,_,_)|summary).collect::>(), + "nextPageToken":next,"coverage":self.status()?}), + ) + } + fn blob_dir(&self, hash: &str, create: bool) -> Result> { + if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("local_storage_corrupt"); + } + let Some(blobs) = fs::open_dir(self.directory(), "blobs".as_ref(), create, true)? else { + return Ok(None); + }; + fs::open_dir(&blobs, hash[..2].as_ref(), create, true) + } + pub(super) fn resource(&self, id: &str) -> Result> { + let row = self.read(|db| { + let hash: Option = sql(db + .query_row("SELECT blob FROM messages WHERE id=?1", [id], |r| r.get(0)) + .optional())?; + hash.map(|hash| Ok((hash, current_labels(db, id)?))) + .transpose() + })?; + let Some((hash, labels)) = row else { + return Ok(None); + }; + let directory = self + .blob_dir(&hash, false)? + .ok_or("local_content_missing")?; + let file = fs::regular(&directory, &hash, false)?.ok_or("local_content_missing")?; + let mut bytes = Vec::new(); + file.take(128 * 1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "local_content_missing")?; + if bytes.len() > 128 * 1024 * 1024 || format!("{:x}", Sha256::digest(&bytes)) != hash { + return Err("local_content_invalid"); + } + let resource: Value = + serde_json::from_slice(&bytes).map_err(|_| "local_content_invalid")?; + if resource["id"] != id { + return Err("local_content_invalid"); + } + let mut resource = resource; + resource["labelIds"] = labels; + Ok(Some(resource)) + } + pub(super) fn complete_resource(&self, id: &str) -> Result> { + let complete = self.read(|db| { + sql(db.query_row( + "SELECT EXISTS(SELECT 1 FROM messages WHERE id=?1 AND text_complete=1)", + [id], + |r| r.get::<_, bool>(0), + )) + })?; + if !complete { + return Ok(None); + } + self.resource(id) + } + pub(super) fn revision(&self, id: &str) -> Result> { + self.read(|db| { + let hash: Option = sql(db + .query_row("SELECT blob FROM messages WHERE id=?1", [id], |r| r.get(0)) + .optional())?; + hash.map(|hash| Ok(format!("{hash}:{}", current_labels(db, id)?))) + .transpose() + }) + } + pub(super) fn put(&self, resource: &Value, generation: i64) -> Result<()> { + let id = resource["id"].as_str().ok_or("local_content_invalid")?; + if id.is_empty() || !resource["payload"].is_object() { + return Err("local_content_invalid"); + } + let bytes = serde_json::to_vec(resource).map_err(|_| "local_content_invalid")?; + if bytes.len() > 128 * 1024 * 1024 { + return Err("local_content_too_large"); + } + if fs::available_bytes(self.directory())? < 1024 * 1024 * 1024 + bytes.len() as u64 { + return Err("local_disk_low"); + } + let hash = format!("{:x}", Sha256::digest(&bytes)); + let directory = self + .blob_dir(&hash, true)? + .ok_or("local_storage_unavailable")?; + if fs::regular(&directory, &hash, false)?.is_none() { + fs::atomic_replace(&directory, &hash, &bytes)?; + } + let summary = + crate::message::content::summarize(resource, chrono::Utc::now().timestamp_millis())?; + let text = content::extract(resource); + let sender = header(resource, "from"); + let recipients = header(resource, "to"); + let copied = header(resource, "cc"); + let subject = header(resource, "subject"); + self.write(|db| { + sql(db.execute("INSERT INTO messages(id,thread_id,date,summary,blob,server_labels,sender,recipients,copied,subject,filenames,has_attachment,text_complete,generation) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14) ON CONFLICT(id) DO UPDATE SET thread_id=excluded.thread_id,date=excluded.date,summary=excluded.summary,blob=excluded.blob,server_labels=excluded.server_labels,sender=excluded.sender,recipients=excluded.recipients,copied=excluded.copied,subject=excluded.subject,filenames=excluded.filenames,has_attachment=excluded.has_attachment,text_complete=excluded.text_complete,generation=max(messages.generation,excluded.generation)", + params![id,resource["threadId"].as_str().unwrap_or(""),resource["internalDate"].as_str().and_then(|v|v.parse::().ok()).unwrap_or(0), + summary.to_string(),hash,resource["labelIds"].to_string(),sender.to_lowercase(),recipients.to_lowercase(),copied.to_lowercase(),subject,text.filenames.to_lowercase(),summary["hasAttachments"]==true,text.complete,generation]))?; + replace_labels(db,id,&resource["labelIds"])?; + sql(db.execute("DELETE FROM search WHERE rowid=(SELECT rowid FROM messages WHERE id=?1)",[id]))?; + sql(db.execute("INSERT INTO search(rowid,id,subject,sender,recipients,copied,filenames,body) VALUES((SELECT rowid FROM messages WHERE id=?1),?1,?2,?3,?4,?5,?6,?7)", + params![id,subject,sender,recipients,copied,text.filenames,text.body]))?; + if text.complete {sql(db.execute("DELETE FROM jobs WHERE id=?1",[id]))?;} + else {sql(db.execute("INSERT INTO jobs(id,error,retry_at,generation) VALUES(?1,'local_text_incomplete',?2,?3) ON CONFLICT(id) DO UPDATE SET error=excluded.error,retry_at=excluded.retry_at,kind='content'",params![id,chrono::Utc::now().timestamp_millis()+300_000,generation]))?;} + Ok(()) + }) + } + pub(super) fn metadata(&self, resource: &Value) -> Result<()> { + let id = resource["id"].as_str().ok_or("local_content_invalid")?; + let labels = resource["labelIds"] + .as_array() + .ok_or("local_content_invalid")?; + self.write(|db| { + let changed = sql(db.execute( + "UPDATE messages SET server_labels=?2 WHERE id=?1", + params![id, json!(labels).to_string()], + ))?; + if changed > 0 { + replace_labels(db, id, &json!(labels))?; + } + sql(db.execute("DELETE FROM jobs WHERE id=?1 AND kind='metadata'", [id]))?; + Ok(()) + }) + } + pub(super) fn delete(&self, id: &str) -> Result<()> { + self.write(|db| delete(db, id)) + } + pub(super) fn edits(&self) -> Result { + self.read(|db| { + let mut statement = sql(db.prepare("SELECT ticket,state,error,count(*) FROM edits GROUP BY ticket,state,error ORDER BY min(sequence)"))?; + let rows = sql(statement.query_map([], |r| Ok(json!({"ticket":r.get::<_,String>(0)?,"state":r.get::<_,String>(1)?,"error":r.get::<_,String>(2)?,"count":r.get::<_,i64>(3)?}))))?; + Ok(json!(sql(rows.collect::>>())?)) + }) + } + pub(super) fn edit( + &self, + ticket: &str, + ids: &[String], + add: &[String], + remove: &[String], + ) -> Result { + self.write(|db| { + let exists: bool = sql(db.query_row("SELECT EXISTS(SELECT 1 FROM edits WHERE ticket=?1)",[ticket],|r|r.get(0)))?; + if exists { + let mut statement=sql(db.prepare("SELECT id,additions,removals FROM edits WHERE ticket=?1 ORDER BY sequence"))?; + let rows=sql(sql(statement.query_map([ticket],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,String>(2)?))))?.collect::>>())?; + if rows.len()!=ids.len() || rows.iter().zip(ids).any(|((id,a,r),expected)| id!=expected || *a!=json!(add).to_string() || *r!=json!(remove).to_string()) { + return Err("local_edit_id_conflict"); + } + return Ok(json!({"ticket":ticket,"queued":true})); + } + for id in ids { + let base: Option = sql(db.query_row("SELECT server_labels FROM messages WHERE id=?1",[id],|r|r.get(0)).optional())?; + let before = current_labels(db,id)?; + sql(db.execute("INSERT INTO edits(ticket,id,additions,removals,before_labels) VALUES(?1,?2,?3,?4,?5)", + params![ticket,id,json!(add).to_string(),json!(remove).to_string(),before.to_string()]))?; + if let Some(base)=base {replace_labels(db,id,&decode(&base)?)?;} + else {sql(db.execute("INSERT INTO jobs(id,priority,generation) VALUES(?1,1000,0) ON CONFLICT(id) DO UPDATE SET priority=1000,retry_at=0",[id]))?;} + } + Ok(json!({"ticket":ticket,"queued":true})) + }) + } + pub(super) fn cancel_edit(&self, ticket: &str) -> Result<()> { + self.write(|db| { + let active: bool = sql(db.query_row( + "SELECT EXISTS(SELECT 1 FROM edits WHERE ticket=?1 AND state!='queued')", + [ticket], + |r| r.get(0), + ))?; + if active { + return Err("local_edit_already_started"); + } + let mut statement = sql(db.prepare("SELECT DISTINCT id FROM edits WHERE ticket=?1"))?; + let ids = sql( + sql(statement.query_map([ticket], |r| r.get::<_, String>(0)))? + .collect::>>(), + )?; + sql(db.execute("DELETE FROM edits WHERE ticket=?1", [ticket]))?; + for id in ids { + let base: Option = sql(db + .query_row( + "SELECT server_labels FROM messages WHERE id=?1", + [&id], + |r| r.get(0), + ) + .optional())?; + if let Some(base) = base { + replace_labels(db, &id, &decode(&base)?)?; + } + } + Ok(()) + }) + } + pub(super) fn claim_changes(&self, id: &str) -> Result> { + self.write(|db| { + let mut statement=sql(db.prepare("SELECT sequence,additions,removals FROM edits WHERE id=?1 AND state IN ('queued','sending') ORDER BY sequence"))?; + let rows=sql(sql(statement.query_map([id],|r|Ok((r.get::<_,i64>(0)?,r.get::<_,String>(1)?,r.get::<_,String>(2)?))))?.collect::>>())?; + let Some((last,_,_))=rows.last() else {return Ok(None)}; + let mut target=std::collections::BTreeMap::new(); + for (_,add,remove) in &rows { + for value in labels(&decode(add)?) {target.insert(value,true);} + for value in labels(&decode(remove)?) {target.insert(value,false);} + } + let add=target.iter().filter(|(_,add)|**add).map(|(label,_)|label).collect::>(); + let remove=target.iter().filter(|(_,add)|!**add).map(|(label,_)|label).collect::>(); + sql(db.execute("UPDATE edits SET state='sending' WHERE id=?1 AND sequence<=?2 AND state='queued'",params![id,last]))?; + Ok(Some((*last,json!(add),json!(remove)))) + }) + } +} +impl Drop for Store { + fn drop(&mut self) { + if let Ok(listener) = self.listener.get_mut() { + if let Some(task) = listener.take() { + task.abort(); + } + } + } +} +pub(super) fn delete(db: &Connection, id: &str) -> Result<()> { + sql(db.execute("UPDATE edits SET state='conflict',error='message_deleted' WHERE id=?1 AND state IN ('queued','sending')",[id]))?; + sql(db.execute( + "DELETE FROM search WHERE rowid=(SELECT rowid FROM messages WHERE id=?1)", + [id], + ))?; + sql(db.execute("DELETE FROM messages WHERE id=?1", [id]))?; + sql(db.execute("DELETE FROM jobs WHERE id=?1", [id]))?; + Ok(()) +} diff --git a/src/local_mail/sync.rs b/src/local_mail/sync.rs new file mode 100644 index 000000000..b2d0017ff --- /dev/null +++ b/src/local_mail/sync.rs @@ -0,0 +1,493 @@ +use super::store::{Store, delete, replace_labels, set_state, sql, state}; +use crate::providers::gmail; +use rusqlite::{OptionalExtension, params}; +use serde_json::{Value, json}; +use std::sync::Arc; +type Result = std::result::Result; +pub(super) async fn disk( + store: &Arc, + work: impl FnOnce(&Store) -> Result + Send + 'static, +) -> Result { + let store = store.clone(); + tokio::task::spawn_blocking(move || work(&store)) + .await + .map_err(|_| "local_storage_unavailable")? +} +fn valid_id(value: &Value) -> Result<&str> { + value + .as_str() + .filter(|v| !v.is_empty() && v.len() <= 1024 && !v.chars().any(char::is_control)) + .ok_or("gmail_invalid_response") +} +pub(super) async fn step( + store: &Arc, + gmail: &gmail::Session, + account: &str, + _tick: u64, +) -> Result { + if deliver_edit(store, gmail, account).await? { + return Ok(true); + } + if disk(store, |s| s.read(|db| Ok(state(db, "paused")? == "true"))).await? { + return Ok(false); + } + let legacy = disk(store, |s| { + s.read(|db| Ok((state(db, "legacyImported")?, state(db, "legacyCursor")?))) + }) + .await?; + if legacy.0 != "true" { + let next = crate::cache::resource::legacy_next(account, &legacy.1).await?; + disk(store, move |s| { + if let Some((cursor, resource)) = next { + if let Some(resource) = resource { + if s.revision(resource["id"].as_str().ok_or("local_content_invalid")?)? + .is_none() + { + s.put(&resource, 0)?; + } + } + s.write(|db| set_state(db, "legacyCursor", &cursor)) + } else { + s.write(|db| set_state(db, "legacyImported", "true")) + } + }) + .await?; + return Ok(true); + } + let mut history = disk(store, |s| s.read(|db| state(db, "history"))).await?; + if history.is_empty() { + let profile = gmail.replica_call(account, "profile", &json!({})).await?; + history = valid_id(&profile["historyId"])?.to_owned(); + let estimate = profile["messagesTotal"].as_u64().unwrap_or(0).to_string(); + let checkpoint = history.clone(); + disk(store, move |s|s.write(|db| { + set_state(db,"history",&checkpoint)?; + set_state(db,"estimate",&estimate)?; + set_state(db,"profile",&json!({"email":profile["emailAddress"],"messagesTotal":profile["messagesTotal"]}).to_string())?; + if state(db,"generation")?.is_empty() { set_state(db,"generation","1")?; } + Ok(()) + })).await?; + } + let due = disk(store, |s| { + s.read(|db| { + Ok(chrono::Utc::now().timestamp_millis() + - state(db, "lastHistory")?.parse::().unwrap_or(0) + >= 30_000) + }) + }) + .await?; + if due { + match changes(store, gmail, account, &history).await { + Err("gmail_not_found") => { + disk(store, restart_inventory).await?; + return Ok(true); + } + answer => answer?, + } + disk(store, |s| { + s.write(|db| { + if state(db, "historyPage")?.is_empty() { + set_state( + db, + "lastHistory", + &chrono::Utc::now().timestamp_millis().to_string(), + ) + } else { + Ok(()) + } + }) + }) + .await?; + let labels = gmail.replica_call(account, "labels", &json!({})).await?; + disk(store,move|s|s.write(|db| { + if !labels["labels"].is_array() {return Err("gmail_invalid_response");} + sql(db.execute("DELETE FROM label_names",[]))?; + set_state(db,"labels",&gmail::normalize_labels(labels.clone()).to_string())?; + for label in labels["labels"].as_array().into_iter().flatten() { + let id = valid_id(&label["id"])?; + let name = label["name"].as_str().unwrap_or(id); + sql(db.execute("INSERT INTO label_names VALUES(?1,?2) ON CONFLICT(id) DO UPDATE SET name=excluded.name",params![id,name]))?; + } + Ok(()) + })).await?; + } + let (complete, page, generation) = disk(store, |s| { + s.read(|db| { + Ok(( + state(db, "inventoryListed")? == "true", + state(db, "page")?, + state(db, "generation")?.parse::().unwrap_or(1), + )) + }) + }) + .await?; + if !complete { + let response = gmail + .replica_call(account, "inventory", &json!({"pageToken":page})) + .await?; + disk(store, move |s| { + apply_inventory(s, &response, &page, generation) + }) + .await?; + } + let job = disk(store,|s|s.read(|db| { + sql(db.query_row("SELECT id,kind,generation FROM jobs WHERE retry_at<=?1 ORDER BY priority DESC,rowid LIMIT 1", + [chrono::Utc::now().timestamp_millis()],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,i64>(2)?))).optional()) + })).await?; + let Some((id, kind, generation)) = job else { + return Ok(false); + }; + let gate = store.fetch_gate(&id)?; + let _guard = gate.lock().await; + let pending = id.clone(); + if !disk(store, move |s| { + s.read(|db| { + sql(db.query_row( + "SELECT EXISTS(SELECT 1 FROM jobs WHERE id=?1)", + [pending], + |r| r.get::<_, bool>(0), + )) + }) + }) + .await? + { + return Ok(true); + } + if disk(store, |s| { + crate::platform::private_fs::available_bytes(s.directory()) + }) + .await? + < 1024 * 1024 * 1024 + { + return Err("local_disk_low"); + } + let answer = if kind == "metadata" { + match gmail + .replica_call(account, "minimal", &json!({"id":id})) + .await + { + Ok(resource) => disk(store, move |s| s.metadata(&resource)).await, + Err(error) => Err(error), + } + } else { + let cached = crate::cache::resource::read(account, &id) + .await + .ok() + .flatten(); + let resource = match cached { + Some(v) => Ok(v), + None => { + gmail + .replica_call(account, "content", &json!({"id":id})) + .await + } + }; + match resource { + Ok(mut resource) => match hydrate_text(gmail, account, &id, &mut resource, false).await + { + Ok(()) => disk(store, move |s| s.put(&resource, generation)).await, + Err(e) => Err(e), + }, + Err(error) => Err(error), + } + }; + match answer { + Ok(()) => (), + Err("gmail_not_found") => { + disk(store, move |s| s.delete(&id)).await?; + } + Err(error) => { + disk(store, move |s| { + s.write(|db| { + sql(db.execute( + "UPDATE jobs SET error=?2,retry_at=?3 WHERE id=?1", + params![id, error, chrono::Utc::now().timestamp_millis() + 60_000], + ))?; + Ok(()) + }) + }) + .await?; + return Err(error); + } + } + Ok(true) +} +pub(super) fn restart_inventory(store: &Store) -> Result<()> { + store.write(|db| { + let generation = state(db, "generation")?.parse::().unwrap_or(0) + 1; + set_state(db, "generation", &generation.to_string())?; + set_state(db, "history", "")?; + set_state(db, "historyPage", "")?; + sql(db.execute("DELETE FROM history_pages", []))?; + sql(db.execute("DELETE FROM inventory_pages", []))?; + set_state(db, "page", "")?; + set_state(db, "inventoryListed", "false")?; + set_state(db, "inventoryComplete", "false") + }) +} +pub(super) fn apply_inventory( + store: &Store, + response: &Value, + page: &str, + generation: i64, +) -> Result<()> { + if response + .get("nextPageToken") + .is_some_and(|token| !token.is_string()) + { + return Err("gmail_invalid_response"); + } + let next = response["nextPageToken"].as_str().unwrap_or(""); + if !next.is_empty() && next == page { + return Err("gmail_invalid_response"); + } + if !response["messages"].is_array() + && !(response["messages"].is_null() + && response["resultSizeEstimate"] == 0 + && next.is_empty()) + { + return Err("gmail_invalid_response"); + } + store.write(|db| { + if !next.is_empty() + && sql(db.execute( + "INSERT OR IGNORE INTO inventory_pages VALUES(?1,?2)", + params![generation, next], + ))? == 0 + { + return Err("gmail_invalid_response"); + } + for message in response["messages"].as_array().into_iter().flatten() { + let id = valid_id(&message["id"])?; + let found = sql(db.execute( + "UPDATE messages SET generation=?2 WHERE id=?1", + params![id, generation], + ))?; + if found == 0 { + sql(db.execute( + "INSERT INTO jobs(id,generation) VALUES(?1,?2) ON CONFLICT(id) DO UPDATE SET generation=excluded.generation", + params![id, generation], + ))?; + } + } + set_state(db, "page", next)?; + if next.is_empty() { + set_state(db, "inventoryListed", "true")?; + } + Ok(()) + }) +} +async fn changes( + store: &Arc, + gmail: &gmail::Session, + account: &str, + history: &str, +) -> Result<()> { + let page = disk(store, |s| s.read(|db| state(db, "historyPage"))).await?; + let response = gmail + .replica_call( + account, + "history", + &json!({"historyId":history,"pageToken":page}), + ) + .await?; + disk(store, move |s| apply_history(s, &response, &page)).await +} +pub(super) fn apply_history(store: &Store, response: &Value, page: &str) -> Result<()> { + if !response.is_object() + || response + .get("nextPageToken") + .is_some_and(|v| !v.is_string()) + { + return Err("gmail_invalid_response"); + } + let next = response["nextPageToken"].as_str().unwrap_or("").to_owned(); + if !next.is_empty() && next == page { + return Err("gmail_invalid_response"); + } + let checkpoint = valid_id(&response["historyId"])?.to_owned(); + store.write(|db| { + let generation = state(db,"generation")?.parse::().unwrap_or(1); + if response.get("history").is_some_and(|v|!v.is_array()) {return Err("gmail_invalid_response");} + if !next.is_empty() && sql(db.execute("INSERT OR IGNORE INTO history_pages VALUES(?1)",[&next]))?==0 {return Err("gmail_invalid_response");} + for event in response["history"].as_array().into_iter().flatten() { + if !event.is_object() {return Err("gmail_invalid_response");} + for field in ["messagesAdded","messagesDeleted","labelsAdded","labelsRemoved"] { + if event.get(field).is_some_and(|v|!v.is_array()) {return Err("gmail_invalid_response");} + } + for added in event["messagesAdded"].as_array().into_iter().flatten() { + let id = valid_id(&added["message"]["id"])?; + sql(db.execute("INSERT INTO jobs(id,priority,generation) VALUES(?1,1000,?2) ON CONFLICT(id) DO UPDATE SET priority=1000,generation=excluded.generation",params![id,generation]))?; + sql(db.execute("UPDATE messages SET generation=?2 WHERE id=?1",params![id,generation]))?; + } + for kind in ["labelsAdded","labelsRemoved"] { + for changed in event[kind].as_array().into_iter().flatten() { + let id = valid_id(&changed["message"]["id"])?; + sql(db.execute("INSERT INTO jobs(id,kind,priority,generation) VALUES(?1,CASE WHEN EXISTS(SELECT 1 FROM messages WHERE id=?1) THEN 'metadata' ELSE 'content' END,100,?2) ON CONFLICT(id) DO UPDATE SET priority=max(priority,100),retry_at=0",params![id,generation]))?; + } + } + for removed in event["messagesDeleted"].as_array().into_iter().flatten() { + delete(db,valid_id(&removed["message"]["id"])?)?; + } + } + set_state(db,"historyPage",&next)?; + if next.is_empty() { + set_state(db,"history",&checkpoint)?; + sql(db.execute("DELETE FROM history_pages",[]))?; + if state(db,"inventoryListed")?=="true" && state(db,"inventoryComplete")?!="true" { + let mut statement=sql(db.prepare("SELECT id FROM messages WHERE generation(0)))?.collect::>>())?; + for id in missing {delete(db,&id)?;} + set_state(db,"inventoryComplete","true")?; + sql(db.execute("DELETE FROM inventory_pages",[]))?; + } + } + Ok(()) + }) +} +pub(super) async fn hydrate_text( + gmail: &gmail::Session, + account: &str, + id: &str, + resource: &mut Value, + foreground: bool, +) -> Result<()> { + let mut pending = vec!["/payload".to_owned()]; + while let Some(path) = pending.pop() { + let part = resource.pointer(&path).ok_or("gmail_invalid_response")?; + for index in 0..part["parts"].as_array().map_or(0, Vec::len) { + pending.push(format!("{path}/parts/{index}")); + } + let attachment = part["headers"] + .as_array() + .into_iter() + .flatten() + .any(|header| { + header["name"] + .as_str() + .is_some_and(|n| n.eq_ignore_ascii_case("content-disposition")) + && header["value"].as_str().is_some_and(|v| { + v.split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case("attachment") + }) + }); + if attachment + || !part["filename"].as_str().unwrap_or("").is_empty() + || !matches!(part["mimeType"].as_str(), Some("text/plain" | "text/html")) + || part["body"]["data"].is_string() + { + continue; + } + let Some(attachment) = part["body"]["attachmentId"].as_str() else { + continue; + }; + let answer = if foreground { + gmail + .call( + "gmail.attachment", + &json!({"accountId":account,"messageId":id,"attachmentId":attachment}), + ) + .await? + } else { + gmail + .replica_call( + account, + "attachment", + &json!({"id":id,"attachmentId":attachment}), + ) + .await? + }; + let data = answer["data"].as_str().ok_or("gmail_invalid_response")?; + resource + .pointer_mut(&path) + .ok_or("gmail_invalid_response")?["body"]["data"] = json!(data); + } + Ok(()) +} +async fn deliver_edit(store: &Arc, gmail: &gmail::Session, account: &str) -> Result { + let edit = disk(store,|s|s.read(|db| { + sql(db.query_row("SELECT id FROM edits WHERE state IN ('queued','sending') ORDER BY sequence LIMIT 1",[],|r|r.get::<_,String>(0)).optional()) + })).await?; + let Some(id) = edit else { return Ok(false) }; + let gate = store.fetch_gate(&id)?; + let _guard = gate.lock().await; + let before = match gmail + .replica_call(account, "minimal", &json!({"id":id})) + .await + { + Err("gmail_not_found") => { + disk(store, move |s| s.delete(&id)).await?; + return Ok(true); + } + answer => answer?, + }; + let claim = id.clone(); + let Some((sequence, add, remove)) = disk(store, move |s| s.claim_changes(&claim)).await? else { + return Ok(true); + }; + let current = before["labelIds"] + .as_array() + .ok_or("gmail_invalid_response")?; + let satisfied = add + .as_array() + .ok_or("local_storage_corrupt")? + .iter() + .all(|v| current.contains(v)) + && remove + .as_array() + .ok_or("local_storage_corrupt")? + .iter() + .all(|v| !current.contains(v)); + if !satisfied { + let delivery = gmail + .call_settled( + "gmail.modify", + &json!({"accountId":account,"id":id,"addLabelIds":add,"removeLabelIds":remove}), + ) + .await; + if let Err(error @ ("gmail_forbidden" | "invalid_params")) = delivery { + disk(store,move|s|s.write(|db| { + sql(db.execute("UPDATE edits SET state='conflict',error=?3 WHERE id=?1 AND sequence<=?2 AND state='sending'",params![id,sequence,error]))?; + if sql(db.query_row("SELECT EXISTS(SELECT 1 FROM messages WHERE id=?1)",[&id],|r|r.get::<_,bool>(0)))? { + replace_labels(db,&id,&before["labelIds"])?; + } + Ok(()) + })).await?; + return Ok(true); + } + delivery?; + } + let after = if satisfied { + before + } else { + gmail + .replica_call(account, "minimal", &json!({"id":id})) + .await? + }; + let current = after["labelIds"] + .as_array() + .ok_or("gmail_invalid_response")?; + if !add + .as_array() + .ok_or("local_storage_corrupt")? + .iter() + .all(|v| current.contains(v)) + || !remove + .as_array() + .ok_or("local_storage_corrupt")? + .iter() + .all(|v| !current.contains(v)) + { + return Err("local_edit_not_confirmed"); + } + disk(store,move|s|s.write(|db| { + sql(db.execute("UPDATE messages SET server_labels=?2 WHERE id=?1",params![id,after["labelIds"].to_string()]))?; + sql(db.execute("UPDATE edits SET state='done',error='' WHERE id=?1 AND sequence<=?2 AND state='sending'",params![id,sequence]))?; + if sql(db.query_row("SELECT EXISTS(SELECT 1 FROM messages WHERE id=?1)",[&id],|r|r.get::<_,bool>(0)))? {replace_labels(db,&id,&after["labelIds"])?;} + Ok(()) + })).await?; + Ok(true) +} diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs new file mode 100644 index 000000000..2b209d00b --- /dev/null +++ b/src/local_mail/tests.rs @@ -0,0 +1,399 @@ +use super::*; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use std::{ + fs::File, + sync::atomic::{AtomicU64, Ordering}, +}; +static SERIAL: AtomicU64 = AtomicU64::new(0); +pub(super) fn directory() -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "magpie-local-{}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(), + SERIAL.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&path).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + path +} +pub(super) fn message(id: &str, text: &str) -> Value { + json!({"id":id,"threadId":"thread","labelIds":["INBOX","UNREAD"],"internalDate":"1700000000000", + "payload":{"mimeType":"text/plain","headers":[{"name":"From","value":"Alice "},{"name":"Subject","value":"Café 合成"}], + "body":{"data":URL_SAFE_NO_PAD.encode(text),"size":text.len()}}}) +} +#[test] +fn local_mail_search_and_edits_survive_restart() { + let path = directory(); + { + let store = Store::open(File::open(&path).unwrap()).unwrap(); + store + .put(&message("one", "Offline café needles"), 1) + .unwrap(); + store.put(&message("two", "Other body"), 1).unwrap(); + assert_eq!( + store.list("\"café needles\"", 50, "").unwrap()["summaries"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + store.list("from:alice café", 50, "").unwrap()["summaries"] + .as_array() + .unwrap() + .len(), + 2 + ); + store + .edit("ticket", &["one".into()], &[], &["UNREAD".into()]) + .unwrap(); + assert_eq!( + store.list("is:unread", 50, "").unwrap()["summaries"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + store.resource("one").unwrap().unwrap()["labelIds"], + json!(["INBOX"]) + ); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + assert!( + Store::open(File::open(&path).unwrap()).is_err(), + "another owner must not open the database" + ); + } + { + let store = Store::open(File::open(&path).unwrap()).unwrap(); + assert_eq!( + store.resource("one").unwrap().unwrap()["labelIds"], + json!(["INBOX"]) + ); + store.cancel_edit("ticket").unwrap(); + assert_eq!( + store.list("is:unread", 50, "").unwrap()["summaries"] + .as_array() + .unwrap() + .len(), + 2 + ); + store.delete("two").unwrap(); + assert_eq!( + store.list("", 50, "").unwrap()["summaries"] + .as_array() + .unwrap() + .len(), + 1 + ); + } + std::fs::remove_dir_all(path).unwrap(); +} +#[test] +fn all_inline_text_parts_are_indexed_and_missing_text_is_explicit() { + let text = |value: &str| json!({"mimeType":"text/plain","body":{"data":URL_SAFE_NO_PAD.encode(value)}}); + let resource = json!({"payload":{"mimeType":"multipart/mixed","parts":[text("first"),text("last"),{"mimeType":"text/html","body":{"attachmentId":"external","size":10}},{"mimeType":"text/plain","filename":"file.txt","body":{"data":URL_SAFE_NO_PAD.encode("private-file-text")}}]}}); + let result = content::extract(&resource); + assert!(result.body.contains("first") && result.body.contains("last")); + assert!(!result.body.contains("private-file-text")); + assert!(!result.complete); +} +#[cfg(unix)] +#[test] +fn database_and_sidecar_links_never_touch_their_targets() { + use std::os::unix::fs::symlink; + for name in ["mail.sqlite", "mail.sqlite-wal", "mail.sqlite-journal"] { + let path = directory(); + let target = path.join("untouched"); + std::fs::write(&target, b"secret sentinel").unwrap(); + symlink(&target, path.join(name)).unwrap(); + let result = Store::open(File::open(&path).unwrap()); + assert!(result.is_err(), "{name}"); + assert_eq!(std::fs::read(&target).unwrap(), b"secret sentinel"); + std::fs::remove_dir_all(path).unwrap(); + } +} +#[test] +fn sqlite_cannot_attach_a_path_outside_its_directory() { + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + let escaped = path.join("escaped"); + assert!( + store + .write(|db| { + store::sql( + db.execute("ATTACH DATABASE ?1 AS escaped", [escaped.to_str().unwrap()]), + )?; + Ok(()) + }) + .is_err() + ); + assert!(!escaped.exists()); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +fn coalescing_preserves_latest_intent_and_undo_stops_before_claim() { + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + store.put(&message("one", "body"), 1).unwrap(); + store + .edit("star", &["one".into()], &["STARRED".into()], &[]) + .unwrap(); + store + .edit("unstar", &["one".into()], &[], &["STARRED".into()]) + .unwrap(); + store + .edit("read", &["one".into()], &[], &["UNREAD".into()]) + .unwrap(); + store.cancel_edit("read").unwrap(); + let (_, add, remove) = store.claim_changes("one").unwrap().unwrap(); + assert_eq!(add, json!([])); + assert_eq!(remove, json!(["STARRED"])); + assert_eq!(store.cancel_edit("star"), Err("local_edit_already_started")); + assert_eq!( + store.resource("one").unwrap().unwrap()["labelIds"], + json!(["INBOX", "UNREAD"]) + ); + assert_eq!( + store.edit("star", &["one".into()], &[], &["STARRED".into()]), + Err("local_edit_id_conflict") + ); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +fn missing_text_is_retryable_and_paging_never_repeats_the_previous_page() { + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + for id in ["one", "two", "three"] { + store.put(&message(id, "body"), 1).unwrap(); + } + let first = store.list("", 2, "").unwrap(); + let second = store + .list("", 2, first["nextPageToken"].as_str().unwrap()) + .unwrap(); + assert_eq!(second["summaries"].as_array().unwrap().len(), 1); + assert!( + !first["summaries"] + .as_array() + .unwrap() + .iter() + .any(|v| v["id"] == second["summaries"][0]["id"]) + ); + assert!( + store + .list("other", 2, first["nextPageToken"].as_str().unwrap()) + .is_err() + ); + let mut missing = message("missing", "body"); + missing["payload"]["body"] = json!({"size":20,"attachmentId":"text-part"}); + store.put(&missing, 1).unwrap(); + assert!(store.resource("missing").unwrap().is_some()); + assert!(store.complete_resource("missing").unwrap().is_none()); + assert!(store.complete_resource("one").unwrap().is_some()); + let status = store.status().unwrap(); + assert_eq!(status["stored"], 4); + assert_eq!(status["textComplete"], 3); + assert_eq!(status["failed"], 1); + assert_eq!(status["complete"], false); + store + .edit( + "unfetched", + &["online-search-result".into()], + &["STARRED".into()], + &[], + ) + .unwrap(); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + store.cancel_edit("unfetched").unwrap(); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +fn malformed_history_rolls_back_jobs_deletions_and_checkpoint() { + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + store.put(&message("kept", "sentinel"), 1).unwrap(); + store + .write(|db| store::set_state(db, "history", "100")) + .unwrap(); + let invalid = json!({"historyId":"200","history":[{"messagesDeleted":[{"message":{"id":"kept"}}]},{"messagesAdded":"invalid"}]}); + assert!(sync::apply_history(&store, &invalid, "").is_err()); + assert!(store.resource("kept").unwrap().is_some()); + assert_eq!(store.read(|db| store::state(db, "history")).unwrap(), "100"); + let page = json!({"historyId":"200","nextPageToken":"next","history":[{"messagesAdded":[{"message":{"id":"new"}}]}]}); + sync::apply_history(&store, &page, "").unwrap(); + assert_eq!(store.status().unwrap()["pending"], 1); + assert!(sync::apply_history(&store, &page, "other").is_err()); + assert_eq!(store.read(|db| store::state(db, "history")).unwrap(), "100"); + sync::apply_history(&store, &json!({"historyId":"200"}), "next").unwrap(); + assert_eq!(store.read(|db| store::state(db, "history")).unwrap(), "200"); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +fn large_summary_pages_keep_a_continuation_and_reject_an_oversized_single_row() { + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + for id in ["a", "b"] { + store.put(&message(id, "body"), 1).unwrap(); + let summary = json!({"id":id,"subject":"x".repeat(9*1024*1024)}).to_string(); + store + .write(|db| { + store::sql(db.execute( + "UPDATE messages SET summary=?2 WHERE id=?1", + rusqlite::params![id, summary], + ))?; + Ok(()) + }) + .unwrap(); + } + let first = store.list("in:inbox", 50, "").unwrap(); + assert_eq!(first["summaries"].as_array().unwrap().len(), 1); + let second = store + .list("in:inbox", 50, first["nextPageToken"].as_str().unwrap()) + .unwrap(); + assert_eq!(second["summaries"].as_array().unwrap().len(), 1); + assert_ne!(first["summaries"][0]["id"], second["summaries"][0]["id"]); + assert_eq!(second["nextPageToken"], ""); + store + .write(|db| { + store::sql(db.execute( + "UPDATE messages SET summary=?1 WHERE id='b'", + [json!({"id":"b","subject":"x".repeat(17*1024*1024)}).to_string()], + ))?; + Ok(()) + }) + .unwrap(); + assert_eq!( + store.list("in:inbox", 50, ""), + Err("local_content_too_large") + ); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +fn committed_mail_and_queued_edits_survive_process_exit_without_checkpoint() { + if let Some(path) = std::env::var_os("MAGPIE_WAL_CHILD") { + let store = Store::open(File::open(path).unwrap()).unwrap(); + store + .put(&message("durable", "committed needle"), 1) + .unwrap(); + store + .edit( + "durable-edit", + &["durable".into()], + &["STARRED".into()], + &[], + ) + .unwrap(); + std::process::exit(73); + } + let path = directory(); + let child=std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact","local_mail::tests::committed_mail_and_queued_edits_survive_process_exit_without_checkpoint","--nocapture"]) + .env("MAGPIE_WAL_CHILD",&path).output().unwrap(); + assert_eq!( + child.status.code(), + Some(73), + "{}", + String::from_utf8_lossy(&child.stdout) + ); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + assert_eq!( + store.list("needle is:starred", 50, "").unwrap()["summaries"][0]["id"], + "durable" + ); + assert_eq!(store.status().unwrap()["pendingEdits"], 1); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} + +#[test] +#[ignore = "synthetic 100k/1m latency benchmark; run explicitly"] +fn benchmark_local_queries() { + use std::time::Instant; + let count = std::env::var("MAGPIE_BENCH_MESSAGES") + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(100_000); + assert!((1..=1_000_000).contains(&count)); + let path = directory(); + let store = Store::open(File::open(&path).unwrap()).unwrap(); + let started = Instant::now(); + store.write(|db| { + let mut messages=store::sql(db.prepare("INSERT INTO messages(id,thread_id,date,summary,blob,server_labels,sender,recipients,copied,subject,filenames,has_attachment,text_complete,generation) VALUES(?1,?1,?2,?3,'synthetic','[\"INBOX\"]','alice@example.org','bob@example.org','','Invoice','','0',1,1)"))?; + let mut labels=store::sql(db.prepare("INSERT INTO labels VALUES(?1,'INBOX')"))?; + let mut search=store::sql(db.prepare("INSERT INTO search(rowid,id,subject,sender,recipients,copied,filenames,body) VALUES(?1,?2,'Invoice','alice@example.org','bob@example.org','','',?3)"))?; + for n in 0..count { + let id=format!("synthetic-{n:08}"); + let summary=json!({"id":id,"subject":"Invoice","from":{"email":"alice@example.org"},"unread":false,"labelIds":["INBOX"]}).to_string(); + store::sql(messages.execute(rusqlite::params![id,1_700_000_000_000i64+n as i64,summary]))?; + store::sql(labels.execute([&id]))?; + store::sql(search.execute(rusqlite::params![(n+1) as i64,id,if n%100==0 {"café needle invoice"} else {"ordinary invoice"}]))?; + } + store::set_state(db,"inventoryComplete","true") + }).unwrap(); + let import_ms = started.elapsed().as_millis(); + let background = std::env::var("MAGPIE_BENCH_BACKGROUND").as_deref() == Ok("1"); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let worker = background.then(|| { + let store = store.clone(); + let stop = stop.clone(); + std::thread::spawn(move || { + let mut writes = 0; + while !stop.load(Ordering::Relaxed) { + store + .put(&message("background", "Synthetic incoming mail"), 1) + .unwrap(); + writes += 1; + std::thread::sleep(std::time::Duration::from_millis(25)); + } + writes + }) + }); + let mut cases = Vec::new(); + for query in [ + "in:inbox", + "needle", + "\"café needle\"", + "from:alice subject:invoice", + "invoice OR needle -is:unread", + ] { + let mut times = Vec::new(); + for _ in 0..31 { + let at = Instant::now(); + let result = store.list(query, 50, "").unwrap(); + assert!(!result["summaries"].as_array().unwrap().is_empty()); + times.push(at.elapsed().as_micros()); + } + times.sort(); + eprintln!( + "LOCAL_CASE {}", + json!({"query":query,"medianUs":times[15],"p95Us":times[29]}) + ); + cases.push(json!({"query":query,"medianUs":times[15],"p95Us":times[29]})); + } + stop.store(true, Ordering::Relaxed); + let writes = worker.map_or(0, |worker| worker.join().unwrap()); + println!( + "LOCAL_BENCH {}", + json!({"messages":count,"fixtureImportMs":import_ms,"cases":cases,"sqlite":rusqlite::version(),"backgroundWrites":writes}) + ); + drop(store); + std::fs::remove_dir_all(path).unwrap(); +} diff --git a/src/local_mail/vfs.rs b/src/local_mail/vfs.rs new file mode 100644 index 000000000..cbfbb3cce --- /dev/null +++ b/src/local_mail/vfs.rs @@ -0,0 +1,471 @@ +//! SQLite filenames are capabilities within one pinned private directory. +//! The owner lease excludes other processes; SQLite's locks coordinate the +//! bounded connections in this process. WAL shared memory is never persisted. +use crate::platform::private_fs as fs; +use rusqlite::{Connection, OpenFlags, ffi::*}; +use std::{ + collections::HashMap, + ffi::{CStr, CString, c_char, c_int, c_void}, + fs::File, + io::{Read, Seek, SeekFrom, Write}, + ptr, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + }, +}; + +static SERIAL: AtomicU64 = AtomicU64::new(0); +#[derive(Default)] +struct Locks { + database: HashMap, + shared: HashMap<(u64, c_int), bool>, + pages: Vec>, +} +struct Root { + directory: File, + _lease: fs::ExclusiveLock, + locks: Mutex, +} +pub(super) struct Vfs { + raw: Box, + name: CString, + root: Arc, +} +// The registration and callbacks are stable allocations; mutable shared state +// is behind Locks. Connections hold an Arc until sqlite3_close completes. +unsafe impl Send for Vfs {} +unsafe impl Sync for Vfs {} +impl Drop for Vfs { + fn drop(&mut self) { + unsafe { + sqlite3_vfs_unregister(self.raw.as_mut()); + } + } +} +impl Vfs { + pub(super) fn new(directory: File) -> Result, &'static str> { + fs::validate_owned_root(&directory)?; + let lease = fs::lock_exclusive(&directory, ".owner")?; + let root = Arc::new(Root { + directory, + _lease: lease, + locks: Mutex::new(Locks::default()), + }); + let name = CString::new(format!( + "magpie-mail-{}", + SERIAL.fetch_add(1, Ordering::Relaxed) + )) + .map_err(|_| "local_storage_unavailable")?; + let mut raw: Box = Box::new(unsafe { std::mem::zeroed() }); + raw.iVersion = 1; + raw.szOsFile = std::mem::size_of::() as c_int; + raw.mxPathname = 64; + raw.zName = name.as_ptr(); + raw.pAppData = Arc::as_ptr(&root).cast_mut().cast(); + raw.xOpen = Some(open); + raw.xDelete = Some(delete); + raw.xAccess = Some(access); + raw.xFullPathname = Some(full_path); + raw.xRandomness = Some(randomness); + raw.xSleep = Some(sleep); + raw.xCurrentTime = Some(time); + if unsafe { sqlite3_vfs_register(raw.as_mut(), 0) } != SQLITE_OK { + return Err("local_storage_unavailable"); + } + Ok(Arc::new(Self { raw, name, root })) + } + pub(super) fn connect(self: &Arc) -> Result { + let connection = Connection::open_with_flags_and_vfs( + "mail.sqlite", + OpenFlags::SQLITE_OPEN_READ_WRITE + | OpenFlags::SQLITE_OPEN_CREATE + | OpenFlags::SQLITE_OPEN_FULL_MUTEX, + self.name + .to_str() + .map_err(|_| "local_storage_unavailable")?, + ) + .map_err(|_| "local_storage_unavailable")?; + connection.execute_batch("PRAGMA temp_store=MEMORY; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000; PRAGMA mmap_size=0;") + .map_err(|_| "local_storage_unavailable")?; + Ok(Database { + connection, + _vfs: self.clone(), + }) + } + pub(super) fn directory(&self) -> &File { + &self.root.directory + } +} +pub(super) struct Database { + pub connection: Connection, + _vfs: Arc, +} +#[repr(C)] +struct Handle { + base: sqlite3_file, + state: *mut OpenFile, +} +struct OpenFile { + file: File, + root: Arc, + id: u64, +} +unsafe fn state<'a>(file: *mut sqlite3_file) -> &'a mut OpenFile { + unsafe { &mut *(*(file.cast::())).state } +} +unsafe fn root<'a>(vfs: *mut sqlite3_vfs) -> &'a Root { + unsafe { &*((*vfs).pAppData.cast::()) } +} +unsafe fn filename<'a>(name: *const c_char) -> Option<&'a str> { + if name.is_null() { + return None; + } + let name = unsafe { CStr::from_ptr(name) }.to_str().ok()?; + matches!( + name, + "mail.sqlite" | "mail.sqlite-wal" | "mail.sqlite-journal" + ) + .then_some(name) +} +unsafe extern "C" fn open( + vfs: *mut sqlite3_vfs, + name: *const c_char, + out: *mut sqlite3_file, + flags: c_int, + returned: *mut c_int, +) -> c_int { + unsafe { + (*out).pMethods = ptr::null(); + } + let Some(name) = (unsafe { filename(name) }) else { + return SQLITE_CANTOPEN; + }; + let root = unsafe { root(vfs) }; + let file = match fs::regular(&root.directory, name, flags & SQLITE_OPEN_READONLY == 0) { + Ok(Some(file)) => file, + Ok(None) if flags & SQLITE_OPEN_CREATE != 0 => { + match fs::create_private(&root.directory, name) { + Ok(file) => file, + Err(_) => return SQLITE_CANTOPEN, + } + } + _ => return SQLITE_CANTOPEN, + }; + let root = unsafe { + let pointer = (*vfs).pAppData.cast::(); + Arc::increment_strong_count(pointer); + Arc::from_raw(pointer) + }; + let state = Box::into_raw(Box::new(OpenFile { + file, + root, + id: SERIAL.fetch_add(1, Ordering::Relaxed), + })); + unsafe { + ptr::write( + out.cast::(), + Handle { + base: sqlite3_file { pMethods: &METHODS }, + state, + }, + ); + if !returned.is_null() { + *returned = flags; + } + } + SQLITE_OK +} +unsafe extern "C" fn close(file: *mut sqlite3_file) -> c_int { + let state = unsafe { Box::from_raw((*file.cast::()).state) }; + if let Ok(mut locks) = state.root.locks.lock() { + locks.database.remove(&state.id); + locks.shared.retain(|(id, _), _| *id != state.id); + } + unsafe { + (*file).pMethods = ptr::null(); + } + SQLITE_OK +} +unsafe extern "C" fn read( + file: *mut sqlite3_file, + output: *mut c_void, + size: c_int, + offset: i64, +) -> c_int { + if size < 0 || offset < 0 { + return SQLITE_IOERR_READ; + } + let file = unsafe { &mut state(file).file }; + let bytes = unsafe { std::slice::from_raw_parts_mut(output.cast::(), size as usize) }; + bytes.fill(0); + if file.seek(SeekFrom::Start(offset as u64)).is_err() { + return SQLITE_IOERR_READ; + } + let mut done = 0; + while done < bytes.len() { + match file.read(&mut bytes[done..]) { + Ok(0) => return SQLITE_IOERR_SHORT_READ, + Ok(count) => done += count, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => (), + Err(_) => return SQLITE_IOERR_READ, + } + } + SQLITE_OK +} +unsafe extern "C" fn write( + file: *mut sqlite3_file, + input: *const c_void, + size: c_int, + offset: i64, +) -> c_int { + if size < 0 || offset < 0 { + return SQLITE_IOERR_WRITE; + } + let file = unsafe { &mut state(file).file }; + let bytes = unsafe { std::slice::from_raw_parts(input.cast::(), size as usize) }; + match file + .seek(SeekFrom::Start(offset as u64)) + .and_then(|_| file.write_all(bytes)) + { + Ok(_) => SQLITE_OK, + Err(e) if e.kind() == std::io::ErrorKind::StorageFull => SQLITE_FULL, + Err(_) => SQLITE_IOERR_WRITE, + } +} +unsafe extern "C" fn truncate(file: *mut sqlite3_file, size: i64) -> c_int { + if size >= 0 && unsafe { state(file) }.file.set_len(size as u64).is_ok() { + SQLITE_OK + } else { + SQLITE_IOERR_TRUNCATE + } +} +unsafe extern "C" fn sync(file: *mut sqlite3_file, _: c_int) -> c_int { + let file = unsafe { state(file) }; + if file.file.sync_all().is_ok() && fs::sync_dir(&file.root.directory).is_ok() { + SQLITE_OK + } else { + SQLITE_IOERR_FSYNC + } +} +unsafe extern "C" fn size(file: *mut sqlite3_file, out: *mut i64) -> c_int { + match unsafe { state(file) }.file.metadata() { + Ok(meta) => { + unsafe { + *out = meta.len() as i64; + } + SQLITE_OK + } + Err(_) => SQLITE_IOERR_FSTAT, + } +} +unsafe extern "C" fn lock(file: *mut sqlite3_file, level: c_int) -> c_int { + let file = unsafe { state(file) }; + let Ok(mut locks) = file.root.locks.lock() else { + return SQLITE_IOERR_LOCK; + }; + if locks.database.iter().any(|(id, held)| { + *id != file.id + && (level >= SQLITE_LOCK_EXCLUSIVE && *held >= SQLITE_LOCK_SHARED + || level >= SQLITE_LOCK_RESERVED && *held >= SQLITE_LOCK_RESERVED + || level == SQLITE_LOCK_SHARED && *held >= SQLITE_LOCK_PENDING) + }) { + return SQLITE_BUSY; + } + locks.database.insert(file.id, level); + SQLITE_OK +} +unsafe extern "C" fn unlock(file: *mut sqlite3_file, level: c_int) -> c_int { + let file = unsafe { state(file) }; + let Ok(mut locks) = file.root.locks.lock() else { + return SQLITE_IOERR_UNLOCK; + }; + locks.database.insert(file.id, level); + SQLITE_OK +} +unsafe extern "C" fn reserved(file: *mut sqlite3_file, out: *mut c_int) -> c_int { + let file = unsafe { state(file) }; + let Ok(locks) = file.root.locks.lock() else { + return SQLITE_IOERR_CHECKRESERVEDLOCK; + }; + unsafe { + *out = i32::from(locks.database.values().any(|v| *v >= SQLITE_LOCK_RESERVED)); + } + SQLITE_OK +} +unsafe extern "C" fn control(_: *mut sqlite3_file, _: c_int, _: *mut c_void) -> c_int { + SQLITE_NOTFOUND +} +unsafe extern "C" fn sector(_: *mut sqlite3_file) -> c_int { + 4096 +} +unsafe extern "C" fn characteristics(_: *mut sqlite3_file) -> c_int { + 0 +} +unsafe extern "C" fn shm_map( + file: *mut sqlite3_file, + page: c_int, + size: c_int, + extend: c_int, + out: *mut *mut c_void, +) -> c_int { + unsafe { + *out = ptr::null_mut(); + } + if !(0..65536).contains(&page) || size != 32768 { + return SQLITE_IOERR_SHMMAP; + } + let file = unsafe { state(file) }; + let Ok(mut locks) = file.root.locks.lock() else { + return SQLITE_IOERR_SHMMAP; + }; + if extend != 0 { + while locks.pages.len() <= page as usize { + locks + .pages + .push(vec![0_u64; size as usize / 8].into_boxed_slice()); + } + } + if let Some(page) = locks.pages.get_mut(page as usize) { + unsafe { + *out = page.as_mut_ptr().cast(); + } + } + SQLITE_OK +} +unsafe extern "C" fn shm_lock( + file: *mut sqlite3_file, + offset: c_int, + count: c_int, + flags: c_int, +) -> c_int { + if offset < 0 || count <= 0 || offset + count > SQLITE_SHM_NLOCK { + return SQLITE_IOERR_SHMLOCK; + } + let file = unsafe { state(file) }; + let Ok(mut locks) = file.root.locks.lock() else { + return SQLITE_IOERR_SHMLOCK; + }; + let exclusive = flags & SQLITE_SHM_EXCLUSIVE != 0; + if flags & SQLITE_SHM_UNLOCK != 0 { + for byte in offset..offset + count { + locks.shared.remove(&(file.id, byte)); + } + return SQLITE_OK; + } + if locks.shared.iter().any(|((id, byte), held)| { + *id != file.id && (offset..offset + count).contains(byte) && (exclusive || *held) + }) { + return SQLITE_BUSY; + } + for byte in offset..offset + count { + locks.shared.insert((file.id, byte), exclusive); + } + SQLITE_OK +} +unsafe extern "C" fn barrier(_: *mut sqlite3_file) { + std::sync::atomic::fence(Ordering::SeqCst); +} +unsafe extern "C" fn shm_unmap(file: *mut sqlite3_file, _: c_int) -> c_int { + let file = unsafe { state(file) }; + let Ok(mut locks) = file.root.locks.lock() else { + return SQLITE_IOERR_SHMLOCK; + }; + locks.shared.retain(|(id, _), _| *id != file.id); + SQLITE_OK +} +static METHODS: sqlite3_io_methods = sqlite3_io_methods { + iVersion: 2, + xClose: Some(close), + xRead: Some(read), + xWrite: Some(write), + xTruncate: Some(truncate), + xSync: Some(sync), + xFileSize: Some(size), + xLock: Some(lock), + xUnlock: Some(unlock), + xCheckReservedLock: Some(reserved), + xFileControl: Some(control), + xSectorSize: Some(sector), + xDeviceCharacteristics: Some(characteristics), + xShmMap: Some(shm_map), + xShmLock: Some(shm_lock), + xShmBarrier: Some(barrier), + xShmUnmap: Some(shm_unmap), + xFetch: None, + xUnfetch: None, +}; +unsafe extern "C" fn delete(vfs: *mut sqlite3_vfs, name: *const c_char, durable: c_int) -> c_int { + let Some(name) = (unsafe { filename(name) }) else { + return SQLITE_IOERR_DELETE; + }; + let root = unsafe { root(vfs) }; + if fs::remove_owned(&root.directory, name).is_err() { + return SQLITE_IOERR_DELETE; + } + if durable != 0 && fs::sync_dir(&root.directory).is_err() { + return SQLITE_IOERR_DIR_FSYNC; + } + SQLITE_OK +} +unsafe extern "C" fn access( + vfs: *mut sqlite3_vfs, + name: *const c_char, + _: c_int, + out: *mut c_int, +) -> c_int { + unsafe { + *out = 0; + } + let Some(name) = (unsafe { filename(name) }) else { + return SQLITE_OK; + }; + match fs::regular(&unsafe { root(vfs) }.directory, name, false) { + Ok(file) => { + unsafe { + *out = i32::from(file.is_some()); + } + SQLITE_OK + } + Err(_) => SQLITE_IOERR_ACCESS, + } +} +unsafe extern "C" fn full_path( + _: *mut sqlite3_vfs, + name: *const c_char, + capacity: c_int, + out: *mut c_char, +) -> c_int { + let Some(name) = (unsafe { filename(name) }) else { + return SQLITE_CANTOPEN; + }; + if capacity as usize <= name.len() { + return SQLITE_CANTOPEN; + } + unsafe { + ptr::copy_nonoverlapping(name.as_ptr(), out.cast(), name.len()); + *out.add(name.len()) = 0; + } + SQLITE_OK +} +unsafe extern "C" fn randomness(_: *mut sqlite3_vfs, count: c_int, out: *mut c_char) -> c_int { + let default = unsafe { sqlite3_vfs_find(ptr::null()) }; + if default.is_null() { + return 0; + } + unsafe { + (*default) + .xRandomness + .map_or(0, |call| call(default, count, out)) + } +} +unsafe extern "C" fn sleep(_: *mut sqlite3_vfs, micros: c_int) -> c_int { + std::thread::sleep(std::time::Duration::from_micros(micros.max(0) as u64)); + micros +} +unsafe extern "C" fn time(_: *mut sqlite3_vfs, out: *mut f64) -> c_int { + unsafe { + *out = chrono::Utc::now().timestamp_millis() as f64 / 86_400_000.0 + 2_440_587.5; + } + SQLITE_OK +} diff --git a/src/message/compose.rs b/src/message/compose.rs index 11b8307ed..6fae6e32a 100644 --- a/src/message/compose.rs +++ b/src/message/compose.rs @@ -460,3 +460,45 @@ pub fn request(params: &Value) -> Result { } build(¶ms["fields"]) } + +pub(crate) fn submission(fields: &Value, stamp: u64, seed: &str) -> Result { + use sha2::{Digest, Sha256}; + let mut fields = fields.clone(); + let digest = format!( + "{:x}", + Sha256::digest( + serde_json::to_vec(&json!([fields, stamp, seed])).map_err(|_| "invalid_params")? + ) + ); + fields["boundary"] = json!(format!("=_Omamail_{}", &digest[..40])); + fields["messageId"] = json!(format!("<{digest}@omamail.invalid>")); + fields["date"] = json!( + chrono::DateTime::from_timestamp_millis( + i64::try_from(stamp).map_err(|_| "invalid_params")? + ) + .ok_or("invalid_params")? + .format("%a, %d %b %Y %H:%M:%S %z") + .to_string() + ); + build(&fields) +} + +#[cfg(test)] +mod submission_tests { + use super::*; + #[test] + fn explicit_send_replays_preserve_mime_and_changed_content_does_not() { + let fields = json!({"from":"a@example.org","to":"b@example.org","body":"one","attachments":[{"filename":"file.txt","data":"YQ"}]}); + let first = submission(&fields, 1700000000000, "send-id").unwrap(); + assert_eq!( + first, + submission(&fields, 1700000000000, "send-id").unwrap() + ); + let mut changed = fields; + changed["body"] = json!("two"); + assert_ne!( + first, + submission(&changed, 1700000000000, "send-id").unwrap() + ); + } +} diff --git a/src/outbox/mod.rs b/src/outbox/mod.rs index 500be456d..9347c61c9 100644 --- a/src/outbox/mod.rs +++ b/src/outbox/mod.rs @@ -1,6 +1,6 @@ //! Durable delayed sends. Every delivery is attempted once, in account order. -//! A restart never resumes a send: queued mail is recoverable and an interrupted -//! delivery is unknown, because a lost acknowledgement cannot prove non-delivery. +//! A restart resumes explicitly authorized waiting mail after a connectivity check. +//! An interrupted delivery remains unknown and is never automatically retried. use futures_util::{FutureExt, future::BoxFuture}; use serde_json::{Value, json}; use std::{ @@ -20,6 +20,8 @@ mod storage; mod tests; pub type Executor = Arc BoxFuture<'static, Result> + Send + Sync>; +pub type Readiness = + Arc BoxFuture<'static, Result<(), &'static str>> + Send + Sync>; static SERIAL: AtomicU64 = AtomicU64::new(0); const MAX_ENTRIES: usize = 65536; const MAX_RECOVERABLE: usize = 128; @@ -28,10 +30,12 @@ struct State { loaded: bool, workers: HashSet, revision: u64, + dirty: bool, } struct Inner { state: tokio::sync::Mutex, executor: Executor, + readiness: Option, events: broadcast::Sender, wake: Notify, stopping: AtomicBool, @@ -63,11 +67,18 @@ fn terminal(state: &str) -> bool { matches!(state, "sent" | "failed" | "unknown" | "cancelled") } fn summary(entry: &Value, payload: bool) -> Value { - let mut copy = entry.clone(); - if !payload { - copy.as_object_mut().unwrap().remove("payload"); - } - copy + Value::Object( + entry + .as_object() + .into_iter() + .flatten() + .filter(|(key, _)| payload || key.as_str() != "payload") + .map(|(key, value)| (key.clone(), value.clone())) + .collect(), + ) +} +fn waiting(entry: &Value) -> bool { + matches!(entry["state"].as_str(), Some("queued" | "waiting")) } fn snapshot(state: &State, account: &str, payload: bool) -> Value { json!({"accountId":account,"revision":state.revision,"entries":state.entries.iter().filter(|entry|entry["accountId"]==account&&(payload||entry["acknowledged"]!=true)).map(|entry|summary(entry,payload)).collect::>()}) @@ -119,6 +130,16 @@ async fn load(inner: &Arc, state: &mut State) -> Result<(), &'static str> .as_array() .filter(|entries| entries.len() <= MAX_ENTRIES) .ok_or("outbox_storage_invalid")?; + let recovered = recover(entries)?; + *inner.lease.lock().unwrap_or_else(|e| e.into_inner()) = Some(lease); + save(inner, &recovered).await?; + state.entries = recovered; + ipc::listen(inner)?; + state.loaded = true; + start_workers(inner, state); + Ok(()) +} +fn recover(entries: &[Value]) -> Result, &'static str> { let mut recovered = Vec::new(); let mut ids = HashSet::new(); for entry in entries { @@ -138,6 +159,7 @@ async fn load(inner: &Arc, state: &mut State) -> Result<(), &'static str> entry.as_object_mut().unwrap().remove("payload"); } match entry["state"].as_str() { + Some("waiting") if entry["resumeUnsent"] == true => (), Some("queued") => { entry["state"] = json!("cancelled"); entry["error"] = json!("outbox_recovered_unsent"); @@ -151,14 +173,15 @@ async fn load(inner: &Arc, state: &mut State) -> Result<(), &'static str> } recovered.push(entry); } - *inner.lease.lock().unwrap_or_else(|e| e.into_inner()) = Some(lease); - save(inner, &recovered).await?; - state.entries = recovered; - ipc::listen(inner)?; - state.loaded = true; - Ok(()) + Ok(recovered) } impl Outbox { + pub fn with_readiness(mut self, readiness: Readiness) -> Self { + if let Some(inner) = Arc::get_mut(&mut self.inner) { + inner.readiness = Some(readiness); + } + self + } pub fn new(executor: Executor) -> Self { Self::with_root(executor, None) } @@ -171,8 +194,10 @@ impl Outbox { loaded: false, workers: HashSet::new(), revision: 0, + dirty: false, }), executor, + readiness: None, events, wake: Notify::new(), stopping: AtomicBool::new(false), @@ -320,6 +345,7 @@ impl Inner { "sendId", "order", "delaySeconds", + "resumeUnsent", ], "outbox.snapshot" => &["accountId", "includePayloads", "sendId"], "outbox.undo" | "outbox.forget" => &["accountId", "sendId"], @@ -345,16 +371,11 @@ impl Inner { if params["includePayloads"] == true && wanted.is_none() { return Err("outbox_payload_id_required"); } - if let Some(id) = wanted - && state.entries.iter().any(|entry| { - entry["accountId"] == account - && entry["id"] == id - && terminal(entry["state"].as_str().unwrap_or("")) - }) - { + if state.dirty { // A delivery acknowledgement is authoritative only after this // transition is durable, including replies to another process. save(self, &state.entries).await?; + state.dirty = false; } return Ok(if let Some(id) = wanted { json!({"accountId":account,"revision":state.revision,"entries":state.entries.iter().filter(|entry|entry["accountId"]==account&&entry["id"]==id).map(|entry|summary(entry,params["includePayloads"]==true)).collect::>()}) @@ -369,6 +390,12 @@ impl Inner { let mut selected = String::new(); match method { "outbox.enqueue" => { + if params + .get("resumeUnsent") + .is_some_and(|value| !value.is_boolean()) + { + return Err("outbox_invalid_params"); + } let provider = text(params, "provider")?; if !["gmail", "outlook", "imap", "jmap", "hey"].contains(&provider) { return Err("outbox_invalid_provider"); @@ -430,7 +457,8 @@ impl Inner { .map(|v| v.as_u64().ok_or("outbox_invalid_params")) .transpose()? .unwrap_or(stamp); - next.push(json!({"id":selected,"accountId":account,"provider":provider,"payload":payload,"digest":digest(payload),"state":"queued","queuedAt":stamp,"dueAt":stamp.saturating_add(delay*1000),"order":order,"draftId":payload.get("draftId").and_then(Value::as_str).unwrap_or("")})); + let resumable = params["resumeUnsent"] == true; + next.push(json!({"id":selected,"accountId":account,"provider":provider,"payload":payload,"digest":digest(payload),"state":if resumable {"waiting"}else{"queued"},"resumeUnsent":resumable,"queuedAt":stamp,"dueAt":stamp.saturating_add(delay*1000),"order":order,"draftId":payload.get("draftId").and_then(Value::as_str).unwrap_or("")})); } "outbox.undo" => { let wanted = params @@ -442,7 +470,7 @@ impl Inner { .rev() .find(|entry| { entry["accountId"] == account - && entry["state"] == "queued" + && waiting(entry) && wanted.is_none_or(|id| entry["id"] == id) }) .ok_or("outbox_not_queued")?; @@ -451,14 +479,14 @@ impl Inner { } "outbox.flush" => { for entry in &mut next { - if entry["accountId"] == account && entry["state"] == "queued" { + if entry["accountId"] == account && waiting(entry) { entry["dueAt"] = json!(0); } } } "outbox.abandon" => { for entry in &mut next { - if entry["accountId"] == account && entry["state"] == "queued" { + if entry["accountId"] == account && waiting(entry) { entry["state"] = json!("cancelled"); } } @@ -488,7 +516,7 @@ impl Inner { if state .entries .iter() - .any(|entry| entry["accountId"] == account && entry["state"] == "queued") + .any(|entry| entry["accountId"] == account && waiting(entry)) && state.workers.insert(account.clone()) { let inner = self.clone(); @@ -504,6 +532,27 @@ impl Inner { Ok(json!({"id":selected,"snapshot":snapshot(&state,&account,false)})) } } +fn start_workers(inner: &Arc, state: &mut State) { + let accounts: HashSet = state + .entries + .iter() + .filter(|entry| waiting(entry)) + .filter_map(|entry| entry["accountId"].as_str().map(str::to_owned)) + .collect(); + for account in accounts { + if !state.workers.insert(account.clone()) { + continue; + } + let inner = inner.clone(); + let owner = inner.clone(); + let job = tokio::spawn(async move { worker(owner, account).await }); + inner + .jobs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(job); + } +} impl Drop for Outbox { fn drop(&mut self) { self.inner.stopping.store(true, Ordering::Release); @@ -530,10 +579,10 @@ async fn worker(inner: Arc, account: String) { state.workers.remove(&account); return; } - let Some(index) = state + let Some(mut index) = state .entries .iter() - .position(|entry| entry["accountId"] == account && entry["state"] == "queued") + .position(|entry| entry["accountId"] == account && waiting(entry)) else { state.workers.remove(&account); return; @@ -545,11 +594,54 @@ async fn worker(inner: Arc, account: String) { tokio::select! {_=tokio::time::sleep(delay)=>(),_=&mut notified=>()}; continue; } + if state.entries[index]["state"] == "waiting" { + let identity = state.entries[index]["id"].clone(); + let provider = state.entries[index]["provider"] + .as_str() + .unwrap_or("") + .to_owned(); + let readiness = inner.readiness.clone(); + drop(state); + let ready = match readiness { + Some(check) => { + tokio::time::timeout(Duration::from_secs(20), check(account.clone(), provider)) + .await + .unwrap_or(Err("outbox_connection_unavailable")) + } + None => Ok(()), + }; + state = inner.state.lock().await; + let Some(current) = state.entries.iter().position(|entry| { + entry["accountId"] == account + && entry["id"] == identity + && entry["state"] == "waiting" + }) else { + continue; + }; + index = current; + if inner.stopping.load(Ordering::Acquire) { + continue; + } + if ready.is_err() { + let mut next = state.entries.clone(); + next[index]["dueAt"] = json!(now() + 30_000); + next[index]["error"] = json!("outbox_awaiting_connection"); + if save(&inner, &next).await.is_err() { + state.workers.remove(&account); + return; + } + state.entries = next; + state.revision += 1; + emit(&inner, &state, &account); + continue; + } + } let mut next = state.entries.clone(); next[index]["state"] = json!("sending"); if save(&inner, &next).await.is_err() { state.entries[index]["state"] = json!("failed"); state.entries[index]["error"] = json!("outbox_storage_unavailable"); + state.dirty = true; state.revision += 1; emit(&inner, &state, &account); state.workers.remove(&account); @@ -595,7 +687,7 @@ async fn worker(inner: Arc, account: String) { // If this write fails, disk still says sending and restart recovers unknown. // No retry is safe, regardless of whether the acknowledgement was received. state.revision += 1; - let _ = save(&inner, &state.entries).await; + state.dirty = save(&inner, &state.entries).await.is_err(); emit(&inner, &state, &account); } } diff --git a/src/outbox/tests.rs b/src/outbox/tests.rs index 59786df43..c6e9f3d3c 100644 --- a/src/outbox/tests.rs +++ b/src/outbox/tests.rs @@ -1053,3 +1053,70 @@ fn test_directories_retry_collisions_without_reusing_or_removing_existing_data() 0o700 ); } + +#[test] +fn restart_resumes_only_explicitly_authorized_never_started_sends() { + let row = |id: &str, state: &str, resume: bool| json!({"id":id,"accountId":"synthetic@example.org","provider":"gmail","state":state,"resumeUnsent":resume,"payload":{"raw":"synthetic"}}); + let entries = recover(&[ + row("waiting", "waiting", true), + row("sending", "sending", true), + row("legacy", "queued", false), + ]) + .unwrap(); + assert_eq!(entries[0]["state"], "waiting"); + assert_eq!(entries[1]["state"], "unknown"); + assert_eq!(entries[2]["state"], "cancelled"); + assert!( + !waiting(&entries[1]), + "an uncertain delivery must never enter the worker's eligible set" + ); + assert!(recover(&[row("unapproved", "waiting", false)]).is_err()); +} + +#[tokio::test] +async fn cancelling_during_offline_preflight_never_calls_delivery() { + let dir = Temp::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + let gate = Arc::new(tokio::sync::Notify::new()); + let entered = Arc::new(tokio::sync::Notify::new()); + let wait = gate.clone(); + let signal = entered.clone(); + let outbox = Outbox::with_root( + Arc::new(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Ok(json!({})) }) + }), + Some(dir.0.clone()), + ) + .with_readiness(Arc::new(move |_, _| { + let wait = wait.clone(); + let signal = signal.clone(); + Box::pin(async move { + signal.notify_one(); + wait.notified().await; + Ok(()) + }) + })); + let mut request = enqueue("offline", "a@example.org", 0); + request["resumeUnsent"] = json!(true); + outbox.call("outbox.enqueue", &request).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), entered.notified()) + .await + .unwrap(); + outbox + .call( + "outbox.undo", + &json!({"accountId":"a@example.org","sendId":"offline"}), + ) + .await + .unwrap(); + gate.notify_one(); + tokio::time::sleep(Duration::from_millis(20)).await; + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!( + state(&outbox, "offline", "a@example.org").await, + "cancelled" + ); + outbox.shutdown().await.unwrap(); +} diff --git a/src/platform/ipc/unix.rs b/src/platform/ipc/unix.rs index d526d9908..a4d373cf0 100644 --- a/src/platform/ipc/unix.rs +++ b/src/platform/ipc/unix.rs @@ -14,6 +14,9 @@ impl LocalEndpoint { pub(crate) fn outbox(root: &Path) -> Result { let dir = crate::platform::private_fs::directories_readonly(root, &["omamail"])? .ok_or("outbox_owner_unavailable")?; + Self::directory(dir) + } + pub(crate) fn directory(dir: File) -> Result { crate::platform::private_fs::validate_owned_root(&dir)?; Ok(Self { dir }) } diff --git a/src/platform/ipc/windows.rs b/src/platform/ipc/windows.rs index 5a9d8ae53..a01b5fddb 100644 --- a/src/platform/ipc/windows.rs +++ b/src/platform/ipc/windows.rs @@ -31,6 +31,9 @@ impl LocalEndpoint { pub(crate) fn outbox(root: &Path) -> Result { let dir = private_fs::directories_readonly(root, &["omamail"])? .ok_or("outbox_owner_unavailable")?; + Self::directory(dir) + } + pub(crate) fn directory(dir: File) -> Result { private_fs::validate_owned_root(&dir)?; let (volume, id, _) = private_fs::file_id(&dir)?; let sid = security::sid_text(&security::current_user()?)?; diff --git a/src/platform/private_fs/unix.rs b/src/platform/private_fs/unix.rs index 00073a8ad..580db31f3 100644 --- a/src/platform/private_fs/unix.rs +++ b/src/platform/private_fs/unix.rs @@ -237,6 +237,25 @@ pub(crate) fn regular_readonly(dir: &File, name: &str) -> Result> { Ok(Some(file)) } +pub(crate) fn create_private(dir: &File, name: &str) -> Result { + validate_owned_root(dir)?; + let name = cstr(name.as_ref())?; + let fd = unsafe { + libc::openat( + dir.as_raw_fd(), + name.as_ptr(), + libc::O_RDWR | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, + 0o600, + ) + }; + if fd < 0 { + return Err("cache_unsafe_path"); + } + let file = unsafe { File::from_raw_fd(fd) }; + validate_acl(&file, true)?; + Ok(file) +} + pub(crate) fn names(dir: &File) -> Result> { let fd = unsafe { libc::openat( @@ -381,6 +400,14 @@ pub(crate) fn sync_dir(dir: &File) -> Result<()> { dir.sync_all().map_err(|_| "cache_unavailable") } +pub(crate) fn available_bytes(dir: &File) -> Result { + let mut status: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstatvfs(dir.as_raw_fd(), &mut status) } != 0 { + return Err("cache_unavailable"); + } + Ok((status.f_bavail as u64).saturating_mul(status.f_frsize as u64)) +} + pub(crate) struct ExclusiveLock { file: File, owner: u32, diff --git a/src/platform/private_fs/windows.rs b/src/platform/private_fs/windows.rs index cb40f5cc7..66fa5c6df 100644 --- a/src/platform/private_fs/windows.rs +++ b/src/platform/private_fs/windows.rs @@ -459,6 +459,28 @@ pub(crate) fn sync_dir(_: &File) -> Result<()> { Ok(()) } +pub(crate) fn available_bytes(dir: &File) -> Result { + use std::os::windows::ffi::OsStrExt; + let path: Vec = final_path(dir)? + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect(); + let mut free = 0u64; + if unsafe { + windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW( + path.as_ptr(), + &mut free, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + } == 0 + { + return Err("cache_unavailable"); + } + Ok(free) +} + pub(crate) struct ExclusiveLock { _file: File, } diff --git a/src/process/async_run.rs b/src/process/async_run.rs index eac4615a7..f866957d4 100644 --- a/src/process/async_run.rs +++ b/src/process/async_run.rs @@ -2,9 +2,27 @@ use std::{process::Stdio, time::Duration}; use tokio::{ io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, - process::Command, + process::{Child, Command}, }; +struct ChildReaper(Option); +impl Drop for ChildReaper { + fn drop(&mut self) { + let Some(mut child) = self.0.take() else { + return; + }; + if matches!(child.try_wait(), Ok(Some(_))) { + return; + } + let _ = child.start_kill(); + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + runtime.spawn(async move { + let _ = child.wait().await; + }); + } + } +} + #[derive(Debug)] pub struct Output { pub success: bool, @@ -56,10 +74,12 @@ pub(super) async fn run_with_stderr_limit( .stderr(Stdio::piped()) .kill_on_drop(true); super::platform::configure(command.as_std_mut()); - let mut child = command.spawn().map_err(|_| "process_unavailable")?; + let child = command.spawn().map_err(|_| "process_unavailable")?; + let mut reaper = ChildReaper(Some(child)); + let child = reaper.0.as_mut().ok_or("process_unavailable")?; // Windows assigns the still-suspended process to its job before resuming it. // A failed attach cannot execute any child code. - let group = super::platform::Tree::for_async_child(&child)?; + let group = super::platform::Tree::for_async_child(child)?; let mut stdin = child.stdin.take().ok_or("process_pipe_failed")?; let stdout = child.stdout.take().ok_or("process_pipe_failed")?; let stderr = child.stderr.take().ok_or("process_pipe_failed")?; @@ -181,6 +201,71 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[tokio::test] + async fn cancellation_prevents_descendant_writes() { + let root = std::env::temp_dir().join(format!( + "omamail-async-descendant-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&root).unwrap(); + let script = r#"import os,sys,time +root=sys.argv[1] +pid=os.fork() +if pid: + os.waitpid(pid,0) +else: + open(os.path.join(root,'ready'),'x').close() + while not os.path.exists(os.path.join(root,'release')): time.sleep(0.01) + open(os.path.join(root,'effect'),'x').close() +"#; + let launch = |path: std::path::PathBuf| { + tokio::spawn(async move { + run( + "python3", + &["-c".into(), script.into(), path.to_str().unwrap().into()], + b"", + Duration::from_secs(15), + 1024, + ) + .await + }) + }; + for cancel in [false, true] { + let path = root.join(if cancel { "cancelled" } else { "control" }); + std::fs::create_dir(&path).unwrap(); + let task = launch(path.clone()); + tokio::time::timeout(Duration::from_secs(5), async { + while !path.join("ready").exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + if cancel { + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + std::fs::write(path.join("release"), b"").unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !path.join("effect").exists(), + "cancelled descendant wrote a file" + ); + continue; + } + std::fs::write(path.join("release"), b"").unwrap(); + assert!(task.await.unwrap().unwrap().success); + assert!( + path.join("effect").exists(), + "control must demonstrate the forbidden write" + ); + } + std::fs::remove_dir_all(root).unwrap(); + } + #[tokio::test] async fn output_is_bounded() { assert!(matches!( diff --git a/src/providers/gmail.rs b/src/providers/gmail.rs index d0b4802b0..827d3ed2f 100644 --- a/src/providers/gmail.rs +++ b/src/providers/gmail.rs @@ -183,7 +183,80 @@ pub(crate) fn validate_message_id(id: &str) -> Result<(), &'static str> { super::gmail_http::validate_path_part(id).map_err(|_| "invalid_params") } +pub(crate) fn normalize_labels(value: Value) -> Value { + resources::normalize("gmail.labels", value) +} + impl Session { + pub(crate) async fn replica_call( + &self, + account: &str, + operation: &str, + params: &Value, + ) -> Result { + self.access_token(account).await?; + let budget = self.account(account)?.budget.clone(); + let mut query = Vec::new(); + let path = match operation { + "inventory" => { + query.extend([ + ("maxResults".into(), "500".into()), + ("includeSpamTrash".into(), "true".into()), + ( + "pageToken".into(), + params["pageToken"].as_str().unwrap_or("").into(), + ), + ]); + vec!["messages"] + } + "history" => { + query.extend([ + ( + "startHistoryId".into(), + field(params, "historyId", true)?.into(), + ), + ( + "pageToken".into(), + params["pageToken"].as_str().unwrap_or("").into(), + ), + ("maxResults".into(), "500".into()), + ]); + vec!["history"] + } + "content" | "minimal" => { + query.push(( + "format".into(), + if operation == "minimal" { + "minimal" + } else { + "full" + } + .into(), + )); + vec!["messages", field(params, "id", true)?] + } + "attachment" => vec![ + "messages", + field(params, "id", true)?, + "attachments", + field(params, "attachmentId", true)?, + ], + "profile" => vec!["profile"], + "labels" => vec!["labels"], + _ => return Err("invalid_params"), + }; + self.get_with( + account, + || refresh_grant(account.to_owned()), + |token| { + let budget = budget.clone(); + let path = &path; + let query = &query; + async move { gmail_http::get_replica(path, query, &token, &budget).await } + }, + ) + .await + } /// Internal, read-only thread context. Never accepts a caller-selected URL. pub(crate) async fn thread_resources( &self, diff --git a/src/providers/gmail_diagnostics.rs b/src/providers/gmail_diagnostics.rs index 92d99ed22..83a954b6f 100644 --- a/src/providers/gmail_diagnostics.rs +++ b/src/providers/gmail_diagnostics.rs @@ -4,6 +4,14 @@ use std::{io::Read, path::Path}; const LIMIT: usize = 65536; const RECORDS: usize = 200; static OPERATIONS: std::sync::Mutex<()> = std::sync::Mutex::new(()); +static WRITER: std::sync::OnceLock> = + std::sync::OnceLock::new(); +static DROPPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +enum Command { + Event(Event), + Flush(std::sync::mpsc::SyncSender<()>), +} #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -12,6 +20,8 @@ pub(super) struct Event { pub process: u32, pub session: u64, pub request: u64, + #[serde(default)] + pub rpc: u64, pub operation: String, pub lane: String, pub cost: u32, @@ -31,6 +41,7 @@ impl Event { && matches!( self.operation.as_str(), "getProfile" + | "history.list" | "labels.list" | "labels.get" | "settings.sendAs.list" @@ -74,6 +85,7 @@ impl Event { && matches!( self.outcome.as_str(), "ok" | "gmail_rate_limited" + | "gmail_not_found" | "gmail_unauthorized" | "gmail_forbidden" | "gmail_length_required" @@ -95,18 +107,80 @@ pub(super) async fn record(event: Event) { if !ENABLED.try_with(|_| ()).is_ok() { return; } - let _ = tokio::task::spawn_blocking(move || { - let dirs = crate::platform::dirs::AppDirs::discover()?; - write(&dirs.state, event) - }) + if !event.valid() { + return; + } + let writer = WRITER.get_or_init(|| { + let (sender, receiver) = std::sync::mpsc::sync_channel(512); + let _ = std::thread::Builder::new() + .name("gmail-diagnostics".into()) + .spawn(move || { + let mut batch = Vec::new(); + let mut deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + match receiver + .recv_timeout(deadline.saturating_duration_since(std::time::Instant::now())) + { + Ok(Command::Event(event)) => batch.push(event), + Ok(Command::Flush(done)) => { + persist(&mut batch); + let _ = done.send(()); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => persist(&mut batch), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + persist(&mut batch); + break; + } + } + if batch.len() >= 64 || std::time::Instant::now() >= deadline { + persist(&mut batch); + deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + } + } + }); + sender + }); + if writer.try_send(Command::Event(event)).is_err() { + DROPPED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +fn persist(batch: &mut Vec) { + if batch.is_empty() { + return; + } + let count = batch.len() as u64; + let events = std::mem::take(batch); + if crate::platform::dirs::AppDirs::discover() + .and_then(|dirs| write_batch(&dirs.state, events)) + .is_err() + { + DROPPED.fetch_add(count, std::sync::atomic::Ordering::Relaxed); + } +} + +pub(super) async fn flush() { + let Some(writer) = WRITER.get() else { return }; + let writer = writer.clone(); + let _ = tokio::time::timeout( + std::time::Duration::from_secs(3), + tokio::task::spawn_blocking(move || { + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + if writer.try_send(Command::Flush(sender)).is_ok() { + let _ = receiver.recv_timeout(std::time::Duration::from_secs(2)); + } + }), + ) .await; } +#[cfg(test)] fn write(root: &Path, event: Event) -> Result<(), &'static str> { + write_batch(root, vec![event]) +} + +fn write_batch(root: &Path, batch: Vec) -> Result<(), &'static str> { use crate::platform::private_fs::{atomic_replace, directories, lock_exclusive, regular}; - if !event.valid() { - return Ok(()); - } let _operation = OPERATIONS.lock().map_err(|_| "cache_unavailable")?; let dir = directories(root, &["omamail", "diagnostics"], true)?.ok_or("cache_unavailable")?; let _lock = lock_exclusive(&dir, ".gmail.lock")?; @@ -121,14 +195,17 @@ fn write(root: &Path, event: Event) -> Result<(), &'static str> { } } events.retain(Event::valid); - events.push(event); + events.extend(batch.into_iter().filter(Event::valid)); if events.len() > RECORDS { events.drain(..events.len() - RECORDS); } loop { let bytes = serde_json::to_vec(&events).map_err(|_| "cache_unavailable")?; if bytes.len() <= LIMIT { - return atomic_replace(&dir, "gmail.json", &bytes); + atomic_replace(&dir, "gmail.json", &bytes)?; + return atomic_replace(&dir, "gmail-writer.json", &serde_json::to_vec( + &serde_json::json!({"dropped":DROPPED.load(std::sync::atomic::Ordering::Relaxed)}) + ).map_err(|_| "cache_unavailable")?); } events.remove(0); } @@ -147,6 +224,7 @@ mod tests { process: 1, session: 1, request: 1, + rpc: 1, operation: "messages.get.full".into(), lane: "interactive".into(), cost: 60, diff --git a/src/providers/gmail_http.rs b/src/providers/gmail_http.rs index a65760f1b..b7e8d690c 100644 --- a/src/providers/gmail_http.rs +++ b/src/providers/gmail_http.rs @@ -10,6 +10,10 @@ use std::{ #[path = "gmail_diagnostics.rs"] mod diagnostics; + +pub(crate) async fn flush_diagnostics() { + diagnostics::flush().await; +} #[path = "gmail_quota.rs"] mod quota; pub use quota::{Budget, Lane}; @@ -28,6 +32,7 @@ struct Request { operation: &'static str, cost: u32, budget: Option<(Arc, Lane)>, + response_limit: usize, } const MAX_INPUT: usize = 64 * 1024; @@ -239,6 +244,7 @@ async fn log_attempt( process: std::process::id(), session, request: serial, + rpc: crate::backend::diagnostics::current(), operation: request.operation.into(), lane: lane.into(), cost: request.cost, @@ -313,6 +319,7 @@ async fn attempt( "gmail_rate_limited" } 403 => "gmail_forbidden", + 404 => "gmail_not_found", 411 => "gmail_length_required", 429 => "gmail_rate_limited", _ => "gmail_http_failed", @@ -320,13 +327,13 @@ async fn attempt( } if response .content_length() - .is_some_and(|size| size > MAX_RESPONSE as u64) + .is_some_and(|size| size > request.response_limit as u64) { return Err("gmail_response_too_large"); } let mut bytes = Vec::new(); while let Some(chunk) = response.chunk().await.map_err(http_error)? { - if chunk.len() > MAX_RESPONSE - bytes.len() { + if chunk.len() > request.response_limit - bytes.len() { return Err("gmail_response_too_large"); } bytes.extend_from_slice(&chunk); @@ -429,6 +436,7 @@ fn read_operation(path: &[&str], query: &[(String, String)]) -> (&'static str, u .any(|(k, v)| k == "format" && matches!(v.as_str(), "metadata" | "minimal")); match path { ["profile"] => ("getProfile", 1), + ["history"] => ("history.list", 2), ["labels"] => ("labels.list", 1), ["labels", _] => ("labels.get", 1), ["settings", "sendAs"] => ("settings.sendAs.list", 1), @@ -470,6 +478,23 @@ pub async fn get_paced( request.budget = Some((Arc::clone(budget), lane)); execute(client()?, request, DEADLINE).await } + +pub(crate) async fn get_replica( + path: &[&str], + query: &[(String, String)], + token: &str, + budget: &Arc, +) -> Result { + static SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2); + let _slot = SLOTS + .acquire() + .await + .map_err(|_| "gmail_session_invalidated")?; + let mut request = prepare_get(path, query, token)?; + request.budget = Some((budget.clone(), Lane::Background)); + request.response_limit = 128 * 1024 * 1024; + execute(client()?, request, Duration::from_secs(60)).await +} pub async fn write_paced( method: reqwest::Method, path: &[&str], @@ -557,6 +582,7 @@ fn prepare_get( operation, cost, budget: None, + response_limit: MAX_RESPONSE, }) } @@ -585,6 +611,7 @@ fn prepare_refresh(id: &str, secret: &str, token: &str) -> Result = page["ids"] diff --git a/tests/calendar_parse_oracle.js b/tests/calendar_parse_oracle.js new file mode 100644 index 000000000..fa4f9fa03 --- /dev/null +++ b/tests/calendar_parse_oracle.js @@ -0,0 +1,24 @@ +// The existing calendar regression suite supplies independent parity cases. +const loader = require("../ui/tests/load") +const original = loader.load +const cases = [] +loader.load = function(path) { + const library = original(path) + const names = path === "calendar/Calendar.js" + ? ["eventsFromCaldav", "eventsFromGoogle", "eventsFromGraph"] + : path === "message/Calendar.js" ? ["invitationFrom", "eventsFrom"] : [] + for (const name of names) { + const call = library[name] + library[name] = function(...args) { + const result = call(...args) + if (JSON.stringify([args,result]).length < 100000) + cases.push({name,args,result}) + return result + } + } + return library +} +console.log = function() {} +require("../ui/tests/test_calendar") +require("../ui/tests/test_calendar_feed") +process.stdout.write(JSON.stringify(cases)) diff --git a/tests/run_qml_components.py b/tests/run_qml_components.py new file mode 100644 index 000000000..fbb7b079f --- /dev/null +++ b/tests/run_qml_components.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Run independent QML components; retain native-bridge exclusions explicitly.""" +import argparse +import importlib.util +import json +from pathlib import Path +import re +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("verification", ROOT / "scripts/verify-performance.py") +verification = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verification) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runner", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False, mode=0o700) + report = {"status": "running", "nativeBridgeRequired": [], "tests": []} + with tempfile.TemporaryDirectory(prefix="magpie-qml-components-") as temporary: + environment = verification.test_environment(Path(temporary)) + for path in sorted((ROOT / "ui/tests/qml").glob("tst_*.qml")): + name = str(path.relative_to(ROOT)) + if re.search(r'^\s*import\s+"NativeIntentFixture\.js"', path.read_text(), re.MULTILINE): + report["nativeBridgeRequired"].append(name) + continue + command = [args.runner, "-input", str(path), "-import", str(ROOT / "ui/tests/qml/imports")] + result = verification.execute(command, environment, output / (path.stem + ".log"), 90) + report["tests"].append(dict(file=name, **result)) + print(path.name + ": " + result["status"], flush=True) + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + report["status"] = "pass" if report["tests"] and all( + test["status"] == "pass" for test in report["tests"]) else "fail" + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"Components: {len(report['tests'])}; native bridge still required: " + f"{len(report['nativeBridgeRequired'])}; result: {report['status']}") + return 0 if report["status"] == "pass" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_app_make.py b/tests/test_app_make.py index de6aae195..7ed44358e 100644 --- a/tests/test_app_make.py +++ b/tests/test_app_make.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """The local standalone targets use the portable backend and explicit dev paths.""" from pathlib import Path +import os import subprocess @@ -8,8 +9,11 @@ def make(*args): + environment = {key: value for key, value in os.environ.items() + if key not in {"MAKEFLAGS", "MFLAGS", "MAKEOVERRIDES", + "APP_BACKEND", "APP_TARGET_DIR", "APP_BUILD_DIR"}} return subprocess.run( - ["make", *args], cwd=ROOT, text=True, stdout=subprocess.PIPE, + ["make", *args], cwd=ROOT, env=environment, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True).stdout diff --git a/tests/test_backend_api.py b/tests/test_backend_api.py index 3e69a3bd4..4bc836f34 100644 --- a/tests/test_backend_api.py +++ b/tests/test_backend_api.py @@ -140,6 +140,7 @@ def terminate_process_group(process, platform=None): assert.deepEqual(storageSnapshot(), before, method + ': disabled method has no effects'); } if (!released) { + assert.equal(info.contractHash, require('crypto').createHash('sha256').update(fs.readFileSync(process.env.CONTRACT_ROOT + '/backend-api.json')).digest('hex'), 'compiled API contract matches the UI contract'); for (const method of ['jmap.actionAvailability', 'jmap.actionRows']) { assert.ok(!info.methods.includes(method), 'internal planner is not advertised'); const before = storageSnapshot(); diff --git a/tests/test_backend_runtime.py b/tests/test_backend_runtime.py index 76b09bd15..45541e351 100644 --- a/tests/test_backend_runtime.py +++ b/tests/test_backend_runtime.py @@ -267,7 +267,7 @@ def download(url, limit): def test_missing_status_never_downloads(self): result = self.manager.run("status") - self.assertEqual(result, dict(state="missing", requiredVersion="0.8.2", requiredApiVersion=1, latestApiVersion=1, unreleasedMethods=[], installedVersion="", executable=str(self.binary), error="", cliInstalled=False)) + self.assertEqual(result, dict(state="missing", requiredVersion="0.8.2", requiredApiVersion=1, latestApiVersion=1, unreleasedMethods=[], contractHash=hashlib.sha256((self.root / "backend-api.json").read_bytes()).hexdigest(), installedVersion="", executable=str(self.binary), error="", cliInstalled=False)) self.assertFalse(self.binary.parent.exists()) def test_release_status_uses_only_local_pin_and_api_despite_newer_cargo(self): diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 214c4a65a..f6e0b8471 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -64,6 +64,25 @@ def test_backend_provider_identifiers_survive_redaction(self): self.assertIn(code, data) self.assertNotIn('unknown_error', data) + def test_rpc_failure_reason_and_time_survive_without_private_values(self): + self.call('record', []) + event = {'method':'local.edit', 'success':False, 'process':12, 'request':34, + 'queueUs':0, 'elapsedUs':23, 'requestBytes':80, + 'timeMs':1792590000000, 'error':'local_disk_full'} + values = [event, dict(event, error='SECRET-token\nprivate@example.test'), + dict(event, method=['SECRET']), dict(event, timeMs='SECRET')] + path = self.folder / 'rpc.json' + path.write_text(json.dumps(values)) + path.chmod(0o600) + self.call('open') + report = (self.folder / 'report.txt').read_text() + self.assertIn('local_disk_full', report) + self.assertIn('1792590000000', report) + self.assertIn('unknown_error', report) + self.assertNotIn('SECRET', report) + self.assertNotIn('private@example.test', report) + self.assertNotIn('SECRET', (self.root / 'state/launched').read_text()) + def test_gmail_report_preserves_transport_facts_and_discards_private_values(self): self.call('record', [self.event('gmail_rate_limited')]) event = {'time': '2026-10-17T14:02:38Z', 'process': 123, 'session': 4, @@ -101,6 +120,26 @@ def test_gmail_report_ignores_unsafe_storage_and_stays_bounded(self): self.call('open') self.assertLessEqual((self.folder / 'report.txt').stat().st_size, 65536) + def test_rpc_report_only_keeps_generated_ids_timings_and_drop_counts(self): + self.call('record', []) + event = {'process': 12, 'request': 34, 'method': 'reader.open', 'queueUs': 56, + 'elapsedUs': 78, 'requestBytes': 90, 'success': True, 'accountId': 'SECRET-address', + 'params': {'body': 'SECRET-body'}} + rows = [event, dict(event, request='SECRET-caller-id'), dict(event, method='SECRET-method')] + for filename, value in [('rpc.json', rows), ('rpc-writer.json', {'dropped': 7, 'private': 'SECRET'}), + ('gmail-writer.json', {'dropped': 9})]: + path = self.folder / filename + path.write_text(json.dumps(value)) + path.chmod(0o600) + self.call('open') + report = (self.folder / 'report.txt').read_text() + self.assertIn('"request": 34', report) + self.assertIn('"elapsedUs": 78', report) + self.assertIn('rpc-writer.json: dropped records=7', report) + self.assertIn('gmail-writer.json: dropped records=9', report) + self.assertNotIn('SECRET', report) + self.assertNotIn('SECRET', (self.root / 'state/launched').read_text()) + def test_static_backend_error_vocabulary_does_not_drift(self): spec = importlib.util.spec_from_file_location('diagnostics', SCRIPT) module = importlib.util.module_from_spec(spec) diff --git a/tests/test_gmail_backend.js b/tests/test_gmail_backend.js index 9e0b5d72b..c19e61527 100644 --- a/tests/test_gmail_backend.js +++ b/tests/test_gmail_backend.js @@ -157,3 +157,33 @@ assert.strictEqual(withdrawn, 1, 'cancellation withdraws the queued physical fra assert.strictEqual(context.inFlight, beforeCancel, 'withdrawal releases the in-flight count') context.abortRequest(unsent) assert.strictEqual(withdrawn, 1, 'withdrawal settles only once') + +vm.runInContext(method('localEdit'),context) +const compatibility=load('backend/Compatibility.js') +const contractHash='a'.repeat(64) +for (const [info,expected] of [ + [{apiVersion:8},'gmail.trash'], + [{apiVersion:8,contractHash:'b'.repeat(64)},'gmail.trash'], + [{apiVersion:8,contractHash},'local.edit'], + [{apiVersion:7},'gmail.trash'] +]) { + const requests=[] + context.backend={ready:true,executable:'/test/omamail', + apiVersion:compatibility.usableApiVersion(info,7,8,contractHash), + call(method,params,callback){requests.push({method,params,callback})}} + let failure + context.trashMessage('frozen-message',(value,error)=>failure=error) + assert.strictEqual(requests.length,1) + assert.strictEqual(requests[0].method,expected) + assert.strictEqual(requests[0].params.accountId,'synthetic@example.org') + if (expected==='local.edit') { + assert.deepStrictEqual(Array.from(requests[0].params.ids),['frozen-message']) + requests[0].callback(null,{message:'local_disk_full'}) + assert(failure.includes('disk space')) + } else { + assert.strictEqual(requests[0].params.id,'frozen-message') + requests[0].callback({},null) + assert.strictEqual(failure,'') + } +} +console.log('Gmail deletion uses only the confirmed API contract and preserves error reasons') diff --git a/tests/test_performance_verification.py b/tests/test_performance_verification.py new file mode 100644 index 000000000..15a9b61f4 --- /dev/null +++ b/tests/test_performance_verification.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""The verification runner preserves failures and confines test state/processes.""" +import importlib.util +import json +import os +from pathlib import Path +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("verification", ROOT / "scripts/verify-performance.py") +verification = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verification) + + +class VerificationTests(unittest.TestCase): + def test_child_environment_has_no_account_state_or_tokens(self): + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + with patch.dict(os.environ, {"GH_TOKEN": "secret", "DBUS_SESSION_BUS_ADDRESS": "real-bus", + "OMAMAIL_BIN": "/installed/binary", "WAYLAND_DISPLAY": "real-display"}): + env = verification.test_environment(directory) + for key in ("GH_TOKEN", "DBUS_SESSION_BUS_ADDRESS", "OMAMAIL_BIN", "WAYLAND_DISPLAY"): + self.assertNotIn(key, env) + for key in ("HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"): + self.assertTrue(Path(env[key]).is_relative_to(directory)) + self.assertEqual(Path(env[key]).stat().st_mode & 0o777, 0o700) + + def test_failure_keeps_exit_status_and_log(self): + with tempfile.TemporaryDirectory() as temp: + log = Path(temp) / "failed.log" + result = verification.execute([sys.executable, "-c", "print('failure evidence');exit(7)"], + os.environ.copy(), log, 5) + self.assertEqual(result["status"], "fail") + self.assertEqual(result["exitCode"], 7) + self.assertIn("failure evidence", log.read_text()) + + def test_timeout_kills_descendants_before_their_write(self): + with tempfile.TemporaryDirectory() as temp: + marker = Path(temp) / "forbidden-write" + child = f"import time;from pathlib import Path;time.sleep(1);Path({str(marker)!r}).touch()" + parent = f"import subprocess,sys,time;subprocess.Popen([sys.executable,'-c',{child!r}]);time.sleep(5)" + result = verification.execute([sys.executable, "-c", parent], os.environ.copy(), + Path(temp) / "timeout.log", .2) + self.assertEqual(result["status"], "fail") + self.assertEqual(result["reason"], "deadline exceeded") + time.sleep(1.1) + self.assertFalse(marker.exists(), "the timed-out process tree must not continue work") + + def test_report_retains_blocked_and_failed_results(self): + with tempfile.TemporaryDirectory() as temp: + report = {"profile": "ci", "status": "fail", "gates": [ + {"name": "one", "status": "pass"}, + {"name": "two", "status": "blocked", "reason": "no socket"}, + {"name": "three", "status": "fail", "exitCode": 7}]} + verification.save(Path(temp), report) + self.assertEqual(json.loads((Path(temp) / "results.json").read_text()), report) + self.assertIn("| two | blocked | no socket |", (Path(temp) / "summary.md").read_text()) + + def test_ci_includes_native_qml_security_and_actual_api(self): + gates = {name: command for name, command, _ in verification.stages("ci", Path("/tmp/report"), "HEAD")} + self.assertIn("test-qml", gates["qml"]) + self.assertIn("tests/test_backend_api.py", gates["api-contract"]) + self.assertIn("--no-tests=error", gates["native-host"]) + self.assertIn("test-rust", gates["rust"]) + self.assertIn("local_mail::recovery_tests", gates["offline-recovery"]) + self.assertIn("process::", gates["subprocess"]) + requirements = {name: needs for name, _, needs in verification.stages("ci", Path("/tmp/report"), "HEAD")} + self.assertNotIn("tcp", requirements["offline-recovery"]) + self.assertNotIn("dbus", requirements["subprocess"]) + for name in ("standalone-qml", "native-host", "qml-lint", "qml-components", "shell-independent"): + self.assertNotIn("dbus", requirements[name]) + self.assertNotIn("tcp", requirements[name]) + self.assertNotIn("dbus-run-session", gates[name]) + self.assertIn("test-shell-independent", gates["shell-independent"]) + self.assertIn("test-shell-portable", gates["shell"]) + self.assertIn("tcp", requirements["shell"]) + self.assertIn("pdf-sandbox", requirements["rust"]) + self.assertIn("tests/run_qml_components.py", gates["qml-components"]) + self.assertIn("QMLLINT=" + (verification.qt_tool("qmllint") or "qmllint"), gates["qml-lint"]) + self.assertEqual(verification.prerequisites("api-contract"), ["build"]) + self.assertEqual(verification.prerequisites("database-background"), ["build-benchmarks"]) + self.assertEqual(verification.prerequisites("javascript"), []) + desktop = {name for name, _, _ in verification.stages("desktop", Path("/tmp/report"), "HEAD")} + self.assertTrue({"validate", "quickshell-bridge"} <= desktop) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_source.sh b/tests/test_source.sh index 250c7601d..1c89ba81b 100755 --- a/tests/test_source.sh +++ b/tests/test_source.sh @@ -419,7 +419,7 @@ if "accountId: root.calendarAccountId" not in service: # one is open. Keying by the account there stored a copy of the same events per # account and turned every mailbox switch into a cache miss and a full refetch. controller = Path("calendar/CalendarController.qml").read_text() -if "eventCache.get(refreshScope" not in controller or "eventCache.put(refreshScope" not in controller: +if "cachedEventsFor(refreshScope" not in controller or "eventCache.get(scope" not in controller or "eventCache.put(refreshScope" not in controller: raise SystemExit("test_source.sh: the event cache must be keyed by the calendar scope, not the mailbox") # The reload watches the scope rather than the two things that go into it. A # mailbox switch under the unified view changes nothing on screen, and neither @@ -515,15 +515,15 @@ grep -q 'onEnabledSourceKeyChanged: reloadVisibleRange()' calendar/CalendarContr || fail "calendar events must load automatically when a source is discovered" grep -q 'function onSourcesLoadedChanged' components/CalendarView.qml \ || fail "the calendar view must refresh when its saved sources become ready" -grep -q 'property double pendingRangeStart' calendar/CalendarController.qml \ - || fail "a calendar range change during loading must be queued" +grep -q 'rangeStart = requestedStart' calendar/CalendarController.qml \ + || fail "a calendar range change must select the target range immediately" grep -q 'CalendarCache {' calendar/CalendarController.qml \ || fail "CalendarController must restore events before refreshing the network" if grep -q '^ events = \[\]$' calendar/CalendarController.qml; then fail "Calendar refresh must not blank cached events before the network answers" fi -grep -q 'root.refresh(nextStart, nextEnd)' calendar/CalendarController.qml \ - || fail "the queued calendar range must run after the active refresh" +grep -q 'serial!==root.refreshSerial' calendar/CalendarController.qml \ + || fail "an old calendar response must not replace the selected range" grep -q '"calendar.request"' calendar/CalendarController.qml \ || fail "calendar operations must use the bounded native backend" python3 - <<'PY' @@ -620,7 +620,7 @@ grep -q 'id: dayHeaders' components/WeekCalendarView.qml \ # Row fills reach the list/reader divider; content padding belongs inside a # row, not in a gutter that cuts every selected background short. -grep -q 'width: listFlick\.width$' App.qml \ +grep -q 'width: root.width$' components/MessageList.qml \ || fail "message rows must reach the list column edge" grep -q 'leadingBoundaryOverlap: listSplitter.visible ? listSplitter.width : 0' App.qml \ || fail "the reader toolbar boundary must cross the splitter hit area to meet its visible rule" diff --git a/ui/App.qml b/ui/App.qml index 1b4fbdaa2..4ab345384 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -617,19 +617,8 @@ Item { nav = Nav.replaceRoot(nav, "calendar") } - // Moving the cursor has to bring the row with it. The list is a Column in a - // Flickable rather than a ListView — the panel already owns a scroller — so - // there is no positionViewAtIndex and this has to be said out loud. - // - // Called only for keyboard movement. Pointer hover stays local to the row, - // and a programmatic selection does not scroll the list under the pointer. function revealCursorRow() { - if (!listFlick.visible) return - var bounds = list.boundsFor(cursorId) - if (!bounds) return - listFlick.contentY = Model.contentYToReveal(listFlick.contentY, - listFlick.height, list.y + bounds.y, bounds.height, - listFlick.contentHeight, MailStyle.space(8)) + if (list.visible) list.reveal(cursorId) } // Keyboard selection is explicit reading, with the same cache, network and @@ -1903,29 +1892,26 @@ Item { visible: width > 0 && !root.showPage && !root.composing && !root.calendarVisible - // The scroller fills the column so its bar sits on the column edge; - // the breathing room is padding on the content, not a margin on the - // viewport, which would push the bar inward with it. - Flickable { - id: listFlick - - WheelScroller { view: listFlick } - anchors.fill: parent - contentWidth: width - contentHeight: list.implicitHeight + MailStyle.space(12) - clip: true - boundsBehavior: Flickable.StopAtBounds - ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } - - MessageList { + LocalMailStatus { + id: localStatus + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.margins: MailStyle.space(8) + mailbox: root.service.localMailbox || null + textColor: root.foreground + dimColor: root.dim + panelFontFamily: MailStyle.listFamily + } + MessageList { id: list - scroller: listFlick - // Match the sidebar's first row inset below the header. - y: MailStyle.space(6) - // Full width, so selected and hovered rows meet the splitter. - // Text and action breathing room belongs inside MessageRow; - // shrinking the whole list leaves a conspicuous dead strip. - width: listFlick.width + anchors.top: localStatus.visible ? localStatus.bottom : parent.top + anchors.topMargin: localStatus.visible ? MailStyle.space(6) : 0 + anchors.bottom: parent.bottom + anchors.left: parent.left + anchors.right: parent.right + WheelScroller { view: list } + ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } service: root.service textColor: root.foreground accentColor: root.accent @@ -1947,7 +1933,6 @@ Item { rowMenu.openAt(id, sceneX, sceneY) } } - } } @@ -2372,6 +2357,7 @@ Item { z: 80 visible: !!root.service && root.service.sendPending && compose.parkedForSend secondsRemaining: root.service ? root.service.sendSecondsRemaining : 0 + awaitingConnection: !!root.service && root.service.sendAwaitingConnection === true queuedCount: root.service && root.service.sendPendingCount !== undefined ? root.service.sendPendingCount : 1 textColor: root.foreground @@ -2425,7 +2411,9 @@ Item { } Text { id: noticeText - anchors.fill: parent + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right anchors.margins: MailStyle.space(8) textFormat: Text.PlainText anchors.rightMargin: diagnoseErrorButton.visible ? diagnoseErrorButton.width + MailStyle.space(8) : MailStyle.space(8) diff --git a/ui/Service.qml b/ui/Service.qml index 460fab480..8b5452272 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -47,9 +47,7 @@ Item { property var manifest: null property var pluginRegistry: null property var barWidgetRegistry: null - // Optional host seam. The Omarchy shell does not inject it and therefore - // keeps every existing plugin path; the standalone composition supplies a - // narrow adapter for native operations and its bundled backend. + // The native host supplies this adapter; the plugin shell leaves it unset. property var platform: null property var initialSettings: null readonly property var capabilities: platform && platform.capabilities @@ -65,7 +63,8 @@ Item { pluginDir: root.pluginDir bundledExecutable: root.standalone ? String(root.platform.backendPath || "") : "" bundledVersion: root.standalone ? root.version : "" - bundledApiVersion: root.standalone ? 6 : 0 + bundledApiVersion: Number(bundledContract.releasedApiVersion || 0) + bundledContract: root.standalone ? root.platform.backendContract || ({}) : ({}) bundledMode: root.standalone developmentExecutable: root.standalone ? "" : (Quickshell.env("OMAMAIL_BIN") || "") onValidated: Qt.callLater(rustBackend.reconcileProcess) @@ -96,6 +95,7 @@ Item { expectedApiVersion: privateRuntime.requiredApiVersion latestApiVersion: privateRuntime.latestApiVersion unreleasedMethods: privateRuntime.unreleasedMethods + expectedContractHash: privateRuntime.contractHash onReadyChanged: root.scheduleUnifiedSnapshot() onRequestFailed: function(method, error) { if (diagnosticsLoader.item) diagnosticsLoader.item.record(method, error) @@ -1699,10 +1699,8 @@ Item { readonly property var auth: current ? current.auth : null readonly property bool ready: !!current && current.ready + readonly property var localMailbox: !unified && current ? current.local : null readonly property string accountEmail: current ? current.accountEmail : "" - // The short name the switcher shows for the account on screen — the label - // the user gave it, or the local part of its address. The sidebar's user - // bar shows this; the full address is on the status line. readonly property string accountLabel: { var entry = Accounts.find(accountList, activeAccountId) return entry ? Accounts.label(entry) : "" @@ -2025,15 +2023,14 @@ Item { } return newest } + readonly property bool sendAwaitingConnection: !!pendingSendHost && !!pendingSendHost.latestSend + && pendingSendHost.latestSend.error === "outbox_awaiting_connection" readonly property bool sendPending: !!pendingSendHost readonly property int sendSecondsRemaining: pendingSendHost ? pendingSendHost.sendSecondsRemaining : 0 readonly property string lastError: unified ? (unifiedBatchAction.error || unifiedSnapshotError || unifiedSnapshot.error || "") : (current ? current.lastError : "") - // The last thing a mailbox said it did, and the undo that goes with it. Read - // from `current` alone, archiving a row from a non-active mailbox in a merged - // list produced no confirmation and no undo affordance at all — so the most - // recent of them wins, which is the one the press just produced. + // Unified actions expose the newest notice and undo across all accounts. readonly property string actionStatus: { if (!unified) return current ? current.actionStatus : "" if (unifiedBatchAction.status !== "") return unifiedBatchAction.status @@ -2391,9 +2388,9 @@ Item { } return host.undoSend(callback) } - function loadAttachments(messageId, attachments, callback) { + function loadAttachments(messageId, attachments, callback, draftKey) { var host = hostForId(messageId) - if (host) return host.loadAttachments(sourceIdFor(messageId), attachments, callback) + if (host) return host.loadAttachments(sourceIdFor(messageId), attachments, callback, draftKey) if (typeof callback === "function") callback([], "No mailbox is selected") return null } @@ -2605,6 +2602,9 @@ Item { // ------------------------------------------------------------- instances + readonly property alias calendarCache: sharedCalendarCache + CalendarCache { id: sharedCalendarCache; backend: root.backend; cacheName: root.backend && Number(root.backend.apiVersion)>=8 ? "calendar-shared" : "calendar" } + CalendarController { id: sharedCalendar service: root diff --git a/ui/account/AccountResources.qml b/ui/account/AccountResources.qml new file mode 100644 index 000000000..7030f42da --- /dev/null +++ b/ui/account/AccountResources.qml @@ -0,0 +1,76 @@ +import QtQuick +import "Model.js" as Model +import "../message/AttachmentPreview.js" as AttachmentPreview + +Item { + id: root + required property var account + readonly property var backend: account.backend + + function summaryProgress(ids, base, serial) { + var arrived = Object.create(null) + return function(payloads) { + if (serial !== root.account.listSerial) return + for (var i=0;i=account.messages.length) continue + ids.push(account.messages[at+offset].id) + } + backend.call("reader.prefetch",{accountId:account.accountId,ids:ids,now:Date.now(), + options:{allowRemoteImages:false,withReader:true}},function(){}) + } + + function previewAttachment(messageId, attachment, callback) { + var done = typeof callback === "function" ? callback : function() {} + var id = String(messageId || "") + var source = null + for (var i = 0; i < account.selectedAttachments.length; i++) { + if (attachment && account.selectedAttachments[i].attachmentId === attachment.attachmentId) + source = account.selectedAttachments[i] + } + if (!account.ready || id !== account.selectedId || !source || !AttachmentPreview.supported(source) + || !backend || !backend.ready || Number(backend.apiVersion) < 8) { done(""); return null } + var serial = account.detailSerial + var identity = account.accountId + var cancelled = false + var request=backend.call("attachment.preview",{accountId:identity,messageId:id, + attachmentId:String(source.attachmentId),filename:String(source.filename || "attachment"), + mimeType:String(source.mimeType || "").toLowerCase()},function(result,error) { + if (cancelled || !root || identity !== root.account.accountId + || id !== root.account.selectedId || serial !== root.account.detailSerial) return + done(error || !result ? "" : String(result.data || "")) + }) + return {cancel:function(){cancelled=true; if(request && typeof request.cancel === "function") request.cancel()}} + } + + function downloadAttachment(messageId, source, open) { + var key = String(source.attachmentId || "") + if (account.savingAttachmentIds[key]) return + var identity = account.accountId + account.markSavingAttachment(key,true) + account.note((open ? "Opening " : "Saving ") + String(source.filename || "attachment")) + backend.call("attachment.download",{accountId:identity,messageId:String(messageId),attachmentId:key, + filename:String(source.filename || "attachment"),mimeType:String(source.mimeType || "application/octet-stream"),open:open},function(result,error) { + if (identity !== root.account.accountId) return + root.account.markSavingAttachment(key,false) + if (error || !result || !result.path) {root.account.fail("That attachment could not be " + (open ? "opened" : "saved"));return} + if (open && root.account.platform && typeof root.account.platform.openExternal === "function") + root.account.platform.openExternal(String(result.path)) + root.account.note(open ? "Opening " + String(source.filename || "attachment") : "Saved " + String(result.path)) + }) + } +} diff --git a/ui/account/LocalMailbox.qml b/ui/account/LocalMailbox.qml new file mode 100644 index 000000000..30586a199 --- /dev/null +++ b/ui/account/LocalMailbox.qml @@ -0,0 +1,159 @@ +import QtQuick + +Item { + id: root + required property var account + readonly property var backend: account.backend + readonly property bool available: account.providerId === "gmail" && !!backend + && backend.ready && Number(backend.apiVersion) >= 8 + property var status: ({}) + property bool onlineSearch: false + property string onlineQuery: "" + readonly property bool hasMail: Number(status.stored || 0) > 0 + property bool refreshing: false + property string error: "" + property var edits: [] + property string watched: "" + property bool overviewBusy: false + function refreshOverview(check) { + if (!available || overviewBusy) return + var identity=account.accountId + overviewBusy=true + var method=watched!==identity ? "local.watch" : check ? "local.refresh" : "local.overview" + backend.call(method,{accountId:identity},function(result,failure) { + if (identity!==root.account.accountId) return + root.overviewBusy=false + if (failure) return + root.watched=identity + root.status=result.coverage || ({}) + var before=root.account.inboxUnread + var first=!root.account.countPrimed + root.account.countPrimed=true + root.account.inboxUnread=Number(result.unread || 0) + root.account.previewMessages=result.summaries || [] + var labels=result.labels || [] + var oldLabels=root.account.labels || [] + var oldById=({}) + for (var l=0;lbefore || (root.account.active && !root.account.listLoaded))) root.account.loadMessages(false,true) + }) + } + function stopWatch() { + if (watched && backend && backend.ready) backend.call("local.unwatch",{accountId:watched},function(){}) + watched="" + } + function dismissConflict(ticket) { + var identity=account.accountId + backend.call("local.dismissConflict",{accountId:identity,ticket:ticket},function(result,failure){ + if (identity!==root.account.accountId) return + if (failure) {root.error="Could not dismiss this notice. Try again.";return} + root.refreshStatus();root.refreshEdits() + }) + } + + function refreshStatus() { + if (!available || refreshing) return + refreshing = true + var identity = account.accountId + backend.call("local.status", {accountId:identity}, function(result, failure) { + root.refreshing = false + if (identity !== root.account.accountId) return + if (failure) { root.error = "Offline mail is unavailable. Your saved messages have been kept."; return } + root.status = result || ({}) + root.error = "" + }) + } + function setPaused(paused) { + if (!available) return + var identity = account.accountId + backend.call("local.pause", {accountId:identity,paused:paused}, function(result,failure) { + if (identity !== root.account.accountId) return + if (failure) { root.error = "Could not change the download setting. Try again."; return } + root.status = result || ({}) + }) + } + function searchOnline() { + onlineSearch = true + onlineQuery = account.effectiveQuery + account.loadMessages(false,true) + } + function load(append, limit, serial) { + if (!available) return false + if (onlineSearch && onlineQuery === account.effectiveQuery) return false + onlineSearch = false + var identity = account.accountId + backend.call("local.list", {accountId:identity,query:account.effectiveQuery, + limit:Math.min(100000,limit),pageToken:append ? account.nextPageToken : ""}, function(result,failure) { + if (identity !== root.account.accountId || serial !== root.account.listSerial) return + root.account.listLoading = false + if (failure) { + root.error = String(failure.message || "") === "local_search_unsupported" + ? "This search needs Gmail. Choose Search online to continue." + : "Could not read offline mail. Your saved messages have been kept." + root.account.nextPageToken = "" + return + } + root.error = "" + root.status = result.coverage || ({}) + var summaries = result.summaries || [] + for (var i=0;i 0 && labels.length === 0) labels = cacheStore.store.labels api.getLabels(function(result, error) { @@ -811,7 +813,7 @@ Item { resource.nativeSummary = root.hydrateSummary(resource.nativeSummary) callback(resource, "", cached, options.allowRemoteImages) } else if (!cached) callback(null, "Could not open that message", false) - if (cached) read(false) + if (cached && !(root.local && root.local.available && resource && !error)) read(false) }) } if (!backend) { callback(null, "Mail backend is unavailable", false); return handle } @@ -938,6 +940,7 @@ Item { listLoading = true var token = append ? nextPageToken : "" var limit = append ? maxMessages : Model.reloadLimit(maxMessages, loadedDepth) + if (localMailbox.load(append,limit,serial)) return // A typed search accepts ids while the provider is still finding them. // Mailbox and label listings have no long-running search phase, so their @@ -1176,6 +1179,8 @@ Item { } function fetchSummaries(ids, append, serial, preservedError) { + var base = append ? root.messages.slice() : [] + var progress = resources.summaryProgress(ids,base,serial) root.summarizedRead(ids, false, function(payloads, error) { if (serial !== root.listSerial) return root.listLoading = false @@ -1197,6 +1202,7 @@ Item { root.fail(metadataError) return } + if (append) root.messages = base root.applySummaries(summaries, append, false, metadataError === "", function() { if (metadataError !== "") { // The list endpoint's token follows every id it returned, including a @@ -1217,7 +1223,7 @@ Item { if (preservedError !== "") root.fail(preservedError) }) }) - }, listHandle) + }, listHandle, progress) } function applySummaries(summaries, append, suppressArrivals, markSynced, callback) { @@ -1225,6 +1231,7 @@ Item { var account = accountId var list = listSerial var merged = append ? root.messages.concat(summaries) : summaries + if (root.local && root.local.available) root.messages = merged // A manual search may uncover an old unread row the current mailbox page // never held. That is a result, not newly arrived mail, so it must not turn // into a desktop notification. @@ -1339,6 +1346,22 @@ Item { } if (cached) root.detailCachedResource = true else root.detailLive = true + var decoded = payload.nativeContent.body + root.renderSerial++ + root.selectedHasHtml = !!payload.hasHtml + root.readerSourceKey = payload.hasHtml ? String(payload.readerKey) : "" + var ready = payload.nativeRender + root.adoptRendered(ready, readAllowsRemoteImages) + root.detailLoading = false + root.detailPainted = true + Qt.callLater(function() { if (serial===root.detailSerial) resources.warmNeighbours(messageId) }) + root.lastError = "" + if (ready.plainText) decoded = ({ text: ready.plainText.text, source: "html", bodyDirection: ready.plainText.bodyDirection || "" }) + root.selectedBody = decoded + root.selectedImages = ready.plainText ? ready.plainText.images : [] + + root.selectedAttachments = payload.nativeContent.attachments + // Merged with the row rather than replacing it: a provider whose detail // read carries no subject line of its own — HEY reads a conversation, not // a message — would otherwise blank the one the list had drawn. @@ -1359,20 +1382,6 @@ Item { if (serial !== root.detailSerial || (cached && root.detailLive)) return summary = root.hydrateSummary(summary) root.selectedMessage = summary - var decoded = payload.nativeContent.body - root.renderSerial++ - root.selectedHasHtml = !!payload.hasHtml - root.readerSourceKey = payload.hasHtml ? String(payload.readerKey) : "" - var ready = payload.nativeRender - root.adoptRendered(ready, readAllowsRemoteImages) - root.detailLoading = false - root.detailPainted = true - root.lastError = "" - if (ready.plainText) decoded = ({ text: ready.plainText.text, source: "html", bodyDirection: ready.plainText.bodyDirection || "" }) - root.selectedBody = decoded - root.selectedImages = ready.plainText ? ready.plainText.images : [] - - root.selectedAttachments = payload.nativeContent.attachments root.selectedInvite = payload.cachedInvite || Calendar.fromPayload(payload.payload) root.selectedUnsubscribe = Unsub.fromMessage(payload) // Only the invitation overlay may need persistence after its attachment @@ -2038,7 +2047,7 @@ Item { // Loads the original bytes before a forward can claim it includes them. // Gmail fetches each part; IMAP reads the same part from the full message. - function loadAttachments(messageId, attachments, callback) { + function loadAttachments(messageId, attachments, callback, draftKey) { var listed = Array.isArray(attachments) ? attachments : [] if (listed.length === 0) { if (typeof callback === "function") callback([], "") @@ -2051,6 +2060,17 @@ Item { for (var i = 0; i < listed.length; i++) { (function(index) { var source = listed[index] || ({}) + if (draftKey && backend && backend.ready && Number(backend.apiVersion)>=8 && providerId!=="hey") { + handles.push(backend.call("attachment.retain",{accountId:accountId,draftKey:String(draftKey), + messageId:String(messageId),attachmentId:String(source.attachmentId || ""), + filename:String(source.filename || "attachment"),mimeType:String(source.mimeType || "application/octet-stream")},function(result,error) { + if (error && firstError === "") firstError = "Could not include " + String(source.filename || "an attachment") + loaded[index] = result + remaining-- + if (remaining === 0 && typeof callback === "function") callback(loaded,firstError) + })) + return + } handles.push(api.getAttachment(messageId, String(source.attachmentId || ""), function(data, error) { if (error && firstError === "") @@ -2072,41 +2092,9 @@ Item { } function previewAttachment(messageId, attachment, callback) { - var done = typeof callback === "function" ? callback : function() {} - var id = String(messageId || "") - var source = null - for (var i = 0; i < selectedAttachments.length; i++) { - if (attachment && selectedAttachments[i].attachmentId === attachment.attachmentId) - source = selectedAttachments[i] - } - if (!ready || id !== selectedId || !source || !AttachmentPreview.supported(source) || !backend || !backend.ready - || Number(backend.apiVersion) < 8) { done(""); return null } - var serial = detailSerial - var account = accountId - var cancelled = false - var previewRequest = null - var request = api.getAttachment(id, String(source.attachmentId), function(data, error) { - if (cancelled || !root) return - if (account !== root.accountId || id !== root.selectedId || serial !== root.detailSerial) { done(""); return } - if (error || !data || data.length > 11200000) { done(""); return } - previewRequest = root.backend.call("attachment.thumbnail", { - data: String(data), mimeType: String(source.mimeType || "").toLowerCase() - }, function(result, failure) { - if (cancelled || !root) return - if (account !== root.accountId || id !== root.selectedId || serial !== root.detailSerial) { done(""); return } - done(failure || !result ? "" : String(result.data || "")) - }) - }) - return {cancel: function() { - cancelled = true - if (root) root.abortRequest(request) - if (previewRequest && typeof previewRequest.cancel === "function") previewRequest.cancel() - }} + return resources.previewAttachment(messageId,attachment,callback) } - // Opens only after the user asks. The provider hands back base64url bytes; - // the backend writes them to a private runtime file before the desktop opens - // the file with its registered application. function openAttachment(messageId, attachment) { var source = attachment || ({}) if (!ready) { @@ -2117,6 +2105,7 @@ Item { fail("That attachment is not available") return } + if (backend && backend.ready && Number(backend.apiVersion)>=8) {resources.downloadAttachment(messageId,source,true);return} clearNotice() loadAttachments(messageId, [source], function(loaded, error) { if (error || !loaded || loaded.length === 0) { @@ -2160,6 +2149,7 @@ Item { fail("That attachment is not available") return } + if (backend && backend.ready && Number(backend.apiVersion)>=8) {resources.downloadAttachment(messageId,source,false);return} // One save at a time for one attachment. A download arrow is a single // click, and a double one used to start a second fetch that the script // then dutifully numbered: two identical files in Downloads, and a notice @@ -2307,6 +2297,7 @@ Item { return null } var composeFields = ({ + draftKey: String(values.draftKey || ""), from: from, fromName: alias ? String(alias.displayName || "") : "", // What the generated Message-ID takes its domain from when the draft @@ -2329,6 +2320,16 @@ Item { var handle = {aborted: false, children: []} var account = accountId if (!backend) { if (typeof callback === "function") callback(null, "Mail backend is unavailable"); return handle } + if (Number(backend.apiVersion)>=8 && providerId!=="hey") { + var nativeJob=backend.call("draft.compose",{accountId:account,fields:composeFields},function(saved,error) { + if (handle.aborted || account!==root.accountId) return + if (typeof callback === "function") callback(saved,error ? "Could not save this draft online. Your local draft has been kept." : "") + if (!error && root.mailboxKey==="drafts") root.loadMessages(false,true,"") + else if (!error) root.refreshCounts() + }) + if (nativeJob) handle.children.push(nativeJob) + return handle + } backend.call("message.compose", {fields: composeFields}, function(payload, composeError) { if (handle.aborted || account !== root.accountId) return if (composeError || !payload) { @@ -2378,7 +2379,7 @@ Item { var files = Array.isArray(values.attachments) ? values.attachments : [] var hasFiles = false for (var fi = 0; fi < files.length; fi++) { - if (files[fi] && (files[fi].data || files[fi].path)) hasFiles = true + if (files[fi] && (files[fi].data || files[fi].path || files[fi].handle)) hasFiles = true } var body = String(values.body || "") if (values.exactBody !== true) body = body.trim() @@ -2401,6 +2402,7 @@ Item { return false } var composeFields = ({ + draftKey: String(values.draftKey || ""), from: from, fromName: alias ? String(alias.displayName || "") : "", // What the generated Message-ID takes its domain from when the compose @@ -2425,6 +2427,10 @@ Item { }) var account = accountId if (!backend) { reportSendFailure("Mail backend is unavailable", id); return "" } + if (Number(backend.apiVersion) >= 8) { + if (!sendQueue.park(null,id,order,composeFields)) reportSendFailure("Could not queue this message",id) + return id + } backend.call("message.compose", {fields: composeFields}, function(payload, error) { if (account !== root.accountId) return if (error || !payload) { root.reportSendFailure("Could not prepare this message", id); return } @@ -2931,7 +2937,7 @@ Item { BackendSync { id: backendSync backend: root.backend - enabled: root.ready && root.nativePolling + enabled: root.ready && root.nativePolling && !localMailbox.available accountId: root.accountId query: Provider.unreadQuery(root.providerId) intervalSec: root.refreshIntervalSec diff --git a/ui/account/SendQueue.qml b/ui/account/SendQueue.qml index 1524f986d..d1061f3b4 100644 --- a/ui/account/SendQueue.qml +++ b/ui/account/SendQueue.qml @@ -68,7 +68,7 @@ QtObject { var entry = entries[i] var id = String(entry.id || "") delete remaining[id] - if (entry.state === "queued") waiting.push(entry) + if (entry.state === "queued" || entry.state === "waiting") waiting.push(entry) if (entry.state === "sending") busy = true if (done[id] === entry.state) continue if (entry.state === "sent") { @@ -102,7 +102,7 @@ QtObject { })(receipts[r]) } } - function park(payload, id, order) { + function park(payload, id, order, nativeFields) { var sendId = String(id || "") var now = Date.now() var next = Object.assign({}, submitted) @@ -110,8 +110,11 @@ QtObject { submitted = next parked = parked.concat([next[sendId]]) arm() - request("outbox.enqueue", { provider: String(account.providerId || ""), payload: payload, - sendId: sendId, order: Math.max(0, Math.floor(Number(order) || 0)), delaySeconds: account.undoSendSeconds }, function(result, error) { + var params = {provider:String(account.providerId || ""),sendId:sendId, + order:Math.max(0,Math.floor(Number(order) || 0)),delaySeconds:account.undoSendSeconds} + if (nativeFields) { params.fields = nativeFields; params.resumeUnsent = true } + else params.payload = payload + request(nativeFields ? "outbox.compose" : "outbox.enqueue", params, function(result, error) { if (error) { if (queue.handled[sendId] === "sent") return var unknown = Object.assign({}, queue.uncertain) diff --git a/ui/backend/Backend.qml b/ui/backend/Backend.qml index 079b22a93..c0e7e2f4e 100644 --- a/ui/backend/Backend.qml +++ b/ui/backend/Backend.qml @@ -15,8 +15,10 @@ Item { // refused here rather than sent to a binary that never heard of it. property int latestApiVersion: 0 property var unreleasedMethods: [] - readonly property int apiVersion: Compatibility.connectedApiVersion(protocolInfo) - readonly property bool needsUpdate: ready && Compatibility.needsUpdate(protocolInfo, latestApiVersion) + property string expectedContractHash: "" + readonly property int apiVersion: Compatibility.usableApiVersion(protocolInfo, + expectedApiVersion, latestApiVersion, expectedContractHash) + readonly property bool needsUpdate: ready && apiVersion < latestApiVersion property bool launchEnabled: true onLaunchEnabledChanged: Qt.callLater(reconcileProcess) onExecutableChanged: Qt.callLater(reconcileProcess) @@ -67,6 +69,8 @@ Item { } function call(method, params, callback) { + if (operationRefusal(method, params) !== null) + return request(method, params, callback, false) // Keep each physical frame small even for Unicode-heavy MIME/JSON data. if (JSON.stringify(params).length > 200000) { return Upload.request(method, params, function(nextMethod, nextParams, done) { @@ -76,6 +80,12 @@ Item { return request(method, params, callback, false) } + function operationRefusal(method, params) { + var operation = method === "request.upload" && params ? params.method : method + return Compatibility.unreleasedRefusal(operation, unreleasedMethods, needsUpdate) + || Compatibility.methodRefusal(protocolInfo, operation) + } + function request(method, params, callback, internal) { var operation = method === "request.upload" && params ? params.method : method var done = function(result, error) { @@ -88,7 +98,7 @@ Item { done(null, { code: -32010, message: message }) return } - var refusal = Compatibility.unreleasedRefusal(operation, unreleasedMethods, needsUpdate) + var refusal = operationRefusal(method, params) if (refusal !== null) { done(null, refusal) return diff --git a/ui/backend/Compatibility.js b/ui/backend/Compatibility.js index 3ec7e6aae..8dbfd4266 100644 --- a/ui/backend/Compatibility.js +++ b/ui/backend/Compatibility.js @@ -26,6 +26,21 @@ function connectedApiVersion(info) { return typeof info.apiVersion === "number" ? info.apiVersion : 0 } +function usableApiVersion(info, released, latest, contractHash) { + var connected = connectedApiVersion(info) + if (connected <= released) return connected + if (connected !== latest || latest !== released + 1) return 0 + if (typeof contractHash !== "string" || !/^[a-f0-9]{64}$/.test(contractHash) + || info.contractHash !== contractHash) return released + return connected +} + +function methodRefusal(info, method) { + if (!info || !Array.isArray(info.methods)) return null + if (info.methods.indexOf(String(method || "")) >= 0) return null + return { code: -32012, message: NEEDS_UPDATE } +} + // Whether the checkout implements an API step the connected binary lacks. // True only with a binary connected: nothing to update until there is one. function needsUpdate(info, latestApiVersion) { diff --git a/ui/backend/Runtime.js b/ui/backend/Runtime.js index becbcc18e..89042c631 100644 --- a/ui/backend/Runtime.js +++ b/ui/backend/Runtime.js @@ -2,7 +2,7 @@ function decode(raw) { var failed = { state: "error", requiredVersion: "", requiredApiVersion: 0, latestApiVersion: 0, - unreleasedMethods: [], installedVersion: "", + unreleasedMethods: [], contractHash: "", installedVersion: "", executable: "", error: "Could not read backend runtime status", development: false, cliInstalled: false } var value try { value = JSON.parse(raw) } catch (e) { return failed } @@ -27,6 +27,8 @@ function decode(raw) { return { state: value.state, requiredVersion: value.requiredVersion, requiredApiVersion: value.requiredApiVersion || 0, latestApiVersion: latest || 0, unreleasedMethods: unreleased, + contractHash: typeof value.contractHash === "string" && /^[a-f0-9]{64}$/.test(value.contractHash) + ? value.contractHash : "", installedVersion: value.installedVersion, executable: value.state === "ready" ? value.executable : "", error: value.error, development: value.development === true, diff --git a/ui/backend/Runtime.qml b/ui/backend/Runtime.qml index ebf14227b..b73169574 100644 --- a/ui/backend/Runtime.qml +++ b/ui/backend/Runtime.qml @@ -11,6 +11,7 @@ Item { property string bundledExecutable: "" property string bundledVersion: "" property int bundledApiVersion: 0 + property var bundledContract: ({}) property bool bundledMode: false property string developmentExecutable: "" state: "checking" @@ -20,6 +21,7 @@ Item { // that step has. The handshake does not read these; `Backend` does. property int latestApiVersion: 0 property var unreleasedMethods: [] + property string contractHash: "" property string installedVersion: "" property string executable: "" property string error: "" @@ -42,8 +44,9 @@ Item { // carries the released backend; `make app-run` builds this checkout's, // which answers with the unreleased step and was refused as incompatible. // Features still gate on the API the connected binary reports. - latestApiVersion = bundledApiVersion > 0 ? bundledApiVersion + 1 : 0 - unreleasedMethods = [] + latestApiVersion = Number(bundledContract.apiVersion || bundledApiVersion) + unreleasedMethods = bundledContract.unreleasedMethods || [] + contractHash = String(bundledContract.contractHash || "") installedVersion = bundledVersion executable = bundledExecutable error = bundledExecutable !== "" && bundledVersion !== "" && bundledApiVersion > 0 @@ -83,6 +86,7 @@ Item { // A status from before the step was reported, or a harness's, has no step. latestApiVersion = typeof result.latestApiVersion === "number" ? result.latestApiVersion : result.requiredApiVersion unreleasedMethods = Array.isArray(result.unreleasedMethods) ? result.unreleasedMethods : [] + contractHash = String(result.contractHash || "") installedVersion = result.installedVersion executable = exitCode === 0 ? result.executable : "" error = result.error diff --git a/ui/backend/Wire.js b/ui/backend/Wire.js index b3a049899..4402e02ce 100644 --- a/ui/backend/Wire.js +++ b/ui/backend/Wire.js @@ -30,7 +30,7 @@ function notification(line) { function notificationValue(value) { if (!value || typeof value !== "object" || Array.isArray(value) - || value.jsonrpc !== "2.0" || ["mail.updated", "accounts.changed", "outbox.changed", "gmail.settled"].indexOf(value.method) < 0 + || value.jsonrpc !== "2.0" || ["mail.updated", "accounts.changed", "outbox.changed", "gmail.settled", "local.changed"].indexOf(value.method) < 0 || Object.prototype.hasOwnProperty.call(value, "id") || !value.params || typeof value.params !== "object" || Array.isArray(value.params) || Object.keys(value).some(function(key) { return ["jsonrpc", "method", "params"].indexOf(key) < 0 })) return null @@ -39,6 +39,9 @@ function notificationValue(value) { || !/^[a-f0-9]{64}$/.test(value.params.revision))) return null if (value.method === "outbox.changed" && (typeof value.params.accountId !== "string" || !Array.isArray(value.params.entries))) return null + if (value.method === "local.changed" + && (typeof value.params.accountId !== "string" || !value.params.status + || typeof value.params.status !== "object" || Array.isArray(value.params.status))) return null if (value.method === "gmail.settled" && (typeof value.params.accountId !== "string" || typeof value.params.ticket !== "string" || typeof value.params.ok !== "boolean" || typeof value.params.error !== "string")) return null diff --git a/ui/calendar/Cache.js b/ui/calendar/Cache.js index 5fdc109bb..2e47f1767 100644 --- a/ui/calendar/Cache.js +++ b/ui/calendar/Cache.js @@ -5,8 +5,8 @@ // Older ranges cannot recover either value, so they are fetched again instead // of restoring rows that are unwritable or unsafe to edit. var VERSION = 3 -var MAX_RANGES = 8 -var MAX_EVENTS = 2500 +var MAX_RANGES = 32 +var MAX_EVENTS = 25000 function emptyStore() { return { version: VERSION, ranges: {} } @@ -34,36 +34,70 @@ function rangeKey(scope, startMs, endMs) { } function eventsFor(store, scope, startMs, endMs, enabledSourceIds) { - var source = store && store.ranges ? store.ranges[rangeKey(scope, startMs, endMs)] : null - if (!source && store && store.ranges) { - var candidates = Object.keys(store.ranges).filter(function(key) { - var range = store.ranges[key] - return key.indexOf(String(scope || "") + "\n") === 0 - && Number(range.startMs) < Number(endMs) && Number(range.endMs) > Number(startMs) - }) - candidates.sort(function(a, b) { return Number(store.ranges[b].at) - Number(store.ranges[a].at) }) - if (candidates.length) source = store.ranges[candidates[0]] - } - var values = source && Array.isArray(source.events) ? source.events : [] - var enabled = {} + var ranges = store && store.ranges || {} + var candidates = Object.keys(ranges).filter(function(key) { + var range = ranges[key] + return key.indexOf(String(scope || "") + "\n") === 0 + && Number(range.startMs) < Number(endMs) && Number(range.endMs) > Number(startMs) + }).map(function(key) { return ranges[key] }) var ids = Array.isArray(enabledSourceIds) ? enabledSourceIds : [] - for (var i = 0; i < ids.length; i++) enabled[String(ids[i])] = true var out = [] - for (var j = 0; j < values.length; j++) { - var event = values[j] - if (event && enabled[String(event.sourceId || "")] - && (!event.start || Number(event.start.ms) < Number(endMs)) - && (!event.end || Number(event.end.ms) > Number(startMs))) out.push(event) + for (var i = 0; i < ids.length; i++) { + var id = String(ids[i]) + var sources = candidates.filter(function(range) { + return (range.sources || []).indexOf(id) >= 0 || (range.events || []).some(function(event) { + return event && String(event.sourceId || "") === id + }) + }) + sources.sort(function(a,b) { + return Number(b.sourceTimes && b.sourceTimes[id] || b.at) + - Number(a.sourceTimes && a.sourceTimes[id] || a.at) + }) + var covered = [] + var seen = {} + for (var j = 0; j < sources.length; j++) { + var source = sources[j] + var values = source.events || [] + for (var k = 0; k < values.length; k++) { + var event = values[k] + if (!event || String(event.sourceId || "") !== id) continue + var begins = event.start ? Number(event.start.ms) : Number(source.startMs) + var ends = event.end ? Number(event.end.ms) : Number(source.endMs) + if (begins >= endMs || ends <= startMs) continue + if (covered.some(function(range) { return range.startMs < ends && range.endMs > begins })) continue + var key = String(event.uid || event.googleId || event.href || "") + ":" + begins + if (!seen[key]) out.push(event) + seen[key] = true + } + if ((source.sources || []).indexOf(id) >= 0) covered.push(source) + } } return out } -function putRange(store, scope, startMs, endMs, events, nowMs, refreshedSourceIds) { +function coversSource(store,scope,startMs,endMs,id) { + var ranges=store && store.ranges || {} + return Object.keys(ranges).some(function(key) { + var range=ranges[key] + return key.indexOf(String(scope || "")+"\n")===0 && Number(range.startMs)<=startMs && Number(range.endMs)>=endMs + && Array.isArray(range.sources) && range.sources.indexOf(String(id))>=0 + }) +} + +function putRange(store, scope, startMs, endMs, events, nowMs, refreshedSourceIds, requestAt) { var source = store && isObject(store.ranges) ? store.ranges : {} var ranges = {} for (var key in source) ranges[key] = source[key] var kept = Array.isArray(events) ? events.slice() : [] var old = source[rangeKey(scope, startMs, endMs)] + var stamp = Number(requestAt) || Number(nowMs) || 0 + var times = Object.assign({},old && old.sourceTimes || {}) + if (Array.isArray(refreshedSourceIds)) { + var accepted = refreshedSourceIds.filter(function(id) {return Number(times[id] || 0) <= stamp}) + kept = kept.filter(function(event) {return accepted.indexOf(String(event.sourceId || ""))>=0}) + refreshedSourceIds = accepted + for (var s=0;s MAX_EVENTS ? [] : (old && Array.isArray(old.sources) ? old.sources : []).concat( + Array.isArray(refreshedSourceIds) ? refreshedSourceIds : []).filter(function(id,index,values) { + return values.indexOf(id) === index + }) } var keys = Object.keys(ranges) keys.sort(function(a, b) { return Number(ranges[b].at) - Number(ranges[a].at) }) diff --git a/ui/calendar/Calendar.js b/ui/calendar/Calendar.js index 20a3f9c41..4b937e857 100644 --- a/ui/calendar/Calendar.js +++ b/ui/calendar/Calendar.js @@ -1285,6 +1285,26 @@ function eventsOnDay(events, day) { return out } +function indexDays(events, days) { + var result = {} + var ordered = (Array.isArray(events) ? events : []).slice().sort(compareEvents) + var dates = Array.isArray(days) ? days : [] + for (var d=0;d=0 + } - function put(scope, startMs, endMs, events, refreshedSourceIds) { - store = Cache.putRange(store, scope, startMs, endMs, events, Date.now(), refreshedSourceIds) + function put(scope, startMs, endMs, events, refreshedSourceIds, requestAt) { + store = Cache.putRange(store, scope, startMs, endMs, events, Date.now(), refreshedSourceIds, requestAt) if (loaded) saveTimer.restart() } diff --git a/ui/calendar/CalendarController.qml b/ui/calendar/CalendarController.qml index 8c69ca80d..3d77a8ba9 100644 --- a/ui/calendar/CalendarController.qml +++ b/ui/calendar/CalendarController.qml @@ -40,6 +40,9 @@ Item { property string refreshScope: "" property var queue: [] property var activeSource: null + property int refreshSerial: 0 + property int activeReads: 0 + readonly property var sharedCache: service && service.calendarCache && service.backend && Number(service.backend.apiVersion)>=8 ? service.calendarCache : null property var passwordSaveQueue: [] property string passwordToSave: "" property bool savingPassword: false @@ -161,16 +164,14 @@ Item { function refresh(startMs, endMs) { var requestedStart = Number(startMs) || 0 var requestedEnd = Number(endMs) || 0 - if (loading) { - pendingRangeStart = requestedStart - pendingRangeEnd = requestedEnd - return - } pendingRangeStart = 0 pendingRangeEnd = 0 rangeStart = requestedStart rangeEnd = requestedEnd - if (!eventCache.loaded) return + setEvents(cachedEventsFor(calendarScope, rangeStart, rangeEnd)) + refreshSerial++ + if (!eventCache.loaded && !(sharedCache && sharedCache.loaded)) {loading=false;return} + activeReads = 0 lastError = "" lastErrorKind = "" refreshAccountId = accountId @@ -181,7 +182,7 @@ Item { }) var sourceIds = queue.map(function(source) { return String(source.id || "") }) loading = true - setEvents(eventCache.get(refreshScope, rangeStart, rangeEnd, sourceIds)) + setEvents(cachedEventsFor(refreshScope, rangeStart, rangeEnd)) processNext() } @@ -321,8 +322,13 @@ Item { var values = sourcesForAccount(accountId).sources.filter(function(source) { return root.sourceIncluded(source) }) - return eventCache.get(scope, startMs, endMs, - values.map(function(source) { return String(source.id || "") })) + var ids = values.map(function(source) { return String(source.id || "") }) + if (sharedCache && sharedCache.loaded) { + var cached = sharedCache.get("sources",startMs,endMs,ids) + var missing=ids.filter(function(id){return !root.sharedCache.knows("sources",startMs,endMs,id)}) + return cached.concat(eventCache.get(scope,startMs,endMs,missing)) + } + return eventCache.get(scope,startMs,endMs,ids) } function findSource(sourceId) { @@ -590,7 +596,7 @@ Item { params.source = source params.operation = operation var notifyConsent = microsoftConsentHandler(source && source.kind === "microsoft" ? source.accountId : "") - service.backend.call("calendar.request", params, function(result, error) { + service.backend.call(operation === "list" && Number(service.backend.apiVersion)>=8 ? "calendar.read" : "calendar.request", params, function(result, error) { var reason = "" if (error) { reason = notifyConsent(error) ? Microsoft.graphConsentMessage() @@ -925,16 +931,17 @@ Item { }) } - function replaceActiveSourceEvents(values) { + function replaceActiveSourceEvents(values, source) { + source = source || activeSource if (refreshScope !== calendarScope) return - var sourceId = activeSource ? String(activeSource.id || "") : "" + var sourceId = source ? String(source.id || "") : "" var next = events.filter(function(event) { return String(event && event.sourceId || "") !== sourceId }) var additions = Array.isArray(values) ? values : [] for (var i = 0; i < additions.length; i++) { - additions[i].sourceName = activeSource - ? String(activeSource.name || activeSource.id || "Calendar") : "Calendar" + additions[i].sourceName = source + ? String(source.name || source.id || "Calendar") : "Calendar" next.push(additions[i]) } next.sort(Calendar.compareEvents) @@ -955,64 +962,76 @@ Item { function processNext() { if (queue.length === 0) { + if (activeReads > 0) return activeSource = null loading = false var enabled = sourcesForAccount(refreshAccountId).sources.filter(function(source) { return root.sourceIncluded(source) }).map(function(source) { return String(source.id || "") }) var allowed = {} - for (var i = 0; i < enabled.length; i++) allowed[enabled[i]] = true - if (refreshScope === calendarScope) setEvents(events.filter(function(event) { + for (var i=0;i0) { + var pending=queue.slice() + var source=pending.shift() + queue=pending + activeReads++ + startNativeList(source,refreshSerial,rangeStart,rangeEnd) + } } - function startPasswordLookup() { startNativeList() } - - function startNativeList() { - var fields = { start: new Date(rangeStart).toISOString(), end: new Date(rangeEnd).toISOString() } - if (activeSource.kind === "caldav" || activeSource.kind === "icloud") - fields.body = Calendar.caldavReport(rangeStart, rangeEnd) - nativeRequest(activeSource, "list", fields, function(result, error) { - if (error) { root.failSource(error); return } - var body = String(result && result.body || "") - var values = [] - if (root.activeSource.kind === "caldav" || root.activeSource.kind === "icloud") - values = Calendar.eventsFromCaldav(body, root.activeSource.id, root.rangeStart, root.rangeEnd) - else { - var payload = null - try { payload = JSON.parse(body) } catch (e) {} - if (!payload) { root.failSource("The calendar returned an unreadable response"); return } - values = root.activeSource.kind === "google" - ? Calendar.eventsFromGoogle(payload, root.activeSource.id) - : Calendar.eventsFromGraph(payload, root.activeSource.id) + function startNativeList(source, serial, start, end) { + var requestedAt=sharedCache ? sharedCache.reserve() : Date.now() + var fields={start:new Date(start).toISOString(),end:new Date(end).toISOString()} + if (source.kind === "caldav" || source.kind === "icloud") fields.body=Calendar.caldavReport(start,end) + nativeRequest(source,"list",fields,function(result,error) { + var values=result && Array.isArray(result.events) ? result.events : null + if (!error && !values) { + var body=String(result && result.body || "") + if (source.kind === "caldav" || source.kind === "icloud") values=Calendar.eventsFromCaldav(body,source.id,start,end) + else { + var payload=null + try {payload=JSON.parse(body)} catch(e) {} + if (!payload) error="The calendar returned an unreadable response" + else values=source.kind === "google" ? Calendar.eventsFromGoogle(payload,source.id) : Calendar.eventsFromGraph(payload,source.id) + } } - root.replaceActiveSourceEvents(values) + if (!error && root.sharedCache) root.sharedCache.put("sources",start,end,values || [],[String(source.id)],requestedAt) + if (serial!==root.refreshSerial) return + root.activeReads-- + if (error) { + root.lastError=Sources.errorLabel(source,root.service ? root.service.accountSummaries : []) + ": " + error + } else root.replaceActiveSourceEvents(values,source) root.processNext() }) } - function startGraph() { startNativeList() } - - function startGoogle() { startNativeList() } + function warmRange(start,end,stillVisible) { + if (!sharedCache || !sharedCache.loaded || !service || !service.backend || Number(service.backend.apiVersion)<8) return + var sources=sourcesForAccount(accountId).sources.filter(function(source){return root.sourceIncluded(source)}) + var serial=refreshSerial + function next() { + if (!root || serial!==root.refreshSerial || root.loading || sources.length===0 + || (typeof stillVisible === "function" && !stillVisible())) return + var source=sources.shift() + if (root.sharedCache.covers("sources",start,end,source.id)) {Qt.callLater(next);return} + var requestedAt=root.sharedCache.reserve() + var fields={start:new Date(start).toISOString(),end:new Date(end).toISOString()} + if(source.kind === "caldav" || source.kind === "icloud") fields.body=Calendar.caldavReport(start,end) + root.nativeRequest(source,"list",fields,function(result,error) { + if (!error && result && Array.isArray(result.events) && root.sharedCache) + root.sharedCache.put("sources",start,end,result.events,[String(source.id)],requestedAt) + Qt.callLater(next) + }) + } + next() + } FileView { path: root.configPath @@ -1039,6 +1058,11 @@ Item { } + Connections { + target: root.sharedCache + ignoreUnknownSignals: true + function onRestored() { if (root.rangeStart && root.rangeEnd && !root.loading) root.refresh(root.rangeStart,root.rangeEnd) } + } CalendarCache { id: eventCache backend: root.service ? root.service.backend : null diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index 9eb3b265d..22a9aceae 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -96,6 +96,7 @@ Item { readonly property var monthSpans: Calendar.monthSpanLayout(controller ? controller.events : [], days) readonly property var days: Calendar.monthGridDays( visibleMonth.getFullYear(), visibleMonth.getMonth(), 1) + readonly property var monthEventsByDay: visible && viewMode === "month" ? Calendar.indexDays(controller ? controller.events : [],days) : ({}) readonly property var weekDays: Calendar.weekDays(visibleWeek.getTime(), 1) readonly property var displayDays: viewMode === "day" ? weekDays.filter(function(day) { return day.isoDate === Calendar.isoDate(visibleWeek) @@ -173,6 +174,7 @@ Item { } } function onLoadingChanged() { + if (!root.controller.loading && root.visible) warmAdjacent.restart() if (root.controller.loading || !root.detailEvent || root.controller.lastError !== "") return var source = root.controller.findSource(root.detailEvent.sourceId) if (source && source.enabled === false) return @@ -264,6 +266,26 @@ Item { moveSelection(1) } + Timer { + id: warmAdjacent + interval: 500 + onTriggered: { + if (!root.visible || !root.controller || root.controller.loading || typeof root.controller.warmRange !== "function") return + for (var offset=-1;offset<=1;offset+=2) { + var adjacent + if (root.viewMode === "month" || root.viewMode === "agenda") { + var month=new Date(root.visibleMonth.getFullYear(),root.visibleMonth.getMonth()+offset,1) + adjacent=Calendar.monthGridDays(month.getFullYear(),month.getMonth(),1) + } else { + var day=new Date(root.visibleWeek) + day.setDate(day.getDate()+offset*7) + adjacent=Calendar.weekDays(day.getTime(),1) + } + root.controller.warmRange(adjacent[0].startMs,adjacent[adjacent.length-1].endMs,function() {return root.visible}) + } + } + } + function refresh() { var range = viewMode === "day" || viewMode === "week" ? displayDays : days if (!controller || range.length === 0) return @@ -703,8 +725,7 @@ Item { objectName: "calendar-month-day-" + modelData.isoDate required property var modelData required property int index - readonly property var dayEvents: Calendar.eventsOnDay( - root.controller ? root.controller.events : [], modelData).filter(function(event) { + readonly property var dayEvents: (root.monthEventsByDay[modelData.startMs] || []).filter(function(event) { return !Calendar.spansMultipleDays(event) }) readonly property int week: Math.floor(index / 7) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index d22b96ae0..ea6d4be17 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -532,12 +532,13 @@ DropArea { function updateRecipientSuggestions() { toSuggestions = toField.activeFocus - ? Recipients.suggest(contactBook, toField.text, 5) : [] + ? Recipients.suggestIndexed(contactIndex, toField.text, 5) : [] ccSuggestions = ccField.activeFocus - ? Recipients.suggest(contactBook, ccField.text, 5) : [] + ? Recipients.suggestIndexed(contactIndex, ccField.text, 5) : [] bccSuggestions = bccField.activeFocus - ? Recipients.suggest(contactBook, bccField.text, 5) : [] + ? Recipients.suggestIndexed(contactIndex, bccField.text, 5) : [] } + readonly property var contactIndex: Recipients.index(contactBook) function acceptTo(contact) { toField.text = Recipients.accept(toField.text, contact) @@ -583,7 +584,7 @@ DropArea { root.forwardAttachmentsLoading = false root.forwardAttachmentError = String(error || "") root.forwardedAttachments = error ? [] : loaded - }) + }, root.draftKey) } function loadDraftAttachments(messageId, attachments) { @@ -602,7 +603,7 @@ DropArea { return } root.draftAttachments = Array.isArray(loaded) ? loaded : [] - }) + }, root.draftKey) } function begin(nextMode, summary, bodyText, attachments) { @@ -773,6 +774,7 @@ DropArea { for (i = 0; i < owned.length; i++) attachments.push(owned[i]) return ({ accountId: String(draft.accountId || ""), + draftKey: String(draft.draftKey || ""), draftId: String(draft.sourceDraftId || ""), from: String(draft.fromEmail || ""), to: String(draft.to || ""), @@ -922,6 +924,7 @@ DropArea { // turn, so two mailboxes sharing a send-as alias sent B's draft from // whichever of them came first. accountId: root.accountId, + draftKey: root.draftKey, from: root.fromEmail, to: toField.text, cc: ccField.text, @@ -996,7 +999,12 @@ DropArea { return } root.attachmentReadPending = true - root.service.backend.call(job.mode === "forget" ? "attachment.forget" : "attachment.read", { path: job.path }, function(result, error) { + var mailbox = typeof root.service.findAccount === "function" ? root.service.findAccount(root.accountId) : null + var stored = job.mode !== "forget" && Number(root.service.backend.apiVersion) >= 8 && (!mailbox || mailbox.providerId !== "hey") + var method = job.mode === "forget" ? "attachment.forget" : stored ? "attachment.import" : "attachment.read" + var params = {path:job.path} + if (stored) { params.accountId = root.accountId; params.draftKey = owner } + root.service.backend.call(method, params, function(result, error) { root.attachmentReadPending = false var code = error ? String(error.message || "") : "" finishAttach(job.mode, JSON.stringify(error ? { ok: false, @@ -1084,6 +1092,7 @@ DropArea { mimeType: String(result.mimeType || "application/octet-stream"), size: Math.max(0, Math.floor(Number(result.size) || 0)), data: String(result.data || ""), + handle: String(result.handle || ""), path: String(result.path || ""), owned: mode === "clipboard" || mode === "recover-owned" }) diff --git a/ui/components/IconButton.qml b/ui/components/IconButton.qml index 092467fde..9c51bfbb6 100644 --- a/ui/components/IconButton.qml +++ b/ui/components/IconButton.qml @@ -39,8 +39,19 @@ Item { Accessible.role: Accessible.Button Accessible.name: tooltipText Accessible.onPressAction: if (root.enabled) root.clicked() - Keys.onReturnPressed: if (root.enabled) root.clicked() - Keys.onSpacePressed: if (root.enabled) root.clicked() + function acceptsActivation(event) { + return root.enabled && root.activeFocus + && (event.modifiers & ~Qt.KeypadModifier) === Qt.NoModifier + && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) + } + Keys.onShortcutOverride: function(event) { + if (root.acceptsActivation(event)) event.accepted = true + } + Keys.onPressed: function(event) { + if (!root.acceptsActivation(event)) return + event.accepted = true + root.clicked() + } signal clicked() readonly property bool hot: (mouse.containsMouse || hasCursor || activeFocus) && enabled @@ -110,7 +121,7 @@ Item { } Widgets.PanelToolTip { - visible: root.tooltipText !== "" && mouse.containsMouse + visible: root.tooltipText !== "" && (mouse.containsMouse || root.activeFocus) text: root.tooltipText fontFamily: root.fontFamily } diff --git a/ui/components/LocalMailStatus.qml b/ui/components/LocalMailStatus.qml new file mode 100644 index 000000000..7d3243b76 --- /dev/null +++ b/ui/components/LocalMailStatus.qml @@ -0,0 +1,106 @@ +import QtQuick +import "../controls" as Widgets +import "../settings" + +Column { + id: root + required property var mailbox + required property color textColor + required property color dimColor + required property string panelFontFamily + readonly property var status: mailbox ? mailbox.status : ({}) + visible: !!mailbox && mailbox.available + && (mailbox.error !== "" || !!status.error || status.paused === true || !status.complete || Number(status.pendingEdits || 0) > 0 + || Number(status.editConflicts || 0) > 0) + height: visible ? implicitHeight : 0 + spacing: MailStyle.space(4) + + Text { + width: parent.width + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: MailStyle.bodySmall + wrapMode: Text.WordWrap + text: { + if (!root.mailbox) return "" + if (root.mailbox.error !== "") return root.mailbox.error + if (root.status.error === "local_disk_low" || root.status.error === "local_disk_full") + return "Downloads paused: free at least 1 GB of disk space. Saved mail is available." + if (root.status.error === "gmail_unauthorized" || root.status.error === "gmail_invalid_token") + return "Sign in to Gmail again to resume syncing. Saved mail and queued changes are kept." + if (root.status.error === "gmail_rate_limited") + return "Gmail is limiting requests. Sync will retry automatically. Saved mail is available." + if (root.status.error) return "Downloads are waiting for Gmail. Saved mail is available." + if (root.status.paused) return "Mail downloads paused. Saved mail is available." + if (Number(root.status.editConflicts || 0) > 0) + return "A mailbox change could not sync. The message may have been removed or its permissions changed." + if (Number(root.status.pendingEdits || 0) > 0) + return root.status.pendingEdits + " mailbox changes saved, waiting to sync." + if (Number(root.status.failed || 0) > 0) + return root.status.failed + " messages could not finish downloading. Sync will retry automatically." + if (root.status.complete) return "" + var saved = Number(root.status.textComplete || 0) + var total = Number(root.status.estimatedTotal || 0) + return total > 0 ? saved + " of about " + total + " messages saved for offline use." + : saved + " messages saved for offline use. Checking the rest..." + } + } + Text { + width: parent.width + visible: !!root.mailbox && !root.status.complete + textFormat: Text.PlainText + text: "Local search covers downloaded text. Files download when opened." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: MailStyle.caption + wrapMode: Text.WordWrap + } + Flow { + width: parent.width + spacing: MailStyle.space(6) + Widgets.Button { + readonly property string ticket: { + var entries = root.mailbox ? root.mailbox.edits : [] + for (var i=0;i=0;i--) + if (entries[i].state === "queued") return String(entries[i].ticket) + return "" + } + visible: ticket !== "" + focusable: true + text: "Undo latest change" + foreground: root.textColor + fontSize: MailStyle.caption + onClicked: root.mailbox.undo(ticket) + } + } +} diff --git a/ui/components/MessageList.qml b/ui/components/MessageList.qml index 12c72b0e9..88791d887 100644 --- a/ui/components/MessageList.qml +++ b/ui/components/MessageList.qml @@ -7,17 +7,7 @@ import "../account/Model.js" as Model import "../account/Unified.js" as Unified import "../agent/Agent.js" as Agent -// The message list. A Repeater in a Column rather than a ListView because the -// panel already owns one Flickable and nesting a second scroller inside it -// gives every wheel event two plausible targets. -// -// Hovering a row does not move the keyboard's cursor. A row reports its own -// hover appearance (MessageRow.hot), and letting hover write `cursorId` as well -// put the mouse and the keyboard in a fight the mouse won: pressing j scrolls -// the list to follow the cursor, and Qt re-reports hover when content moves -// under a pointer that has not moved — so the cursor was pulled straight back -// to whatever the mouse happened to be resting on, and j went nowhere. -Column { +ListView { id: root required property var service @@ -46,29 +36,41 @@ Column { width: parent ? parent.width : 0 spacing: MailStyle.space(2) - // Where a row sits in this column's own coordinates, so the panel's scroller - // can bring it into view. Found by index rather than by asking the rows which - // one holds the cursor: the answer must not wait on a binding to propagate. + clip: true + boundsBehavior: Flickable.StopAtBounds + reuseItems: true + cacheBuffer: height + topMargin: MailStyle.space(6) + bottomMargin: MailStyle.space(6) + model: root.service ? root.service.messages.length : 0 + + function updateVisibleRows() { + if (!visible || !service || !service.inboxTools) return + var first = indexAt(1, contentY + 1) + var last = indexAt(1, contentY + height - 1) + if (first < 0) first = 0 + if (last < first) last = Math.min(count - 1, first + 20) + service.inboxTools.visibleRows = service.messages.slice(Math.max(0, first - 2), last + 3) + } + onContentYChanged: { Qt.callLater(updateVisibleRows); loadMoreSoon() } + onContentHeightChanged: loadMoreSoon() + onCountChanged: Qt.callLater(updateVisibleRows) + onVisibleChanged: Qt.callLater(updateVisibleRows) + Component.onCompleted: Qt.callLater(updateVisibleRows) + + function reveal(id) { + var index = Model.indexById(root.service.messages, id) + if (index >= 0) positionViewAtIndex(index, ListView.Contain) + } + function boundsFor(id) { - if (!root.service) return null var index = Model.indexById(root.service.messages, id) - if (index < 0) return null - var item = rows.itemAt(index) - if (!item) return null - return ({ y: item.y, height: item.height }) + var item = itemAtIndex(index) + return item ? ({y:item.y, height:item.height}) : null } - // The model is a COUNT, not the array. The list is handed a new array - // whenever anything about any message changes — a row opened half a - // second ago comes back read, a poll lands — and a Repeater fed the array - // tore every row down and built it again each time: a pointer pressed on - // a row at that moment was pressed on nothing, and the click was lost. - // With the count, a row stays while its summary is read again by index. - Repeater { - id: rows - model: root.service.messages.length - - MessageRow { + delegate: MessageRow { + width: root.width required property int index // The array and its count change together, but a row's binding can be // asked between the two; an empty summary for that instant draws an @@ -112,8 +114,9 @@ Column { root.menuRequested(modelData.id, sceneX, sceneY) } } - } + footer: Column { + width: root.width ListSkeleton { width: parent.width visible: Model.showInitialListSkeleton(root.service.listLoading, @@ -170,23 +173,17 @@ Column { } } - // The scroller this list sits in, handed over by the panel that owns it: - // when its foot comes into view and there is more, the next page is asked - // for without a press, and never while a page is on its way, which is - // what keeps a slow server from being asked twice. A page that lands and - // still leaves the foot in view — a short mailbox, a merged list held - // back by a mailbox that has not caught up — is followed by the next - // once the list settles, until the foot is out of view or there is no - // more. Asked a moment later rather than in the signal itself: a cached - // page painted on the way into a live load can put the foot in view - // before that load has said it is running, and a page asked for from - // inside the load would race it. - property var scroller: null + } + + property var scroller: root property int loadStartCount: -1 + property int lastAutoCount: -1 function loadMoreIfAtFoot() { if (!root.scroller || !root.service) return false - if (!root.scroller.atYEnd || !root.service.hasMore || root.service.listLoading) return false + var atFoot = root.scroller.atYEnd || root.scroller.contentY + root.scroller.height >= root.scroller.contentHeight - 1 + if (!atFoot || !root.service.hasMore || root.service.listLoading || !root.count || root.lastAutoCount === root.count) return false + root.lastAutoCount = root.count root.service.loadMore() return true } @@ -209,6 +206,7 @@ Column { Connections { target: root.service + function onMessagesChanged() { root.lastAutoCount = -1; Qt.callLater(root.updateVisibleRows) } function onListLoadingChanged() { if (root.service.listLoading) { root.loadStartCount = root.service.messages.length diff --git a/ui/components/UndoSendToast.qml b/ui/components/UndoSendToast.qml index a30c065e6..23ae49a74 100644 --- a/ui/components/UndoSendToast.qml +++ b/ui/components/UndoSendToast.qml @@ -11,6 +11,7 @@ Rectangle { // How many sends are parked. Past one, the countdown is the newest's and // Undo says so. property int queuedCount: 1 + property bool awaitingConnection: false required property color textColor required property color dimColor required property color accentColor @@ -20,8 +21,9 @@ Rectangle { signal undoRequested() - implicitWidth: content.implicitWidth + MailStyle.space(16) + implicitWidth: message.implicitWidth + undoButton.implicitWidth + content.spacing + MailStyle.space(16) implicitHeight: Math.max(content.implicitHeight + MailStyle.space(12), MailStyle.space(42)) + width: Math.min(implicitWidth, parent ? parent.width - MailStyle.space(32) : implicitWidth) radius: Style.cornerRadius color: Qt.rgba(popupBackgroundColor.r, popupBackgroundColor.g, popupBackgroundColor.b, 1) @@ -31,12 +33,16 @@ Rectangle { Row { id: content anchors.centerIn: parent + width: root.width - MailStyle.space(16) spacing: MailStyle.space(12) Text { + id: message objectName: "undo-send-message" + width: Math.max(0, content.width - undoButton.implicitWidth - content.spacing) + wrapMode: Text.WordWrap anchors.verticalCenter: parent.verticalCenter - text: root.queuedCount > 1 + text: root.awaitingConnection ? "Saved. Will send when connected." : root.queuedCount > 1 ? root.queuedCount + " queued \u00b7 newest in " + root.secondsRemaining + "s" : "Sending in " + root.secondsRemaining + "s" textFormat: Text.PlainText @@ -46,7 +52,9 @@ Rectangle { } Widgets.Button { + id: undoButton objectName: "undo-send-button" + focusable: true anchors.verticalCenter: parent.verticalCenter text: root.queuedCount > 1 ? "Undo last alt+z" : "Undo alt+z" foreground: root.accentColor diff --git a/ui/components/WeekCalendarView.qml b/ui/components/WeekCalendarView.qml index 900524b22..c1cad15f2 100644 --- a/ui/components/WeekCalendarView.qml +++ b/ui/components/WeekCalendarView.qml @@ -41,6 +41,15 @@ Item { } } + readonly property var eventsByDay: visible ? Calendar.indexDays((root.controller ? root.controller.events : []).map(function(event) { + if (!root.pendingGesture || Calendar.eventKey(event) !== root.pendingGesture.key) return event + var moved = {} + for (var key in event) moved[key] = event[key] + moved.start = { ms: root.pendingGesture.start } + moved.end = { ms: root.pendingGesture.end } + return moved + }), days) : ({}) + readonly property real timeRailWidth: Math.max(MailStyle.space(52), allDayLabelMetrics.advanceWidth + MailStyle.space(12), midnightTimeMetrics.advanceWidth + MailStyle.space(12), @@ -368,15 +377,7 @@ Item { delegate: Item { id: dayColumn required property var modelData - readonly property var dayEvents: Calendar.eventsOnDay( - (root.controller ? root.controller.events : []).map(function(event) { - if (!root.pendingGesture || Calendar.eventKey(event) !== root.pendingGesture.key) return event - var moved = {} - for (var key in event) moved[key] = event[key] - moved.start = { ms: root.pendingGesture.start } - moved.end = { ms: root.pendingGesture.end } - return moved - }), modelData) + readonly property var dayEvents: root.eventsByDay[modelData.startMs] || [] readonly property var positionedEvents: Calendar.timedLayout(dayEvents, modelData) width: (timeline.width - root.timeRailWidth) / Math.max(1, root.days.length) height: parent.height diff --git a/ui/compose/Recipients.js b/ui/compose/Recipients.js index 235932484..591f545da 100644 --- a/ui/compose/Recipients.js +++ b/ui/compose/Recipients.js @@ -79,34 +79,39 @@ function usedAddresses(text) { } function suggest(values, text, limit) { + return suggestIndexed(index(values),text,limit) +} + +function index(values) { + var contacts = normalize(values) + var result = contacts.map(function(contact) { + return {contact:contact,email:contact.email.toLowerCase(),name:contact.name.toLowerCase(), + sort:(contact.name || contact.email).toLowerCase()} + }) + result.sort(function(left,right) { return left.sort < right.sort ? -1 : left.sort > right.sort ? 1 : 0 }) + return result +} + +function suggestIndexed(contacts, text, limit) { var query = currentToken(text).toLowerCase() if (query === "") return [] - var contacts = normalize(values) var used = usedAddresses(text) - var ranked = [] + var count = Math.max(1, Math.floor(Number(limit) || 5)) + var prefix = [] + var matches = [] for (var i = 0; i < contacts.length; i++) { var contact = contacts[i] - var email = contact.email.toLowerCase() - var name = contact.name.toLowerCase() + var email = contact.email + var name = contact.name if (used[email] || query === email) continue var emailAt = email.indexOf(query) var nameAt = name.indexOf(query) if (emailAt < 0 && nameAt < 0) continue - ranked.push({ - contact: contact, - score: emailAt === 0 || nameAt === 0 ? 0 : 1 - }) + if (emailAt === 0 || nameAt === 0) prefix.push(contact.contact) + else if (matches.length < count) matches.push(contact.contact) + if (prefix.length >= count) break } - ranked.sort(function(left, right) { - if (left.score !== right.score) return left.score - right.score - var leftName = (left.contact.name || left.contact.email).toLowerCase() - var rightName = (right.contact.name || right.contact.email).toLowerCase() - return leftName < rightName ? -1 : (leftName > rightName ? 1 : 0) - }) - var count = Math.max(1, Math.floor(Number(limit) || 5)) - var out = [] - for (var j = 0; j < ranked.length && j < count; j++) out.push(ranked[j].contact) - return out + return prefix.concat(matches).slice(0,count) } function address(contact) { diff --git a/ui/controls/Button.qml b/ui/controls/Button.qml index 7c0874fe8..f2ddf9372 100644 --- a/ui/controls/Button.qml +++ b/ui/controls/Button.qml @@ -65,9 +65,22 @@ BorderSurface { signal hovered(bool isHovered) activeFocusOnTab: focusable - Keys.onReturnPressed: if (focusable) root.clicked() - Keys.onEnterPressed: if (focusable) root.clicked() - Keys.onSpacePressed: if (focusable) root.clicked() + Accessible.role: Accessible.Button + Accessible.name: text || tooltipText + Accessible.onPressAction: if (root.enabled) root.clicked() + function acceptsActivation(event) { + return root.enabled && root.activeFocus && root.focusable + && (event.modifiers & ~Qt.KeypadModifier) === Qt.NoModifier + && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) + } + Keys.onShortcutOverride: function(event) { + if (root.acceptsActivation(event)) event.accepted = true + } + Keys.onPressed: function(event) { + if (!root.acceptsActivation(event)) return + event.accepted = true + root.clicked() + } // Reserve the largest border any visual state can paint. Otherwise a // borderless idle button grows by a pixel per side on hover/focus and @@ -130,7 +143,7 @@ BorderSurface { Behavior on color { ColorAnimation { duration: 120 } } ToolTip { - visible: root.tooltipText !== "" && mouseArea.containsMouse + visible: root.tooltipText !== "" && (mouseArea.containsMouse || root.activeFocus) text: root.tooltipText delay: 400 padding: 0 diff --git a/ui/controls/PanelActionButton.qml b/ui/controls/PanelActionButton.qml index 8a16f44cd..0c8f21725 100644 --- a/ui/controls/PanelActionButton.qml +++ b/ui/controls/PanelActionButton.qml @@ -46,9 +46,22 @@ BorderSurface { signal hovered(bool isHovered) activeFocusOnTab: focusable - Keys.onReturnPressed: if (focusable) root.clicked() - Keys.onEnterPressed: if (focusable) root.clicked() - Keys.onSpacePressed: if (focusable) root.clicked() + Accessible.role: Accessible.Button + Accessible.name: tooltipText + Accessible.onPressAction: if (root.enabled) root.clicked() + function acceptsActivation(event) { + return root.enabled && root.activeFocus && root.focusable + && (event.modifiers & ~Qt.KeypadModifier) === Qt.NoModifier + && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) + } + Keys.onShortcutOverride: function(event) { + if (root.acceptsActivation(event)) event.accepted = true + } + Keys.onPressed: function(event) { + if (!root.acceptsActivation(event)) return + event.accepted = true + root.clicked() + } implicitWidth: size implicitHeight: size @@ -97,7 +110,7 @@ BorderSurface { } Widgets.PanelToolTip { - visible: root.tooltipText !== "" && mouse.containsMouse + visible: root.tooltipText !== "" && (mouse.containsMouse || root.activeFocus) text: root.tooltipText fontFamily: root.fontFamily } diff --git a/ui/inbox/InboxTools.qml b/ui/inbox/InboxTools.qml index e7de061b3..d5791ca7c 100644 --- a/ui/inbox/InboxTools.qml +++ b/ui/inbox/InboxTools.qml @@ -2,6 +2,8 @@ import QtQuick Item { id: root required property var service + property var visibleRows: [] + readonly property bool browsing: !!service && service.windowOpen === true property var overviews: ({}) property var avatars: ({}) property string avatarRefreshId: "" @@ -46,10 +48,12 @@ Item { for (var i=0;i=8 && backendIdentity) + return localRequest("local.labelCounts",{id:String(labelId || "")},callback) return backendRequest("gmail.labelCounts", { id: String(labelId || "") }, callback) } @@ -314,6 +327,8 @@ Item { }) return handle } + if (backend && backend.ready && Number(backend.apiVersion)>=8 && backendIdentity) + return localRequest("local.overview",{},function(result,error){callback(error ? null : result.profile || {email:root.backendIdentity},error)}) return backendRequest("gmail.profile", {}, callback) } @@ -327,9 +342,13 @@ Item { // Mail operations and draft resolution are owned by the persistent backend. function modifyMessage(id, addLabelIds, removeLabelIds, callback) { + if (backend && backend.ready && Number(backend.apiVersion) >= 8) + return localEdit([String(id || "")],addLabelIds || [],removeLabelIds || [],callback) return backendRequest("gmail.modify", { id: String(id || ""), addLabelIds: addLabelIds || [], removeLabelIds: removeLabelIds || [] }, callback) } function batchModify(ids, addLabelIds, removeLabelIds, callback) { + if (backend && backend.ready && Number(backend.apiVersion) >= 8) + return localEdit(ids || [],addLabelIds || [],removeLabelIds || [],callback) return backendRequest("gmail.batchModify", { ids: ids || [], addLabelIds: addLabelIds || [], removeLabelIds: removeLabelIds || [] }, callback) } function createLabel(name, callback) { @@ -345,6 +364,9 @@ Item { function untrashMessage(id, callback) { return trashEach("gmail.untrash", id, callback) } function trashEach(method, id, callback) { var list = Array.isArray(id) ? id : [id] + if (backend && backend.ready && Number(backend.apiVersion) >= 8) + return localEdit(list,method === "gmail.trash" ? ["TRASH"] : ["INBOX"], + method === "gmail.trash" ? ["INBOX"] : ["TRASH"],callback) var handle = newHandle() var remaining = list.length var firstError = "" @@ -362,6 +384,17 @@ Item { } return handle } + function localEdit(ids, additions, removals, callback) { + var handle = newHandle() + var identity = String(auth ? auth.accountId || "" : "") + var ticket = "edit-" + Date.now() + "-" + Math.random().toString(36).slice(2) + backend.call("local.edit", {accountId:identity,ticket:ticket,ids:ids, + addLabelIds:additions,removeLabelIds:removals}, function(result,error) { + if (handle.aborted || identity !== String(root.auth ? root.auth.accountId || "" : "")) return + if (typeof callback === "function") callback(error ? null : result,Api.localEditError(error)) + }) + return handle + } Component { id: progressTimerComponent Timer { repeat: false } diff --git a/ui/tests/qml/tst_app_navigation.qml b/ui/tests/qml/tst_app_navigation.qml index af1c3f273..3c452ee3d 100644 --- a/ui/tests/qml/tst_app_navigation.qml +++ b/ui/tests/qml/tst_app_navigation.qml @@ -525,6 +525,38 @@ Item { tryCompare(banner,"height",0) } + function test_notices_wrap_without_layout_cycles() { + mailService.lastError = "" + mailService.actionStatus = "" + var banner = named(app, "mail-notice") + var text = having(banner, function(item) { return typeof item.text === "string" }) + var host = having(app, function(item) { return item.title === "🐦 Magpie" }) + var oldWidth = host.width + var oldPreferences = MailStyle.preferences + failOnWarning(/Binding loop detected for property "height"/) + try { + for (var size of [12, 18]) { + MailStyle.preferences = {interfaceSize: size} + for (var width of [720, 360]) { + host.width = width + app.notice = "" + wait(10) + app.notice = "Magpie could not confirm this change. Check the message’s current state before trying again." + waitForRendering(banner) + verify(banner.height > 0) + verify(text.paintedWidth <= text.width + 1) + verify(text.paintedHeight <= text.height + 1) + app.notice = "" + tryCompare(banner, "height", 0) + } + } + } finally { + host.width = oldWidth + MailStyle.preferences = oldPreferences + app.notice = "" + } + } + function test_header_shows_compose_for_mail_and_view_selector_for_calendar() { var compose = named(app, "compose-button") verify(compose && compose.visible) @@ -564,7 +596,13 @@ Item { verify(!back.visible) } - function test_status_error_opens_external_diagnosis_once() { + function test_status_error_opens_external_diagnosis_once_data() { + return [{tag: "mouse"}, {tag: "return", key: Qt.Key_Return}, + {tag: "keypad-enter", key: Qt.Key_Enter, modifiers: Qt.KeypadModifier}, + {tag: "space", key: Qt.Key_Space}] + } + + function test_status_error_opens_external_diagnosis_once(data) { mailService.lastError = "Could not confirm AI started. Check the conversation before retrying." mailService.actionStatus = "" mailService.diagnosing = false @@ -574,7 +612,13 @@ Item { verify(waitForRendering(app)) verify(button.visible) verify(button.width > 0 && button.height > 0) - mouseClick(button, button.width / 2, button.height / 2) + if (data.key !== undefined) { + button.forceActiveFocus() + verify(button.activeFocus) + keyClick(data.key, data.modifiers || Qt.NoModifier) + } else { + mouseClick(button, button.width / 2, button.height / 2) + } compare(mailService.diagnosisCalls, 1) compare(button.enabled, false) mailService.diagnosing = false diff --git a/ui/tests/qml/tst_attachment_preview.qml b/ui/tests/qml/tst_attachment_preview.qml index aa0306453..05de054d2 100644 --- a/ui/tests/qml/tst_attachment_preview.qml +++ b/ui/tests/qml/tst_attachment_preview.qml @@ -9,8 +9,9 @@ Item { property int apiVersion: 8 property var requests: [] function call(method,params,done) { - if(method === "attachment.thumbnail") requests=requests.concat([{params:params,done:done}]) - return {cancel:function(){}} + var request={method:method,params:params,done:done,cancelled:false} + if(method === "attachment.preview") requests=requests.concat([request]) + return {cancel:function(){request.cancelled=true}} } } Component { @@ -64,10 +65,12 @@ Item { function test_previews_use_listed_metadata_and_return_prepared_bytes(){ var result="" account.previewAttachment("one",{attachmentId:"same-part",mimeType:"text/html"},function(data){result=data}) - compare(account.api.requests.length,1) - compare(account.api.requests[0].messageId,"one") - account.api.requests[0].done("cGRm","") + compare(account.api.requests.length,0) compare(backend.requests.length,1) + compare(backend.requests[0].params.accountId,"ada@example.org") + compare(backend.requests[0].params.messageId,"one") + compare(backend.requests[0].params.attachmentId,"same-part") + compare(backend.requests[0].params.filename,"report.pdf") compare(backend.requests[0].params.mimeType,"application/pdf") backend.requests[0].done({data:"prepared-raster"},null) compare(result,"prepared-raster") @@ -76,25 +79,25 @@ Item { var result="pending" account.previewAttachment("one",file,function(data){result=data}) account.selectedId="two" - account.api.requests[0].done("cGRm","") - compare(backend.requests.length,0) - compare(result,"") + backend.requests[0].done({data:"stale-raster"},null) + compare(result,"pending") account.selectedId="one" account.previewAttachment("one",file,function(data){result=data}) - account.api.requests[1].done("cGRm","") - compare(backend.requests.length,1) + compare(backend.requests.length,2) account.accountId="bob@example.net" - backend.requests[0].done({data:"foreign-raster"},null) - compare(result,"") + backend.requests[1].done({data:"foreign-raster"},null) + compare(result,"pending") + compare(account.api.requests.length,0) } - function test_cancel_stops_fetch_and_never_renders_its_response(){ + function test_cancel_withdraws_request_and_ignores_late_preview(){ var called=false var handle=account.previewAttachment("one",file,function(){called=true}) handle.cancel() - compare(account.api.requests[0].aborted,true) - account.api.requests[0].done("cGRm","") + compare(backend.requests[0].cancelled,true) + backend.requests[0].done({data:"cancelled-raster"},null) compare(called,false) - compare(backend.requests.length,0) + compare(backend.requests.length,1) + compare(account.api.requests.length,0) } } } diff --git a/ui/tests/qml/tst_backend.qml b/ui/tests/qml/tst_backend.qml index 0b31b7839..6d84e7788 100644 --- a/ui/tests/qml/tst_backend.qml +++ b/ui/tests/qml/tst_backend.qml @@ -285,12 +285,36 @@ Item { name: "omamail", apiVersion: 1, protocol: 1, version: "0.8.2", - methods: ["system.info", "system.quit"] + methods: ["system.info", "system.quit", "agent.context", "agent.jobStart", "cache.resourcePut", + "gmail.read", "gmail.sendAs", "message.prepare", "providers.list", "request.upload", + "upload.begin", "upload.append", "upload.discard", "message.parseUpload", "cache.bodyPutUpload"] }, null) compare(backend.ready, true) return process } + function test_partial_unreleased_backend_refuses_local_mutation_before_dispatch() { + var hash = "a".repeat(64) + var backend = createTemporaryObject(backendFactory, parent, { + expectedApiVersion: 7, latestApiVersion: 8, expectedContractHash: hash, + unreleasedMethods: ["local.edit"] }) + var process = start(backend) + reply(process, requests(process)[0], { + protocol:1, version:"0.8.2", apiVersion:8, + methods:["system.info", "system.quit", "gmail.trash"] }, null) + verify(backend.ready) + compare(backend.apiVersion, 7) + verify(backend.needsUpdate) + var failure + backend.call("local.edit", {accountId:"synthetic@example.test", ids:["message"]}, + function(result,error) {failure=error}) + compare(failure.message,"backend_needs_update") + compare(requests(process).length,1,"the unsupported mutation must not be written") + backend.call("gmail.trash", {accountId:"synthetic@example.test", id:"message"}, function(){}) + compare(requests(process).length,2) + compare(requests(process)[1].method,"gmail.trash") + } + function test_business_call_is_not_written_before_handshake() { var backend = makeBackend() var process = processOf(backend) @@ -363,7 +387,9 @@ Item { name: "omamail", apiVersion: 1, protocol: 1, version: "0.8.1", - methods: ["system.info", "system.quit"] + methods: ["system.info", "system.quit", "agent.context", "agent.jobStart", "cache.resourcePut", + "gmail.read", "gmail.sendAs", "message.prepare", "providers.list", "request.upload", + "upload.begin", "upload.append", "upload.discard", "message.parseUpload", "cache.bodyPutUpload"] }, null) compare(backend.ready, false) compare(backend.failure, "Incompatible backend") @@ -382,7 +408,9 @@ Item { name: "omamail", apiVersion: 1, protocol: 1, version: "0.8.1", - methods: ["system.info", "system.quit"] + methods: ["system.info", "system.quit", "agent.context", "agent.jobStart", "cache.resourcePut", + "gmail.read", "gmail.sendAs", "message.prepare", "providers.list", "request.upload", + "upload.begin", "upload.append", "upload.discard", "message.parseUpload", "cache.bodyPutUpload"] }, null) compare(backend.shutdownFinished, false, "a disconnected failure still waits for process exit acknowledgement") diff --git a/ui/tests/qml/tst_backend_runtime.qml b/ui/tests/qml/tst_backend_runtime.qml index 0653952eb..50685c655 100644 --- a/ui/tests/qml/tst_backend_runtime.qml +++ b/ui/tests/qml/tst_backend_runtime.qml @@ -30,6 +30,7 @@ Item { bundledExecutable: "/synthetic/app/omamail" bundledVersion: "0.10.7" bundledApiVersion: 5 + bundledContract: ({apiVersion:6, releasedApiVersion:5, contractHash:"", unreleasedMethods:[]}) } } TestCase { @@ -50,6 +51,13 @@ Item { } } + function test_bundle_never_invents_an_unreleased_step() { + var runtime = createTemporaryObject(bundledFactory, parent) + runtime.bundledContract = ({}) + runtime.refresh() + compare(runtime.latestApiVersion, 5) + } + function make() { return createTemporaryObject(factory, parent) } function processOf(runtime) { for (var i = 0; i < runtime.children.length; i++) @@ -146,7 +154,7 @@ Item { var handshake = JSON.parse(process.written.trim()) backend.receive(JSON.stringify({ jsonrpc: "2.0", id: handshake.id, result: { name: "omamail", apiVersion: 1, protocol: 1, version: "0.8.2", - methods: ["system.info", "system.quit"] } })) + methods: ["system.info", "system.quit", "gmail.modify", "reader.render"] } })) verify(backend.ready) return backend } @@ -254,7 +262,7 @@ Item { var request = JSON.parse(processOf(backend).written.trim().split("\n").pop()) backend.receive(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { name: "omamail", apiVersion: 1, protocol: 1, version: "0.8.2", - methods: ["system.info", "system.quit"] } })) + methods: ["system.info", "system.quit", "gmail.modify", "reader.render"] } })) verify(!backend.ready) verify(!processOf(backend).running) } diff --git a/ui/tests/qml/tst_calendar_controller.qml b/ui/tests/qml/tst_calendar_controller.qml index b8b7eea44..afb550972 100644 --- a/ui/tests/qml/tst_calendar_controller.qml +++ b/ui/tests/qml/tst_calendar_controller.qml @@ -530,8 +530,9 @@ Item { mailService.unifiedCalendarView = true - compare(controller.pendingRangeStart, 1000) - compare(controller.pendingRangeEnd, 2000) + compare(controller.rangeStart, 1000) + compare(controller.rangeEnd, 2000) + compare(controller.pendingRangeStart, 0, "the visible range refreshes without waiting for an obsolete request") } function test_updating_a_caldav_password_refreshes_the_visible_range() { @@ -541,8 +542,9 @@ Item { controller.updateCalendarPassword(controller.sourceList.sources[0], "new-secret") compare(mailService.credentialWrites, [{kind:"calendar-password", accountId:"caldav:team",clientId:"",secret:"new-secret"}]) - compare(controller.pendingRangeStart, 1000) - compare(controller.pendingRangeEnd, 2000) + compare(controller.rangeStart, 1000) + compare(controller.rangeEnd, 2000) + compare(controller.pendingRangeStart, 0, "the visible range refreshes without waiting for an obsolete request") } // Google and Microsoft calendars arrive with their account's sign-in, diff --git a/ui/tests/qml/tst_composer_sender_name.qml b/ui/tests/qml/tst_composer_sender_name.qml index 163163fe6..de7cac237 100644 --- a/ui/tests/qml/tst_composer_sender_name.qml +++ b/ui/tests/qml/tst_composer_sender_name.qml @@ -12,7 +12,8 @@ Item { BackendModule.Backend { executable: "/synthetic/runtime/bin/omamail" expectedVersion: "0.8.2" - expectedApiVersion: 1 + expectedApiVersion: 7 + latestApiVersion: 8 launchEnabled: false } } diff --git a/ui/tests/qml/tst_event_suggestions.qml b/ui/tests/qml/tst_event_suggestions.qml index 5223fd475..c7e534a56 100644 --- a/ui/tests/qml/tst_event_suggestions.qml +++ b/ui/tests/qml/tst_event_suggestions.qml @@ -124,7 +124,7 @@ Item { } function initTestCase() { - BackendFixture.markReady(mailService) + BackendFixture.markReady(mailService, 2) listener = BackendFixture.install(mailService) // The read: Rust would fetch the message inside its account; here the // payload is built from what was asked, and the ask is recorded. @@ -180,8 +180,7 @@ Item { function init() { if (Qt.platform.os !== "linux") { skip("The plugin agent backend is Linux-only"); return } added.clear(); dismissed.clear(); card.suggestions = [] - mailService.backend.protocolInfo = { apiVersion: 2, protocol: 1, version: "0.0.0" } - mailService.backendRuntime.latestApiVersion = 2 + BackendFixture.markReady(mailService, 2) } function test_a_dated_message_is_looked_at_once_when_asked() { diff --git a/ui/tests/qml/tst_inbox_tools.qml b/ui/tests/qml/tst_inbox_tools.qml index 12ea36eb2..6c92ebff6 100644 --- a/ui/tests/qml/tst_inbox_tools.qml +++ b/ui/tests/qml/tst_inbox_tools.qml @@ -15,15 +15,16 @@ Item { QtObject { id: service property var backend: backend + property bool windowOpen: true property var accountSummaries: [{id:"one@example.org"},{id:"two@example.org"}] property var messages: [{id:"one-message",sourceId:"shared-id",from:{email:"alex@example.com"}},{id:"two-message",sourceId:"shared-id",from:{email:"alex@example.com"}}] function hostForId(id) { return String(id).indexOf("two-")===0 ? second : first } } - Inbox.InboxTools { id: tools; service: service } + Inbox.InboxTools { id: tools; service: service; visibleRows: service.messages } TestCase { name: "InboxTools" when: windowShown - function init() { backend.ready=false;backend.apiVersion=7;backend.calls=[];tools.avatarRefreshId="";tools.avatarEpoch++;tools.paused=false;tools.overviews=({});tools.avatars=({});tools.avatarPending=({});tools.snapshotsPending=({});tools.requesting=false } + function init() { backend.ready=false;backend.apiVersion=7;backend.calls=[];tools.avatarRefreshId="";tools.avatarEpoch++;tools.paused=false;tools.overviews=({});tools.avatars=({});tools.avatarPending=({});tools.snapshotsPending=({});tools.requesting=false;service.windowOpen=true;tools.visibleRows=service.messages } function cleanup() { backend.ready=false } function test_admission_failure_explains_each_affected_row_without_leaking_error() { backend.apiVersion=8;backend.ready=true @@ -40,6 +41,19 @@ Item { compare(tools.available,false) compare(backend.calls.length,0) } + function test_hidden_window_starts_no_overviews_or_avatar_fetches() { + service.windowOpen=false + backend.apiVersion=8;backend.ready=true + tools.refresh() + verify(!backend.calls.some(function(v){return v.method==="inbox.overviews" || v.method==="inbox.avatar"})) + } + function test_only_visible_rows_request_overviews_and_avatars() { + tools.visibleRows=[service.messages[0]] + backend.apiVersion=8;backend.ready=true + var jobs=backend.calls.filter(function(v){return v.method==="inbox.overviews" || v.method==="inbox.avatar"}) + compare(jobs.length,2) + for (var i=0;i flick.height, "the list is longer than the view") + verify(list.contentHeight > list.height, "the list is longer than the view") compare(fakeService.loads, 0) - flick.contentY = flick.contentHeight - flick.height + list.positionViewAtEnd() tryCompare(fakeService, "loads", 1, 1000, "reaching the foot asks for the page") // Staying at the foot, or wobbling on it, does not ask again while // the page is on its way. - flick.contentY = flick.contentY - 1 - flick.contentY = flick.contentHeight - flick.height + list.contentY = list.contentY - 1 + list.positionViewAtEnd() wait(20) compare(fakeService.loads, 1) // The page lands: the list grows, the foot moves away, and reaching @@ -88,8 +82,8 @@ Item { for (var i = 13; i <= 24; i++) more.push(row(i + ":INBOX")) fakeService.messages = more wait(20) - verify(flick.contentY < flick.contentHeight - flick.height, "the foot moved away") - flick.contentY = flick.contentHeight - flick.height + verify(list.contentY < list.contentHeight - list.height, "the foot moved away") + list.positionViewAtEnd() tryCompare(fakeService, "loads", 2, 1000) } @@ -104,7 +98,7 @@ Item { fakeService.hasMore = true fakeService.messages = [row("1:INBOX"), row("2:INBOX")] wait(30) - verify(flick.contentHeight <= flick.height, "shorter than the view") + verify(list.contentHeight <= list.height, "shorter than the view") fakeService.listLoading = false tryCompare(fakeService, "loads", 1, 1000, "the page that settled short is followed") compare(fakeService.listLoading, true, "and that ask is on its way") @@ -123,14 +117,32 @@ Item { function test_no_more_means_no_ask() { fakeService.hasMore = false - flick.contentY = flick.contentHeight - flick.height + list.positionViewAtEnd() wait(20) compare(fakeService.loads, 0) compare(list.loadMoreIfAtFoot(), false) } + function test_large_lists_keep_delegates_bounded_and_rebind_identity() { + fakeService.hasMore = false + var values=[] + for (var i=0;i<10000;i++) values.push(row("synthetic-"+i)) + fakeService.messages=values + wait(100) + compare(list.count,10000) + verify(list.contentItem.children.length<100,"only the viewport and nearby rows are instantiated") + list.reveal("synthetic-9999") + tryVerify(function(){return list.itemAtIndex(9999)!==null},1000) + compare(list.itemAtIndex(9999).summary.id,"synthetic-9999") + verify(list.contentItem.children.length<100,"recycling keeps the delegate count bounded") + list.reveal("synthetic-0") + tryVerify(function(){return list.itemAtIndex(0)!==null},1000) + compare(list.itemAtIndex(0).summary.id,"synthetic-0") + compare(fakeService.loads,0) + } + function test_a_failed_page_waits_for_manual_retry() { - flick.contentY = flick.contentHeight - flick.height + list.positionViewAtEnd() tryCompare(fakeService, "loads", 1, 1000) // A failure ends the load without adding messages. Remaining at the diff --git a/ui/tests/qml/tst_local_mail_status.qml b/ui/tests/qml/tst_local_mail_status.qml new file mode 100644 index 000000000..bef5f394d --- /dev/null +++ b/ui/tests/qml/tst_local_mail_status.qml @@ -0,0 +1,88 @@ +import QtQuick +import QtTest +import "../../components" as Mail + +Item { + width: 480 + height: 400 + QtObject { + id: mailbox + property bool available: true + property string error: "" + property var status: ({complete:false,textComplete:501,estimatedTotal:1200}) + property var account: ({listLoading:false}) + property var edits: [] + property int pauses: 0 + property int searches: 0 + property string undone: "" + function setPaused(value) { pauses++; status=Object.assign({},status,{paused:value}) } + function searchOnline() { searches++ } + function undo(ticket) { undone=ticket } + } + Mail.LocalMailStatus { + id: notice + width: parent.width + mailbox: mailbox + textColor: Qt.rgba(1,1,1,1) + dimColor: Qt.rgba(0.69,0.74,0.74,1) + panelFontFamily: "monospace" + } + TestCase { + name: "LocalMailStatus" + when: windowShown + function findText(item, text) { + if (item.text === text) return item + for (var i=0;i message.font.pixelSize) + button.forceActiveFocus() + keyClick(Qt.Key_Return) + compare(undoSpy.count, 1) + } } } diff --git a/ui/tests/test_backend_compatibility.js b/ui/tests/test_backend_compatibility.js index 4c5f958d0..df7fde8c4 100644 --- a/ui/tests/test_backend_compatibility.js +++ b/ui/tests/test_backend_compatibility.js @@ -105,3 +105,23 @@ assert.strictEqual(compatibility.accepts({ protocol: 1, version: "0.9.0", apiVer assert.strictEqual(compatibility.accepts({ protocol: 1, version: "0.9.0", apiVersion: 2 }, "0.9.0", 1, "2"), false) assert.strictEqual(compatibility.accepts({ protocol: 1, version: "0.9.1", apiVersion: 2 }, "0.9.0", 1, 2), false, "the version is still the pin's") assert.strictEqual(compatibility.accepts({ protocol: 1, version: "0.9.0", apiVersion: 0 }, "0.9.0", 1, 2), false) + +const hash = "a".repeat(64) +const step = {protocol: 1, version: "0.11.0", apiVersion: 8, contractHash: hash, + methods: ["system.info", "gmail.trash", "local.edit"]} +assert.strictEqual(compatibility.usableApiVersion(step, 7, 8, hash), 8) +for (const contractHash of [undefined, null, "", "b".repeat(64), "a".repeat(63), 8]) { + assert.strictEqual(compatibility.usableApiVersion({...step, contractHash}, 7, 8, hash), 7, + "a stale development build must not enable the current unreleased feature set") + assert.strictEqual(compatibility.usableApiVersion(step, 7, 8, contractHash), 7) +} +assert.strictEqual(compatibility.usableApiVersion(null, 7, 8, hash), 0) +assert.strictEqual(compatibility.usableApiVersion({...step, apiVersion:7}, 7, 8, hash), 7) +assert.strictEqual(compatibility.usableApiVersion({...step, apiVersion:9}, 7, 8, hash), 0) +assert.strictEqual(compatibility.usableApiVersion({...step, contractHash:undefined}, 8, 8, hash), 8, + "released contracts retain their stable revision semantics") +assert.strictEqual(compatibility.methodRefusal(step, "gmail.trash"), null) +assert.strictEqual(compatibility.methodRefusal(step, "local.edit"), null) +assert.strictEqual(compatibility.methodRefusal(null, "system.info"), null) +assert.deepEqual(compatibility.methodRefusal(step, "local.watch"), + {code:-32012, message:"backend_needs_update"}) diff --git a/ui/tests/test_backend_queue.js b/ui/tests/test_backend_queue.js index 5bfa40648..24ee54173 100644 --- a/ui/tests/test_backend_queue.js +++ b/ui/tests/test_backend_queue.js @@ -15,7 +15,7 @@ function bridge() { Chunks: load('backend/Chunks.js'), Compatibility: load('backend/Compatibility.js'), connected: true, ready: true, stopping: false, pending: {}, sequence: 0, queued: [], draining: false, uploadQueue: null, - unreleasedMethods: [], needsUpdate: false, responseTransfer: null, + unreleasedMethods: [], needsUpdate: false, responseTransfer: null, protocolInfo: null, shutdownStarted: false, shutdownFinished: false, quitRequested: false, shutdownCallbacks: [], shutdownFailure: null, shutdownDeadline: {restart(){}, stop(){}}, stopConfirmationDeadline: {restart(){}, stop(){}}, @@ -355,3 +355,19 @@ if(process.argv[2]) { } testNative().catch(error=>{console.error(error);process.exitCode=1;backend.failPending('test failed');child.kill()}) } + +{ + const {backend, sent, errors} = bridge() + backend.protocolInfo = {apiVersion:8, methods:["system.info", "gmail.trash"]} + let result + backend.call("local.edit", {accountId:"synthetic@example.test"}, (value,error)=>result=error) + assert.strictEqual(result.message,"backend_needs_update") + assert.strictEqual(sent.length,0,"unsupported mutation must never reach the process") + assert.strictEqual(Object.keys(backend.pending).length,0) + assert.strictEqual(errors[0].method,"local.edit") + backend.call("local.edit", {payload:"x".repeat(210000)}, (value,error)=>result=error) + assert.strictEqual(result.message,"backend_needs_update") + assert.strictEqual(sent.length,0,"unsupported uploads must not reserve or transfer any payload") + backend.call("gmail.trash", {accountId:"synthetic@example.test",id:"synthetic"},()=>{}) + assert.strictEqual(sent.length,1,"supported released actions remain available") +} diff --git a/ui/tests/test_backend_runtime.js b/ui/tests/test_backend_runtime.js index bdb7bbeb9..532e9f06f 100644 --- a/ui/tests/test_backend_runtime.js +++ b/ui/tests/test_backend_runtime.js @@ -42,3 +42,8 @@ for (const latestApiVersion of [undefined, "2", 3, 0, 1.5]) assert.deepEqual(runtime.decode(status({ latestApiVersion: 1, unreleasedMethods: ["message.new"] })).unreleasedMethods, [], "no step, no unreleased methods") assert.strictEqual(runtime.decode("not json").latestApiVersion, 0) + +const hash = "a".repeat(64) +assert.strictEqual(runtime.decode(status({contractHash:hash})).contractHash,hash) +for (const contractHash of [undefined,null,"bad",7,"a".repeat(65)]) + assert.strictEqual(runtime.decode(status({contractHash})).contractHash,"") diff --git a/ui/tests/test_calendar_cache.js b/ui/tests/test_calendar_cache.js index f061e0a38..5594f907a 100644 --- a/ui/tests/test_calendar_cache.js +++ b/ui/tests/test_calendar_cache.js @@ -47,3 +47,21 @@ for (let i = 0; i < 20; i++) assert.ok(Object.keys(store.ranges).length <= cache.MAX_RANGES) console.log("test_calendar_cache.js ok") + +{ + const fresh=cache.putRange(cache.emptyStore(),"sources",0,1000,[],300,[first.sourceId],200) + const stale=cache.putRange(fresh,"sources",0,1000,[first],400,[first.sourceId],100) + assert.strictEqual(cache.eventsFor(stale,"sources",0,1000,[first.sourceId]).length,0,"an old reply cannot resurrect a removed event") + assert.strictEqual(cache.coversSource(stale,"sources",0,1000,first.sourceId),true,"a confirmed empty range is still known") +} + +{ + let overlap = cache.putRange(cache.emptyStore(), "sources", 0, 1000, [first, second], 10, + [first.sourceId, second.sourceId], 10) + overlap = cache.putRange(overlap, "sources", 50, 500, [], 20, [first.sourceId], 20) + assert.deepStrictEqual(JSON.parse(JSON.stringify(cache.eventsFor(overlap, "sources", 0, 1000, + [first.sourceId, second.sourceId]))), [second], + "a newer empty overlap removes deleted events without hiding other sources") + assert.strictEqual(cache.eventsFor(overlap, "sources", 50, 500, [second.sourceId]).length, 1, + "an exact range for one source must retain another source's wider cached range") +} diff --git a/ui/tests/test_calendar_feed.js b/ui/tests/test_calendar_feed.js index 9b80c64f4..7c22f1066 100644 --- a/ui/tests/test_calendar_feed.js +++ b/ui/tests/test_calendar_feed.js @@ -781,3 +781,10 @@ console.log("test_calendar_feed.js ok") assert.strictEqual(made.graph.subject, "Plan") assert.strictEqual(made.recurring, false) } + +{ + const days=[{startMs:0,endMs:100},{startMs:100,endMs:190},{startMs:190,endMs:300}] + const events=[null,{uid:'wide',start:{ms:-10},end:{ms:200}},{uid:'edge',start:{ms:100},end:{ms:190}},{uid:'instant',start:{ms:190}},{uid:'outside',start:{ms:300},end:{ms:400}}] + const indexed=feed.indexDays(events,days) + for (const day of days) assert.strictEqual(JSON.stringify(indexed[day.startMs]),JSON.stringify(feed.eventsOnDay(events,day)), 'day index preserves half-open boundaries and unequal day lengths') +} diff --git a/ui/tests/test_gmail_api.js b/ui/tests/test_gmail_api.js index ca5e927dd..a6e67749e 100644 --- a/ui/tests/test_gmail_api.js +++ b/ui/tests/test_gmail_api.js @@ -189,3 +189,13 @@ assert.strictEqual(api.webMessageUrl("18f3a", -1), "https://mail.google.com/mail assert.strictEqual(api.webSearchUrl("from:jane", 0), "https://mail.google.com/mail/u/0/#search/from%3Ajane") console.log("test_gmail_api.js ok") + +assert.strictEqual(api.localEditError(null), "") +for (const message of ["backend_needs_update", "Invalid params", "Method not found"]) + assert(api.localEditError({message}).includes("do not match")) +for (const message of ["local_disk_full", "local_disk_low"]) + assert(api.localEditError({message}).includes("disk space")) +const uncertain = api.localEditError({message:"Backend request timed out"}) +assert(uncertain.includes("could not confirm")) +assert(!uncertain.includes("kept as it was"),"a timeout does not prove rollback") +assert(!api.localEditError({message:"private@example.test Bearer secret"}).includes("secret")) From 6536df370ed4e1e0832afe987b136595aa6da7bf Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:35:40 +0100 Subject: [PATCH 002/568] Fix standalone verification and add provider recovery acceptance checks --- .../workflows/performance-verification.yml | 2 +- app/CMakeLists.txt | 17 +- app/scripts/package-release.ps1 | 17 +- app/scripts/package-release.sh | 16 +- app/src/resource_check.cpp | 2 +- app/tests/test_package.py | 3 +- docs/BACKEND-RUNTIME.md | 2 + scripts/package-backend.py | 19 +- scripts/test-low-space.py | 39 ++ scripts/verify-performance.py | 3 + src/local_mail/mod.rs | 2 + src/local_mail/provider_tests.rs | 478 ++++++++++++++++++ src/local_mail/recovery_tests.rs | 8 +- src/local_mail/tests.rs | 29 +- src/outbox/tests.rs | 100 ++++ tests/test_backend_release.py | 18 +- ui/App.qml | 3 +- ui/components/ComposeExitDialog.qml | 18 +- .../qml/tst_imap_credential_control_bytes.qml | 8 +- 19 files changed, 745 insertions(+), 39 deletions(-) create mode 100644 scripts/test-low-space.py create mode 100644 src/local_mail/provider_tests.rs diff --git a/.github/workflows/performance-verification.yml b/.github/workflows/performance-verification.yml index c02dd6901..bd085547a 100644 --- a/.github/workflows/performance-verification.yml +++ b/.github/workflows/performance-verification.yml @@ -25,7 +25,7 @@ concurrency: jobs: verify: name: Synthetic verification (${{ matrix.profile }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-22.04 timeout-minutes: 90 strategy: fail-fast: false diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index be12ef64d..6e3c0b126 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -24,6 +24,17 @@ find_package(Qt6 6.5 REQUIRED COMPONENTS qt_standard_project_setup(REQUIRES 6.5) +find_package(Python3 REQUIRED COMPONENTS Interpreter) +set(standalone_manifest "${CMAKE_CURRENT_BINARY_DIR}/manifest.json") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/../manifest.json" + "${CMAKE_CURRENT_SOURCE_DIR}/../Cargo.toml" + "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/package-backend.py") +execute_process(COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/package-backend.py" + standalone-manifest --output "${standalone_manifest}" + COMMAND_ERROR_IS_FATAL ANY) + set(OMAMAIL_NATIVE_SOURCES src/app_icon.cpp src/app_icon.h @@ -77,6 +88,7 @@ target_include_directories(omamail_native PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/sr target_compile_definitions(omamail_native PUBLIC OMAMAIL_APP_VERSION="${PROJECT_VERSION}" OMAMAIL_SOURCE_ROOT="${CMAKE_CURRENT_SOURCE_DIR}/.." + OMAMAIL_MANIFEST_PATH="${standalone_manifest}" ) if(DEFINED OMAMAIL_BACKEND AND NOT OMAMAIL_BACKEND STREQUAL "") get_filename_component(OMAMAIL_BACKEND_ABSOLUTE "${OMAMAIL_BACKEND}" ABSOLUTE) @@ -119,8 +131,11 @@ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/qml/Main.qml") qt_add_resources(omamail-app standalone_qml PREFIX "/omamail" BASE "${CMAKE_CURRENT_SOURCE_DIR}/.." - FILES ${OMAMAIL_STANDALONE_QML} "${CMAKE_CURRENT_SOURCE_DIR}/../manifest.json" + FILES ${OMAMAIL_STANDALONE_QML} ) + qt_add_resources(omamail-app standalone_manifest + PREFIX "/omamail" BASE "${CMAKE_CURRENT_BINARY_DIR}" + FILES "${standalone_manifest}") qt_add_resources(omamail-app standalone_brand PREFIX "/omamail/app" BASE "${CMAKE_CURRENT_SOURCE_DIR}" diff --git a/app/scripts/package-release.ps1 b/app/scripts/package-release.ps1 index cce97f6a5..ecb414eea 100644 --- a/app/scripts/package-release.ps1 +++ b/app/scripts/package-release.ps1 @@ -4,7 +4,7 @@ param( [string]$Backend = "target\release\omamail.exe", [string]$Qml = "app\qml", [string]$Ui = "ui", - [string]$Manifest = "manifest.json", + [string]$Manifest = "", [string]$Icon = "app\resources\windows\omamail.ico", [string]$Dist = "dist", [string]$Version = "", @@ -67,7 +67,7 @@ $HostPath = Resolve-InputPath $HostBinary $BackendPath = Resolve-InputPath $Backend $QmlPath = Resolve-InputPath $Qml $UiPath = Resolve-InputPath $Ui -$ManifestPath = Resolve-InputPath $Manifest +$ManifestPath = if ($Manifest) { Resolve-InputPath $Manifest } else { "" } $IconPath = Resolve-InputPath $Icon $DistPath = Resolve-InputPath $Dist $NerdFontsLicensePath = Join-Path $RepoRoot "app\assets\fonts\NerdFonts-LICENSE" @@ -79,7 +79,7 @@ Assert-File $HostPath "standalone host" Assert-File $BackendPath "backend" Assert-Directory $QmlPath "standalone QML directory" Assert-Directory $UiPath "shared UI directory" -Assert-File $ManifestPath "manifest" +if ($ManifestPath) { Assert-File $ManifestPath "manifest" } Assert-File $IconPath "application icon" Assert-File $NerdFontsLicensePath "Nerd Fonts license" Assert-File $NerdFontsReadmePath "Nerd Fonts notices" @@ -90,7 +90,13 @@ Assert-File (Join-Path $UiPath "Service.qml") "shared UI entry point" Assert-X64Pe $HostPath "standalone host" Assert-X64Pe $BackendPath "backend" -$ManifestObject = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json +if ($ManifestPath) { + $ManifestObject = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json +} else { + $ManifestJson = & $Python (Join-Path $RepoRoot "scripts/package-backend.py") standalone-manifest + if ($LASTEXITCODE -ne 0) { throw "standalone manifest generation failed" } + $ManifestObject = ($ManifestJson -join "`n") | ConvertFrom-Json +} $ManifestVersion = $ManifestObject.version if ($ManifestVersion -isnot [string] -or $ManifestVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$') { @@ -133,7 +139,8 @@ try { Copy-Item -LiteralPath $BackendPath -Destination (Join-Path $Bin "omamail.exe") Copy-Item -LiteralPath $QmlPath -Destination (Join-Path $Package "qml") -Recurse Copy-Item -LiteralPath $UiPath -Destination (Join-Path $Package "ui") -Recurse - Copy-Item -LiteralPath $ManifestPath -Destination (Join-Path $Package "manifest.json") + [IO.File]::WriteAllText((Join-Path $Package "manifest.json"), + ($ManifestObject | ConvertTo-Json -Depth 64), [Text.UTF8Encoding]::new($false)) $Licenses = Join-Path $Package "licenses" New-Item -ItemType Directory -Force $Licenses | Out-Null Copy-Item -LiteralPath $NerdFontsLicensePath -Destination (Join-Path $Licenses "NerdFonts-LICENSE") diff --git a/app/scripts/package-release.sh b/app/scripts/package-release.sh index 3d531e9a5..ffc852082 100755 --- a/app/scripts/package-release.sh +++ b/app/scripts/package-release.sh @@ -17,7 +17,7 @@ host=${OMAMAIL_APP_HOST:-"$repo_root/app/build/omamail-app"} backend=${OMAMAIL_BACKEND:-"$repo_root/target/release/omamail"} qml=${OMAMAIL_STANDALONE_QML:-"$repo_root/app/qml"} ui=${OMAMAIL_SHARED_UI:-"$repo_root/ui"} -manifest=${OMAMAIL_MANIFEST:-"$repo_root/manifest.json"} +manifest=${OMAMAIL_MANIFEST:-} dist=${OMAMAIL_DIST:-"$repo_root/dist"} qt_bin=${OMAMAIL_QT_BIN:-} platform_plugin=${OMAMAIL_PLATFORM_PLUGIN:-} @@ -46,13 +46,15 @@ fi version=$(sed -n '/^\[package\]/,/^\[/s/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$repo_root/Cargo.toml" | head -n 1) [ -n "$version" ] || { printf 'Cargo.toml has no package version\n' >&2; exit 1; } -manifest_version=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["version"])' "$manifest") -[ "$manifest_version" = "$version" ] || { printf 'manifest version %s does not match Cargo version %s\n' "$manifest_version" "$version" >&2; exit 1; } +if [ -n "$manifest" ]; then + manifest_version=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["version"])' "$manifest") + [ "$manifest_version" = "$version" ] || { printf 'manifest version %s does not match Cargo version %s\n' "$manifest_version" "$version" >&2; exit 1; } +fi [ -x "$host" ] || { printf 'standalone host is missing or not executable: %s\n' "$host" >&2; exit 1; } [ -x "$backend" ] || { printf 'backend is missing or not executable: %s\n' "$backend" >&2; exit 1; } [ -f "$qml/Main.qml" ] || { printf 'standalone QML is missing: %s/Main.qml\n' "$qml" >&2; exit 1; } [ -f "$ui/Service.qml" ] || { printf 'shared UI is missing: %s/Service.qml\n' "$ui" >&2; exit 1; } -[ -f "$manifest" ] || { printf 'manifest is missing: %s\n' "$manifest" >&2; exit 1; } +[ -z "$manifest" ] || [ -f "$manifest" ] || { printf 'manifest is missing: %s\n' "$manifest" >&2; exit 1; } if find "$qml" "$ui" -type l -print | grep -q .; then printf 'QML inputs must not contain symbolic links\n' >&2 exit 1 @@ -76,7 +78,11 @@ copy_product_files() { mkdir -p "$destination/qml" "$destination/ui" "$destination/licenses" cp -R "$qml/." "$destination/qml/" cp -R "$ui/." "$destination/ui/" - cp "$manifest" "$destination/manifest.json" + if [ -n "$manifest" ]; then + cp "$manifest" "$destination/manifest.json" + else + python3 "$repo_root/scripts/package-backend.py" standalone-manifest --output "$destination/manifest.json" + fi cp "$repo_root/app/assets/fonts/NerdFonts-LICENSE" "$destination/licenses/NerdFonts-LICENSE" cp "$repo_root/app/assets/fonts/NerdFonts-README.md" "$destination/licenses/NerdFonts-README.md" cp "$repo_root/app/assets/fonts/NerdFonts-PROVENANCE.md" "$destination/licenses/NerdFonts-PROVENANCE.md" diff --git a/app/src/resource_check.cpp b/app/src/resource_check.cpp index d846fd280..82e69359d 100644 --- a/app/src/resource_check.cpp +++ b/app/src/resource_check.cpp @@ -260,7 +260,7 @@ ResourcePaths defaultResourcePaths(const QString &executablePath, bool developme QDir::cleanPath(executableDir.filePath(QStringLiteral("../manifest.json"))), QDir::cleanPath(executableDir.filePath(QStringLiteral("../Resources/manifest.json")))}; if (developmentMode) - manifestCandidates.prepend(sourceRoot.filePath(QStringLiteral("manifest.json"))); + manifestCandidates.prepend(QStringLiteral(OMAMAIL_MANIFEST_PATH)); paths.manifest = firstExisting(manifestCandidates); return paths; } diff --git a/app/tests/test_package.py b/app/tests/test_package.py index d9a2909df..ac27ef304 100755 --- a/app/tests/test_package.py +++ b/app/tests/test_package.py @@ -13,12 +13,13 @@ import subprocess import tarfile import tempfile +import tomllib import unittest ROOT = Path(__file__).resolve().parents[2] PACKAGER = ROOT / "app/scripts/package-release.sh" -VERSION = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8"))["version"] +VERSION = tomllib.loads((ROOT / "Cargo.toml").read_text(encoding="utf-8"))["package"]["version"] class PackageTest(unittest.TestCase): diff --git a/docs/BACKEND-RUNTIME.md b/docs/BACKEND-RUNTIME.md index d96f65b4f..86454f915 100644 --- a/docs/BACKEND-RUNTIME.md +++ b/docs/BACKEND-RUNTIME.md @@ -40,6 +40,8 @@ to make the override available when the shell constructs the plugin, restarting the shell with that environment when needed. This is not a second Quickshell application. Rust mail migration remains incomplete; see [BACKEND.md](BACKEND.md). +Standalone builds derive their manifest from the plugin settings but use the standalone identity and Cargo/CMake version. The plugin milestone version is independent. CMake and all native packagers use `package-backend.py standalone-manifest`; the packaged host still refuses a mismatched manifest or backend. Generating this build resource does not modify `manifest.json` or `backend-version`. + ### Forcing a clean reconnect The running `omamail serve` process holds its Secret Service session, its diff --git a/scripts/package-backend.py b/scripts/package-backend.py index 3d1939bb4..0d9e1c9c7 100644 --- a/scripts/package-backend.py +++ b/scripts/package-backend.py @@ -33,7 +33,8 @@ def check(root, tag=None, require_pin=False): manifest = json.loads((root / 'manifest.json').read_bytes()) if not isinstance(manifest, dict) or not isinstance(manifest.get('version'), str): raise ValueError('manifest.json requires a string version') - versions['manifest'] = manifest['version'] + if not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', manifest['version']): + raise ValueError('plugin manifest requires canonical MAJOR.MINOR.PATCH') cmake = (root / 'app/CMakeLists.txt').read_text() app_versions = re.findall( r'^\s*project\s*\(\s*omamail-app\s+VERSION\s+([^\s\)]+)', cmake, @@ -50,6 +51,13 @@ def check(root, tag=None, require_pin=False): return version +def standalone_manifest(root): + version = check(root) + manifest = json.loads((root / 'manifest.json').read_bytes()) + manifest.update(id='omamail', name='Omamail', version=version) + return json.dumps(manifest, ensure_ascii=False, indent=2) + '\n' + + def pin_version(root): path = root / 'backend-version' if path.is_symlink() or not path.is_file(): @@ -504,6 +512,9 @@ def main(): cmd.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1]) cmd.add_argument('--tag') cmd.add_argument('--require-pin', action='store_true') + cmd = sub.add_parser('standalone-manifest') + cmd.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1]) + cmd.add_argument('--output', type=Path) cmd = sub.add_parser('pin-version') cmd.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1]) cmd = sub.add_parser('check-api') @@ -535,6 +546,12 @@ def main(): try: if args.command == 'check': print(check(args.root, args.tag, args.require_pin)) + elif args.command == 'standalone-manifest': + contents = standalone_manifest(args.root) + if args.output: + args.output.write_text(contents, encoding='utf-8') + else: + print(contents, end='') elif args.command == 'pin-version': print(pin_version(args.root)) elif args.command == 'check-api': diff --git a/scripts/test-low-space.py b/scripts/test-low-space.py new file mode 100644 index 000000000..d1f4437c0 --- /dev/null +++ b/scripts/test-low-space.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Exercise real free-space refusal in a private 64 MiB filesystem.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +TEST = "local_mail::provider_tests::low_space_refuses_body_download_and_preserves_saved_mail" + + +def main(): + build = subprocess.run( + ["cargo", "test", "--locked", "--lib", "--no-run", "--message-format=json"], + cwd=ROOT, stdout=subprocess.PIPE, text=True, check=True) + executables = [row["executable"] for line in build.stdout.splitlines() + if (row := json.loads(line)).get("reason") == "compiler-artifact" + and row.get("executable") and row["profile"]["test"] + and row["target"]["kind"] == ["lib"]] + if len(executables) != 1: + raise SystemExit("expected exactly one library test executable") + with tempfile.TemporaryDirectory(prefix="magpie-low-space-seed-") as seed: + subprocess.run([executables[0], "--exact", TEST, "--ignored", "--nocapture"], + env=dict(os.environ, MAGPIE_LOW_SPACE_SEED=seed), check=True) + command = ["/usr/bin/bwrap", "--unshare-all", "--die-with-parent", "--new-session", + "--cap-drop", "ALL", "--ro-bind", "/", "/", "--proc", "/proc", + "--dev", "/dev", "--size", str(64 * 1024 * 1024), "--tmpfs", "/tmp", + "--ro-bind", seed, "/tmp/fixture-seed", + "--perms", "0700", "--dir", "/tmp/mail-check", + "--setenv", "TMPDIR", "/tmp/mail-check", + "--setenv", "OMAMAIL_ACTION_TEST_CHILD", TEST, + executables[0], "--exact", TEST, "--ignored", "--nocapture"] + result = subprocess.run(command, cwd=ROOT, env=os.environ.copy(), timeout=30) + raise SystemExit(result.returncode) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify-performance.py b/scripts/verify-performance.py index daaf7c4e6..992debc86 100644 --- a/scripts/verify-performance.py +++ b/scripts/verify-performance.py @@ -118,6 +118,9 @@ def stages(profile, output, baseline): gates = [ gate("build", ["cargo", "build", "--locked", "--bin", "omamail"], ["cargo"]), gate("offline-recovery", ["cargo", "test", "--locked", "--lib", "local_mail::recovery_tests"], ["cargo"]), + gate("provider-recovery", ["cargo", "test", "--locked", "--lib", "local_mail::provider_tests"], ["cargo"] + runtime), + gate("send-recovery", ["cargo", "test", "--locked", "--lib", "outbox::tests::recorder_confirms"], ["cargo"] + runtime), + gate("low-space", [sys.executable, "scripts/test-low-space.py"], ["cargo", "pdf-sandbox"] + runtime), gate("subprocess", ["cargo", "test", "--locked", "--lib", "process::"], ["cargo"]), gate("rust", isolated + make + ["test-rust"], ["cargo", "pdf-sandbox"] + runtime), gate("javascript", make + ["test-js"], ["node"]), diff --git a/src/local_mail/mod.rs b/src/local_mail/mod.rs index 66e7656f3..f771ae650 100644 --- a/src/local_mail/mod.rs +++ b/src/local_mail/mod.rs @@ -2,6 +2,8 @@ mod content; mod ipc; #[cfg(test)] mod recovery_tests; +#[cfg(test)] +mod provider_tests; mod search; mod store; mod sync; diff --git a/src/local_mail/provider_tests.rs b/src/local_mail/provider_tests.rs new file mode 100644 index 000000000..f2c374a0f --- /dev/null +++ b/src/local_mail/provider_tests.rs @@ -0,0 +1,478 @@ +use super::{LocalMail, store, sync, tests::message}; +use crate::{ + credentials, + mail::tests::{account_fixture, isolated}, + providers::{gmail, gmail_http}, +}; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +const ACCOUNT: &str = "replica@example.org"; + +struct World { + messages: BTreeMap, + requests: Vec, + writes: Vec, + unauthorized: bool, + pause: String, + paginated_history: bool, + expired_history: bool, +} + +struct Provider { + origin: String, + world: Arc>, + task: tokio::task::JoinHandle<()>, +} + +impl Provider { + async fn new() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let world = Arc::new(Mutex::new(World { + messages: ["one", "two"] + .into_iter() + .map(|id| (id.into(), message(id, "Synthetic saved body"))) + .collect(), + requests: Vec::new(), + writes: Vec::new(), + unauthorized: false, + pause: String::new(), + paginated_history: false, + expired_history: false, + })); + let state = world.clone(); + let task = tokio::spawn(async move { + let mut handlers = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let state = state.clone(); + handlers.spawn(async move { + let mut bytes = Vec::new(); + while !bytes.ends_with(b"\r\n\r\n") { + let Ok(byte) = socket.read_u8().await else { return }; + bytes.push(byte); + assert!(bytes.len() < 65_536); + } + let headers = String::from_utf8(bytes).unwrap(); + let line = headers.lines().next().unwrap().to_owned(); + let length: usize = headers.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap()) + }).unwrap_or(0); + assert!(length < 65_536); + let mut body = vec![0; length]; + socket.read_exact(&mut body).await.unwrap(); + let request = serde_json::from_slice(&body).unwrap_or(Value::Null); + let (status, response, pause) = { + let mut world = state.lock().unwrap(); + world.requests.push(line.clone()); + let url = reqwest::Url::parse(&format!("http://fixture{}", line.split_whitespace().nth(1).unwrap())).unwrap(); + let pause = !world.pause.is_empty() && line.contains(&world.pause); + let (status, response) = answer(&mut world, &line, &url, request); + (status, response.to_string(), pause) + }; + if pause { std::future::pending::<()>().await; } + let reply = format!("HTTP/1.1 {status} Fixture\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()); + let _ = socket.write_all(reply.as_bytes()).await; + }); + } + }); + Self { + origin, + world, + task, + } + } +} + +impl Drop for Provider { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn answer(world: &mut World, line: &str, url: &reqwest::Url, body: Value) -> (u16, Value) { + let path = url.path(); + if path == "/token" { + return ( + 200, + json!({"access_token":"synthetic-access","expires_in":3600}), + ); + } + if world.unauthorized { + return (401, json!({"error":{"errors":[{"reason":"authError"}]}})); + } + if path.ends_with("/profile") { + return ( + 200, + json!({"historyId":"100","messagesTotal":2,"emailAddress":ACCOUNT}), + ); + } + if path.ends_with("/history") { + if world.expired_history { + return (404, json!({})); + } + if world.paginated_history + && !url + .query_pairs() + .any(|(key, value)| key == "pageToken" && !value.is_empty()) + { + return ( + 200, + json!({"historyId":"200","nextPageToken":"history-two"}), + ); + } + return (200, json!({"historyId":"200"})); + } + if path.ends_with("/labels") { + return (200, json!({"labels":[{"id":"INBOX","name":"INBOX"}]})); + } + if path.ends_with("/messages") { + return if url + .query_pairs() + .any(|(key, value)| key == "pageToken" && value == "page-two") + { + (200, json!({"messages":[{"id":"two"}]})) + } else { + ( + 200, + json!({"messages":[{"id":"one"}],"nextPageToken":"page-two"}), + ) + }; + } + if let Some(id) = path.strip_prefix("/gmail/v1/users/me/messages/") { + if let Some(id) = id.strip_suffix("/modify") { + assert!(line.starts_with("POST ")); + world.writes.push(body.clone()); + let Some(message) = world.messages.get_mut(id) else { + return (404, json!({})); + }; + let labels = message["labelIds"].as_array_mut().unwrap(); + labels.retain(|label| !body["removeLabelIds"].as_array().unwrap().contains(label)); + for label in body["addLabelIds"].as_array().unwrap() { + if !labels.contains(label) { + labels.push(label.clone()); + } + } + return (200, message.clone()); + } + return world + .messages + .get(id) + .map(|m| (200, m.clone())) + .unwrap_or((404, json!({}))); + } + panic!("unexpected synthetic provider request: {line}") +} + +fn credentials(fixture: &crate::mail::tests::AccountFixture) -> credentials::tests::StoreOverride { + let directory = crate::platform::private_fs::directories(&fixture.config, &["omamail"], true) + .unwrap() + .unwrap(); + crate::platform::private_fs::atomic_replace(&directory, "credentials.json", + json!({"installed":{"client_id":"123-replica.apps.googleusercontent.com","client_secret":"synthetic-secret"}}).to_string().as_bytes()).unwrap(); + credentials::tests::isolated_store(credentials::tests::SingleCredential { + key: credentials::CredentialKey { + provider: "gmail".into(), + account_id: ACCOUNT.into(), + kind: credentials::CredentialKind::GoogleRefreshToken { + client_id: "123-replica.apps.googleusercontent.com".into(), + }, + }, + secret: credentials::Secret::new(b"synthetic-refresh".to_vec()).unwrap(), + }) +} + +fn set(store: &store::Store, key: &str, value: &str) { + store.write(|db| store::set_state(db, key, value)).unwrap(); +} + +async fn synchronize(local: &LocalMail, gmail: &gmail::Session) { + let store = local.store(ACCOUNT).await.unwrap(); + for _ in 0..8 { + set(&store, "lastHistory", "0"); + sync::step(&store, gmail, ACCOUNT, 0).await.unwrap(); + if store.status().unwrap()["complete"] == true { + return; + } + } + panic!( + "synthetic inventory did not finish: {}", + store.status().unwrap() + ); +} + +#[tokio::test] +async fn cached_mail_survives_auth_failure_and_offline_edits_reconcile_with_provider() { + if isolated() { + return; + } + let fixture = + account_fixture(json!({"version":1,"accounts":[{"provider":"gmail","email":ACCOUNT}]})); + let _credential = credentials(&fixture); + let provider = Provider::new().await; + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + gmail_http::with_test_transport(client, provider.origin.clone(), async { + let local = LocalMail::default(); + let gmail = gmail::Session::default(); + synchronize(&local, &gmail).await; + let store = local.store(ACCOUNT).await.unwrap(); + provider.world.lock().unwrap().unauthorized = true; + set(&store, "lastHistory", "0"); + assert_eq!(sync::step(&store, &gmail, ACCOUNT, 0).await, Err("gmail_unauthorized")); + let requests = provider.world.lock().unwrap().requests.len(); + let list = local.call("local.list", &json!({"accountId":ACCOUNT,"query":"in:inbox","limit":50})).await.unwrap(); + assert_eq!(list["summaries"].as_array().unwrap().len(), 2); + assert_eq!(local.call("local.labelCounts", &json!({"accountId":ACCOUNT,"id":"INBOX"})).await.unwrap()["unread"], 2); + assert!(local.read(ACCOUNT, "one", &gmail).await.unwrap()["payload"]["body"]["data"].is_string()); + assert_eq!(provider.world.lock().unwrap().requests.len(), requests, "cached reads must not contact the unauthorized provider"); + local.call("local.edit", &json!({"accountId":ACCOUNT,"ticket":"undo","ids":["one"],"addLabelIds":["STARRED"],"removeLabelIds":[]})).await.unwrap(); + local.call("local.cancelEdit", &json!({"accountId":ACCOUNT,"ticket":"undo"})).await.unwrap(); + assert!(!store.resource("one").unwrap().unwrap()["labelIds"].as_array().unwrap().contains(&json!("STARRED"))); + for (ticket, add, remove) in [("star", vec!["STARRED"], vec![]), ("unstar", vec![], vec!["STARRED"]), ("read-archive", vec![], vec!["UNREAD","INBOX"])] { + local.call("local.edit", &json!({"accountId":ACCOUNT,"ticket":ticket,"ids":["one"],"addLabelIds":add,"removeLabelIds":remove})).await.unwrap(); + } + assert_eq!(local.call("local.labelCounts", &json!({"accountId":ACCOUNT,"id":"INBOX"})).await.unwrap()["total"], 1); + assert!(provider.world.lock().unwrap().writes.is_empty()); + drop(store); + local.shutdown().await; + drop(local); + let restarted = LocalMail::default(); + let store = restarted.store(ACCOUNT).await.unwrap(); + assert!(store.status().unwrap()["pendingEdits"].as_u64().unwrap() > 0); + provider.world.lock().unwrap().unauthorized = false; + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + assert_eq!(store.status().unwrap()["pendingEdits"], 0); + let world = provider.world.lock().unwrap(); + assert_eq!(world.writes.len(), 1, "rapid reversals must coalesce to one mutation"); + assert_eq!(world.messages["one"]["labelIds"], json!([])); + drop(world); + restarted.call("local.edit", &json!({"accountId":ACCOUNT,"ticket":"deleted","ids":["two"],"addLabelIds":["STARRED"],"removeLabelIds":[]})).await.unwrap(); + provider.world.lock().unwrap().messages.remove("two"); + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + assert_eq!(store.status().unwrap()["editConflicts"], 1); + let edits = store.edits().unwrap(); + let conflict = edits.as_array().unwrap().iter().find(|edit| edit["ticket"] == "deleted").unwrap(); + assert_eq!(conflict["error"], "message_deleted"); + assert_eq!(provider.world.lock().unwrap().writes.len(), 1, "a deleted message must not receive a mutation"); + restarted.shutdown().await; + }).await; +} + +#[tokio::test] +async fn interrupted_provider_body_keeps_inventory_checkpoint_and_unvisited_mail() { + if isolated() { + return; + } + let fixture = + account_fixture(json!({"version":1,"accounts":[{"provider":"gmail","email":ACCOUNT}]})); + let _credential = credentials(&fixture); + let provider = Provider::new().await; + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + gmail_http::with_test_transport(client, provider.origin.clone(), async { + let local = LocalMail::default(); + let gmail = gmail::Session::default(); + let store = local.store(ACCOUNT).await.unwrap(); + store + .put(&message("unvisited", "preserved until reconciliation"), 0) + .unwrap(); + set(&store, "legacyImported", "true"); + provider.world.lock().unwrap().pause = "/messages/one".into(); + assert!( + tokio::time::timeout( + Duration::from_millis(300), + sync::step(&store, &gmail, ACCOUNT, 0) + ) + .await + .is_err() + ); + assert!( + provider + .world + .lock() + .unwrap() + .requests + .iter() + .any(|r| r.contains("/messages/one?")), + "the real body request must have started" + ); + assert_eq!( + store.read(|db| store::state(db, "page")).unwrap(), + "page-two" + ); + assert_eq!(store.status().unwrap()["complete"], false); + assert!(store.resource("unvisited").unwrap().is_some()); + assert!(store.resource("one").unwrap().is_none()); + drop(store); + local.shutdown().await; + drop(local); + provider.world.lock().unwrap().pause.clear(); + let restarted = LocalMail::default(); + synchronize(&restarted, &gmail).await; + let store = restarted.store(ACCOUNT).await.unwrap(); + assert_eq!(store.status().unwrap()["complete"], true); + assert!(store.resource("unvisited").unwrap().is_none()); + assert!(store.complete_resource("one").unwrap().is_some()); + assert!(store.complete_resource("two").unwrap().is_some()); + restarted.shutdown().await; + }) + .await; +} + +#[tokio::test] +async fn interrupted_inventory_and_history_requests_resume_their_saved_page() { + if isolated() { + return; + } + let fixture = + account_fixture(json!({"version":1,"accounts":[{"provider":"gmail","email":ACCOUNT}]})); + let _credential = credentials(&fixture); + let provider = Provider::new().await; + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + gmail_http::with_test_transport(client, provider.origin.clone(), async { + let gmail = gmail::Session::default(); + let mut local = LocalMail::default(); + let mut store = local.store(ACCOUNT).await.unwrap(); + store + .put(&message("unvisited", "kept during partial inventory"), 0) + .unwrap(); + set(&store, "legacyImported", "true"); + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + assert_eq!( + store.read(|db| store::state(db, "page")).unwrap(), + "page-two" + ); + for (pause, checkpoint, expected) in [ + ("pageToken=page-two", "page", "page-two"), + ("pageToken=history-two", "historyPage", "history-two"), + ] { + if checkpoint == "historyPage" { + provider.world.lock().unwrap().paginated_history = true; + set(&store, "lastHistory", "0"); + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + } + provider.world.lock().unwrap().pause = pause.into(); + assert!( + tokio::time::timeout( + Duration::from_millis(300), + sync::step(&store, &gmail, ACCOUNT, 0) + ) + .await + .is_err() + ); + assert!( + provider + .world + .lock() + .unwrap() + .requests + .iter() + .any(|line| line.contains(pause)) + ); + assert_eq!( + store.read(|db| store::state(db, checkpoint)).unwrap(), + expected + ); + assert!(store.resource("unvisited").unwrap().is_some()); + assert_eq!(store.status().unwrap()["inventoryComplete"], false); + drop(store); + local.shutdown().await; + drop(local); + local = LocalMail::default(); + store = local.store(ACCOUNT).await.unwrap(); + assert_eq!( + store.read(|db| store::state(db, checkpoint)).unwrap(), + expected + ); + provider.world.lock().unwrap().pause.clear(); + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + } + assert!(store.resource("unvisited").unwrap().is_none()); + assert_eq!(store.status().unwrap()["complete"], true); + store + .put( + &message("retained", "kept while expired history rebuilds"), + 0, + ) + .unwrap(); + provider.world.lock().unwrap().expired_history = true; + set(&store, "lastHistory", "0"); + sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + assert!(store.resource("retained").unwrap().is_some()); + assert_eq!(store.status().unwrap()["inventoryComplete"], false); + provider.world.lock().unwrap().expired_history = false; + provider.world.lock().unwrap().paginated_history = false; + synchronize(&local, &gmail).await; + assert!(store.resource("retained").unwrap().is_none()); + local.shutdown().await; + }) + .await; +} + +#[cfg(target_os = "linux")] +#[tokio::test] +#[ignore = "requires an isolated tmpfs smaller than 1 GiB; scripts/test-low-space.py"] +async fn low_space_refuses_body_download_and_preserves_saved_mail() { + if let Some(path) = std::env::var_os("MAGPIE_LOW_SPACE_SEED") { + let store = store::Store::open(super::tests::open_directory(&std::path::PathBuf::from( + path, + ))) + .unwrap(); + store + .put(&message("saved", "saved body remains readable"), 0) + .unwrap(); + return; + } + if isolated() { + return; + } + let fixture = + account_fixture(json!({"version":1,"accounts":[{"provider":"gmail","email":ACCOUNT}]})); + let _credential = credentials(&fixture); + let provider = Provider::new().await; + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + gmail_http::with_test_transport(client, provider.origin.clone(), async { + let gmail = gmail::Session::default(); + let directory = super::tests::directory(); + std::fs::copy("/tmp/fixture-seed/mail.sqlite", directory.join("mail.sqlite")).unwrap(); + let store = store::Store::open(super::tests::open_directory(&directory)).unwrap(); + assert!( + crate::platform::private_fs::available_bytes(store.directory()).unwrap() + < 1024 * 1024 * 1024 + ); + assert_eq!( + store.put(&message("unsaved", "refused body"), 0), + Err("local_disk_low") + ); + set(&store, "legacyImported", "true"); + assert_eq!( + sync::step(&store, &gmail, ACCOUNT, 0).await, + Err("local_disk_low") + ); + assert!(store.resource("saved").unwrap().is_some()); + assert_eq!(store.status().unwrap()["complete"], false); + assert!( + provider + .world + .lock() + .unwrap() + .requests + .iter() + .all(|line| !line.contains("/messages/one")), + "low space must refuse before a body request" + ); + assert!(store.resource("unsaved").unwrap().is_none()); + drop(store); + std::fs::remove_dir_all(directory).unwrap(); + }) + .await; +} diff --git a/src/local_mail/recovery_tests.rs b/src/local_mail/recovery_tests.rs index d4ebabbd6..90e9d1ce5 100644 --- a/src/local_mail/recovery_tests.rs +++ b/src/local_mail/recovery_tests.rs @@ -1,10 +1,10 @@ use super::{ store::{self, Store}, sync, - tests::{directory, message}, + tests::{directory, message, open_directory}, }; use serde_json::json; -use std::{fs::File, path::PathBuf, sync::Arc}; +use std::{path::PathBuf, sync::Arc}; struct Mailbox(PathBuf); impl Mailbox { @@ -12,7 +12,7 @@ impl Mailbox { Self(directory()) } fn open(&self) -> Arc { - Store::open(File::open(&self.0).unwrap()).unwrap() + Store::open(open_directory(&self.0)).unwrap() } } impl Drop for Mailbox { @@ -30,7 +30,7 @@ fn set(store: &Store, key: &str, value: &str) { #[test] fn inventory_and_history_checkpoints_survive_process_exit() { if let Some(path) = std::env::var_os("MAGPIE_RECOVERY_CHILD") { - let store = Store::open(File::open(path).unwrap()).unwrap(); + let store = Store::open(open_directory(&PathBuf::from(path))).unwrap(); match std::env::var("MAGPIE_RECOVERY_PHASE").unwrap().as_str() { "inventory" => { store.put(&message("seen", "cached body"), 1).unwrap(); diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs index 2b209d00b..2563016cb 100644 --- a/src/local_mail/tests.rs +++ b/src/local_mail/tests.rs @@ -23,6 +23,11 @@ pub(super) fn directory() -> std::path::PathBuf { } path } +pub(super) fn open_directory(path: &std::path::Path) -> File { + crate::platform::private_fs::directories(path, &[], false) + .unwrap() + .unwrap() +} pub(super) fn message(id: &str, text: &str) -> Value { json!({"id":id,"threadId":"thread","labelIds":["INBOX","UNREAD"],"internalDate":"1700000000000", "payload":{"mimeType":"text/plain","headers":[{"name":"From","value":"Alice "},{"name":"Subject","value":"Café 合成"}], @@ -32,7 +37,7 @@ pub(super) fn message(id: &str, text: &str) -> Value { fn local_mail_search_and_edits_survive_restart() { let path = directory(); { - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); store .put(&message("one", "Offline café needles"), 1) .unwrap(); @@ -67,12 +72,12 @@ fn local_mail_search_and_edits_survive_restart() { ); assert_eq!(store.status().unwrap()["pendingEdits"], 1); assert!( - Store::open(File::open(&path).unwrap()).is_err(), + Store::open(open_directory(&path)).is_err(), "another owner must not open the database" ); } { - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); assert_eq!( store.resource("one").unwrap().unwrap()["labelIds"], json!(["INBOX"]) @@ -114,7 +119,7 @@ fn database_and_sidecar_links_never_touch_their_targets() { let target = path.join("untouched"); std::fs::write(&target, b"secret sentinel").unwrap(); symlink(&target, path.join(name)).unwrap(); - let result = Store::open(File::open(&path).unwrap()); + let result = Store::open(open_directory(&path)); assert!(result.is_err(), "{name}"); assert_eq!(std::fs::read(&target).unwrap(), b"secret sentinel"); std::fs::remove_dir_all(path).unwrap(); @@ -123,7 +128,7 @@ fn database_and_sidecar_links_never_touch_their_targets() { #[test] fn sqlite_cannot_attach_a_path_outside_its_directory() { let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); let escaped = path.join("escaped"); assert!( store @@ -143,7 +148,7 @@ fn sqlite_cannot_attach_a_path_outside_its_directory() { #[test] fn coalescing_preserves_latest_intent_and_undo_stops_before_claim() { let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); store.put(&message("one", "body"), 1).unwrap(); store .edit("star", &["one".into()], &["STARRED".into()], &[]) @@ -174,7 +179,7 @@ fn coalescing_preserves_latest_intent_and_undo_stops_before_claim() { #[test] fn missing_text_is_retryable_and_paging_never_repeats_the_previous_page() { let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); for id in ["one", "two", "three"] { store.put(&message(id, "body"), 1).unwrap(); } @@ -224,7 +229,7 @@ fn missing_text_is_retryable_and_paging_never_repeats_the_previous_page() { #[test] fn malformed_history_rolls_back_jobs_deletions_and_checkpoint() { let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); store.put(&message("kept", "sentinel"), 1).unwrap(); store .write(|db| store::set_state(db, "history", "100")) @@ -247,7 +252,7 @@ fn malformed_history_rolls_back_jobs_deletions_and_checkpoint() { #[test] fn large_summary_pages_keep_a_continuation_and_reject_an_oversized_single_row() { let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); for id in ["a", "b"] { store.put(&message(id, "body"), 1).unwrap(); let summary = json!({"id":id,"subject":"x".repeat(9*1024*1024)}).to_string(); @@ -289,7 +294,7 @@ fn large_summary_pages_keep_a_continuation_and_reject_an_oversized_single_row() #[test] fn committed_mail_and_queued_edits_survive_process_exit_without_checkpoint() { if let Some(path) = std::env::var_os("MAGPIE_WAL_CHILD") { - let store = Store::open(File::open(path).unwrap()).unwrap(); + let store = Store::open(open_directory(&std::path::PathBuf::from(path))).unwrap(); store .put(&message("durable", "committed needle"), 1) .unwrap(); @@ -313,7 +318,7 @@ fn committed_mail_and_queued_edits_survive_process_exit_without_checkpoint() { "{}", String::from_utf8_lossy(&child.stdout) ); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); assert_eq!( store.list("needle is:starred", 50, "").unwrap()["summaries"][0]["id"], "durable" @@ -333,7 +338,7 @@ fn benchmark_local_queries() { .unwrap_or(100_000); assert!((1..=1_000_000).contains(&count)); let path = directory(); - let store = Store::open(File::open(&path).unwrap()).unwrap(); + let store = Store::open(open_directory(&path)).unwrap(); let started = Instant::now(); store.write(|db| { let mut messages=store::sql(db.prepare("INSERT INTO messages(id,thread_id,date,summary,blob,server_labels,sender,recipients,copied,subject,filenames,has_attachment,text_complete,generation) VALUES(?1,?1,?2,?3,'synthetic','[\"INBOX\"]','alice@example.org','bob@example.org','','Invoice','','0',1,1)"))?; diff --git a/src/outbox/tests.rs b/src/outbox/tests.rs index c6e9f3d3c..0815588d8 100644 --- a/src/outbox/tests.rs +++ b/src/outbox/tests.rs @@ -1120,3 +1120,103 @@ async fn cancelling_during_offline_preflight_never_calls_delivery() { ); outbox.shutdown().await.unwrap(); } + +#[tokio::test] +async fn recorder_confirms_one_resumed_send_and_no_retry_or_cancelled_delivery() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let recorded = Arc::new(Mutex::new(Vec::::new())); + let records = recorded.clone(); + let server = tokio::spawn(async move { + let mut handlers = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let records = records.clone(); + handlers.spawn(async move { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + let Ok(byte) = socket.read_u8().await else { return }; + headers.push(byte); + assert!(headers.len() < 65_536); + } + let headers = String::from_utf8(headers).unwrap(); + let length: usize = headers.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }).unwrap(); + assert!(length < 65_536); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await.unwrap(); + let request: Value = serde_json::from_slice(&bytes).unwrap(); + let id = request["sendId"].as_str().unwrap().to_owned(); + records.lock().unwrap().push(id.clone()); + if id == "interrupted" { std::future::pending::<()>().await; } + let _ = socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}").await; + }); + } + }); + let executor: Executor = Arc::new(move |request| { + let origin = origin.clone(); + Box::pin(async move { + reqwest::Client::builder().no_proxy().build().unwrap() + .post(origin).header("Content-Type", "application/json").body(request.to_string()).send().await + .map_err(|_| "network_timed_out")?; + Ok(json!({})) + }) + }); + let gate = Arc::new(Notify::new()); + let entered = Arc::new(Notify::new()); + let gate_copy = gate.clone(); + let entered_copy = entered.clone(); + let readiness: Readiness = Arc::new(move |_, _| { + let gate = gate_copy.clone(); + let entered = entered_copy.clone(); + Box::pin(async move { + entered.notify_one(); + gate.notified().await; + Ok(()) + }) + }); + let dir = Temp::new(); + let waiting = Outbox::with_root(executor.clone(), Some(dir.0.clone())) + .with_readiness(readiness.clone()); + let mut request = enqueue("resumed", "a@example.org", 0); + request["resumeUnsent"] = json!(true); + waiting.call("outbox.enqueue", &request).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), entered.notified()).await.unwrap(); + assert!(recorded.lock().unwrap().is_empty()); + waiting.shutdown().await.unwrap(); + drop(waiting); + + let connected = Outbox::with_root(executor.clone(), Some(dir.0.clone())); + wait_state(&connected, "resumed", "a@example.org", "sent").await; + assert_eq!(connected.call("outbox.enqueue", &request).await.unwrap()["duplicate"], true); + let interrupted = enqueue("interrupted", "a@example.org", 0); + connected.call("outbox.enqueue", &interrupted).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), async { + while recorded.lock().unwrap().len() != 2 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }).await.unwrap(); + assert_eq!(state(&connected, "interrupted", "a@example.org").await, "sending"); + connected.shutdown().await.unwrap(); + drop(connected); + + let recovered = Outbox::with_root(executor, Some(dir.0.clone())).with_readiness(readiness); + assert_eq!(state(&recovered, "interrupted", "a@example.org").await, "unknown"); + assert_eq!(recovered.call("outbox.enqueue", &interrupted).await.unwrap()["duplicate"], true); + let mut cancelled = enqueue("cancelled", "a@example.org", 0); + cancelled["resumeUnsent"] = json!(true); + recovered.call("outbox.enqueue", &cancelled).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), entered.notified()).await.unwrap(); + recovered.call("outbox.undo", &json!({"accountId":"a@example.org","sendId":"cancelled"})).await.unwrap(); + gate.notify_one(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(*recorded.lock().unwrap(), vec!["resumed", "interrupted"]); + assert_eq!(state(&recovered, "cancelled", "a@example.org").await, "cancelled"); + recovered.shutdown().await.unwrap(); + server.abort(); + let _ = server.await; +} diff --git a/tests/test_backend_release.py b/tests/test_backend_release.py index 86f8adfcd..e7eecb924 100644 --- a/tests/test_backend_release.py +++ b/tests/test_backend_release.py @@ -74,11 +74,11 @@ def test_preparation_allows_old_pin_but_merge_requires_equality(self): (self.root / 'Cargo.lock').write_text('[[package]]\nname = "omamail"\nversion = "0.8.1"\n') self.assertNotEqual(self.run_helper('check', '--root', self.root).returncode, 0) - def test_release_version_includes_plugin_manifest_and_standalone_host(self): + def test_backend_version_includes_standalone_host_and_keeps_plugin_independent(self): self.metadata() self.assertEqual(self.run_helper('check', '--root', self.root, '--tag', 'v0.8.2').returncode, 0) fixtures = { - 'manifest.json': '{"version":"0.8.1"}', + 'manifest.json': '{"version":"invalid"}', 'app/CMakeLists.txt': 'project(omamail-app VERSION 0.8.1 LANGUAGES CXX)\n', } for name, value in fixtures.items(): @@ -90,6 +90,20 @@ def test_release_version_includes_plugin_manifest_and_standalone_host(self): self.assertNotEqual(result.returncode, 0) path.write_text(original) + def test_standalone_manifest_preserves_defaults_without_changing_plugin_metadata(self): + self.metadata() + plugin = {'id': 'magpie', 'name': 'Magpie', 'version': '1.0.0', + 'barWidget': {'defaults': {'maxMessages': 50}}} + path = self.root / 'manifest.json' + path.write_text(json.dumps(plugin)) + result = self.run_helper('standalone-manifest', '--root', self.root) + self.assertEqual(result.returncode, 0, result.stderr) + bundled = json.loads(result.stdout) + self.assertEqual(bundled, dict(plugin, id='omamail', name='Omamail', version='0.8.2')) + self.assertEqual(json.loads(path.read_text()), plugin) + (self.root / 'app/CMakeLists.txt').write_text('project(omamail-app VERSION 0.8.1 LANGUAGES CXX)\n') + self.assertNotEqual(self.run_helper('standalone-manifest', '--root', self.root).returncode, 0) + def test_release_pr_gate_requires_published_version_before_merge(self): # Execute the actual workflow guard: removing or weakening it must let # the pre-publication release PR reach the forbidden merge marker. diff --git a/ui/App.qml b/ui/App.qml index 4ab345384..9d1bf2a44 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -338,7 +338,8 @@ Item { onRootStateChanged: { var flipped = rootState.anyReady !== wasReady wasReady = rootState.anyReady - if (flipped || (!rootState.anyReady && navUntouched)) resetNavigation() + var editingUnreadyAccount = page === "setup" && !ready + if ((flipped && !editingUnreadyAccount) || (!rootState.anyReady && navUntouched)) resetNavigation() } function resetNavigation() { var next = Nav.rootFor(rootState) diff --git a/ui/components/ComposeExitDialog.qml b/ui/components/ComposeExitDialog.qml index 7bc4bb44f..bf2ad1a9f 100644 --- a/ui/components/ComposeExitDialog.qml +++ b/ui/components/ComposeExitDialog.qml @@ -1,4 +1,5 @@ import QtQuick +import QtQuick.Window import "../controls" as Widgets import "../settings" import QtQuick.Controls as QQC @@ -16,6 +17,8 @@ Item { required property string currentDraftKey readonly property bool opened: dialog.opened property string requestedDraftKey: "" + property var returnFocusItem: null + property string returnDraftKey: "" signal saveRequested(string draftKey) signal discardRequested(string draftKey) @@ -32,6 +35,8 @@ Item { function open() { if (currentDraftKey === "") return requestedDraftKey = currentDraftKey + returnDraftKey = currentDraftKey + returnFocusItem = root.Window.activeFocusItem dialog.open() } function close() { @@ -63,7 +68,18 @@ Item { focus: true closePolicy: QQC.Popup.CloseOnEscape onOpened: saveButton.forceActiveFocus() - onClosed: root.requestedDraftKey = "" + onClosed: { + root.requestedDraftKey = "" + var target = root.returnFocusItem + var key = root.returnDraftKey + root.returnFocusItem = null + root.returnDraftKey = "" + Qt.callLater(function() { + if (target && target.visible && target.enabled && key === root.currentDraftKey + && root.Window.window && root.Window.window.visible) + target.forceActiveFocus() + }) + } background: Rectangle { radius: Style.cornerRadius color: root.popupBackgroundColor diff --git a/ui/tests/qml/tst_imap_credential_control_bytes.qml b/ui/tests/qml/tst_imap_credential_control_bytes.qml index 4d829137e..bb62647da 100644 --- a/ui/tests/qml/tst_imap_credential_control_bytes.qml +++ b/ui/tests/qml/tst_imap_credential_control_bytes.qml @@ -63,10 +63,10 @@ Item { function test_controls_are_refused_without_verification_or_storage_data() { var cases = [] - for (var byte = 0; byte < 32; byte++) { - cases.push({tag: "embedded-" + byte, value: "before" + String.fromCharCode(byte) + "after"}) - if (byte !== 10 && byte !== 13) - cases.push({tag: "trailing-" + byte, value: "password" + String.fromCharCode(byte)}) + for (var codePoint = 0; codePoint < 32; codePoint++) { + cases.push({tag: "embedded-" + codePoint, value: "before" + String.fromCharCode(codePoint) + "after"}) + if (codePoint !== 10 && codePoint !== 13) + cases.push({tag: "trailing-" + codePoint, value: "password" + String.fromCharCode(codePoint)}) } cases.push({tag: "embedded-DEL", value: "before\u007fafter"}) cases.push({tag: "trailing-DEL", value: "password\u007f"}) From daf67da563f1e296a05ec09a970e5112345eff46 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:58:09 +0100 Subject: [PATCH 003/568] Fix cross-platform recovery fixtures and setup completion navigation --- scripts/test-low-space.py | 7 ++++++- src/local_mail/provider_tests.rs | 3 +-- src/local_mail/tests.rs | 22 ++++++++-------------- ui/App.qml | 7 ++++++- 4 files changed, 21 insertions(+), 18 deletions(-) diff --git a/scripts/test-low-space.py b/scripts/test-low-space.py index d1f4437c0..dcd751233 100644 --- a/scripts/test-low-space.py +++ b/scripts/test-low-space.py @@ -4,6 +4,8 @@ import os from pathlib import Path import subprocess +import shutil +import sys import tempfile ROOT = Path(__file__).resolve().parents[1] @@ -11,6 +13,9 @@ def main(): + if len(sys.argv) == 3 and sys.argv[1] == "--worker": + shutil.copytree("/tmp/fixture-seed", "/tmp/mail-check/store") + os.execv(sys.argv[2], [sys.argv[2], "--exact", TEST, "--ignored", "--nocapture"]) build = subprocess.run( ["cargo", "test", "--locked", "--lib", "--no-run", "--message-format=json"], cwd=ROOT, stdout=subprocess.PIPE, text=True, check=True) @@ -30,7 +35,7 @@ def main(): "--perms", "0700", "--dir", "/tmp/mail-check", "--setenv", "TMPDIR", "/tmp/mail-check", "--setenv", "OMAMAIL_ACTION_TEST_CHILD", TEST, - executables[0], "--exact", TEST, "--ignored", "--nocapture"] + sys.executable, str(Path(__file__).resolve()), "--worker", executables[0]] result = subprocess.run(command, cwd=ROOT, env=os.environ.copy(), timeout=30) raise SystemExit(result.returncode) diff --git a/src/local_mail/provider_tests.rs b/src/local_mail/provider_tests.rs index f2c374a0f..a23e655cb 100644 --- a/src/local_mail/provider_tests.rs +++ b/src/local_mail/provider_tests.rs @@ -442,8 +442,7 @@ async fn low_space_refuses_body_download_and_preserves_saved_mail() { let client = reqwest::Client::builder().no_proxy().build().unwrap(); gmail_http::with_test_transport(client, provider.origin.clone(), async { let gmail = gmail::Session::default(); - let directory = super::tests::directory(); - std::fs::copy("/tmp/fixture-seed/mail.sqlite", directory.join("mail.sqlite")).unwrap(); + let directory = std::path::PathBuf::from("/tmp/mail-check/store"); let store = store::Store::open(super::tests::open_directory(&directory)).unwrap(); assert!( crate::platform::private_fs::available_bytes(store.directory()).unwrap() diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs index 2563016cb..ba12063e5 100644 --- a/src/local_mail/tests.rs +++ b/src/local_mail/tests.rs @@ -6,25 +6,19 @@ use std::{ }; static SERIAL: AtomicU64 = AtomicU64::new(0); pub(super) fn directory() -> std::path::PathBuf { - let path = std::env::temp_dir().join(format!( + let parent = std::env::temp_dir().canonicalize().unwrap(); + let name = format!( "magpie-local-{}-{}-{}", std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(), SERIAL.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir(&path).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); - } - path + ); + crate::platform::private_fs::directories(&parent, &[&name], true).unwrap().unwrap(); + parent.join(name) } pub(super) fn open_directory(path: &std::path::Path) -> File { - crate::platform::private_fs::directories(path, &[], false) + let path = path.canonicalize().unwrap(); + crate::platform::private_fs::directories(path.parent().unwrap(), &[path.file_name().unwrap().to_str().unwrap()], false) .unwrap() .unwrap() } diff --git a/ui/App.qml b/ui/App.qml index 9d1bf2a44..697768f9c 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -328,6 +328,7 @@ Item { // an untouched root, so saving an address cannot reopen a dismissed form. readonly property var rootState: ({ anyReady: anyReady, + accountReady: ready, hasSavedAccounts: !!service && service.hasSavedAccounts === true, setupUnderway: setupUnderway, provider: service ? String(service.providerId || "") : "", @@ -335,11 +336,15 @@ Item { }) property bool navUntouched: true property bool wasReady: false + property bool wasAccountReady: false onRootStateChanged: { var flipped = rootState.anyReady !== wasReady + var signedIn = rootState.accountReady && !wasAccountReady wasReady = rootState.anyReady + wasAccountReady = rootState.accountReady var editingUnreadyAccount = page === "setup" && !ready - if ((flipped && !editingUnreadyAccount) || (!rootState.anyReady && navUntouched)) resetNavigation() + var completedSetup = signedIn && page === "setup" && editingProvider === rootState.provider + if ((flipped && !editingUnreadyAccount) || completedSetup || (!rootState.anyReady && navUntouched)) resetNavigation() } function resetNavigation() { var next = Nav.rootFor(rootState) From a01c3c12088f5f44f096f3a48fdb95a7feefb009 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:08:28 +0100 Subject: [PATCH 004/568] Fix Windows database sharing and avoid storage creation on failed reads --- src/local_mail/mod.rs | 44 ++++++++++++++++++++++++++++++----------- src/local_mail/tests.rs | 5 +++-- src/local_mail/vfs.rs | 10 +++++++++- tests/cli.rs | 2 ++ 4 files changed, 46 insertions(+), 15 deletions(-) diff --git a/src/local_mail/mod.rs b/src/local_mail/mod.rs index f771ae650..a2ee4dd3b 100644 --- a/src/local_mail/mod.rs +++ b/src/local_mail/mod.rs @@ -104,6 +104,9 @@ impl LocalMail { } } async fn store(&self, account: &str) -> Result, &'static str> { + self.open_store(account, true).await?.ok_or("local_storage_unavailable") + } + async fn open_store(&self, account: &str, create: bool) -> Result>, &'static str> { let account = account.to_owned(); let stores = self.stores.clone(); let identity = account.clone(); @@ -119,20 +122,23 @@ impl LocalMail { } let mut stores = stores.lock().map_err(|_| "local_storage_unavailable")?; if let Some(store) = stores.get(&account) { - return Ok(store.clone()); + return Ok(Some(store.clone())); } let dirs = AppDirs::discover()?; let hash = format!("{:x}", Sha256::digest(account.as_bytes())); - let directory = + let directory = if create { private_fs::directories(&dirs.state, &["omamail", "mail", &hash], true)? - .ok_or("local_storage_unavailable")?; + } else { + private_fs::directories_readonly(&dirs.state, &["omamail", "mail", &hash])? + }; + let Some(directory) = directory else { return Ok(None) }; let store = Store::open(directory)?; stores.insert(account, store.clone()); - Ok(store) + Ok(Some(store)) }) .await .map_err(|_| "local_storage_unavailable")??; - ipc::listen(&store, &identity)?; + if let Some(store) = &store { ipc::listen(store, &identity)?; } Ok(store) } pub(crate) async fn resource( @@ -140,7 +146,7 @@ impl LocalMail { account: &str, id: &str, ) -> Result, &'static str> { - let store = match self.store(account).await { + let store = match self.open_store(account, false).await { Err("private_fs_busy") => { return ipc::request( account, @@ -150,7 +156,8 @@ impl LocalMail { .await .map(|v| if v.is_null() { None } else { Some(v) }); } - answer => answer?, + Ok(None) => return Ok(None), + answer => answer?.ok_or("local_storage_unavailable")?, }; let id = id.to_owned(); tokio::task::spawn_blocking(move || store.complete_resource(&id)) @@ -162,7 +169,7 @@ impl LocalMail { account: &str, id: &str, ) -> Result, &'static str> { - let store = match self.store(account).await { + let store = match self.open_store(account, false).await { Err("private_fs_busy") => { return ipc::request( account, @@ -172,7 +179,8 @@ impl LocalMail { .await .map(|v| v.as_str().map(str::to_owned)); } - answer => answer?, + Ok(None) => return Ok(None), + answer => answer?.ok_or("local_storage_unavailable")?, }; let id = id.to_owned(); sync::disk(&store, move |s| s.revision(&id)).await @@ -183,7 +191,7 @@ impl LocalMail { id: &str, gmail: &crate::providers::gmail::Session, ) -> Result { - let store = match self.store(account).await { + let store = match self.open_store(account, false).await { Err("private_fs_busy") => { if let Some(value) = self.resource(account, id).await? { return Ok(value); @@ -195,7 +203,16 @@ impl LocalMail { ) .await; } - answer => answer?, + Ok(None) => { + let mut resource = match crate::cache::resource::read(account, id).await? { + Some(resource) => resource, + None => gmail.call("gmail.read", &json!({"accountId":account,"id":id,"full":true})).await?, + }; + sync::hydrate_text(gmail, account, id, &mut resource, true).await?; + let store = self.store(account).await?; + return Self::save_read(&store, resource).await; + } + answer => answer?.ok_or("local_storage_unavailable")?, }; let gate = store.fetch_gate(id)?; let _guard = gate.lock().await; @@ -224,8 +241,11 @@ impl LocalMail { } }; sync::hydrate_text(gmail, account, id, &mut resource, true).await?; + Self::save_read(&store, resource).await + } + async fn save_read(store: &Arc, resource: Value) -> Result { let saved = resource.clone(); - let saved = sync::disk(&store, move |s| { + let saved = sync::disk(store, move |s| { let generation = s.read(|db| Ok(store::state(db, "generation")?.parse().unwrap_or(1)))?; s.put(&saved, generation) diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs index ba12063e5..9f5082879 100644 --- a/src/local_mail/tests.rs +++ b/src/local_mail/tests.rs @@ -309,8 +309,9 @@ fn committed_mail_and_queued_edits_survive_process_exit_without_checkpoint() { assert_eq!( child.status.code(), Some(73), - "{}", - String::from_utf8_lossy(&child.stdout) + "{}\n{}", + String::from_utf8_lossy(&child.stdout), + String::from_utf8_lossy(&child.stderr) ); let store = Store::open(open_directory(&path)).unwrap(); assert_eq!( diff --git a/src/local_mail/vfs.rs b/src/local_mail/vfs.rs index cbfbb3cce..c3b25e796 100644 --- a/src/local_mail/vfs.rs +++ b/src/local_mail/vfs.rs @@ -146,7 +146,15 @@ unsafe extern "C" fn open( Ok(Some(file)) => file, Ok(None) if flags & SQLITE_OPEN_CREATE != 0 => { match fs::create_private(&root.directory, name) { - Ok(file) => file, + Ok(file) => { + // Private creation excludes other Windows writers. Reopen + // under the owner lease so our SQLite connections can share it. + drop(file); + match fs::regular(&root.directory, name, true) { + Ok(Some(file)) => file, + _ => return SQLITE_CANTOPEN, + } + } Err(_) => return SQLITE_CANTOPEN, } } diff --git a/tests/cli.rs b/tests/cli.rs index 71a3dc59f..ef8287c7c 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -570,6 +570,8 @@ fn configured_read_failures_do_not_repair_registry_metadata() { ] { let output = call_mail_read(&fixture.0, account, id); assert!(!output.status.success(), "{account}: {output:?}"); + assert!(!state_root(&fixture.0).join("omamail/mail").exists(), + "a failed read must not initialize local storage"); if let Some(expected_error) = expected_error { assert_eq!( serde_json::from_slice::(&output.stdout).unwrap()["error"]["code"], From e012c2bee58cc2bdd171363c7d6b65aba5c4434f Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:47:28 +0100 Subject: [PATCH 005/568] Fix desktop accessibility and automate native acceptance checks --- .github/workflows/ci.yml | 6 +- .../workflows/performance-verification.yml | 3 + Makefile | 1 + app/CMakeLists.txt | 15 + app/src/backend_contract.h.in | 2 +- app/tests/qml/tst_host_contract.qml | 7 +- benchmarks/mail/README.md | 15 + benchmarks/mail/desktop_acceptance.py | 340 ++++++++++++++++++ benchmarks/mail/desktop_main.cpp | 62 ++++ benchmarks/mail/tst_desktop.qml | 146 ++++++++ docs/PERFORMANCE-VALIDATION.md | 20 +- scripts/verify-performance.py | 3 +- src/attachment/thumbnail.rs | 8 +- tests/test_agent_bridge.py | 5 +- tests/test_attachment_handles_rpc.py | 106 ++++++ ui/components/ComposeView.qml | 7 + ui/components/IconTextButton.qml | 23 +- ui/components/LocalMailStatus.qml | 4 + ui/tests/qml/tst_calendar_pending_ranges.qml | 93 +++++ ui/tests/qml/tst_keyrouter.qml | 3 +- 20 files changed, 840 insertions(+), 29 deletions(-) create mode 100644 benchmarks/mail/desktop_acceptance.py create mode 100644 benchmarks/mail/desktop_main.cpp create mode 100644 benchmarks/mail/tst_desktop.qml create mode 100644 tests/test_attachment_handles_rpc.py create mode 100644 ui/tests/qml/tst_calendar_pending_ranges.qml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6dc986e7b..73d635449 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -183,8 +183,10 @@ jobs: ctest --test-dir build/app -C Release --output-on-failure if ($LASTEXITCODE -ne 0) { throw "Qt tests failed" } python app/tests/test_qml_inventory.py - qmltestrunner -input app/tests/qml/tst_host_contract.qml -import app/qml/imports -import app/qml/styles -import ui - if ($LASTEXITCODE -ne 0) { throw "QML tests failed" } + qmltestrunner -input app/tests/qml/tst_host_contract.qml -import app/qml/imports -import app/qml/styles -import ui -o qml-host-contract.txt,txt + $qmlStatus = $LASTEXITCODE + Get-Content qml-host-contract.txt + if ($qmlStatus -ne 0) { throw "QML tests failed ($qmlStatus)" } python tests/test_backend_api.py --binary target/release/omamail.exe --expected-version $version --standalone if ($LASTEXITCODE -ne 0) { throw "backend API contract failed" } - name: Build and exercise the production archive diff --git a/.github/workflows/performance-verification.yml b/.github/workflows/performance-verification.yml index bd085547a..875835cbe 100644 --- a/.github/workflows/performance-verification.yml +++ b/.github/workflows/performance-verification.yml @@ -41,6 +41,9 @@ jobs: with: toolchain: "1.98.1" - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: performance-${{ matrix.profile }}-v2 + cache-targets: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.13.5" diff --git a/Makefile b/Makefile index 2c430c3f3..00978112b 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,7 @@ QML_FILES := ui/tests/qml/tst_attachment_preview.qml ui/tests/qml/tst_inbox_tool ui/tests/qml/tst_unified_batch.qml ui/tests/qml/tst_clipboard_arguments.qml \ ui/tests/qml/tst_reader_subject_menu.qml \ ui/tests/qml/tst_local_mail_status.qml \ + ui/tests/qml/tst_calendar_pending_ranges.qml \ ui/backend/Backend.qml ui/backend/Runtime.qml ui/diagnostics/Diagnostics.qml \ ui/components/BackendSetup.qml ui/components/LocalMailStatus.qml ui/components/MagpieLogo.qml ui/components/DisplaySettings.qml ui/settings/MailStyle.qml \ ui/account/MailAccount.qml ui/account/LocalMailbox.qml ui/account/AccountResources.qml ui/account/BackendSync.qml ui/account/SendQueue.qml ui/account/Intents.qml ui/account/BatchAction.qml ui/account/UnifiedBatchAction.qml ui/account/UnifiedBatchSelection.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \ diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 6e3c0b126..e45a98fea 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -145,6 +145,13 @@ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/qml/Main.qml") endif() include(CTest) +option(OMAMAIL_DESKTOP_ACCEPTANCE "Build the synthetic desktop acceptance driver" OFF) +if(OMAMAIL_DESKTOP_ACCEPTANCE) + find_package(Qt6 REQUIRED COMPONENTS QuickTest) + qt_add_executable(desktop_acceptance ../benchmarks/mail/desktop_main.cpp) + target_link_libraries(desktop_acceptance PRIVATE + omamail_native omamail_nativeplugin Qt6::QuickTest Qt6::QuickControls2) +endif() if(BUILD_TESTING) find_package(Python3 REQUIRED COMPONENTS Interpreter) function(omamail_native_test name source) @@ -179,6 +186,14 @@ if(BUILD_TESTING) find_program(QMLTESTRUNNER_EXECUTABLE qmltestrunner HINTS "${QT6_INSTALL_PREFIX}/bin") if(QMLTESTRUNNER_EXECUTABLE) + add_test(NAME tst_host_contract COMMAND ${QMLTESTRUNNER_EXECUTABLE} + -import "${CMAKE_CURRENT_SOURCE_DIR}/qml/imports" + -import "${CMAKE_CURRENT_SOURCE_DIR}/qml/styles" + -import "${CMAKE_CURRENT_SOURCE_DIR}/../ui" + -input "${CMAKE_CURRENT_SOURCE_DIR}/tests/qml/tst_host_contract.qml" + -o -,txt) + set_tests_properties(tst_host_contract PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_CONTROLS_STYLE=Omamail;QT_QUICK_CONTROLS_FALLBACK_STYLE=Basic") add_test(NAME tst_standalone_composition COMMAND ${QMLTESTRUNNER_EXECUTABLE} -import "${CMAKE_CURRENT_SOURCE_DIR}/qml/imports" -import "${CMAKE_CURRENT_SOURCE_DIR}/qml/styles" diff --git a/app/src/backend_contract.h.in b/app/src/backend_contract.h.in index 2858f7886..d3957ea56 100644 --- a/app/src/backend_contract.h.in +++ b/app/src/backend_contract.h.in @@ -3,4 +3,4 @@ #define OMAMAIL_BACKEND_API_VERSION @OMAMAIL_BACKEND_API_VERSION@ #define OMAMAIL_RELEASED_API_VERSION @OMAMAIL_RELEASED_API_VERSION@ #define OMAMAIL_BACKEND_CONTRACT_HASH "@OMAMAIL_BACKEND_CONTRACT_HASH@" -#define OMAMAIL_UNRELEASED_METHODS R"methods(@OMAMAIL_UNRELEASED_METHODS@)methods" +inline constexpr char OMAMAIL_UNRELEASED_METHODS[] = R"methods(@OMAMAIL_UNRELEASED_METHODS@)methods"; diff --git a/app/tests/qml/tst_host_contract.qml b/app/tests/qml/tst_host_contract.qml index b112d1793..3e44e13c3 100644 --- a/app/tests/qml/tst_host_contract.qml +++ b/app/tests/qml/tst_host_contract.qml @@ -204,15 +204,16 @@ TestCase { compare(Style.spacing.controlGap, 8) } - function test_standalone_uses_native_text_and_bundles_the_nerd_icon_range() { + function test_standalone_fonts_load_and_action_icons_render_vectors() { tryCompare(Style.iconFont, "status", FontLoader.Ready) compare(Style.font.family, Style.metrics.font.family) verify(Style.font.family.length > 0) compare(Style.font.iconFamily, "Symbols Nerd Font Mono") var icon = createTemporaryObject(actionIconComponent, testCase) verify(icon) - compare(icon.fontFamily, Style.font.iconFamily) - compare(icon.glyphText.codePointAt(0), 0xF120E) + verify(icon.imageSource.indexOf("data:image/svg+xml") === 0) + tryCompare(icon.children[0], "status", Image.Ready) + compare(icon.children[0].sourceSize.width, Math.ceil(icon.iconSize * 2)) } function test_current_omarchy_theme_wins_over_stale_legacy_theme() { diff --git a/benchmarks/mail/README.md b/benchmarks/mail/README.md index a5f45460b..28491cb8a 100644 --- a/benchmarks/mail/README.md +++ b/benchmarks/mail/README.md @@ -8,6 +8,21 @@ This is a comparison of actual old and new QML components, not a comparison of t `make verify-performance VERIFY_PROFILE=benchmarks` collects this comparison and the database cases below into a fresh result directory. The GitHub Actions `Performance verification` workflow runs the same profile and saves its logs and JSON as artifacts. +## Native desktop acceptance + +Build the optimized backend and optional native test driver before measuring: + +```sh +cargo build --release --locked --bin omamail +cmake -S app -B /tmp/magpie-desktop-build -DCMAKE_BUILD_TYPE=Release -DOMAMAIL_DESKTOP_ACCEPTANCE=ON -DBUILD_TESTING=OFF +cmake --build /tmp/magpie-desktop-build --target desktop_acceptance -j4 +python3 benchmarks/mail/desktop_acceptance.py --binary target/release/omamail --driver /tmp/magpie-desktop-build/desktop_acceptance --messages 100000 --samples 31 --display-mode xvfb --output /tmp/magpie-desktop-result +``` + +The output directory must be new. Linux dependencies include Pillow, Xvfb and DBus; `--accessibility` also requires GI Atspi and the accessibility bus. `--scale 1.5 --accessibility` checks enlarged controls and AT-SPI Pause/Resume, field editing and Send. The default `--display-mode physical` requires an unlocked Hyprland session and Grim. It never unlocks the session. All account state and messages are synthetic; sends have no provider credentials and remain queued. The driver preserves the active theme palette but uses the application's default text settings. + +The driver captures a changing marker only after the application state for each sample is ready. Measurements include key handling, RPC, model/layout work and capture overhead; Xvfb results describe the virtual display, not physical compositor presentation. Search is invoked through the production service. Startup means fresh app/backend processes with warm OS caches; one invocation has one startup sample and three distinct 256 KiB HTML samples. Navigation, input and search use `--samples` observations each. Do not describe one startup observation or three HTML observations as a statistically established p95. The report records raw values, source/binary hashes, hardware, Qt, theme, scale and display mode. Functional success does not imply that latency targets passed. Build activity must stop before measurement. + ## Local replica and completed Qt frames `cargo test --release --lib local_mail::tests::benchmark_local_queries -- --ignored --nocapture` creates a synthetic 100,000-message database and measures five searches returning 50 summaries. Set `MAGPIE_BENCH_MESSAGES=1000000` for the separate scale case or `MAGPIE_BENCH_BACKGROUND=1` to run concurrent durable body writes at a 25 ms minimum interval. Results include median/p95 and the actual background write count. Fixture import is a bulk transaction, not a Gmail download simulation. These measurements exclude UI, RPC and network latency. diff --git a/benchmarks/mail/desktop_acceptance.py b/benchmarks/mail/desktop_acceptance.py new file mode 100644 index 000000000..4cad6eecb --- /dev/null +++ b/benchmarks/mail/desktop_acceptance.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Measure a synthetic native window through physical or virtual display capture.""" +import argparse +import base64 +import hashlib +import io +import json +import math +import os +from pathlib import Path +import platform +import queue +import shutil +import sqlite3 +import subprocess +import threading +import time + +from PIL import Image, ImageGrab + +ROOT = Path(__file__).resolve().parents[2] +ACCOUNT = "desktop-fixture@example.test" + + +def private(path, content): + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + path.write_bytes(content if isinstance(content, bytes) else content.encode()) + path.chmod(0o600) + + +def source_hash(): + paths = subprocess.check_output(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], cwd=ROOT).decode().split("\0") + digest = hashlib.sha256() + for name in sorted(set(paths)): + if not name or name.startswith("docs/"): continue + path = ROOT / name + if path.is_file(): digest.update(name.encode() + b"\0" + path.read_bytes() + b"\0") + return digest.hexdigest() + + +def seed(folder, binary, count, html_bytes): + env = dict(os.environ) + for key in ("HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"): + path = folder / key.lower() + path.mkdir(mode=0o700) + env[key] = str(path) + registry = {"version": 1, "accounts": [{"provider": "gmail", "email": ACCOUNT}], "activeId": ACCOUNT} + private(Path(env["XDG_CONFIG_HOME"]) / "omamail/accounts.json", json.dumps(registry)) + for name in ("colors.toml", "shell.toml"): + source = Path.home() / ".local/state/omarchy/current/theme" / name + if source.exists(): + private(Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name, source.read_bytes()) + request = {"jsonrpc": "2.0", "id": 1, "method": "local.status", "params": {"accountId": ACCOUNT}} + initialized = subprocess.run([str(binary), "serve"], input=json.dumps(request) + "\n", + text=True, capture_output=True, env=env, timeout=30, check=True) + replies = [json.loads(line) for line in initialized.stdout.splitlines()] + if not any(reply.get("id") == 1 and "result" in reply for reply in replies): + raise RuntimeError(initialized.stdout + initialized.stderr) + directory = Path(env["XDG_STATE_HOME"]) / "omamail/mail" / hashlib.sha256(ACCOUNT.encode()).hexdigest() + db = sqlite3.connect(directory / "mail.sqlite") + for n in range(count): + identity = f"synthetic-{n:08}" + body = ("needle" if n % 100 == 0 else "ordinary") + f" synthetic saved message {n}" + large = n >= count - 3 and html_bytes > 0 + if large: + line = "

Large synthetic message with readable text and no external resources.

" + body = "" + line * math.ceil(html_bytes / len(line)) + "" + resource = {"id": identity, "threadId": identity, "internalDate": str(1_700_000_000_000 + n), + "labelIds": ["INBOX"], "snippet": body[:140], + "payload": {"mimeType": "text/html" if large else "text/plain", "headers": [ + {"name": "From", "value": "Synthetic sender "}, + {"name": "To", "value": ACCOUNT}, + {"name": "Subject", "value": f"Synthetic message {n}"}], + "body": {"data": base64.urlsafe_b64encode(body.encode()).decode().rstrip("="), "size": len(body)}}} + raw = json.dumps(resource, separators=(",", ":")).encode() + digest = hashlib.sha256(raw).hexdigest() + private(directory / "blobs" / digest[:2] / digest, raw) + summary = {"id": identity, "threadId": identity, "subject": f"Synthetic message {n}", + "snippet": body[:140], "from": {"display": "Synthetic sender", "email": "sender@example.test"}, + "unread": False, "date": "2026-10-21T09:00:00Z", "labelIds": ["INBOX"]} + db.execute("INSERT INTO messages VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + (identity, identity, 1_700_000_000_000 + n, json.dumps(summary), digest, '["INBOX"]', + "sender@example.test", ACCOUNT, "", summary["subject"], "", 0, 1, 1)) + db.execute("INSERT INTO labels VALUES(?, 'INBOX')", (identity,)) + db.execute("INSERT INTO search(id,subject,sender,recipients,copied,filenames,body) VALUES(?,?,?,?,?,?,?)", + (identity, summary["subject"], "sender@example.test", ACCOUNT, "", "", body)) + state = {"paused": "true", "legacyImported": "true", "history": "100", "generation": "1", + "inventoryListed": "true", "inventoryComplete": "true", "estimate": str(count), + "profile": json.dumps({"email": ACCOUNT, "messagesTotal": count}), + "labels": json.dumps([{"id": "INBOX", "name": "INBOX"}])} + db.executemany("INSERT OR REPLACE INTO state VALUES(?,?)", state.items()) + db.commit() + db.close() + return env + + +def hypr(env, *arguments): + if arguments[0] == "dispatch": + arguments = ("dispatch", ", ".join(json.dumps(value) for value in arguments[1:])) + result = subprocess.run(["hyprctl", *arguments], env=env, text=True, capture_output=True, timeout=10) + if result.returncode: + raise RuntimeError(f"hyprctl {arguments}: {result.stdout} {result.stderr}") + return result.stdout + + +def window_for(env, pid): + for window in json.loads(hypr(env, "clients", "-j")): + if window["pid"] == pid and window["title"] == "Magpie synthetic acceptance": + return window + return None + + +def accessible_nodes(pid): + import gi + gi.require_version("Atspi", "2.0") + from gi.repository import Atspi, GLib + Atspi.set_timeout(2000, 2000) + desktop = Atspi.get_desktop(0) + rows = [] + def walk(node, depth=0): + if node is None: return + if depth > 30: raise RuntimeError("Accessibility tree exceeded depth bound") + if not node.get_state_set().contains(Atspi.StateType.SHOWING): return + rows.append(node) + for i in range(node.get_child_count()): walk(node.get_child_at_index(i), depth+1) + deadline = time.monotonic() + 5 + while not rows and time.monotonic() < deadline: + while GLib.MainContext.default().pending(): GLib.MainContext.default().iteration(False) + for i in range(desktop.get_child_count()): + application = desktop.get_child_at_index(i) + if application.get_process_id() == pid: walk(application) + if not rows: time.sleep(.05) + if not rows: raise RuntimeError("Synthetic application is absent from AT-SPI") + return rows + + +def accessibility(pid, stage, output): + visible = accessible_nodes(pid) + def find(name): + found = [node for node in visible if node.get_name() == name] + if len(found) != 1: raise RuntimeError(f"Expected one visible accessible {name}, found {len(found)}") + return found[0] + def press(name): + action = find(name).get_action_iface() + for i in range(action.get_n_actions()): + if action.get_action_name(i).lower() == "press": + if not action.do_action(i): raise RuntimeError(f"AT-SPI refused {name}") + return + raise RuntimeError(f"No accessible press action for {name}") + rows = [] + for node in visible: + action = node.get_action_iface() + rows.append({"name": node.get_name(), "role": node.get_role_name(), + "actions": [action.get_action_name(i) for i in range(action.get_n_actions())] if action else []}) + private(output / (stage + ".json"), json.dumps(rows, indent=2)) + if stage == "accessibility-inbox": + find("Mail downloads paused. Saved mail is available.") + press("Resume downloads") + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + from gi.repository import GLib + while GLib.MainContext.default().pending(): GLib.MainContext.default().iteration(False) + if any(node.get_name() == "Pause downloads" for node in visible): break + time.sleep(.05) + press("Pause downloads") + else: + for name, value in (("To", "recipient@example.test"), ("Subject", "Synthetic accessible send"), ("Message body", "Synthetic body")): + editable = find(name).get_editable_text_iface() + if not editable or not editable.set_text_contents(value): raise RuntimeError(f"AT-SPI cannot edit {name}") + find("Attach...") + press("Send") + (output / (stage + ".done")).touch() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--binary", type=Path, default=ROOT / "target/debug/omamail") + parser.add_argument("--driver", type=Path, default=ROOT / "app/build/desktop_acceptance") + parser.add_argument("--messages", type=int, default=1000) + parser.add_argument("--samples", type=int, default=7) + parser.add_argument("--accessibility", action="store_true") + parser.add_argument("--scale", default="1") + parser.add_argument("--html-bytes", type=int, default=256 * 1024) + parser.add_argument("--display-mode", choices=("physical", "xvfb"), default="physical") + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(mode=0o700) + binary = args.binary.resolve() + driver = args.driver.resolve() + source_before = source_hash() + backend_hash = hashlib.sha256(binary.read_bytes()).hexdigest() + driver_hash = hashlib.sha256(driver.read_bytes()).hexdigest() + if args.messages < 50 or args.samples < 3 or args.html_bytes < 0: + parser.error("Use at least 50 messages, 3 samples and nonnegative HTML size") + env = seed(output, binary, args.messages, args.html_bytes) + env["GSETTINGS_BACKEND"] = "memory" + bus = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"], env=env, + stdout=subprocess.PIPE, stderr=(output / "dbus.log").open("w"), text=True) + env["DBUS_SESSION_BUS_ADDRESS"] = bus.stdout.readline().strip() + os.environ["DBUS_SESSION_BUS_ADDRESS"] = env["DBUS_SESSION_BUS_ADDRESS"] + server = None + if args.display_mode == "physical": + instances = json.loads(subprocess.check_output(["hyprctl", "instances", "-j"], text=True)) + if len(instances) != 1: + raise RuntimeError("Expected one available Hyprland session") + env.update(HYPRLAND_INSTANCE_SIGNATURE=instances[0]["instance"], WAYLAND_DISPLAY=instances[0]["wl_socket"], + QT_QPA_PLATFORM="wayland") + else: + server = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1600x24", "-nolisten", "tcp"], + stdout=subprocess.PIPE, stderr=(output / "xvfb.log").open("w"), text=True) + env.update(DISPLAY=":" + server.stdout.readline().strip(), QT_QPA_PLATFORM="xcb") + env.update(QT_SCALE_FACTOR=args.scale, OMAMAIL_DEVELOPMENT_RESOURCES="1", + OMAMAIL_BIN=str(binary), MAGPIE_DESKTOP_OPTIONS=str(output / "options.json"), + QT_ACCESSIBILITY="1", QT_LINUX_ACCESSIBILITY_ALWAYS_ON="1") + env.pop("QT_QUICK_BACKEND", None) + private(output / "options.json", json.dumps({"output": str(output), "samples": args.samples, + "largeIds": [f"synthetic-{args.messages-1-i:08}" for i in range(3)] if args.html_bytes else [], + "accessibility": args.accessibility})) + if args.accessibility: + subprocess.run(["gdbus", "call", "--session", "--dest", "org.a11y.Bus", "--object-path", "/org/a11y/bus", + "--method", "org.freedesktop.DBus.Properties.Set", "org.a11y.Status", "IsEnabled", ""], + check=True, capture_output=True, text=True, env=env) + launched = time.time() * 1000 + process = subprocess.Popen([str(driver), "-input", str(ROOT / "benchmarks/mail/tst_desktop.qml")], + env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + lines = queue.Queue() + + def read(): + for line in process.stdout: + lines.put(line) + lines.put(None) + + threading.Thread(target=read, daemon=True).start() + results = [] + code = None + failure = None + deadline = time.monotonic() + 180 + try: + with (output / "desktop.log").open("w") as log: + while time.monotonic() < deadline: + line = lines.get(timeout=20) + if line is None: + break + log.write(line) + log.flush() + if "DESKTOP_CHECKPOINT accessibility-" in line and args.accessibility: + accessibility(process.pid, line.split("DESKTOP_CHECKPOINT ", 1)[1].strip(), output) + if "DESKTOP_CAPTURE " not in line: + continue + event = json.loads(line.split("DESKTOP_CAPTURE ", 1)[1]) + window = window_for(env, process.pid) if args.display_mode == "physical" else { + "at": [0, 0], "size": [round(1024 * float(args.scale)), round(768 * float(args.scale))]} + if not window: + raise RuntimeError("Synthetic window is not mapped") + expected = event["serial"] % 2 + until = time.monotonic() + 10 + while time.monotonic() < until: + if args.display_mode == "physical": window = window_for(env, process.pid) + x, y = window["at"] + scale = float(args.scale) + region = f"{x + round(12 * scale)},{y + round(12 * scale)} 2x2" + if args.display_mode == "physical": + capture = subprocess.check_output(["grim", "-g", region, "-t", "ppm", "-"], env=env, timeout=5) + pixels = Image.open(io.BytesIO(capture)).convert("RGB") + else: + pixels = ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((round(12*scale), round(12*scale), round(12*scale)+2, round(12*scale)+2)).convert("RGB") + red, green, blue = pixels.getpixel((0, 0)) + if blue > 100 and ((expected and red > green + 80) or (not expected and green > red + 80)): + elapsed = time.time() * 1000 - (launched if event["kind"] == "coldInbox" else event["started"]) + break + else: + private(output / "window.json", json.dumps(window, indent=2)) + x, y = window["at"] + width, height = window["size"] + if args.display_mode == "physical": + subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / "failed-window.png")], env=env, check=True) + else: + ImageGrab.grab(xdisplay=env["DISPLAY"]).save(output / "failed-window.png") + raise RuntimeError(f"Compositor never presented marker {expected}; last pixel {pixels.getpixel((0, 0))}") + results.append(dict(event, presentedMs=round(elapsed, 3))) + if event["kind"] in ("coldInbox", "compose", "composeFocus", "largeHtml", "offlineEdit"): + x, y = window["at"] + width, height = window["size"] + if args.display_mode == "physical": + subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / (event["kind"] + ".png"))], env=env, check=True) + else: + ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((0,0,width,height)).save(output / (event["kind"] + ".png")) + (output / ("capture-" + str(event["serial"]))).touch() + else: + raise RuntimeError("Desktop acceptance timed out") + code = process.wait(timeout=10) + except Exception as error: + failure = str(error) + raise + finally: + if process.poll() is None: + process.terminate() + try: process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + if server is not None: + server.terminate() + server.wait(timeout=10) + bus.terminate() + bus.wait(timeout=10) + groups = {} + for result in results: + groups.setdefault(result["kind"], []).append(result["presentedMs"]) + summary = {kind: {"samplesMs": values, "p95Ms": sorted(values)[math.ceil(.95 * len(values)) - 1]} + for kind, values in groups.items()} + unchanged = (source_before == source_hash() + and backend_hash == hashlib.sha256(binary.read_bytes()).hexdigest() + and driver_hash == hashlib.sha256(driver.read_bytes()).hexdigest()) + if not unchanged: + failure = "Source or binaries changed during measurement" + code = 1 + report = {"source": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), + "sourceSha256": source_before, "driverSha256": driver_hash, + "backendSha256": backend_hash, "messages": args.messages, + "largeHtmlBytes": args.html_bytes, + "backendPath": str(binary), "driverPath": str(driver), + "cpu": next((line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name")), "unknown"), + "qt": next((line for line in (output / "desktop.log").read_text().splitlines() if line.startswith("Config:")), "unknown"), + "viewport": [1024, 768], "osCaches": "warm", "input": "Qt key event delivered to the actual application window", + "themeSha256": {name: hashlib.sha256((Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).read_bytes()).hexdigest() + for name in ("colors.toml", "shell.toml") if (Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).exists()}, + "scale": args.scale, "platform": platform.platform(), "results": summary, "raw": results, + "status": "pass" if code == 0 and failure is None else "fail", "error": failure, + "statusScope": "Functional acceptance only; compare timings with targets separately.", + "displayMode": args.display_mode, + "boundary": "Input/RPC/model/layout to captured pixels. Includes capture overhead. Cold means new app/backend processes; OS caches are warm. Xvfb measures an isolated virtual display, not physical compositor presentation."} + private(output / "results.json", json.dumps(report, indent=2)) + print(json.dumps(summary, indent=2)) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/mail/desktop_main.cpp b/benchmarks/mail/desktop_main.cpp new file mode 100644 index 000000000..3e4731f15 --- /dev/null +++ b/benchmarks/mail/desktop_main.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class DesktopProbe : public QObject { + Q_OBJECT + Q_PROPERTY(QVariantMap options READ options CONSTANT) + Q_PROPERTY(qint64 launchedAt READ launchedAt CONSTANT) +public: + using QObject::QObject; + static inline qint64 launched = QDateTime::currentMSecsSinceEpoch(); + QVariantMap options() const { + QFile file(qEnvironmentVariable("MAGPIE_DESKTOP_OPTIONS")); + if (!file.open(QIODevice::ReadOnly)) qFatal("Missing desktop fixture options"); + return QJsonDocument::fromJson(file.readAll()).object().toVariantMap(); + } + qint64 launchedAt() const { return launched; } + Q_INVOKABLE void capture(const QString &kind, qint64 started, int serial) { + const auto record = QJsonObject{{"kind", kind}, {"started", started}, {"serial", serial}}; + qInfo().noquote() << "DESKTOP_CAPTURE" << QJsonDocument(record).toJson(QJsonDocument::Compact); + } + Q_INVOKABLE bool captured(int serial) { + return QFile::exists(options().value("output").toString() + "/capture-" + QString::number(serial)); + } + Q_INVOKABLE void checkpoint(const QString &name) { + qInfo().noquote() << "DESKTOP_CHECKPOINT" << name; + } + Q_INVOKABLE bool checkpointComplete(const QString &name) { + return QFile::exists(options().value("output").toString() + "/" + name + ".done"); + } + Q_INVOKABLE void press(QObject *window, int key) { + auto *target = qobject_cast(window); + if (!target) qFatal("Desktop key target must be a window"); + QTest::keyClick(target, static_cast(key)); + } +}; + +class DesktopSetup : public QObject { + Q_OBJECT +public slots: + void applicationAvailable() { + QCoreApplication::setApplicationName("Magpie acceptance"); + QQuickStyle::setStyle("Omamail"); + QQuickStyle::setFallbackStyle("Basic"); + qmlRegisterSingletonType("Magpie.Acceptance", 1, 0, "Probe", + [](QQmlEngine *, QJSEngine *) -> QObject * { return new DesktopProbe; }); + } + void qmlEngineAvailable(QQmlEngine *engine) { + engine->addImportPath(QStringLiteral(OMAMAIL_SOURCE_ROOT) + "/app/qml/imports"); + engine->addImportPath(QStringLiteral(OMAMAIL_SOURCE_ROOT) + "/app/qml/styles"); + } +}; + +QUICK_TEST_MAIN_WITH_SETUP(desktop_acceptance, DesktopSetup) +#include "desktop_main.moc" diff --git a/benchmarks/mail/tst_desktop.qml b/benchmarks/mail/tst_desktop.qml new file mode 100644 index 000000000..b37f505de --- /dev/null +++ b/benchmarks/mail/tst_desktop.qml @@ -0,0 +1,146 @@ +import QtQuick +import QtTest +import Magpie.Acceptance +import "../../app/qml" as Standalone + +Item { + width: 1; height: 1 + Standalone.Main { + id: desktop + title: "Magpie synthetic acceptance" + x: 0; y: 0 + property int marker: 0 + Rectangle { + x: 8; y: 8; width: 16; height: 16; z: 10000 + color: desktop.marker % 2 ? "#ff00ff" : "#00ffff" + } + TestCase { + name: "DesktopAcceptance" + when: desktop.visible + SignalSpy { id: sendClicks; signalName: "clicked" } + function capture(kind, started) { + desktop.marker++ + Probe.capture(kind, started, desktop.marker) + tryVerify(function() { return Probe.captured(desktop.marker) }, 15000) + } + function find(item, name) { + if (!item) return null + if (item.objectName === name) return item + var children = item.children || [] + for (var i = 0; i < children.length; i++) { + var found = find(children[i], name) + if (found) return found + } + return null + } + function row(id) { + var rows = desktop.service.messages + for (var i = 0; i < rows.length; i++) if (rows[i].id === id) return rows[i] + return null + } + function undoLatest() { + desktop.service.localMailbox.refreshEdits() + var ticket = "" + tryVerify(function() { + var edits = desktop.service.localMailbox.edits + for (var i = edits.length - 1; i >= 0; i--) { + if (edits[i].state === "queued") { ticket = edits[i].ticket; return true } + } + return false + }, 5000) + desktop.service.localMailbox.undo(ticket) + } + function test_offline_desktop() { + tryCompare(desktop.service.backend, "ready", true, 15000) + tryVerify(function() { return desktop.service.messages.length > 0 }, 15000) + tryCompare(desktop.service, "listLoading", false, 15000) + compare(desktop.service.backend.apiVersion, 8) + capture("coldInbox", Probe.launchedAt) + verify(desktop.service.localMailbox.hasMail) + Probe.checkpoint("cached-inbox-visible-without-credentials") + if (Probe.options.accessibility) { + Probe.checkpoint("accessibility-inbox") + tryVerify(function() { return Probe.checkpointComplete("accessibility-inbox") }, 15000) + tryCompare(desktop.service.localMailbox.status, "paused", true) + } + var samples = Number(Probe.options.samples || 7) + desktop.app.openMessage(desktop.service.messages[20].id) + tryVerify(function() { return !!desktop.service.selectedBody.text && !desktop.service.detailLoading }, 10000) + for (var i = 0; i < samples; i++) { + var previous = desktop.app.cursorId + var started = Date.now() + Probe.press(desktop, i % 2 === 0 ? Qt.Key_J : Qt.Key_K) + verify(desktop.app.cursorId !== previous) + capture("input", started) + } + for (var j = 0; j < samples; j++) { + var oldId = desktop.app.cursorId + var navigationStarted = Date.now() + Probe.press(desktop, j % 2 === 0 ? Qt.Key_K : Qt.Key_J) + verify(desktop.app.cursorId !== oldId) + tryVerify(function() { return !!desktop.service.selectedBody.text && !desktop.service.detailLoading }, 10000) + capture("navigation", navigationStarted) + } + desktop.app.backToList() + for (var n = 0; n < samples; n++) { + var began = Date.now() + desktop.service.search(n % 2 === 0 ? "needle" : "ordinary") + tryVerify(function() { return !desktop.service.listLoading && desktop.service.messages.length > 0 }, 10000) + capture("search", began) + } + desktop.service.search("") + tryVerify(function() { return !desktop.service.listLoading && desktop.service.messages.length > 0 }, 10000) + var large = Probe.options.largeIds || [] + for (var h = 0; h < large.length; h++) { + var htmlStarted = Date.now() + desktop.app.openMessage(large[h]) + tryVerify(function() { return desktop.service.selectedHasHtml && desktop.service.detailPainted && !desktop.service.detailLoading }, 15000) + capture("largeHtml", htmlStarted) + } + desktop.app.backToList() + var editedId = desktop.service.messages[25].id + desktop.service.toggleStar(editedId) + tryVerify(function() { return row(editedId) && row(editedId).starred === true }, 5000) + capture("offlineEdit", Date.now()) + undoLatest() + tryVerify(function() { return row(editedId) && row(editedId).starred === false }, 5000) + verify(desktop.service.act(editedId, "archive")) + tryVerify(function() { return row(editedId) === null }, 5000) + undoLatest() + tryVerify(function() { return row(editedId) !== null }, 5000) + Probe.checkpoint("offline-star-and-archive-visible-and-undo-restores-mail") + desktop.app.startCompose("new") + tryCompare(desktop.app, "composing", true) + capture("compose", Date.now()) + var send = find(desktop.app, "compose-send-button") + verify(send !== null) + send.forceActiveFocus() + verify(send.activeFocus) + capture("composeFocus", Date.now()) + if (Probe.options.accessibility) { + Probe.checkpoint("accessibility-compose") + tryVerify(function() { return Probe.checkpointComplete("accessibility-compose") }, 15000) + tryCompare(desktop.app, "composing", false, 10000) + tryCompare(desktop.service, "sendPending", true, 10000) + Probe.checkpoint("accessible-send-durably-queued-without-credentials") + } else { + find(desktop.app, "compose-to-field").text = "recipient@example.test" + find(desktop.app, "compose-subject-field").text = "Synthetic keyboard send" + find(desktop.app, "compose-body-editor").text = "Synthetic body" + wait(50) + send.forceActiveFocus() + verify(send.activeFocus) + sendClicks.target = send + sendClicks.clear() + Probe.press(desktop, Qt.Key_Space) + compare(sendClicks.count, 1) + tryCompare(desktop.app, "composing", false, 10000) + tryCompare(desktop.service, "sendPending", true, 10000) + Probe.checkpoint("keyboard-send-durably-queued-without-credentials") + } + desktop.service.backend.shutdown(function() {}) + } + } + } + +} diff --git a/docs/PERFORMANCE-VALIDATION.md b/docs/PERFORMANCE-VALIDATION.md index 9a9a0e383..f77d44736 100644 --- a/docs/PERFORMANCE-VALIDATION.md +++ b/docs/PERFORMANCE-VALIDATION.md @@ -22,25 +22,17 @@ The independent `shell-independent` gate runs the 35 shell/Python files that nee On 2026-10-21, the installed interface was found to call `local.edit`, `local.watch` and `calendar.read` against a backend that advertised API 8 but did not implement those methods. Isolated probes reproduced the `Invalid params` response. The UI now verifies the unreleased contract hash, retains the released API for an older development build, and refuses unsupported methods before dispatch. Regression tests cover the real production delete adapter, queued and oversized requests, Qt handshake behavior, and native bundle readiness. RPC diagnostics now retain bounded timestamps and allowlisted failure reasons; the diagnostic export preserves those facts while stripping private text. Installation and release remain separate acceptance steps. -The 2026-10-21 native build and all seven CTest groups passed in an isolated offscreen environment, including the standalone composition and backend resource checks. Those groups do not require the provider suite's TCP/DBus fixtures, so their automation gates now run independently; QML lint is also an independent gate. The corresponding CI-profile run has ten passing gates and five blocked gates. The final full Rust run remains 477 passed, 195 failed and 14 ignored under the restricted runtime, with exactly the same failed-test names as the previous run; this is not a passing `make validate` result. Physical desktop, provider integration and published-release verification remain outstanding. +The authorized 2026-10-21 run passed all 22 desktop-profile gates, including complete `make validate`, the Quickshell process bridge, native PDF isolation, provider recovery and the real API contract. Subsequent acceptance added a retained-attachment RPC gate and the standalone host-contract fixture to CTest. Rerun the complete profile after the final source changes; a passing earlier snapshot is not final-source certification. Current evidence and remaining gates are published in Peacock P-002, with the implementation in [draft PR #17](https://github.com/WebscapeOrg/magpie/pull/17). -Focused compatibility checks pass: 38 runtime tests, 17 diagnostic/privacy tests, 5 automation tests, the production Gmail adapter JavaScript tests, and Qt backend/runtime/Gmail-queue groups with 25/18/8 passes. The production error-notice block was rendered in 56 synthetic before/after states covering seven failure categories at wide, narrow and enlarged text sizes, plus standalone without the AI diagnostics button. All tested text fits; an initial height-binding warning also occurs with the old message. These captures do not certify desktop themes or screen-reader behavior. The installed plugin/backend pair remains unchanged by this fix. +The checksum-verified upstream 0.11.0 executable passed the released contract locally: 37 behavioral methods, 181 advertised methods, API 7. Hosted released-binary gates cover both Linux architectures. Keep the installer source (`huacnlee/omamail`) distinct from this development fork. The installed executable was not changed and is not evidence for published-release compatibility. -A further 2026-10-21 interaction run reproduced and fixed that height-binding cycle by leaving the notice text's height intrinsic. A regression fails on the original warning and passes after the change; all 28 updated notice captures are pixel-identical to the previous layouts. Keyboard tests also showed that mailbox shortcuts intercepted focused buttons. Shared icon, text and panel action buttons now reserve unmodified Return, keypad Enter and Space, while modified shortcuts and Escape keep their normal routing. Focus shows the tooltip label; text and panel action buttons expose accessible names and press actions. The full application fixture has 33 passes, and the keyboard-router fixture has 32, covering three control types and proving that activation does not open or select an underlying message. +Controlled provider fixtures now exercise cached mail after authentication failure, interrupted inventory/history/body work, expired history, coalesced offline edits, reconnect reconciliation and a server-deletion conflict. A private 64 MiB filesystem exercises genuine low-space refusal without filling the host disk. The send recorder verifies exactly one resumed delivery, no automatic retry after an ambiguous send, and zero requests after cancellation during preflight. The retained-attachment RPC fixture restarts the backend, removes the original attachment file, refuses foreign-account/draft reuse without queuing mail, verifies the owning draft's MIME bytes and cancels its delayed send. -The independent component run passes all 111 selected files with 1,078 test cases plus 222 setup/cleanup pass records; 11 files still require the native bridge. Four stale fixtures were updated to exercise the current native attachment path, complete runtime metadata and visible-row inbox admission; account isolation, cancellation and refusal checks remain. That interaction-stage automation recorded 11 passing gates and 5 blocked gates. The latest full `make validate` still fails with 477 passes, the same 195 failures and 14 ignored tests. Failure-stage triage identifies denied OS operations, remapped private-path ownership, unavailable TLS fixtures and the PDF worker's denied socket setup; it does not establish that integration behavior is correct. Complete integration, release and desktop acceptance remain open. +Calendar component acceptance switches months and accounts while requests are pending, rejects stale replies and stale events after a newer empty range, and checks cached range reuse by reminders. Existing native and JavaScript suites cover provider parsing, recurrence and DST. These synthetic results do not certify every real mailbox or calendar server. -The subsequent shell audit ran all 38 portable test files separately in isolated state: 35 passed, and three failed when their socket/DBus fixtures were refused. The new combined independent target also passes all 35 files plus the seven HTTP policy cases. This combined run exposed a fixture isolation error: the default standalone-target test inherited the runner's explicit backend-path override. Its nested Make invocations now clear inherited Make flags and standalone path overrides while retaining the original default-path assertions. Those assertions pass both normally and with synthetic inherited overrides. All original shell commands remain in the full portable target; neither a partial hostile-input run nor the independent target establishes the real network boundary tests. The final CI-profile rerun has 12 passing gates, no failed runnable gates and 5 blocked gates; full validation and desktop acceptance remain incomplete. +The standalone desktop driver operates the real native host and backend against isolated synthetic mail. It checks saved lists/bodies, star/archive and Undo, and durable queued Send by keyboard. AT-SPI operation exposed missing send/attachment semantics and unnamed compose fields; those controls now expose names, roles, focus and press actions. The same driver exercises Pause/Resume and compose/Send through AT-SPI. Accessible API operation and virtual-display screenshots remain distinct from a human screen-reader or physical-compositor assessment. -The `desktop` profile runs `make validate` from a repository checkout with local TCP/Unix sockets, DBus and ordinary filesystem ownership available. In the restricted implementation environment, the initial implementation run had 471 Rust passes, 196 failures and 14 ignored tests. Failures included denied local server/IPC/DBus setup and private-directory ownership checks. The pre-existing subprocess cancellation failure was subsequently reproduced: the child was terminated but remained a zombie because its exit status was not collected promptly. The async transport now retains an explicit child reaper on cancellation; all 19 focused subprocess tests pass, including a control-backed regression that asserts a cancelled descendant cannot write a file. The source, JavaScript, QML lint, diagnostic privacy and focused UI gates passed independently. A failed full gate remains a failed gate. - -The follow-up isolated `make validate` run on 2026-10-20 recorded 477 Rust passes, 195 failures and 14 ignored tests, then stopped at the Rust gate. Its failed-test names are exactly the earlier set minus the corrected cancellation case; no new failed test appeared. This is still a failed full gate, and later Makefile targets were not reached by that invocation. - -Four additional storage recovery tests exercise the production inventory/history transaction functions and the rooted SQLite store. Child processes exit without destructors after an inventory page and a history page; reopening retains the checkpoints, pending downloads and edit intents. Unvisited mail is removed only after reconciliation, pending bodies prevent complete coverage, and a deleted message turns its queued edit into a conflict. The other cases verify atomic rollback for malformed/cyclic inventory pages, preservation through expired history, and availability of saved bodies/counts/Undo while a sync authentication error is recorded. These tests pass alongside the nine existing local-store correctness tests. They establish durable storage behavior; the provider transport, credential lifecycle and full UI flows below still require integration evidence. - -Run the native QML security tests, including the message renderer and attachment preview workers, through the Makefile targets. Do not skip them merely because the focused component tests pass. New local-store tests cover WAL recovery, link refusal, paging, edit coalescing, history rollback and IPC dispatch isolation. The authenticated owner socket test and actual provider recovery flows still need their unrestricted runtime. - -Run `python3 tests/test_backend_api.py --binary target/debug/omamail` after a fresh build. The ten new validation/parser cases can run without storage; the complete contract requires the private filesystem fixtures. Also run the Published backend gate with the checksum-verified executable from the exact `backend-version` release. The already installed executable reported API 8 while the repository's released contract declares API 7, so it is not valid evidence for this gate. Keep the release download separate from the installed executable; follow [BACKEND-RUNTIME.md](BACKEND-RUNTIME.md). No installation or pin change was made by the performance implementation. +The physical session was locked during the attempted presentation check. T-002 requests only an unlocked session; C-001 retains all test execution. Do not bypass the lock screen, replace physical evidence with virtual evidence, or declare acceptance complete while a required scenario is missing. Historical restricted runs and their failures remain in P-002's archived evidence; they no longer describe the authorized local run. ## Desktop and recovery checks diff --git a/scripts/verify-performance.py b/scripts/verify-performance.py index 992debc86..7cadae03c 100644 --- a/scripts/verify-performance.py +++ b/scripts/verify-performance.py @@ -41,7 +41,7 @@ def thumbnail_sandbox(): result = subprocess.run([ "/usr/bin/bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", "--clearenv", "--ro-bind", "/usr", "/usr", - "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib", "/lib64", + "--ro-bind", "/lib", "/lib", "--ro-bind-try", "/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--chdir", "/tmp", "/usr/bin/true"], capture_output=True, text=True, timeout=10) if result.returncode: @@ -120,6 +120,7 @@ def stages(profile, output, baseline): gate("offline-recovery", ["cargo", "test", "--locked", "--lib", "local_mail::recovery_tests"], ["cargo"]), gate("provider-recovery", ["cargo", "test", "--locked", "--lib", "local_mail::provider_tests"], ["cargo"] + runtime), gate("send-recovery", ["cargo", "test", "--locked", "--lib", "outbox::tests::recorder_confirms"], ["cargo"] + runtime), + gate("retained-attachments", isolated + [sys.executable, "tests/test_attachment_handles_rpc.py"], runtime), gate("low-space", [sys.executable, "scripts/test-low-space.py"], ["cargo", "pdf-sandbox"] + runtime), gate("subprocess", ["cargo", "test", "--locked", "--lib", "process::"], ["cargo"]), gate("rust", isolated + make + ["test-rust"], ["cargo", "pdf-sandbox"] + runtime), diff --git a/src/attachment/thumbnail.rs b/src/attachment/thumbnail.rs index 6a9257f9e..bffee6e96 100644 --- a/src/attachment/thumbnail.rs +++ b/src/attachment/thumbnail.rs @@ -59,11 +59,11 @@ fn sandbox(program: &str, arguments: &[&str]) -> tokio::process::Command { "--ro-bind", "/usr", "/usr", - "--symlink", - "usr/lib", + "--ro-bind", + "/lib", "/lib", - "--symlink", - "usr/lib", + "--ro-bind-try", + "/lib64", "/lib64", "--proc", "/proc", diff --git a/tests/test_agent_bridge.py b/tests/test_agent_bridge.py index 817459786..a0b722cc7 100644 --- a/tests/test_agent_bridge.py +++ b/tests/test_agent_bridge.py @@ -79,7 +79,10 @@ def wait(self,ident,states=('done','failed','cancelled')): def cleanup(self): for ident in self.ids: subprocess.run(['python3',str(SCRIPT),'cancel',ident],env=self.env,capture_output=True) - time.sleep(.3) + for ident in self.ids: + path = self.store/ident/'job.json' + if path.exists() and json.loads(path.read_text()).get('state') in ('queued', 'running'): + self.wait(ident) self.assertFalse((self.root/'TERMINAL').exists()) def test_background_stdin_result_and_resume(self): diff --git a/tests/test_attachment_handles_rpc.py b/tests/test_attachment_handles_rpc.py new file mode 100644 index 000000000..d7728737e --- /dev/null +++ b/tests/test_attachment_handles_rpc.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Retained-file ownership through real backend processes and durable outbox state.""" +import base64 +import email +import json +import os +from pathlib import Path +import queue +import subprocess +import tempfile +import threading + +ROOT = Path(__file__).resolve().parents[1] +OWNER = "owner@example.test" +FOREIGN = "foreign@example.test" + + +class Backend: + def __init__(self, env): + self.process = subprocess.Popen([str(ROOT / "target/debug/omamail"), "serve"], env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True) + self.replies = queue.Queue() + self.serial = 0 + def read(): + for line in self.process.stdout: + self.replies.put(json.loads(line)) + threading.Thread(target=read, daemon=True).start() + + def call(self, method, params, error=None): + self.serial += 1 + self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self.serial, + "method": method, "params": params}) + "\n") + self.process.stdin.flush() + while True: + reply = self.replies.get(timeout=15) + if reply.get("id") == self.serial: break + if error: + assert reply.get("error", {}).get("message") == error, reply + return reply + assert "error" not in reply, reply + return reply["result"] + + def close(self): + if self.process.poll() is not None: return + self.process.stdin.close() + try: self.process.wait(timeout=15) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + raise + + +def main(): + with tempfile.TemporaryDirectory(prefix="magpie-retained-rpc-") as name: + root = Path(name) + env = dict(os.environ) + for key in ("HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"): + path = root / key.lower() + path.mkdir(mode=0o700) + env[key] = str(path) + config = Path(env["XDG_CONFIG_HOME"]) / "omamail" + config.mkdir(mode=0o700) + registry = config / "accounts.json" + registry.write_text(json.dumps({"version": 1, "activeId": OWNER, + "accounts": [{"email": account, "provider": "gmail"} for account in (OWNER, FOREIGN)]})) + registry.chmod(0o600) + original = root / "retained.txt" + sentinel = b"synthetic retained attachment bytes" + original.write_bytes(sentinel) + backend = Backend(env) + try: + retained = backend.call("attachment.import", {"accountId": OWNER, "draftKey": "draft-a", "path": str(original)}) + assert "handle" in retained and "data" not in retained + finally: + backend.close() + original.unlink() + backend = Backend(env) + try: + def compose(account, draft, identity, error=None): + return backend.call("outbox.compose", {"accountId": account, "provider": "gmail", "sendId": identity, + "order": 1, "delaySeconds": 60, "resumeUnsent": True, "fields": { + "from": account, "to": "recipient@example.test", "subject": "Synthetic restored draft", + "body": "Synthetic body", "draftKey": draft, "attachments": [retained]}}, error) + for account, draft, identity in ((FOREIGN, "draft-a", "foreign-account"), (OWNER, "draft-b", "foreign-draft")): + refused = compose(account, draft, identity, "attachment_handle_unavailable") + assert sentinel.decode() not in json.dumps(refused) + snapshot = backend.call("outbox.snapshot", {"accountId": account}) + assert snapshot["entries"] == [], "foreign handles must not reach the outbox" + accepted = compose(OWNER, "draft-a", "restored-owner") + snapshot = backend.call("outbox.snapshot", {"accountId": OWNER, "sendId": accepted["id"], "includePayloads": True}) + entries = snapshot["entries"] + assert len(entries) == 1 and entries[0]["state"] in ("waiting", "queued") + raw = entries[0]["payload"]["raw"] + message = email.message_from_bytes(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + assert [part.get_payload(decode=True) for part in message.walk() if part.get_filename()] == [sentinel] + backend.call("outbox.undo", {"accountId": OWNER, "sendId": accepted["id"]}) + cancelled = backend.call("outbox.snapshot", {"accountId": OWNER}) + assert cancelled["entries"][0]["state"] == "cancelled" + finally: + backend.close() + print("PASS: restored handle survives process restart and source removal; foreign account/draft enqueue nothing; owner MIME retains exact bytes; synthetic send cancelled before dispatch") + + +if __name__ == "__main__": + main() diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index ea6d4be17..effb99636 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -1354,6 +1354,7 @@ DropArea { Widgets.TextField { id: toField objectName: "compose-to-field" + Accessible.name: "To" TextMenuTrigger {} onTextEdited: root.noteUserModified() anchors.left: toLabel.right @@ -1440,6 +1441,7 @@ DropArea { Widgets.TextField { id: ccField objectName: "compose-cc-field" + Accessible.name: "Cc" TextMenuTrigger {} onTextEdited: root.noteUserModified() anchors.left: ccLabel.right @@ -1520,6 +1522,7 @@ DropArea { Widgets.TextField { id: bccField objectName: "compose-bcc-field" + Accessible.name: "Bcc" TextMenuTrigger {} onTextEdited: root.noteUserModified() anchors.left: bccLabel.right @@ -1600,6 +1603,7 @@ DropArea { Widgets.TextField { id: replyToField objectName: "compose-reply-to-field" + Accessible.name: "Reply-To" TextMenuTrigger {} onTextEdited: root.noteUserModified() anchors.left: replyToLabel.right @@ -1645,6 +1649,7 @@ DropArea { Widgets.TextField { id: subjectField objectName: "compose-subject-field" + Accessible.name: "Subject" TextMenuTrigger {} onTextEdited: root.noteUserModified() anchors.left: subjectLabel.right @@ -1894,6 +1899,7 @@ DropArea { TextEdit { id: bodyEdit objectName: "compose-body-editor" + Accessible.name: "Message body" TextMenuTrigger {} activeFocusOnTab: true width: bodyFlick.width @@ -2054,6 +2060,7 @@ DropArea { IconTextButton { iconName: "send" + objectName: "compose-send-button" tooltipText: "Send · ctrl+enter" // A send in flight or parked is no reason to hold the next: each is // parked in its account's line and goes in turn. diff --git a/ui/components/IconTextButton.qml b/ui/components/IconTextButton.qml index 38c33e3ce..be1b6a483 100644 --- a/ui/components/IconTextButton.qml +++ b/ui/components/IconTextButton.qml @@ -43,7 +43,25 @@ Rectangle { signal clicked() - readonly property bool hot: mouse.containsMouse && enabled + activeFocusOnTab: true + Accessible.role: Accessible.Button + Accessible.name: text || tooltipText + Accessible.onPressAction: if (root.enabled) root.clicked() + function acceptsActivation(event) { + return root.enabled && root.activeFocus + && (event.modifiers & ~Qt.KeypadModifier) === Qt.NoModifier + && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) + } + Keys.onShortcutOverride: function(event) { + if (root.acceptsActivation(event)) event.accepted = true + } + Keys.onPressed: function(event) { + if (!root.acceptsActivation(event)) return + event.accepted = true + root.clicked() + } + + readonly property bool hot: (mouse.containsMouse || activeFocus) && enabled implicitWidth: row.implicitWidth + Style.spacing.controlPaddingX * 2 implicitHeight: ghost @@ -52,6 +70,7 @@ Rectangle { radius: Style.cornerRadius opacity: enabled ? 1.0 : 0.4 color: mouse.pressed ? Style.pressedFillFor(root.foreground, root.accent) + : root.activeFocus ? Style.focusFillFor(root.foreground, root.accent) : (root.selected ? Style.selectedFillFor(root.foreground, root.accent) : (hot ? Style.hoverFillFor(root.foreground, root.accent) : (bordered && !ghost && !outline @@ -95,7 +114,7 @@ Rectangle { } Widgets.PanelToolTip { - visible: root.tooltipText !== "" && mouse.containsMouse + visible: root.tooltipText !== "" && (mouse.containsMouse || root.activeFocus) text: root.tooltipText fontFamily: root.fontFamily } diff --git a/ui/components/LocalMailStatus.qml b/ui/components/LocalMailStatus.qml index 7d3243b76..dc84e974a 100644 --- a/ui/components/LocalMailStatus.qml +++ b/ui/components/LocalMailStatus.qml @@ -16,6 +16,8 @@ Column { spacing: MailStyle.space(4) Text { + Accessible.role: Accessible.StaticText + Accessible.name: text width: parent.width textFormat: Text.PlainText color: root.textColor @@ -47,6 +49,8 @@ Column { } } Text { + Accessible.role: Accessible.StaticText + Accessible.name: text width: parent.width visible: !!root.mailbox && !root.status.complete textFormat: Text.PlainText diff --git a/ui/tests/qml/tst_calendar_pending_ranges.qml b/ui/tests/qml/tst_calendar_pending_ranges.qml new file mode 100644 index 000000000..a7a3defc0 --- /dev/null +++ b/ui/tests/qml/tst_calendar_pending_ranges.qml @@ -0,0 +1,93 @@ +import QtQuick +import QtTest +import "../../calendar" as Calendar +import "../../calendar/Cache.js" as Cache + +Item { + width: 800; height: 600 + QtObject { + id: backend + property bool ready: false + property int apiVersion: 8 + property var pending: [] + function call(method, params, callback) { + if (method === "calendar.read") pending.push({params: params, callback: callback}) + } + } + Calendar.CalendarCache { id: shared; loaded: true } + QtObject { + id: service + property var backend: backend + property var calendarCache: shared + property bool backendCanDiscoverCalendars: true + property bool backendCanGoogleCalendars: true + property bool unifiedCalendarView: false + property var accountSummaries: [ + {id: "one@example.test", email: "one@example.test", provider: "gmail", signedIn: true}, + {id: "two@example.test", email: "two@example.test", provider: "gmail", signedIn: true} + ] + } + Calendar.CalendarController { + id: controller + service: service + pluginDir: "/tmp/magpie-calendar-acceptance" + accountId: "one@example.test" + } + TestCase { + name: "CalendarPendingRanges" + when: windowShown + function init() { + controller.rangeStart = 0 + controller.rangeEnd = 0 + controller.accountId = "one@example.test" + shared.store = Cache.emptyStore() + shared.loaded = true + backend.pending = [] + } + function reply(index, title) { + var request = backend.pending[index] + var start = Date.parse(request.params.start) + 100 + var values = title === "" ? [] : [{uid: title, title: title, + sourceId: request.params.source.id, start: {ms: start}, end: {ms: start + 100}}] + request.callback({events: values}, null) + } + function test_old_month_and_account_replies_cannot_replace_the_visible_range() { + controller.refresh(1000, 2000) + compare(backend.pending.length, 1) + controller.refresh(3000, 4000) + compare(backend.pending.length, 2) + reply(1, "current-month") + reply(0, "old-month") + compare(controller.rangeStart, 3000) + compare(controller.events.length, 1) + compare(controller.events[0].title, "current-month") + compare(shared.get("sources", 3000, 4000, ["google:one@example.test"])[0].title, "current-month") + controller.refresh(3000, 4000) + var oldAccount = backend.pending.length - 1 + controller.accountId = "two@example.test" + var newAccount = backend.pending.length - 1 + verify(newAccount > oldAccount) + reply(newAccount, "other-account") + reply(oldAccount, "late-original-account") + compare(controller.accountId, "two@example.test") + compare(controller.events.length, 1) + compare(controller.events[0].title, "other-account") + } + function test_new_empty_range_wins_and_warm_reads_reuse_shared_cache() { + controller.refresh(1000, 2000) + controller.refresh(1000, 2000) + compare(backend.pending.length, 2) + reply(1, "") + reply(0, "deleted-event") + compare(controller.events.length, 0) + compare(shared.get("sources", 1000, 2000, ["google:one@example.test"]).length, 0) + verify(shared.knows("sources", 1000, 2000, "google:one@example.test")) + controller.warmRange(1000, 2000, function() { return true }) + wait(20) + compare(backend.pending.length, 2) + controller.reminderMode = true + compare(controller.cachedEventsFor(controller.calendarScope, 1000, 2000).length, 0) + controller.reminderMode = false + } + } +} diff --git a/ui/tests/qml/tst_keyrouter.qml b/ui/tests/qml/tst_keyrouter.qml index b777be63b..7080b00b3 100644 --- a/ui/tests/qml/tst_keyrouter.qml +++ b/ui/tests/qml/tst_keyrouter.qml @@ -30,6 +30,7 @@ Item { readonly property Item focusItem: host.Window.activeFocusItem Omamail.IconButton { id: iconButton; tooltipText: "Test action" } + Omamail.IconTextButton { id: iconTextButton; text: "Test action" } Widgets.Button { id: textButton; text: "Test action"; focusable: true } Widgets.PanelActionButton { id: panelButton; tooltipText: "Test action"; focusable: true } SignalSpy { id: buttonClicks; signalName: "clicked" } @@ -78,7 +79,7 @@ Item { function test_focused_buttons_activate_before_mailbox_shortcuts_data() { return [{tag: "icon", button: iconButton}, {tag: "text", button: textButton}, - {tag: "panel", button: panelButton}] + {tag: "panel", button: panelButton}, {tag: "icon-text", button: iconTextButton}] } function test_focused_buttons_activate_before_mailbox_shortcuts(data) { From d3fd594c97476bba02c05f73dc0646ecdd8b6ad0 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:49:08 +0100 Subject: [PATCH 006/568] Fix notices covering compose actions --- ui/App.qml | 1 + ui/components/ComposeView.qml | 1 + ui/tests/qml/tst_app_navigation.qml | 16 ++++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/ui/App.qml b/ui/App.qml index 697768f9c..01256459f 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2394,6 +2394,7 @@ Item { id: statusBar objectName: "mail-notice" anchors.bottom: parent.bottom + anchors.bottomMargin: compose.visible ? compose.actionBarHeight + MailStyle.space(8) : 0 anchors.horizontalCenter: parent.horizontalCenter width: Math.min(parent.width - MailStyle.space(28), MailStyle.space(720)) height: visible ? noticeText.implicitHeight + MailStyle.space(16) : 0 diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index effb99636..4f9ac61af 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -37,6 +37,7 @@ DropArea { readonly property int formInset: MailStyle.space(18) readonly property int formLabelWidth: MailStyle.space(52) readonly property int formLabelGap: MailStyle.space(10) + readonly property real actionBarHeight: actions.height property bool opened: false property bool userModified: false diff --git a/ui/tests/qml/tst_app_navigation.qml b/ui/tests/qml/tst_app_navigation.qml index 3c452ee3d..4ee4872ce 100644 --- a/ui/tests/qml/tst_app_navigation.qml +++ b/ui/tests/qml/tst_app_navigation.qml @@ -557,6 +557,22 @@ Item { } } + function test_compose_notices_leave_send_visible() { + app.startCompose("new") + var send = named(app, "compose-send-button") + var banner = named(app, "mail-notice") + app.notice = "Archived" + tryVerify(function() { return send.visible && banner.visible }) + waitForRendering(banner) + var noticeBottom = banner.mapToItem(send, 0, banner.height).y + verify(noticeBottom <= 0, "Notices must remain above the compose actions") + send.forceActiveFocus() + verify(send.activeFocus) + app.notice = "" + app.back() + tryCompare(app, "composing", false) + } + function test_header_shows_compose_for_mail_and_view_selector_for_calendar() { var compose = named(app, "compose-button") verify(compose && compose.visible) From 5b5bb57638c6ae8c742bb7752c61b5f553d7d149 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:07:39 +0100 Subject: [PATCH 007/568] chore: Isolate Windows contract storage and require bounded tmpfs support --- .github/workflows/ci.yml | 4 +- .../workflows/performance-verification.yml | 2 +- .github/workflows/release.yml | 4 +- docs/PERFORMANCE-VALIDATION.md | 4 +- scripts/test-low-space.py | 3 + tests/test_backend_api.py | 89 ++++++++++++++++--- tests/test_backend_release.py | 17 ++++ 7 files changed, 107 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73d635449..19e92fa12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -187,7 +187,7 @@ jobs: $qmlStatus = $LASTEXITCODE Get-Content qml-host-contract.txt if ($qmlStatus -ne 0) { throw "QML tests failed ($qmlStatus)" } - python tests/test_backend_api.py --binary target/release/omamail.exe --expected-version $version --standalone + python tests/test_backend_api.py --binary target/release/omamail.exe --expected-version $version --standalone --isolated-windows-runner if ($LASTEXITCODE -ne 0) { throw "backend API contract failed" } - name: Build and exercise the production archive shell: pwsh @@ -208,7 +208,7 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "resource check failed" } & $appExecutable --smoke-test (Join-Path $env:RUNNER_TEMP "omamail-ready.json") if ($LASTEXITCODE -ne 0) { throw "live smoke failed" } - python tests/test_backend_api.py --binary $backend --expected-version $version --standalone + python tests/test_backend_api.py --binary $backend --expected-version $version --standalone --isolated-windows-runner if ($LASTEXITCODE -ne 0) { throw "packaged backend API contract failed" } portable-tests: diff --git a/.github/workflows/performance-verification.yml b/.github/workflows/performance-verification.yml index 875835cbe..5fd79ab32 100644 --- a/.github/workflows/performance-verification.yml +++ b/.github/workflows/performance-verification.yml @@ -25,7 +25,7 @@ concurrency: jobs: verify: name: Synthetic verification (${{ matrix.profile }}) - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 timeout-minutes: 90 strategy: fail-fast: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fdd5d30d2..9f2c1fce4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -309,7 +309,7 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "QML inventory failed" } qmltestrunner -input app/tests/qml/tst_host_contract.qml -import app/qml/imports -import app/qml/styles -import ui if ($LASTEXITCODE -ne 0) { throw "QML tests failed" } - python tests/test_backend_api.py --binary target/release/omamail.exe --expected-version "${{ needs.prepare.outputs.version }}" --standalone + python tests/test_backend_api.py --binary target/release/omamail.exe --expected-version "${{ needs.prepare.outputs.version }}" --standalone --isolated-windows-runner if ($LASTEXITCODE -ne 0) { throw "backend API contract failed" } - name: Package, unpack, and test the Windows archive and installer shell: pwsh @@ -337,7 +337,7 @@ jobs: if ([string]$readyValue.version -ne "${{ needs.prepare.outputs.version }}" -or -not $apiIsInteger) { throw "live smoke returned invalid readiness metadata" } $reported = & $backend --version if ($LASTEXITCODE -ne 0 -or $reported -ne "omamail ${{ needs.prepare.outputs.version }}") { throw "backend version mismatch" } - python tests/test_backend_api.py --binary $backend --expected-version "${{ needs.prepare.outputs.version }}" --standalone + python tests/test_backend_api.py --binary $backend --expected-version "${{ needs.prepare.outputs.version }}" --standalone --isolated-windows-runner if ($LASTEXITCODE -ne 0) { throw "packaged backend API contract failed" } - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: diff --git a/docs/PERFORMANCE-VALIDATION.md b/docs/PERFORMANCE-VALIDATION.md index f77d44736..429d91ec3 100644 --- a/docs/PERFORMANCE-VALIDATION.md +++ b/docs/PERFORMANCE-VALIDATION.md @@ -26,7 +26,9 @@ The authorized 2026-10-21 run passed all 22 desktop-profile gates, including com The checksum-verified upstream 0.11.0 executable passed the released contract locally: 37 behavioral methods, 181 advertised methods, API 7. Hosted released-binary gates cover both Linux architectures. Keep the installer source (`huacnlee/omamail`) distinct from this development fork. The installed executable was not changed and is not evidence for published-release compatibility. -Controlled provider fixtures now exercise cached mail after authentication failure, interrupted inventory/history/body work, expired history, coalesced offline edits, reconnect reconciliation and a server-deletion conflict. A private 64 MiB filesystem exercises genuine low-space refusal without filling the host disk. The send recorder verifies exactly one resumed delivery, no automatic retry after an ambiguous send, and zero requests after cancellation during preflight. The retained-attachment RPC fixture restarts the backend, removes the original attachment file, refuses foreign-account/draft reuse without queuing mail, verifies the owning draft's MIME bytes and cancels its delayed send. +The Windows production contract fixture requires `--isolated-windows-runner` on a disposable GitHub-hosted runner. Production resolves native Known Folders and intentionally ignores environment substitutions for those paths. The fixture temporarily redirects the runner's RoamingAppData, LocalAppData and Downloads through the Windows API, runs the unchanged production binary, and restores every redirected folder on success or failure. It refuses to perform this operation on an ordinary development session. No production path or credential bypass is added. + +Controlled provider fixtures now exercise cached mail after authentication failure, interrupted inventory/history/body work, expired history, coalesced offline edits, reconnect reconciliation and a server-deletion conflict. A private 64 MiB filesystem exercises genuine low-space refusal without filling the host disk. This fixture requires Bubblewrap 0.7 or newer for bounded tmpfs support; the performance workflow uses Ubuntu 24.04. The send recorder verifies exactly one resumed delivery, no automatic retry after an ambiguous send, and zero requests after cancellation during preflight. The retained-attachment RPC fixture restarts the backend, removes the original attachment file, refuses foreign-account/draft reuse without queuing mail, verifies the owning draft's MIME bytes and cancels its delayed send. Calendar component acceptance switches months and accounts while requests are pending, rejects stale replies and stale events after a newer empty range, and checks cached range reuse by reminders. Existing native and JavaScript suites cover provider parsing, recurrence and DST. These synthetic results do not certify every real mailbox or calendar server. diff --git a/scripts/test-low-space.py b/scripts/test-low-space.py index dcd751233..6fb34cc8d 100644 --- a/scripts/test-low-space.py +++ b/scripts/test-low-space.py @@ -16,6 +16,9 @@ def main(): if len(sys.argv) == 3 and sys.argv[1] == "--worker": shutil.copytree("/tmp/fixture-seed", "/tmp/mail-check/store") os.execv(sys.argv[2], [sys.argv[2], "--exact", TEST, "--ignored", "--nocapture"]) + options = subprocess.run(["/usr/bin/bwrap", "--help"], capture_output=True, text=True, check=True) + if "--size BYTES" not in options.stdout: + raise SystemExit("Low-space verification requires Bubblewrap 0.7 or newer with bounded tmpfs support") build = subprocess.run( ["cargo", "test", "--locked", "--lib", "--no-run", "--message-format=json"], cwd=ROOT, stdout=subprocess.PIPE, text=True, check=True) diff --git a/tests/test_backend_api.py b/tests/test_backend_api.py index 4bc836f34..fa0f3e48d 100644 --- a/tests/test_backend_api.py +++ b/tests/test_backend_api.py @@ -7,6 +7,7 @@ an exhaustive provider/network integration suite. """ import argparse +from contextlib import contextmanager, nullcontext import json import os from pathlib import Path @@ -19,6 +20,64 @@ WINDOWS_CREATE_NEW_PROCESS_GROUP = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0x00000200) +@contextmanager +def redirected_folders(changes, get_path, set_path): + originals = [] + try: + for key, path in changes: + original = get_path(key) + set_path(key, str(path)) + originals.append((key, original)) + yield + finally: + errors = [] + for key, original in reversed(originals): + try: + set_path(key, original) + except OSError as error: + errors.append(error) + if errors: + raise RuntimeError('Could not restore isolated runner Known Folders') from errors[0] + + +def windows_fixture_folders(home, config, local): + import ctypes + import uuid + shell = ctypes.WinDLL('shell32') + memory = ctypes.WinDLL('ole32') + shell.SHGetKnownFolderPath.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, + ctypes.POINTER(ctypes.c_void_p)] + shell.SHGetKnownFolderPath.restype = ctypes.c_long + shell.SHSetKnownFolderPath.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_wchar_p] + shell.SHSetKnownFolderPath.restype = ctypes.c_long + memory.CoTaskMemFree.argtypes = [ctypes.c_void_p] + memory.CoTaskMemFree.restype = None + + def guid(key): + return ctypes.create_string_buffer(uuid.UUID(key).bytes_le) + + def get_path(key): + pointer = ctypes.c_void_p() + result = shell.SHGetKnownFolderPath(guid(key), 0x4000, None, ctypes.byref(pointer)) + if result < 0: + raise OSError(f'SHGetKnownFolderPath failed: {result:#x}') + try: + return ctypes.wstring_at(pointer) + finally: + memory.CoTaskMemFree(pointer) + + def set_path(key, path): + result = shell.SHSetKnownFolderPath(guid(key), 0x2000, None, path) + if result < 0: + raise OSError(f'SHSetKnownFolderPath failed: {result:#x}') + + return redirected_folders([ + ('3eb685db-65f9-4cf6-a03a-e3ef65729f3d', config), + ('f1b32785-6fba-4fcf-9d55-7b8e7f157091', local), + ('374de290-123f-4565-9164-39c4925e467b', home / 'Downloads'), + ], get_path, set_path) + + def process_group_options(platform=None): """Start the Node harness in a group that can be torn down with its backend.""" if (platform or os.name) == 'nt': @@ -268,7 +327,13 @@ def main(): help='check only the released API, as the pinned published binary speaks it') parser.add_argument('--standalone', action='store_true', help='check standalone capabilities, including native agents on Linux/macOS') + parser.add_argument('--isolated-windows-runner', action='store_true', + help='temporarily redirect Known Folders on a disposable GitHub-hosted Windows runner') args = parser.parse_args() + if os.name == 'nt' and not (args.isolated_windows_runner + and os.environ.get('GITHUB_ACTIONS') == 'true' + and os.environ.get('RUNNER_ENVIRONMENT') == 'github-hosted'): + parser.error('Windows contract tests require --isolated-windows-runner on a disposable GitHub-hosted runner') binary = args.binary.resolve(strict=True) contract = json.loads((ROOT / 'backend-api.json').read_text()) if (type(contract.get('apiVersion')) is not int or contract['apiVersion'] < 1 @@ -316,6 +381,8 @@ def main(): CONTRACT_RELEASED='1' if args.released else '', CONTRACT_STANDALONE='1' if args.standalone else '') runtime_root.mkdir(parents=True, mode=0o700) + if os.name == 'nt': + (home / 'Downloads').mkdir(mode=0o700) registry.parent.mkdir(parents=True) if os.name != 'nt': registry.parent.chmod(0o700) @@ -371,17 +438,19 @@ def main(): grant = user + (':(OI)(CI)F' if path.is_dir() else ':F') subprocess.run(['icacls', str(path), '/inheritance:r', '/grant:r', grant, '/Q'], check=True, capture_output=True) - process = subprocess.Popen(['node', '-e', HARNESS], env=env, cwd=home, - **process_group_options()) - try: - status = process.wait(timeout=60) - finally: - # A failed/expired harness must not leave its backend running. + folders = windows_fixture_folders(home, config_root, local_root) if os.name == 'nt' else nullcontext() + with folders: + process = subprocess.Popen(['node', '-e', HARNESS], env=env, cwd=home, + **process_group_options()) try: - terminate_process_group(process) - except (OSError, ProcessLookupError): - pass - process.wait(timeout=10) + status = process.wait(timeout=60) + finally: + # A failed/expired harness must not leave its backend running. + try: + terminate_process_group(process) + except (OSError, ProcessLookupError): + pass + process.wait(timeout=10) if status: raise SystemExit(status) diff --git a/tests/test_backend_release.py b/tests/test_backend_release.py index e7eecb924..7f4010591 100644 --- a/tests/test_backend_release.py +++ b/tests/test_backend_release.py @@ -67,6 +67,23 @@ def kill(self): killpg.assert_called_once_with(42, backend_api.signal.SIGKILL) self.assertFalse(posix.killed) + def test_windows_fixture_restores_folders_after_setup_and_test_failures(self): + spec = importlib.util.spec_from_file_location('backend_api_folders', ROOT / 'tests/test_backend_api.py') + backend_api = importlib.util.module_from_spec(spec) + spec.loader.exec_module(backend_api) + for fail_at in ('setup', 'test'): + current = {'config': 'original-config', 'local': 'original-local'} + original = dict(current) + def set_path(key, value): + if fail_at == 'setup' and key == 'local' and value == 'fixture-local': + raise OSError('synthetic setup failure') + current[key] = value + with self.assertRaises(OSError): + with backend_api.redirected_folders( + [('config', 'fixture-config'), ('local', 'fixture-local')], current.get, set_path): + raise OSError('synthetic test failure') + self.assertEqual(current, original, 'no redirected folder may survive a failed fixture') + def test_preparation_allows_old_pin_but_merge_requires_equality(self): self.metadata() self.assertEqual(self.run_helper('check', '--root', self.root, '--tag', 'v0.8.2').returncode, 0) From e99d7337ce8ffae41be32692a06ec68642eba247 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:40:24 +0100 Subject: [PATCH 008/568] chore: Fix benchmark subprocess cleanup across completion and startup failure --- Makefile | 1 + benchmarks/mail/desktop_acceptance.py | 271 +++++++++++++------------- benchmarks/mail/roundtrip.py | 6 +- tests/test_benchmark_processes.py | 122 ++++++++++++ 4 files changed, 265 insertions(+), 135 deletions(-) create mode 100644 tests/test_benchmark_processes.py diff --git a/Makefile b/Makefile index 00978112b..19d223492 100644 --- a/Makefile +++ b/Makefile @@ -188,6 +188,7 @@ test-shell-portable: test-shell-independent python3 tests/test_public_http.py test-shell-independent: + python3 tests/test_benchmark_processes.py python3 tests/test_app_make.py python3 tests/test_performance_verification.py python3 tests/test_diagnostics.py diff --git a/benchmarks/mail/desktop_acceptance.py b/benchmarks/mail/desktop_acceptance.py index 4cad6eecb..8ed88f015 100644 --- a/benchmarks/mail/desktop_acceptance.py +++ b/benchmarks/mail/desktop_acceptance.py @@ -2,6 +2,7 @@ """Measure a synthetic native window through physical or virtual display capture.""" import argparse import base64 +from contextlib import ExitStack import hashlib import io import json @@ -172,6 +173,17 @@ def press(name): (output / (stage + ".done")).touch() +def stop_process(process): + if process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path, required=True) @@ -195,143 +207,136 @@ def main(): parser.error("Use at least 50 messages, 3 samples and nonnegative HTML size") env = seed(output, binary, args.messages, args.html_bytes) env["GSETTINGS_BACKEND"] = "memory" - bus = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"], env=env, - stdout=subprocess.PIPE, stderr=(output / "dbus.log").open("w"), text=True) - env["DBUS_SESSION_BUS_ADDRESS"] = bus.stdout.readline().strip() - os.environ["DBUS_SESSION_BUS_ADDRESS"] = env["DBUS_SESSION_BUS_ADDRESS"] - server = None - if args.display_mode == "physical": - instances = json.loads(subprocess.check_output(["hyprctl", "instances", "-j"], text=True)) - if len(instances) != 1: - raise RuntimeError("Expected one available Hyprland session") - env.update(HYPRLAND_INSTANCE_SIGNATURE=instances[0]["instance"], WAYLAND_DISPLAY=instances[0]["wl_socket"], - QT_QPA_PLATFORM="wayland") - else: - server = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1600x24", "-nolisten", "tcp"], - stdout=subprocess.PIPE, stderr=(output / "xvfb.log").open("w"), text=True) - env.update(DISPLAY=":" + server.stdout.readline().strip(), QT_QPA_PLATFORM="xcb") - env.update(QT_SCALE_FACTOR=args.scale, OMAMAIL_DEVELOPMENT_RESOURCES="1", - OMAMAIL_BIN=str(binary), MAGPIE_DESKTOP_OPTIONS=str(output / "options.json"), - QT_ACCESSIBILITY="1", QT_LINUX_ACCESSIBILITY_ALWAYS_ON="1") - env.pop("QT_QUICK_BACKEND", None) - private(output / "options.json", json.dumps({"output": str(output), "samples": args.samples, - "largeIds": [f"synthetic-{args.messages-1-i:08}" for i in range(3)] if args.html_bytes else [], - "accessibility": args.accessibility})) - if args.accessibility: - subprocess.run(["gdbus", "call", "--session", "--dest", "org.a11y.Bus", "--object-path", "/org/a11y/bus", - "--method", "org.freedesktop.DBus.Properties.Set", "org.a11y.Status", "IsEnabled", ""], - check=True, capture_output=True, text=True, env=env) - launched = time.time() * 1000 - process = subprocess.Popen([str(driver), "-input", str(ROOT / "benchmarks/mail/tst_desktop.qml")], - env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) - lines = queue.Queue() + with ExitStack() as cleanup: + bus = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"], env=env, + stdout=subprocess.PIPE, stderr=cleanup.enter_context((output / "dbus.log").open("w")), text=True) + cleanup.callback(stop_process, bus) + env["DBUS_SESSION_BUS_ADDRESS"] = bus.stdout.readline().strip() + os.environ["DBUS_SESSION_BUS_ADDRESS"] = env["DBUS_SESSION_BUS_ADDRESS"] + server = None + if args.display_mode == "physical": + instances = json.loads(subprocess.check_output(["hyprctl", "instances", "-j"], text=True)) + if len(instances) != 1: + raise RuntimeError("Expected one available Hyprland session") + env.update(HYPRLAND_INSTANCE_SIGNATURE=instances[0]["instance"], WAYLAND_DISPLAY=instances[0]["wl_socket"], + QT_QPA_PLATFORM="wayland") + else: + server = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1600x24", "-nolisten", "tcp"], + stdout=subprocess.PIPE, stderr=cleanup.enter_context((output / "xvfb.log").open("w")), text=True) + cleanup.callback(stop_process, server) + env.update(DISPLAY=":" + server.stdout.readline().strip(), QT_QPA_PLATFORM="xcb") + env.update(QT_SCALE_FACTOR=args.scale, OMAMAIL_DEVELOPMENT_RESOURCES="1", + OMAMAIL_BIN=str(binary), MAGPIE_DESKTOP_OPTIONS=str(output / "options.json"), + QT_ACCESSIBILITY="1", QT_LINUX_ACCESSIBILITY_ALWAYS_ON="1") + env.pop("QT_QUICK_BACKEND", None) + private(output / "options.json", json.dumps({"output": str(output), "samples": args.samples, + "largeIds": [f"synthetic-{args.messages-1-i:08}" for i in range(3)] if args.html_bytes else [], + "accessibility": args.accessibility})) + if args.accessibility: + subprocess.run(["gdbus", "call", "--session", "--dest", "org.a11y.Bus", "--object-path", "/org/a11y/bus", + "--method", "org.freedesktop.DBus.Properties.Set", "org.a11y.Status", "IsEnabled", ""], + check=True, capture_output=True, text=True, env=env) + launched = time.time() * 1000 + process = subprocess.Popen([str(driver), "-input", str(ROOT / "benchmarks/mail/tst_desktop.qml")], + env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + cleanup.callback(stop_process, process) + lines = queue.Queue() - def read(): - for line in process.stdout: - lines.put(line) - lines.put(None) + def read(): + for line in process.stdout: + lines.put(line) + lines.put(None) - threading.Thread(target=read, daemon=True).start() - results = [] - code = None - failure = None - deadline = time.monotonic() + 180 - try: - with (output / "desktop.log").open("w") as log: - while time.monotonic() < deadline: - line = lines.get(timeout=20) - if line is None: - break - log.write(line) - log.flush() - if "DESKTOP_CHECKPOINT accessibility-" in line and args.accessibility: - accessibility(process.pid, line.split("DESKTOP_CHECKPOINT ", 1)[1].strip(), output) - if "DESKTOP_CAPTURE " not in line: - continue - event = json.loads(line.split("DESKTOP_CAPTURE ", 1)[1]) - window = window_for(env, process.pid) if args.display_mode == "physical" else { - "at": [0, 0], "size": [round(1024 * float(args.scale)), round(768 * float(args.scale))]} - if not window: - raise RuntimeError("Synthetic window is not mapped") - expected = event["serial"] % 2 - until = time.monotonic() + 10 - while time.monotonic() < until: - if args.display_mode == "physical": window = window_for(env, process.pid) - x, y = window["at"] - scale = float(args.scale) - region = f"{x + round(12 * scale)},{y + round(12 * scale)} 2x2" - if args.display_mode == "physical": - capture = subprocess.check_output(["grim", "-g", region, "-t", "ppm", "-"], env=env, timeout=5) - pixels = Image.open(io.BytesIO(capture)).convert("RGB") - else: - pixels = ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((round(12*scale), round(12*scale), round(12*scale)+2, round(12*scale)+2)).convert("RGB") - red, green, blue = pixels.getpixel((0, 0)) - if blue > 100 and ((expected and red > green + 80) or (not expected and green > red + 80)): - elapsed = time.time() * 1000 - (launched if event["kind"] == "coldInbox" else event["started"]) + threading.Thread(target=read, daemon=True).start() + results = [] + code = None + failure = None + deadline = time.monotonic() + 180 + try: + with (output / "desktop.log").open("w") as log: + while time.monotonic() < deadline: + line = lines.get(timeout=20) + if line is None: break - else: - private(output / "window.json", json.dumps(window, indent=2)) - x, y = window["at"] - width, height = window["size"] - if args.display_mode == "physical": - subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / "failed-window.png")], env=env, check=True) + log.write(line) + log.flush() + if "DESKTOP_CHECKPOINT accessibility-" in line and args.accessibility: + accessibility(process.pid, line.split("DESKTOP_CHECKPOINT ", 1)[1].strip(), output) + if "DESKTOP_CAPTURE " not in line: + continue + event = json.loads(line.split("DESKTOP_CAPTURE ", 1)[1]) + window = window_for(env, process.pid) if args.display_mode == "physical" else { + "at": [0, 0], "size": [round(1024 * float(args.scale)), round(768 * float(args.scale))]} + if not window: + raise RuntimeError("Synthetic window is not mapped") + expected = event["serial"] % 2 + until = time.monotonic() + 10 + while time.monotonic() < until: + if args.display_mode == "physical": window = window_for(env, process.pid) + x, y = window["at"] + scale = float(args.scale) + region = f"{x + round(12 * scale)},{y + round(12 * scale)} 2x2" + if args.display_mode == "physical": + capture = subprocess.check_output(["grim", "-g", region, "-t", "ppm", "-"], env=env, timeout=5) + pixels = Image.open(io.BytesIO(capture)).convert("RGB") + else: + pixels = ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((round(12*scale), round(12*scale), round(12*scale)+2, round(12*scale)+2)).convert("RGB") + red, green, blue = pixels.getpixel((0, 0)) + if blue > 100 and ((expected and red > green + 80) or (not expected and green > red + 80)): + elapsed = time.time() * 1000 - (launched if event["kind"] == "coldInbox" else event["started"]) + break else: - ImageGrab.grab(xdisplay=env["DISPLAY"]).save(output / "failed-window.png") - raise RuntimeError(f"Compositor never presented marker {expected}; last pixel {pixels.getpixel((0, 0))}") - results.append(dict(event, presentedMs=round(elapsed, 3))) - if event["kind"] in ("coldInbox", "compose", "composeFocus", "largeHtml", "offlineEdit"): - x, y = window["at"] - width, height = window["size"] - if args.display_mode == "physical": - subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / (event["kind"] + ".png"))], env=env, check=True) - else: - ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((0,0,width,height)).save(output / (event["kind"] + ".png")) - (output / ("capture-" + str(event["serial"]))).touch() - else: - raise RuntimeError("Desktop acceptance timed out") - code = process.wait(timeout=10) - except Exception as error: - failure = str(error) - raise - finally: - if process.poll() is None: - process.terminate() - try: process.wait(timeout=10) - except subprocess.TimeoutExpired: - process.kill() - process.wait(timeout=10) - if server is not None: - server.terminate() - server.wait(timeout=10) - bus.terminate() - bus.wait(timeout=10) - groups = {} - for result in results: - groups.setdefault(result["kind"], []).append(result["presentedMs"]) - summary = {kind: {"samplesMs": values, "p95Ms": sorted(values)[math.ceil(.95 * len(values)) - 1]} - for kind, values in groups.items()} - unchanged = (source_before == source_hash() - and backend_hash == hashlib.sha256(binary.read_bytes()).hexdigest() - and driver_hash == hashlib.sha256(driver.read_bytes()).hexdigest()) - if not unchanged: - failure = "Source or binaries changed during measurement" - code = 1 - report = {"source": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), - "sourceSha256": source_before, "driverSha256": driver_hash, - "backendSha256": backend_hash, "messages": args.messages, - "largeHtmlBytes": args.html_bytes, - "backendPath": str(binary), "driverPath": str(driver), - "cpu": next((line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name")), "unknown"), - "qt": next((line for line in (output / "desktop.log").read_text().splitlines() if line.startswith("Config:")), "unknown"), - "viewport": [1024, 768], "osCaches": "warm", "input": "Qt key event delivered to the actual application window", - "themeSha256": {name: hashlib.sha256((Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).read_bytes()).hexdigest() - for name in ("colors.toml", "shell.toml") if (Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).exists()}, - "scale": args.scale, "platform": platform.platform(), "results": summary, "raw": results, - "status": "pass" if code == 0 and failure is None else "fail", "error": failure, - "statusScope": "Functional acceptance only; compare timings with targets separately.", - "displayMode": args.display_mode, - "boundary": "Input/RPC/model/layout to captured pixels. Includes capture overhead. Cold means new app/backend processes; OS caches are warm. Xvfb measures an isolated virtual display, not physical compositor presentation."} - private(output / "results.json", json.dumps(report, indent=2)) + private(output / "window.json", json.dumps(window, indent=2)) + x, y = window["at"] + width, height = window["size"] + if args.display_mode == "physical": + subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / "failed-window.png")], env=env, check=True) + else: + ImageGrab.grab(xdisplay=env["DISPLAY"]).save(output / "failed-window.png") + raise RuntimeError(f"Compositor never presented marker {expected}; last pixel {pixels.getpixel((0, 0))}") + results.append(dict(event, presentedMs=round(elapsed, 3))) + if event["kind"] in ("coldInbox", "compose", "composeFocus", "largeHtml", "offlineEdit"): + x, y = window["at"] + width, height = window["size"] + if args.display_mode == "physical": + subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(output / (event["kind"] + ".png"))], env=env, check=True) + else: + ImageGrab.grab(xdisplay=env["DISPLAY"]).crop((0,0,width,height)).save(output / (event["kind"] + ".png")) + (output / ("capture-" + str(event["serial"]))).touch() + else: + raise RuntimeError("Desktop acceptance timed out") + code = process.wait(timeout=10) + except Exception as error: + failure = str(error) + raise + finally: + groups = {} + for result in results: + groups.setdefault(result["kind"], []).append(result["presentedMs"]) + summary = {kind: {"samplesMs": values, "p95Ms": sorted(values)[math.ceil(.95 * len(values)) - 1]} + for kind, values in groups.items()} + unchanged = (source_before == source_hash() + and backend_hash == hashlib.sha256(binary.read_bytes()).hexdigest() + and driver_hash == hashlib.sha256(driver.read_bytes()).hexdigest()) + if not unchanged: + failure = "Source or binaries changed during measurement" + code = 1 + report = {"source": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), + "sourceSha256": source_before, "driverSha256": driver_hash, + "backendSha256": backend_hash, "messages": args.messages, + "largeHtmlBytes": args.html_bytes, + "backendPath": str(binary), "driverPath": str(driver), + "cpu": next((line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name")), "unknown"), + "qt": next((line for line in (output / "desktop.log").read_text().splitlines() if line.startswith("Config:")), "unknown"), + "viewport": [1024, 768], "osCaches": "warm", "input": "Qt key event delivered to the actual application window", + "themeSha256": {name: hashlib.sha256((Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).read_bytes()).hexdigest() + for name in ("colors.toml", "shell.toml") if (Path(env["HOME"]) / ".local/state/omarchy/current/theme" / name).exists()}, + "scale": args.scale, "platform": platform.platform(), "results": summary, "raw": results, + "status": "pass" if code == 0 and failure is None else "fail", "error": failure, + "statusScope": "Functional acceptance only; compare timings with targets separately.", + "displayMode": args.display_mode, + "boundary": "Input/RPC/model/layout to captured pixels. Includes capture overhead. Cold means new app/backend processes; OS caches are warm. Xvfb measures an isolated virtual display, not physical compositor presentation."} + private(output / "results.json", json.dumps(report, indent=2)) print(json.dumps(summary, indent=2)) raise SystemExit(code) diff --git a/benchmarks/mail/roundtrip.py b/benchmarks/mail/roundtrip.py index a0ef84f07..59b41d399 100644 --- a/benchmarks/mail/roundtrip.py +++ b/benchmarks/mail/roundtrip.py @@ -151,10 +151,12 @@ def main(): load_before=os.getloadavg();start=time.perf_counter() process=subprocess.Popen([shutil.which('qs'),'--no-color','--path',str(temp/'shell.qml')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True) try:output,_=process.communicate(timeout=920) - finally: + except subprocess.TimeoutExpired: + # Invariant: the timed-out leader has not been reaped, so its process-group identity is reserved. try:os.killpg(process.pid,signal.SIGKILL) except ProcessLookupError:pass - process.wait() + process.communicate() + raise if process.returncode!=0 or 'ROUNDTRIP_ERROR' in output or 'ROUNDTRIP_DONE' not in output:raise RuntimeError(output[-6000:]) rows=[];parts=[];total=None for line in output.splitlines(): diff --git a/tests/test_benchmark_processes.py b/tests/test_benchmark_processes.py new file mode 100644 index 000000000..f30d1caf1 --- /dev/null +++ b/tests/test_benchmark_processes.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +import importlib.util +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +MAIL = ROOT / "benchmarks/mail" +sys.path.insert(0, str(MAIL)) + + +def load(name): + specification = importlib.util.spec_from_file_location(name, MAIL / (name + ".py")) + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +class Child: + def __init__(self, output="", timeout=False): + self.pid = 12345 + self.returncode = None + self.stdout = io.StringIO(output) + self.output = output + self.timeout = timeout + self.waited = False + + def communicate(self, timeout=None): + if self.timeout: + self.timeout = False + raise subprocess.TimeoutExpired("synthetic", timeout) + self.returncode = 0 + return self.output, None + + def poll(self): + return self.returncode + + def terminate(self): + self.returncode = -15 + + def kill(self): + self.returncode = -9 + + def wait(self, timeout=None): + self.waited = True + self.returncode = self.returncode or 0 + return self.returncode + + +class BenchmarkProcesses(unittest.TestCase): + def roundtrip(self, child): + module = load("roundtrip") + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + benchmark = root / "benchmarks/mail" + baseline = benchmark / "baseline/ui" + baseline.mkdir(parents=True) + (baseline.parent / "manifest.json").write_text(json.dumps({"sha256": {}})) + for name in ("roundtrip.py", "corpus.py", "run.py"): + (benchmark / name).write_text("") + for folder in ("ui/backend", "ui/message", "src", "target/release"): + (root / folder).mkdir(parents=True) + (root / "Cargo.toml").write_text('[package]\nversion="0.11.0"\n') + (root / "backend-api.json").write_text('{"apiVersion":8}') + (root / "target/release/omamail").write_bytes(b"synthetic executable") + with patch.object(module, "HERE", benchmark), patch.object(module, "ROOT", root), \ + patch.object(module, "corpus", return_value=[]), \ + patch.object(module, "__file__", str(benchmark / "roundtrip.py")), \ + patch.object(sys, "argv", ["roundtrip.py", "--samples", "3"]), \ + patch.object(subprocess, "run"), \ + patch.object(subprocess, "check_output", return_value="synthetic version"), \ + patch.object(subprocess, "Popen", return_value=child), \ + patch.object(os, "killpg") as kill_group, \ + patch("builtins.print"): + try: + module.main() + except subprocess.TimeoutExpired: + pass + return kill_group.call_args_list + + def test_completed_roundtrip_does_not_signal_reaped_process_group(self): + child = Child("ROUNDTRIP_DONE\n") + self.assertEqual(self.roundtrip(child), []) + self.assertEqual(child.returncode, 0) + + def test_timed_out_roundtrip_terminates_owned_group(self): + child = Child(timeout=True) + calls = self.roundtrip(child) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].args[0], child.pid) + self.assertIsNotNone(child.returncode) + + def test_desktop_setup_failure_reaps_private_bus(self): + with patch.dict(sys.modules, {"PIL": SimpleNamespace(Image=None, ImageGrab=None)}): + module = load("desktop_acceptance") + bus = Child("unix:path=/synthetic-private-bus\n") + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + executable = root / "synthetic" + executable.write_bytes(b"synthetic executable") + arguments = ["desktop_acceptance.py", "--output", str(root / "output"), + "--binary", str(executable), "--driver", str(executable), + "--display-mode", "xvfb"] + with patch.object(sys, "argv", arguments), \ + patch.object(module, "source_hash", return_value="synthetic source"), \ + patch.object(module, "seed", return_value={}), \ + patch.object(subprocess, "Popen", side_effect=[bus, OSError("display startup refused")]), \ + patch.dict(os.environ, {}, clear=False): + with self.assertRaisesRegex(OSError, "display startup refused"): + module.main() + self.assertTrue(bus.waited, "Setup failure must reap the private DBus process") + + +if __name__ == "__main__": + unittest.main() From 499aa8b03282bb3a9f11f7f7fca756abb6b24763 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:42:56 +0100 Subject: [PATCH 009/568] chore: Reject incomplete or unequal benchmark comparisons --- Makefile | 1 + benchmarks/mail/compiler_profiles.py | 12 +++--- benchmarks/mail/run.py | 21 ++++++++-- tests/test_benchmark_results.py | 63 ++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 10 deletions(-) create mode 100644 tests/test_benchmark_results.py diff --git a/Makefile b/Makefile index 19d223492..3c5a7a819 100644 --- a/Makefile +++ b/Makefile @@ -189,6 +189,7 @@ test-shell-portable: test-shell-independent test-shell-independent: python3 tests/test_benchmark_processes.py + python3 tests/test_benchmark_results.py python3 tests/test_app_make.py python3 tests/test_performance_verification.py python3 tests/test_diagnostics.py diff --git a/benchmarks/mail/compiler_profiles.py b/benchmarks/mail/compiler_profiles.py index 8db5b7801..4d61bb84a 100644 --- a/benchmarks/mail/compiler_profiles.py +++ b/benchmarks/mail/compiler_profiles.py @@ -9,7 +9,7 @@ import time from corpus import corpus -from run import html_semantics, mime_semantics, stats +from run import html_semantics, measured_cases, mime_semantics, stats def main(): @@ -18,21 +18,21 @@ def main(): parser.add_argument("--speed", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() - payload = json.dumps(dict(cases=corpus(), samples=31, batch=3, phases=["mime", "readprep"])) + payload = dict(cases=corpus(), samples=31, batch=3, phases=["mime", "readprep"]) outputs = {} binaries = {} load = os.getloadavg() for name, path in [("size", args.size), ("speed", args.speed)]: - result = subprocess.run([str(path.resolve())], input=payload, text=True, + result = subprocess.run([str(path.resolve())], input=json.dumps(payload), text=True, capture_output=True, check=True, timeout=180) - outputs[name] = json.loads(result.stdout)["cases"] + outputs[name] = measured_cases(json.loads(result.stdout), payload) binaries[name] = dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(), bytes=path.stat().st_size) rows = [] for size, speed in zip(outputs["size"], outputs["speed"], strict=True): - assert (size["name"], size["phase"]) == (speed["name"], speed["phase"]) normalize = mime_semantics if size["phase"] == "mime" else html_semantics - assert normalize(size["result"]) == normalize(speed["result"]) + if normalize(size["result"]) != normalize(speed["result"]): + raise RuntimeError("Compiler profiles produced unequal output: " + size["name"]) rows.append(dict(name=size["name"], phase=size["phase"], size=stats(size), speed=stats(speed))) report = dict(measuredAt=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), diff --git a/benchmarks/mail/run.py b/benchmarks/mail/run.py index 279761c46..ff731e0ca 100644 --- a/benchmarks/mail/run.py +++ b/benchmarks/mail/run.py @@ -90,6 +90,22 @@ def stats(row): p95Us=values[min(len(values)-1,math.ceil(len(values)*.95)-1)],samplesUs=row['samplesUs']) +def measured_cases(measured, payload): + cases = measured.get('cases', []) + expected = [(case['name'], phase) for case in payload['cases'] for phase in payload['phases']] + actual = [(case.get('name'), case.get('phase')) for case in cases] + if actual != expected: + raise RuntimeError('Missing, duplicated or reordered benchmark operations') + for case in cases: + samples = case.get('samplesUs', []) + if len(samples) != payload['samples']: + raise RuntimeError('Missing benchmark samples: ' + case['name']) + if any(not isinstance(value, (int, float)) or isinstance(value, bool) + or not math.isfinite(value) or value < 0 for value in samples): + raise RuntimeError('Invalid benchmark sample: ' + case['name']) + return cases + + def main(): command_started=time.perf_counter() parser=argparse.ArgumentParser() @@ -124,12 +140,10 @@ def main(): qml_file=directory/'benchmark.qml' qml_file.write_text(qml_source(payload,HERE/'baseline/ui')) qml,qml_process=run_process(['/usr/lib/qt6/bin/qml',str(qml_file)],{},directory,'qml') - expected=len(payload['cases'])*len(payload['phases']) for measured in [js,native]+([qml] if qml else []): - if len(measured['cases'])!=expected:raise RuntimeError('Missing benchmark operations') + measured_cases(measured, payload) results=[] for index,(old,new) in enumerate(zip(js['cases'],native['cases'],strict=True)): - assert(old['name'],old['phase'])==(new['name'],new['phase']) canonical=mime_semantics if old['phase']=='mime' else html_semantics a,b=canonical(old['result']),canonical(new['result']) results.append(dict(name=old['name'],phase=old['phase'],semanticMatch=a==b, @@ -137,7 +151,6 @@ def main(): node=stats(old),rust=stats(new),speedup=statistics.median(old['samplesUs'])/statistics.median(new['samplesUs']))) if qml: actual=qml['cases'][index] - assert(actual['name'],actual['phase'])==(old['name'],old['phase']) results[-1]['qml']=stats(actual) results[-1]['qml']['batch']=actual['batch'] results[-1]['qmlSemanticMatch']=canonical(actual['result'])==a diff --git a/tests/test_benchmark_results.py b/tests/test_benchmark_results.py new file mode 100644 index 000000000..a8d5369c6 --- /dev/null +++ b/tests/test_benchmark_results.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class CompilerProfileResults(unittest.TestCase): + def compare(self, transform): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + program = '''import json, sys +payload = json.load(sys.stdin) +cases = [dict(name=case["name"], phase=phase, coldUs=1, + samplesUs=[1] * payload["samples"], + result={"document": {"type": "root", "children": []}}) + for case in payload["cases"] for phase in payload["phases"]] +TRANSFORM +print(json.dumps({"cases": cases})) +''' + for name, change in (("size", ""), ("speed", transform)): + executable = root / name + executable.write_text("#!" + sys.executable + "\n" + program.replace("TRANSFORM", change)) + executable.chmod(0o700) + output = root / "results.json" + result = subprocess.run( + [sys.executable, "-O", str(ROOT / "benchmarks/mail/compiler_profiles.py"), + "--size", str(root / "size"), "--speed", str(root / "speed"), + "--output", str(output)], capture_output=True, text=True, timeout=30, + env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1")) + report = json.loads(output.read_text()) if output.exists() else None + return result, report + + def test_valid_comparison_is_recorded(self): + result, report = self.compare("") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(report["results"]), 10) + + def assert_refused(self, transform): + result, report = self.compare(transform) + self.assertNotEqual(result.returncode, 0, "Unequal work must not pass in optimized Python") + self.assertIsNone(report, "Invalid measurement must not publish a comparison") + + def test_wrong_identity_is_refused_with_python_optimization(self): + self.assert_refused('cases[0]["name"] = "wrong-case"') + + def test_unequal_output_is_refused_with_python_optimization(self): + self.assert_refused('cases[0]["result"]["filename"] = "different.txt"') + + def test_missing_samples_are_refused(self): + self.assert_refused('cases[0]["samplesUs"] = [1]') + + def test_missing_case_is_refused(self): + self.assert_refused('cases.pop()') + + +if __name__ == "__main__": + unittest.main() From 4c8ffac496ad6fba996ebad20b43db6656a25d66 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:51:55 +0100 Subject: [PATCH 010/568] chore: Honor absolute standalone build directories when launching --- Makefile | 2 +- tests/test_app_make.py | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 3c5a7a819..b8aed1d2d 100644 --- a/Makefile +++ b/Makefile @@ -86,7 +86,7 @@ APP_BUILD_DIR ?= app/build APP_EXEEXT := $(if $(filter Windows_NT,$(OS)),.exe,) APP_TARGET_DIR ?= $(CURDIR)/target/standalone APP_BACKEND := $(APP_TARGET_DIR)/debug/omamail$(APP_EXEEXT) -APP_EXECUTABLE := $(CURDIR)/$(APP_BUILD_DIR)/omamail-app$(APP_EXEEXT) +APP_EXECUTABLE := $(APP_BUILD_DIR)/omamail-app$(APP_EXEEXT) .PHONY: test test-js test-shell test-shell-portable test-shell-independent test-shell-libcurl \ test-qml test-app-qml test-local test-backend-process qml-check validate bench install \ diff --git a/tests/test_app_make.py b/tests/test_app_make.py index 7ed44358e..81796c377 100644 --- a/tests/test_app_make.py +++ b/tests/test_app_make.py @@ -2,6 +2,7 @@ """The local standalone targets use the portable backend and explicit dev paths.""" from pathlib import Path import os +import shlex import subprocess @@ -36,11 +37,18 @@ def make(*args): launch = launches[0] assert "OMAMAIL_DEVELOPMENT_RESOURCES=1" in launch assert 'OMAMAIL_BIN="' in launch and "/target/standalone/debug/omamail" in launch -assert "/app/build/omamail-app" in launch +assert '"app/build/omamail-app"' in launch assert "backend-runtime.py" not in run assert "install" not in run assert "PATH=" not in launch +for build_dir in ("/tmp/magpie-app-build", "app/custom build"): + custom_run = make("-n", "app-run", "APP_BUILD_DIR=" + build_dir) + custom_launch = next(line for line in custom_run.splitlines() + if "OMAMAIL_DEVELOPMENT_RESOURCES=1" in line) + executable = (ROOT / build_dir / "omamail-app").resolve() + assert (ROOT / shlex.split(custom_launch)[-1]).resolve() == executable, custom_launch + cmake = (ROOT / "app/CMakeLists.txt").read_text() assert 'ui/assets/*' in cmake From c01e42663a16f6fc4f9d69fd4eaa628c88dcabe1 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:53:23 +0100 Subject: [PATCH 011/568] chore: Keep build comments focused on test and release constraints --- .gitignore | 5 +---- Makefile | 42 ++++++++++-------------------------------- 2 files changed, 11 insertions(+), 36 deletions(-) diff --git a/.gitignore b/.gitignore index 304204c24..ba2ef3863 100644 --- a/.gitignore +++ b/.gitignore @@ -7,12 +7,9 @@ node_modules/ .worktrees/ app/build/ -# Design canvases and planning notes are working material, not something a -# user installing the plugin should have to download. They live outside the -# repository; see AGENTS.md for what is kept and why. +# Invariant: planning material is excluded from the installed plugin; see AGENTS.md. docs/design/ docs/superpowers/ .superpowers/ -# Python leaves these beside the harvester scripts. __pycache__/ diff --git a/Makefile b/Makefile index b8aed1d2d..0ce72a471 100644 --- a/Makefile +++ b/Makefile @@ -98,8 +98,7 @@ help: test: test-rust test-js test-shell test-qml -# The real Quickshell process bridge needs the desktop runtime installed. -# Keep it explicit so the portable suite can still run without Quickshell. +# Invariant: the explicit local gate requires Quickshell; portable tests do not. test-local: test test-backend-process test-backend-process: @@ -115,8 +114,6 @@ test-rust: backend: cargo build --locked --release --target-dir "$(CURDIR)/target" --bin omamail -# The parsing, formatting, and decision rules live in plain JS precisely so -# they can be tested without a compositor. These run anywhere node does. test-js: node ui/tests/test_inbox.js node ui/tests/test_display.js @@ -180,8 +177,7 @@ test-js: test-shell: test-shell-portable test-shell-libcurl -# Everything here drives one of our own scripts against a fake server and -# asserts what the script did with the answer, so any libcurl can run it. +# Invariant: portable transport tests assert our policy using controlled servers. test-shell-portable: test-shell-independent python3 tests/test_calendar_notifications.py python3 tests/test_curl_config.py @@ -227,30 +223,17 @@ test-shell-independent: python3 tests/test_publish_backend.py bash tests/test_release_source.sh -# This one asserts libcurl's own behaviour rather than ours: which of its two -# output channels a single-UID BODY.PEEK fetch arrives on. That is a property -# of the installed libcurl and it differs by version — Omarchy's 8.21 puts the -# message on stdout, and the libcurl on a GitHub runner delivers neither the -# body there nor a complete one through the header callback. Running it on a -# runner reports on a library nobody here runs, which is why the release -# workflow does not, and why `make test` still does. +# Invariant: BODY.PEEK output channels depend on the installed libcurl version. +# This local gate checks the desktop library; release CI uses the portable gate. test-shell-libcurl: bash tests/test_imap_ordering.sh -# Focus ownership and key routing cannot be tested without a focus scope, and a -# focus scope needs the QML engine. Offscreen, so it needs no compositor: the -# bugs this catches — a hidden component owning the focus and swallowing keys, a -# Repeater building no Shortcuts — are invisible to any test that cannot -# instantiate one. -# -# Found rather than hard-coded: the binary is at /usr/lib/qt6/bin on Arch and on -# PATH as qmltestrunner6 on Debian and Ubuntu, and pinning one of those makes -# the suite unrunnable on the other. +# Invariant: Arch and Debian install Qt's test runner under different names/paths. QMLTESTRUNNER := $(shell command -v qmltestrunner6 2>/dev/null \ || ls /usr/lib/qt6/bin/qmltestrunner 2>/dev/null \ || command -v qmltestrunner 2>/dev/null) -# Use the verified release download, not a build from this checkout. +# Invariant: this gate needs the verified release download, not a source build. .PHONY: test-agent-published test-agent-published: @test -n "$(PUBLISHED_BACKEND)" || { echo "Set PUBLISHED_BACKEND to the verified pinned executable" >&2; exit 1; } @@ -287,14 +270,11 @@ app-build: app-run: app-build OMAMAIL_DEVELOPMENT_RESOURCES=1 OMAMAIL_BIN="$(APP_BACKEND)" "$(APP_EXECUTABLE)" -# Both engines on the same fixtures. The QML column is the one that decides -# anything — the shell runs that engine, not node's — so run it on the machine -# the shell runs on. Not part of `test`: it takes a few seconds and measures -# rather than asserts. +# Performance: QML measurements represent the desktop engine; Node is a comparison. bench: bash ui/tests/bench.sh -# Needs the Omarchy shell's qs.Commons / qs.Ui on the import path. +# Invariant: qs.Commons and qs.Ui come from the installed Omarchy shell. qml-check: $(QMLLINT) -I /usr/share/omarchy/shell $(QML_FILES) $(QMLLINT) -I app/qml/imports -I app/build/qml $(APP_QML_FILES) @@ -309,7 +289,7 @@ VERIFY_OUTPUT ?= /tmp/magpie-verification-$(shell date +%Y%m%d-%H%M%S) verify-performance: python3 scripts/verify-performance.py --profile "$(VERIFY_PROFILE)" --output "$(VERIFY_OUTPUT)" -# Development only: the Marketplace installs the plugin for ordinary users. +# Invariant: these local installation targets are explicitly requested by developers. .PHONY: install-backend-local install-plugin install-backend-local: backend python3 scripts/backend-runtime.py install-local @@ -317,13 +297,11 @@ install-backend-local: backend install: install-backend-local bash scripts/link-plugin.sh -# Reset the private runtime so the setup page exercises a fresh installation. install-plugin: python3 scripts/backend-runtime.py uninstall bash scripts/link-plugin.sh -# Prepare release/X.Y.Z and its PR; CI publishes, verifies, then updates its pin. -# VERSION defaults to the next patch. Main changes only when the PR is merged. +# Invariant: publication and pin advancement occur on a release branch before merging. .PHONY: publish publish: bash scripts/publish.sh "$(VERSION)" From ae5f1cfa099da44a990ed7a8ad4e79ccafd7d299 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 012/568] Fix attachment classification and avatar cache admission --- src/inbox/store.rs | 69 +++++++++++++++++++++++++++++++++++---- src/local_mail/content.rs | 33 ++++++++++++++----- src/local_mail/sync.rs | 19 +---------- src/local_mail/tests.rs | 10 ++++++ 4 files changed, 97 insertions(+), 34 deletions(-) diff --git a/src/inbox/store.rs b/src/inbox/store.rs index b6e744002..40f92a35b 100644 --- a/src/inbox/store.rs +++ b/src/inbox/store.rs @@ -30,12 +30,16 @@ pub fn read(name: &str) -> Result, &'static str> { .map(Some) .map_err(|_| "inbox_storage_invalid") } -pub fn write(name: &str, value: &Value) -> Result<(), &'static str> { - let dir = directory()?; +fn encode(value: &Value) -> Result, &'static str> { let bytes = serde_json::to_vec(value).map_err(|_| "inbox_storage_invalid")?; if bytes.len() > 8 * 1024 * 1024 { return Err("inbox_storage_invalid"); } + Ok(bytes) +} +pub fn write(name: &str, value: &Value) -> Result<(), &'static str> { + let bytes = encode(value)?; + let dir = directory()?; fs::atomic_replace(&dir, name, &bytes)?; fs::sync_dir(&dir) } @@ -52,11 +56,17 @@ pub fn update( } pub fn cache(name: &str, value: &Value) -> Result<(), &'static str> { + let bytes = encode(value)?; let dir = directory()?; let _lock = fs::lock_exclusive(&dir, ".cache-lock")?; + fs::regular_readonly(&dir, name)?; let mut entries = Vec::new(); - let mut total = 0u64; - for name in fs::names(&dir)? { + let mut total = bytes.len() as u64; + for entry_name in fs::names(&dir)? { + if entry_name == name { + continue; + } + let name = entry_name; if !name.starts_with("avatar-") { continue; } @@ -73,16 +83,17 @@ pub fn cache(name: &str, value: &Value) -> Result<(), &'static str> { } } entries.sort_by_key(|entry| entry.0); - let mut count = entries.len(); + let mut count = entries.len() + 1; for (_, name, bytes) in entries { - if count < 1024 && total < 128 * 1024 * 1024 { + if count <= 1024 && total <= 128 * 1024 * 1024 { break; } fs::remove_owned(&dir, &name)?; count -= 1; total = total.saturating_sub(bytes); } - write(name, value) + fs::atomic_replace(&dir, name, &bytes)?; + fs::sync_dir(&dir) } #[cfg(all(test, unix))] @@ -90,6 +101,50 @@ mod tests { use super::*; use std::os::unix::fs::{PermissionsExt, symlink}; #[test] + fn avatar_cache_reserves_incoming_bytes_before_writing() { + if crate::mail::tests::isolated() { + return; + } + let fixture = + crate::mail::tests::account_fixture(serde_json::json!({"version":1,"accounts":[]})); + let dir = directory().unwrap(); + drop(dir); + let path = fixture.state.join("omamail/inbox/avatar-old.json"); + File::create(&path) + .unwrap() + .set_len(128 * 1024 * 1024 - 1) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + cache("avatar-new.json", &serde_json::json!({"image":"new"})).unwrap(); + assert!(!path.exists()); + assert_eq!(read("avatar-new.json").unwrap().unwrap()["image"], "new"); + } + #[test] + fn avatar_cache_rejects_oversized_writes_without_eviction() { + if crate::mail::tests::isolated() { + return; + } + let fixture = + crate::mail::tests::account_fixture(serde_json::json!({"version":1,"accounts":[]})); + let dir = directory().unwrap(); + drop(dir); + let path = fixture.state.join("omamail/inbox/avatar-old.json"); + File::create(&path) + .unwrap() + .set_len(128 * 1024 * 1024) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!( + cache( + "avatar-new.json", + &Value::String("x".repeat(8 * 1024 * 1024)) + ), + Err("inbox_storage_invalid") + ); + assert!(path.exists()); + assert!(read("avatar-new.json").unwrap().is_none()); + } + #[test] fn private_store_refuses_links_and_keeps_sender_bytes_out_of_paths() { if crate::mail::tests::isolated() { return; diff --git a/src/local_mail/content.rs b/src/local_mail/content.rs index 8b4669dae..0daf1bff2 100644 --- a/src/local_mail/content.rs +++ b/src/local_mail/content.rs @@ -6,6 +6,29 @@ pub(super) struct Text { pub filenames: String, pub complete: bool, } +pub(super) fn is_attachment(part: &Value) -> bool { + if !part["filename"].as_str().unwrap_or("").is_empty() { + return true; + } + part["headers"] + .as_array() + .into_iter() + .flatten() + .any(|header| { + header["name"] + .as_str() + .is_some_and(|name| name.eq_ignore_ascii_case("content-disposition")) + && header["value"].as_str().is_some_and(|value| { + value + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case("attachment") + }) + }) +} + pub(super) fn extract(resource: &Value) -> Text { let mut output = Text { body: String::new(), @@ -18,19 +41,11 @@ pub(super) fn extract(resource: &Value) -> Text { pending.extend(parts.iter().rev()); } let filename = part["filename"].as_str().unwrap_or(""); - let attachment = part["headers"].as_array().into_iter().flatten().any(|h| { - h["name"] - .as_str() - .is_some_and(|s| s.eq_ignore_ascii_case("Content-Disposition")) - && h["value"] - .as_str() - .is_some_and(|s| s.to_lowercase().starts_with("attachment")) - }); if !filename.is_empty() { output.filenames.push_str(filename); output.filenames.push('\n'); } - if !filename.is_empty() || attachment { + if is_attachment(part) { continue; } let mime = part["mimeType"].as_str().unwrap_or(""); diff --git a/src/local_mail/sync.rs b/src/local_mail/sync.rs index b2d0017ff..d4a54dc02 100644 --- a/src/local_mail/sync.rs +++ b/src/local_mail/sync.rs @@ -358,24 +358,7 @@ pub(super) async fn hydrate_text( for index in 0..part["parts"].as_array().map_or(0, Vec::len) { pending.push(format!("{path}/parts/{index}")); } - let attachment = part["headers"] - .as_array() - .into_iter() - .flatten() - .any(|header| { - header["name"] - .as_str() - .is_some_and(|n| n.eq_ignore_ascii_case("content-disposition")) - && header["value"].as_str().is_some_and(|v| { - v.split(';') - .next() - .unwrap_or("") - .trim() - .eq_ignore_ascii_case("attachment") - }) - }); - if attachment - || !part["filename"].as_str().unwrap_or("").is_empty() + if super::content::is_attachment(part) || !matches!(part["mimeType"].as_str(), Some("text/plain" | "text/html")) || part["body"]["data"].is_string() { diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs index 9f5082879..f6b6ca87e 100644 --- a/src/local_mail/tests.rs +++ b/src/local_mail/tests.rs @@ -104,6 +104,16 @@ fn all_inline_text_parts_are_indexed_and_missing_text_is_explicit() { assert!(!result.body.contains("private-file-text")); assert!(!result.complete); } +#[test] +fn attachment_disposition_uses_the_complete_trimmed_token() { + let resource = json!({"payload":{"mimeType":"multipart/mixed","parts":[ + {"mimeType":"text/plain","headers":[{"name":"content-disposition","value":" \tAttachment ; filename=file.txt"}],"body":{"attachmentId":"external","size":10}}, + {"mimeType":"text/plain","headers":[{"name":"Content-Disposition","value":"attachment-extra"}],"body":{"data":URL_SAFE_NO_PAD.encode("inline body")}} + ]}}); + let result = content::extract(&resource); + assert!(result.complete); + assert_eq!(result.body, "inline body\n"); +} #[cfg(unix)] #[test] fn database_and_sidecar_links_never_touch_their_targets() { From 2a476b498082f6f94ea10a1806391b930ab73f40 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 013/568] Separate local mail worker lifetime and cache restoration --- src/backend/attachments.rs | 21 +++--- src/backend/rpc.rs | 14 ++-- src/cache/query.rs | 115 +++++++++++++++---------------- src/local_mail/mod.rs | 59 ++++++++-------- src/local_mail/provider_tests.rs | 22 +++--- src/local_mail/store.rs | 29 ++++++-- src/local_mail/sync.rs | 76 ++++++++++++-------- src/local_mail/tests.rs | 25 ++++--- src/local_mail/vfs.rs | 4 +- src/mail/send.rs | 15 ++-- src/sync/preload.rs | 10 +-- 11 files changed, 215 insertions(+), 175 deletions(-) diff --git a/src/backend/attachments.rs b/src/backend/attachments.rs index 784cccd11..d1075db47 100644 --- a/src/backend/attachments.rs +++ b/src/backend/attachments.rs @@ -14,10 +14,13 @@ impl Session { return Err("invalid_params"); } let provider = super::reader::registered(account).await?; - let (a, m, p) = (account.to_owned(), id.to_owned(), part.to_owned()); - if let Some(value) = tokio::task::spawn_blocking(move || vault::cached(&a, &m, &p)) - .await - .map_err(|_| "worker_failed")?? + let (cached_account, message_id, attachment_id) = + (account.to_owned(), id.to_owned(), part.to_owned()); + if let Some(value) = tokio::task::spawn_blocking(move || { + vault::cached(&cached_account, &message_id, &attachment_id) + }) + .await + .map_err(|_| "worker_failed")?? { return Ok(value); } @@ -35,15 +38,17 @@ impl Session { "imap" | "outlook" => crate::providers::imap::call("imap.attachment", ¶ms).await?, _ => return Err("attachment_provider_unsupported"), }; - let (a, m, p, saved) = ( + let (cached_account, message_id, attachment_id, saved) = ( account.to_owned(), id.to_owned(), part.to_owned(), value.clone(), ); - tokio::task::spawn_blocking(move || vault::cache(&a, &m, &p, &saved)) - .await - .map_err(|_| "worker_failed")??; + tokio::task::spawn_blocking(move || { + vault::cache(&cached_account, &message_id, &attachment_id, &saved) + }) + .await + .map_err(|_| "worker_failed")??; Ok(value) } pub(super) async fn attachment_request( diff --git a/src/backend/rpc.rs b/src/backend/rpc.rs index 1f49d0a16..6d1820a22 100644 --- a/src/backend/rpc.rs +++ b/src/backend/rpc.rs @@ -64,7 +64,7 @@ pub async fn handle( one(raw.get(), session, deadline).await } -// Detect the control barrier without executing any domain operation. Batch +// Invariant: Detect the control barrier without executing any domain operation. Batch // shutdown drains earlier frames, then completes its entire batch before exit. pub fn requests_quit(frame: &[u8]) -> bool { let Ok(raw) = serde_json::from_slice::>(frame) else { @@ -108,7 +108,7 @@ async fn one( { return (Some(error(Value::Null, -32600, "Invalid Request")), false); } - // An expired queued request must not start a side effect: timeout_at polls + // Invariant: An expired queued request must not start a side effect: timeout_at polls // its future before checking the clock. let began = std::time::Instant::now(); let request_number = super::diagnostics::next(); @@ -133,7 +133,7 @@ async fn one( .await .unwrap_or(Err("request_timed_out")) } else { - // Legacy process operations have their own deadlines. Dropping a + // Invariant: Legacy process operations have their own deadlines. Dropping a // spawn_blocking join cannot cancel a running send; await it so quit // remains a completion barrier and never reports a false cancellation. session.dispatch(&request.method, &request.params).await @@ -174,7 +174,7 @@ mod tests { let (response, quit) = handle(frame, &session, deadline).await; assert!(!quit); assert_eq!(response.unwrap()["error"]["message"], "request_timed_out"); - // An expired call must leave every upload slot available, not merely + // Invariant: An expired call must leave every upload slot available, not merely // return a timeout after executing the immediate upload future. for _ in 0..8 { assert!( @@ -205,7 +205,7 @@ mod tests { ) .await .unwrap(); - // Occupy both decode permits. The uploaded request must expire while + // Invariant: Occupy both decode permits. The uploaded request must expire while // waiting, before consuming its bytes or starting provider work. let permits = session.upload_jobs.acquire_many(2).await.unwrap(); let frame = serde_json::to_vec(&json!({"jsonrpc":"2.0","id":"bounded", @@ -246,7 +246,7 @@ mod tests { }); started.await.unwrap(); let session = crate::backend::Session::default(); - // Unknown methods use the same blocking dispatch path as the HEY + // Invariant: Unknown methods use the same blocking dispatch path as the HEY // process adapter, without invoking a real provider or changing PATH. let frame = br#"{"jsonrpc":"2.0","id":1,"method":"unknown"}"#; let deadline = tokio::time::Instant::now() + Duration::from_millis(20); @@ -257,7 +257,7 @@ mod tests { response = &mut request => Some(response), _ = tokio::time::sleep(Duration::from_millis(60)) => None, }; - // Always release the thread before asserting so a regression does + // Invariant: Always release the thread before asserting so a regression does // not hang Runtime::drop with an unfinished blocking operation. release.send(()).unwrap(); blocker.await.unwrap(); diff --git a/src/cache/query.rs b/src/cache/query.rs index f9173f10d..efc71e1a4 100644 --- a/src/cache/query.rs +++ b/src/cache/query.rs @@ -188,12 +188,17 @@ fn eligible(provider: &str, query: &str, row: &Value) -> bool { } }) } -fn stale(stamp: f64, now: f64, ttl: f64) -> bool { - stamp <= 0.0 || now - stamp > ttl.max(0.0) +fn stale(stored_at_ms: f64, now_ms: f64, ttl_ms: f64) -> bool { + stored_at_ms <= 0.0 || now_ms - stored_at_ms > ttl_ms.max(0.0) } fn date(row: &Value) -> i64 { row["dateMs"].as_i64().unwrap_or(0) } +struct SearchCandidate { + summary: Value, + eligible: bool, + matched: bool, +} fn search(value: &Value, query: &str, provider: &str) -> Vec { let wanted = terms(query); if wanted.is_empty() { @@ -210,32 +215,37 @@ fn search(value: &Value, query: &str, provider: &str) -> Vec { .total_cmp(&a.1["at"].as_f64().unwrap_or(0.0)) }); let mut seen: HashMap = HashMap::new(); - let mut rows: Vec<(Value, bool, bool)> = Vec::new(); + let mut rows: Vec = Vec::new(); for (key, page) in queries { - if let Some(entries) = page["summaries"].as_array() { - for row in entries { - let Some(id) = row["id"].as_str().filter(|id| !id.is_empty()) else { - continue; - }; - let index = if let Some(index) = seen.get(id) { - *index - } else { - let index = rows.len(); - seen.insert(id.into(), index); - rows.push(( - row.clone(), - eligible(provider, source_query(key), row), - false, - )); - index - }; - if rows[index].1 && matches(row, &wanted) { - rows[index].2 = true; - } + let Some(entries) = page["summaries"].as_array() else { + continue; + }; + for row in entries { + let Some(id) = row["id"].as_str().filter(|id| !id.is_empty()) else { + continue; + }; + let index = if let Some(index) = seen.get(id) { + *index + } else { + let index = rows.len(); + seen.insert(id.into(), index); + rows.push(SearchCandidate { + summary: row.clone(), + eligible: eligible(provider, source_query(key), row), + matched: false, + }); + index + }; + if rows[index].eligible && matches(row, &wanted) { + rows[index].matched = true; } } } - let mut found: Vec<_> = rows.into_iter().filter(|r| r.2).map(|r| r.0).collect(); + let mut found: Vec<_> = rows + .into_iter() + .filter(|candidate| candidate.matched) + .map(|candidate| candidate.summary) + .collect(); found.sort_by_key(|row| std::cmp::Reverse(date(row))); found } @@ -323,22 +333,7 @@ impl QueryCache { let shared = self.account(&account).await?; let mut state = shared.lock().await; if !state.loaded { - let p = json!({"accountId":account}); - let root = self.root.clone(); - state.store = tokio::task::spawn_blocking(move || disk(root, "cache.storeRead", &p)) - .await - .map_err(|_| "cache_unavailable")? - .unwrap_or_else(|_| store::empty()); - let expected = account - .split_once(':') - .map(|(_, email)| email) - .unwrap_or(&account); - if state.store["account"] - .as_str() - .is_some_and(|stored| !stored.is_empty() && !stored.eq_ignore_ascii_case(expected)) - { - state.store = store::empty(); - } + state.store = self.restore_store(&account).await?; state.loaded = true; } if !*live.lock().map_err(|_| "cache_unavailable")? { @@ -354,7 +349,7 @@ impl QueryCache { { return Err("cache_store_too_large"); } - // A background snapshot cannot join the UI debounce: that timer can + // Invariant: A background snapshot cannot join the UI debounce: that timer can // outlive its watch, or carry cancelled data into an unrelated UI save. // Hold the same cancellation mutex through the actual atomic disk // commit, then publish only the successfully committed snapshot. @@ -374,6 +369,23 @@ impl QueryCache { state.touched = now(); Ok(()) } + async fn restore_store(&self, account: &str) -> Result { + let params = json!({"accountId":account}); + let root = self.root.clone(); + let saved = tokio::task::spawn_blocking(move || disk(root, "cache.storeRead", ¶ms)) + .await + .map_err(|_| "cache_unavailable")? + .unwrap_or_else(|_| store::empty()); + let expected = account + .split_once(':') + .map(|(_, email)| email) + .unwrap_or(account); + let stored = saved["account"].as_str().unwrap_or(""); + if !stored.is_empty() && !stored.eq_ignore_ascii_case(expected) { + return Ok(store::empty()); + } + Ok(saved) + } async fn account(&self, account: &str) -> Result>> { let mut map = self.accounts.lock().await; if let Some(state) = map.get(account) { @@ -409,23 +421,10 @@ impl QueryCache { state.touched = now(); if method == "cache.queryRestore" { if !state.loaded { - let p = json!({"accountId":account}); - let root = self.root.clone(); - state.store = - match tokio::task::spawn_blocking(move || disk(root, "cache.storeRead", &p)) - .await - { - Ok(Ok(value)) => value, - _ => store::empty(), - }; - let expected = account - .split_once(':') - .map(|(_, email)| email) - .unwrap_or(&account); - let stored = state.store["account"].as_str().unwrap_or(""); - if !stored.is_empty() && !stored.eq_ignore_ascii_case(expected) { - state.store = store::empty(); - } + state.store = self + .restore_store(&account) + .await + .unwrap_or_else(|_| store::empty()); state.loaded = true; } state.generation = self.serial.fetch_add(1, Ordering::Relaxed) + 1; diff --git a/src/local_mail/mod.rs b/src/local_mail/mod.rs index a2ee4dd3b..e09c1f83e 100644 --- a/src/local_mail/mod.rs +++ b/src/local_mail/mod.rs @@ -1,9 +1,9 @@ mod content; mod ipc; #[cfg(test)] -mod recovery_tests; -#[cfg(test)] mod provider_tests; +#[cfg(test)] +mod recovery_tests; mod search; mod store; mod sync; @@ -52,30 +52,10 @@ impl LocalMail { .events .get_or_init(|| tokio::sync::broadcast::channel(128).0) .clone(); - jobs.insert(account,tokio::spawn(async move { - let mut tick = 0u64; - let mut reported = std::time::Instant::now()-std::time::Duration::from_secs(2); - let mut changed = false; - loop { - let answer = sync::step(&store,&gmail,&worker_account,tick).await; - changed |= answer==Ok(true); - if reported.elapsed() >= std::time::Duration::from_secs(1) || answer.is_err() { - let error = answer.as_ref().err().copied().unwrap_or(""); - let _ = sync::disk(&store,move|s|s.write(|db| { - store::set_state(db,"error",error)?; - if error.is_empty() && changed { store::set_state(db,"updated",&chrono::Utc::now().timestamp_millis().to_string())?; } - Ok(()) - })).await; - if let Ok(status) = sync::disk(&store,|s|s.status()).await { - let _ = events.send(json!({"jsonrpc":"2.0","method":"local.changed","params":{"accountId":worker_account,"status":status,"changed":changed}})); - } - reported = std::time::Instant::now(); - changed = false; - } - tick += 1; - tokio::time::sleep(std::time::Duration::from_millis(if answer.is_err() {30_000} else if answer==Ok(false) {5_000} else {25})).await; - } - })); + jobs.insert( + account, + tokio::spawn(sync::watch(store, gmail, worker_account, events)), + ); Ok(()) } pub async fn refresh(&self, account: &str) -> Result<(), &'static str> { @@ -104,9 +84,15 @@ impl LocalMail { } } async fn store(&self, account: &str) -> Result, &'static str> { - self.open_store(account, true).await?.ok_or("local_storage_unavailable") + self.open_store(account, true) + .await? + .ok_or("local_storage_unavailable") } - async fn open_store(&self, account: &str, create: bool) -> Result>, &'static str> { + async fn open_store( + &self, + account: &str, + create: bool, + ) -> Result>, &'static str> { let account = account.to_owned(); let stores = self.stores.clone(); let identity = account.clone(); @@ -131,14 +117,18 @@ impl LocalMail { } else { private_fs::directories_readonly(&dirs.state, &["omamail", "mail", &hash])? }; - let Some(directory) = directory else { return Ok(None) }; + let Some(directory) = directory else { + return Ok(None); + }; let store = Store::open(directory)?; stores.insert(account, store.clone()); Ok(Some(store)) }) .await .map_err(|_| "local_storage_unavailable")??; - if let Some(store) = &store { ipc::listen(store, &identity)?; } + if let Some(store) = &store { + ipc::listen(store, &identity)?; + } Ok(store) } pub(crate) async fn resource( @@ -206,7 +196,14 @@ impl LocalMail { Ok(None) => { let mut resource = match crate::cache::resource::read(account, id).await? { Some(resource) => resource, - None => gmail.call("gmail.read", &json!({"accountId":account,"id":id,"full":true})).await?, + None => { + gmail + .call( + "gmail.read", + &json!({"accountId":account,"id":id,"full":true}), + ) + .await? + } }; sync::hydrate_text(gmail, account, id, &mut resource, true).await?; let store = self.store(account).await?; diff --git a/src/local_mail/provider_tests.rs b/src/local_mail/provider_tests.rs index a23e655cb..28d02ef88 100644 --- a/src/local_mail/provider_tests.rs +++ b/src/local_mail/provider_tests.rs @@ -200,7 +200,7 @@ async fn synchronize(local: &LocalMail, gmail: &gmail::Session) { let store = local.store(ACCOUNT).await.unwrap(); for _ in 0..8 { set(&store, "lastHistory", "0"); - sync::step(&store, gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, gmail, ACCOUNT).await.unwrap(); if store.status().unwrap()["complete"] == true { return; } @@ -228,7 +228,7 @@ async fn cached_mail_survives_auth_failure_and_offline_edits_reconcile_with_prov let store = local.store(ACCOUNT).await.unwrap(); provider.world.lock().unwrap().unauthorized = true; set(&store, "lastHistory", "0"); - assert_eq!(sync::step(&store, &gmail, ACCOUNT, 0).await, Err("gmail_unauthorized")); + assert_eq!(sync::step(&store, &gmail, ACCOUNT).await, Err("gmail_unauthorized")); let requests = provider.world.lock().unwrap().requests.len(); let list = local.call("local.list", &json!({"accountId":ACCOUNT,"query":"in:inbox","limit":50})).await.unwrap(); assert_eq!(list["summaries"].as_array().unwrap().len(), 2); @@ -250,7 +250,7 @@ async fn cached_mail_survives_auth_failure_and_offline_edits_reconcile_with_prov let store = restarted.store(ACCOUNT).await.unwrap(); assert!(store.status().unwrap()["pendingEdits"].as_u64().unwrap() > 0); provider.world.lock().unwrap().unauthorized = false; - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); assert_eq!(store.status().unwrap()["pendingEdits"], 0); let world = provider.world.lock().unwrap(); assert_eq!(world.writes.len(), 1, "rapid reversals must coalesce to one mutation"); @@ -258,7 +258,7 @@ async fn cached_mail_survives_auth_failure_and_offline_edits_reconcile_with_prov drop(world); restarted.call("local.edit", &json!({"accountId":ACCOUNT,"ticket":"deleted","ids":["two"],"addLabelIds":["STARRED"],"removeLabelIds":[]})).await.unwrap(); provider.world.lock().unwrap().messages.remove("two"); - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); assert_eq!(store.status().unwrap()["editConflicts"], 1); let edits = store.edits().unwrap(); let conflict = edits.as_array().unwrap().iter().find(|edit| edit["ticket"] == "deleted").unwrap(); @@ -290,7 +290,7 @@ async fn interrupted_provider_body_keeps_inventory_checkpoint_and_unvisited_mail assert!( tokio::time::timeout( Duration::from_millis(300), - sync::step(&store, &gmail, ACCOUNT, 0) + sync::step(&store, &gmail, ACCOUNT) ) .await .is_err() @@ -346,7 +346,7 @@ async fn interrupted_inventory_and_history_requests_resume_their_saved_page() { .put(&message("unvisited", "kept during partial inventory"), 0) .unwrap(); set(&store, "legacyImported", "true"); - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); assert_eq!( store.read(|db| store::state(db, "page")).unwrap(), "page-two" @@ -358,13 +358,13 @@ async fn interrupted_inventory_and_history_requests_resume_their_saved_page() { if checkpoint == "historyPage" { provider.world.lock().unwrap().paginated_history = true; set(&store, "lastHistory", "0"); - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); } provider.world.lock().unwrap().pause = pause.into(); assert!( tokio::time::timeout( Duration::from_millis(300), - sync::step(&store, &gmail, ACCOUNT, 0) + sync::step(&store, &gmail, ACCOUNT) ) .await .is_err() @@ -394,7 +394,7 @@ async fn interrupted_inventory_and_history_requests_resume_their_saved_page() { expected ); provider.world.lock().unwrap().pause.clear(); - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); } assert!(store.resource("unvisited").unwrap().is_none()); assert_eq!(store.status().unwrap()["complete"], true); @@ -406,7 +406,7 @@ async fn interrupted_inventory_and_history_requests_resume_their_saved_page() { .unwrap(); provider.world.lock().unwrap().expired_history = true; set(&store, "lastHistory", "0"); - sync::step(&store, &gmail, ACCOUNT, 0).await.unwrap(); + sync::step(&store, &gmail, ACCOUNT).await.unwrap(); assert!(store.resource("retained").unwrap().is_some()); assert_eq!(store.status().unwrap()["inventoryComplete"], false); provider.world.lock().unwrap().expired_history = false; @@ -454,7 +454,7 @@ async fn low_space_refuses_body_download_and_preserves_saved_mail() { ); set(&store, "legacyImported", "true"); assert_eq!( - sync::step(&store, &gmail, ACCOUNT, 0).await, + sync::step(&store, &gmail, ACCOUNT).await, Err("local_disk_low") ); assert!(store.resource("saved").unwrap().is_some()); diff --git a/src/local_mail/store.rs b/src/local_mail/store.rs index 5fe38761a..2dc5c4523 100644 --- a/src/local_mail/store.rs +++ b/src/local_mail/store.rs @@ -13,6 +13,27 @@ use std::{ }; type Result = std::result::Result; +pub(super) struct ClaimedChanges { + pub sequence: i64, + pub additions: Vec, + pub removals: Vec, +} +impl ClaimedChanges { + pub(super) fn satisfied_by(&self, resource: &Value) -> Result { + let current = resource["labelIds"] + .as_array() + .ok_or("gmail_invalid_response")?; + Ok(self + .additions + .iter() + .all(|label| current.iter().any(|value| value == label)) + && self + .removals + .iter() + .all(|label| !current.iter().any(|value| value == label))) + } +} + pub(super) struct Store { writer: Mutex, readers: Vec>, @@ -447,7 +468,7 @@ impl Store { Ok(()) }) } - pub(super) fn claim_changes(&self, id: &str) -> Result> { + pub(super) fn claim_changes(&self, id: &str) -> Result> { self.write(|db| { let mut statement=sql(db.prepare("SELECT sequence,additions,removals FROM edits WHERE id=?1 AND state IN ('queued','sending') ORDER BY sequence"))?; let rows=sql(sql(statement.query_map([id],|r|Ok((r.get::<_,i64>(0)?,r.get::<_,String>(1)?,r.get::<_,String>(2)?))))?.collect::>>())?; @@ -457,10 +478,10 @@ impl Store { for value in labels(&decode(add)?) {target.insert(value,true);} for value in labels(&decode(remove)?) {target.insert(value,false);} } - let add=target.iter().filter(|(_,add)|**add).map(|(label,_)|label).collect::>(); - let remove=target.iter().filter(|(_,add)|!**add).map(|(label,_)|label).collect::>(); + let add=target.iter().filter(|(_,add)|**add).map(|(label,_)|label.clone()).collect::>(); + let remove=target.iter().filter(|(_,add)|!**add).map(|(label,_)|label.clone()).collect::>(); sql(db.execute("UPDATE edits SET state='sending' WHERE id=?1 AND sequence<=?2 AND state='queued'",params![id,last]))?; - Ok(Some((*last,json!(add),json!(remove)))) + Ok(Some(ClaimedChanges { sequence: *last, additions: add, removals: remove })) }) } } diff --git a/src/local_mail/sync.rs b/src/local_mail/sync.rs index d4a54dc02..2f6b41b68 100644 --- a/src/local_mail/sync.rs +++ b/src/local_mail/sync.rs @@ -19,11 +19,51 @@ fn valid_id(value: &Value) -> Result<&str> { .filter(|v| !v.is_empty() && v.len() <= 1024 && !v.chars().any(char::is_control)) .ok_or("gmail_invalid_response") } +pub(super) async fn watch( + store: Arc, + gmail: Arc, + account: String, + events: tokio::sync::broadcast::Sender, +) { + let mut reported = std::time::Instant::now() - std::time::Duration::from_secs(2); + let mut changed = false; + loop { + let answer = step(&store, &gmail, &account).await; + changed |= answer == Ok(true); + if reported.elapsed() >= std::time::Duration::from_secs(1) || answer.is_err() { + let error = answer.as_ref().err().copied().unwrap_or(""); + let _ = disk(&store, move |store| { + store.write(|db| { + set_state(db, "error", error)?; + if error.is_empty() && changed { + set_state( + db, + "updated", + &chrono::Utc::now().timestamp_millis().to_string(), + )?; + } + Ok(()) + }) + }) + .await; + if let Ok(status) = disk(&store, |store| store.status()).await { + let _ = events.send(json!({"jsonrpc":"2.0","method":"local.changed","params":{"accountId":account,"status":status,"changed":changed}})); + } + reported = std::time::Instant::now(); + changed = false; + } + let delay_ms = match answer { + Err(_) => 30_000, + Ok(false) => 5_000, + Ok(true) => 25, + }; + tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await; + } +} pub(super) async fn step( store: &Arc, gmail: &gmail::Session, account: &str, - _tick: u64, ) -> Result { if deliver_edit(store, gmail, account).await? { return Ok(true); @@ -408,27 +448,16 @@ async fn deliver_edit(store: &Arc, gmail: &gmail::Session, account: &str) answer => answer?, }; let claim = id.clone(); - let Some((sequence, add, remove)) = disk(store, move |s| s.claim_changes(&claim)).await? else { + let Some(changes) = disk(store, move |s| s.claim_changes(&claim)).await? else { return Ok(true); }; - let current = before["labelIds"] - .as_array() - .ok_or("gmail_invalid_response")?; - let satisfied = add - .as_array() - .ok_or("local_storage_corrupt")? - .iter() - .all(|v| current.contains(v)) - && remove - .as_array() - .ok_or("local_storage_corrupt")? - .iter() - .all(|v| !current.contains(v)); + let sequence = changes.sequence; + let satisfied = changes.satisfied_by(&before)?; if !satisfied { let delivery = gmail .call_settled( "gmail.modify", - &json!({"accountId":account,"id":id,"addLabelIds":add,"removeLabelIds":remove}), + &json!({"accountId":account,"id":id,"addLabelIds":changes.additions,"removeLabelIds":changes.removals}), ) .await; if let Err(error @ ("gmail_forbidden" | "invalid_params")) = delivery { @@ -450,20 +479,7 @@ async fn deliver_edit(store: &Arc, gmail: &gmail::Session, account: &str) .replica_call(account, "minimal", &json!({"id":id})) .await? }; - let current = after["labelIds"] - .as_array() - .ok_or("gmail_invalid_response")?; - if !add - .as_array() - .ok_or("local_storage_corrupt")? - .iter() - .all(|v| current.contains(v)) - || !remove - .as_array() - .ok_or("local_storage_corrupt")? - .iter() - .all(|v| !current.contains(v)) - { + if !changes.satisfied_by(&after)? { return Err("local_edit_not_confirmed"); } disk(store,move|s|s.write(|db| { diff --git a/src/local_mail/tests.rs b/src/local_mail/tests.rs index f6b6ca87e..63ab2c980 100644 --- a/src/local_mail/tests.rs +++ b/src/local_mail/tests.rs @@ -10,17 +10,26 @@ pub(super) fn directory() -> std::path::PathBuf { let name = format!( "magpie-local-{}-{}-{}", std::process::id(), - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(), SERIAL.fetch_add(1, Ordering::Relaxed) ); - crate::platform::private_fs::directories(&parent, &[&name], true).unwrap().unwrap(); + crate::platform::private_fs::directories(&parent, &[&name], true) + .unwrap() + .unwrap(); parent.join(name) } pub(super) fn open_directory(path: &std::path::Path) -> File { let path = path.canonicalize().unwrap(); - crate::platform::private_fs::directories(path.parent().unwrap(), &[path.file_name().unwrap().to_str().unwrap()], false) - .unwrap() - .unwrap() + crate::platform::private_fs::directories( + path.parent().unwrap(), + &[path.file_name().unwrap().to_str().unwrap()], + false, + ) + .unwrap() + .unwrap() } pub(super) fn message(id: &str, text: &str) -> Value { json!({"id":id,"threadId":"thread","labelIds":["INBOX","UNREAD"],"internalDate":"1700000000000", @@ -164,9 +173,9 @@ fn coalescing_preserves_latest_intent_and_undo_stops_before_claim() { .edit("read", &["one".into()], &[], &["UNREAD".into()]) .unwrap(); store.cancel_edit("read").unwrap(); - let (_, add, remove) = store.claim_changes("one").unwrap().unwrap(); - assert_eq!(add, json!([])); - assert_eq!(remove, json!(["STARRED"])); + let changes = store.claim_changes("one").unwrap().unwrap(); + assert!(changes.additions.is_empty()); + assert_eq!(changes.removals, ["STARRED"]); assert_eq!(store.cancel_edit("star"), Err("local_edit_already_started")); assert_eq!( store.resource("one").unwrap().unwrap()["labelIds"], diff --git a/src/local_mail/vfs.rs b/src/local_mail/vfs.rs index c3b25e796..177435d29 100644 --- a/src/local_mail/vfs.rs +++ b/src/local_mail/vfs.rs @@ -32,7 +32,7 @@ pub(super) struct Vfs { name: CString, root: Arc, } -// The registration and callbacks are stable allocations; mutable shared state +// Invariant: The registration and callbacks are stable allocations; mutable shared state // is behind Locks. Connections hold an Arc until sqlite3_close completes. unsafe impl Send for Vfs {} unsafe impl Sync for Vfs {} @@ -147,7 +147,7 @@ unsafe extern "C" fn open( Ok(None) if flags & SQLITE_OPEN_CREATE != 0 => { match fs::create_private(&root.directory, name) { Ok(file) => { - // Private creation excludes other Windows writers. Reopen + // Invariant: Private creation excludes other Windows writers. Reopen // under the owner lease so our SQLite connections can share it. drop(file); match fs::regular(&root.directory, name, true) { diff --git a/src/mail/send.rs b/src/mail/send.rs index 47878900d..90774d36f 100644 --- a/src/mail/send.rs +++ b/src/mail/send.rs @@ -6,7 +6,7 @@ use base64::{ }; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::{collections::HashSet, fs::File, future::Future, io::Read, path::Path, pin::Pin}; +use std::{collections::HashSet, future::Future, io::Read, pin::Pin}; pub(crate) const MAX_BODY: usize = 16 * 1024 * 1024; const MAX_HEADER: usize = 8192; @@ -29,7 +29,7 @@ pub(crate) struct Prepared { } fn header(value: &str) -> Result<()> { - // Inputs are decoded text. The composer owns encoded words; accepting one + // Invariant: Inputs are decoded text. The composer owns encoded words; accepting one // here lets a downstream MIME decoder change a previewed name or envelope. if value.len() > MAX_HEADER || value.chars().any(char::is_control) || value.contains("=?") { Err("mail_send_invalid_header") @@ -117,12 +117,6 @@ fn recipients(values: &[String], seen: &mut HashSet) -> Result Result { - crate::platform::private_fs::open_external(path) -} - fn attachment(input: &super::AttachmentInput, total: &mut usize) -> Result { header(&input.name)?; if input.name.is_empty() @@ -132,7 +126,7 @@ fn attachment(input: &super::AttachmentInput, total: &mut usize) -> Result Result Result = summaries.into_iter().map(|(summary, _)| summary).collect(); current(&live)?; queries.prefetch(&account,inbox(&account),limit,&json!({"summaries":summaries,"estimate":page["estimate"],"nextPageToken":page["nextPageToken"]}),live.clone()).await?; - // Full resources are fetched one at a time per account. Across all + // Invariant: Full resources are fetched one at a time per account. Across all // accounts only two preload network requests may consume transport slots. for (id, size) in ids.into_iter().zip(sizes) { current(&live)?; From 3d623aaf24b402d6aed4c10983daf5a2fbdbc3d7 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 014/568] Fix reply address structure and overview evidence validation --- src/agent/overview.rs | 49 ++++++++++--- src/message/content.rs | 156 ++++++++++++++++++++++++++--------------- 2 files changed, 138 insertions(+), 67 deletions(-) diff --git a/src/agent/overview.rs b/src/agent/overview.rs index 78d3ef6a5..b4f713d63 100644 --- a/src/agent/overview.rs +++ b/src/agent/overview.rs @@ -114,7 +114,7 @@ pub fn validate(answer: &Value, messages: &Value) -> Result let text = row["text"] .as_str() .filter(|s| { - !s.is_empty() + !s.trim().is_empty() && s.chars().count() <= 140 && !s.chars().any(char::is_control) && !s.contains(['<', '>']) @@ -132,17 +132,17 @@ pub fn validate(answer: &Value, messages: &Value) -> Result .replace(['\u{2018}', '\u{2019}'], "'") .replace(['\u{201c}', '\u{201d}'], "\"") }; - if !normalized(&source.to_string()).contains(&normalized(evidence)) { - // JSON escaping can alter quoted source. Check original text fields too. - let found = source + let evidence = normalized(evidence); + let supported = !evidence.is_empty() + && source .as_object() .into_iter() - .flat_map(|v| v.values()) - .filter_map(Value::as_str) - .any(|v| normalized(v).contains(&normalized(evidence))); - if !found { - return Err("overview_unsupported_claim"); - } + .flat_map(|fields| fields.iter()) + .filter(|(key, _)| key.as_str() != "id") + .filter_map(|(_, value)| value.as_str()) + .any(|value| normalized(value).contains(&evidence)); + if !supported { + return Err("overview_unsupported_claim"); } out.push(json!({"id":id,"text":text})); } @@ -154,6 +154,35 @@ mod tests { use super::*; use std::collections::VecDeque; + #[test] + fn review_overview_must_have_visible_text() { + let messages = json!([{"id":"a","body":"Payment received: R780."}]); + let answer = + json!({"overviews":[{"id":"a","text":" ","evidence":"Payment received: R780."}]}); + assert_eq!( + validate(&answer, &messages), + Err("overview_invalid_response") + ); + } + + #[test] + fn review_evidence_must_quote_nonempty_original_text() { + let messages = json!([{"id":"a","subject":"Invoice","body":"Payment received: R780."}]); + for evidence in [" \t\n ", "\"body\":", "R780.\",\"id\":\"a"] { + let answer = + json!({"overviews":[{"id":"a","text":"Pay R500 immediately","evidence":evidence}]}); + assert!( + validate(&answer, &messages).is_err(), + "accepted {evidence:?}" + ); + } + let answer = json!({"overviews":[{"id":"a","text":"R780 payment confirmed","evidence":"Payment received: R780."}]}); + assert_eq!( + validate(&answer, &messages).unwrap()[0]["text"], + "R780 payment confirmed" + ); + } + #[test] fn evidence_accepts_typographic_quotes_but_not_changed_claims() { let messages = json!([{"id":"a","body":"The project’s build failed in four seconds."}]); diff --git a/src/message/content.rs b/src/message/content.rs index 88a63aab8..f87261012 100644 --- a/src/message/content.rs +++ b/src/message/content.rs @@ -149,64 +149,54 @@ pub fn decoded_header(value: &str) -> String { out.push_str(&value[end..]); out } +fn structural_addresses(value: &str) -> Option { + let source = format!("From: {value}"); + let (header, consumed) = mailparse::parse_header(source.as_bytes()).ok()?; + if consumed != source.len() { + return None; + } + mailparse::addrparse_header(&header).ok() +} + +fn mailbox(single: &mailparse::SingleInfo) -> Value { + let email = single.addr.trim(); + if email.chars().any(char::is_control) { + return json!({"name":"","email":"","display":""}); + } + let name = single + .display_name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| email.split_once('@').map_or("", |(local, _)| local)); + json!({"name":name,"email":email,"display":if name.is_empty(){email}else{name}}) +} + pub fn address(value: &str) -> Value { - let raw = decoded_header(value); - let raw = raw.trim(); - let mut name = String::new(); - let email = if raw.ends_with('>') { - if let Some(at) = raw.rfind('<') { - let phrase = raw[..at].trim(); - let phrase = phrase - .strip_prefix('"') - .and_then(|s| s.strip_suffix('"')) - .unwrap_or(phrase); - let mut chars = phrase.chars(); - while let Some(c) = chars.next() { - name.push(if c == '\\' { - chars.next().unwrap_or(c) - } else { - c - }); - } - name = name.trim().into(); - raw[at + 1..raw.len() - 1].trim().to_owned() - } else { - raw.into() - } - } else { - raw.into() - }; - if name.is_empty() - && let Some((local, _)) = email.split_once('@') - && !local.is_empty() - { - name = local.into(); + if let Some(single) = structural_addresses(value).and_then(|list| list.extract_single_info()) { + return mailbox(&single); } - json!({"name":name,"email":email,"display":if name.is_empty(){&email}else{&name}}) + let display = decoded_header(value).trim().to_owned(); + json!({"name":display,"email":"","display":display}) } + pub fn addresses(value: &str) -> Vec { - let mut quotes = false; - let mut angled = false; - let mut start = 0; - let mut result = Vec::new(); - for (i, c) in value.char_indices() { - match c { - '"' => quotes = !quotes, - '<' => angled = true, - '>' => angled = false, - _ => {} - } - if c == ',' && !quotes && !angled { - if !value[start..i].trim().is_empty() { - result.push(address(&value[start..i])); - } - start = i + 1; - } - } - if !value[start..].trim().is_empty() { - result.push(address(&value[start..])); - } - result + let Some(parsed) = structural_addresses(value) else { + return Vec::new(); + }; + parsed + .iter() + .flat_map(|entry| match entry { + mailparse::MailAddr::Single(single) => std::slice::from_ref(single), + mailparse::MailAddr::Group(group) => group.addrs.as_slice(), + }) + .map(mailbox) + .filter(|entry| { + entry["email"] + .as_str() + .is_some_and(|email| !email.is_empty()) + }) + .collect() } /// Legacy list snippet text semantics, separate from the reader's HTML tree walk. pub fn html_to_text(value: &str) -> String { @@ -350,10 +340,14 @@ pub fn summarize(message: &Value, now: i64) -> Result { } fn has_attachments(message: &Value) -> bool { fn walk(part: &Value, depth: usize, budget: &mut usize) -> bool { - if depth > 12 || *budget == 0 { return false; } + if depth > 12 || *budget == 0 { + return false; + } *budget -= 1; - attachment(part) || part["parts"].as_array().is_some_and(|parts| - parts.iter().any(|part| walk(part, depth + 1, budget))) + attachment(part) + || part["parts"] + .as_array() + .is_some_and(|parts| parts.iter().any(|part| walk(part, depth + 1, budget))) } message["hasAttachments"] == true || walk(&message["payload"], 0, &mut 4000) } @@ -602,6 +596,54 @@ pub fn request(method: &str, params: &Value) -> Result { } } +#[cfg(test)] +mod address_tests { + use super::*; + use base64::{Engine as _, engine::general_purpose::STANDARD}; + + #[test] + fn review_encoded_display_text_never_becomes_a_reply_recipient() { + let encoded = format!( + "=?UTF-8?B?{}?=", + STANDARD.encode("Alias ") + ); + let message = json!({"payload":{"headers":[ + {"name":"From","value":"Actual "}, + {"name":"Reply-To","value":encoded}, + {"name":"To","value":encoded} + ]}}); + let summary = summarize(&message, 0).unwrap(); + assert_eq!(summary["from"]["email"], "actual@example.test"); + assert_eq!(summary["replyTo"]["email"], ""); + assert_eq!(summary["to"], json!([])); + assert!( + address(&encoded)["display"] + .as_str() + .unwrap() + .contains("Alias") + ); + } + + #[test] + fn review_structural_mailboxes_survive_encoded_names_and_groups() { + let encoded = format!( + "=?UTF-8?B?{}?=", + STANDARD.encode("Alias , Team") + ); + let parsed = address(&format!("{encoded} ")); + assert_eq!(parsed["email"], "actual@example.test"); + assert_eq!(parsed["name"], "Alias , Team"); + let group = addresses("Team: one@example.test, \"Two, Example\" ;"); + assert_eq!( + group + .iter() + .map(|entry| entry["email"].as_str().unwrap()) + .collect::>(), + ["one@example.test", "two@example.test"] + ); + } +} + #[cfg(test)] mod date_tests { use super::*; From 0a904578d455edd0350fc1cb4d01e52202f8d3e5 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 015/568] Fix Unix process group ownership until descendant cleanup --- src/process/async_run.rs | 65 +++++++++++++++++++++++++++++++++++--- src/process/mod.rs | 3 ++ src/process/tests.rs | 67 ++++++++++++++++++++++++++++++++++++++++ src/process/unix.rs | 51 +++++++++++++++++++++++++++--- 4 files changed, 176 insertions(+), 10 deletions(-) diff --git a/src/process/async_run.rs b/src/process/async_run.rs index f866957d4..f7e456dad 100644 --- a/src/process/async_run.rs +++ b/src/process/async_run.rs @@ -1,11 +1,14 @@ //! Async, bounded, cancellation-safe transport for official provider tools. -use std::{process::Stdio, time::Duration}; -use tokio::{ - io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, - process::{Child, Command}, -}; +#[cfg(windows)] +use std::process::Stdio; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +#[cfg(windows)] +use tokio::process::{Child, Command}; +#[cfg(windows)] struct ChildReaper(Option); +#[cfg(windows)] impl Drop for ChildReaper { fn drop(&mut self) { let Some(mut child) = self.0.take() else { @@ -55,6 +58,7 @@ pub async fn run( ) -> Result { run_with_stderr_limit(program, args, input, timeout, limit, limit.min(65536)).await } +#[cfg(windows)] pub(super) async fn run_with_stderr_limit( program: &str, args: &[String], @@ -112,6 +116,57 @@ pub(super) async fn run_with_stderr_limit( result } +#[cfg(unix)] +pub(super) async fn run_with_stderr_limit( + program: &str, + args: &[String], + input: &[u8], + timeout: Duration, + limit: usize, + stderr_limit: usize, +) -> Result { + use tokio::net::unix::pipe::{Receiver, Sender}; + use tokio::signal::unix::{SignalKind, signal}; + if input.len() > limit { + return Err("process_input_too_large"); + } + let mut exits = signal(SignalKind::child()).map_err(|_| "process_wait_failed")?; + let mut child = super::spawn_managed(program, args)?; + let mut stdin = Sender::from_owned_fd(child.take_stdin().ok_or("process_pipe_failed")?.into()) + .map_err(|_| "process_pipe_failed")?; + let stdout = Receiver::from_owned_fd(child.take_stdout().ok_or("process_pipe_failed")?.into()) + .map_err(|_| "process_pipe_failed")?; + let stderr = Receiver::from_owned_fd(child.take_stderr().ok_or("process_pipe_failed")?.into()) + .map_err(|_| "process_pipe_failed")?; + tokio::time::timeout(timeout, async { + let write = async { + stdin + .write_all(input) + .await + .map_err(|_| "process_input_failed")?; + drop(stdin); + Ok(()) + }; + let wait = async { + loop { + if let Some(status) = child.try_wait().map_err(|_| "process_wait_failed")? { + return Ok(status); + } + exits.recv().await.ok_or("process_wait_failed")?; + } + }; + let (_, stdout, stderr, status) = + tokio::try_join!(write, read(stdout, limit), read(stderr, stderr_limit), wait)?; + Ok(Output { + success: status.success(), + stdout, + stderr, + }) + }) + .await + .unwrap_or(Err("process_timed_out")) +} + #[cfg(all(test, unix))] mod tests { use super::*; diff --git a/src/process/mod.rs b/src/process/mod.rs index abcf62fd5..aafff0780 100644 --- a/src/process/mod.rs +++ b/src/process/mod.rs @@ -68,6 +68,9 @@ impl ManagedChild { self.child.stderr.take() } pub fn try_wait(&mut self) -> std::io::Result> { + #[cfg(unix)] + return self.tree.try_wait(&mut self.child); + #[cfg(windows)] self.child.try_wait() } diff --git a/src/process/tests.rs b/src/process/tests.rs index 957e1a2c3..64d9502c3 100644 --- a/src/process/tests.rs +++ b/src/process/tests.rs @@ -158,6 +158,73 @@ fn invalid_input_is_refused_before_process_creation() { Err("process_input_too_large") ); } + +#[cfg(target_os = "linux")] +#[test] +fn review_observing_exit_reserves_group_identity_until_cleanup() { + let mut child = spawn_managed(python(), &args("pass")).unwrap(); + let pid = child.id(); + let deadline = Instant::now() + Duration::from_secs(5); + while child.try_wait().unwrap().is_none() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(2)); + } + let mut info = unsafe { std::mem::zeroed::() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + pid, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + assert_eq!( + result, 0, + "exit observation released the PID before group cleanup" + ); + assert_eq!(unsafe { info.si_pid() }, pid as i32); + child.terminate_tree(Duration::from_secs(1)).unwrap(); + drop(child); + assert_eq!(unsafe { libc::kill(pid as i32, 0) }, -1); +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn review_async_transport_reserves_exited_leader_until_pipe_cleanup() { + let root = std::env::temp_dir().join(format!("omamail-process-leader-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let ready = root.join("ready"); + let mut argv = args( + "import os,sys,time,pathlib\npid=os.fork()\nif pid:\n pathlib.Path(sys.argv[1]).write_text(str(os.getpid()))\n os._exit(0)\ntime.sleep(30)", + ); + argv.push(ready.to_str().unwrap().into()); + let task = tokio::spawn(async move { + async_run::run(python(), &argv, b"", Duration::from_secs(15), 1024).await + }); + let deadline = Instant::now() + Duration::from_secs(5); + let pid = loop { + if let Some(pid) = std::fs::read_to_string(&ready) + .ok() + .and_then(|value| value.parse::().ok()) + { + break pid; + } + assert!(Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(2)).await; + }; + tokio::time::sleep(Duration::from_millis(100)).await; + let reserved = std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| { + stat.split_once(") ") + .is_some_and(|(_, fields)| fields.starts_with('Z')) + }); + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + std::fs::remove_dir_all(root).unwrap(); + assert!( + reserved, + "the async process driver reaped the group leader before cleanup" + ); +} #[tokio::test] async fn blocked_stdin_cannot_defeat_the_deadline() { let input = vec![42; 1024 * 1024]; diff --git a/src/process/unix.rs b/src/process/unix.rs index 89d44c2b2..7975254e6 100644 --- a/src/process/unix.rs +++ b/src/process/unix.rs @@ -229,16 +229,57 @@ mod unix_tests { pub(super) fn configure(command: &mut Command) { command.process_group(0); } -pub(super) struct Tree(u32); +pub(super) struct Tree { + pid: u32, + active: std::cell::Cell, +} impl Tree { pub(super) fn for_child(child: &std::process::Child) -> Result { - Ok(Self(child.id())) + Ok(Self { + pid: child.id(), + active: std::cell::Cell::new(true), + }) } - pub(super) fn for_async_child(child: &tokio::process::Child) -> Result { - Ok(Self(child.id().ok_or("process_unavailable")?)) + pub(super) fn try_wait( + &self, + child: &mut std::process::Child, + ) -> std::io::Result> { + use std::os::unix::process::ExitStatusExt; + if !self.active.get() { + return child.try_wait(); + } + // Reaping would let this PID identify an unrelated process group before cleanup. + let mut info = unsafe { std::mem::zeroed::() }; + if unsafe { + libc::waitid( + libc::P_PID, + self.pid, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + } != 0 + { + return Err(std::io::Error::last_os_error()); + } + #[cfg(target_os = "linux")] + let (pid, status) = unsafe { (info.si_pid(), info.si_status()) }; + #[cfg(target_os = "macos")] + let (pid, status) = (info.si_pid, info.si_status); + if pid == 0 { + return Ok(None); + } + let status = match info.si_code { + libc::CLD_EXITED => status << 8, + libc::CLD_DUMPED => status | 0x80, + _ => status, + }; + Ok(Some(std::process::ExitStatus::from_raw(status))) } pub(super) fn terminate(&self) -> Result<(), super::Error> { - if unsafe { libc::kill(-(self.0 as i32), libc::SIGKILL) } == 0 + if !self.active.replace(false) { + return Ok(()); + } + if unsafe { libc::kill(-(self.pid as i32), libc::SIGKILL) } == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { Ok(()) From dd611bb2200c4594f4227706a0469aca54b5f6ba Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 016/568] Name rendering records and narrow agent session access --- src/agent/codex.rs | 187 ++++++++++++----------- src/agent/opencode.rs | 4 +- src/calendar/reads.rs | 21 ++- src/message/html/tree.rs | 311 +++++++++++++++++++++++---------------- 4 files changed, 295 insertions(+), 228 deletions(-) diff --git a/src/agent/codex.rs b/src/agent/codex.rs index 9a1f47761..fb376720c 100644 --- a/src/agent/codex.rs +++ b/src/agent/codex.rs @@ -8,14 +8,100 @@ pub struct Profile(toml_edit::DocumentMut); fn setting(key: &str, item: &toml_edit::Item) -> Result { match key { "requires_openai_auth" | "supports_websockets" => item.as_bool().map(Into::into), - "request_max_retries" | "stream_max_retries" | "stream_idle_timeout_ms" => { - item.as_integer().filter(|n| *n >= 0).map(Into::into) - } + "request_max_retries" | "stream_max_retries" | "stream_idle_timeout_ms" => item + .as_integer() + .filter(|number| *number >= 0) + .map(Into::into), _ => item.as_str().map(Into::into), } .ok_or("agent_config_invalid") } +fn configure_provider( + command: &mut std::process::Command, + name: &str, + item: &toml_edit::Item, +) -> Result<(), &'static str> { + if name.is_empty() + || !name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + { + return Err("agent_config_invalid"); + } + let provider = item.as_table_like().ok_or("agent_config_invalid")?; + let mut headers = toml_edit::InlineTable::new(); + for (key, item) in provider.iter() { + let prefix = format!("model_providers.{name}"); + if key == "experimental_bearer_token" { + let token = item.as_str().ok_or("agent_config_invalid")?; + let variable = format!( + "OMAMAIL_CODEX_TOKEN_{}", + name.bytes() + .map(|byte| format!("{byte:02x}")) + .collect::() + ); + command.env(&variable, token).args([ + "-c", + &format!("{prefix}.env_key={}", serde_json::json!(variable)), + ]); + } else if key == "http_headers" { + for (header, value) in item.as_table_like().ok_or("agent_config_invalid")?.iter() { + let variable = format!( + "OMAMAIL_CODEX_HEADER_{}_{}", + name.bytes() + .map(|byte| format!("{byte:02x}")) + .collect::(), + header + .bytes() + .map(|byte| format!("{byte:02x}")) + .collect::() + ); + command.env(&variable, value.as_str().ok_or("agent_config_invalid")?); + headers.insert(header, variable.into()); + } + } else if key == "env_http_headers" { + for (header, value) in item.as_table_like().ok_or("agent_config_invalid")?.iter() { + headers.insert(header, value.as_str().ok_or("agent_config_invalid")?.into()); + } + } else if [ + "name", + "base_url", + "env_key", + "wire_api", + "requires_openai_auth", + "supports_websockets", + "request_max_retries", + "stream_max_retries", + "stream_idle_timeout_ms", + ] + .contains(&key) + { + if key == "base_url" { + let url = reqwest::Url::parse(item.as_str().ok_or("agent_config_invalid")?) + .map_err(|_| "agent_config_invalid")?; + if !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err("agent_config_invalid"); + } + } + command.args(["-c", &format!("{prefix}.{key}={}", setting(key, item)?)]); + } else { + return Err("agent_config_invalid"); + } + } + if !headers.is_empty() { + command.args([ + "-c", + &format!("model_providers.{name}.env_http_headers={headers}"), + ]); + } + Ok(()) +} + impl Profile { pub fn configure(&self, command: &mut std::process::Command) -> Result<(), &'static str> { let source = &self.0; @@ -37,96 +123,17 @@ impl Profile { } if let Some(providers) = source .get("model_providers") - .and_then(|v| v.as_table_like()) + .and_then(|value| value.as_table_like()) { for (name, item) in providers.iter() { - if name.is_empty() - || !name - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') - { - return Err("agent_config_invalid"); - } - let provider = item.as_table_like().ok_or("agent_config_invalid")?; - let mut headers = toml_edit::InlineTable::new(); - for (key, item) in provider.iter() { - let prefix = format!("model_providers.{name}"); - if key == "experimental_bearer_token" { - let token = item.as_str().ok_or("agent_config_invalid")?; - let variable = format!( - "OMAMAIL_CODEX_TOKEN_{}", - name.bytes().map(|b| format!("{b:02x}")).collect::() - ); - command.env(&variable, token).args([ - "-c", - &format!("{prefix}.env_key={}", serde_json::json!(variable)), - ]); - } else if key == "http_headers" { - for (header, value) in - item.as_table_like().ok_or("agent_config_invalid")?.iter() - { - let variable = format!( - "OMAMAIL_CODEX_HEADER_{}_{}", - name.bytes().map(|b| format!("{b:02x}")).collect::(), - header - .bytes() - .map(|b| format!("{b:02x}")) - .collect::() - ); - command.env(&variable, value.as_str().ok_or("agent_config_invalid")?); - headers.insert(header, variable.into()); - } - } else if key == "env_http_headers" { - for (header, value) in - item.as_table_like().ok_or("agent_config_invalid")?.iter() - { - headers.insert( - header, - value.as_str().ok_or("agent_config_invalid")?.into(), - ); - } - } else if [ - "name", - "base_url", - "env_key", - "wire_api", - "requires_openai_auth", - "supports_websockets", - "request_max_retries", - "stream_max_retries", - "stream_idle_timeout_ms", - ] - .contains(&key) - { - if key == "base_url" { - let url = - reqwest::Url::parse(item.as_str().ok_or("agent_config_invalid")?) - .map_err(|_| "agent_config_invalid")?; - if !url.username().is_empty() - || url.password().is_some() - || url.query().is_some() - || url.fragment().is_some() - { - return Err("agent_config_invalid"); - } - } - command.args(["-c", &format!("{prefix}.{key}={}", setting(key, item)?)]); - } else { - return Err("agent_config_invalid"); - } - } - if !headers.is_empty() { - command.args([ - "-c", - &format!("model_providers.{name}.env_http_headers={headers}"), - ]); - } + configure_provider(command, name, item)?; } } + if let Some(value) = source .get("features") - .and_then(|f| f.get("enable_request_compression")) - .and_then(|v| v.as_bool()) + .and_then(|features| features.get("enable_request_compression")) + .and_then(|value| value.as_bool()) { command.args([ "-c", @@ -139,7 +146,7 @@ impl Profile { super::storage::check_id(id)?; let home = std::env::var_os("CODEX_HOME") .map(PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".codex"))) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".codex"))) .ok_or("agent_config_unavailable")?; let mut bytes = String::new(); match File::open(home.join("config.toml")) { @@ -148,7 +155,7 @@ impl Profile { .read_to_string(&mut bytes) .map_err(|_| "agent_config_invalid")?; } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return Err("agent_config_unavailable"), } if bytes.len() > 1024 * 1024 { @@ -176,7 +183,7 @@ impl Profile { // Transport formatting is not authority and is needed by local providers. if let Some(value) = source .get("features") - .and_then(|f| f.get("enable_request_compression")) + .and_then(|features| features.get("enable_request_compression")) { selected["features"]["enable_request_compression"] = value.clone(); } diff --git a/src/agent/opencode.rs b/src/agent/opencode.rs index 576283f36..aab106402 100644 --- a/src/agent/opencode.rs +++ b/src/agent/opencode.rs @@ -84,8 +84,8 @@ fn secret() -> Result { pub struct Lease { _stream: UnixStream, - pub url: String, - pub password: String, + url: String, + password: String, } impl Lease { pub async fn release(&mut self) -> Result<()> { diff --git a/src/calendar/reads.rs b/src/calendar/reads.rs index 2d1497eb3..264eb425d 100644 --- a/src/calendar/reads.rs +++ b/src/calendar/reads.rs @@ -8,7 +8,11 @@ use std::{ }; struct Entry { key: [u8; 32], - value: tokio::sync::Mutex>, + value: tokio::sync::Mutex>, +} +struct Snapshot { + created: Instant, + value: Value, } pub(crate) struct Reads { entries: Mutex>>, @@ -37,7 +41,7 @@ impl Reads { Sha256::digest(serde_json::to_vec(params).map_err(|_| "invalid_params")?).into(); let entry = { let mut entries = self.entries.lock().map_err(|_| "session_failed")?; - if let Some(index) = entries.iter().position(|e| e.key == key) { + if let Some(index) = entries.iter().position(|entry| entry.key == key) { let entry = entries.remove(index).unwrap(); entries.push_back(entry.clone()); entry @@ -58,10 +62,10 @@ impl Reads { } }; let mut saved = entry.value.lock().await; - if let Some((at, value, _)) = saved.as_ref() { - if at.elapsed() < Duration::from_secs(5) { - return Ok(value.clone()); - } + if let Some(snapshot) = saved.as_ref() + && snapshot.created.elapsed() < Duration::from_secs(5) + { + return Ok(snapshot.value.clone()); } let _permit = self.slots.acquire().await.map_err(|_| "session_failed")?; let value = fetch().await?; @@ -69,7 +73,10 @@ impl Reads { .map_err(|_| "calendar_invalid_response")? .len(); if bytes <= 4 * 1024 * 1024 { - *saved = Some((Instant::now(), value.clone(), bytes)); + *saved = Some(Snapshot { + created: Instant::now(), + value: value.clone(), + }); } Ok(value) } diff --git a/src/message/html/tree.rs b/src/message/html/tree.rs index 03aa14e17..985f6cd47 100644 --- a/src/message/html/tree.rs +++ b/src/message/html/tree.rs @@ -61,32 +61,36 @@ impl Node { } } pub fn root() -> Self { - let mut n = Self::element(""); - n.kind = "root".into(); - n + let mut node = Self::element(""); + node.kind = "root".into(); + node } pub fn text(text: &str) -> Self { - let mut n = Self::element(""); - n.kind = "text".into(); - n.text = text.into(); - n + let mut node = Self::element(""); + node.kind = "text".into(); + node.text = text.into(); + node } pub fn attr(&self, name: &str) -> &str { self.attrs .iter() - .find(|a| a.name == name) - .and_then(|a| a.value.as_deref()) + .find(|attribute| attribute.name == name) + .and_then(|attribute| attribute.value.as_deref()) .unwrap_or("") } pub fn has(&self, name: &str) -> bool { - self.attrs.iter().any(|a| a.name == name) + self.attrs.iter().any(|attribute| attribute.name == name) } pub fn remove(&mut self, name: &str) { - self.attrs.retain(|a| a.name != name) + self.attrs.retain(|attribute| attribute.name != name) } pub fn set(&mut self, name: &str, value: &str) { - if let Some(a) = self.attrs.iter_mut().find(|a| a.name == name) { - a.value = Some(value.into()) + if let Some(attribute) = self + .attrs + .iter_mut() + .find(|attribute| attribute.name == name) + { + attribute.value = Some(value.into()) } else { self.attrs.push(Attr { name: name.into(), @@ -115,85 +119,116 @@ pub fn void(name: &str) -> bool { | "keygen" ) } -fn space(b: u8) -> bool { - matches!(b, b' ' | b'\t' | b'\r' | b'\n' | 12) +fn space(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | 12) } -fn name(b: u8) -> bool { - b.is_ascii_alphanumeric() || matches!(b, b':' | b'-' | b'_' | b'.') +fn name(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b':' | b'-' | b'_' | b'.') } -fn tag(s: &str, start: usize) -> Option<(Node, bool, usize, bool)> { - let b = s.as_bytes(); - let mut i = start + 1; - let closing = b.get(i) == Some(&b'/'); +struct Tag { + node: Node, + closing: bool, + end: usize, + terminated: bool, +} + +fn tag(source: &str, start: usize) -> Option { + let bytes = source.as_bytes(); + let mut cursor = start + 1; + let closing = bytes.get(cursor) == Some(&b'/'); if closing { - i += 1 + cursor += 1 } - if !b.get(i).is_some_and(u8::is_ascii_alphabetic) { + if !bytes.get(cursor).is_some_and(u8::is_ascii_alphabetic) { return None; } - let begin = i; - while i < b.len() && name(b[i]) { - i += 1 + let token_start = cursor; + while cursor < bytes.len() && name(bytes[cursor]) { + cursor += 1 } - let mut n = Node::element(&s[begin..i].to_ascii_lowercase()); - while i < b.len() { - while i < b.len() && space(b[i]) { - i += 1 + let mut node = Node::element(&source[token_start..cursor].to_ascii_lowercase()); + while cursor < bytes.len() { + while cursor < bytes.len() && space(bytes[cursor]) { + cursor += 1 } - if i == b.len() { + if cursor == bytes.len() { break; } - if b[i] == b'>' { - return Some((n, closing, i + 1, true)); + if bytes[cursor] == b'>' { + return Some(Tag { + node, + closing, + end: cursor + 1, + terminated: true, + }); } - if b[i] == b'/' { - n.self_closing = b.get(i + 1) == Some(&b'>'); - i += 1; + if bytes[cursor] == b'/' { + node.self_closing = bytes.get(cursor + 1) == Some(&b'>'); + cursor += 1; continue; } - let begin = i; - while i < b.len() && !space(b[i]) && !matches!(b[i], b'=' | b'>' | b'/') { - i += 1 + let token_start = cursor; + while cursor < bytes.len() + && !space(bytes[cursor]) + && !matches!(bytes[cursor], b'=' | b'>' | b'/') + { + cursor += 1 } - if i == begin { - i += 1; + if cursor == token_start { + cursor += 1; continue; } - let key = s[begin..i].to_ascii_lowercase(); - while i < b.len() && space(b[i]) { - i += 1 + let attribute_name = source[token_start..cursor].to_ascii_lowercase(); + while cursor < bytes.len() && space(bytes[cursor]) { + cursor += 1 } let mut value = None; - if b.get(i) == Some(&b'=') { - i += 1; - while i < b.len() && space(b[i]) { - i += 1 + if bytes.get(cursor) == Some(&b'=') { + cursor += 1; + while cursor < bytes.len() && space(bytes[cursor]) { + cursor += 1 } - if b.get(i).is_some_and(|c| matches!(c, b'\'' | b'"')) { - let quote = b[i]; - i += 1; - let begin = i; - while i < b.len() && b[i] != quote { - i += 1 + if bytes + .get(cursor) + .is_some_and(|byte| matches!(byte, b'\'' | b'"')) + { + let quote = bytes[cursor]; + cursor += 1; + let token_start = cursor; + while cursor < bytes.len() && bytes[cursor] != quote { + cursor += 1 } - value = Some(s[begin..i].into()); - if i < b.len() { - i += 1 + value = Some(source[token_start..cursor].into()); + if cursor < bytes.len() { + cursor += 1 } } else { - let begin = i; - while i < b.len() && !space(b[i]) && b[i] != b'>' { - i += 1 + let token_start = cursor; + while cursor < bytes.len() && !space(bytes[cursor]) && bytes[cursor] != b'>' { + cursor += 1 } - value = Some(s[begin..i].into()) + value = Some(source[token_start..cursor].into()) } } - n.attrs.push(Attr { name: key, value }); - if n.attrs.len() > 1024 { - return Some((n, closing, b.len(), false)); + node.attrs.push(Attr { + name: attribute_name, + value, + }); + if node.attrs.len() > 1024 { + return Some(Tag { + node, + closing, + end: bytes.len(), + terminated: false, + }); } } - Some((n, closing, b.len(), false)) + Some(Tag { + node, + closing, + end: bytes.len(), + terminated: false, + }) } fn implied(new: &str, old: &str) -> bool { match new { @@ -208,8 +243,8 @@ fn implied(new: &str, old: &str) -> bool { } } fn finish(stack: &mut Vec) { - let n = stack.pop().unwrap(); - stack.last_mut().unwrap().children.push(n) + let node = stack.pop().unwrap(); + stack.last_mut().unwrap().children.push(node) } fn emitted(count: &mut usize, nodes: usize) -> Result<(), &'static str> { *count = count.checked_add(nodes).ok_or("html_too_complex")?; @@ -218,21 +253,21 @@ fn emitted(count: &mut usize, nodes: usize) -> Result<(), &'static str> { } Ok(()) } -pub fn parse(s: &str) -> Result { - if s.len() > MAX_INPUT { +pub fn parse(source: &str) -> Result { + if source.len() > MAX_INPUT { return Err("html_too_large"); } let mut stack = vec![Node::root()]; let mut at = 0; let mut count = 1; - while at < s.len() { - let Some(offset) = s[at..].find('<') else { + while at < source.len() { + let Some(offset) = source[at..].find('<') else { emitted(&mut count, 1)?; stack .last_mut() .unwrap() .children - .push(Node::text(&s[at..])); + .push(Node::text(&source[at..])); break; }; let open = at + offset; @@ -242,77 +277,94 @@ pub fn parse(s: &str) -> Result { .last_mut() .unwrap() .children - .push(Node::text(&s[at..open])) + .push(Node::text(&source[at..open])) } - if s[open..].starts_with("") - .map_or(s.len(), |v| open + 4 + v + 3); + .map_or(source.len(), |offset| open + 4 + offset + 3); continue; } - if s[open..].starts_with("').map_or(s.len(), |v| open + v + 1); + if source[open..].starts_with("') + .map_or(source.len(), |offset| open + offset + 1); continue; } - let Some((mut n, closing, end, terminated)) = tag(s, open) else { + let Some(Tag { + node: mut node, + closing, + end, + terminated, + }) = tag(source, open) + else { emitted(&mut count, 1)?; stack.last_mut().unwrap().children.push(Node::text("<")); at = open + 1; continue; }; at = end; - if n.attrs.len() > 1024 { + if node.attrs.len() > 1024 { return Err("html_too_complex"); } if !terminated { break; } if closing { - if let Some(i) = stack.iter().rposition(|v| v.name == n.name) { - while stack.len() > i && stack.len() > 1 { + if let Some(index) = stack + .iter() + .rposition(|ancestor| ancestor.name == node.name) + { + while stack.len() > index && stack.len() > 1 { finish(&mut stack) } } continue; } - while stack.len() > 1 && implied(&n.name, &stack.last().unwrap().name) { + while stack.len() > 1 && implied(&node.name, &stack.last().unwrap().name) { finish(&mut stack) } - if matches!(n.name.as_str(), "script" | "style" | "textarea" | "title") && !n.self_closing { - let needle = format!("')) + .is_some_and(|byte| space(*byte) || matches!(byte, b'/' | b'>')) { found = Some(pos); break; } search = pos + 1 } - let stop = found.unwrap_or(s.len()); + let stop = found.unwrap_or(source.len()); emitted(&mut count, 2)?; - let mut raw = Node::text(&s[at..stop]); + let mut raw = Node::text(&source[at..stop]); raw.raw = true; - n.children.push(raw); + node.children.push(raw); at = found - .and_then(|pos| tag(s, pos).map(|v| v.2)) - .unwrap_or(s.len()); - stack.last_mut().unwrap().children.push(n); + .and_then(|pos| tag(source, pos).map(|tag| tag.end)) + .unwrap_or(source.len()); + stack.last_mut().unwrap().children.push(node); continue; } emitted(&mut count, 1)?; - if void(&n.name) || n.self_closing || stack.len() >= MAX_DEPTH { - stack.last_mut().unwrap().children.push(n) + if void(&node.name) || node.self_closing || stack.len() >= MAX_DEPTH { + stack.last_mut().unwrap().children.push(node) } else { - stack.push(n) + stack.push(node) } } while stack.len() > 1 { @@ -320,52 +372,53 @@ pub fn parse(s: &str) -> Result { } Ok(stack.pop().unwrap()) } -pub fn escape_text(s: &str) -> String { - s.replace('&', "&") +pub fn escape_text(source: &str) -> String { + source + .replace('&', "&") .replace('<', "<") .replace('>', ">") } -pub fn serialize(n: &Node) -> Result { - let mut out = String::new(); - write(n, &mut out)?; - Ok(out) +pub fn serialize(node: &Node) -> Result { + let mut output = String::new(); + write(node, &mut output)?; + Ok(output) } -fn write(n: &Node, out: &mut String) -> Result<(), &'static str> { - if n.kind == "text" { - out.push_str(&n.text.replace('<', "<").replace('>', ">")) +fn write(node: &Node, output: &mut String) -> Result<(), &'static str> { + if node.kind == "text" { + output.push_str(&node.text.replace('<', "<").replace('>', ">")) } else { - if n.kind != "root" { - out.push('<'); - out.push_str(&n.name); - for a in &n.attrs { - out.push(' '); - out.push_str(&a.name); - if let Some(v) = &a.value { - out.push_str("=\""); - out.push_str(&v.replace('"', """)); - out.push('"') + if node.kind != "root" { + output.push('<'); + output.push_str(&node.name); + for attribute in &node.attrs { + output.push(' '); + output.push_str(&attribute.name); + if let Some(value) = &attribute.value { + output.push_str("=\""); + output.push_str(&value.replace('"', """)); + output.push('"') } } - if void(&n.name) || n.self_closing { - out.push_str(if n.self_closing { "/>" } else { ">" }); - return if out.len() > MAX_OUTPUT { + if void(&node.name) || node.self_closing { + output.push_str(if node.self_closing { "/>" } else { ">" }); + return if output.len() > MAX_OUTPUT { Err("html_output_too_large") } else { Ok(()) }; } - out.push('>') + output.push('>') } - for c in &n.children { - write(c, out)? + for child in &node.children { + write(child, output)? } - if n.kind != "root" { - out.push_str("') + if node.kind != "root" { + output.push_str("') } } - if out.len() > MAX_OUTPUT { + if output.len() > MAX_OUTPUT { Err("html_output_too_large") } else { Ok(()) From f0a2648136c71273ae98d59f0fc66d96be3d4cf0 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:55:45 +0100 Subject: [PATCH 017/568] Fix recurrence arithmetic for extreme calendar ranges --- src/calendar/parse/recurrence.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/calendar/parse/recurrence.rs b/src/calendar/parse/recurrence.rs index fd6d6d3ed..aca592576 100644 --- a/src/calendar/parse/recurrence.rs +++ b/src/calendar/parse/recurrence.rs @@ -72,11 +72,13 @@ fn starts(event: &Value, from: i64, to: i64) -> Result> { let calendar = ics::parse(&format!("BEGIN:VCALENDAR\r\n{zones}\r\nEND:VCALENDAR"))?; let mut current = base; if count == 0 { - let skip = (from.saturating_sub(172_800_000) - base.and_utc().timestamp_millis()) + let skip = from + .saturating_sub(172_800_000) + .saturating_sub(base.and_utc().timestamp_millis()) .div_euclid(86_400_000) .max(0); current = current - .checked_add_signed(Duration::days(skip)) + .checked_add_signed(Duration::try_days(skip).ok_or("calendar_invalid_response")?) .ok_or("calendar_invalid_response")?; } let mut out = Vec::new(); @@ -199,3 +201,19 @@ pub(super) fn expand(events: Vec, from: i64, to: i64) -> Result Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 018/568] Clarify provider operations and account intent records --- src/account/intents.rs | 282 +++++++++++----------- src/account/model.rs | 264 +++++++++++--------- src/account/model_tests.rs | 2 +- src/account/storage.rs | 2 +- src/account/unified.rs | 2 +- src/contacts/mod.rs | 230 ++++++++++-------- src/providers/domain.rs | 46 ++-- src/providers/gmail.rs | 8 +- src/providers/gmail_credentials.rs | 25 +- src/providers/gmail_http.rs | 52 ++-- src/providers/gmail_http_runtime_tests.rs | 25 +- src/providers/gmail_queue.rs | 5 +- src/providers/gmail_quota.rs | 2 +- src/providers/gmail_resources.rs | 1 - src/providers/gmail_tests.rs | 7 +- src/providers/gmail_writes.rs | 4 +- src/providers/hey.rs | 130 +++++----- src/providers/hey_access.rs | 4 +- src/providers/hey_actions.rs | 8 +- src/providers/outlook.rs | 4 +- 20 files changed, 588 insertions(+), 515 deletions(-) diff --git a/src/account/intents.rs b/src/account/intents.rs index ca7930e52..eec2a8378 100644 --- a/src/account/intents.rs +++ b/src/account/intents.rs @@ -26,6 +26,36 @@ struct Context { bytes: usize, view_bytes: usize, } +impl Context { + fn replace_view(&mut self, view: &Value) -> Result<()> { + let bytes = serde_json::to_vec(view) + .map_err(|_| "intent_view_invalid")? + .len(); + if bytes > MAX_VIEW { + return Err("intent_limit"); + } + self.bytes = self.bytes.saturating_sub(self.view_bytes) + bytes; + self.view_bytes = bytes; + self.view = view.clone(); + Ok(()) + } +} + +impl State { + fn check_context_bytes(&self, key: &(String, String), bytes: usize) -> Result<()> { + let retained: usize = self + .contexts + .iter() + .filter(|(existing, _)| *existing != key) + .map(|(_, context)| context.bytes) + .sum(); + if retained.saturating_add(bytes) > 32 * 1024 * 1024 { + return Err("intent_limit"); + } + Ok(()) + } +} + #[derive(Clone)] struct Edit { token: u64, @@ -41,12 +71,12 @@ struct Item { failed: bool, targets: Vec, } -fn field(p: &Value, k: &str) -> Result { - let s = p[k].as_str().ok_or("intent_invalid")?; - if s.is_empty() || s.len() > 8192 || s.contains('\0') { +fn field(params: &Value, key: &str) -> Result { + let value = params[key].as_str().ok_or("intent_invalid")?; + if value.is_empty() || value.len() > 8192 || value.contains('\0') { return Err("intent_invalid"); } - Ok(s.to_owned()) + Ok(value.to_owned()) } fn list(v: &Value) -> Vec { v.as_array().cloned().unwrap_or_default() @@ -92,12 +122,12 @@ fn descriptor(p: &Value) -> Value { } out } -fn same_descriptor(a: &Value, b: &Value) -> bool { - let mut a = a.clone(); - let mut b = b.clone(); - a.as_object_mut().unwrap().remove("readerThread"); - b.as_object_mut().unwrap().remove("readerThread"); - a == b +fn same_descriptor(first: &Value, second: &Value) -> bool { + let mut first = first.clone(); + let mut second = second.clone(); + first.as_object_mut().unwrap().remove("readerThread"); + second.as_object_mut().unwrap().remove("readerThread"); + first == second } fn selected(view: &mut Value, current: &Value) { if current.get("selectedId").is_none() { @@ -170,7 +200,7 @@ fn apply_one(view: &mut Value, desc: &Value, message: &str) -> Result { json!({"rowId":message,"targets":[message],"change":change,"removed":false,"survives":true,"detached":true}), ); } - Err(e) => return Err(e), + Err(error) => return Err(error), }; if outcome["refused"] == true { return Ok(outcome); @@ -183,16 +213,18 @@ fn apply_one(view: &mut Value, desc: &Value, message: &str) -> Result { ("messages", outcome["removed"] == true), ("previewMessages", outcome["updated"]["unread"] != true), ] { - if let Some(list) = view[key].as_array_mut() { - if removed { - list.retain(|entry| entry["id"] != outcome["rowId"]); - } else { - for entry in list { - if entry["id"] == outcome["rowId"] { - *entry = outcome["updated"].clone(); - } - } - } + let Some(list) = view[key].as_array_mut() else { + continue; + }; + if removed { + list.retain(|entry| entry["id"] != outcome["rowId"]); + continue; + } + for entry in list + .iter_mut() + .filter(|entry| entry["id"] == outcome["rowId"]) + { + *entry = outcome["updated"].clone(); } } if !view["memberSummaries"].is_object() { @@ -248,16 +280,16 @@ fn replay(context: &Context) -> Result { match apply_one(&mut view, &edit.descriptor, &item.id) { Ok(_) => (), Err("model_message_missing") => (), - Err(e) => return Err(e), + Err(error) => return Err(error), } } } Ok(view) } impl IntentStore { - pub fn call(&self, p: &Value) -> Result { - let account = field(p, "accountId")?; - let operation = id(&p["operation"]); + pub fn call(&self, params: &Value) -> Result { + let account = field(params, "accountId")?; + let operation = id(¶ms["operation"]); let mut state = self.state.lock().map_err(|_| "intent_unavailable")?; if operation == "reset" { if !state.generations.contains_key(&account) && state.generations.len() >= 1024 { @@ -270,30 +302,35 @@ impl IntentStore { .unwrap_or(0) .checked_add(1) .ok_or("intent_limit")?; - state.contexts.retain(|(a, _), _| a != &account); + state + .contexts + .retain(|(account_id, _), _| account_id != &account); state.generations.insert(account, generation); return Ok(json!({"generation":generation,"cleared":true})); } if operation == "clear" { let generation = state.generations.get(&account).copied().unwrap_or(0); - if p["generation"].as_u64().ok_or("intent_invalid")? != generation { + if params["generation"].as_u64().ok_or("intent_invalid")? != generation { return Err("intent_stale"); } - state.contexts.retain(|(a, q), _| { - a != &account || p["query"].as_str().is_some_and(|wanted| wanted != q) + state.contexts.retain(|(account_id, query_key), _| { + account_id != &account + || params["query"] + .as_str() + .is_some_and(|wanted| wanted != query_key) }); return Ok(json!({"cleared":true,"generation":generation})); } - let query = field(p, "query")?; + let query = field(params, "query")?; let key = (account.clone(), query); - let generation = p["generation"].as_u64().ok_or("intent_invalid")?; + let generation = params["generation"].as_u64().ok_or("intent_invalid")?; let prior = state.generations.get(&account).copied().unwrap_or(0); if state.generations.contains_key(&account) && generation != prior { return Err("intent_stale"); } if operation == "coalesce" { - let newer = p["token"].as_u64().ok_or("intent_invalid")?; - let older = p["intoToken"].as_u64().ok_or("intent_invalid")?; + let newer = params["token"].as_u64().ok_or("intent_invalid")?; + let older = params["intoToken"].as_u64().ok_or("intent_invalid")?; let mut context = state.contexts.get(&key).ok_or("intent_unknown")?.clone(); if context.generation != generation { return Err("intent_stale"); @@ -301,17 +338,17 @@ impl IntentStore { let old = context .edits .iter() - .position(|e| e.token == older) + .position(|edit| edit.token == older) .ok_or("intent_unknown")?; let new = context .edits .iter() - .position(|e| e.token == newer) + .position(|edit| edit.token == newer) .ok_or("intent_unknown")?; let ids: Vec<_> = context.edits[old] .items .iter() - .map(|i| i.id.as_str()) + .map(|item| item.id.as_str()) .collect(); if old >= new || context.edits[old].settled @@ -324,11 +361,13 @@ impl IntentStore { != context.edits[new] .items .iter() - .map(|i| i.id.as_str()) + .map(|item| item.id.as_str()) .collect::>() - || context.edits[old + 1..new] - .iter() - .any(|e| e.items.iter().any(|i| ids.contains(&i.id.as_str()))) + || context.edits[old + 1..new].iter().any(|edit| { + edit.items + .iter() + .any(|item| ids.contains(&item.id.as_str())) + }) { return Err("intent_coalesce_invalid"); } @@ -336,36 +375,20 @@ impl IntentStore { context.bytes = context.bytes.saturating_sub(removed.bytes); let mut view = replay(&context)?; selected(&mut view, &context.view); - let bytes = serde_json::to_vec(&view) - .map_err(|_| "intent_view_invalid")? - .len(); - if bytes > MAX_VIEW { - return Err("intent_limit"); - } - context.bytes = context.bytes.saturating_sub(context.view_bytes) + bytes; - let other_bytes: usize = state - .contexts - .iter() - .filter(|(k, _)| **k != key) - .map(|(_, c)| c.bytes) - .sum(); - if other_bytes.saturating_add(context.bytes) > 32 * 1024 * 1024 { - return Err("intent_limit"); - } - context.view_bytes = bytes; - context.view = view.clone(); + context.replace_view(&view)?; + state.check_context_bytes(&key, context.bytes)?; state.contexts.insert(key, context); return Ok(json!({"view":view,"token":older,"generation":generation})); } if operation == "settle" { - if serde_json::to_vec(&p["view"]) + if serde_json::to_vec(¶ms["view"]) .map_err(|_| "intent_view_invalid")? .len() > MAX_VIEW { return Err("intent_limit"); } - let token = p["token"].as_u64().ok_or("intent_invalid")?; + let token = params["token"].as_u64().ok_or("intent_invalid")?; let mut context = state.contexts.get(&key).ok_or("intent_unknown")?.clone(); if context.generation != generation { return Err("intent_stale"); @@ -373,15 +396,15 @@ impl IntentStore { let edit = context .edits .iter_mut() - .find(|e| e.token == token) + .find(|edit| edit.token == token) .ok_or("intent_unknown")?; if edit.settled { return Err("intent_already_settled"); } - let failed = list(&p["failedIds"]); + let failed = list(¶ms["failedIds"]); if failed .iter() - .any(|f| !edit.items.iter().any(|i| json!(i.row) == *f)) + .any(|failed_row| !edit.items.iter().any(|item| json!(item.row) == *failed_row)) { return Err("intent_invalid"); } @@ -392,38 +415,22 @@ impl IntentStore { let targets: Vec<_> = edit .items .iter() - .filter(|i| !i.failed) - .flat_map(|i| i.targets.clone()) + .filter(|item| !item.failed) + .flat_map(|item| item.targets.clone()) .collect(); let mut view = replay(&context)?; selected( &mut view, - if p["view"].is_object() { - &p["view"] + if params["view"].is_object() { + ¶ms["view"] } else { &context.view }, ); - let bytes = serde_json::to_vec(&view) - .map_err(|_| "intent_view_invalid")? - .len(); - if bytes > MAX_VIEW { - return Err("intent_limit"); - } - context.bytes = context.bytes.saturating_sub(context.view_bytes) + bytes; - let other_bytes: usize = state - .contexts - .iter() - .filter(|(k, _)| **k != key) - .map(|(_, c)| c.bytes) - .sum(); - if other_bytes.saturating_add(context.bytes) > 32 * 1024 * 1024 { - return Err("intent_limit"); - } - context.view_bytes = bytes; - context.view = view.clone(); - // Settled successors remain ordered until every predecessor settles. - if context.edits.iter().all(|e| e.settled) { + context.replace_view(&view)?; + state.check_context_bytes(&key, context.bytes)?; + // Invariant: Settled successors remain ordered until every predecessor settles. + if context.edits.iter().all(|edit| edit.settled) { state.contexts.remove(&key); } else { state.contexts.insert(key, context); @@ -433,7 +440,7 @@ impl IntentStore { if operation != "begin" { return Err("intent_invalid"); } - validate_view(&p["view"])?; + validate_view(¶ms["view"])?; if !state.generations.contains_key(&account) && state.generations.len() >= 1024 { return Err("intent_limit"); } @@ -443,69 +450,74 @@ impl IntentStore { if state .contexts .get(&key) - .is_some_and(|c| c.edits.len() >= MAX_EDITS) + .is_some_and(|context| context.edits.len() >= MAX_EDITS) { return Err("intent_limit"); } - let desc = descriptor(p); - let action = id(&desc["action"]); + let action_descriptor = descriptor(params); + let action = id(&action_descriptor["action"]); let capability = model::capability(action); - if !capability.is_empty() && desc["capabilities"][capability] != true { + if !capability.is_empty() && action_descriptor["capabilities"][capability] != true { return Ok(json!({"refused":true,"capability":capability})); } - if model::changes(action, id(&desc["sourceLabelId"])).is_null() + if model::changes(action, id(&action_descriptor["sourceLabelId"])).is_null() && !matches!(action, "trash" | "untrash") { return Err("intent_invalid"); } - let mut ids = if p["allRead"] == true { - list(&p["view"]["messages"]) + let mut ids = if params["allRead"] == true { + list(¶ms["view"]["messages"]) .into_iter() - .filter(|r| r["unread"] == true) - .map(|r| r["id"].clone()) + .filter(|row| row["unread"] == true) + .map(|row| row["id"].clone()) .collect() } else { - list(&p["ids"]) + list(¶ms["ids"]) }; - if ids.len() > 1000 || ids.iter().any(|v| id(v).is_empty() || id(v).len() > 8192) { + if ids.len() > 1000 + || ids + .iter() + .any(|value| id(value).is_empty() || id(value).len() > 8192) + { return Err("intent_invalid"); } let mut seen = HashSet::new(); - ids.retain(|v| seen.insert(id(v).to_owned())); + ids.retain(|value| seen.insert(id(value).to_owned())); let context = state.contexts.get(&key); let mut view = context - .map(|c| c.view.clone()) - .unwrap_or_else(|| p["view"].clone()); + .map(|context| context.view.clone()) + .unwrap_or_else(|| params["view"].clone()); let mut base = context - .map(|c| c.base.clone()) - .unwrap_or_else(|| p["view"].clone()); - if let Some(members) = p["view"]["memberSummaries"].as_object() { + .map(|context| context.base.clone()) + .unwrap_or_else(|| params["view"].clone()); + if let Some(members) = params["view"]["memberSummaries"].as_object() { for (key, member) in members { - if base["memberSummaries"].get(key).is_none() { - if !base["memberSummaries"].is_object() { - base["memberSummaries"] = json!({}); - } - if !view["memberSummaries"].is_object() { - view["memberSummaries"] = json!({}); - } - base["memberSummaries"][key] = member.clone(); - view["memberSummaries"][key] = member.clone(); + if base["memberSummaries"].get(key).is_some() { + continue; + } + if !base["memberSummaries"].is_object() { + base["memberSummaries"] = json!({}); } + if !view["memberSummaries"].is_object() { + view["memberSummaries"] = json!({}); + } + base["memberSummaries"][key] = member.clone(); + view["memberSummaries"][key] = member.clone(); } } - view["selectedThread"] = p["view"]["selectedThread"].clone(); - selected(&mut view, &p["view"]); + view["selectedThread"] = params["view"]["selectedThread"].clone(); + selected(&mut view, ¶ms["view"]); let mut items = Vec::new(); let mut targets = Vec::new(); let mut targets_of = json!({}); let mut rows = Vec::new(); let mut removed = Vec::new(); - let mut invalidates = desc["opaqueQuery"] == true; + let mut invalidates = action_descriptor["opaqueQuery"] == true; for message in ids { - let outcome = match apply_one(&mut view, &desc, id(&message)) { - Ok(v) => v, + let outcome = match apply_one(&mut view, &action_descriptor, id(&message)) { + Ok(value) => value, Err("model_message_missing") => continue, - Err(e) => return Err(e), + Err(error) => return Err(error), }; let row = id(&outcome["rowId"]).to_owned(); if row.is_empty() { @@ -544,15 +556,15 @@ impl IntentStore { if view_bytes > MAX_VIEW { return Err("intent_limit"); } - let edit_bytes = serde_json::to_vec(&desc) + let edit_bytes = serde_json::to_vec(&action_descriptor) .map_err(|_| "intent_invalid")? .len() + items .iter() - .map(|i| { - i.id.len() - + i.row.len() - + serde_json::to_vec(&i.targets).map_or(MAX_VIEW, |v| v.len()) + .map(|item| { + item.id.len() + + item.row.len() + + serde_json::to_vec(&item.targets).map_or(MAX_VIEW, |value| value.len()) }) .sum::(); let base_bytes = serde_json::to_vec(&base) @@ -564,26 +576,18 @@ impl IntentStore { let context_bytes = state .contexts .get(&key) - .map(|c| c.edits.iter().map(|e| e.bytes).sum::() + base_bytes) + .map(|context| context.edits.iter().map(|edit| edit.bytes).sum::() + base_bytes) .unwrap_or(base_bytes) + view_bytes + edit_bytes; - let total = state - .contexts - .iter() - .filter(|(k, _)| **k != key) - .map(|(_, c)| c.bytes) - .sum::(); - if total.saturating_add(context_bytes) > 32 * 1024 * 1024 { - return Err("intent_limit"); - } + state.check_context_bytes(&key, context_bytes)?; state.serial = state.serial.checked_add(1).ok_or("intent_limit")?; state.generations.insert(account, generation); let token = state.serial; let context = state.contexts.entry(key).or_insert_with(|| Context { generation, - base: p["view"].clone(), - view: p["view"].clone(), + base: params["view"].clone(), + view: params["view"].clone(), edits: Vec::new(), bytes: 0, view_bytes: 0, @@ -594,13 +598,13 @@ impl IntentStore { context.view_bytes = view_bytes; context.edits.push(Edit { token, - descriptor: desc.clone(), + descriptor: action_descriptor.clone(), items, settled: false, bytes: edit_bytes, }); Ok( - json!({"token":token,"generation":generation,"view":view,"targets":targets,"targetsOf":targets_of,"rows":rows,"expanded":targets.len()>rows.len(),"change":model::changes(action,id(&desc["sourceLabelId"])),"invalidatesPage":invalidates,"removedIds":removed,"refused":false,"capability":capability}), + json!({"token":token,"generation":generation,"view":view,"targets":targets,"targetsOf":targets_of,"rows":rows,"expanded":targets.len()>rows.len(),"change":model::changes(action,id(&action_descriptor["sourceLabelId"])),"invalidatesPage":invalidates,"removedIds":removed,"refused":false,"capability":capability}), ) } } diff --git a/src/account/model.rs b/src/account/model.rs index b9e8ec737..1bc28a12c 100644 --- a/src/account/model.rs +++ b/src/account/model.rs @@ -4,16 +4,16 @@ use serde_json::{Value, json}; use std::collections::{HashMap, HashSet}; fn block(row: &Value) -> Value { - let b = &row["thread"]; - if !b.is_object() { + let thread = &row["thread"]; + if !thread.is_object() { return Value::Null; } - let ids: Vec<_> = rows(&b["memberIds"]) + let ids: Vec<_> = rows(&thread["memberIds"]) .iter() - .map(|v| text(v).trim().to_owned()) - .filter(|s| !s.is_empty()) + .map(|value| text(value).trim().to_owned()) + .filter(|member_id| !member_id.is_empty()) .collect(); - json!({"id":text(&b["id"]).trim(),"count":ids.len(),"memberIds":ids,"unread":b["unread"] == true,"flagged":b["flagged"] == true}) + json!({"id":text(&thread["id"]).trim(),"count":ids.len(),"memberIds":ids,"unread":thread["unread"] == true,"flagged":thread["flagged"] == true}) } pub fn action_scope(action: &str) -> &'static str { if [ @@ -99,7 +99,7 @@ pub(crate) fn action_targets_checked( .ok_or("mail_action_invalid_target")? .as_array() .ok_or("mail_action_invalid_target")?; - // An absent thread means this is an individual row. A present, empty + // Invariant: An absent thread means this is an individual row. A present, empty // member list is authoritative: provider applicability removed every // member, so restoring the representative would mutate the wrong mail. if members.is_empty() { @@ -497,10 +497,10 @@ fn fuzzy(query: &str, hay: &str) -> i64 { score } -pub fn apply(p: &Value) -> Result { - if p["operation"] == "batch" { - let calls = rows(&p["calls"]); - if calls.len() > 128 || calls.iter().any(|c| c["operation"] == "batch") { +pub fn apply(params: &Value) -> Result { + if params["operation"] == "batch" { + let calls = rows(¶ms["calls"]); + if calls.len() > 128 || calls.iter().any(|call| call["operation"] == "batch") { return Err("model_batch_invalid"); } return calls @@ -509,13 +509,13 @@ pub fn apply(p: &Value) -> Result { .collect::, _>>() .map(Value::Array); } - if p["operation"] == "action" { - return action(p); + if params["operation"] == "action" { + return action(params); } - let args = rows(&p["args"]); - // Declarative rebase copies a baseline into later entries. Check the + let args = rows(¶ms["args"]); + // Invariant: Declarative rebase copies a baseline into later entries. Check the // worst-case expansion before cloning that baseline repeatedly. - let operation = text(&p["operation"]); + let operation = text(¶ms["operation"]); let replay_entries = if operation == "rebaseIntents" { args.first().unwrap_or(&Value::Null) } else if operation == "intentsSettled" { @@ -538,25 +538,25 @@ pub fn apply(p: &Value) -> Result { { return Err("model_output_too_large"); } - if args.iter().any(|a| rows(a).len() > 100_000) { + if args.iter().any(|argument| rows(argument).len() > 100_000) { return Err("model_too_many_rows"); } - let a = |n: usize| args.get(n).unwrap_or(&Value::Null); - let s = |n| text(a(n)); - Ok(match text(&p["operation"]).as_str() { - "fuzzyScore" => json!(fuzzy(&s(0), &s(1))), + let argument = |index: usize| args.get(index).unwrap_or(&Value::Null); + let string_argument = |index| text(argument(index)); + Ok(match text(¶ms["operation"]).as_str() { + "fuzzyScore" => json!(fuzzy(&string_argument(0), &string_argument(1))), "filterRows" => { - let typed = s(1); + let typed = string_argument(1); let typed = typed.trim(); let mut kept = Vec::new(); - for (i, row) in rows(a(0)).iter().enumerate() { + for (index, row) in rows(argument(0)).iter().enumerate() { if !row.is_object() { continue; } let hay = ["name", "label", "email"] .iter() - .map(|k| text(&row[k])) - .filter(|v| !v.is_empty()) + .map(|field| text(&row[field])) + .filter(|value| !value.is_empty()) .collect::>() .join(" "); let score = if typed.is_empty() { @@ -568,79 +568,101 @@ pub fn apply(p: &Value) -> Result { continue; } let mut copy = row.clone(); - copy["sourceIndex"] = json!(i); + copy["sourceIndex"] = json!(index); copy["score"] = json!(score); kept.push(copy); } if !typed.is_empty() { - kept.sort_by_key(|r| std::cmp::Reverse(r["score"].as_i64().unwrap_or(0))); + kept.sort_by_key(|row| std::cmp::Reverse(row["score"].as_i64().unwrap_or(0))); } json!(kept) } "railLabels" => { - let mut kept: Vec<_> = rows(a(0)) + let mut kept: Vec<_> = rows(argument(0)) .iter() - .filter(|r| r.is_object() && r["system"] != true) + .filter(|row| row.is_object() && row["system"] != true) .cloned() .collect(); - kept.sort_by_key(|r| (text(&r["name"]).to_lowercase(), text(&r["id"]))); + kept.sort_by_key(|row| (text(&row["name"]).to_lowercase(), text(&row["id"]))); json!(kept) } - "actionScope" => json!(action_scope(&s(0))), - "actionCapability" => json!(capability(&s(0))), - "labelTarget" => json!(target(&s(0))), - "isSystemLabelId" => json!(system(&s(0))), - "actionTargets" => action_targets(a(0), &s(1)), - "labelChangesFor" => changes(&s(0), &s(1)), - "threadAfterAction" => thread_action(a(0), &s(1)), - "threadAfterMemberChange" => thread_members(a(0), a(1)), - "rowWithThread" => with_thread(a(0), a(1)), - "applyLabelChange" => label_change(a(0), &s(1), &s(2), a(3)), - "survivesAction" => json!(survives(&s(0), &s(1), &s(2), *a(3) == true, &s(4), a(5))), - "rowHoldsMember" => json!(holds(a(0), &s(1))), - "rowIndexForMember" => json!(row_index(a(0), a(1)).map(|i| i as i64).unwrap_or(-1)), - "indexById" => json!(index(a(0), a(1)).map(|i| i as i64).unwrap_or(-1)), - "messageById" => index(a(0), a(2)) - .map(|i| rows(a(0))[i].clone()) - .or_else(|| index(a(1), a(2)).map(|i| rows(a(1))[i].clone())) + "actionScope" => json!(action_scope(&string_argument(0))), + "actionCapability" => json!(capability(&string_argument(0))), + "labelTarget" => json!(target(&string_argument(0))), + "isSystemLabelId" => json!(system(&string_argument(0))), + "actionTargets" => action_targets(argument(0), &string_argument(1)), + "labelChangesFor" => changes(&string_argument(0), &string_argument(1)), + "threadAfterAction" => thread_action(argument(0), &string_argument(1)), + "threadAfterMemberChange" => thread_members(argument(0), argument(1)), + "rowWithThread" => with_thread(argument(0), argument(1)), + "applyLabelChange" => label_change( + argument(0), + &string_argument(1), + &string_argument(2), + argument(3), + ), + "survivesAction" => json!(survives( + &string_argument(0), + &string_argument(1), + &string_argument(2), + *argument(3) == true, + &string_argument(4), + argument(5) + )), + "rowHoldsMember" => json!(holds(argument(0), &string_argument(1))), + "rowIndexForMember" => json!( + row_index(argument(0), argument(1)) + .map(|index| index as i64) + .unwrap_or(-1) + ), + "indexById" => json!( + index(argument(0), argument(1)) + .map(|index| index as i64) + .unwrap_or(-1) + ), + "messageById" => index(argument(0), argument(2)) + .map(|index| rows(argument(0))[index].clone()) + .or_else(|| { + index(argument(1), argument(2)).map(|index| rows(argument(1))[index].clone()) + }) .unwrap_or(Value::Null), - "removeById" => remove(a(0), a(1)), - "replaceById" => replace(a(0), a(1)), - "restoreRow" => restore(a(0), a(1), a(2), a(3)), + "removeById" => remove(argument(0), argument(1)), + "replaceById" => replace(argument(0), argument(1)), + "restoreRow" => restore(argument(0), argument(1), argument(2), argument(3)), "listAfterRestore" => { - if a(1).is_null() { - a(0).clone() - } else if index(a(0), &a(1)["id"]).is_some() { - replace(a(0), a(1)) - } else if *a(2) == true && *a(3) != true { - restore(a(0), a(1), a(4), a(5)) + if argument(1).is_null() { + argument(0).clone() + } else if index(argument(0), &argument(1)["id"]).is_some() { + replace(argument(0), argument(1)) + } else if *argument(2) == true && *argument(3) != true { + restore(argument(0), argument(1), argument(4), argument(5)) } else { - a(0).clone() + argument(0).clone() } } "previewAfterRestore" => { - if *a(2) == true { - if index(a(0), &a(1)["id"]).is_some() { - replace(a(0), a(1)) + if *argument(2) == true { + if index(argument(0), &argument(1)["id"]).is_some() { + replace(argument(0), argument(1)) } else { - restore(a(0), a(1), a(3), a(4)) + restore(argument(0), argument(1), argument(3), argument(4)) } } else { - remove(a(0), &a(1)["id"]) + remove(argument(0), &argument(1)["id"]) } } "restoreRows" => { - let mut out = a(0).clone(); - for (i, row) in rows(a(1)).iter().enumerate() { - if !rows(a(2)).contains(&row["id"]) { + let mut out = argument(0).clone(); + for (position, row) in rows(argument(1)).iter().enumerate() { + if !rows(argument(2)).contains(&row["id"]) { continue; } if index(&out, &row["id"]).is_some() { out = replace(&out, row); } else { - let at = rows(a(1))[i + 1..] + let at = rows(argument(1))[position + 1..] .iter() - .find_map(|r| index(&out, &r["id"])) + .find_map(|row| index(&out, &row["id"])) .unwrap_or(rows(&out).len()); let mut list = rows(&out).to_vec(); list.insert(at, row.clone()); @@ -649,30 +671,31 @@ pub fn apply(p: &Value) -> Result { } out } - "detailSummary" => detail(a(0), a(1)), - "sameSummaries" => json!(a(0) == a(1)), - "mergeSearchResults" => merge(a(0), a(1)), + "detailSummary" => detail(argument(0), argument(1)), + "sameSummaries" => json!(argument(0) == argument(1)), + "mergeSearchResults" => merge(argument(0), argument(1)), "searchProgress" => { - let live = merge(a(1), a(2)); - json!({"visible":merge(a(0),&live),"live":live}) + let live = merge(argument(1), argument(2)); + json!({"visible":merge(argument(0),&live),"live":live}) } "searchFinish" => { let settled = apply(&json!({"operation":"settledSearchResults","args":args}))?; - let missing = - apply(&json!({"operation":"missingSearchSummaryIds","args":[a(2),a(3)]}))?; + let missing = apply( + &json!({"operation":"missingSearchSummaryIds","args":[argument(2),argument(3)]}), + )?; json!({"settled":settled,"missing":missing}) } "settledSearchResults" => { - let known: HashMap<_, _> = rows(a(1)) + let known: HashMap<_, _> = rows(argument(1)) .iter() - .chain(rows(a(2))) - .filter(|r| !text(&r["id"]).is_empty()) - .map(|r| (text(&r["id"]), r)) + .chain(rows(argument(2))) + .filter(|row| !text(&row["id"]).is_empty()) + .map(|row| (text(&row["id"]), row)) .collect(); let mut budget = 16usize * 1024 * 1024; let mut sizes = HashMap::new(); let mut page = Vec::new(); - for wanted in rows(a(3)) { + for wanted in rows(argument(3)) { let key = text(wanted); let Some(row) = known.get(&key).copied() else { continue; @@ -686,82 +709,95 @@ pub fn apply(p: &Value) -> Result { page.push(row); } let page = json!(page); - if *a(4) == true { - merge(a(0), &page) + if *argument(4) == true { + merge(argument(0), &page) } else { page } } "missingSearchSummaryIds" => { - let known: HashSet<_> = rows(a(0)).iter().map(|r| text(&r["id"])).collect(); + let known: HashSet<_> = rows(argument(0)) + .iter() + .map(|row| text(&row["id"])) + .collect(); json!( - rows(a(1)) + rows(argument(1)) .iter() .filter(|id| !text(id).is_empty() && !known.contains(&text(id))) .collect::>() ) } - "unreadCount" => json!(rows(a(0)).iter().filter(|r| r["unread"] == true).count()), - "newestDate" => json!(rows(a(0)).iter().map(time).max().unwrap_or(0)), + "unreadCount" => json!( + rows(argument(0)) + .iter() + .filter(|row| row["unread"] == true) + .count() + ), + "newestDate" => json!(rows(argument(0)).iter().map(time).max().unwrap_or(0)), "newArrivals" => { - let floor = a(3).as_i64().unwrap_or(0); + let floor = argument(3).as_i64().unwrap_or(0); json!( - rows(a(0)) + rows(argument(0)) .iter() - .filter(|r| *a(2) == true - && r["unread"] == true - && r["inInbox"] == true - && a(1)[text(&r["id"])] != true - && (time(r) == 0 || time(r) >= floor)) + .filter(|row| *argument(2) == true + && row["unread"] == true + && row["inInbox"] == true + && argument(1)[text(&row["id"])] != true + && (time(row) == 0 || time(row) >= floor)) .collect::>() ) } "withoutIntent" => json!( - rows(a(0)) + rows(argument(0)) .iter() - .filter(|e| e.is_object() && e["token"] != *a(1)) + .filter(|entry| entry.is_object() && entry["token"] != *argument(1)) .collect::>() ), - "rebaseIntents" => rebase(a(0), a(1)), - "anyIntentRemoved" => json!(rows(a(0)).iter().any(|e| e["removed"] == true)), + "rebaseIntents" => rebase(argument(0), argument(1)), + "anyIntentRemoved" => json!( + rows(argument(0)) + .iter() + .any(|entry| entry["removed"] == true) + ), "intentsWith" => { - let mut out = a(0).as_object().cloned().unwrap_or_default(); - let mut entries = rows(&out.get(&s(1)).cloned().unwrap_or(Value::Null)).to_vec(); - entries.push(a(2).clone()); - out.insert(s(1), json!(entries)); + let mut out = argument(0).as_object().cloned().unwrap_or_default(); + let mut entries = + rows(&out.get(&string_argument(1)).cloned().unwrap_or(Value::Null)).to_vec(); + entries.push(argument(2).clone()); + out.insert(string_argument(1), json!(entries)); Value::Object(out) } "intentsSettled" => { - let mut out = a(0).as_object().cloned().unwrap_or_default(); - let held = out.get(&s(1)).cloned().unwrap_or(json!([])); - let mut outcome = if *a(3) == true { - rebase(&held, a(2)) + let mut out = argument(0).as_object().cloned().unwrap_or_default(); + let held = out.get(&string_argument(1)).cloned().unwrap_or(json!([])); + let mut outcome = if *argument(3) == true { + rebase(&held, argument(2)) } else { Value::Null }; if outcome.is_null() { - outcome = json!({"entries":rows(&held).iter().filter(|e| e["token"]!=*a(2)).collect::>(),"summary":a(4)}); + outcome = json!({"entries":rows(&held).iter().filter(|entry| entry["token"]!=*argument(2)).collect::>(),"summary":argument(4)}); } if rows(&outcome["entries"]).is_empty() { - out.remove(&s(1)); + out.remove(&string_argument(1)); } else { - out.insert(s(1), outcome["entries"].clone()); + out.insert(string_argument(1), outcome["entries"].clone()); } json!({"intents":out,"outcome":outcome}) } "settledListsHeld" => { - let mut out = a(0).as_object().cloned().unwrap_or_default(); - let held = out.get(&s(1)); - let entry = json!({"messages":held.map(|h| &h["messages"]).unwrap_or(a(2)),"previews":held.map(|h| &h["previews"]).unwrap_or(a(3)),"pending":held.and_then(|h| h["pending"].as_u64()).unwrap_or(0).saturating_add(1)}); - out.insert(s(1), entry); + let mut out = argument(0).as_object().cloned().unwrap_or_default(); + let held = out.get(&string_argument(1)); + let entry = json!({"messages":held.map(|h| &h["messages"]).unwrap_or(argument(2)),"previews":held.map(|h| &h["previews"]).unwrap_or(argument(3)),"pending":held.and_then(|h| h["pending"].as_u64()).unwrap_or(0).saturating_add(1)}); + out.insert(string_argument(1), entry); Value::Object(out) } "settledListsReleased" => { - let mut out = a(0).as_object().cloned().unwrap_or_default(); - if let Some(held) = out.get_mut(&s(1)) { + let mut out = argument(0).as_object().cloned().unwrap_or_default(); + if let Some(held) = out.get_mut(&string_argument(1)) { let count = held["pending"].as_u64().unwrap_or(0); if count <= 1 { - out.remove(&s(1)); + out.remove(&string_argument(1)); } else { held["pending"] = json!(count - 1); } diff --git a/src/account/model_tests.rs b/src/account/model_tests.rs index 03b0002a7..cb4b3851d 100644 --- a/src/account/model_tests.rs +++ b/src/account/model_tests.rs @@ -184,7 +184,7 @@ fn rollback_replays_later_intent_and_restores_settled_order() { &json!([{"operation":"rebaseIntents","args":[entries,1]}]), false, ); - // Function descriptors deliberately survive native replay, unlike JSON's function omission. + // Invariant: Function descriptors deliberately survive native replay, unlike JSON's function omission. assert_eq!(result["summary"], oracle_value[0]["summary"]); assert_eq!( result["entries"][0]["before"], diff --git a/src/account/storage.rs b/src/account/storage.rs index babaf7d44..6265ce70b 100644 --- a/src/account/storage.rs +++ b/src/account/storage.rs @@ -88,7 +88,7 @@ fn call_at(root: &std::path::Path, method: &str, params: &Value) -> Result Vec { .collect() } pub fn apply(p: &Value) -> Result { - // Prefixes are repeated in every composed row and thread member. Count the + // Invariant: Prefixes are repeated in every composed row and thread member. Count the // projected representation before allocating any expanded identifiers. let mut budget = 16usize * 1024 * 1024; for source in rows(&p["sources"]) { diff --git a/src/contacts/mod.rs b/src/contacts/mod.rs index e6f2075a3..d24cbc2ee 100644 --- a/src/contacts/mod.rs +++ b/src/contacts/mod.rs @@ -13,29 +13,35 @@ const MAX_FILE: u64 = 16 * 1024 * 1024; const MAX_CONTACTS: usize = 10000; type Book = BTreeMap; -fn address(s: &str) -> bool { - let Some((local, domain)) = s.split_once('@') else { +fn address(email: &str) -> bool { + let Some((local, domain)) = email.split_once('@') else { return false; }; !local.is_empty() - && !local - .chars() - .any(|c| c.is_control() || c.is_whitespace() || "@<>,;\"\\".contains(c)) + && !local.chars().any(|character| { + character.is_control() || character.is_whitespace() || "@<>,;\"\\".contains(character) + }) && domain.split('.').count() >= 2 - && domain - .split('.') - .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')) - && domain - .rsplit('.') - .next() - .is_some_and(|p| p.len() >= 2 && p.bytes().all(|b| b.is_ascii_alphabetic())) + && domain.split('.').all(|part| { + !part.is_empty() + && part + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + }) + && domain.rsplit('.').next().is_some_and(|part| { + part.len() >= 2 && part.bytes().all(|byte| byte.is_ascii_alphabetic()) + }) } fn collect(book: &mut Book, name: &str, email: &str) { let email = email.trim(); if !address(email) || book.len() >= MAX_CONTACTS { return; } - let name: String = name.trim().chars().filter(|c| !c.is_control()).collect(); + let name: String = name + .trim() + .chars() + .filter(|character| !character.is_control()) + .collect(); let key = email.to_lowercase(); if !book.contains_key(&key) || (book[&key]["name"] == "" && !name.is_empty()) { book.insert(key, json!({"name":name,"email":email})); @@ -108,64 +114,71 @@ fn paths(dir: &Path) -> Vec { .flatten() .filter_map(Result::ok) .take(2000) - .map(|e| e.path()) + .map(|entry| entry.path()) .collect(); result.sort(); result } +fn message_contacts(row: &Value) -> Vec<&Value> { + let mut people = vec![&row["from"], &row["replyTo"]]; + for field in ["to", "cc"] { + if let Some(items) = row[field].as_array().filter(|items| items.len() <= 5) { + people.extend(items); + } + } + people +} +fn cache_contacts(query: &Value) -> impl Iterator { + query["summaries"] + .as_array() + .filter(|rows| !rows.is_empty()) + .or_else(|| query["messages"].as_array()) + .into_iter() + .flatten() + .flat_map(message_contacts) +} fn cache(book: &mut Book, dir: &Path) { let mut harvested = 0; - for file in paths(dir).into_iter().filter(|p| { - p.file_name().is_some_and(|n| { - n.to_string_lossy().starts_with("account-") && n.to_string_lossy().ends_with(".json") + for file in paths(dir).into_iter().filter(|path| { + path.file_name().is_some_and(|name| { + let name = name.to_string_lossy(); + name.starts_with("account-") && name.ends_with(".json") }) }) { - let Some(raw) = read(&file).and_then(|s| serde_json::from_str::(&s).ok()) else { + let Some(raw) = read(&file).and_then(|text| serde_json::from_str::(&text).ok()) + else { continue; }; let Some(queries) = raw["queries"].as_object() else { continue; }; - for entry in queries.values() { - let rows = entry["summaries"] - .as_array() - .filter(|r| !r.is_empty()) - .or_else(|| entry["messages"].as_array()); - for row in rows.into_iter().flatten() { - let mut people = vec![&row["from"], &row["replyTo"]]; - for field in ["to", "cc"] { - if let Some(items) = row[field].as_array().filter(|a| a.len() <= 5) { - people.extend(items) - } - } - for person in people { - let email = person["email"].as_str().unwrap_or(""); - let name = person["name"] - .as_str() - .filter(|s| !s.is_empty()) - .or_else(|| person["display"].as_str()) - .unwrap_or(""); - if address(email) { - if harvested >= 2000 { - return; - } - harvested += 1; - collect( - book, - if email.split('@').next() == Some(name) { - "" - } else { - name - }, - email, - ) - } - } + for person in queries.values().flat_map(cache_contacts) { + let email = person["email"].as_str().unwrap_or(""); + if !address(email) { + continue; } + if harvested >= 2000 { + return; + } + harvested += 1; + let name = person["name"] + .as_str() + .filter(|name| !name.is_empty()) + .or_else(|| person["display"].as_str()) + .unwrap_or(""); + collect( + book, + if email.split('@').next() == Some(name) { + "" + } else { + name + }, + email, + ); } } } -fn thunderbird(book: &mut Book, root: &Path) { +fn thunderbird_profiles(root: &Path) -> Vec { let mut profiles = paths(root); profiles.extend(paths(&root.join("Profiles"))); if let Some(ini) = read(&root.join("profiles.ini")) { @@ -175,14 +188,18 @@ fn thunderbird(book: &mut Book, root: &Path) { for line in ini.lines().chain(std::iter::once("[end]")) { let line = line.trim(); if line.starts_with('[') { - if section && let Some(p) = path.take() { - let p = PathBuf::from(p); - profiles.push(if relative { root.join(p) } else { p }); + if section && let Some(profile) = path.take() { + let profile = PathBuf::from(profile); + profiles.push(if relative { + root.join(profile) + } else { + profile + }); } section = line.to_lowercase().starts_with("[profile"); relative = true; - } else if let Some(v) = line.strip_prefix("Path=") { - path = Some(v.to_string()) + } else if let Some(value) = line.strip_prefix("Path=") { + path = Some(value.to_string()) } else if line == "IsRelative=0" { relative = false } @@ -190,38 +207,53 @@ fn thunderbird(book: &mut Book, root: &Path) { } profiles.sort(); profiles.dedup(); - for profile in profiles { - for db in paths(&profile).into_iter().filter(|p| { - p.file_name().is_some_and(|n| { - let n = n.to_string_lossy(); - (n.starts_with("abook") || n.starts_with("history")) && n.ends_with(".sqlite") + profiles +} + +fn thunderbird(book: &mut Book, root: &Path) { + for profile in thunderbird_profiles(root) { + for database in paths(&profile).into_iter().filter(|path| { + path.file_name().is_some_and(|name| { + let name = name.to_string_lossy(); + (name.starts_with("abook") || name.starts_with("history")) + && name.ends_with(".sqlite") }) }) { - let Ok(connection) = rusqlite::Connection::open_with_flags( - db, - rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY - | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, - ) else { - continue; - }; - let _ = connection.busy_timeout(std::time::Duration::from_millis(200)); - let Ok(mut query)=connection.prepare("SELECT MAX(CASE WHEN name='DisplayName' THEN value ELSE '' END), MAX(CASE WHEN name='PrimaryEmail' THEN value ELSE '' END), MAX(CASE WHEN name='SecondEmail' THEN value ELSE '' END) FROM properties GROUP BY card LIMIT 10000") else {continue}; - let Ok(rows) = query.query_map([], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, String>(2)?, - )) - }) else { - continue; - }; - for (name, email, second) in rows.flatten() { - collect(book, &name, &email); - collect(book, &name, &second) - } + thunderbird_book(book, &database); } } } +fn thunderbird_book(book: &mut Book, database: &Path) { + let Ok(connection) = rusqlite::Connection::open_with_flags( + database, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) else { + return; + }; + let _ = connection.busy_timeout(std::time::Duration::from_millis(200)); + let Ok(mut query) = connection.prepare( + "SELECT MAX(CASE WHEN name='DisplayName' THEN value ELSE '' END), + MAX(CASE WHEN name='PrimaryEmail' THEN value ELSE '' END), + MAX(CASE WHEN name='SecondEmail' THEN value ELSE '' END) + FROM properties GROUP BY card LIMIT 10000", + ) else { + return; + }; + let Ok(rows) = query.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + )) + }) else { + return; + }; + for (name, email, second) in rows.flatten() { + collect(book, &name, &email); + collect(book, &name, &second) + } +} + pub fn suggest() -> Result { let dirs = crate::platform::dirs::AppDirs::discover()?; Ok(discover( @@ -272,7 +304,7 @@ mod tests { let before = fs::read(&database).unwrap(); fs::create_dir_all(root.join("cache/omamail")).unwrap(); let bulk: Vec<_> = (0..6) - .map(|n| json!({"email":format!("bulk{n}@example.com")})) + .map(|index| json!({"email":format!("bulk{index}@example.com")})) .collect(); fs::write(root.join("cache/omamail/account-a.json"),json!({"queries":{"inbox":{"summaries":[{"from":{"email":"bob@example.com","name":"bob"},"bcc":[{"email":"hidden@example.com"}],"to":bulk}]}}}).to_string()).unwrap(); let result = discover(&root, &root.join("config"), &root.join("cache")); @@ -284,30 +316,30 @@ mod tests { } #[test] fn validates_addresses_without_coercing_objects() { - let mut b = Book::new(); + let mut book = Book::new(); json_book( - &mut b, + &mut book, &json!({"contacts":[{"email":"a@example.com"}],"Jane":"jane@example.com","bad":"a@example.com\nInjected"}), ); - assert_eq!(b.len(), 1); - assert!(b.contains_key("jane@example.com")); + assert_eq!(book.len(), 1); + assert!(book.contains_key("jane@example.com")); } #[test] fn unfolds_cards_and_skips_malformed_lines() { - let mut b = Book::new(); + let mut book = Book::new(); vcard( - &mut b, + &mut book, "BEGIN:VCARD\nFN:Jane\nEMAIL broken\nEMAIL:a@exam\n ple.com\nEND:VCARD\n", ); - assert_eq!(b["a@example.com"]["name"], "Jane"); + assert_eq!(book["a@example.com"]["name"], "Jane"); } #[test] fn named_contact_replaces_inferred_empty_name() { - let mut b = Book::new(); - collect(&mut b, "", "A@example.com"); - collect(&mut b, "Alice", "a@example.com"); - assert_eq!(b.len(), 1); - assert_eq!(b["a@example.com"]["name"], "Alice"); + let mut book = Book::new(); + collect(&mut book, "", "A@example.com"); + collect(&mut book, "Alice", "a@example.com"); + assert_eq!(book.len(), 1); + assert_eq!(book["a@example.com"]["name"], "Alice"); } } diff --git a/src/providers/domain.rs b/src/providers/domain.rs index 703f08adc..956354c97 100644 --- a/src/providers/domain.rs +++ b/src/providers/domain.rs @@ -86,33 +86,37 @@ fn encode(text: &str) -> String { out } pub fn snapshot() -> Value { - let mut out = json!({}); - for p in super::list().as_array().unwrap() { - let id = p["id"].as_str().unwrap(); - out[id] = json!({"capabilities":p["capabilities"],"queries":QUERIES[id],"nativeSync":true,"inheritedDefault":"in:inbox","addressSearch":matches!(id,"gmail"|"hey"|"imap"),"webHomeUrl":match id {"gmail"=>"https://mail.google.com/mail/u/0/","hey"=>"https://app.hey.com","outlook"=>"https://outlook.live.com/mail/",_=>""}}); + let mut snapshot = json!({}); + for provider in super::list().as_array().unwrap() { + let id = provider["id"].as_str().unwrap(); + snapshot[id] = json!({"capabilities":provider["capabilities"],"queries":QUERIES[id],"nativeSync":true,"inheritedDefault":"in:inbox","addressSearch":matches!(id,"gmail"|"hey"|"imap"),"webHomeUrl":match id {"gmail"=>"https://mail.google.com/mail/u/0/","hey"=>"https://app.hey.com","outlook"=>"https://outlook.live.com/mail/",_=>""}}); } - out + snapshot } -pub fn resolve(p: &Value) -> Result { - if !p.is_object() { +pub fn resolve(params: &Value) -> Result { + if !params.is_object() { return Err("invalid_params"); } - let canonical = p["provider"].as_str().unwrap_or("").trim().to_lowercase(); + let canonical = params["provider"] + .as_str() + .unwrap_or("") + .trim() + .to_lowercase(); let id = provider(&Value::String(canonical)).to_owned(); - let value = p["value"].as_str().unwrap_or(""); + let value = params["value"].as_str().unwrap_or(""); let text = value.trim(); if ["value", "search", "defaultQuery"].iter().any(|key| { - p[*key] - .as_str() - .is_some_and(|v| v.len() > 32768 || v.chars().any(|c| c.is_control())) + params[*key].as_str().is_some_and(|value| { + value.len() > 32768 || value.chars().any(|character| character.is_control()) + }) }) { return Err("invalid_params"); } - let result = match p["operation"].as_str().unwrap_or("query") { + let result = match params["operation"].as_str().unwrap_or("query") { "query" => { - let search_text = p["search"].as_str().unwrap_or("").trim(); - let custom = p["defaultQuery"].as_str().unwrap_or("").trim(); - let mailbox = p["mailbox"].as_str().unwrap_or("inbox"); + let search_text = params["search"].as_str().unwrap_or("").trim(); + let custom = params["defaultQuery"].as_str().unwrap_or("").trim(); + let mailbox = params["mailbox"].as_str().unwrap_or("inbox"); if !search_text.is_empty() { search(&id, search_text) } else if mailbox == "inbox" @@ -144,9 +148,13 @@ pub fn resolve(p: &Value) -> Result { if text.is_empty() { String::new() } else { - let to = p["field"] == "to"; + let to = params["field"] == "to"; match id.as_str() { - "gmail" if !text.chars().any(|c| c.is_whitespace() || c == '"') => { + "gmail" + if !text + .chars() + .any(|character| character.is_whitespace() || character == '"') => + { format!("{}:{text}", if to { "to" } else { "from" }) } "imap" => format!("search:{} {}", if to { "TO" } else { "FROM" }, quoted(text)), @@ -209,7 +217,7 @@ mod tests { let cases: Value = serde_json::from_str(include_str!("../../tests/provider_domain_parity.json")).unwrap(); for case in cases.as_array().unwrap() { - // Legacy fixtures predate account-wide IMAP search. Folder browsing + // Invariant: Legacy fixtures predate account-wide IMAP search. Folder browsing // is unchanged; only resolved search/address queries change scope. let expected = case["expected"].as_str().unwrap(); let expected = if expected.starts_with("folder:INBOX ") diff --git a/src/providers/gmail.rs b/src/providers/gmail.rs index 827d3ed2f..5ee32f839 100644 --- a/src/providers/gmail.rs +++ b/src/providers/gmail.rs @@ -53,7 +53,7 @@ impl AccountSession { &self, refresh: impl FnOnce() -> F, ) -> Result, &'static str> { - // Refresh coalesces per account. Invalidation never waits on this lock. + // Invariant: Refresh coalesces per account. Invalidation never waits on this lock. let mut cached = self.token.lock().await; self.check()?; if let Some(token) = cached.as_ref().filter(|t| t.expires > Instant::now()) { @@ -83,7 +83,7 @@ impl AccountSession { async fn reject(&self, rejected: &Arc) -> Result<(), &'static str> { let mut cached = self.token.lock().await; self.check()?; - // An old 401 cannot evict a new grant, even with identical token bytes. + // Invariant: An old 401 cannot evict a new grant, even with identical token bytes. if cached .as_ref() .is_some_and(|current| Arc::ptr_eq(current, rejected)) @@ -470,7 +470,7 @@ impl Session { } let account = field(params, "accountId", true)?.to_lowercase(); if method == "gmail.invalidate" { - // Cache eviction, not keyring logout or an IPC ordering barrier. + // Invariant: Cache eviction, not keyring logout or an IPC ordering barrier. // New calls can authenticate again. In-flight HTTP cannot be recalled; // retired leases refuse its result and never refresh for a retry. if let Some(session) = self @@ -528,7 +528,7 @@ impl Session { field(params, "attachmentId", true)?, ], }; - // Resolve the registered provider before any credential or network read. + // Invariant: Resolve the registered provider before any credential or network read. let accounts = tokio::task::spawn_blocking(crate::account::list_readonly) .await .map_err(|_| "session_failed")??; diff --git a/src/providers/gmail_credentials.rs b/src/providers/gmail_credentials.rs index afea55136..c2d53dced 100644 --- a/src/providers/gmail_credentials.rs +++ b/src/providers/gmail_credentials.rs @@ -64,18 +64,19 @@ fn parse_client(bytes: &[u8], account: &str) -> Result { if let Some(entries) = raw["accounts"].as_array() { let mut shared = None; for entry in entries { - if let Some(value) = client(entry) { - if entry["id"] - .as_str() - .unwrap_or("") - .trim() - .eq_ignore_ascii_case(account.trim()) - { - return Ok(value); - } - if shared.is_none() { - shared = Some(value); - } + let Some(value) = client(entry) else { + continue; + }; + if entry["id"] + .as_str() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(account.trim()) + { + return Ok(value); + } + if shared.is_none() { + shared = Some(value); } } shared.ok_or("gmail_client_missing") diff --git a/src/providers/gmail_http.rs b/src/providers/gmail_http.rs index b7e8d690c..41241e9ba 100644 --- a/src/providers/gmail_http.rs +++ b/src/providers/gmail_http.rs @@ -38,13 +38,13 @@ struct Request { const MAX_INPUT: usize = 64 * 1024; const MAX_RESPONSE: usize = 16 * 1024 * 1024; const DEADLINE: Duration = Duration::from_secs(20); -// Only an explicit rate-limit refusal is retried; timeouts remain ambiguous. +// Invariant: Only an explicit rate-limit refusal is retried; timeouts remain ambiguous. const RATE_LIMIT_BACKOFF: Duration = Duration::from_secs(1); const RATE_LIMIT_RETRIES: usize = 3; static REQUEST_SERIAL: AtomicU64 = AtomicU64::new(0); static CLIENT: OnceLock> = OnceLock::new(); -// The integration fixture exercises the real dispatcher, credential reader and +// Invariant: The integration fixture exercises the real dispatcher, credential reader and // request serializer. This override exists only in test builds and only inside // its task scope; production has no environment/configuration bypass. #[cfg(test)] @@ -286,7 +286,7 @@ async fn attempt( .header(reqwest::header::CONTENT_TYPE, request.content_type) .body(body); } else if empty_post { - // Bodyless Gmail trash/untrash requests still need explicit framing. + // Invariant: Bodyless Gmail trash/untrash requests still need explicit framing. // Some gateways reject a POST without Content-Length with HTTP 411. builder = builder.header(reqwest::header::CONTENT_LENGTH, "0"); } @@ -402,30 +402,34 @@ fn body_retry_after(body: &Value) -> Option { messages.push(error["message"].as_str().unwrap_or("")); } for message in messages { - if let Some(captures) = pattern.captures(message) { - if let Ok(date) = chrono::DateTime::parse_from_rfc3339(&captures[1]) { - let duration = Duration::from_millis( - (date.timestamp_millis() - chrono::Utc::now().timestamp_millis()) - .clamp(0, 86400000) as u64, - ); - wait = wait.into_iter().chain(Some(duration)).max(); - } - } + let Some(captures) = pattern.captures(message) else { + continue; + }; + let Ok(date) = chrono::DateTime::parse_from_rfc3339(&captures[1]) else { + continue; + }; + let duration = Duration::from_millis( + (date.timestamp_millis() - chrono::Utc::now().timestamp_millis()).clamp(0, 86400000) + as u64, + ); + wait = wait.into_iter().chain(Some(duration)).max(); } for detail in body["error"]["details"].as_array().into_iter().flatten() { - if detail["@type"] == "type.googleapis.com/google.rpc.RetryInfo" { - if let Some(seconds) = detail["retryDelay"] - .as_str() - .and_then(|s| s.strip_suffix('s')) - .and_then(|s| s.parse::().ok()) - .filter(|s| s.is_finite() && *s >= 0.0) - { - wait = wait - .into_iter() - .chain(Some(Duration::from_secs_f64(seconds.min(86400.0)))) - .max(); - } + if detail["@type"] != "type.googleapis.com/google.rpc.RetryInfo" { + continue; } + let Some(seconds) = detail["retryDelay"] + .as_str() + .and_then(|seconds| seconds.strip_suffix('s')) + .and_then(|seconds| seconds.parse::().ok()) + .filter(|seconds| seconds.is_finite() && *seconds >= 0.0) + else { + continue; + }; + wait = wait + .into_iter() + .chain(Some(Duration::from_secs_f64(seconds.min(86400.0)))) + .max(); } wait } diff --git a/src/providers/gmail_http_runtime_tests.rs b/src/providers/gmail_http_runtime_tests.rs index 70a95d40d..8743838ec 100644 --- a/src/providers/gmail_http_runtime_tests.rs +++ b/src/providers/gmail_http_runtime_tests.rs @@ -25,7 +25,6 @@ async fn server(response: Vec, delay: Duration) -> Server { server_sequence(vec![response], delay).await } -// Answers the n-th request with the n-th response; the last one repeats. async fn server_sequence(responses: Vec>, delay: Duration) -> Server { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}/messages/abc", listener.local_addr().unwrap()); @@ -143,7 +142,7 @@ async fn mail_send_preview_reads_google_identity_without_mutation_or_local_write std::fs::write(directory.join("sentinel"), b"unchanged existing state").unwrap(); } std::fs::write(fixture.state.join("omamail/outbox.json"), b"[]\n").unwrap(); - // Keep the hostile display name separate from a Windows-valid filename. + // Invariant: Keep the hostile display name separate from a Windows-valid filename. let attachment = fixture.root.join(if cfg!(windows) { "attachment-工.txt" } else { @@ -253,7 +252,6 @@ async fn native_concurrency_overlaps_response_waits() { let request = local(&server, get_request()); work.spawn(async move { execute(&client, request, DEADLINE).await }); } - // All four requests arrive before the server releases the first response. tokio::time::timeout(Duration::from_secs(2), async { while server.requests.lock().unwrap().len() != 4 { tokio::task::yield_now().await; @@ -335,7 +333,7 @@ async fn timeout_and_response_bounds_are_enforced_on_actual_streams() { #[tokio::test] async fn auth_and_invalid_json_return_only_static_errors() { let client = client_builder().https_only(false).build().unwrap(); - // Gmail reports per-user rate limiting as 403 with a usageLimits reason, + // Invariant: Gmail reports per-user rate limiting as 403 with a usageLimits reason, // not only as 429. Any other 403 is a permission problem. let limited = r#"{"error":{"errors":[{"domain":"usageLimits","reason":"userRateLimitExceeded","message":"User-rate limit exceeded. Retry after 2026-09-16T00:00:00Z"}],"code":403,"message":"User-rate limit exceeded."}}"#; let global = r#"{"error":{"errors":[{"domain":"usageLimits","reason":"rateLimitExceeded","message":"Rate Limit Exceeded"}],"code":403,"message":"Rate Limit Exceeded"}}"#; @@ -362,7 +360,7 @@ async fn auth_and_invalid_json_return_only_static_errors() { Duration::ZERO, ) .await; - // A deadline shorter than the first backoff leaves no room to retry. + // Invariant: A deadline shorter than the first backoff leaves no room to retry. let started = std::time::Instant::now(); assert_eq!( execute( @@ -378,9 +376,6 @@ async fn auth_and_invalid_json_return_only_static_errors() { } } -// A message mutation answers with a ticket, is sent from the account's queue -// with the real credential reader, token refresh and serializer, and settles -// as a notification; the in-process caller holds the line for the answer. #[tokio::test] async fn queued_mutation_settles_by_notification_and_in_process() { use crate::mail::tests::{account_fixture, isolated}; @@ -476,7 +471,7 @@ async fn queued_mutation_settles_by_notification_and_in_process() { ); } -// A rate-limited request was rejected before it ran, so resending it — even +// Invariant: A rate-limited request was rejected before it ran, so resending it — even // a mutation — cannot duplicate anything. Google asks for exponential backoff // starting at a second; the retry budget stays inside the request deadline. #[tokio::test] @@ -503,7 +498,6 @@ async fn rate_limited_requests_back_off_and_resend_within_the_deadline() { .await, Ok(serde_json::json!({"ok":true})) ); - // 20ms, then 40ms: exponential, not a tight loop. assert!(started.elapsed() >= Duration::from_millis(60)); let requests = target.requests.lock().unwrap().clone(); assert_eq!(requests.len(), 3); @@ -513,7 +507,6 @@ async fn rate_limited_requests_back_off_and_resend_within_the_deadline() { .all(|r| r.starts_with("POST /messages/abc ")) ); - // Persistent limiting gives up after a bounded number of attempts. let target = server(limited, Duration::ZERO).await; assert_eq!( execute_with_backoff( @@ -850,7 +843,7 @@ async fn real_tls_rejects_untrusted_certificate_before_sending_credentials() { .add_root_certificate(certificate) .build() .unwrap(); - // First reject the untrusted issuer; then trust that issuer and independently + // Invariant: First reject the untrusted issuer; then trust that issuer and independently // reject the mismatched IP hostname (the certificate only names localhost). for (client, host) in [(client().unwrap(), "localhost"), (&trusted, "127.0.0.1")] { let mut request = get_request(); @@ -863,7 +856,7 @@ async fn real_tls_rejects_untrusted_certificate_before_sending_credentials() { output.read_line(&mut report).unwrap(); assert_eq!(report.trim(), "tls-refused-no-http"); } - // A successful trusted, matching-host control proves that the previous + // Invariant: A successful trusted, matching-host control proves that the previous // rejection was hostname verification, not a malformed CA/end-entity cert. let mut request = get_request(); request.url = format!("https://localhost:{port}/messages/abc"); @@ -917,14 +910,14 @@ fn pending_dns_obeys_deadline_and_does_not_block_runtime_shutdown() { .dns_resolver(Arc::new(resolver)) .build() .unwrap(); - // Retain the real fixed HTTPS URL: the only injected seam is a DNS + // Invariant: Retain the real fixed HTTPS URL: the only injected seam is a DNS // future that never yields an address, so no connection is possible. execute(&client, get_request(), Duration::from_millis(40)).await }); drop(runtime); finished.send(result).unwrap(); }); - // Receive only after normal runtime destruction, not shutdown_timeout or a + // Invariant: Receive only after normal runtime destruction, not shutdown_timeout or a // leaked runtime: lingering blocking DNS work would fail this assertion. let result = completion .recv_timeout(Duration::from_secs(2)) @@ -1019,7 +1012,7 @@ async fn mutation_timeout_does_not_retry_an_accepted_request() { assert_eq!(peer.connections.load(Ordering::SeqCst), 1); } -// Model a gateway which rejects unframed POSTs with 411, before any mutation. +// Algorithm: Model a gateway which rejects unframed POSTs with 411, before any mutation. async fn strict_empty_post_server() -> Server { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); diff --git a/src/providers/gmail_queue.rs b/src/providers/gmail_queue.rs index 368df2ffd..f42c54d6d 100644 --- a/src/providers/gmail_queue.rs +++ b/src/providers/gmail_queue.rs @@ -318,7 +318,6 @@ mod tests { let (_, head) = queue.enqueue("one", Arc::clone(&one), job("a")).unwrap(); let (_, behind) = queue.enqueue("one", Arc::clone(&one), job("b")).unwrap(); let (_, other) = queue.enqueue("two", two, job("c")).unwrap(); - // The other account's send is not behind this one's backoff. assert_eq!(other.await.unwrap(), Ok(json!({"account":"two"}))); assert_eq!(next(&mut events).await["accountId"], "two"); tokio::task::yield_now().await; @@ -329,7 +328,7 @@ mod tests { next(&mut events).await["error"], "gmail_session_invalidated" ); - // The head was mid-backoff: it is refused before its resend, not resent. + // Invariant: The head was mid-backoff: it is refused before its resend, not resent. assert_eq!(head.await.unwrap(), Err("gmail_session_invalidated")); assert_eq!( sent.lock() @@ -346,7 +345,7 @@ mod tests { let sent = Arc::new(Mutex::new(Vec::new())); let queue = Queue::new(scripted(vec![], Arc::clone(&sent))); let session = Arc::new(AccountSession::new()); - // Fill without draining by never yielding to the drainer. + // Algorithm: Fill without draining by never yielding to the drainer. { let mut accounts = queue.inner.accounts.lock().unwrap(); let line = accounts.entry("one".into()).or_default(); diff --git a/src/providers/gmail_quota.rs b/src/providers/gmail_quota.rs index ad0796a5b..e7a3e50bb 100644 --- a/src/providers/gmail_quota.rs +++ b/src/providers/gmail_quota.rs @@ -10,7 +10,7 @@ use tokio::{ time::Instant, }; -// 1,200 + 75 * 60 = 5,700 units in any minute, below Google's 6,000. +// Invariant: 1,200 + 75 * 60 = 5,700 units in any minute, below Google's 6,000. const BURST: f64 = 1200.0; const UNITS_PER_SECOND: f64 = 75.0; const BACKGROUND_RESERVE: f64 = 600.0; diff --git a/src/providers/gmail_resources.rs b/src/providers/gmail_resources.rs index d7b5af8d8..c841f70ae 100644 --- a/src/providers/gmail_resources.rs +++ b/src/providers/gmail_resources.rs @@ -68,7 +68,6 @@ pub(super) fn normalize(method: &str, answer: Value) -> Value { #[cfg(test)] mod tests { use super::*; - use serde_json::json; #[test] fn list_fields_include_mime_metadata_without_message_or_attachment_octets() { diff --git a/src/providers/gmail_tests.rs b/src/providers/gmail_tests.rs index 6ba2540aa..e2cf3dc0e 100644 --- a/src/providers/gmail_tests.rs +++ b/src/providers/gmail_tests.rs @@ -231,7 +231,7 @@ async fn invalidation_during_refresh_cannot_publish_token_or_send_get() { #[tokio::test] async fn slow_account_refresh_does_not_stall_another_account() { - // A single-thread runtime proves the wait yields, rather than being hidden by workers. + // Invariant: A single-thread runtime proves the wait yields, rather than being hidden by workers. let session = &Session::default(); let started = tokio::sync::Notify::new(); let release = tokio::sync::Notify::new(); @@ -351,8 +351,3 @@ async fn credentials_failure_prevents_refresh_and_mail_network_requests() { }) .await; } - -// Gmail meters each user at 250 quota units per second and answers a burst -// past that with 403 rateLimitExceeded. Trashing a screen of conversations -// fires one 5-unit call per message, so the session paces every account -// below that line instead of letting the burst reach Google. diff --git a/src/providers/gmail_writes.rs b/src/providers/gmail_writes.rs index 95ae4a7f5..4806f23e7 100644 --- a/src/providers/gmail_writes.rs +++ b/src/providers/gmail_writes.rs @@ -157,7 +157,7 @@ fn plan(method: &str, params: &Value) -> Result { } _ => unreachable!(), } - // Validate path spelling before reading credentials, including dot segments. + // Invariant: Validate path spelling before reading credentials, including dot segments. for part in &result.path { super::super::gmail_http::validate_path_part(part).map_err(|_| "invalid_params")?; } @@ -298,7 +298,7 @@ impl Session { if answer == Err("gmail_unauthorized") { session.reject(&token).await?; } - // Delivery suppression after logout does not pretend a dispatched mutation was undone. + // Invariant: Delivery suppression after logout does not pretend a dispatched mutation was undone. session.check()?; answer } diff --git a/src/providers/hey.rs b/src/providers/hey.rs index 4311f4c3a..5bd5f389c 100644 --- a/src/providers/hey.rs +++ b/src/providers/hey.rs @@ -41,71 +41,73 @@ fn strings(items: &[&str]) -> Vec { items.iter().map(|s| (*s).into()).collect() } -struct Query { - kind: String, - argument: String, - unseen: bool, +enum Query { + Drafts, + Trash { unseen: bool }, + Label(String), + Search(String), + Box { name: String, unseen: bool }, +} +impl Query { + fn unseen(&self) -> bool { + matches!( + self, + Self::Trash { unseen: true } | Self::Box { unseen: true, .. } + ) + } } fn query(raw: &str) -> Result { let raw = raw.trim(); - let (kind, argument, unseen) = if raw == "drafts:" { - ("drafts", "".into(), false) - } else if let Some(label) = raw.strip_prefix("label:") { + if raw == "drafts:" { + return Ok(Query::Drafts); + } + if let Some(label) = raw.strip_prefix("label:") { if !number(label.trim()) { return Err("Invalid HEY label"); } - ("label", label.trim().into(), false) - } else if let Some(search) = raw.strip_prefix("search:") { - // CLI flag parsers can interpret positional strings beginning with '-'. + return Ok(Query::Label(label.trim().into())); + } + if let Some(search) = raw.strip_prefix("search:") { + // Invariant: CLI flag parsers can interpret positional strings beginning with '-'. if search.trim().starts_with('-') { return Err("HEY search cannot start with a flag"); } - ("search", search.trim().into(), false) + return Ok(Query::Search(search.trim().into())); + } + let mut words = raw + .strip_prefix("box:") + .unwrap_or("imbox") + .split_whitespace(); + let name = words.next().unwrap_or("imbox").to_lowercase(); + let unseen = words.any(|word| word.eq_ignore_ascii_case("unseen")); + if name == "trash" { + return Ok(Query::Trash { unseen }); + } + let name = if [ + "imbox", + "feedbox", + "asidebox", + "laterbox", + "trailbox", + "bubblebox", + ] + .contains(&name.as_str()) + { + name } else { - let mut words = raw - .strip_prefix("box:") - .unwrap_or("imbox") - .split_whitespace(); - let box_name = words.next().unwrap_or("imbox").to_lowercase(); - let unseen = words.any(|s| s.eq_ignore_ascii_case("unseen")); - if box_name == "trash" { - ("trash", "".into(), unseen) - } else { - ( - "box", - if [ - "imbox", - "feedbox", - "asidebox", - "laterbox", - "trailbox", - "bubblebox", - ] - .contains(&box_name.as_str()) - { - box_name - } else { - "imbox".into() - }, - unseen, - ) - } + "imbox".into() }; - Ok(Query { - kind: kind.into(), - argument, - unseen, - }) + Ok(Query::Box { name, unseen }) } -fn command(q: &Query, cursor: &str) -> Vec { - let mut args = match q.kind.as_str() { - "drafts" => strings(&["draft", "list", "--json"]), - "trash" => strings(&["search", "--in", "trash", "--json"]), - "label" => strings(&["label", &q.argument, "--json"]), - "search" => strings(&["search", &q.argument, "--json"]), - _ => strings(&["box", &q.argument, "--json"]), +fn command(query: &Query, cursor: &str) -> Vec { + let mut args = match query { + Query::Drafts => strings(&["draft", "list", "--json"]), + Query::Trash { .. } => strings(&["search", "--in", "trash", "--json"]), + Query::Label(label) => strings(&["label", label, "--json"]), + Query::Search(search) => strings(&["search", search, "--json"]), + Query::Box { name, .. } => strings(&["box", name, "--json"]), }; - if q.unseen && q.kind == "box" { + if matches!(query, Query::Box { unseen: true, .. }) { args.extend(strings(&["--limit", "100"])); } if !cursor.is_empty() { @@ -224,14 +226,14 @@ fn listing(q: &Query, data: &Value) -> Vec { entries .iter() .filter_map(|entry| { - if q.unseen && entry["seen"] == true { + if q.unseen() && entry["seen"] == true { return None; } let posting = text(&entry["id"]); if !number(&posting) { return None; } - if q.kind == "drafts" { + if matches!(q, Query::Drafts) { return Some(resource( &format!("draft:{posting}"), entry, @@ -242,7 +244,7 @@ fn listing(q: &Query, data: &Value) -> Vec { )); } let search = data.is_array(); - if q.unseen && search { + if q.unseen() && search { return None; } let topic = if search { @@ -284,7 +286,7 @@ fn listing(q: &Query, data: &Value) -> Vec { .collect() } -// A thread response contains bodies, not the posting's subject, unread state, +// Invariant: A thread response contains bodies, not the posting's subject, unread state, // or box. The UI may retain those fields from its listing, but a standalone // read must not invent them. Entry IDs are not routable posting:topic IDs. fn read_resource(id: &str, data: &Value, draft: bool) -> Result { @@ -312,7 +314,7 @@ fn read_resource(id: &str, data: &Value, draft: bool) -> Result Result { static DROPPED: std::sync::OnceLock>> = std::sync::OnceLock::new(); @@ -405,7 +407,7 @@ async fn login(method: &str) -> Result { } async fn list_request(q: &Query, cursor: &str) -> Result { - if q.kind != "drafts" { + if !matches!(q, Query::Drafts) { return run(&command(q, cursor)).await; } let program = super::hey_access::program()?; @@ -424,7 +426,7 @@ async fn list_request(q: &Query, cursor: &str) -> Result { } let stdout = String::from_utf8_lossy(&output.stdout); let diagnostic = format!("{} {}", stdout, String::from_utf8_lossy(&output.stderr)); - // The initial published CLI calls the read-only index `drafts`. + // Invariant: The initial published CLI calls the read-only index `drafts`. // No mutation is ever retried on a usage error. if diagnostic.contains("unknown command") && (diagnostic.contains("\\\"draft\\\"") || diagnostic.contains("\"draft\"")) @@ -551,18 +553,18 @@ pub async fn call(method: &str, params: &Value) -> Result { let total = rows.len(); let next = if offset.saturating_add(size) < total { format!("{}|{}", offset + size, cursor) - } else if q.unseen { + } else if q.unseen() { String::new() } else { - let next = match q.kind.as_str() { - "search" | "trash" if total > 0 => cursor + let next = match q { + Query::Search(_) | Query::Trash { .. } if total > 0 => cursor .parse::() .unwrap_or(1) .checked_add(1) .ok_or("Invalid HEY page cursor")? .to_string(), - "search" | "trash" => String::new(), - "drafts" => text(&answer["meta"]["next_page"]), + Query::Search(_) | Query::Trash { .. } => String::new(), + Query::Drafts => text(&answer["meta"]["next_page"]), _ => text(&answer["data"]["next_page"]), }; if next.is_empty() { diff --git a/src/providers/hey_access.rs b/src/providers/hey_access.rs index 62c3876cf..8e055646f 100644 --- a/src/providers/hey_access.rs +++ b/src/providers/hey_access.rs @@ -73,7 +73,7 @@ fn resolve_program() -> Option { if !metadata.is_file() || metadata.permissions().mode() & 0o111 == 0 { return None; } - // Multicall shims such as mise select the tool from argv[0]. + // Invariant: Multicall shims such as mise select the tool from argv[0]. // Canonicalize only for identity checks, never for invocation. Some(candidate) }) @@ -85,7 +85,7 @@ pub fn program() -> Result { .ok_or("hey_unavailable") } -// The official HEY client is not a Windows provider dependency. Never fall back +// Invariant: The official HEY client is not a Windows provider dependency. Never fall back // to a private API or an unrelated executable with the same name. #[cfg(not(unix))] fn resolve_program() -> Option { diff --git a/src/providers/hey_actions.rs b/src/providers/hey_actions.rs index 786088cc1..243ef85ef 100644 --- a/src/providers/hey_actions.rs +++ b/src/providers/hey_actions.rs @@ -91,7 +91,7 @@ fn prepare(method: &str, params: &Value) -> Result<(Vec, Vec), &'sta if method != "hey.saveDraft" || !numeric(id) { return Err("Invalid HEY draft id"); } - // Newer official clients accept draft edit body from stdin, like compose. + // Invariant: Newer official clients accept draft edit body from stdin, like compose. // Never put private body text in --message / the process table. args.extend(["draft".into(), "edit".into(), id.into()]); for (flag, value) in [ @@ -169,14 +169,14 @@ fn execute( params: &Value, run: impl FnOnce(&[String], &[u8]) -> Result, &'static str>, ) -> Result { - // Validate the complete batch before a subprocess can start. + // Invariant: Validate the complete batch before a subprocess can start. let (args, input) = prepare(method, params)?; let bytes = run(&args, &input)?; let answer: Value = serde_json::from_slice(&bytes).map_err(|_| "HEY returned invalid JSON")?; if answer["ok"] != true { return Err("HEY refused the request"); } - // Mutation output is only an acknowledgement; do not forward diagnostics. + // Invariant: Mutation output is only an acknowledgement; do not forward diagnostics. Ok(json!({"ok":true})) } @@ -227,7 +227,7 @@ fn decode_message(params: &Value) -> Result { "draftId":params.get("draftId").cloned().unwrap_or(json!(""))}); if thread.is_empty() { for (key, header) in [("to", "To"), ("cc", "Cc"), ("bcc", "Bcc")] { - // The official CLI accepts address lists. Pass the structural + // Invariant: The official CLI accepts address lists. Pass the structural // addresses, not decoded names for another parser to reinterpret. out[key] = json!(crate::message::envelope::addresses(&mail.headers, header)?.join(", ")); diff --git a/src/providers/outlook.rs b/src/providers/outlook.rs index 59f3f790d..e79cfe4bc 100644 --- a/src/providers/outlook.rs +++ b/src/providers/outlook.rs @@ -40,7 +40,7 @@ pub async fn connection_check(params: &Value) -> Result { if !configured { return Ok(json!({"mail":false,"graph":false,"calendar":false})); } - // Each provider state machine is large enough to overflow the backend + // Performance: Each provider state machine is large enough to overflow the backend // worker's stack when nested in one combined future. Separate Tokio tasks // keep their state on the heap and let the independent probes overlap. let mail_account = account.clone(); @@ -51,7 +51,7 @@ pub async fn connection_check(params: &Value) -> Result { }); let graph_account = account.clone(); let graph_and_calendar = tokio::spawn(async move { - // The frontend expires ordinary RPCs after 30 seconds. Bound the + // Invariant: The frontend expires ordinary RPCs after 30 seconds. Bound the // entire Graph chain, including token-lock and keyring waits, rather // than only the final HTTP request. within_graph_deadline( From 63be23366baebf07c7173bc50446e39d4446dcc4 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 019/568] Fix contact name upgrades at the directory limit --- src/contacts/mod.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/contacts/mod.rs b/src/contacts/mod.rs index d24cbc2ee..37970942c 100644 --- a/src/contacts/mod.rs +++ b/src/contacts/mod.rs @@ -34,7 +34,11 @@ fn address(email: &str) -> bool { } fn collect(book: &mut Book, name: &str, email: &str) { let email = email.trim(); - if !address(email) || book.len() >= MAX_CONTACTS { + if !address(email) { + return; + } + let key = email.to_lowercase(); + if book.len() >= MAX_CONTACTS && !book.contains_key(&key) { return; } let name: String = name @@ -42,7 +46,6 @@ fn collect(book: &mut Book, name: &str, email: &str) { .chars() .filter(|character| !character.is_control()) .collect(); - let key = email.to_lowercase(); if !book.contains_key(&key) || (book[&key]["name"] == "" && !name.is_empty()) { book.insert(key, json!({"name":name,"email":email})); } @@ -334,6 +337,18 @@ mod tests { assert_eq!(book["a@example.com"]["name"], "Jane"); } #[test] + fn contact_limit_allows_existing_address_name_updates() { + let mut book = Book::new(); + for index in 0..MAX_CONTACTS { + collect(&mut book, "", &format!("contact{index}@example.com")); + } + collect(&mut book, "Updated Name", "contact0@example.com"); + collect(&mut book, "New Contact", "overflow@example.com"); + assert_eq!(book.len(), MAX_CONTACTS); + assert_eq!(book["contact0@example.com"]["name"], "Updated Name"); + assert!(!book.contains_key("overflow@example.com")); + } + #[test] fn named_contact_replaces_inferred_empty_name() { let mut book = Book::new(); collect(&mut book, "", "A@example.com"); From d700afa403c2e6b8cc64b4b43b6e5f31c0d6fac4 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 020/568] Name credential session and secret values explicitly --- src/auth/callback.rs | 42 ++++++++--------- src/auth/credentials.rs | 40 ++++++++--------- src/auth/graph.rs | 2 +- src/auth/mod.rs | 22 ++++----- src/credentials/mod.rs | 12 ++--- src/credentials/secret_service.rs | 14 +++--- src/credentials/secret_service_tests.rs | 4 +- src/credentials/tests.rs | 8 ++-- src/public_http/mod.rs | 60 ++++++++++++------------- src/public_http/tests.rs | 8 ++-- src/tls/tests.rs | 22 ++++----- 11 files changed, 117 insertions(+), 117 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 5cbee8112..14064777d 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -25,7 +25,7 @@ fn random() -> Result { fn text<'a>(params: &'a Value, key: &str) -> Result<&'a str, &'static str> { params[key] .as_str() - .filter(|s| s.len() <= 8192 && !s.chars().any(char::is_control)) + .filter(|value| value.len() <= 8192 && !value.chars().any(char::is_control)) .ok_or("invalid_params") } @@ -71,7 +71,7 @@ impl Flows { let hint = text(params, "loginHint")?.to_owned(); let port = params["port"] .as_u64() - .filter(|p| (1024..=65535).contains(p)) + .filter(|port| (1024..=65535).contains(port)) .ok_or("invalid_params")? as u16; let scopes = params["scopes"].as_array().ok_or("invalid_params")?; if scopes.len() > 32 { @@ -79,9 +79,9 @@ impl Flows { } let scopes: Vec<&str> = scopes .iter() - .map(|s| { - s.as_str() - .filter(|s| s.len() < 512 && !s.chars().any(char::is_whitespace)) + .map(|value| { + value.as_str() + .filter(|value| value.len() < 512 && !value.chars().any(char::is_whitespace)) .ok_or("invalid_params") }) .collect::>()?; @@ -162,13 +162,13 @@ async fn finish_google(mut response: Value, client_id: &str) -> Result Result = lines .filter_map(|line| line.split_once(':')) - .filter(|(k, _)| k.eq_ignore_ascii_case("host")) + .filter(|(key, _)| key.eq_ignore_ascii_case("host")) .collect(); if hosts.len() != 1 || hosts[0].1.trim() != format!("127.0.0.1:{port}") { return Err("auth_invalid_callback"); @@ -214,8 +214,8 @@ fn callback(request: &str, state: &str, port: u16) -> Result Result = url.query_pairs().collect(); - let states: Vec<_> = pairs.iter().filter(|(k, _)| k == "state").collect(); - let codes: Vec<_> = pairs.iter().filter(|(k, _)| k == "code").collect(); + let states: Vec<_> = pairs.iter().filter(|(key, _)| key == "state").collect(); + let codes: Vec<_> = pairs.iter().filter(|(key, _)| key == "code").collect(); if states.len() != 1 || states[0].1 != state || codes.len() != 1 || codes[0].1.is_empty() - || pairs.iter().any(|(k, _)| k == "error") + || pairs.iter().any(|(key, _)| key == "error") || codes[0] .1 .chars() - .any(|c| !c.is_ascii() || c.is_ascii_control() || c.is_whitespace()) + .any(|character| !character.is_ascii() || character.is_ascii_control() || character.is_whitespace()) { return Err("auth_invalid_callback"); } @@ -419,10 +419,10 @@ mod tests { #[test] fn callback_checks_exact_route_host_and_single_state() { - let req = |path: &str, host: &str| format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n"); + let request_for = |path: &str, host: &str| format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n"); assert_eq!( callback( - &req( + &request_for( "/oauth2callback?code=good&state=expected", "127.0.0.1:53682" ), @@ -439,11 +439,11 @@ mod tests { "/oauth2callback/../?code=x&state=expected", "/oauth2callback?code=%00&state=expected", ] { - assert!(callback(&req(path, "127.0.0.1:53682"), "expected", 53682).is_err()); + assert!(callback(&request_for(path, "127.0.0.1:53682"), "expected", 53682).is_err()); } assert!( callback( - &req("/oauth2callback?code=good&state=expected", "evil.test"), + &request_for("/oauth2callback?code=good&state=expected", "evil.test"), "expected", 53682 ) diff --git a/src/auth/credentials.rs b/src/auth/credentials.rs index 4c308a55d..37b73fb08 100644 --- a/src/auth/credentials.rs +++ b/src/auth/credentials.rs @@ -25,13 +25,13 @@ fn settings_with(provider: &str, account: &str, raw: Value) -> Result Result<(), &'static str> { if !account.starts_with(&format!("{provider}:")) || !account.contains('@') || account.len() > 1024 - || account.chars().any(|c| c.is_control() || c.is_whitespace()) + || account.chars().any(|character| character.is_control() || character.is_whitespace()) { return Err("auth_account_invalid"); } @@ -319,10 +319,10 @@ where } if token["error_codes"] .as_array() - .is_some_and(|codes| codes.iter().any(|v| *v == 65001)) + .is_some_and(|codes| codes.iter().any(|value| *value == 65001)) || token["error_description"] .as_str() - .is_some_and(|s| s.contains("AADSTS65001")) + .is_some_and(|value| value.contains("AADSTS65001")) { return Err("auth_consent_required"); } @@ -338,7 +338,7 @@ where } let lifetime = token["expires_in"] .as_u64() - .filter(|n| *n <= 86400) + .filter(|seconds| *seconds <= 86400) .unwrap_or(0); Ok((access.to_owned(), lifetime)) } @@ -359,10 +359,10 @@ fn aadsts_code(token: &Value, code: u64) -> bool { fn outlook_access(token: &Value) -> Result<&str, &'static str> { token["access_token"] .as_str() - .filter(|s| { - !s.is_empty() - && s.len() <= 16384 - && !s.chars().any(|c| c.is_whitespace() || c.is_control()) + .filter(|value| { + !value.is_empty() + && value.len() <= 16384 + && !value.chars().any(|character| character.is_whitespace() || character.is_control()) }) .ok_or("auth_invalid_response") } @@ -371,13 +371,13 @@ fn outlook_scopes(token: &Value, scope: &str) -> bool { let granted = token["scope"].as_str().unwrap_or(""); scope .split_whitespace() - .filter(|s| s.starts_with("https://")) + .filter(|value| value.starts_with("https://")) .all(|required| { - granted.split_whitespace().any(|s| { - s == required + granted.split_whitespace().any(|value| { + value == required || required .strip_prefix("https://graph.microsoft.com/") - .is_some_and(|short| s == short) + .is_some_and(|short| value == short) }) }) } @@ -427,7 +427,7 @@ pub(super) async fn change_outlook(params: &Value, clear: bool) -> Result Result<(), &'static str> { .await .iter() .filter(|(key, _)| key.starts_with(&prefix)) - .map(|(_, v)| v.clone()) + .map(|(_, value)| value.clone()) .collect(); for lock in locks { lock.lock().await.clear(); @@ -498,11 +498,11 @@ where || account.is_empty() || !account.contains('@') || account.len() > 1024 - || account.chars().any(|c| c.is_control() || c.is_whitespace()) + || account.chars().any(|character| character.is_control() || character.is_whitespace()) || token.is_empty() || client_id.chars().any(char::is_control) || token.len() > 16384 - || token.chars().any(|c| c.is_whitespace() || c.is_control()) + || token.chars().any(|character| character.is_whitespace() || character.is_control()) { return Err("auth_secret_invalid"); } @@ -558,7 +558,7 @@ where { if let Some(rotated) = token["refresh_token"] .as_str() - .filter(|s| !s.is_empty() && *s != refresh) + .filter(|value| !value.is_empty() && *value != refresh) { if rotated.len() > 16384 || rotated.chars().any(char::is_control) { return Err("auth_invalid_response"); diff --git a/src/auth/graph.rs b/src/auth/graph.rs index 40cdf5161..696941052 100644 --- a/src/auth/graph.rs +++ b/src/auth/graph.rs @@ -4,7 +4,7 @@ pub(super) async fn send(params: &Value) -> Result { let fields = params.as_object().ok_or("invalid_params")?; if fields .keys() - .any(|k| !["accountId", "raw"].contains(&k.as_str())) + .any(|key| !["accountId", "raw"].contains(&key.as_str())) { return Err("invalid_params"); } diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 9d808ad9e..4e1c2c99c 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -29,13 +29,13 @@ fn client() -> Result<&'static reqwest::Client, &'static str> { .map_err(|_| "auth_transport_failed") }) .as_ref() - .map_err(|e| *e) + .map_err(|error| *error) } fn destination(params: &Value) -> Result { - let p = params.as_object().ok_or("invalid_params")?; - if p.keys() - .any(|k| !["provider", "endpoint", "tenant", "body"].contains(&k.as_str())) + let fields = params.as_object().ok_or("invalid_params")?; + if fields.keys() + .any(|key| !["provider", "endpoint", "tenant", "body"].contains(&key.as_str())) { return Err("invalid_params"); } @@ -44,7 +44,7 @@ fn destination(params: &Value) -> Result { (Some("outlook"), Some(endpoint @ ("token" | "device"))) => { let tenant = params .get("tenant") - .map(|v| v.as_str().ok_or("invalid_params")) + .map(|value| value.as_str().ok_or("invalid_params")) .transpose()? .unwrap_or("consumers"); if tenant.is_empty() @@ -53,7 +53,7 @@ fn destination(params: &Value) -> Result { || !tenant.as_bytes()[0].is_ascii_alphanumeric() || !tenant .bytes() - .all(|b| b.is_ascii_alphanumeric() || b".-".contains(&b)) + .all(|byte| byte.is_ascii_alphanumeric() || b".-".contains(&byte)) { return Err("invalid_params"); } @@ -95,7 +95,7 @@ async fn post_with_deadline( if status.is_redirection() { return Err("auth_redirect_refused"); } - if response.content_length().is_some_and(|n| n > LIMIT as u64) { + if response.content_length().is_some_and(|size| size > LIMIT as u64) { return Err("auth_response_too_large"); } let mut bytes = Vec::new(); @@ -148,7 +148,7 @@ impl Session { let account = params["accountId"].as_str().ok_or("invalid_params")?; let resource = params .get("resource") - .map(|v| v.as_str().ok_or("invalid_params")) + .map(|value| value.as_str().ok_or("invalid_params")) .transpose()? .unwrap_or("mail"); let access = access_token("outlook", account, resource).await?; @@ -176,7 +176,7 @@ impl Session { } let url = destination(params)?; let body = params["body"].as_str().ok_or("invalid_params")?; - if body.len() > LIMIT || body.bytes().any(|b| b < 32 || b == 127) { + if body.len() > LIMIT || body.bytes().any(|byte| byte < 32 || byte == 127) { return Err("invalid_params"); } post(client()?, &url, body.into()).await @@ -283,7 +283,7 @@ mod tests { net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let addr = listener.local_addr().unwrap(); + let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { let (mut socket, _) = listener.accept().await.unwrap(); let mut bytes = [0; 4096]; @@ -301,7 +301,7 @@ mod tests { .build() .unwrap(); assert_eq!( - post(&client, &format!("http://{addr}"), "token=synthetic".into()).await, + post(&client, &format!("http://{address}"), "token=synthetic".into()).await, Err("auth_redirect_refused") ); server.await.unwrap(); diff --git a/src/credentials/mod.rs b/src/credentials/mod.rs index f15575808..9082a5e1a 100644 --- a/src/credentials/mod.rs +++ b/src/credentials/mod.rs @@ -158,12 +158,12 @@ impl CredentialKey { if self.provider != provider { return Err(Error::InvalidKey); } - let mut attrs = BTreeMap::from([ + let mut attributes = BTreeMap::from([ ("service".into(), "omamail".into()), ("kind".into(), kind.into()), ]); if provider == "caldav" { - attrs.insert("source".into(), self.account_id.clone()); + attributes.insert("source".into(), self.account_id.clone()); } else { if self.account_id.chars().any(char::is_whitespace) || (provider != "gmail" && !self.account_id.starts_with(&format!("{provider}:"))) @@ -174,18 +174,18 @@ impl CredentialKey { { return Err(Error::InvalidKey); } - attrs.insert("account".into(), self.account_id.to_lowercase()); + attributes.insert("account".into(), self.account_id.to_lowercase()); } if let CredentialKind::GoogleRefreshToken { client_id } | CredentialKind::OutlookRefreshToken { client_id } = &self.kind { metadata(client_id)?; - attrs.insert("client-id".into(), client_id.clone()); + attributes.insert("client-id".into(), client_id.clone()); } if matches!(self.kind, CredentialKind::GoogleRefreshToken { .. }) { - attrs.insert("grant".into(), "calendar-events-v1".into()); + attributes.insert("grant".into(), "calendar-events-v1".into()); } - Ok(attrs) + Ok(attributes) } /// Length-delimited fields prevent delimiter collisions. Hashing also keeps diff --git a/src/credentials/secret_service.rs b/src/credentials/secret_service.rs index 8fa991f91..fad5f4735 100644 --- a/src/credentials/secret_service.rs +++ b/src/credentials/secret_service.rs @@ -260,13 +260,13 @@ async fn close(connection: zbus::Connection) { async fn find<'a>( service: &'a SecretService<'a>, - attrs: &HashMap, + attributes: &HashMap, ) -> Result>, Fault> { let result = service .search_items( - attrs + attributes .iter() - .map(|(k, v)| (k.as_str(), v.as_str())) + .map(|(name, value)| (name.as_str(), value.as_str())) .collect(), ) .await @@ -289,12 +289,12 @@ async fn execute( key: &CredentialKey, operation: Operation<'_>, ) -> Result, Fault> { - let attrs = key + let attributes = key .attributes() .map_err(Fault::Answer)? .into_iter() .collect(); - let item = find(service, &attrs).await?; + let item = find(service, &attributes).await?; match operation { Operation::Get => { let item = item.ok_or(Fault::Answer(Error::Missing))?; @@ -326,9 +326,9 @@ async fn execute( collection .create_item( "Omamail", - attrs + attributes .iter() - .map(|(k, v)| (k.as_str(), v.as_str())) + .map(|(name, value)| (name.as_str(), value.as_str())) .collect(), secret, false, diff --git a/src/credentials/secret_service_tests.rs b/src/credentials/secret_service_tests.rs index 3642cc444..a173d8310 100644 --- a/src/credentials/secret_service_tests.rs +++ b/src/credentials/secret_service_tests.rs @@ -519,14 +519,14 @@ fn credentials_native_linux_a_refused_unlock_keeps_the_session() { #[ignore = "requires native dbus-daemon; mandatory in the Linux credential gate"] fn credentials_native_linux_silently_unlocks_a_locked_item() { let fixture = Fixture::with_locked_item(); - let attrs: HashMap<_, _> = key().attributes().unwrap().into_iter().collect(); + let attributes: HashMap<_, _> = key().attributes().unwrap().into_iter().collect(); let found = fixture.runtime.block_on(async { let connection = fixture.client().await.unwrap(); let service = SecretService::connect_with_existing(EncryptionType::Dh, connection) .await .unwrap(); - find(&service, &attrs).await.map(|item| item.is_some()) + find(&service, &attributes).await.map(|item| item.is_some()) }); assert!(matches!(found, Ok(true))); diff --git a/src/credentials/tests.rs b/src/credentials/tests.rs index 1536d25f5..192bc7b68 100644 --- a/src/credentials/tests.rs +++ b/src/credentials/tests.rs @@ -138,13 +138,13 @@ fn credentials_native_contract() { b"control\x01", b"opaque\xff", ]; - for (i, key) in cleanup.0.iter().enumerate() { + for (index, key) in cleanup.0.iter().enumerate() { NativeStore - .put(key, format!("synthetic-{i}").as_bytes()) + .put(key, format!("synthetic-{index}").as_bytes()) .unwrap(); } - for (i, key) in cleanup.0.iter().enumerate() { - assert!(NativeStore.get(key).unwrap().as_slice() == format!("synthetic-{i}").as_bytes()); + for (index, key) in cleanup.0.iter().enumerate() { + assert!(NativeStore.get(key).unwrap().as_slice() == format!("synthetic-{index}").as_bytes()); } for (index, sample) in samples.iter().enumerate() { NativeStore.put(&cleanup.0[0], sample).unwrap(); diff --git a/src/public_http/mod.rs b/src/public_http/mod.rs index 52eca8614..cc3d0ef28 100644 --- a/src/public_http/mod.rs +++ b/src/public_http/mod.rs @@ -26,18 +26,18 @@ impl Resolve for PublicResolver { builder.options_mut().ip_strategy = LookupIpStrategy::Ipv4AndIpv6; let resolver = builder.build(); let answer = resolver.lookup_ip(name.as_str()).await?; - let ips: Vec<_> = answer.iter().collect(); - let addresses = checked_addresses(ips).map_err(std::io::Error::other)?; + let addresses: Vec<_> = answer.iter().collect(); + let addresses = checked_addresses(addresses).map_err(std::io::Error::other)?; Ok(Box::new(addresses.into_iter()) as Addrs) }) } } -fn checked_addresses(ips: Vec) -> Result, &'static str> { - if ips.is_empty() || ips.iter().any(|ip| !is_public(*ip)) { +fn checked_addresses(addresses: Vec) -> Result, &'static str> { + if addresses.is_empty() || addresses.iter().any(|ip| !is_public(*ip)) { return Err("public_destination_refused"); } - Ok(ips.into_iter().map(|ip| SocketAddr::new(ip, 0)).collect()) + Ok(addresses.into_iter().map(|ip| SocketAddr::new(ip, 0)).collect()) } /// Conservative global-unicast policy, including transition mechanisms that @@ -45,28 +45,28 @@ fn checked_addresses(ips: Vec) -> Result, &'static str> pub fn is_public(ip: IpAddr) -> bool { match ip { IpAddr::V4(ip) => { - let [a, b, c, _] = ip.octets(); - !(a == 0 - || a == 10 - || a == 127 - || a >= 224 - || (a == 100 && (64..=127).contains(&b)) - || (a == 169 && b == 254) - || (a == 172 && (16..=31).contains(&b)) - || (a == 192 - && ((b == 168) || (b == 0 && (c == 0 || c == 2)) || (b == 88 && c == 99))) - || (a == 198 && (b == 18 || b == 19 || (b == 51 && c == 100))) - || (a == 203 && b == 0 && c == 113)) + let [first_octet, second_octet, third_octet, _] = ip.octets(); + !(first_octet == 0 + || first_octet == 10 + || first_octet == 127 + || first_octet >= 224 + || (first_octet == 100 && (64..=127).contains(&second_octet)) + || (first_octet == 169 && second_octet == 254) + || (first_octet == 172 && (16..=31).contains(&second_octet)) + || (first_octet == 192 + && ((second_octet == 168) || (second_octet == 0 && (third_octet == 0 || third_octet == 2)) || (second_octet == 88 && third_octet == 99))) + || (first_octet == 198 && (second_octet == 18 || second_octet == 19 || (second_octet == 51 && third_octet == 100))) + || (first_octet == 203 && second_octet == 0 && third_octet == 113)) } IpAddr::V6(ip) => { - let s = ip.segments(); + let segments = ip.segments(); // Only currently allocated global unicast; excludes mapped IPv4, // NAT64, local/multicast and deprecated site-local addresses. - (s[0] & 0xe000) == 0x2000 - && !(s[0] == 0x2001 && s[1] < 0x0200) - && !(s[0] == 0x2001 && s[1] == 0x0db8) - && s[0] != 0x2002 - && !(s[0] == 0x3fff && s[1] < 0x1000) + (segments[0] & 0xe000) == 0x2000 + && !(segments[0] == 0x2001 && segments[1] < 0x0200) + && !(segments[0] == 0x2001 && segments[1] == 0x0db8) + && segments[0] != 0x2002 + && !(segments[0] == 0x3fff && segments[1] < 0x1000) } } } @@ -77,7 +77,7 @@ fn parse_url(raw: &str, https_only: bool) -> Result { || raw.len() > 128 * 1024 || raw .chars() - .any(|c| c.is_control() || c.is_whitespace() || c == '\\') + .any(|character| character.is_control() || character.is_whitespace() || character == '\\') { return Err("public_url_invalid"); } @@ -115,7 +115,7 @@ fn parse_url(raw: &str, https_only: bool) -> Result { || label.ends_with('-') || !label .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-') + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') }) { return Err("public_url_invalid"); @@ -151,7 +151,7 @@ async fn execute( client: &Client, url: Url, method: Method, - max: usize, + max_bytes: usize, deadline: Duration, ) -> Result { tokio::time::timeout(deadline, async { @@ -166,7 +166,7 @@ async fn execute( let content_type = response .headers() .get("Content-Type") - .and_then(|v| v.to_str().ok()) + .and_then(|value| value.to_str().ok()) .unwrap_or("") .split(';') .next() @@ -179,18 +179,18 @@ async fn execute( if response .headers() .get("Content-Encoding") - .is_some_and(|v| v != "identity") + .is_some_and(|value| value != "identity") { return Err("public_encoding_refused"); } if response .content_length() - .is_some_and(|size| size > max as u64) + .is_some_and(|size| size > max_bytes as u64) { return Err("public_response_too_large"); } while let Some(chunk) = response.chunk().await.map_err(|_| "public_http_failed")? { - if chunk.len() > max - body.len() { + if chunk.len() > max_bytes - body.len() { return Err("public_response_too_large"); } body.extend_from_slice(&chunk); diff --git a/src/public_http/tests.rs b/src/public_http/tests.rs index 9642ad760..00176486b 100644 --- a/src/public_http/tests.rs +++ b/src/public_http/tests.rs @@ -91,12 +91,12 @@ async fn server(response: Vec) -> (SocketAddr, tokio::task::JoinHandle std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("omamail-tls-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir + let directory = std::env::temp_dir().join(format!("omamail-tls-{}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + directory } From 02bf565f6e77d1c5892e5ab5e83e185b57d722ce Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 021/568] Clarify authentication boundary invariants --- src/auth/callback.rs | 12 ++++---- src/auth/credentials.rs | 23 +++++++------- src/auth/graph.rs | 2 +- src/credentials/keychain.rs | 2 +- src/credentials/rpc.rs | 2 +- src/credentials/secret_service.rs | 40 ++++++++++++------------- src/credentials/secret_service_tests.rs | 29 +++++++----------- src/credentials/tests.rs | 4 +-- src/credentials/windows.rs | 4 +-- src/public_http/mod.rs | 6 ++-- src/public_http/tests.rs | 4 +-- src/tls/tests.rs | 3 -- 12 files changed, 59 insertions(+), 72 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 14064777d..719aec2fe 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -1,4 +1,4 @@ -//! Loopback OAuth listener. PKCE and state never leave the pending Rust flow. +//! Loopback OAuth listener with pending PKCE and state owned by Rust. use super::*; use base64::Engine; use sha2::{Digest, Sha256}; @@ -148,7 +148,7 @@ async fn finish_google(mut response: Value, client_id: &str) -> Result Result Result<&str, &'static str> { Ok(value) } -// The setup page stores an empty string for a personal account's tenant +// Invariant: The setup page stores an empty string for a personal account's tenant // (there is no tenant to name), while a missing field only ever occurs on // data from before that field existed. Both mean the same thing here, and // must resolve to the same string everywhere it is read: `destination` @@ -146,7 +146,7 @@ fn cached_token( wall_now: std::time::SystemTime, ) -> Option { let (token, expiry) = tokens.get(resource)?; - // Linux's monotonic clock stops during suspend. Wall time catches sleep + // Invariant: Linux's monotonic clock stops during suspend. Wall time catches sleep // and forward corrections; the monotonic deadline still bounds reuse if // the wall clock moves backwards. Keep the original 60-second margin. let monotonic_remaining = expiry.monotonic.checked_duration_since(monotonic_now)?; @@ -207,7 +207,7 @@ async fn access_token_with( let client_id = client_id.to_owned(); let resource = resource.to_owned(); in_outlook_lane(lock, move |mut tokens| async move { - // One refresh at a time per mailbox, shared by mail and Graph resources: + // Invariant: One refresh at a time per mailbox, shared by mail and Graph resources: // rotating a refresh token must not race another resource's exchange. if let Some(token) = cached_token( &tokens, @@ -248,7 +248,7 @@ async fn access_token_with( .await } -// The account lock remains held across every exchange and refresh-token store. +// Invariant: The account lock remains held across every exchange and refresh-token store. // Inject only the transport and store so provider fixtures never touch a keyring. async fn refresh_outlook_with( client_id: &str, @@ -264,7 +264,7 @@ where PersistFuture: std::future::Future>, { let scope = scope(resource)?; - // Both network exchanges share one budget below the UI's RPC timeout. + // Invariant: Both network exchanges share one budget below the UI's RPC timeout. // Do not time out a keyring write: its blocking native operation must // finish while the caller still owns the account rotation lock. let deadline = tokio::time::Instant::now() + Duration::from_secs(20); @@ -282,7 +282,7 @@ where let token: Value = serde_json::from_str(reply["body"].as_str().ok_or("auth_invalid_response")?) .map_err(|_| "auth_invalid_response")?; if reply["status"] != 200 { - // Consumers can refuse the first Graph grant with 70000 while this + // Invariant: Consumers can refuse the first Graph grant with 70000 while this // refresh token still works for mail. A cached mail access token is // not evidence: verify this exact grant, under the same rotation lock. if resource == "graph" && token["error"] == "invalid_grant" && aadsts_code(&token, 70000) { @@ -309,7 +309,7 @@ where }); } outlook_access(&mail)?; - // Even a scope refusal may rotate the grant. Keep the successful + // Invariant: Even a scope refusal may rotate the grant. Keep the successful // mail probe's rotation before reporting missing Graph consent. persist(mail.clone()).await?; if !outlook_scopes(&mail, mail_scope) { @@ -388,7 +388,7 @@ where F: FnOnce(tokio::sync::OwnedMutexGuard) -> Fut + Send + 'static, Fut: std::future::Future> + Send + 'static, { - // Waiting is cancellable. Once admitted, finish under the owned guard: + // Invariant: Waiting is cancellable. Once admitted, finish under the owned guard: // native keyring writes use spawn_blocking and cannot be cancelled when // a calendar caller's outer deadline drops its authentication future. let guard = lane.lock_owned().await; @@ -587,7 +587,7 @@ mod tests { "refresh_token":"synthetic-rotated", "scope":scope("mail").unwrap()}) } - // This is Microsoft's consumer-account refusal, not proof the grant died. + // Invariant: This is Microsoft's consumer-account refusal, not proof the grant died. fn unconsented_graph() -> Value { json!({"error":"invalid_grant", "error_codes":[70000], "error_description":"AADSTS70000: The request was denied because one or more scopes requested are unauthorized or expired. The user must first sign in and grant the client application access to the requested scope."}) @@ -1084,7 +1084,7 @@ mod tests { "organizations" ); } - /// A personal account's setup page writes an empty `tenant`, not a + /// Invariant: A personal account's setup page writes an empty `tenant`, not a /// missing one (there is no tenant to name). `destination` rejects an /// empty tenant outright, so building its URL straight from the stored /// field failed every refresh for exactly the accounts that are meant to @@ -1119,7 +1119,7 @@ mod tests { ("mail".into(), ("mail-token".into(), expiry)), ("graph".into(), ("graph-token".into(), expiry)), ]); - // Linux monotonic time advanced only while awake; wall time includes + // Invariant: Linux monotonic time advanced only while awake; wall time includes // the five hours asleep. Neither resource may reuse the old token. for resource in ["mail", "graph"] { assert!( @@ -1178,7 +1178,6 @@ mod tests { ("graph-token".into(), expiry_at(monotonic, wall, 1800)), ), ]); - // Short suspend does not force a needless refresh of still-live grants. assert_eq!( cached_token( &tokens, diff --git a/src/auth/graph.rs b/src/auth/graph.rs index 696941052..9679e98f7 100644 --- a/src/auth/graph.rs +++ b/src/auth/graph.rs @@ -13,7 +13,7 @@ pub(super) async fn send(params: &Value) -> Result { if raw.len() > 16 * 1024 * 1024 { return Err("message_too_large"); } - // Graph's MIME endpoint consumes standard base64, never raw MIME bytes. + // Invariant: Graph's MIME endpoint consumes standard base64, never raw MIME bytes. use base64::Engine; let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(raw) diff --git a/src/credentials/keychain.rs b/src/credentials/keychain.rs index ed592fbc5..99ce8ee9d 100644 --- a/src/credentials/keychain.rs +++ b/src/credentials/keychain.rs @@ -6,7 +6,7 @@ use security_framework::passwords::{ const SERVICE: &str = "org.omamail.credentials.v1"; fn error(error: security_framework::base::Error) -> Error { - // errSecItemNotFound. Authorization denial, locked keychains and other + // Invariant: errSecItemNotFound. Authorization denial, locked keychains and other // platform errors are failures, never a claim that an account is signed out. if error.code() == -25300 { Error::Missing diff --git a/src/credentials/rpc.rs b/src/credentials/rpc.rs index 484ed67eb..a087e452d 100644 --- a/src/credentials/rpc.rs +++ b/src/credentials/rpc.rs @@ -124,7 +124,7 @@ async fn call_with_store( method: &str, params: &Value, ) -> Result { - // Parsing before the first await is deliberate: malformed metadata or a + // Invariant: Parsing before the first await is deliberate: malformed metadata or a // secret containing NUL cannot prompt, read, write, or delete in a native // credential store. match parse(method, params)? { diff --git a/src/credentials/secret_service.rs b/src/credentials/secret_service.rs index fad5f4735..a3e206319 100644 --- a/src/credentials/secret_service.rs +++ b/src/credentials/secret_service.rs @@ -24,15 +24,15 @@ enum Operation<'a> { Delete, } -/// Why an operation produced no secret. Only a session that failed is worth +/// Invariant: Why an operation produced no secret. Only a session that failed is worth /// dropping: a locked item and a locked collection are answers the daemon gave /// over a connection that is still good, and dropping the session for those /// would renegotiate on every read against a keyring that is merely locked. enum Fault { Answer(Error), - /// The call did not complete. A read may be repeated on a fresh session. + /// Invariant: The call did not complete. A read may be repeated on a fresh session. Transport, - /// The deadline passed. The session is unusable and nothing is repeated: + /// Invariant: The deadline passed. The session is unusable and nothing is repeated: /// the deadline is the caller's bound and a second attempt would double it. Timeout, } @@ -46,21 +46,20 @@ impl Fault { } } -/// A negotiated session. `SecretService` owns the connection it was built on, +/// Invariant: A negotiated session. `SecretService` owns the connection it was built on, /// so dropping the last `Arc` closes it. Held behind an `Arc` so an operation /// keeps it alive after it has been dropped from the cache. struct Session { service: SecretService<'static>, } -/// The runtime owning the shared connection's zbus tasks, and the session. struct Shared { runtime: tokio::runtime::Runtime, session: Mutex>>, } impl Shared { - /// One worker, so credential operations still run alongside each other as + /// Invariant: One worker, so credential operations still run alongside each other as /// they did when each built its own runtime. A current-thread runtime would /// serialise every operation behind whichever one holds it, and a stuck /// prompt would then block them all for the whole deadline. @@ -77,19 +76,18 @@ impl Shared { } } -/// A failed build is not remembered: the next operation tries again, as it did +/// Invariant: A failed build is not remembered: the next operation tries again, as it did /// when every operation built its own runtime. fn shared() -> Result<&'static Shared, Error> { static SHARED: OnceLock = OnceLock::new(); if let Some(shared) = SHARED.get() { return Ok(shared); } - // A racing caller may install theirs first, in which case ours is dropped. let _ = SHARED.set(Shared::new()?); SHARED.get().ok_or(Error::Unavailable) } -/// The session slot, recovered if a panic poisoned it. The slot is only written +/// Invariant: The session slot, recovered if a panic poisoned it. The slot is only written /// once the connection is built, so a poisoned lock guards nothing broken and /// refusing it would disable credentials for the life of the process. fn slot(shared: &Shared) -> MutexGuard<'_, Option>> { @@ -99,7 +97,7 @@ fn slot(shared: &Shared) -> MutexGuard<'_, Option>> { .unwrap_or_else(PoisonError::into_inner) } -/// What is left of the caller's deadline, or None once it has passed. One +/// Invariant: What is left of the caller's deadline, or None once it has passed. One /// budget covers opening the session, the operation and any second attempt. fn remaining(until: Instant) -> Option { until @@ -120,7 +118,7 @@ fn run(key: &CredentialKey, operation: Operation<'_>) -> Result, run_on(shared()?, key, operation, session_bus, DEADLINE) } -/// Runs one operation on the shared session, opening it if there is none. +/// Invariant: Runs one operation on the shared session, opening it if there is none. /// /// One `block_on` and one deadline cover opening the session and running the /// operation, so a credential read costs the caller exactly what it asked for. @@ -160,7 +158,7 @@ where } } -/// One attempt at the operation on the shared session, opening one if there is +/// Invariant: One attempt at the operation on the shared session, opening one if there is /// none. Returns the session it used alongside any fault, so the caller drops /// that session and not a newer one. #[allow(clippy::type_complexity)] @@ -192,7 +190,7 @@ where .map_err(|fault| (Some(session), fault)) } -/// The shared session, negotiated if there is none. +/// Invariant: The shared session, negotiated if there is none. /// /// The lock is held across the negotiation so that two callers arriving at an /// empty slot do not each open one; opening a single session is the point. It @@ -222,7 +220,7 @@ where }) .await .unwrap_or(Err(Fault::Timeout)); - // A session that half-opened still holds a name on the bus. + // Invariant: A session that half-opened still holds a name on the bus. if let (Err(_), Some(connection)) = (&result, opened) { close(connection).await; } @@ -233,7 +231,7 @@ where Ok(session) } -/// Drops the session from the cache so the next operation opens a fresh one. +/// Invariant: Drops the session from the cache so the next operation opens a fresh one. /// /// It is not closed here. Concurrent operations run on their own blocking /// threads and share this connection, and closing it terminates their in-flight @@ -250,7 +248,7 @@ fn invalidate(shared: &Shared, session: &Arc) { } } -/// This is close, never graceful_shutdown: waiting for a pending prompt or an +/// Invariant: This is close, never graceful_shutdown: waiting for a pending prompt or an /// outstanding clone before closing would recreate the indefinite wait. It runs /// when a session has already failed rather than after every operation, so it /// no longer races the handshake of the session that follows it. @@ -311,7 +309,7 @@ async fn execute( .get_default_collection() .await .map_err(|_| Fault::Transport)?; - // A blank-password collection is locked again by every fresh + // Invariant: A blank-password collection is locked again by every fresh // login, and unlocking it is an answer the daemon gives over a // connection that is still good; a password-protected one // prompts inside this operation's single deadline. Refusing @@ -322,7 +320,7 @@ async fn execute( if collection.is_locked().await.map_err(|_| Fault::Transport)? { collection.unlock().await.map_err(|_| Fault::Transport)?; } - // Keep older grants intact until the current-scope item exists. + // Invariant: Keep older grants intact until the current-scope item exists. collection .create_item( "Omamail", @@ -349,7 +347,7 @@ async fn execute( } } -/// One operation on a private session, closed immediately afterwards. The +/// Invariant: One operation on a private session, closed immediately afterwards. The /// connection-lifetime tests observe a single attempt this way; production /// shares one session through `run` and lets the last reference close it. #[cfg(test)] @@ -383,12 +381,12 @@ fn run_with( ); let Shared { runtime, session } = shared; drop(session); - // Awaited rather than left to drop, so the bus has deregistered the name by + // Invariant: Awaited rather than left to drop, so the bus has deregistered the name by // the time a one-shot returns. if let Some(connection) = opened.lock().ok().and_then(|mut slot| slot.take()) { runtime.block_on(async { close(connection).await }); } - // zbus's async reader/signal tasks are owned by this runtime. There is no + // Invariant: zbus's async reader/signal tasks are owned by this runtime. There is no // detached blocking secret-service call left behind when the worker returns. runtime.shutdown_timeout(Duration::ZERO); result diff --git a/src/credentials/secret_service_tests.rs b/src/credentials/secret_service_tests.rs index a173d8310..33153b80e 100644 --- a/src/credentials/secret_service_tests.rs +++ b/src/credentials/secret_service_tests.rs @@ -25,19 +25,12 @@ impl Drop for Daemon { struct Service { denial: bool, missing: bool, - /// Reports the item as present but locked, which the daemon answers over a - /// connection that is still good. locked: Arc, - /// Reports the default collection as locked, the state a fresh login - /// leaves a blank-password keyring in. collection_locked: Arc, unlock_denial: bool, unlocks: Arc, - /// Counts negotiated sessions, which is what tells a reused connection from - /// one rebuilt per operation. sessions: Arc, searches: Arc, - /// Searches to fail before answering, for exercising reconnection. failures: Arc, } #[zbus::interface(name = "org.freedesktop.Secret.Service")] @@ -100,7 +93,7 @@ impl Service { Ok((objects, path("/"))) } } -/// The default collection, so a Put reaches CreateItem. It counts the calls +/// Invariant: The default collection, so a Put reaches CreateItem. It counts the calls /// that actually reached the daemon, then refuses, which is the shape of a /// write the daemon commits and the client never hears about. struct Collection { @@ -140,7 +133,7 @@ impl Prompt { fn prompt(&self, _window_id: &str) { self.0.fetch_add(1, Ordering::SeqCst); } - // Deliberately never emits Completed. This is a real signal wait inside the + // Invariant: Deliberately never emits Completed. This is a real signal wait inside the // secret-service crate, rather than a pending future substituted for it. } @@ -169,7 +162,7 @@ impl Fixture { fn with_refused_unlock() -> Self { Self::build(false, false, true, true, 0) } - /// A missing item in a locked default collection: the state a fresh login + /// Invariant: A missing item in a locked default collection: the state a fresh login /// leaves behind, where a write has nothing to set and must create. fn with_locked_collection() -> Self { let fixture = Self::build(false, true, false, false, 0); @@ -365,7 +358,7 @@ fn credentials_native_linux_denial_and_unavailability_are_not_missing() { )); } -/// The regression test for the per-operation session. Opening a session for +/// Invariant: The regression test for the per-operation session. Opening a session for /// every credential read and force-closing it afterwards races /// gnome-keyring's own handshake, which aborts the daemon holding every /// credential on the machine. Against the unfixed code this counts three. @@ -395,7 +388,7 @@ fn credentials_native_linux_reuses_one_session_across_operations() { ); } -/// A session the daemon has forgotten fails like an absent one, so the +/// Invariant: A session the daemon has forgotten fails like an absent one, so the /// operation has to survive it rather than report a failure the caller cannot /// act on. Without the retry the first read after a daemon restart just fails. #[test] @@ -424,7 +417,7 @@ fn credentials_native_linux_reconnects_after_a_transport_failure() { ); } -/// Missing is an answer, not a transport failure: it must neither drop the +/// Invariant: Missing is an answer, not a transport failure: it must neither drop the /// session nor spend the retry, or every absent credential would cost a /// reconnection and a second search. #[test] @@ -452,7 +445,7 @@ fn credentials_native_linux_keeps_the_session_when_an_item_is_missing() { assert_eq!(fixture.sessions.load(Ordering::SeqCst), 1); } -/// A write is never repeated. A request already on the socket cannot be +/// Invariant: A write is never repeated. A request already on the socket cannot be /// retracted, so a `CreateItem` the daemon committed before the connection /// failed would be made a second time, leaving two items with the same /// attributes; `find` answers `Ambiguous` for both from then on, and the @@ -482,7 +475,7 @@ fn credentials_native_linux_a_failed_write_reaches_the_daemon_once() { ); } -/// A locked keyring is an answer, not a broken connection. Dropping the session +/// Invariant: A locked keyring is an answer, not a broken connection. Dropping the session /// for it would renegotiate a session on every read in exactly the state where /// the daemon is least able to survive one. #[test] @@ -512,7 +505,7 @@ fn credentials_native_linux_a_refused_unlock_keeps_the_session() { assert_eq!(fixture.searches.load(Ordering::SeqCst), 2); } -/// A locked result is still the matching credential. Blank-password Secret +/// Invariant: A locked result is still the matching credential. Blank-password Secret /// Service collections unlock without a prompt, so the item must be returned /// from the same search instead of being discarded as unavailable. #[test] @@ -534,7 +527,7 @@ fn credentials_native_linux_silently_unlocks_a_locked_item() { assert_eq!(fixture.searches.load(Ordering::SeqCst), 1); } -/// A fresh login leaves a blank-password default collection locked. A write +/// Invariant: A fresh login leaves a blank-password default collection locked. A write /// must unlock it and carry on rather than refuse: the refresh token is stored /// during sign-in, before any mailbox request, so refusing here is what made /// Gmail sign-in fail with a generic keyring error after Google had already @@ -568,7 +561,7 @@ fn credentials_native_linux_a_locked_collection_is_unlocked_before_a_write() { ); } -/// One operation costs the caller one deadline. Opening the session and running +/// Invariant: One operation costs the caller one deadline. Opening the session and running /// the operation share a single budget, so a connect that never answers cannot /// be waited for once and then waited for again. #[test] diff --git a/src/credentials/tests.rs b/src/credentials/tests.rs index 192bc7b68..8e48fbf20 100644 --- a/src/credentials/tests.rs +++ b/src/credentials/tests.rs @@ -67,7 +67,7 @@ fn credentials_preserve_linux_scope_and_native_key_is_unambiguous() { assert_ne!(key.native_id().unwrap(), other.native_id().unwrap()); } -/// Explicit native runner gate. Never silently succeeds when the store is locked, +/// Invariant: Explicit native runner gate. Never silently succeeds when the store is locked, /// absent, or unavailable. Unique synthetic entries are removed by Drop even on panic. #[test] #[ignore = "requires an unlocked native credential store; run explicitly on each native runner"] @@ -175,7 +175,7 @@ fn credentials_native_contract() { } } -// A process-local native-store substitute for existing isolated dispatcher +// Invariant: A process-local native-store substitute for existing isolated dispatcher // fixtures. It cannot be enabled by production builds, settings or environment. static STORE: std::sync::Mutex>> = std::sync::Mutex::new(None); diff --git a/src/credentials/windows.rs b/src/credentials/windows.rs index ff701f453..b51a20d5f 100644 --- a/src/credentials/windows.rs +++ b/src/credentials/windows.rs @@ -19,7 +19,7 @@ fn target(key: &CredentialKey) -> Result, Error> { pub(super) fn get(key: &CredentialKey) -> Result { let target = target(key)?; let mut credential: *mut CREDENTIALW = std::ptr::null_mut(); - // CredRead owns the returned allocation until CredFree. Never interpret the + // Invariant: CredRead owns the returned allocation until CredFree. Never interpret the // opaque blob as a NUL-terminated string or write its contents to a log. if unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut credential) } == 0 { return Err(error()); @@ -98,7 +98,7 @@ mod tests { Security::{ImpersonateAnonymousToken, RevertToSelf}, System::Threading::GetCurrentThread, }; - // Thread-scoped impersonation needs no test user's password and never + // Invariant: Thread-scoped impersonation needs no test user's password and never // modifies the runner's actual credential set. assert_ne!(unsafe { ImpersonateAnonymousToken(GetCurrentThread()) }, 0); struct Revert; diff --git a/src/public_http/mod.rs b/src/public_http/mod.rs index cc3d0ef28..3beaffc84 100644 --- a/src/public_http/mod.rs +++ b/src/public_http/mod.rs @@ -60,7 +60,7 @@ pub fn is_public(ip: IpAddr) -> bool { } IpAddr::V6(ip) => { let segments = ip.segments(); - // Only currently allocated global unicast; excludes mapped IPv4, + // Invariant: Only currently allocated global unicast; excludes mapped IPv4, // NAT64, local/multicast and deprecated site-local addresses. (segments[0] & 0xe000) == 0x2000 && !(segments[0] == 0x2001 && segments[1] < 0x0200) @@ -72,7 +72,7 @@ pub fn is_public(ip: IpAddr) -> bool { } fn parse_url(raw: &str, https_only: bool) -> Result { - // URL parsing normalizes controls and backslashes, so reject raw bytes first. + // Invariant: URL parsing normalizes controls and backslashes, so reject raw bytes first. if raw.is_empty() || raw.len() > 128 * 1024 || raw @@ -174,7 +174,7 @@ async fn execute( .trim() .to_ascii_lowercase(); let mut body = Vec::new(); - // Unsubscribe only consumes the status; redirects never consume a body. + // Invariant: Unsubscribe only consumes the status; redirects never consume a body. if method == Method::GET && (200..300).contains(&status) { if response .headers() diff --git a/src/public_http/tests.rs b/src/public_http/tests.rs index 00176486b..dfcee7d0a 100644 --- a/src/public_http/tests.rs +++ b/src/public_http/tests.rs @@ -109,7 +109,7 @@ async fn server(response: Vec) -> (SocketAddr, tokio::task::JoinHandle Client { client_builder() @@ -294,7 +294,7 @@ async fn tls_verifies_issuer_and_original_hostname_before_http() { .add_root_certificate(certificate) .build() .unwrap(); - // Both requests connect to the pinned address, retaining sender.example as + // Invariant: Both requests connect to the pinned address, retaining sender.example as // the TLS name. Trusting the issuer alone must not trust its localhost name. for client in [test_client(address), trusted] { let result = execute( diff --git a/src/tls/tests.rs b/src/tls/tests.rs index 090bea327..8ebf76258 100644 --- a/src/tls/tests.rs +++ b/src/tls/tests.rs @@ -5,8 +5,6 @@ fn the_system_store_is_added_to_the_bundled_list_and_bad_entries_are_skipped() { let bundled = webpki_roots::TLS_SERVER_ROOTS.len(); assert_eq!(roots_with(Vec::new()).len(), bundled); - // A private authority, as a system store carries it. Self-signed with - // openssl at test time so nothing in the tree is a certificate. let directory = tempdir(); let certificate_path = directory.join("ca.pem"); let generated = std::process::Command::new("openssl") @@ -25,7 +23,6 @@ fn the_system_store_is_added_to_the_bundled_list_and_bad_entries_are_skipped() { assert_eq!(private.len(), 1); assert_eq!(roots_with(private.clone()).len(), bundled + 1); - // Bytes that are not a certificate cost nothing but themselves. let mut mixed = private; mixed.push(CertificateDer::from(vec![0u8; 8])); assert_eq!(roots_with(mixed).len(), bundled + 1); From 4de4dee4f9ae2295dce4bbc59ce4c4633e115763 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 022/568] Flatten credential session retry handling --- src/auth/callback.rs | 24 ++++++++++++------------ src/auth/credentials.rs | 28 ++++++++++++++-------------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 719aec2fe..d33d56a1d 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -168,18 +168,18 @@ async fn finish_google(mut response: Value, client_id: &str) -> Result Fut, Fut: std::future::Future>, { - if let Some(rotated) = token["refresh_token"] + let Some(rotated) = token["refresh_token"] .as_str() .filter(|value| !value.is_empty() && *value != refresh) - { - if rotated.len() > 16384 || rotated.chars().any(char::is_control) { - return Err("auth_invalid_response"); - } - if read_only { - return Ok(()); - } - put( - key, - Secret::new(rotated.as_bytes().to_vec()).map_err(store_error)?, - ) - .await?; + else { + return Ok(()); + }; + if rotated.len() > 16384 || rotated.chars().any(char::is_control) { + return Err("auth_invalid_response"); } - Ok(()) + if read_only { + return Ok(()); + } + put( + key, + Secret::new(rotated.as_bytes().to_vec()).map_err(store_error)?, + ) + .await } #[cfg(test)] From 402c3bec2cef7bd6e1bcc86fad54ff66397b50d2 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 023/568] Fix credential cache identity and account invalidation --- src/auth/credentials.rs | 52 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/src/auth/credentials.rs b/src/auth/credentials.rs index ad039647e..571312527 100644 --- a/src/auth/credentials.rs +++ b/src/auth/credentials.rs @@ -156,7 +156,15 @@ fn cached_token( } type AccountTokens = std::sync::Arc>; -static TOKENS: OnceLock>> = + +#[derive(Eq, Hash, PartialEq)] +struct Grant { + account_id: String, + client_id: String, + tenant: String, +} + +static TOKENS: OnceLock>> = OnceLock::new(); pub async fn access_token( @@ -402,7 +410,11 @@ async fn account_tokens( client: &str, tenant: &str, ) -> Result { - let key = format!("{}:{client}:{tenant}", account.to_lowercase()); + let key = Grant { + account_id: account.to_lowercase(), + client_id: client.into(), + tenant: tenant.into(), + }; let mut accounts = TOKENS.get_or_init(Default::default).lock().await; if accounts.len() >= 128 && !accounts.contains_key(&key) { return Err("auth_too_many_accounts"); @@ -457,12 +469,12 @@ pub(super) async fn change_outlook(params: &Value, clear: bool) -> Result Result<(), &'static str> { valid_account("outlook", account)?; if let Some(accounts) = TOKENS.get() { - let prefix = format!("{}:", account.to_lowercase()); + let account_id = account.to_lowercase(); let locks: Vec<_> = accounts .lock() .await .iter() - .filter(|(key, _)| key.starts_with(&prefix)) + .filter(|(key, _)| key.account_id == account_id) .map(|(_, value)| value.clone()) .collect(); for lock in locks { @@ -1279,6 +1291,38 @@ mod tests { assert_eq!(calls[0].0, key); assert!(calls[0].1.as_slice() == b"rotated-synthetic"); } + #[tokio::test] + async fn token_cache_identity_preserves_field_boundaries() { + let first = account_tokens( + "outlook:lane-fixture@example.org", "left:right", "consumers", + ).await.unwrap(); + let second = account_tokens( + "outlook:lane-fixture@example.org:left", "right", "consumers", + ).await.unwrap(); + let normalized = account_tokens( + "outlook:LANE-FIXTURE@example.org", "left:right", "consumers", + ).await.unwrap(); + assert!(std::sync::Arc::ptr_eq(&first, &normalized)); + assert!(!std::sync::Arc::ptr_eq(&first, &second), + "different account/client fields must not share cached credentials"); + } + + #[tokio::test] + async fn token_cache_invalidation_matches_the_exact_account() { + let account = "outlook:exact-fixture@example.org"; + let related = account_tokens( + "outlook:exact-fixture@example.org:alias", "client", "consumers", + ).await.unwrap(); + related.lock().await.insert("mail".into(), ( + "unrelated-token".into(), + TokenExpiry::after(Duration::from_secs(3600), + std::time::Instant::now(), std::time::SystemTime::now()), + )); + invalidate(account).await.unwrap(); + assert_eq!(related.lock().await.get("mail").unwrap().0, "unrelated-token", + "invalidating an account must preserve another account's token"); + } + #[tokio::test] async fn invalidation_waits_for_rotation_without_opening_another_refresh_lane() { let account = "outlook:rotation-fixture@example.org"; From 09a9f8e1adfdb170c726f3965037c05c7fa7815a Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 024/568] Fix failed credential session invalidation after retry --- src/credentials/secret_service.rs | 10 +++++++++- src/credentials/secret_service_tests.rs | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/credentials/secret_service.rs b/src/credentials/secret_service.rs index a3e206319..1f4c159ac 100644 --- a/src/credentials/secret_service.rs +++ b/src/credentials/secret_service.rs @@ -153,7 +153,15 @@ where if !repeatable { return Err(fault.error()); } - attempt(shared, key, operation, &connect, until).map_err(|(_, fault)| fault.error()) + attempt(shared, key, operation, &connect, until).map_err(|(session, fault)| { + if matches!(fault, Fault::Answer(_)) { + return fault.error(); + } + if let Some(session) = session { + invalidate(shared, &session); + } + fault.error() + }) } } } diff --git a/src/credentials/secret_service_tests.rs b/src/credentials/secret_service_tests.rs index 33153b80e..fcead3781 100644 --- a/src/credentials/secret_service_tests.rs +++ b/src/credentials/secret_service_tests.rs @@ -417,6 +417,18 @@ fn credentials_native_linux_reconnects_after_a_transport_failure() { ); } +#[test] +#[ignore = "requires native dbus-daemon; mandatory in the Linux credential gate"] +fn credentials_native_linux_discards_a_failed_retry_session() { + let fixture = Fixture::with_failures(false, true, 2); + let shared = Shared::new().unwrap(); + assert!(matches!(run_on(&shared, &key(), Operation::Get, + || fixture.client(), DEADLINE), Err(Error::Unavailable))); + assert_eq!(fixture.sessions.load(Ordering::SeqCst), 2); + assert!(slot(&shared).is_none(), + "a failed retry must not leave its unusable session cached"); +} + /// Invariant: Missing is an answer, not a transport failure: it must neither drop the /// session nor spend the retry, or every absent credential would cost a /// reconnection and a second search. From a629e1be0c6db36ed01a051e5aa90cac7f3be7c2 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 025/568] Simplify authentication callback byte handling --- src/auth/callback.rs | 58 +++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index d33d56a1d..07bf5cff6 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -5,7 +5,7 @@ use sha2::{Digest, Sha256}; use std::collections::HashMap; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, - net::TcpListener, + net::{TcpListener, TcpStream}, sync::Mutex, task::JoinHandle, }; @@ -240,6 +240,32 @@ fn callback(request: &str, state: &str, port: u16) -> Result Result { + let mut request = Vec::new(); + let mut byte = [0]; + while request.len() < 16384 { + if socket + .read(&mut byte) + .await + .map_err(|_| "auth_invalid_callback")? == 0 + { + break; + } + request.push(byte[0]); + if request.ends_with(b"\r\n\r\n") { + break; + } + } + if !request.ends_with(b"\r\n\r\n") { + return Err("auth_invalid_callback"); + } + callback( + std::str::from_utf8(&request).map_err(|_| "auth_invalid_callback")?, + state, + port, + ) +} + async fn receive(listener: TcpListener, state: &str, port: u16) -> Result { loop { let (mut socket, peer) = listener @@ -249,32 +275,10 @@ async fn receive(listener: TcpListener, state: &str, port: u16) -> Result Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 026/568] Clarify native credential error mapping --- src/credentials/rpc.rs | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/credentials/rpc.rs b/src/credentials/rpc.rs index a087e452d..7d3826318 100644 --- a/src/credentials/rpc.rs +++ b/src/credentials/rpc.rs @@ -63,7 +63,7 @@ fn key(params: &serde_json::Map) -> Result Result { .get("secret") .and_then(Value::as_str) .ok_or("invalid_params")?; - let secret = Secret::new(text.as_bytes().to_vec()).map_err(map_input_error)?; + let secret = Secret::new(text.as_bytes().to_vec()).map_err(map_error)?; Ok(Request::Put(key, secret)) } _ => Err("unknown_method"), } } -fn map_input_error(error: Error) -> &'static str { - match error { - Error::InvalidKey | Error::InvalidSecret | Error::TooLarge => "invalid_params", - Error::Missing => "credential_missing", - Error::Unavailable | Error::Ambiguous => "credential_store_unavailable", - } -} - -fn map_store_error(error: Error) -> &'static str { +fn map_error(error: Error) -> &'static str { match error { Error::Missing => "credential_missing", Error::InvalidKey | Error::InvalidSecret | Error::TooLarge => "invalid_params", @@ -133,16 +125,16 @@ async fn call_with_store( .map_err(|_| "credential_store_unavailable")? { Ok(secret) => { - Ok(json!({"found":true,"secret":secret.text().map_err(map_store_error)?})) + Ok(json!({"found":true,"secret":secret.text().map_err(map_error)?})) } Err(Error::Missing) => Ok(json!({"found":false})), - Err(error) => Err(map_store_error(error)), + Err(error) => Err(map_error(error)), }, Request::Put(key, secret) => { tokio::task::spawn_blocking(move || store.put(&key, secret.as_slice())) .await .map_err(|_| "credential_store_unavailable")? - .map_err(map_store_error)?; + .map_err(map_error)?; Ok(json!({"stored":true})) } Request::Delete(key) => match tokio::task::spawn_blocking(move || store.delete(&key)) @@ -151,7 +143,7 @@ async fn call_with_store( { Ok(()) => Ok(json!({"deleted":true})), Err(Error::Missing) => Ok(json!({"deleted":false})), - Err(error) => Err(map_store_error(error)), + Err(error) => Err(map_error(error)), }, } } From eddd871ab46e560eacdba75a9fdac1c5adde10cf Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 027/568] Name TLS and public HTTP boundary values --- src/auth/callback.rs | 26 +++++++++--------- src/auth/credentials.rs | 34 ++++++++++++------------ src/auth/graph.rs | 8 +++--- src/auth/mod.rs | 44 +++++++++++++++---------------- src/credentials/rpc.rs | 34 ++++++++++++------------ src/credentials/secret_service.rs | 22 ++++++++-------- src/public_http/mod.rs | 8 +++--- src/public_http/tests.rs | 2 +- 8 files changed, 89 insertions(+), 89 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 07bf5cff6..393c617ee 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -22,8 +22,8 @@ fn random() -> Result { Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)) } -fn text<'a>(params: &'a Value, key: &str) -> Result<&'a str, &'static str> { - params[key] +fn text<'a>(parameters: &'a Value, key: &str) -> Result<&'a str, &'static str> { + parameters[key] .as_str() .filter(|value| value.len() <= 8192 && !value.chars().any(char::is_control)) .ok_or("invalid_params") @@ -36,11 +36,11 @@ pub(super) fn form(fields: &[(&str, &str)]) -> String { } impl Flows { - pub async fn call(&self, method: &str, params: &Value) -> Result { + pub async fn call(&self, method: &str, parameters: &Value) -> Result { match method { - "auth.begin" => self.begin(params).await, + "auth.begin" => self.begin(parameters).await, "auth.poll" | "auth.cancel" => { - let id = text(params, "id")?; + let id = text(parameters, "id")?; let mut flows = self.0.lock().await; let task = flows.get(id).ok_or("auth_flow_missing")?; if method == "auth.cancel" { @@ -59,21 +59,21 @@ impl Flows { } } - async fn begin(&self, params: &Value) -> Result { + async fn begin(&self, parameters: &Value) -> Result { let id = random()?; let verifier = random()?; let state = random()?; - let client_id = text(params, "clientId")?.to_owned(); + let client_id = text(parameters, "clientId")?.to_owned(); if client_id.is_empty() { return Err("invalid_params"); } - let secret = text(params, "clientSecret")?.to_owned(); - let hint = text(params, "loginHint")?.to_owned(); - let port = params["port"] + let secret = text(parameters, "clientSecret")?.to_owned(); + let hint = text(parameters, "loginHint")?.to_owned(); + let port = parameters["port"] .as_u64() .filter(|port| (1024..=65535).contains(port)) .ok_or("invalid_params")? as u16; - let scopes = params["scopes"].as_array().ok_or("invalid_params")?; + let scopes = parameters["scopes"].as_array().ok_or("invalid_params")?; if scopes.len() > 32 { return Err("invalid_params"); } @@ -365,8 +365,8 @@ mod tests { let reservation=TcpListener::bind("127.0.0.1:0").await.unwrap(); let port=reservation.local_addr().unwrap().port(); drop(reservation); - let params=json!({"clientId":"synthetic-client", "clientSecret":"synthetic-secret", "loginHint":"", "port":port, "scopes":["openid"]}); - match flows.begin(¶ms).await { + let parameters=json!({"clientId":"synthetic-client", "clientSecret":"synthetic-secret", "loginHint":"", "port":port, "scopes":["openid"]}); + match flows.begin(¶meters).await { Ok(answer)=>return (port,answer), Err("auth_port_unavailable")=>{ assert!(flows.0.lock().await.is_empty(),"Refused admission cannot register a flow"); diff --git a/src/auth/credentials.rs b/src/auth/credentials.rs index 571312527..66a73638e 100644 --- a/src/auth/credentials.rs +++ b/src/auth/credentials.rs @@ -390,11 +390,11 @@ fn outlook_scopes(token: &Value, scope: &str) -> bool { }) } -async fn in_outlook_lane(lane: AccountTokens, operation: F) -> Result +async fn in_outlook_lane(lane: AccountTokens, operation: Operation) -> Result where - T: Send + 'static, - F: FnOnce(tokio::sync::OwnedMutexGuard) -> Fut + Send + 'static, - Fut: std::future::Future> + Send + 'static, + Output: Send + 'static, + Operation: FnOnce(tokio::sync::OwnedMutexGuard) -> OperationFuture + Send + 'static, + OperationFuture: std::future::Future> + Send + 'static, { // Invariant: Waiting is cancellable. Once admitted, finish under the owned guard: // native keyring writes use spawn_blocking and cannot be cancelled when @@ -423,21 +423,21 @@ async fn account_tokens( } /// Serialize explicit stores/clears with refresh-token rotation. -pub(super) async fn change_outlook(params: &Value, clear: bool) -> Result { - let account = params["accountId"].as_str().ok_or("invalid_params")?; +pub(super) async fn change_outlook(parameters: &Value, clear: bool) -> Result { + let account = parameters["accountId"].as_str().ok_or("invalid_params")?; valid_account("outlook", account)?; let owned = account.to_owned(); let entry = tokio::task::spawn_blocking(move || settings("outlook", &owned)) .await .map_err(|_| "auth_account_invalid")??; let client = entry["clientId"].as_str().ok_or("auth_client_missing")?; - if params["clientId"] != client || client.is_empty() || client.chars().any(char::is_control) { + if parameters["clientId"] != client || client.is_empty() || client.chars().any(char::is_control) { return Err("auth_client_invalid"); } let token = if clear { "" } else { - params["token"] + parameters["token"] .as_str() .filter(|value| !value.is_empty() && value.len() <= 16384 && !value.chars().any(char::is_control)) .ok_or("auth_secret_invalid")? @@ -495,15 +495,15 @@ pub(super) async fn store_google( .await } -async fn store_google_with( +async fn store_google_with( client_id: &str, account: &str, token: &str, - mut run: F, + mut persist: Persist, ) -> Result<(), &'static str> where - F: FnMut(CredentialKey, Secret) -> Fut, - Fut: std::future::Future>, + Persist: FnMut(CredentialKey, Secret) -> PersistFuture, + PersistFuture: std::future::Future>, { if client_id.is_empty() || client_id.len() > 1024 @@ -525,7 +525,7 @@ where client_id: client_id.into(), }, }; - run( + persist( key, Secret::new(token.as_bytes().to_vec()).map_err(store_error)?, ) @@ -557,16 +557,16 @@ async fn persist_outlook_rotation( .await } -async fn persist_outlook_rotation_with( +async fn persist_outlook_rotation_with( refresh: &str, token: &Value, key: CredentialKey, read_only: bool, - mut put: F, + mut put: Persist, ) -> Result<(), &'static str> where - F: FnMut(CredentialKey, Secret) -> Fut, - Fut: std::future::Future>, + Persist: FnMut(CredentialKey, Secret) -> PersistFuture, + PersistFuture: std::future::Future>, { let Some(rotated) = token["refresh_token"] .as_str() diff --git a/src/auth/graph.rs b/src/auth/graph.rs index 9679e98f7..2b1118d61 100644 --- a/src/auth/graph.rs +++ b/src/auth/graph.rs @@ -1,15 +1,15 @@ //! Microsoft Graph submission: one fixed destination and no automatic retry. use super::*; -pub(super) async fn send(params: &Value) -> Result { - let fields = params.as_object().ok_or("invalid_params")?; +pub(super) async fn send(parameters: &Value) -> Result { + let fields = parameters.as_object().ok_or("invalid_params")?; if fields .keys() .any(|key| !["accountId", "raw"].contains(&key.as_str())) { return Err("invalid_params"); } - let account = params["accountId"].as_str().ok_or("invalid_params")?; - let raw = params["raw"].as_str().ok_or("invalid_params")?; + let account = parameters["accountId"].as_str().ok_or("invalid_params")?; + let raw = parameters["raw"].as_str().ok_or("invalid_params")?; if raw.len() > 16 * 1024 * 1024 { return Err("message_too_large"); } diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 4e1c2c99c..0a5cb9478 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -13,7 +13,7 @@ pub struct Session { } static CLIENT: OnceLock> = OnceLock::new(); -const LIMIT: usize = 256 * 1024; +const MAX_AUTH_PAYLOAD_BYTES: usize = 256 * 1024; fn client() -> Result<&'static reqwest::Client, &'static str> { CLIENT @@ -32,17 +32,17 @@ fn client() -> Result<&'static reqwest::Client, &'static str> { .map_err(|error| *error) } -fn destination(params: &Value) -> Result { - let fields = params.as_object().ok_or("invalid_params")?; +fn destination(parameters: &Value) -> Result { + let fields = parameters.as_object().ok_or("invalid_params")?; if fields.keys() .any(|key| !["provider", "endpoint", "tenant", "body"].contains(&key.as_str())) { return Err("invalid_params"); } - match (params["provider"].as_str(), params["endpoint"].as_str()) { + match (parameters["provider"].as_str(), parameters["endpoint"].as_str()) { (Some("gmail"), Some("token")) => Ok("https://oauth2.googleapis.com/token".into()), (Some("outlook"), Some(endpoint @ ("token" | "device"))) => { - let tenant = params + let tenant = parameters .get("tenant") .map(|value| value.as_str().ok_or("invalid_params")) .transpose()? @@ -95,7 +95,7 @@ async fn post_with_deadline( if status.is_redirection() { return Err("auth_redirect_refused"); } - if response.content_length().is_some_and(|size| size > LIMIT as u64) { + if response.content_length().is_some_and(|size| size > MAX_AUTH_PAYLOAD_BYTES as u64) { return Err("auth_response_too_large"); } let mut bytes = Vec::new(); @@ -104,7 +104,7 @@ async fn post_with_deadline( .await .map_err(|_| "auth_transport_failed")? { - if chunk.len() > LIMIT - bytes.len() { + if chunk.len() > MAX_AUTH_PAYLOAD_BYTES - bytes.len() { return Err("auth_response_too_large"); } bytes.extend_from_slice(&chunk); @@ -121,9 +121,9 @@ async fn post_with_deadline( } impl Session { - pub async fn call(&self, method: &str, params: &Value) -> Result { + pub async fn call(&self, method: &str, parameters: &Value) -> Result { if matches!(method, "auth.store" | "auth.clear") { - if params + if parameters .as_object() .ok_or("invalid_params")? .keys() @@ -131,10 +131,10 @@ impl Session { { return Err("invalid_params"); } - return credentials::change_outlook(params, method == "auth.clear").await; + return credentials::change_outlook(parameters, method == "auth.clear").await; } if method == "auth.token" { - if params + if parameters .as_object() .ok_or("invalid_params")? .keys() @@ -142,11 +142,11 @@ impl Session { { return Err("invalid_params"); } - if params["provider"] != "outlook" { + if parameters["provider"] != "outlook" { return Err("invalid_params"); } - let account = params["accountId"].as_str().ok_or("invalid_params")?; - let resource = params + let account = parameters["accountId"].as_str().ok_or("invalid_params")?; + let resource = parameters .get("resource") .map(|value| value.as_str().ok_or("invalid_params")) .transpose()? @@ -156,7 +156,7 @@ impl Session { return Ok(json!({"access_token":access,"expires_in":60,"scope":scope})); } if method == "auth.invalidate" { - if params + if parameters .as_object() .ok_or("invalid_params")? .keys() @@ -164,19 +164,19 @@ impl Session { { return Err("invalid_params"); } - let account = params["accountId"].as_str().ok_or("invalid_params")?; + let account = parameters["accountId"].as_str().ok_or("invalid_params")?; credentials::invalidate(account).await?; return Ok(json!({"invalidated":true})); } if method == "outlook.graphSend" { - return graph::send(params).await; + return graph::send(parameters).await; } if method != "auth.form" { - return self.flows.call(method, params).await; + return self.flows.call(method, parameters).await; } - let url = destination(params)?; - let body = params["body"].as_str().ok_or("invalid_params")?; - if body.len() > LIMIT || body.bytes().any(|byte| byte < 32 || byte == 127) { + let url = destination(parameters)?; + let body = parameters["body"].as_str().ok_or("invalid_params")?; + if body.len() > MAX_AUTH_PAYLOAD_BYTES || body.bytes().any(|byte| byte < 32 || byte == 127) { return Err("invalid_params"); } post(client()?, &url, body.into()).await @@ -229,7 +229,7 @@ mod tests { assert!(socket.read(&mut request).await.unwrap() > 0); socket .write_all( - format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", LIMIT + 1).as_bytes(), + format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", MAX_AUTH_PAYLOAD_BYTES + 1).as_bytes(), ) .await .unwrap(); diff --git a/src/credentials/rpc.rs b/src/credentials/rpc.rs index 7d3826318..4b0588ef7 100644 --- a/src/credentials/rpc.rs +++ b/src/credentials/rpc.rs @@ -13,19 +13,19 @@ enum Request { Delete(CredentialKey), } -fn key(params: &serde_json::Map) -> Result { - let kind = params +fn key(parameters: &serde_json::Map) -> Result { + let kind = parameters .get("kind") .and_then(Value::as_str) .ok_or("invalid_params")?; - let account_id = params + let account_id = parameters .get("accountId") .and_then(Value::as_str) .filter(|value| !value.is_empty()) .ok_or("invalid_params")? .to_owned(); let client_id = || { - params + parameters .get("clientId") .and_then(Value::as_str) .filter(|value| !value.is_empty()) @@ -50,7 +50,7 @@ fn key(params: &serde_json::Map) -> Result ("caldav", CredentialKind::CalendarPassword), _ => return Err("invalid_params"), }; - let has_client = params.contains_key("clientId"); + let has_client = parameters.contains_key("clientId"); let needs_client = matches!( kind, CredentialKind::GoogleRefreshToken { .. } | CredentialKind::OutlookRefreshToken { .. } @@ -67,8 +67,8 @@ fn key(params: &serde_json::Map) -> Result Result { - let fields = params.as_object().ok_or("invalid_params")?; +fn parse(method: &str, parameters: &Value) -> Result { + let fields = parameters.as_object().ok_or("invalid_params")?; let expected = match method { "credentials.get" | "credentials.delete" => { 2 + usize::from(matches!( @@ -114,12 +114,12 @@ fn map_error(error: Error) -> &'static str { async fn call_with_store( store: Arc, method: &str, - params: &Value, + parameters: &Value, ) -> Result { // Invariant: Parsing before the first await is deliberate: malformed metadata or a // secret containing NUL cannot prompt, read, write, or delete in a native // credential store. - match parse(method, params)? { + match parse(method, parameters)? { Request::Get(key) => match tokio::task::spawn_blocking(move || store.get(&key)) .await .map_err(|_| "credential_store_unavailable")? @@ -148,8 +148,8 @@ async fn call_with_store( } } -pub async fn call(method: &str, params: &Value) -> Result { - call_with_store(Arc::new(super::NativeStore), method, params).await +pub async fn call(method: &str, parameters: &Value) -> Result { + call_with_store(Arc::new(super::NativeStore), method, parameters).await } #[cfg(test)] @@ -196,7 +196,7 @@ mod tests { #[test] fn typed_requests_reject_unknown_fields_kinds_and_control_characters() { - for params in [ + for parameters in [ json!({"kind":"shell-command","accountId":"imap:a@example.org"}), json!({"kind":"imap-password","accountId":"imap:a@example.org","clientId":"forged"}), json!({"kind":"imap-password","accountId":"imap:a@example.org\n"}), @@ -205,7 +205,7 @@ mod tests { json!({"kind":"google-refresh-token","accountId":"a@example.org","clientId":"client","nativeAttributes":[]}), ] { assert!(matches!( - parse("credentials.get", ¶ms), + parse("credentials.get", ¶meters), Err("invalid_params") )); } @@ -252,8 +252,8 @@ mod tests { "outlook", ), ]; - for (params, provider) in cases { - let Request::Get(key) = parse("credentials.get", ¶ms).unwrap() else { + for (parameters, provider) in cases { + let Request::Get(key) = parse("credentials.get", ¶meters).unwrap() else { panic!() }; assert_eq!(key.provider, provider); @@ -305,7 +305,7 @@ mod tests { #[tokio::test] async fn rejected_public_requests_have_no_store_side_effect() { let store = Arc::new(RecordingStore::default()); - for (method, params) in [ + for (method, parameters) in [ ( "credentials.get", json!({"kind":"native-command","accountId":"imap:a@example.org"}), @@ -320,7 +320,7 @@ mod tests { ), ] { assert_eq!( - call_with_store(store.clone(), method, ¶ms).await, + call_with_store(store.clone(), method, ¶meters).await, Err("invalid_params") ); } diff --git a/src/credentials/secret_service.rs b/src/credentials/secret_service.rs index 1f4c159ac..00dded369 100644 --- a/src/credentials/secret_service.rs +++ b/src/credentials/secret_service.rs @@ -129,16 +129,16 @@ fn run(key: &CredentialKey, operation: Operation<'_>) -> Result, /// committed it, so repeating `CreateItem` would leave two items carrying the /// same attributes and `find` would answer `Ambiguous` for the rest of the /// credential's life. A write reports the failure and the caller asks again. -fn run_on( +fn run_on( shared: &Shared, key: &CredentialKey, operation: Operation<'_>, - connect: F, + connect: Connect, deadline: Duration, ) -> Result, Error> where - F: Fn() -> C, - C: Future>, + Connect: Fn() -> ConnectionFuture, + ConnectionFuture: Future>, { let until = Instant::now() + deadline; match attempt(shared, key, operation, &connect, until) { @@ -170,16 +170,16 @@ where /// none. Returns the session it used alongside any fault, so the caller drops /// that session and not a newer one. #[allow(clippy::type_complexity)] -fn attempt( +fn attempt( shared: &Shared, key: &CredentialKey, operation: Operation<'_>, - connect: &F, + connect: &Connect, until: Instant, ) -> Result, (Option>, Fault)> where - F: Fn() -> C, - C: Future>, + Connect: Fn() -> ConnectionFuture, + ConnectionFuture: Future>, { let session = match acquire(shared, connect, until) { Ok(session) => session, @@ -205,10 +205,10 @@ where /// is held outside the runtime rather than inside a task, so a caller waiting /// for it is only waiting for another thread to finish negotiating, and no /// prompt is ever awaited underneath it: every prompting call is in `execute`. -fn acquire(shared: &Shared, connect: &F, until: Instant) -> Result, Fault> +fn acquire(shared: &Shared, connect: &Connect, until: Instant) -> Result, Fault> where - F: Fn() -> C, - C: Future>, + Connect: Fn() -> ConnectionFuture, + ConnectionFuture: Future>, { let mut held = slot(shared); if let Some(session) = held.as_ref() { diff --git a/src/public_http/mod.rs b/src/public_http/mod.rs index 3beaffc84..04f69e3b6 100644 --- a/src/public_http/mod.rs +++ b/src/public_http/mod.rs @@ -13,8 +13,8 @@ use std::{ }; const DEADLINE: Duration = Duration::from_secs(20); -const MAX_IMAGE: usize = 5 * 1024 * 1024; -const MAX_RESPONSE: usize = 16 * 1024 * 1024; +const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024; +const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024; static CLIENT: OnceLock> = OnceLock::new(); #[derive(Debug)] @@ -212,7 +212,7 @@ pub async fn fetch(url: &str, max_bytes: usize) -> Result Result { Ok(format!("data:{mime};base64,{}", STANDARD.encode(data))) } pub async fn image(url: &str) -> Result { - image_data(fetch(url, MAX_IMAGE).await?) + image_data(fetch(url, MAX_IMAGE_BYTES).await?) } #[cfg(test)] diff --git a/src/public_http/tests.rs b/src/public_http/tests.rs index dfcee7d0a..747921c71 100644 --- a/src/public_http/tests.rs +++ b/src/public_http/tests.rs @@ -141,7 +141,7 @@ async fn connection_is_pinned_and_original_host_is_preserved() { &test_client(address), parse_url("http://sender.example/image", false).unwrap(), Method::GET, - MAX_IMAGE, + MAX_IMAGE_BYTES, DEADLINE, ) .await From 1960fe359fa923dbcb88ce121b17298350c54cc7 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 028/568] Format credential boundary changes consistently --- src/auth/callback.rs | 26 +++++--- src/auth/credentials.rs | 89 ++++++++++++++++++------- src/auth/mod.rs | 29 ++++++-- src/credentials/rpc.rs | 4 +- src/credentials/secret_service.rs | 6 +- src/credentials/secret_service_tests.rs | 18 +++-- src/credentials/tests.rs | 4 +- src/public_http/mod.rs | 20 ++++-- src/public_http/tests.rs | 6 +- 9 files changed, 147 insertions(+), 55 deletions(-) diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 393c617ee..d8f35eb6b 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -80,7 +80,8 @@ impl Flows { let scopes: Vec<&str> = scopes .iter() .map(|value| { - value.as_str() + value + .as_str() .filter(|value| value.len() < 512 && !value.chars().any(char::is_whitespace)) .ok_or("invalid_params") }) @@ -165,7 +166,9 @@ async fn finish_google(mut response: Value, client_id: &str) -> Result Result Result { +async fn read_callback( + socket: &mut TcpStream, + state: &str, + port: u16, +) -> Result { let mut request = Vec::new(); let mut byte = [0]; while request.len() < 16384 { if socket .read(&mut byte) .await - .map_err(|_| "auth_invalid_callback")? == 0 + .map_err(|_| "auth_invalid_callback")? + == 0 { break; } @@ -423,7 +430,8 @@ mod tests { #[test] fn callback_checks_exact_route_host_and_single_state() { - let request_for = |path: &str, host: &str| format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n"); + let request_for = + |path: &str, host: &str| format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n"); assert_eq!( callback( &request_for( diff --git a/src/auth/credentials.rs b/src/auth/credentials.rs index 66a73638e..aab7d2af7 100644 --- a/src/auth/credentials.rs +++ b/src/auth/credentials.rs @@ -50,7 +50,9 @@ fn valid_account(provider: &str, account: &str) -> Result<(), &'static str> { if !account.starts_with(&format!("{provider}:")) || !account.contains('@') || account.len() > 1024 - || account.chars().any(|character| character.is_control() || character.is_whitespace()) + || account + .chars() + .any(|character| character.is_control() || character.is_whitespace()) { return Err("auth_account_invalid"); } @@ -370,7 +372,9 @@ fn outlook_access(token: &Value) -> Result<&str, &'static str> { .filter(|value| { !value.is_empty() && value.len() <= 16384 - && !value.chars().any(|character| character.is_whitespace() || character.is_control()) + && !value + .chars() + .any(|character| character.is_whitespace() || character.is_control()) }) .ok_or("auth_invalid_response") } @@ -390,7 +394,10 @@ fn outlook_scopes(token: &Value, scope: &str) -> bool { }) } -async fn in_outlook_lane(lane: AccountTokens, operation: Operation) -> Result +async fn in_outlook_lane( + lane: AccountTokens, + operation: Operation, +) -> Result where Output: Send + 'static, Operation: FnOnce(tokio::sync::OwnedMutexGuard) -> OperationFuture + Send + 'static, @@ -431,7 +438,8 @@ pub(super) async fn change_outlook(parameters: &Value, clear: bool) -> Result Result 1024 - || account.chars().any(|character| character.is_control() || character.is_whitespace()) + || account + .chars() + .any(|character| character.is_control() || character.is_whitespace()) || token.is_empty() || client_id.chars().any(char::is_control) || token.len() > 16384 - || token.chars().any(|character| character.is_whitespace() || character.is_control()) + || token + .chars() + .any(|character| character.is_whitespace() || character.is_control()) { return Err("auth_secret_invalid"); } @@ -1294,33 +1308,60 @@ mod tests { #[tokio::test] async fn token_cache_identity_preserves_field_boundaries() { let first = account_tokens( - "outlook:lane-fixture@example.org", "left:right", "consumers", - ).await.unwrap(); + "outlook:lane-fixture@example.org", + "left:right", + "consumers", + ) + .await + .unwrap(); let second = account_tokens( - "outlook:lane-fixture@example.org:left", "right", "consumers", - ).await.unwrap(); + "outlook:lane-fixture@example.org:left", + "right", + "consumers", + ) + .await + .unwrap(); let normalized = account_tokens( - "outlook:LANE-FIXTURE@example.org", "left:right", "consumers", - ).await.unwrap(); + "outlook:LANE-FIXTURE@example.org", + "left:right", + "consumers", + ) + .await + .unwrap(); assert!(std::sync::Arc::ptr_eq(&first, &normalized)); - assert!(!std::sync::Arc::ptr_eq(&first, &second), - "different account/client fields must not share cached credentials"); + assert!( + !std::sync::Arc::ptr_eq(&first, &second), + "different account/client fields must not share cached credentials" + ); } #[tokio::test] async fn token_cache_invalidation_matches_the_exact_account() { let account = "outlook:exact-fixture@example.org"; let related = account_tokens( - "outlook:exact-fixture@example.org:alias", "client", "consumers", - ).await.unwrap(); - related.lock().await.insert("mail".into(), ( - "unrelated-token".into(), - TokenExpiry::after(Duration::from_secs(3600), - std::time::Instant::now(), std::time::SystemTime::now()), - )); + "outlook:exact-fixture@example.org:alias", + "client", + "consumers", + ) + .await + .unwrap(); + related.lock().await.insert( + "mail".into(), + ( + "unrelated-token".into(), + TokenExpiry::after( + Duration::from_secs(3600), + std::time::Instant::now(), + std::time::SystemTime::now(), + ), + ), + ); invalidate(account).await.unwrap(); - assert_eq!(related.lock().await.get("mail").unwrap().0, "unrelated-token", - "invalidating an account must preserve another account's token"); + assert_eq!( + related.lock().await.get("mail").unwrap().0, + "unrelated-token", + "invalidating an account must preserve another account's token" + ); } #[tokio::test] diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 0a5cb9478..91d98ebb8 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -34,12 +34,16 @@ fn client() -> Result<&'static reqwest::Client, &'static str> { fn destination(parameters: &Value) -> Result { let fields = parameters.as_object().ok_or("invalid_params")?; - if fields.keys() + if fields + .keys() .any(|key| !["provider", "endpoint", "tenant", "body"].contains(&key.as_str())) { return Err("invalid_params"); } - match (parameters["provider"].as_str(), parameters["endpoint"].as_str()) { + match ( + parameters["provider"].as_str(), + parameters["endpoint"].as_str(), + ) { (Some("gmail"), Some("token")) => Ok("https://oauth2.googleapis.com/token".into()), (Some("outlook"), Some(endpoint @ ("token" | "device"))) => { let tenant = parameters @@ -95,7 +99,10 @@ async fn post_with_deadline( if status.is_redirection() { return Err("auth_redirect_refused"); } - if response.content_length().is_some_and(|size| size > MAX_AUTH_PAYLOAD_BYTES as u64) { + if response + .content_length() + .is_some_and(|size| size > MAX_AUTH_PAYLOAD_BYTES as u64) + { return Err("auth_response_too_large"); } let mut bytes = Vec::new(); @@ -176,7 +183,8 @@ impl Session { } let url = destination(parameters)?; let body = parameters["body"].as_str().ok_or("invalid_params")?; - if body.len() > MAX_AUTH_PAYLOAD_BYTES || body.bytes().any(|byte| byte < 32 || byte == 127) { + if body.len() > MAX_AUTH_PAYLOAD_BYTES || body.bytes().any(|byte| byte < 32 || byte == 127) + { return Err("invalid_params"); } post(client()?, &url, body.into()).await @@ -229,7 +237,11 @@ mod tests { assert!(socket.read(&mut request).await.unwrap() > 0); socket .write_all( - format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", MAX_AUTH_PAYLOAD_BYTES + 1).as_bytes(), + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", + MAX_AUTH_PAYLOAD_BYTES + 1 + ) + .as_bytes(), ) .await .unwrap(); @@ -301,7 +313,12 @@ mod tests { .build() .unwrap(); assert_eq!( - post(&client, &format!("http://{address}"), "token=synthetic".into()).await, + post( + &client, + &format!("http://{address}"), + "token=synthetic".into() + ) + .await, Err("auth_redirect_refused") ); server.await.unwrap(); diff --git a/src/credentials/rpc.rs b/src/credentials/rpc.rs index 4b0588ef7..97170e5fa 100644 --- a/src/credentials/rpc.rs +++ b/src/credentials/rpc.rs @@ -124,9 +124,7 @@ async fn call_with_store( .await .map_err(|_| "credential_store_unavailable")? { - Ok(secret) => { - Ok(json!({"found":true,"secret":secret.text().map_err(map_error)?})) - } + Ok(secret) => Ok(json!({"found":true,"secret":secret.text().map_err(map_error)?})), Err(Error::Missing) => Ok(json!({"found":false})), Err(error) => Err(map_error(error)), }, diff --git a/src/credentials/secret_service.rs b/src/credentials/secret_service.rs index 00dded369..f577fd9ce 100644 --- a/src/credentials/secret_service.rs +++ b/src/credentials/secret_service.rs @@ -205,7 +205,11 @@ where /// is held outside the runtime rather than inside a task, so a caller waiting /// for it is only waiting for another thread to finish negotiating, and no /// prompt is ever awaited underneath it: every prompting call is in `execute`. -fn acquire(shared: &Shared, connect: &Connect, until: Instant) -> Result, Fault> +fn acquire( + shared: &Shared, + connect: &Connect, + until: Instant, +) -> Result, Fault> where Connect: Fn() -> ConnectionFuture, ConnectionFuture: Future>, diff --git a/src/credentials/secret_service_tests.rs b/src/credentials/secret_service_tests.rs index fcead3781..49cf64d13 100644 --- a/src/credentials/secret_service_tests.rs +++ b/src/credentials/secret_service_tests.rs @@ -422,11 +422,21 @@ fn credentials_native_linux_reconnects_after_a_transport_failure() { fn credentials_native_linux_discards_a_failed_retry_session() { let fixture = Fixture::with_failures(false, true, 2); let shared = Shared::new().unwrap(); - assert!(matches!(run_on(&shared, &key(), Operation::Get, - || fixture.client(), DEADLINE), Err(Error::Unavailable))); + assert!(matches!( + run_on( + &shared, + &key(), + Operation::Get, + || fixture.client(), + DEADLINE + ), + Err(Error::Unavailable) + )); assert_eq!(fixture.sessions.load(Ordering::SeqCst), 2); - assert!(slot(&shared).is_none(), - "a failed retry must not leave its unusable session cached"); + assert!( + slot(&shared).is_none(), + "a failed retry must not leave its unusable session cached" + ); } /// Invariant: Missing is an answer, not a transport failure: it must neither drop the diff --git a/src/credentials/tests.rs b/src/credentials/tests.rs index 8e48fbf20..480513d82 100644 --- a/src/credentials/tests.rs +++ b/src/credentials/tests.rs @@ -144,7 +144,9 @@ fn credentials_native_contract() { .unwrap(); } for (index, key) in cleanup.0.iter().enumerate() { - assert!(NativeStore.get(key).unwrap().as_slice() == format!("synthetic-{index}").as_bytes()); + assert!( + NativeStore.get(key).unwrap().as_slice() == format!("synthetic-{index}").as_bytes() + ); } for (index, sample) in samples.iter().enumerate() { NativeStore.put(&cleanup.0[0], sample).unwrap(); diff --git a/src/public_http/mod.rs b/src/public_http/mod.rs index 04f69e3b6..d0b49ee81 100644 --- a/src/public_http/mod.rs +++ b/src/public_http/mod.rs @@ -37,7 +37,10 @@ fn checked_addresses(addresses: Vec) -> Result, &'static if addresses.is_empty() || addresses.iter().any(|ip| !is_public(*ip)) { return Err("public_destination_refused"); } - Ok(addresses.into_iter().map(|ip| SocketAddr::new(ip, 0)).collect()) + Ok(addresses + .into_iter() + .map(|ip| SocketAddr::new(ip, 0)) + .collect()) } /// Conservative global-unicast policy, including transition mechanisms that @@ -54,8 +57,13 @@ pub fn is_public(ip: IpAddr) -> bool { || (first_octet == 169 && second_octet == 254) || (first_octet == 172 && (16..=31).contains(&second_octet)) || (first_octet == 192 - && ((second_octet == 168) || (second_octet == 0 && (third_octet == 0 || third_octet == 2)) || (second_octet == 88 && third_octet == 99))) - || (first_octet == 198 && (second_octet == 18 || second_octet == 19 || (second_octet == 51 && third_octet == 100))) + && ((second_octet == 168) + || (second_octet == 0 && (third_octet == 0 || third_octet == 2)) + || (second_octet == 88 && third_octet == 99))) + || (first_octet == 198 + && (second_octet == 18 + || second_octet == 19 + || (second_octet == 51 && third_octet == 100))) || (first_octet == 203 && second_octet == 0 && third_octet == 113)) } IpAddr::V6(ip) => { @@ -75,9 +83,9 @@ fn parse_url(raw: &str, https_only: bool) -> Result { // Invariant: URL parsing normalizes controls and backslashes, so reject raw bytes first. if raw.is_empty() || raw.len() > 128 * 1024 - || raw - .chars() - .any(|character| character.is_control() || character.is_whitespace() || character == '\\') + || raw.chars().any(|character| { + character.is_control() || character.is_whitespace() || character == '\\' + }) { return Err("public_url_invalid"); } diff --git a/src/public_http/tests.rs b/src/public_http/tests.rs index 747921c71..a2d197fc6 100644 --- a/src/public_http/tests.rs +++ b/src/public_http/tests.rs @@ -153,7 +153,11 @@ async fn connection_is_pinned_and_original_host_is_preserved() { let request = server.await.unwrap(); assert!(request.to_lowercase().contains("host: sender.example\r\n")); assert!(!request.to_lowercase().contains("authorization:")); - assert!(request.to_lowercase().contains("user-agent: magpie/0.11\r\n")); + assert!( + request + .to_lowercase() + .contains("user-agent: magpie/0.11\r\n") + ); } #[tokio::test] From e93116a4ff6ad8b267ee6f7f8f0d8bcb99650d46 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 029/568] Document credential cache identity invariants --- src/credentials/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/credentials/mod.rs b/src/credentials/mod.rs index 9082a5e1a..5627820bc 100644 --- a/src/credentials/mod.rs +++ b/src/credentials/mod.rs @@ -138,7 +138,7 @@ fn validate_secret(bytes: &[u8]) -> Result<(), Error> { } impl CredentialKey { - /// Keep Linux's historical libsecret attributes: a provider's credential + /// Invariant: Keep Linux's historical libsecret attributes: a provider's credential /// kind is its namespace, OAuth also binds the client and current grant. fn attributes(&self) -> Result, Error> { fn metadata(value: &str) -> Result<(), Error> { @@ -188,7 +188,7 @@ impl CredentialKey { Ok(attributes) } - /// Length-delimited fields prevent delimiter collisions. Hashing also keeps + /// Invariant: Length-delimited fields prevent delimiter collisions. Hashing also keeps /// Windows target names below its limit without putting secrets in metadata. #[cfg(any(target_os = "macos", target_os = "windows", test))] fn native_id(&self) -> Result { From 1fb8b7a7a800bfc056cae862941ae4b204057c69 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 030/568] Fix JMAP watch identity validation --- src/providers/jmap/mod.rs | 67 ++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 40 deletions(-) diff --git a/src/providers/jmap/mod.rs b/src/providers/jmap/mod.rs index 27c94a647..834e80beb 100644 --- a/src/providers/jmap/mod.rs +++ b/src/providers/jmap/mod.rs @@ -40,6 +40,29 @@ struct Registration<'a> { requests: &'a Mutex>>, id: &'a str, } +impl<'a> Registration<'a> { + fn new( + requests: &'a Mutex>>, + params: &'a Value, + ) -> Result<(Self, tokio::sync::watch::Receiver), &'static str> { + let id = params + .get("requestId") + .and_then(Value::as_str) + .unwrap_or(""); + if id.len() > 256 || id.chars().any(char::is_control) { + return Err("invalid_params"); + } + let (cancel, cancelled) = tokio::sync::watch::channel(false); + if !id.is_empty() { + let mut active = requests.lock().map_err(|_| "session_failed")?; + if active.len() >= 64 || active.contains_key(id) { + return Err("jmap_request_limit"); + } + active.insert(id.to_owned(), cancel); + } + Ok((Self { requests, id }, cancelled)) + } +} impl Drop for Registration<'_> { fn drop(&mut self) { if !self.id.is_empty() @@ -110,25 +133,7 @@ impl Session { method: &str, params: &Value, ) -> Result { - let id = params - .get("requestId") - .and_then(Value::as_str) - .unwrap_or(""); - if id.len() > 256 || id.chars().any(char::is_control) { - return Err("invalid_params"); - } - let (cancel, mut cancelled) = tokio::sync::watch::channel(false); - if !id.is_empty() { - let mut requests = self.requests.lock().map_err(|_| "session_failed")?; - if requests.len() >= 64 || requests.contains_key(id) { - return Err("jmap_request_limit"); - } - requests.insert(id.to_owned(), cancel); - } - let _registration = Registration { - requests: &self.requests, - id, - }; + let (registration, mut cancelled) = Registration::new(&self.requests, params)?; let operation = async { if method == "jmap.verify" { self.verify(params).await @@ -138,7 +143,7 @@ impl Session { }; let result = tokio::select! { result=tokio::time::timeout(Duration::from_secs(25),operation)=>result.unwrap_or(Err(if method=="jmap.send"{"jmap_submission_unconfirmed"}else{"jmap_timeout"})), - _=cancelled.changed(),if !id.is_empty()=>Err("jmap_cancelled") + _=cancelled.changed(),if !registration.id.is_empty()=>Err("jmap_cancelled") }; if result == Err("jmap_unauthorized") && let Some(account) = params["accountId"].as_str() @@ -155,25 +160,7 @@ impl Session { "jmap.verify" => self.native_cancellable(method, params).await, "jmap.request" => { let request = prepare(params)?; - let request_id = params - .get("requestId") - .and_then(Value::as_str) - .unwrap_or(""); - if request_id.len() > 256 || request_id.chars().any(char::is_control) { - return Err("invalid_params"); - } - let (cancel, mut cancelled) = tokio::sync::watch::channel(false); - if !request_id.is_empty() { - let mut requests = self.requests.lock().map_err(|_| "session_failed")?; - if requests.len() >= 64 || requests.contains_key(request_id) { - return Err("jmap_request_limit"); - } - requests.insert(request_id.to_owned(), cancel); - } - let _registration = Registration { - requests: &self.requests, - id: request_id, - }; + let (registration, mut cancelled) = Registration::new(&self.requests, params)?; let operation = async { self.authorize(params, &request).await?; let client = self.client.as_ref().map_err(|e| *e)?; @@ -191,7 +178,7 @@ impl Session { }; tokio::select! { result = tokio::time::timeout(REQUEST_TIME, operation) => result.map_err(|_| "jmap_timeout")?, - _ = cancelled.changed(), if !request_id.is_empty() => Err("jmap_cancelled"), + _ = cancelled.changed(), if !registration.id.is_empty() => Err("jmap_cancelled"), } } "jmap.cancel" => { From 9c69f0b05241bf8c6383c3cc7edbd2f86a2af5de Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 031/568] Fix JMAP replacement eviction and IMAP folder refresh --- src/providers/imap/read.rs | 59 ++++++++++++---- src/providers/imap/read/tests.rs | 78 +++++++++++++++++++-- src/providers/jmap/mailbox.rs | 9 ++- src/providers/jmap/mailbox_runtime_tests.rs | 63 +++++++++++++++++ 4 files changed, 184 insertions(+), 25 deletions(-) diff --git a/src/providers/imap/read.rs b/src/providers/imap/read.rs index 90f694a4c..c97c99c6b 100644 --- a/src/providers/imap/read.rs +++ b/src/providers/imap/read.rs @@ -281,12 +281,13 @@ pub(super) async fn mailboxes(w: &mut Wire, p: &Value) -> Result { let epoch = EPOCH.load(std::sync::atomic::Ordering::SeqCst); let boxes = discover_mailboxes(w).await?; let mut cache = BOXES.get_or_init(Default::default).lock().await; - if cache.len() >= 32 { - cache.remove(0); - } if epoch != EPOCH.load(std::sync::atomic::Ordering::SeqCst) { return Ok(boxes); } + cache.retain(|entry| entry.key != key); + if cache.len() >= 32 { + cache.remove(0); + } cache.push(Cached { key, boxes: boxes.clone(), @@ -647,28 +648,56 @@ fn snippet(payload: &Value) -> String { .unwrap_or_default() } fn structure_has_attachments(node: &Node, depth: usize, budget: &mut usize) -> bool { - if depth > 12 || *budget == 0 { return false; } + if depth > 12 || *budget == 0 { + return false; + } *budget -= 1; let fields = node.list(); if matches!(fields.first(), Some(Node::List(_))) { - return fields.iter().take_while(|node| matches!(node, Node::List(_))) + return fields + .iter() + .take_while(|node| matches!(node, Node::List(_))) .any(|node| structure_has_attachments(node, depth + 1, budget)); } - let named = |params: &[Node], key: &str| params.chunks_exact(2) - .any(|pair| pair[0].is(key) && !pair[1].is("NIL") && !pair[1].text().is_empty()); + let named = |params: &[Node], key: &str| { + params + .chunks_exact(2) + .any(|pair| pair[0].is(key) && !pair[1].is("NIL") && !pair[1].text().is_empty()) + }; let text = fields.first().is_some_and(|node| node.is("TEXT")); let nested = fields.first().is_some_and(|node| node.is("MESSAGE")) && fields.get(1).is_some_and(|node| node.is("RFC822")); - let disposition = fields.get(if text { 9 } else if nested { 11 } else { 8 }) - .map(Node::list).unwrap_or(&[]); - let attached = disposition.first().is_some_and(|node| node.is("ATTACHMENT")); + let disposition = fields + .get(if text { + 9 + } else if nested { + 11 + } else { + 8 + }) + .map(Node::list) + .unwrap_or(&[]); + let attached = disposition + .first() + .is_some_and(|node| node.is("ATTACHMENT")); let inline = disposition.first().is_some_and(|node| node.is("INLINE")); let image = fields.first().is_some_and(|node| node.is("IMAGE")); - let cid = fields.get(3).is_some_and(|node| !node.is("NIL") && !node.text().is_empty()); - if image && !attached && (inline || cid) { return false; } - attached || named(fields.get(2).map(Node::list).unwrap_or(&[]), "NAME") - || named(disposition.get(1).map(Node::list).unwrap_or(&[]), "FILENAME") - || (nested && fields.get(8).is_some_and(|node| structure_has_attachments(node, depth + 1, budget))) + let cid = fields + .get(3) + .is_some_and(|node| !node.is("NIL") && !node.text().is_empty()); + if image && !attached && (inline || cid) { + return false; + } + attached + || named(fields.get(2).map(Node::list).unwrap_or(&[]), "NAME") + || named( + disposition.get(1).map(Node::list).unwrap_or(&[]), + "FILENAME", + ) + || (nested + && fields + .get(8) + .is_some_and(|node| structure_has_attachments(node, depth + 1, budget))) } fn parse_messages(data: &[u8], folder: &str, full: bool, boxes: &Mailboxes) -> Result> { diff --git a/src/providers/imap/read/tests.rs b/src/providers/imap/read/tests.rs index 95764fe8c..4ee086f47 100644 --- a/src/providers/imap/read/tests.rs +++ b/src/providers/imap/read/tests.rs @@ -361,14 +361,78 @@ async fn a_command_that_is_never_answered_ends_the_call() { #[test] fn bodystructure_distinguishes_real_files_from_inline_logos_without_reading_body_octets() { for (raw, expected) in [ - (r#"("APPLICATION" "PDF" ("NAME" "report.pdf") NIL NIL "BASE64" 100 NIL ("ATTACHMENT" ("FILENAME" "report.pdf")))"#, true), - (r#"("IMAGE" "PNG" ("NAME" "logo.png") "" NIL "BASE64" 100 NIL ("INLINE" NIL))"#, false), - (r#"("IMAGE" "PNG" ("NAME" "photo.png") "" NIL "BASE64" 100 NIL ("ATTACHMENT" NIL))"#, true), - (r#"("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL NIL)"#, false), - (r#"("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL ("ATTACHMENT" ("FILENAME" "notes.txt")))"#, true), - (r#"(("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL NIL)("APPLICATION" "PDF" NIL NIL NIL "BASE64" 100 NIL ("ATTACHMENT" NIL))"MIXED")"#, true), + ( + r#"("APPLICATION" "PDF" ("NAME" "report.pdf") NIL NIL "BASE64" 100 NIL ("ATTACHMENT" ("FILENAME" "report.pdf")))"#, + true, + ), + ( + r#"("IMAGE" "PNG" ("NAME" "logo.png") "" NIL "BASE64" 100 NIL ("INLINE" NIL))"#, + false, + ), + ( + r#"("IMAGE" "PNG" ("NAME" "photo.png") "" NIL "BASE64" 100 NIL ("ATTACHMENT" NIL))"#, + true, + ), + ( + r#"("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL NIL)"#, + false, + ), + ( + r#"("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL ("ATTACHMENT" ("FILENAME" "notes.txt")))"#, + true, + ), + ( + r#"(("TEXT" "PLAIN" NIL NIL NIL "7BIT" 100 3 NIL NIL)("APPLICATION" "PDF" NIL NIL NIL "BASE64" 100 NIL ("ATTACHMENT" NIL))"MIXED")"#, + true, + ), ] { let parsed = nodes(raw.as_bytes()).unwrap(); - assert_eq!(structure_has_attachments(&parsed[0][0], 0, &mut 4000), expected, "{raw}"); + assert_eq!( + structure_has_attachments(&parsed[0][0], 0, &mut 4000), + expected, + "{raw}" + ); } } + +#[tokio::test] +async fn refreshed_mailboxes_replace_the_cached_roles() { + let (client, server) = tokio::io::duplex(4096); + let peer = tokio::spawn(async move { + let mut wire: Wire = BufReader::new(Box::new(server)); + for name in ["OldArchive", "NewArchive"] { + assert_eq!(line(&mut wire).await.unwrap(), b"O1 CAPABILITY\r\n"); + write( + &mut wire, + b"* CAPABILITY IMAP4rev1\r\nO1 OK capabilities\r\n", + ) + .await + .unwrap(); + assert_eq!(line(&mut wire).await.unwrap(), b"O1 LIST \"\" \"*\"\r\n"); + write( + &mut wire, + format!("* LIST (\\Archive) \"/\" {name}\r\nO1 OK folders\r\n").as_bytes(), + ) + .await + .unwrap(); + } + let mut bytes = [0; 1]; + assert_eq!( + wire.read(&mut bytes).await.unwrap(), + 0, + "cached lookup must not issue another command" + ); + }); + let mut wire: Wire = BufReader::new(Box::new(client)); + let mut params = json!({"settings":{"username":"refresh-regression"},"credential":"synthetic:refresh-regression"}); + let first = mailboxes(&mut wire, ¶ms).await.unwrap(); + assert_eq!(resolve(&first, "\\Archive").unwrap(), "OldArchive"); + params["refresh"] = json!(true); + let refreshed = mailboxes(&mut wire, ¶ms).await.unwrap(); + assert_eq!(resolve(&refreshed, "\\Archive").unwrap(), "NewArchive"); + params["refresh"] = json!(false); + let cached = mailboxes(&mut wire, ¶ms).await.unwrap(); + assert_eq!(resolve(&cached, "\\Archive").unwrap(), "NewArchive"); + drop(wire); + peer.await.unwrap(); +} diff --git a/src/providers/jmap/mailbox.rs b/src/providers/jmap/mailbox.rs index dfc497078..51aff4f94 100644 --- a/src/providers/jmap/mailbox.rs +++ b/src/providers/jmap/mailbox.rs @@ -95,12 +95,12 @@ impl Cache { .unwrap_or(CACHE_BYTES) .saturating_mul(4) .saturating_add(id.len() * 4 + 128); - if size > CACHE_BYTES { - return; - } if let Some((_, old)) = self.entries.remove(&id) { self.bytes = self.bytes.saturating_sub(old); } + if size > CACHE_BYTES { + return; + } if self.bytes.saturating_add(size) > CACHE_BYTES || self.entries.len() >= 4096 { self.clear(); } @@ -661,6 +661,9 @@ impl Session { { return Err("method_not_found"); } + if method == "jmap.watch" { + stream_id(params)?; + } let id = text(params, "accountId")?; if method == "jmap.invalidate" { if let Some(context) = self diff --git a/src/providers/jmap/mailbox_runtime_tests.rs b/src/providers/jmap/mailbox_runtime_tests.rs index 1051f6cfe..1dd8484f8 100644 --- a/src/providers/jmap/mailbox_runtime_tests.rs +++ b/src/providers/jmap/mailbox_runtime_tests.rs @@ -239,3 +239,66 @@ fn retained_caches_evict_by_bytes_and_skip_oversized_entries() { cache.clear(); assert_eq!(cache.bytes, 0); } + +#[test] +fn oversized_cache_replacement_drops_the_stale_entry() { + let mut cache = Cache::default(); + cache.insert("message".into(), json!({"subject":"old"})); + cache.insert("other".into(), json!({"subject":"kept"})); + cache.insert("message".into(), json!("x".repeat(CACHE_BYTES))); + assert!(cache.get("message").is_none()); + assert_eq!(cache.get("other"), Some(&json!({"subject":"kept"}))); + assert_eq!( + cache.bytes, + cache + .entries + .values() + .map(|(_, bytes)| bytes) + .sum::() + ); +} + +#[tokio::test] +async fn native_watch_rejects_unmanageable_stream_ids_before_starting_a_stream() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let session = Session::default(); + let account = "jmap:watch-validation@example.test"; + session.install_verified( + account, + json!({ + "apiUrl":format!("https://localhost:{port}/api"), + "eventSourceUrl":format!("https://localhost:{port}/events"), + "capabilities":{CORE:{},MAIL:{}}, + "primaryAccounts":{MAIL:"account"}, + "accounts":{"account":{"accountCapabilities":{MAIL:{"emailQuerySortOptions":["receivedAt"]}}}} + }), + vec![], + json!({"scheme":"basic","username":"synthetic","secret":"synthetic"}), + "watch-validation@example.test", + ).await.unwrap(); + for stream_id in [ + String::new(), + "x".repeat(257), + "watch\r".into(), + "watch\n".into(), + "watch\r\n".into(), + "watch\0".into(), + ] { + assert_eq!( + session + .native( + "jmap.watch", + &json!({"accountId":account,"streamId":stream_id}) + ) + .await, + Err("invalid_params") + ); + assert!(session.streams.lock().unwrap().is_empty()); + } + assert!( + tokio::time::timeout(Duration::from_millis(20), listener.accept()) + .await + .is_err() + ); +} From 40d260c8504be730ce6983e1b825e34809aa5c86 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 032/568] Name IMAP and JMAP protocol values --- src/providers/imap/mod.rs | 260 ++++++++++++++----------- src/providers/imap/mutation.rs | 136 ++++++------- src/providers/imap/read.rs | 131 +++++++------ src/providers/imap/read/search/page.rs | 37 ++-- src/providers/jmap/query.rs | 57 +++--- 5 files changed, 332 insertions(+), 289 deletions(-) diff --git a/src/providers/imap/mod.rs b/src/providers/imap/mod.rs index 3080b0bc3..a5eca0e7b 100644 --- a/src/providers/imap/mod.rs +++ b/src/providers/imap/mod.rs @@ -43,9 +43,13 @@ struct Idle { since: Instant, } static POOL: OnceLock>> = OnceLock::new(); -async fn acquire(p: &Value) -> Result<(Wire, String)> { - let key = serde_json::to_string(&json!([p["settings"], p["credential"], p["oauth"]])) - .map_err(|_| "invalid_params")?; +async fn acquire(params: &Value) -> Result<(Wire, String)> { + let key = serde_json::to_string(&json!([ + params["settings"], + params["credential"], + params["oauth"] + ])) + .map_err(|_| "invalid_params")?; { let mut pool = POOL.get_or_init(Default::default).lock().await; pool.retain(|entry| entry.since.elapsed() < Duration::from_secs(45)); @@ -53,8 +57,8 @@ async fn acquire(p: &Value) -> Result<(Wire, String)> { return Ok((pool.swap_remove(index).wire, key)); } } - let mut wire = connect(&p["settings"], false).await?; - login(&mut wire, p).await?; + let mut wire = connect(¶ms["settings"], false).await?; + login(&mut wire, params).await?; // Capabilities are negotiated afresh after authentication/TLS, and ID is // sent once on this connection before any mailbox can be selected. let capabilities = command(&mut wire, "CAPABILITY").await?; @@ -85,8 +89,11 @@ async fn release(wire: Wire, key: String) { }); } } -fn string<'a>(p: &'a Value, key: &str) -> Result<&'a str> { - p.get(key).and_then(Value::as_str).ok_or("invalid_params") +fn string<'a>(params: &'a Value, key: &str) -> Result<&'a str> { + params + .get(key) + .and_then(Value::as_str) + .ok_or("invalid_params") } fn safe(s: &str) -> bool { !s.bytes().any(|b| b < 32 || b == 127) @@ -100,16 +107,16 @@ fn quote(s: &str) -> Result { s.replace('\\', "\\\\").replace('"', "\\\"") )) } -async fn write(w: &mut Wire, bytes: &[u8]) -> Result<()> { - w.write_all(bytes) +async fn write(wire: &mut Wire, bytes: &[u8]) -> Result<()> { + wire.write_all(bytes) .await .map_err(|_| "mail_network_failed")?; - w.flush().await.map_err(|_| "mail_network_failed") + wire.flush().await.map_err(|_| "mail_network_failed") } -async fn line(w: &mut Wire) -> Result> { +async fn line(wire: &mut Wire) -> Result> { let mut out = Vec::new(); loop { - let buf = w.fill_buf().await.map_err(|_| "mail_network_failed")?; + let buf = wire.fill_buf().await.map_err(|_| "mail_network_failed")?; if buf.is_empty() { return Err("mail_connection_closed"); } @@ -121,15 +128,15 @@ async fn line(w: &mut Wire) -> Result> { return Err("mail_response_too_large"); } out.extend_from_slice(&buf[..n]); - w.consume(n); + wire.consume(n); if out.ends_with(b"\n") { return Ok(out); } } } -async fn response(w: &mut Wire, tag: &str, continuation: bool) -> Result> { +async fn response(wire: &mut Wire, tag: &str, continuation: bool) -> Result> { let mut out = Vec::new(); - response_each(w, tag, continuation, |record| { + response_each(wire, tag, continuation, |record| { out.extend_from_slice(record); Ok(()) }) @@ -140,12 +147,12 @@ async fn response(w: &mut Wire, tag: &str, continuation: bool) -> Result /// then goes quiet fails the call here, rather than holding it until the /// conversation as a whole runs out of time. async fn response_each( - w: &mut Wire, + wire: &mut Wire, tag: &str, continuation: bool, visit: impl FnMut(&[u8]) -> Result<()>, ) -> Result<()> { - tokio::time::timeout(COMMAND_BUDGET, records(w, tag, continuation, visit)) + tokio::time::timeout(COMMAND_BUDGET, records(wire, tag, continuation, visit)) .await .unwrap_or(Err("request_timed_out")) } @@ -153,14 +160,14 @@ async fn response_each( /// protocol record. UID inventories can retain only numbers instead of a full /// response and a second, much larger parsed syntax tree. async fn records( - w: &mut Wire, + wire: &mut Wire, tag: &str, continuation: bool, mut visit: impl FnMut(&[u8]) -> Result<()>, ) -> Result<()> { let mut total = 0; loop { - let l = line(w).await?; + let l = line(wire).await?; if total + l.len() > LIMIT { return Err("mail_response_too_large"); } @@ -195,11 +202,11 @@ async fn records( } let start = record.len(); record.resize(start + n, 0); - w.read_exact(&mut record[start..]) + wire.read_exact(&mut record[start..]) .await .map_err(|_| "mail_network_failed")?; total += n; - let suffix = line(w).await?; + let suffix = line(wire).await?; if total + suffix.len() > LIMIT { return Err("mail_response_too_large"); } @@ -217,17 +224,21 @@ fn literal_length(line: &str) -> Option()) } -async fn command(w: &mut Wire, cmd: &str) -> Result> { - write(w, format!("O1 {cmd}\r\n").as_bytes()).await?; - response(w, "O1", false).await +async fn command(wire: &mut Wire, command_text: &str) -> Result> { + write(wire, format!("O1 {command_text}\r\n").as_bytes()).await?; + response(wire, "O1", false).await } -async fn tls(w: Wire, host: &str) -> Result { - if !w.buffer().is_empty() { +async fn tls(wire: Wire, host: &str) -> Result { + if !wire.buffer().is_empty() { return Err("mail_tls_failed"); } - tls_with_roots(w, host, crate::tls::roots()).await + tls_with_roots(wire, host, crate::tls::roots()).await } -async fn tls_with_roots(w: Wire, host: &str, roots: impl Into>) -> Result { +async fn tls_with_roots( + wire: Wire, + host: &str, + roots: impl Into>, +) -> Result { let config = ClientConfig::builder_with_provider(Arc::new( tokio_rustls::rustls::crypto::ring::default_provider(), )) @@ -235,15 +246,15 @@ async fn tls_with_roots(w: Wire, host: &str, roots: impl Into .map_err(|_| "mail_tls_failed")? .with_root_certificates(roots) .with_no_client_auth(); - tls_with_config(w, host, config).await + tls_with_config(wire, host, config).await } -async fn tls_with_config(w: Wire, host: &str, config: ClientConfig) -> Result { - if !w.buffer().is_empty() { +async fn tls_with_config(wire: Wire, host: &str, config: ClientConfig) -> Result { + if !wire.buffer().is_empty() { return Err("mail_tls_failed"); } let name = ServerName::try_from(host.to_owned()).map_err(|_| "invalid_params")?; let stream = TlsConnector::from(Arc::new(config)) - .connect(name, w.into_inner()) + .connect(name, wire.into_inner()) .await .map_err(|_| "mail_tls_failed")?; Ok(BufReader::new(Box::new(stream))) @@ -305,7 +316,7 @@ where } let port = settings[if smtp { "smtpPort" } else { "imapPort" }] .as_u64() - .filter(|p| *p > 0 && *p <= 65535) + .filter(|params| *params > 0 && *params <= 65535) .ok_or("invalid_params")? as u16; let loopback = matches!(host, "127.0.0.1" | "::1" | "localhost"); let allow_self_signed = loopback && settings["insecure"] == true; @@ -333,49 +344,49 @@ where host }; let stream = dial(dial_host.to_owned(), port).await?; - let w: Wire = BufReader::new(Box::new(stream)); - handshake(w, host, smtp, allow_self_signed, transport).await + let wire: Wire = BufReader::new(Box::new(stream)); + handshake(wire, host, smtp, allow_self_signed, transport).await } async fn handshake( - mut w: Wire, + mut wire: Wire, host: &str, smtp: bool, allow_self_signed: bool, transport: Transport, ) -> Result { if transport == Transport::Tls { - w = secure(w, host, allow_self_signed).await? + wire = secure(wire, host, allow_self_signed).await? } if smtp { - smtp_response(&mut w, 220).await?; + smtp_response(&mut wire, 220).await?; } else { - let greeting = line(&mut w).await?; + let greeting = line(&mut wire).await?; if !greeting.starts_with(b"* OK") { return Err("imap_invalid_response"); } } if transport == Transport::StartTls { if smtp { - smtp_cmd(&mut w, "EHLO omamail", 250).await?; - smtp_cmd(&mut w, "STARTTLS", 220).await?; + smtp_cmd(&mut wire, "EHLO omamail", 250).await?; + smtp_cmd(&mut wire, "STARTTLS", 220).await?; } else { - command(&mut w, "STARTTLS").await?; + command(&mut wire, "STARTTLS").await?; } - w = secure(w, host, allow_self_signed).await?; + wire = secure(wire, host, allow_self_signed).await?; } - Ok(w) + Ok(wire) } -async fn secure(w: Wire, host: &str, allow_self_signed: bool) -> Result { +async fn secure(wire: Wire, host: &str, allow_self_signed: bool) -> Result { if allow_self_signed { - bridge_tls::upgrade(w, host).await + bridge_tls::upgrade(wire, host).await } else { - tls(w, host).await + tls(wire, host).await } } -fn credentials(p: &Value) -> Result<(String, String)> { - let supplied = string(p, "credential")?; - let username = string(&p["settings"], "username")?; - let secret = if p["oauth"] == true { +fn credentials(params: &Value) -> Result<(String, String)> { + let supplied = string(params, "credential")?; + let username = string(¶ms["settings"], "username")?; + let secret = if params["oauth"] == true { supplied } else { supplied @@ -387,21 +398,24 @@ fn credentials(p: &Value) -> Result<(String, String)> { } Ok((username.to_owned(), secret.to_owned())) } -async fn login(w: &mut Wire, p: &Value) -> Result<()> { - let (user, secret) = credentials(p)?; - if p["oauth"] == true { - write(w, b"O1 AUTHENTICATE XOAUTH2\r\n").await?; - let l = line(w).await?; +async fn login(wire: &mut Wire, params: &Value) -> Result<()> { + let (user, secret) = credentials(params)?; + if params["oauth"] == true { + write(wire, b"O1 AUTHENTICATE XOAUTH2\r\n").await?; + let l = line(wire).await?; if !l.starts_with(b"+") { return Err("mail_auth_failed"); } let auth = STANDARD.encode(format!("user={user}\x01auth=Bearer {secret}\x01\x01")); - write(w, format!("{auth}\r\n").as_bytes()).await?; - response(w, "O1", false).await.map_err(refused)?; + write(wire, format!("{auth}\r\n").as_bytes()).await?; + response(wire, "O1", false).await.map_err(refused)?; } else { - command(w, &format!("LOGIN {} {}", quote(&user)?, quote(&secret)?)) - .await - .map_err(refused)?; + command( + wire, + &format!("LOGIN {} {}", quote(&user)?, quote(&secret)?), + ) + .await + .map_err(refused)?; } Ok(()) } @@ -493,11 +507,11 @@ pub(crate) async fn execute_planned_action( })) } -pub async fn call(method: &str, p: &Value) -> Result { - read::validate(method, p)?; - mutation::validate(method, p)?; +pub async fn call(method: &str, params: &Value) -> Result { + read::validate(method, params)?; + mutation::validate(method, params)?; if method == "imap.cancel" { - return cancel::cancel(p).await; + return cancel::cancel(params).await; } if matches!( method, @@ -509,14 +523,14 @@ pub async fn call(method: &str, p: &Value) -> Result { | "imap.attachment" | "imap.check" ) { - return cancel::run(p, call_inner(method, p)).await; + return cancel::run(params, call_inner(method, params)).await; } - call_inner(method, p).await + call_inner(method, params).await } -async fn call_inner(method: &str, p: &Value) -> Result { +async fn call_inner(method: &str, params: &Value) -> Result { let sent = std::sync::atomic::AtomicBool::new(false); match tokio::time::timeout(CALL_BUDGET, async { - let resolved = resolve_account(p, method).await?; + let resolved = resolve_account(params, method).await?; execute(method, &resolved, &sent).await }) .await @@ -529,9 +543,9 @@ async fn call_inner(method: &str, p: &Value) -> Result { Err(_) => Err("request_timed_out"), } } -async fn resolve_account(p: &Value, method: &str) -> Result { - let Some(account) = p.get("accountId").and_then(Value::as_str) else { - return Ok(p.clone()); +async fn resolve_account(params: &Value, method: &str) -> Result { + let Some(account) = params.get("accountId").and_then(Value::as_str) else { + return Ok(params.clone()); }; let provider = if account.starts_with("outlook:") { "outlook" @@ -541,7 +555,7 @@ async fn resolve_account(p: &Value, method: &str) -> Result { return Err("invalid_params"); }; let owned = account.to_owned(); - let read_only = p["readOnly"] == true; + let read_only = params["readOnly"] == true; let entry = tokio::task::spawn_blocking(move || { if read_only { crate::auth::settings_readonly(provider, &owned) @@ -551,7 +565,7 @@ async fn resolve_account(p: &Value, method: &str) -> Result { }) .await .map_err(|_| "worker_failed")??; - let mut result = p.clone(); + let mut result = params.clone(); let credential = if provider == "outlook" { let username = account.strip_prefix("outlook:").ok_or("invalid_params")?; result["settings"] = outlook_settings(&entry, username); @@ -602,8 +616,12 @@ fn unsafe_fetch(command: &str) -> bool { .split(|c: char| c.is_whitespace() || c == '(' || c == ')') .any(|part| matches!(part, "RFC822" | "RFC822.TEXT" | "BODY")) } -async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) -> Result { - credentials(p)?; +async fn execute( + method: &str, + params: &Value, + sent: &std::sync::atomic::AtomicBool, +) -> Result { + credentials(params)?; if matches!( method, "imap.folders" @@ -613,7 +631,7 @@ async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) | "imap.count" | "imap.attachment" ) { - return read::call(method, p).await; + return read::call(method, params).await; } if matches!( method, @@ -627,14 +645,14 @@ async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) | "imap.deleteDraft" | "imap.send" ) { - return mutation::call(method, p, sent).await; + return mutation::call(method, params, sent).await; } // Validate the entire batch and envelope before opening any socket. - credentials(p)?; - let folder = p["folder"].as_str().unwrap_or(""); + credentials(params)?; + let folder = params["folder"].as_str().unwrap_or(""); let quoted = quote(folder)?; let commands = if method == "imap.request" { - p["commands"] + params["commands"] .as_array() .ok_or("invalid_params")? .iter() @@ -679,19 +697,19 @@ async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) return Err("invalid_params"); } if method == "smtp.send" { - return send(p).await; + return send(params).await; } if !matches!(method, "imap.request" | "imap.append" | "imap.check") { return Err("method_not_found"); } let append = if method == "imap.append" { let body = STANDARD - .decode(string(p, "body")?) + .decode(string(params, "body")?) .map_err(|_| "invalid_params")?; if body.len() > LIMIT { return Err("invalid_params"); } - let flag = match string(p, "flags")? { + let flag = match string(params, "flags")? { "seen" => "\\Seen", "draft" => "\\Draft", _ => return Err("invalid_params"), @@ -700,47 +718,51 @@ async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) } else { None }; - let (mut w, key) = acquire(p).await?; + let (mut wire, key) = acquire(params).await?; if method == "imap.check" { - let data = command(&mut w, "STATUS INBOX (UNSEEN MESSAGES UIDNEXT UIDVALIDITY)").await?; - release(w, key).await; + let data = command( + &mut wire, + "STATUS INBOX (UNSEEN MESSAGES UIDNEXT UIDVALIDITY)", + ) + .await?; + release(wire, key).await; let text = String::from_utf8_lossy(&data); let tokens: Vec<_> = text .split(|c: char| c.is_whitespace() || c == '(' || c == ')') .collect(); let unseen = tokens .windows(2) - .find(|w| w[0].eq_ignore_ascii_case("UNSEEN")) - .and_then(|w| w[1].parse::().ok()) + .find(|fields| fields[0].eq_ignore_ascii_case("UNSEEN")) + .and_then(|fields| fields[1].parse::().ok()) .ok_or("imap_invalid_response")?; return Ok(json!({"estimate":unseen,"messages":[],"fingerprint":STANDARD.encode(data)})); } let mut out = Vec::new(); if let Some((body, flag)) = append { write( - &mut w, + &mut wire, format!("O1 APPEND {quoted} ({flag}) {{{}}}\r\n", body.len()).as_bytes(), ) .await?; // APPEND must be granted a continuation before any message bytes are sent. - let l = line(&mut w).await?; + let l = line(&mut wire).await?; if !l.starts_with(b"+") { return Err("imap_command_failed"); } - write(&mut w, &body).await?; - write(&mut w, b"\r\n").await?; - response(&mut w, "O1", false).await?; + write(&mut wire, &body).await?; + write(&mut wire, b"\r\n").await?; + response(&mut wire, "O1", false).await?; } else { if !folder.is_empty() { - command(&mut w, &format!("SELECT {quoted}")).await?; + command(&mut wire, &format!("SELECT {quoted}")).await?; } - let changes_folders = commands.iter().any(|cmd| { + let changes_folders = commands.iter().any(|command_text| { ["CREATE ", "RENAME ", "DELETE "] .iter() - .any(|prefix| cmd.to_ascii_uppercase().starts_with(prefix)) + .any(|prefix| command_text.to_ascii_uppercase().starts_with(prefix)) }); - for cmd in commands { - let part = command(&mut w, cmd).await?; + for command_text in commands { + let part = command(&mut wire, command_text).await?; if out.len() + part.len() > LIMIT { return Err("mail_response_too_large"); } @@ -750,13 +772,13 @@ async fn execute(method: &str, p: &Value, sent: &std::sync::atomic::AtomicBool) read::invalidate().await; } } - release(w, key).await; + release(wire, key).await; Ok(json!({"data":STANDARD.encode(out)})) } -async fn smtp_response(w: &mut Wire, wanted: u16) -> Result<()> { +async fn smtp_response(wire: &mut Wire, wanted: u16) -> Result<()> { let mut total = 0; loop { - let l = line(w).await?; + let l = line(wire).await?; total += l.len(); if total > 65536 || l.len() < 5 { return Err("smtp_invalid_response"); @@ -775,9 +797,9 @@ async fn smtp_response(w: &mut Wire, wanted: u16) -> Result<()> { } } } -async fn smtp_cmd(w: &mut Wire, cmd: &str, code: u16) -> Result<()> { - write(w, format!("{cmd}\r\n").as_bytes()).await?; - smtp_response(w, code).await +async fn smtp_cmd(wire: &mut Wire, command_text: &str, code: u16) -> Result<()> { + write(wire, format!("{command_text}\r\n").as_bytes()).await?; + smtp_response(wire, code).await } fn smtp_data(body: &[u8]) -> Result> { if body @@ -803,9 +825,9 @@ fn smtp_data(body: &[u8]) -> Result> { encoded.extend_from_slice(b".\r\n"); Ok(encoded) } -async fn send(p: &Value) -> Result { +async fn send(params: &Value) -> Result { let body = STANDARD - .decode(string(p, "body")?) + .decode(string(params, "body")?) .map_err(|_| "invalid_params")?; if body.len() > LIMIT { return Err("invalid_params"); @@ -817,8 +839,8 @@ async fn send(p: &Value) -> Result { Ok(s) } } - let from = address(string(p, "from")?)?; - let to = p["recipients"] + let from = address(string(params, "from")?)?; + let to = params["recipients"] .as_array() .ok_or("invalid_params")? .iter() @@ -828,10 +850,10 @@ async fn send(p: &Value) -> Result { return Err("invalid_params"); } let encoded = smtp_data(&body)?; - let (user, secret) = credentials(p)?; - let mut w = connect(&p["settings"], true).await?; - smtp_cmd(&mut w, "EHLO omamail", 250).await?; - let auth = if p["oauth"] == true { + let (user, secret) = credentials(params)?; + let mut wire = connect(¶ms["settings"], true).await?; + smtp_cmd(&mut wire, "EHLO omamail", 250).await?; + let auth = if params["oauth"] == true { format!( "AUTH XOAUTH2 {}", STANDARD.encode(format!("user={user}\x01auth=Bearer {secret}\x01\x01")) @@ -842,19 +864,19 @@ async fn send(p: &Value) -> Result { STANDARD.encode(format!("\0{user}\0{secret}")) ) }; - smtp_cmd(&mut w, &auth, 235) + smtp_cmd(&mut wire, &auth, 235) .await .map_err(|_| "mail_auth_failed")?; - smtp_cmd(&mut w, &format!("MAIL FROM:<{from}>"), 250).await?; + smtp_cmd(&mut wire, &format!("MAIL FROM:<{from}>"), 250).await?; for recipient in to { - smtp_cmd(&mut w, &format!("RCPT TO:<{recipient}>"), 250).await?; + smtp_cmd(&mut wire, &format!("RCPT TO:<{recipient}>"), 250).await?; } - smtp_cmd(&mut w, "DATA", 354).await?; + smtp_cmd(&mut wire, "DATA", 354).await?; // After DATA starts, a failed final reply cannot prove the message was not delivered. - write(&mut w, &encoded) + write(&mut wire, &encoded) .await .map_err(|_| "smtp_delivery_unknown")?; - smtp_response(&mut w, 250) + smtp_response(&mut wire, 250) .await .map_err(|_| "smtp_delivery_unknown")?; Ok(json!({"sent":true})) diff --git a/src/providers/imap/mutation.rs b/src/providers/imap/mutation.rs index f76fe8d7c..2d6242aa2 100644 --- a/src/providers/imap/mutation.rs +++ b/src/providers/imap/mutation.rs @@ -3,8 +3,8 @@ use super::read::{Mailboxes, mailboxes, message_id, resolve}; use super::*; use base64::engine::general_purpose::{STANDARD_NO_PAD, URL_SAFE_NO_PAD}; use std::collections::BTreeMap; -fn ids(p: &Value) -> Result>> { - let entries = p["ids"].as_array().ok_or("invalid_params")?; +fn ids(params: &Value) -> Result>> { + let entries = params["ids"].as_array().ok_or("invalid_params")?; if entries.len() > 500 { return Err("invalid_params"); } @@ -15,8 +15,8 @@ fn ids(p: &Value) -> Result>> { } Ok(groups) } -fn strings(p: &Value, key: &str) -> Result> { - p[key] +fn strings(params: &Value, key: &str) -> Result> { + params[key] .as_array() .ok_or("invalid_params")? .iter() @@ -29,7 +29,7 @@ fn strings(p: &Value, key: &str) -> Result> { } fn plan( method: &str, - p: &Value, + params: &Value, boxes: &Mailboxes, ) -> Result<(Vec, Vec, Option)> { if method == "imap.trash" { @@ -38,8 +38,8 @@ fn plan( if method == "imap.untrash" { return Ok((vec![], vec!["\\Deleted".into()], Some("INBOX".into()))); } - let added = strings(p, "addLabelIds")?; - let removed = strings(p, "removeLabelIds")?; + let added = strings(params, "addLabelIds")?; + let removed = strings(params, "removeLabelIds")?; let has = |items: &[String], name: &str| items.iter().any(|v| v.eq_ignore_ascii_case(name)); let target = if has(&removed, "INBOX") { added.first().cloned() @@ -110,9 +110,9 @@ fn encoded_mailbox(name: &str) -> Result { flush(&mut out, &mut run); Ok(out) } -async fn append(w: &mut Wire, folder: &str, body: &[u8], flag: &str) -> Result<()> { +async fn append(wire: &mut Wire, folder: &str, body: &[u8], flag: &str) -> Result<()> { write( - w, + wire, format!( "O1 APPEND {} ({flag}) {{{}}}\r\n", quote(folder)?, @@ -121,22 +121,22 @@ async fn append(w: &mut Wire, folder: &str, body: &[u8], flag: &str) -> Result<( .as_bytes(), ) .await?; - let answer = line(w).await?; + let answer = line(wire).await?; if !answer.starts_with(b"+") { return Err("imap_command_failed"); } - write(w, body).await?; - write(w, b"\r\n").await?; - response(w, "O1", false).await?; + write(wire, body).await?; + write(wire, b"\r\n").await?; + response(wire, "O1", false).await?; Ok(()) } -async fn delete_uid(w: &mut Wire, uid: u32) -> Result<()> { - command(w, &format!("UID STORE {uid} +FLAGS.SILENT (\\Deleted)")).await?; - command(w, &format!("UID EXPUNGE {uid}")).await?; +async fn delete_uid(wire: &mut Wire, uid: u32) -> Result<()> { + command(wire, &format!("UID STORE {uid} +FLAGS.SILENT (\\Deleted)")).await?; + command(wire, &format!("UID EXPUNGE {uid}")).await?; Ok(()) } -fn raw(p: &Value) -> Result> { - let text = string(p, "raw")?; +fn raw(params: &Value) -> Result> { + let text = string(params, "raw")?; if text.len() > LIMIT * 4 / 3 + 4 { return Err("invalid_params"); } @@ -189,41 +189,41 @@ fn without_bcc(body: &[u8]) -> Vec { } out } -pub(super) fn validate(method: &str, p: &Value) -> Result<()> { +pub(super) fn validate(method: &str, params: &Value) -> Result<()> { match method { "imap.createFolder" => { - encoded_mailbox(string(p, "name")?)?; + encoded_mailbox(string(params, "name")?)?; } "imap.renameFolder" => { - let id = string(p, "id")?; + let id = string(params, "id")?; if id.is_empty() { return Err("invalid_params"); } quote(id)?; - encoded_mailbox(string(p, "name")?)?; + encoded_mailbox(string(params, "name")?)?; } "imap.deleteFolder" => { - let id = string(p, "id")?; + let id = string(params, "id")?; if id.is_empty() { return Err("invalid_params"); } quote(id)?; } "imap.modify" => { - ids(p)?; - strings(p, "addLabelIds")?; - strings(p, "removeLabelIds")?; + ids(params)?; + strings(params, "addLabelIds")?; + strings(params, "removeLabelIds")?; } "imap.trash" | "imap.untrash" => { - ids(p)?; + ids(params)?; } "imap.deleteDraft" => { - message_id(string(p, "id")?)?; + message_id(string(params, "id")?)?; } "imap.saveDraft" | "imap.send" => { - let body = raw(p)?; + let body = raw(params)?; if method == "imap.saveDraft" - && let Some(value) = p.get("draftId") + && let Some(value) = params.get("draftId") { let id = value.as_str().ok_or("invalid_params")?; if !id.is_empty() { @@ -241,43 +241,43 @@ pub(super) fn validate(method: &str, p: &Value) -> Result<()> { } pub(super) async fn call( method: &str, - p: &Value, + params: &Value, sent: &std::sync::atomic::AtomicBool, ) -> Result { - call_planned(method, p, sent, None, None).await + call_planned(method, params, sent, None, None).await } pub(super) async fn call_planned( method: &str, - p: &Value, + params: &Value, sent: &std::sync::atomic::AtomicBool, planned: Option<&Mailboxes>, mut completed_folders: Option<&mut Vec>, ) -> Result { if method == "imap.send" { - let body = raw(p)?; - if p["oauth"] == true && p["settings"]["send"] == "graph" { + let body = raw(params)?; + if params["oauth"] == true && params["settings"]["send"] == "graph" { let result = crate::auth::Session::default() .call( "outlook.graphSend", - &json!({"accountId":p["accountId"],"raw":p["raw"]}), + &json!({"accountId":params["accountId"],"raw":params["raw"]}), ) .await?; sent.store(true, std::sync::atomic::Ordering::SeqCst); return Ok(result); } - let (from, recipients) = envelope(&body, string(&p["settings"], "username")?)?; - let mut submit = p.clone(); + let (from, recipients) = envelope(&body, string(¶ms["settings"], "username")?)?; + let mut submit = params.clone(); submit["from"] = json!(from); submit["recipients"] = json!(recipients); submit["body"] = json!(STANDARD.encode(without_bcc(&body))); super::send(&submit).await?; sent.store(true, std::sync::atomic::Ordering::SeqCst); let copy = async { - let (mut w, key) = acquire(p).await?; - let boxes = mailboxes(&mut w, p).await?; + let (mut wire, key) = acquire(params).await?; + let boxes = mailboxes(&mut wire, params).await?; let folder = resolve(&boxes, "\\Sent")?; - append(&mut w, &folder, &body, "\\Seen").await?; - release(w, key).await; + append(&mut wire, &folder, &body, "\\Seen").await?; + release(wire, key).await; Ok::<_, &'static str>(()) } .await; @@ -289,15 +289,15 @@ pub(super) async fn call_planned( let folder_command = match method { "imap.createFolder" => Some(format!( "CREATE {}", - quote(&encoded_mailbox(string(p, "name")?)?)? + quote(&encoded_mailbox(string(params, "name")?)?)? )), "imap.renameFolder" => Some(format!( "RENAME {} {}", - quote(string(p, "id")?)?, - quote(&encoded_mailbox(string(p, "name")?)?)? + quote(string(params, "id")?)?, + quote(&encoded_mailbox(string(params, "name")?)?)? )), "imap.deleteFolder" => { - let id = string(p, "id")?; + let id = string(params, "id")?; if id.is_empty() { return Err("invalid_params"); } @@ -306,39 +306,39 @@ pub(super) async fn call_planned( _ => None, }; let groups = if matches!(method, "imap.modify" | "imap.trash" | "imap.untrash") { - let groups = ids(p)?; + let groups = ids(params)?; if method == "imap.modify" { - strings(p, "addLabelIds")?; - strings(p, "removeLabelIds")?; + strings(params, "addLabelIds")?; + strings(params, "removeLabelIds")?; } Some(groups) } else { None }; let draft = if method == "imap.saveDraft" { - Some(raw(p)?) + Some(raw(params)?) } else { None }; let deleting = if method == "imap.deleteDraft" { - Some(message_id(string(p, "id")?)?) + Some(message_id(string(params, "id")?)?) } else { None }; - let (mut w, key) = acquire(p).await?; + let (mut wire, key) = acquire(params).await?; let result = if let Some(command_text) = folder_command { - command(&mut w, &command_text).await?; + command(&mut wire, &command_text).await?; read::invalidate().await; json!({}) } else { let boxes = match planned { Some(boxes) => boxes.clone(), - None => mailboxes(&mut w, p).await?, + None => mailboxes(&mut wire, params).await?, }; if let Some(groups) = groups { - let (add, remove, destination) = plan(method, p, &boxes)?; + let (add, remove, destination) = plan(method, params, &boxes)?; for (folder, uids) in groups { - command(&mut w, &format!("SELECT {}", quote(&folder)?)).await?; + command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; let set = uids .iter() .map(u32::to_string) @@ -347,7 +347,7 @@ pub(super) async fn call_planned( for (mode, flags) in [("+", &add), ("-", &remove)] { if !flags.is_empty() { command( - &mut w, + &mut wire, &format!("UID STORE {set} {mode}FLAGS.SILENT ({})", flags.join(" ")), ) .await?; @@ -361,15 +361,15 @@ pub(super) async fn call_planned( .iter() .any(|v| v.eq_ignore_ascii_case("MOVE")) { - command(&mut w, &format!("UID MOVE {set} {}", quote(target)?)).await?; + command(&mut wire, &format!("UID MOVE {set} {}", quote(target)?)).await?; } else { - command(&mut w, &format!("UID COPY {set} {}", quote(target)?)).await?; + command(&mut wire, &format!("UID COPY {set} {}", quote(target)?)).await?; command( - &mut w, + &mut wire, &format!("UID STORE {set} +FLAGS.SILENT (\\Deleted)"), ) .await?; - command(&mut w, &format!("UID EXPUNGE {set}")).await?; + command(&mut wire, &format!("UID EXPUNGE {set}")).await?; } } // Record only a fully acknowledged group. Keep the ledger @@ -382,14 +382,14 @@ pub(super) async fn call_planned( json!({}) } else if let Some(body) = draft { let folder = resolve(&boxes, "\\Drafts")?; - append(&mut w, &folder, &body, "\\Draft").await?; - let warning = if let Some(id) = p["draftId"].as_str().filter(|id| !id.is_empty()) { + append(&mut wire, &folder, &body, "\\Draft").await?; + let warning = if let Some(id) = params["draftId"].as_str().filter(|id| !id.is_empty()) { if let Ok((uid, previous_folder)) = message_id(id) && previous_folder == folder { let cleanup = async { - command(&mut w, &format!("SELECT {}", quote(&folder)?)).await?; - delete_uid(&mut w, uid).await + command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; + delete_uid(&mut wire, uid).await } .await; if cleanup.is_ok() { @@ -405,14 +405,14 @@ pub(super) async fn call_planned( }; json!({"saved":true,"warning":warning}) } else if let Some((uid, folder)) = deleting { - command(&mut w, &format!("SELECT {}", quote(&folder)?)).await?; - delete_uid(&mut w, uid).await?; + command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; + delete_uid(&mut wire, uid).await?; json!({}) } else { return Err("method_not_found"); } }; - release(w, key).await; + release(wire, key).await; Ok(result) } #[cfg(test)] diff --git a/src/providers/imap/read.rs b/src/providers/imap/read.rs index c97c99c6b..d822ab1e7 100644 --- a/src/providers/imap/read.rs +++ b/src/providers/imap/read.rs @@ -175,8 +175,8 @@ pub(super) async fn invalidate() { BOXES.get_or_init(Default::default).lock().await.clear(); } static BOXES: OnceLock>> = OnceLock::new(); -fn cache_key(p: &Value) -> String { - json!([p["settings"], p["credential"], p["oauth"]]).to_string() +fn cache_key(params: &Value) -> String { + json!([params["settings"], params["credential"], params["oauth"]]).to_string() } fn parse_folders(data: &[u8]) -> Result { let mut folders = Vec::new(); @@ -264,22 +264,25 @@ fn parse_folders(data: &[u8]) -> Result { capabilities, }) } -pub(super) async fn discover_mailboxes(w: &mut Wire) -> Result { - let mut data = command(w, "CAPABILITY").await?; - data.extend(command(w, "LIST \"\" \"*\"").await?); +pub(super) async fn discover_mailboxes(wire: &mut Wire) -> Result { + let mut data = command(wire, "CAPABILITY").await?; + data.extend(command(wire, "LIST \"\" \"*\"").await?); parse_folders(&data) } -pub(super) async fn mailboxes(w: &mut Wire, p: &Value) -> Result { - let key = cache_key(p); +pub(super) async fn mailboxes(wire: &mut Wire, params: &Value) -> Result { + let key = cache_key(params); { let mut cache = BOXES.get_or_init(Default::default).lock().await; cache.retain(|c| c.since.elapsed() < Duration::from_secs(60)); - if let Some(c) = cache.iter().find(|c| c.key == key && p["refresh"] != true) { + if let Some(c) = cache + .iter() + .find(|c| c.key == key && params["refresh"] != true) + { return Ok(c.boxes.clone()); } } let epoch = EPOCH.load(std::sync::atomic::Ordering::SeqCst); - let boxes = discover_mailboxes(w).await?; + let boxes = discover_mailboxes(wire).await?; let mut cache = BOXES.get_or_init(Default::default).lock().await; if epoch != EPOCH.load(std::sync::atomic::Ordering::SeqCst) { return Ok(boxes); @@ -479,20 +482,20 @@ fn page( let can_continue = next < ordered.len() || more; json!({"ids":ids,"threadIds":[],"nextPageToken":if can_continue{next.to_string()}else{String::new()},"estimate":if more{ordered.len().max(offset+limit+1)}else{ordered.len()}}) } -async fn list(w: &mut Wire, p: &Value, boxes: &Mailboxes) -> Result { - let limit = p["limit"].as_u64().unwrap_or(25).clamp(1, 100) as usize; - let offset = p["pageToken"] +async fn list(wire: &mut Wire, params: &Value, boxes: &Mailboxes) -> Result { + let limit = params["limit"].as_u64().unwrap_or(25).clamp(1, 100) as usize; + let offset = params["pageToken"] .as_str() .unwrap_or("") .parse::() .unwrap_or(0) .min(10_000_000); - let (folder, criteria) = query(p["query"].as_str().unwrap_or(""))?; + let (folder, criteria) = query(params["query"].as_str().unwrap_or(""))?; let folder = resolve(boxes, &folder)?; - command(w, &format!("SELECT {}", quote(&folder)?)).await?; + command(wire, &format!("SELECT {}", quote(&folder)?)).await?; let mut found = Vec::new(); let mut ceiling = None; - if let Some(token) = p["continuation"].as_str() { + if let Some(token) = params["continuation"].as_str() { if token.len() > 128 * 1024 { return Err("invalid_params"); } @@ -502,8 +505,8 @@ async fn list(w: &mut Wire, p: &Value, boxes: &Mailboxes) -> Result { let state: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid_params")?; if state["folder"] != folder || state["criteria"] != criteria - || state["accountId"] != p["accountId"] - || state["requestToken"] != p["requestToken"] + || state["accountId"] != params["accountId"] + || state["requestToken"] != params["requestToken"] { return Err("invalid_params"); } @@ -531,7 +534,7 @@ async fn list(w: &mut Wire, p: &Value, boxes: &Mailboxes) -> Result { // Keep the compact, response-limited UID snapshot. Explicit UID batches // bound the larger date responses without walking gaps in sparse UIDs // or relying on sequence numbers that move when mail is expunged. - let mut snapshot: Vec<_> = fetched_dates(&command(w, "UID FETCH 1:* (UID)").await?)? + let mut snapshot: Vec<_> = fetched_dates(&command(wire, "UID FETCH 1:* (UID)").await?)? .into_keys() .collect(); let mut dates = BTreeMap::new(); @@ -541,8 +544,9 @@ async fn list(w: &mut Wire, p: &Value, boxes: &Mailboxes) -> Result { .map(u32::to_string) .collect::>() .join(","); - let fetched = - fetched_dates(&command(w, &format!("UID FETCH {set} (UID INTERNALDATE)")).await?)?; + let fetched = fetched_dates( + &command(wire, &format!("UID FETCH {set} (UID INTERNALDATE)")).await?, + )?; // Ignore unsolicited updates outside this batch (including arrivals // after the snapshot), and drop messages expunged before this fetch. dates.extend( @@ -563,7 +567,7 @@ async fn list(w: &mut Wire, p: &Value, boxes: &Mailboxes) -> Result { let first = window[0]; let last = *window.last().unwrap(); matches.extend(search_uids( - &command(w, &format!("UID SEARCH UID {first}:{last} {criteria}")).await?, + &command(wire, &format!("UID SEARCH UID {first}:{last} {criteria}")).await?, )?); } Ok((matches, dates)) @@ -713,10 +717,10 @@ fn parse_messages(data: &[u8], folder: &str, full: bool, boxes: &Mailboxes) -> R let mut size = 0u64; let mut raw = None; let mut has_attachments = false; - let mut i = 0; - while i + 1 < fields.len() { - let key = &fields[i]; - let value = &fields[i + 1]; + let mut field_index = 0; + while field_index + 1 < fields.len() { + let key = &fields[field_index]; + let value = &fields[field_index + 1]; if key.is("UID") { uid = value.number() } else if key.is("FLAGS") { @@ -739,7 +743,7 @@ fn parse_messages(data: &[u8], folder: &str, full: bool, boxes: &Mailboxes) -> R } else if key.text().to_ascii_uppercase().starts_with(b"BODY[") { raw = Some(value.text()) } - i += 2; + field_index += 2; } let Some(uid) = uid else { continue }; let Some(raw) = raw else { continue }; @@ -748,8 +752,8 @@ fn parse_messages(data: &[u8], folder: &str, full: bool, boxes: &Mailboxes) -> R } Ok(result) } -async fn messages(p: &Value) -> Result { - let ids = p["ids"].as_array().ok_or("invalid_params")?; +async fn messages(params: &Value) -> Result { + let ids = params["ids"].as_array().ok_or("invalid_params")?; if ids.len() > 500 { return Err("invalid_params"); } @@ -758,7 +762,7 @@ async fn messages(p: &Value) -> Result { .map(|id| id.as_str().ok_or("invalid_params")) .collect::>>()?; let original_ids = ids.clone(); - let offset = if let Some(token) = p["continuation"].as_str() { + let offset = if let Some(token) = params["continuation"].as_str() { if token.len() > 65536 { return Err("invalid_params"); } @@ -768,9 +772,9 @@ async fn messages(p: &Value) -> Result { .map_err(|_| "invalid_params")?, ) .map_err(|_| "invalid_params")?; - if cursor["accountId"] != p["accountId"] - || cursor["requestToken"] != p["requestToken"] - || cursor["ids"] != p["ids"] + if cursor["accountId"] != params["accountId"] + || cursor["requestToken"] != params["requestToken"] + || cursor["ids"] != params["ids"] { return Err("invalid_params"); } @@ -781,7 +785,7 @@ async fn messages(p: &Value) -> Result { } else { 0 }; - let end = if p["progressive"] == true { + let end = if params["progressive"] == true { (offset + 10).min(ids.len()) } else { ids.len() @@ -792,11 +796,11 @@ async fn messages(p: &Value) -> Result { let (uid, folder) = message_id(id)?; groups.entry(folder).or_default().push(uid); } - let full = p["full"] == true; + let full = params["full"] == true; let futures = groups.into_iter().map(|(folder, uids)| async move { - let (mut w, key) = acquire(p).await?; - let boxes = mailboxes(&mut w, p).await?; - command(&mut w, &format!("SELECT {}", quote(&folder)?)).await?; + let (mut wire, key) = acquire(params).await?; + let boxes = mailboxes(&mut wire, params).await?; + command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; let set = uids .iter() .map(u32::to_string) @@ -808,11 +812,11 @@ async fn messages(p: &Value) -> Result { "HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID REPLY-TO LIST-UNSUBSCRIBE)" }; let data = command( - &mut w, + &mut wire, &format!("UID FETCH {set} (UID FLAGS INTERNALDATE RFC822.SIZE BODYSTRUCTURE BODY.PEEK[{section}])"), ) .await?; - release(w, key).await; + release(wire, key).await; tokio::task::spawn_blocking(move || parse_messages(&data, &folder, full, &boxes)) .await .map_err(|_| "worker_failed")? @@ -835,7 +839,7 @@ async fn messages(p: &Value) -> Result { } let ordered: Vec<_> = ids.iter().filter_map(|id| found.remove(*id)).collect(); let continuation = if end < original_ids.len() && error.is_none() { - Some(URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"accountId":p["accountId"],"requestToken":p["requestToken"],"ids":p["ids"],"offset":end})).map_err(|_|"invalid_params")?)) + Some(URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"accountId":params["accountId"],"requestToken":params["requestToken"],"ids":params["ids"],"offset":end})).map_err(|_|"invalid_params")?)) } else { None }; @@ -865,16 +869,16 @@ fn status(data: &[u8]) -> Result<(u64, u64)> { } Err("imap_invalid_response") } -pub(super) fn validate(method: &str, p: &Value) -> Result<()> { +pub(super) fn validate(method: &str, params: &Value) -> Result<()> { match method { "imap.list" | "imap.listContinue" => { - query(p["query"].as_str().unwrap_or(""))?; + query(params["query"].as_str().unwrap_or(""))?; } "imap.count" => { - quote(string(p, "labelId")?)?; + quote(string(params, "labelId")?)?; } "imap.messages" => { - let ids = p["ids"].as_array().ok_or("invalid_params")?; + let ids = params["ids"].as_array().ok_or("invalid_params")?; if ids.len() > 500 { return Err("invalid_params"); } @@ -883,22 +887,25 @@ pub(super) fn validate(method: &str, p: &Value) -> Result<()> { } } "imap.attachment" => { - message_id(string(p, "messageId")?)?; - string(p, "attachmentId")?; + message_id(string(params, "messageId")?)?; + string(params, "attachmentId")?; } _ => {} } Ok(()) } -pub(super) async fn call(method: &str, p: &Value) -> Result { +pub(super) async fn call(method: &str, params: &Value) -> Result { if matches!(method, "imap.list" | "imap.listContinue") - && p["query"].as_str().unwrap_or("").starts_with("search:") + && params["query"] + .as_str() + .unwrap_or("") + .starts_with("search:") { - return search::call(p).await; + return search::call(params).await; } if method == "imap.attachment" { - let mut request = p.clone(); - request["ids"] = json!([string(p, "messageId")?]); + let mut request = params.clone(); + request["ids"] = json!([string(params, "messageId")?]); request["full"] = json!(true); request["progressive"] = json!(false); let data = messages(&request).await?; @@ -913,32 +920,32 @@ pub(super) async fn call(method: &str, p: &Value) -> Result { payload["parts"] .as_array()? .iter() - .find_map(|p| part(p, id)) + .find_map(|child| part(child, id)) } return Ok( - json!({"data":part(&message["payload"],string(p,"attachmentId")?).ok_or("imap_attachment_missing")?}), + json!({"data":part(&message["payload"],string(params,"attachmentId")?).ok_or("imap_attachment_missing")?}), ); } if method == "imap.messages" { - return messages(p).await; + return messages(params).await; } // Refuse malformed query/folder input before any credential-bearing socket. if matches!(method, "imap.list" | "imap.listContinue") { - query(p["query"].as_str().unwrap_or(""))?; + query(params["query"].as_str().unwrap_or(""))?; } if method == "imap.count" { - quote(string(p, "labelId")?)?; + quote(string(params, "labelId")?)?; } - let (mut w, key) = acquire(p).await?; - let boxes = mailboxes(&mut w, p).await?; + let (mut wire, key) = acquire(params).await?; + let boxes = mailboxes(&mut wire, params).await?; let result = match method { "imap.folders" => folders_value(&boxes), - "imap.list" | "imap.listContinue" => list(&mut w, p, &boxes).await?, + "imap.list" | "imap.listContinue" => list(&mut wire, params, &boxes).await?, "imap.count" => { - let id = string(p, "labelId")?; + let id = string(params, "labelId")?; let folder = resolve(&boxes, id)?; let data = command( - &mut w, + &mut wire, &format!("STATUS {} (MESSAGES UNSEEN)", quote(&folder)?), ) .await?; @@ -953,7 +960,7 @@ pub(super) async fn call(method: &str, p: &Value) -> Result { { return Ok(result); } - release(w, key).await; + release(wire, key).await; Ok(result) } #[cfg(test)] diff --git a/src/providers/imap/read/search/page.rs b/src/providers/imap/read/search/page.rs index 71066d2ae..8eb3fb4ff 100644 --- a/src/providers/imap/read/search/page.rs +++ b/src/providers/imap/read/search/page.rs @@ -6,30 +6,30 @@ use super::*; impl Snapshot { pub(super) async fn verify_page( &mut self, - p: &Value, + params: &Value, cursor: Option<&Cursor>, limit: usize, ) -> Result { let offset = self.offset(cursor); let ordered = self.ordered.as_ref().ok_or("imap_invalid_response")?; let mut groups: BTreeMap> = BTreeMap::new(); - for &(f, m) in ordered.iter().skip(offset).take(limit) { - if !self.verified.contains(&(f, m)) { - groups.entry(f).or_default().push(m); + for &(folder_index, message_index) in ordered.iter().skip(offset).take(limit) { + if !self.verified.contains(&(folder_index, message_index)) { + groups.entry(folder_index).or_default().push(message_index); } } let gate = gate(self.owner).await; let mut work = FuturesUnordered::new(); - for (f, indices) in groups.into_iter().take(WORKERS) { - let folder = &self.folders[f]; + for (folder_index, indices) in groups.into_iter().take(WORKERS) { + let folder = &self.folders[folder_index]; let gate = gate.clone(); work.push(worker(gate, async move { let uids = indices .iter() - .map(|m| folder.messages[*m].uid.to_string()) + .map(|message_index| folder.messages[*message_index].uid.to_string()) .collect::>() .join(","); - let (mut wire, key) = acquire(p).await?; + let (mut wire, key) = acquire(params).await?; let selected = command(&mut wire, &format!("SELECT {}", quote(&folder.name)?)).await?; if Some(validity(&selected)?) != folder.validity { @@ -39,22 +39,27 @@ impl Snapshot { let present = fetched_dates(&data)?; release(wire, key).await; Ok(( - f, + folder_index, indices .into_iter() - .map(|m| (m, present.contains_key(&folder.messages[m].uid))) + .map(|message_index| { + ( + message_index, + present.contains_key(&folder.messages[message_index].uid), + ) + }) .collect::>(), )) })); } let mut missing = BTreeSet::new(); while let Some(result) = work.next().await { - let (f, results) = result?; - for (m, present) in results { + let (folder_index, results) = result?; + for (message_index, present) in results { if present { - self.verified.insert((f, m)); + self.verified.insert((folder_index, message_index)); } else { - missing.insert((f, m)); + missing.insert((folder_index, message_index)); } } } @@ -62,7 +67,7 @@ impl Snapshot { self.ordered .as_mut() .unwrap() - .retain(|i| !missing.contains(i)); + .retain(|location| !missing.contains(location)); // Deletion may bring more candidates into the page. Verify those on // the next continuation rather than returning a short or stale page. Ok(self @@ -72,6 +77,6 @@ impl Snapshot { .iter() .skip(self.offset(cursor)) .take(limit) - .all(|i| self.verified.contains(i))) + .all(|location| self.verified.contains(location))) } } diff --git a/src/providers/jmap/query.rs b/src/providers/jmap/query.rs index ccc5eb60c..451a86e98 100644 --- a/src/providers/jmap/query.rs +++ b/src/providers/jmap/query.rs @@ -1,20 +1,20 @@ use serde_json::{Map, Value, json}; pub(super) const ROLES: &[&str] = &["inbox", "archive", "sent", "drafts", "junk", "trash"]; -pub(super) fn string(v: &Value) -> &str { - v.as_str().unwrap_or("").trim() +pub(super) fn string(value: &Value) -> &str { + value.as_str().unwrap_or("").trim() } pub(super) fn roles(boxes: &[Value]) -> Value { let mut map = Map::new(); for role in ROLES { let exact = boxes .iter() - .find(|b| string(&b["role"]).eq_ignore_ascii_case(role)); + .find(|mailbox| string(&mailbox["role"]).eq_ignore_ascii_case(role)); let found = exact.or_else(|| { - boxes.iter().find(|b| { - if !string(&b["parentId"]).is_empty() { + boxes.iter().find(|mailbox| { + if !string(&mailbox["parentId"]).is_empty() { return false; } - let name = string(&b["name"]).to_lowercase(); + let name = string(&mailbox["name"]).to_lowercase(); match *role { "sent" => ["sent", "sent mail", "sent items", "sent messages"] .contains(&name.as_str()), @@ -40,7 +40,7 @@ pub(super) fn roles(boxes: &[Value]) -> Value { }); map.insert( (*role).into(), - json!(found.map(|b| string(&b["id"])).unwrap_or("")), + json!(found.map(|mailbox| string(&mailbox["id"])).unwrap_or("")), ); } Value::Object(map) @@ -60,8 +60,8 @@ pub(super) fn filter(query: &str, roles: &Value) -> Result if kind == "text" { let exclude: Vec<_> = ["junk", "trash"] .iter() - .map(|k| string(&roles[k])) - .filter(|s| !s.is_empty()) + .map(|role| string(&roles[role])) + .filter(|text| !text.is_empty()) .collect(); return Ok(if exclude.is_empty() { json!({"text":value}) @@ -95,7 +95,7 @@ pub(super) fn query( ) -> Value { let page = token .split_once('|') - .and_then(|(n, id)| n.parse::().ok().map(|n| (n, id))) + .and_then(|(position, id)| position.parse::().ok().map(|position| (position, id))) .unwrap_or((0, "")); let mut args = json!({"accountId":account,"filter":filter,"sort":[{"property":"receivedAt","isAscending":false}],"collapseThreads":true,"limit":limit,"calculateTotal":true}); if !page.1.is_empty() && !by_position { @@ -112,7 +112,7 @@ pub(super) fn page(args: &Value, limit: usize) -> Value { .into_iter() .flatten() .map(string) - .filter(|s| !s.is_empty()) + .filter(|text| !text.is_empty()) .collect(); let position = args["position"].as_u64().unwrap_or(0); let end = position.saturating_add(ids.len() as u64); @@ -130,40 +130,49 @@ pub(super) fn page(args: &Value, limit: usize) -> Value { pub(super) fn labels(boxes: &[Value]) -> Value { let roles = roles(boxes); let mut result = Vec::new(); - for b in boxes { - let id = string(&b["id"]); + for mailbox in boxes { + let id = string(&mailbox["id"]); if id.is_empty() { continue; } - let mut parts = vec![string(&b["name"])]; + let mut parts = vec![string(&mailbox["name"])]; let mut seen = vec![id]; - let mut current = b; + let mut current = mailbox; for _ in 0..32 { let parent = string(¤t["parentId"]); if parent.is_empty() || seen.contains(&parent) { break; } seen.push(parent); - let Some(found) = boxes.iter().find(|b| string(&b["id"]) == parent) else { + let Some(found) = boxes + .iter() + .find(|mailbox| string(&mailbox["id"]) == parent) + else { break; }; parts.insert(0, string(&found["name"])); current = found; } - let mut label = counts(b); + let mut label = counts(mailbox); label["name"] = json!(parts.join(" / ")); label["rawName"] = json!(id); label["system"] = json!(ROLES.iter().any(|role| string(&roles[role]) == id)); - result.push((b["sortOrder"].as_u64().unwrap_or(0), label)); + result.push((mailbox["sortOrder"].as_u64().unwrap_or(0), label)); } - result.sort_by(|a, b| { - a.0.cmp(&b.0) - .then_with(|| string(&a.1["name"]).cmp(string(&b.1["name"]))) + result.sort_by(|left, right| { + left.0 + .cmp(&right.0) + .then_with(|| string(&left.1["name"]).cmp(string(&right.1["name"]))) }); - json!(result.into_iter().map(|(_, v)| v).collect::>()) + json!( + result + .into_iter() + .map(|(_, label)| label) + .collect::>() + ) } -pub(super) fn counts(b: &Value) -> Value { - json!({"id":string(&b["id"]),"unread":b["unreadEmails"].as_u64().unwrap_or(0),"total":b["totalEmails"].as_u64().unwrap_or(0),"threadsUnread":b["unreadThreads"].as_u64().unwrap_or(0)}) +pub(super) fn counts(mailbox: &Value) -> Value { + json!({"id":string(&mailbox["id"]),"unread":mailbox["unreadEmails"].as_u64().unwrap_or(0),"total":mailbox["totalEmails"].as_u64().unwrap_or(0),"threadsUnread":mailbox["unreadThreads"].as_u64().unwrap_or(0)}) } #[cfg(test)] mod tests { From a4fc6e71f2322fc65f59bbeda3813493d301f510 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 033/568] Retain protocol comments for invariants and algorithms --- src/providers/imap/cancel.rs | 4 +-- src/providers/imap/idle.rs | 32 +++++++++---------- src/providers/imap/idle/tests.rs | 18 ++++------- src/providers/imap/mod.rs | 12 +++---- src/providers/imap/mutation.rs | 4 +-- src/providers/imap/mutation/tests.rs | 2 +- src/providers/imap/read.rs | 14 ++++---- src/providers/imap/read/search.rs | 20 ++++++------ src/providers/imap/read/search/cursor.rs | 4 +-- src/providers/imap/read/search/page.rs | 2 +- src/providers/imap/read/search/tests.rs | 6 ---- .../imap/read/search/tests/paging.rs | 6 +--- src/providers/imap/read/tests.rs | 10 +++--- src/providers/imap/starttls_test.py | 2 +- src/providers/imap/tests.rs | 10 +++--- src/providers/jmap/discovery.rs | 6 ++-- src/providers/jmap/discovery_tls_test.py | 2 +- src/providers/jmap/mailbox.rs | 6 ++-- src/providers/jmap/mailbox_tls_test.py | 4 +-- src/providers/jmap/mutation.rs | 6 ++-- src/providers/jmap/read.rs | 2 +- src/providers/jmap/resource.rs | 2 +- src/providers/jmap/resource_tests.rs | 2 +- src/providers/jmap/tests.rs | 2 +- 24 files changed, 81 insertions(+), 97 deletions(-) diff --git a/src/providers/imap/cancel.rs b/src/providers/imap/cancel.rs index edcd2b80c..07c4804ea 100644 --- a/src/providers/imap/cancel.rs +++ b/src/providers/imap/cancel.rs @@ -55,7 +55,7 @@ pub(super) async fn run( return future.await; }; let entry = entry(&key).await?; - // Notify is registered before reading the flag, closing cancel-before-poll races. + // Invariant: Notify is registered before reading the flag, closing cancel-before-poll races. let notified = entry.notify.notified(); tokio::pin!(notified); notified.as_mut().enable(); @@ -64,7 +64,7 @@ pub(super) async fn run( } let result = tokio::select! {result=future=>result,_=notified=>Err("request_cancelled")}; let mut reads = READS.get_or_init(Default::default).lock().await; - // Keep aborted entries briefly so an already queued continuation cannot revive a read. + // Invariant: Keep aborted entries briefly so an already queued continuation cannot revive a read. // Map + this reader are two references. Any additional reader (including // one that just registered) must retain this cancellation identity. if !entry.aborted.load(Ordering::SeqCst) && Arc::strong_count(&entry) == 2 { diff --git a/src/providers/imap/idle.rs b/src/providers/imap/idle.rs index 1f4d68a9f..48f243672 100644 --- a/src/providers/imap/idle.rs +++ b/src/providers/imap/idle.rs @@ -79,14 +79,14 @@ impl Backoff { /// which is what counts as having worked. fn after(&mut self, error: &str, refreshed: bool) -> Option { if error == "imap_idle_unsupported" { - // A server property; asking again would only log in to be told so. + // Invariant: A server property; asking again would only log in to be told so. return None; } if refreshed { self.next = self.timing.first_retry; } let delay = if error == "mail_auth_failed" || error.starts_with("auth_") { - // A refused login or a missing credential is unlikely to be + // Invariant: A refused login or a missing credential is unlikely to be // different in a few seconds, and each attempt costs the server a // LOGIN or Microsoft a token request. Polling reports the error. self.timing.last_retry @@ -119,7 +119,7 @@ where let mut refreshed = false; let error = match tokio::time::timeout(STEP, resolve()).await { Ok(Ok(params)) => { - // The watch checked when it started. Any later session may + // Invariant: The watch checked when it started. Any later session may // follow a gap in which a change raised nothing, so it asks for // a check of its own. let Err(error) = session(params, changed, !first, timing, &mut refreshed).await; @@ -161,19 +161,17 @@ async fn session( if advertises(&capabilities, "ID") { command(&mut wire, "ID (\"name\" \"Omamail\")").await?; } - // EXAMINE rather than SELECT: watching must not clear \Recent. + // Invariant: EXAMINE rather than SELECT: watching must not clear \Recent. command(&mut wire, "EXAMINE \"INBOX\"").await?; Ok(wire) }) .await?; - // Not kept for the life of the connection. drop(p); if announce { changed.notify_one(); } let mut lines = Lines::default(); - // When to wake the check for changes already seen but not yet reported. - let mut due: Option = None; + let mut change_due: Option = None; let mut resume_clock = tokio::time::interval(RESUME_CHECK); let mut last_wall = SystemTime::now(); loop { @@ -188,22 +186,22 @@ async fn session( return Err("imap_command_failed"); } if changes_inbox(&line)? { - due.get_or_insert(Instant::now() + timing.coalesce); + change_due.get_or_insert(Instant::now() + timing.coalesce); } } }) .await?; let refresh_at = Instant::now() + timing.refresh; loop { - let wake = due.map_or(refresh_at, |due| due.min(refresh_at)); - // Biased toward the timers, so a server that never stops sending + let wake = change_due.map_or(refresh_at, |change_due| change_due.min(refresh_at)); + // Invariant: Biased toward the timers, so a server that never stops sending // cannot hold off either the wake or the refresh. tokio::select! { biased; _ = tokio::time::sleep_until(wake) => { let now = Instant::now(); - if due.is_some_and(|due| due <= now) { - due = None; + if change_due.is_some_and(|change_due| change_due <= now) { + change_due = None; changed.notify_one(); } if refresh_at <= now { @@ -213,7 +211,7 @@ async fn session( _ = resume_clock.tick() => { let now = SystemTime::now(); if resumed(last_wall, now) { - // The connection almost certainly died while the + // Invariant: The connection almost certainly died while the // machine slept; a new session also asks for a check. return Err("mail_connection_closed"); } @@ -221,14 +219,14 @@ async fn session( } line = lines.next(&mut wire) => { let line = line?; - // A server ends IDLE only when told to. One that ends it + // Invariant: A server ends IDLE only when told to. One that ends it // unasked is treated as a failed connection, so it goes // through the backoff rather than straight back into IDLE. if tagged(&line).is_some() { return Err("mail_connection_closed"); } if changes_inbox(&line)? { - due.get_or_insert(Instant::now() + timing.coalesce); + change_due.get_or_insert(Instant::now() + timing.coalesce); } } } @@ -243,7 +241,7 @@ async fn session( None => {} } if changes_inbox(&line)? { - due.get_or_insert(Instant::now() + timing.coalesce); + change_due.get_or_insert(Instant::now() + timing.coalesce); } } }) @@ -310,7 +308,7 @@ struct Lines { impl Lines { async fn next(&mut self, w: &mut Wire) -> Result> { loop { - // `fill_buf` is cancel-safe, and nothing below awaits between + // Invariant: `fill_buf` is cancel-safe, and nothing below awaits between // reading bytes and recording them. let buf = w.fill_buf().await.map_err(|_| "mail_network_failed")?; if buf.is_empty() { diff --git a/src/providers/imap/idle/tests.rs b/src/providers/imap/idle/tests.rs index e1be33985..7b28f6d81 100644 --- a/src/providers/imap/idle/tests.rs +++ b/src/providers/imap/idle/tests.rs @@ -41,7 +41,7 @@ async fn open(listener: &TcpListener, capabilities: &[u8]) -> Wire { /// EXAMINE, then the client's IDLE, read but not yet answered. async fn examined(w: &mut Wire) { assert_eq!(line(w).await.unwrap(), b"O1 EXAMINE \"INBOX\"\r\n"); - // An EXISTS in the EXAMINE answer describes the mailbox, not a change. + // Invariant: An EXISTS in the EXAMINE answer describes the mailbox, not a change. send(w, b"* 4 EXISTS\r\nO1 OK [READ-ONLY] examined\r\n") .await .unwrap(); @@ -106,7 +106,6 @@ async fn a_burst_of_changes_wakes_the_check_once() { }); let client = spawn_session(port, &changed, FAST); woken(&changed).await; - // Several coalescing periods later, nothing further is waiting. tokio::time::sleep(FAST.coalesce * 4).await; assert!(!permit(&changed).await); client.abort(); @@ -125,7 +124,7 @@ async fn a_server_that_never_stops_sending_cannot_hold_off_the_wake_or_the_refre let burst = b"* 1 EXISTS\r\n".repeat(64); while write.write_all(&burst).await.is_ok() {} }); - // Anything the client sends while idling can only be DONE. + // Invariant: Anything the client sends while idling can only be DONE. let mut first = [0u8; 4]; read.read_exact(&mut first).await.unwrap(); assert_eq!(&first, b"DONE"); @@ -155,7 +154,7 @@ async fn idle_is_reissued_each_refresh_and_keepalives_wake_nothing() { let mut w = idling(&listener).await; send(&mut w, b"* OK Still here\r\n").await.unwrap(); for _ in 0..2 { - // Status atoms are case-insensitive. + // Invariant: Status atoms are case-insensitive. refreshed(&mut w, b"O1 ok idle done\r\n").await; send(&mut w, b"+ idling\r\n").await.unwrap(); } @@ -167,7 +166,7 @@ async fn idle_is_reissued_each_refresh_and_keepalives_wake_nothing() { &changed, Timing { refresh: Duration::from_millis(20), - // Shorter than a refresh, so a keepalive taken for a change would + // Invariant: Shorter than a refresh, so a keepalive taken for a change would // have woken the check before the first DONE. coalesce: Duration::from_millis(1), ..FAST @@ -194,7 +193,6 @@ async fn a_change_during_done_wakes_the_check_from_the_next_idle() { &changed, Timing { refresh: Duration::from_millis(20), - // Due well before the next refresh ends this IDLE too. coalesce: Duration::from_millis(1), ..FAST }, @@ -210,7 +208,7 @@ async fn a_server_ending_idle_unasked_fails_the_session_instead_of_looping() { let server = tokio::spawn(async move { let mut w = idling(&listener).await; send(&mut w, b"O1 OK idle ended\r\n").await.unwrap(); - // No second IDLE: the connection is closed instead. + // Invariant: No second IDLE: the connection is closed instead. assert!(line(&mut w).await.is_err()); }); let client = spawn_session(port, &Arc::new(Notify::new()), FAST); @@ -320,7 +318,7 @@ async fn a_server_without_idle_is_asked_once() { let (listener, port) = server().await; let server = tokio::spawn(async move { let mut w = open(&listener, b"IMAP4rev1").await; - // Nothing follows CAPABILITY: no EXAMINE, no IDLE, no second login. + // Invariant: Nothing follows CAPABILITY: no EXAMINE, no IDLE, no second login. assert!(line(&mut w).await.is_err()); assert!( tokio::time::timeout(Duration::from_millis(100), listener.accept()) @@ -345,7 +343,6 @@ async fn only_the_first_session_of_a_watch_skips_the_check() { let (end_first, first_ended) = oneshot::channel::<()>(); let server = tokio::spawn(async move { let mut first = open(&listener, b"IMAP4rev1 IDLE").await; - // The client has sent IDLE, so any announcement has already happened. examined(&mut first).await; first_idle.send(()).unwrap(); first_ended.await.unwrap(); @@ -424,7 +421,7 @@ fn backoff_doubles_to_its_ceiling_resets_after_a_refresh_and_stops_only_for_miss backoff.after("mail_connection_closed", true), Some(timing.first_retry) ); - // A session that never completed a refresh does not reset it. + // Invariant: A session that never completed a refresh does not reset it. assert_eq!( backoff.after("mail_connection_closed", false), Some(Duration::from_secs(10)) @@ -456,7 +453,6 @@ fn a_wall_clock_jump_past_two_checks_means_the_machine_slept() { last, last + RESUME_CHECK * 2 + Duration::from_secs(1) )); - // A clock set backwards is not a sleep. assert!(!resumed(last, last - Duration::from_secs(3600))); } diff --git a/src/providers/imap/mod.rs b/src/providers/imap/mod.rs index a5eca0e7b..2b05325f2 100644 --- a/src/providers/imap/mod.rs +++ b/src/providers/imap/mod.rs @@ -59,7 +59,7 @@ async fn acquire(params: &Value) -> Result<(Wire, String)> { } let mut wire = connect(¶ms["settings"], false).await?; login(&mut wire, params).await?; - // Capabilities are negotiated afresh after authentication/TLS, and ID is + // Invariant: Capabilities are negotiated afresh after authentication/TLS, and ID is // sent once on this connection before any mailbox can be selected. let capabilities = command(&mut wire, "CAPABILITY").await?; if advertises(&capabilities, "ID") { @@ -320,7 +320,7 @@ where .ok_or("invalid_params")? as u16; let loopback = matches!(host, "127.0.0.1" | "::1" | "localhost"); let allow_self_signed = loopback && settings["insecure"] == true; - // Bridge supports custom ports. Its clear greeting still requires STARTTLS; + // Invariant: Bridge supports custom ports. Its clear greeting still requires STARTTLS; // `insecure` relaxes certificate trust, never the encryption requirement. // Remote nonstandard ports retain the existing implicit-TLS convention. let transport = if (smtp && matches!(port, 25 | 587)) @@ -331,7 +331,7 @@ where } else { Transport::Tls }; - // Plain peers are only available in test builds, by explicit fixture opt-in. + // Invariant: Plain peers are only available in test builds, by explicit fixture opt-in. #[cfg(any(test, feature = "integration-test-credentials"))] let transport = if allow_self_signed && settings["testPlaintext"] == true { Transport::TestPlaintext @@ -647,7 +647,7 @@ async fn execute( ) { return mutation::call(method, params, sent).await; } - // Validate the entire batch and envelope before opening any socket. + // Invariant: Validate the entire batch and envelope before opening any socket. credentials(params)?; let folder = params["folder"].as_str().unwrap_or(""); let quoted = quote(folder)?; @@ -744,7 +744,7 @@ async fn execute( format!("O1 APPEND {quoted} ({flag}) {{{}}}\r\n", body.len()).as_bytes(), ) .await?; - // APPEND must be granted a continuation before any message bytes are sent. + // Invariant: APPEND must be granted a continuation before any message bytes are sent. let l = line(&mut wire).await?; if !l.starts_with(b"+") { return Err("imap_command_failed"); @@ -872,7 +872,7 @@ async fn send(params: &Value) -> Result { smtp_cmd(&mut wire, &format!("RCPT TO:<{recipient}>"), 250).await?; } smtp_cmd(&mut wire, "DATA", 354).await?; - // After DATA starts, a failed final reply cannot prove the message was not delivered. + // Invariant: After DATA starts, a failed final reply cannot prove the message was not delivered. write(&mut wire, &encoded) .await .map_err(|_| "smtp_delivery_unknown")?; diff --git a/src/providers/imap/mutation.rs b/src/providers/imap/mutation.rs index 2d6242aa2..0217fa755 100644 --- a/src/providers/imap/mutation.rs +++ b/src/providers/imap/mutation.rs @@ -285,7 +285,7 @@ pub(super) async fn call_planned( json!({"sent":true,"warning":if copy.is_ok(){""}else{"Sent, but the copy for the Sent folder could not be saved"}}), ); } - // Validate every mutation's identifiers and bytes before connecting. + // Invariant: Validate every mutation's identifiers and bytes before connecting. let folder_command = match method { "imap.createFolder" => Some(format!( "CREATE {}", @@ -372,7 +372,7 @@ pub(super) async fn call_planned( command(&mut wire, &format!("UID EXPUNGE {set}")).await?; } } - // Record only a fully acknowledged group. Keep the ledger + // Invariant: Record only a fully acknowledged group. Keep the ledger // outside this future so later errors and deadline cancellation // cannot discard earlier successes or invite their retry. if let Some(completed) = completed_folders.as_mut() { diff --git a/src/providers/imap/mutation/tests.rs b/src/providers/imap/mutation/tests.rs index bf688562b..ea3971d4b 100644 --- a/src/providers/imap/mutation/tests.rs +++ b/src/providers/imap/mutation/tests.rs @@ -138,7 +138,7 @@ async fn planned_group_failure(failure: &str, use_move: bool, flags_only: bool, ); }); let mut p = params(port); - // Preserve input order and spelling, not the BTreeMap's folder/UID order. + // Invariant: Preserve input order and spelling, not the BTreeMap's folder/UID order. p["ids"] = json!(["8:ZOther", "007:INBOX", "9:INBOX", "10:ZZLast"]); p["addLabelIds"] = json!([]); p["removeLabelIds"] = if flags_only { diff --git a/src/providers/imap/read.rs b/src/providers/imap/read.rs index d822ab1e7..2e77d311a 100644 --- a/src/providers/imap/read.rs +++ b/src/providers/imap/read.rs @@ -238,7 +238,7 @@ fn parse_folders(data: &[u8]) -> Result { special.insert("\\inbox".into(), folder.name.clone()); } } - // Fallbacks select only an existing LIST name, never invent a destination. + // Invariant: Fallbacks select only an existing LIST name, never invent a destination. for (flag, names) in [ ("\\sent", &["sent", "sent items", "sent messages"][..]), ("\\trash", &["trash", "deleted items", "deleted messages"]), @@ -450,7 +450,7 @@ fn fetched_dates(data: &[u8]) -> Result> { if let Some(date) = date { dates.insert(uid, date); } else { - // Unsolicited UID/FLAGS updates must not erase an arrival date. + // Invariant: Unsolicited UID/FLAGS updates must not erase an arrival date. dates.entry(uid).or_insert(0); } } @@ -528,10 +528,10 @@ async fn list(wire: &mut Wire, params: &Value, boxes: &Mailboxes) -> Result = fetched_dates(&command(wire, "UID FETCH 1:* (UID)").await?)? @@ -547,7 +547,7 @@ async fn list(wire: &mut Wire, params: &Value, boxes: &Mailboxes) -> Result Result Result { if method == "imap.messages" { return messages(params).await; } - // Refuse malformed query/folder input before any credential-bearing socket. + // Invariant: Refuse malformed query/folder input before any credential-bearing socket. if matches!(method, "imap.list" | "imap.listContinue") { query(params["query"].as_str().unwrap_or(""))?; } diff --git a/src/providers/imap/read/search.rs b/src/providers/imap/read/search.rs index ab16eb84e..b5a58bb42 100644 --- a/src/providers/imap/read/search.rs +++ b/src/providers/imap/read/search.rs @@ -14,7 +14,7 @@ const MAX_UIDS: usize = 1_000_000; const BATCH: usize = 4096; const MAX_SNAPSHOTS: usize = 16; const TTL: Duration = Duration::from_secs(300); -// A full body is read only to verify an All/Trash overlap. Larger candidates stay +// Invariant: A full body is read only to verify an All/Trash overlap. Larger candidates stay // visible rather than risk the 32 MiB response ceiling failing the whole search. const CONTENT_LIMIT: u64 = 8 * 1024 * 1024; const CONTENT_BATCH: usize = 64; @@ -117,7 +117,7 @@ fn owner(p: &Value) -> [u8; 32] { } fn authorization(p: &Value) -> [u8; 32] { - // A changed credential/transport must authenticate on the wire before it + // Invariant: A changed credential/transport must authenticate on the wire before it // can reuse results. This digest stays private, never inside a cursor. Sha256::digest(json!([p["settings"], p["credential"], p["oauth"]]).to_string()).into() } @@ -176,12 +176,12 @@ fn plan(boxes: &Mailboxes, p: &Value, criteria: String) -> Result { ] .iter() .any(|name| folder.name.eq_ignore_ascii_case(name)); - // Excluded folders are read only to subtract their membership from All. + // Invariant: Excluded folders are read only to subtract their membership from All. if excluded && !aggregate { continue; } let all = has_role(folder, boxes, "\\all"); - // \All presents every message in the store (RFC 6154). Without a server + // Invariant: \All presents every message in the store (RFC 6154). Without a server // identity, physical folders would only add unverifiable duplicates of it. if identity == Identity::Candidate && !all && !excluded { continue; @@ -262,7 +262,7 @@ async fn step( return Err("imap_search_expired"); } if folder.validity.is_none() { - // SEARCH returns all matches on one line, whose transport limit is + // Invariant: SEARCH returns all matches on one line, whose transport limit is // 64 KiB. Inventory UIDs through separate FETCH responses instead, // then SEARCH only bounded windows of these existing UIDs. Capturing // UIDNEXT excludes later arrivals and avoids walking sparse UID gaps. @@ -276,7 +276,7 @@ async fn step( folder.validity = Some(current); } else if folder.fetched < folder.pending.len() { let end = if identity == Identity::Content { - // Candidates were chosen at or under CONTENT_LIMIT, so one always fits. + // Invariant: Candidates were chosen at or under CONTENT_LIMIT, so one always fits. let mut end = folder.fetched; let mut bytes = 0; while end < folder.pending.len() && end - folder.fetched < CONTENT_BATCH { @@ -378,7 +378,7 @@ async fn inventory(wire: &mut Wire, ceiling: u32) -> Result> { impl Snapshot { fn refine(&mut self) { - // Message-ID and size nominate candidates; they NEVER suppress a result. + // Invariant: Message-ID and size nominate candidates; they NEVER suppress a result. // Only compare bodies for candidates shared by All and Trash/Junk. let excluded: BTreeSet<_> = self .folders @@ -419,14 +419,14 @@ impl Snapshot { let mut ordered = Vec::new(); for (f, folder) in self.folders.iter().enumerate().filter(|(_, f)| !f.excluded) { for (m, msg) in folder.messages.iter().enumerate() { - // Only aggregate destinations need subtraction. A real copy in + // Invariant: Only aggregate destinations need subtraction. A real copy in // Inbox remains a valid result even if a copy is in Trash. if !folder.aggregate || !msg.identity.is_some_and(|id| excluded.contains(&id)) { ordered.push((f, m)); } } } - // A rescan may receive LIST in a different order. Choose the same + // Invariant: A rescan may receive LIST in a different order. Choose the same // representative for a server-issued identity independently of that. ordered.sort_by(|(af, am), (bf, bm)| { let a = &self.folders[*af]; @@ -703,7 +703,7 @@ fn fetched(data: &[u8], window: &[u32], identity: Identity) -> Result (Reverse, &str, Reverse) { (Reverse(date), folder, Reverse(uid)) @@ -81,7 +81,7 @@ impl Cursor { } fn binding(owner: [u8; 32], criteria: &str) -> [u8; 32] { - // Version also fixes scope and ordering semantics. No credential digest is + // Invariant: Version also fixes scope and ordering semantics. No credential digest is // exported in a cursor, and an OAuth refresh does not change its binding. Sha256::digest(json!(["imap-account-search-v1", owner, criteria]).to_string()).into() } diff --git a/src/providers/imap/read/search/page.rs b/src/providers/imap/read/search/page.rs index 8eb3fb4ff..4a4d38e67 100644 --- a/src/providers/imap/read/search/page.rs +++ b/src/providers/imap/read/search/page.rs @@ -68,7 +68,7 @@ impl Snapshot { .as_mut() .unwrap() .retain(|location| !missing.contains(location)); - // Deletion may bring more candidates into the page. Verify those on + // Invariant: Deletion may bring more candidates into the page. Verify those on // the next continuation rather than returning a short or stale page. Ok(self .ordered diff --git a/src/providers/imap/read/search/tests.rs b/src/providers/imap/read/search/tests.rs index 6160835c4..7ddfc67e5 100644 --- a/src/providers/imap/read/search/tests.rs +++ b/src/providers/imap/read/search/tests.rs @@ -176,7 +176,6 @@ fn metadata(uid: u32, day: u8, body: &str) -> Vec { format!("* 1 FETCH (UID {uid} INTERNALDATE \"{day:02}-Sep-2026 12:00:00 +0000\" BODY[] {{{}}}\r\n{body})\r\n", body.len()).into_bytes() } -// Generic \All server with no server-issued identity: (folder, uid, day, raw message). const GENERIC: [(&str, u32, u8, &str); 10] = [ ( "INBOX", @@ -336,9 +335,6 @@ async fn generic_all_server_lists_each_message_once_and_verifies_exclusions() { p["continuation"] = result["continuation"].clone(); method = "imap.listContinue"; }; - // Inbox and Archive copies are not repeated from their folders; the - // aggregate-only message survives; a verified Trash/Junk copy does not; - // a message that only shares Message-ID and size with Trash survives. assert_eq!( result["page"]["ids"], json!([ @@ -438,7 +434,6 @@ fn matching_headers_only_nominate_candidates_and_different_bodies_survive() { .messages .extend(fetched(data.as_bytes(), &[uid], Identity::Candidate).unwrap()); } - // An aggregate-only message with no matching Trash header needs no body read. let data = b"* 1 FETCH (UID 3 INTERNALDATE \"24-Sep-2026 12:00:00 +0000\" RFC822.SIZE 100 BODY[HEADER] {3}\r\nnew)\r\n"; scan.folders[0] .messages @@ -451,7 +446,6 @@ fn matching_headers_only_nominate_candidates_and_different_bodies_survive() { .iter() .all(|f| f.messages.iter().all(|m| m.identity.is_none())) ); - // Same Message-ID, same full headers and same size, but unrelated content. for (folder, uid, body) in [ (0, 1, "legitimate"), (0, 2, "junk mail!"), diff --git a/src/providers/imap/read/search/tests/paging.rs b/src/providers/imap/read/search/tests/paging.rs index f286d6c6f..5abc25f91 100644 --- a/src/providers/imap/read/search/tests/paging.rs +++ b/src/providers/imap/read/search/tests/paging.rs @@ -7,7 +7,6 @@ struct State { inventories: usize, searches: usize, largest_search: usize, - // Expunged between SEARCH and the metadata FETCH. missing: Vec, } @@ -202,8 +201,6 @@ async fn cache_loss_and_deletions_resume_from_a_position_not_an_existing_message let rescanned = complete(&p).await.unwrap(); assert_eq!(rescanned["ids"], cached["ids"]); assert_eq!(server.state.lock().unwrap().inventories, 2); - // Delete a prior row, the cursor's row, and an upcoming row. Add a new row - // before the cursor. A metadata-time expunge must be skipped as well. server .state .lock() @@ -211,7 +208,6 @@ async fn cache_loss_and_deletions_resume_from_a_position_not_an_existing_message .folders .insert("INBOX".into(), vec![(4, 25), (5, 24), (6, 23), (7, 29)]); server.state.lock().unwrap().missing = vec![4]; - // Evict the new snapshot too; the original hint is already unavailable. let page = complete(&p).await.unwrap(); assert_eq!(page["ids"], json!(["5:INBOX", "6:INBOX"])); assert_eq!(page["nextPageToken"], ""); @@ -257,7 +253,7 @@ async fn page_assembly_continues_across_more_than_four_folders_and_binds_its_cur p["limit"] = json!(1); let first = complete(&p).await.unwrap(); p["limit"] = json!(5); - // Force fallback with a page cursor, then keep that cursor on every work + // Invariant: Force fallback with a page cursor, then keep that cursor on every work // continuation. The QML client and CLI adapter both use this exact shape. p["pageToken"] = first["nextPageToken"].clone(); evict(&p).await; diff --git a/src/providers/imap/read/tests.rs b/src/providers/imap/read/tests.rs index 4ee086f47..24b3f37c4 100644 --- a/src/providers/imap/read/tests.rs +++ b/src/providers/imap/read/tests.rs @@ -153,7 +153,7 @@ async fn multi_window_dates_settle_before_paging_and_ignore_unsolicited_flags() batches.push(ids.len()); } for uid in ids { - // Date order deliberately crosses the 4096-message boundary. + // Invariant: Date order deliberately crosses the 4096-message boundary. let day = match uid { 1 => 24, 4097 => 23, @@ -166,7 +166,7 @@ async fn multi_window_dates_settle_before_paging_and_ignore_unsolicited_flags() format!("* {uid} FETCH (UID {uid})\r\n") }); } - // Both within and outside the current batch: neither may erase + // Invariant: Both within and outside the current batch: neither may erase // UID 1's date or add a post-snapshot arrival to the page. if dated { response.push_str( @@ -197,7 +197,7 @@ async fn multi_window_dates_settle_before_paging_and_ignore_unsolicited_flags() }); let mut p = params(port); p["limit"] = json!(2); - // Also usable as a runtime regression on the old UID-only implementation: + // Invariant: Also usable as a runtime regression on the old UID-only implementation: // it understands the same snapshot/search commands but chooses the wrong page. p["progressive"] = json!(false); let first = super::super::call("imap.list", &p).await.unwrap(); @@ -279,7 +279,7 @@ async fn a_slow_server_that_answers_every_command_still_pages() { loop { let request = String::from_utf8(line(&mut w).await.unwrap()).unwrap(); replies += 1; - // Well inside one command's budget, and well outside the call's + // Invariant: Well inside one command's budget, and well outside the call's // old one once the conversation has run its length. tokio::time::sleep(SLOW).await; let mut response = String::new(); @@ -311,7 +311,7 @@ async fn a_slow_server_that_answers_every_command_still_pages() { }); } response.push_str("O1 OK fetched\r\n"); - // The snapshot, then one date window per 4 096 UIDs. + // Invariant: The snapshot, then one date window per 4 096 UIDs. dated && ids.last() == Some(&9000) } else { panic!("unexpected command: {request}"); diff --git a/src/providers/imap/starttls_test.py b/src/providers/imap/starttls_test.py index 7c6d45c7f..10b44a0ad 100644 --- a/src/providers/imap/starttls_test.py +++ b/src/providers/imap/starttls_test.py @@ -49,7 +49,7 @@ def greeting(connection): reply = b"220 upgrade\r\n" if smtp else b"O1 OK upgrade\r\n" if mode == "buffered": connection.sendall(reply + b"plaintext-after-upgrade\r\n") - # A reset also discards the injected plaintext. Neither path + # Invariant: A reset also discards the injected plaintext. Neither path # may contain credential bytes (a ClientHello is harmless). received = bytearray() try: diff --git a/src/providers/imap/tests.rs b/src/providers/imap/tests.rs index aeca20a51..112874ebd 100644 --- a/src/providers/imap/tests.rs +++ b/src/providers/imap/tests.rs @@ -70,7 +70,7 @@ async fn bridge_starttls_encrypts_credentials_and_never_downgrades() { settings["imapHost"] = json!(host); settings["imapPort"] = json!(logical_port); } - // Only the socket destination is substituted. All host/port/trust + // Invariant: Only the socket destination is substituted. All host/port/trust // decisions go through the production connection selection path. let result = connect_with_dial(&settings, smtp, |dial_host, dial_port| async move { assert_eq!( @@ -87,7 +87,7 @@ async fn bridge_starttls_encrypts_credentials_and_never_downgrades() { .map_err(|_| "mail_network_failed") }) .await; - // Keep the TLS socket alive until the peer has read and reported + // Invariant: Keep the TLS socket alive until the peer has read and reported // the credentials. Closing it here can abort the peer's handshake // on Windows while TLS 1.3 session tickets are still in flight. let mut secure = None; @@ -292,7 +292,7 @@ async fn smtp_native_submission_dot_stuffs_and_never_retries() { assert_eq!(line(&mut w).await.unwrap(), b"\r\n"); assert_eq!(line(&mut w).await.unwrap(), b"..body\r\n"); assert_eq!(line(&mut w).await.unwrap(), b".\r\n"); - // The server accepted DATA but disconnected without an acknowledgement. + // Invariant: The server accepted DATA but disconnected without an acknowledgement. drop(w); assert!( tokio::time::timeout(Duration::from_millis(30), listener.accept()) @@ -434,12 +434,12 @@ async fn actual_tls_rejects_untrusted_issuer_and_wrong_hostname() { output.read_line(&mut report).unwrap(); assert_eq!(report.trim(), "tls-refused-no-http"); } - // A private authority the store was built from — the system's, in + // Invariant: A private authority the store was built from — the system's, in // production — is honoured for the host it issued for (#185). let socket = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); let w: Wire = BufReader::new(Box::new(socket)); let mut secure = tls_with_roots(w, "localhost", trusted).await.unwrap(); - // close_notify, so the peer reads a clean end rather than a reset. + // Invariant: close_notify, so the peer reads a clean end rather than a reset. secure.shutdown().await.unwrap(); let mut report = String::new(); output.read_line(&mut report).unwrap(); diff --git a/src/providers/jmap/discovery.rs b/src/providers/jmap/discovery.rs index 99453552f..59d4ef8ff 100644 --- a/src/providers/jmap/discovery.rs +++ b/src/providers/jmap/discovery.rs @@ -20,7 +20,7 @@ fn session_policy( let mut origins = vec![origin(&url(root)?)]; for key in ["apiUrl", "downloadUrl", "uploadUrl", "eventSourceUrl"] { if let Some(endpoint) = document[key].as_str().filter(|v| !v.is_empty()) { - // Placeholders are only legal in the resource path/query, never in + // Invariant: Placeholders are only legal in the resource path/query, never in // the server authority that authorizes a credential destination. let endpoint = url(endpoint)?; if endpoint @@ -144,7 +144,7 @@ impl Session { .unwrap_or(address); let (mut endpoint, typed) = discovery_url(address, settings["sessionUrl"].as_str().unwrap_or(""))?; - // Refuse malformed credentials before even the unauthenticated probe. + // Invariant: Refuse malformed credentials before even the unauthenticated probe. prepare( &json!({"verb":"session","url":endpoint,"credential":{"scheme":"basic","username":username,"secret":secret}}), )?; @@ -248,7 +248,7 @@ impl Session { request: &Request, ) -> Result<(), &'static str> { if request.authorization.is_none() { - // Unauthenticated discovery is owned by verify(), not the public + // Invariant: Unauthenticated discovery is owned by verify(), not the public // arbitrary request API. It cannot become a sender-controlled fetch. return Err("jmap_destination_refused"); } diff --git a/src/providers/jmap/discovery_tls_test.py b/src/providers/jmap/discovery_tls_test.py index b3a0e9de8..cedae0823 100644 --- a/src/providers/jmap/discovery_tls_test.py +++ b/src/providers/jmap/discovery_tls_test.py @@ -29,7 +29,7 @@ def do_GET(self): threading.Thread(target=self.server.shutdown, daemon=True).start() -# HTTPServer.server_bind resolves the bound address to a name: a reverse lookup +# Performance: HTTPServer.server_bind resolves the bound address to a name: a reverse lookup # that a CI host's resolver leaves to time out, ten seconds a start. The peer # has no use for a name. class LoopbackServer(http.server.HTTPServer): diff --git a/src/providers/jmap/mailbox.rs b/src/providers/jmap/mailbox.rs index 51aff4f94..39b763a7c 100644 --- a/src/providers/jmap/mailbox.rs +++ b/src/providers/jmap/mailbox.rs @@ -70,7 +70,7 @@ pub(super) struct Context { pub(super) memberships: Mutex, pub(super) known: Mutex>, } -// Each cache has a retained-memory allowance, independent of entry count. +// Performance: Each cache has a retained-memory allowance, independent of entry count. // A conservative JSON-size multiplier covers Value/String allocation overhead. const CACHE_BYTES: usize = 8 * 1024 * 1024; #[derive(Default)] @@ -246,7 +246,7 @@ impl Session { if by_id.len() != requested.len() { return Err("mail_action_target_unknown"); } - // A message-scoped action needs only the validated representatives. + // Invariant: A message-scoped action needs only the validated representatives. // Unrelated conversation size and membership cannot prevent starring. if crate::account::model::action_scope(action) == "message" { return Ok(requested.iter().map(|id| json!({"id":id})).collect()); @@ -332,7 +332,7 @@ impl Session { if member_by_id.len() != all_member_ids.len() { return Err("mail_action_target_unknown"); } - // A response has one row per requested representative, so a server can + // Performance: A response has one row per requested representative, so a server can // otherwise make 1,000 representatives of one 2,000-member thread // retain two million copied IDs. Share the expansion per thread/view // and reject the aggregate projection before any row is built. diff --git a/src/providers/jmap/mailbox_tls_test.py b/src/providers/jmap/mailbox_tls_test.py index 98c30c66c..a18e632dd 100644 --- a/src/providers/jmap/mailbox_tls_test.py +++ b/src/providers/jmap/mailbox_tls_test.py @@ -11,7 +11,7 @@ scenario = sys.argv[1] if len(sys.argv) > 1 else "default" -# HTTPServer.server_bind resolves the bound address to a name: a reverse lookup +# Performance: HTTPServer.server_bind resolves the bound address to a name: a reverse lookup # that a CI host's resolver leaves to time out, ten seconds a start. The peer # has no use for a name. class LoopbackServer(http.server.HTTPServer): @@ -57,7 +57,7 @@ def answer(self,payload,status=200): self.send_response(status);self.send_header("Content-Length",str(len(payload)));self.end_headers();self.wfile.write(payload) def do_GET(self): if self.path=="/report": - # Omit only this final harness read from the returned snapshot. + # Invariant: Omit only this final harness read from the returned snapshot. self.answer(requests[:-1]);threading.Thread(target=self.server.shutdown,daemon=True).start();return if self.path=="/events": payload=b'event: state\r\ndata: {"changed":{"account":{"Email":"e2","Mailbox":"m2"}}}\r\n\r\n' diff --git a/src/providers/jmap/mutation.rs b/src/providers/jmap/mutation.rs index 2ec56e17e..8c4300160 100644 --- a/src/providers/jmap/mutation.rs +++ b/src/providers/jmap/mutation.rs @@ -143,7 +143,7 @@ impl Session { if has(&added, "SPAM") && !learns_junk(&snapshot) { return Err("jmap_spam_unavailable"); } - // All patches are validated before the first network mutation. + // Invariant: All patches are validated before the first network mutation. let change = patch(&added, &removed, roles, None)?; if change.as_object().is_none_or(|change| change.is_empty()) { return Err("invalid_params"); @@ -194,7 +194,7 @@ impl Session { .await; match result { Ok(ids) => succeeded.extend(ids), - // Unknown delivery: retain earlier acknowledgements, stop, and + // Invariant: Unknown delivery: retain earlier acknowledgements, stop, and // report this chunk and every unsent target as failed. Err(_) => break, } @@ -432,7 +432,7 @@ impl Session { snapshot: &Snapshot, id: &str, ) -> Result<(), &'static str> { - // Cleanup survives cancellation of the composer request. Dropping a + // Invariant: Cleanup survives cancellation of the composer request. Dropping a // JoinHandle detaches its owned task; no UI/request borrow outlives it. let body = json!({"using":[mailbox::CORE,mailbox::MAIL],"methodCalls":[["Email/set",{"accountId":snapshot.account,"destroy":[id]},"0"]]}); let request = prepare( diff --git a/src/providers/jmap/read.rs b/src/providers/jmap/read.rs index a810cd2a8..84c4e51f3 100644 --- a/src/providers/jmap/read.rs +++ b/src/providers/jmap/read.rs @@ -216,7 +216,7 @@ impl Session { message["thread"] = block.clone(); } let parts = super::resource::truncated_parts(email); - // A message can advertise arbitrarily many truncated text parts. Repair + // Performance: A message can advertise arbitrarily many truncated text parts. Repair // incrementally under one byte budget rather than retaining every blob. // Failed/oversized repairs retain the text already delivered, matching // the prior reader's best-effort behavior. diff --git a/src/providers/jmap/resource.rs b/src/providers/jmap/resource.rs index f91437079..61946e5a2 100644 --- a/src/providers/jmap/resource.rs +++ b/src/providers/jmap/resource.rs @@ -288,7 +288,7 @@ pub(super) fn validate_budget(email: &Value, full: bool) -> Result<(), &'static .get(..5) .is_some_and(|prefix| prefix.eq_ignore_ascii_case("text/")) { - // Match to_part coercion exactly, including malformed numeric IDs. + // Invariant: Match to_part coercion exactly, including malformed numeric IDs. let id = trim(&part["partId"]); if !id.is_empty() && let Some(body) = values diff --git a/src/providers/jmap/resource_tests.rs b/src/providers/jmap/resource_tests.rs index 0cf49140e..78b0b4800 100644 --- a/src/providers/jmap/resource_tests.rs +++ b/src/providers/jmap/resource_tests.rs @@ -156,7 +156,7 @@ fn refuses_duplicate_body_value_amplification_before_building_mime() { let leaves = vec![json!({"partId":"same","type":"text/plain"}); 512]; let email = json!({"bodyStructure":{"type":"multipart/mixed","subParts":leaves},"bodyValues":{"same":{"value":"x".repeat(65536)}}}); assert!(serde_json::to_vec(&email).unwrap().len() < 100_000); - // Were construction allowed, the same small source would emit over44MiB + // Invariant: Were construction allowed, the same small source would emit over44MiB // of base64 strings. Reject from sizes alone before encoding any of them. assert_eq!( validate_budget(&email, true), diff --git a/src/providers/jmap/tests.rs b/src/providers/jmap/tests.rs index 89f7315fc..fcc02ced5 100644 --- a/src/providers/jmap/tests.rs +++ b/src/providers/jmap/tests.rs @@ -224,7 +224,7 @@ async fn cancelling_a_pending_native_request_closes_the_socket_without_retrying( let (mut socket, _) = listener.accept().await.unwrap(); let mut buffer = [0; 4096]; assert!(socket.read(&mut buffer).await.unwrap() > 0); - // The server never supplies a response. Dropping the request future + // Invariant: The server never supplies a response. Dropping the request future // must release the connection instead of leaving a blocked curl child. assert_eq!( tokio::time::timeout(Duration::from_secs(1), socket.read(&mut buffer)) From bcda8b994585df499a08ab2c8a9853e565e9344e Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 034/568] Flatten provider read and discovery control flow --- src/providers/imap/mutation.rs | 175 ++++++++++++++++++--------------- 1 file changed, 94 insertions(+), 81 deletions(-) diff --git a/src/providers/imap/mutation.rs b/src/providers/imap/mutation.rs index 0217fa755..002cd26e2 100644 --- a/src/providers/imap/mutation.rs +++ b/src/providers/imap/mutation.rs @@ -189,6 +189,72 @@ fn without_bcc(body: &[u8]) -> Vec { } out } +async fn move_messages(wire: &mut Wire, uids: &str, target: &str, boxes: &Mailboxes) -> Result<()> { + if boxes + .capabilities + .iter() + .any(|value| value.eq_ignore_ascii_case("MOVE")) + { + command(wire, &format!("UID MOVE {uids} {}", quote(target)?)).await?; + return Ok(()); + } + command(wire, &format!("UID COPY {uids} {}", quote(target)?)).await?; + command(wire, &format!("UID STORE {uids} +FLAGS.SILENT (\\Deleted)")).await?; + command(wire, &format!("UID EXPUNGE {uids}")).await?; + Ok(()) +} +async fn apply_group( + wire: &mut Wire, + folder: &str, + uids: &[u32], + boxes: &Mailboxes, + changes: &(Vec, Vec, Option), +) -> Result<()> { + let (add, remove, destination) = changes; + command(wire, &format!("SELECT {}", quote(folder)?)).await?; + let set = uids + .iter() + .map(u32::to_string) + .collect::>() + .join(","); + for (mode, flags) in [("+", add), ("-", remove)] { + if flags.is_empty() { + continue; + } + command( + wire, + &format!("UID STORE {set} {mode}FLAGS.SILENT ({})", flags.join(" ")), + ) + .await?; + } + if let Some(target) = destination + && target != folder + { + move_messages(wire, &set, target, boxes).await?; + } + Ok(()) +} +async fn cleanup_previous_draft(wire: &mut Wire, params: &Value, folder: &str) -> &'static str { + let Some(id) = params["draftId"].as_str().filter(|id| !id.is_empty()) else { + return ""; + }; + let Ok((uid, previous_folder)) = message_id(id) else { + return "The updated draft was saved, but the old copy could not be identified"; + }; + if previous_folder != folder { + return "The updated draft was saved, but the old copy could not be identified"; + } + let cleanup = async { + command(wire, &format!("SELECT {}", quote(folder)?)).await?; + delete_uid(wire, uid).await + } + .await; + if cleanup.is_ok() { + "" + } else { + "The updated draft was saved, but the old copy could not be removed" + } +} pub(super) fn validate(method: &str, params: &Value) -> Result<()> { match method { "imap.createFolder" => { @@ -326,91 +392,38 @@ pub(super) async fn call_planned( None }; let (mut wire, key) = acquire(params).await?; - let result = if let Some(command_text) = folder_command { + if let Some(command_text) = folder_command { command(&mut wire, &command_text).await?; read::invalidate().await; - json!({}) - } else { - let boxes = match planned { - Some(boxes) => boxes.clone(), - None => mailboxes(&mut wire, params).await?, - }; - if let Some(groups) = groups { - let (add, remove, destination) = plan(method, params, &boxes)?; - for (folder, uids) in groups { - command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; - let set = uids - .iter() - .map(u32::to_string) - .collect::>() - .join(","); - for (mode, flags) in [("+", &add), ("-", &remove)] { - if !flags.is_empty() { - command( - &mut wire, - &format!("UID STORE {set} {mode}FLAGS.SILENT ({})", flags.join(" ")), - ) - .await?; - } - } - if let Some(target) = &destination - && target != &folder - { - if boxes - .capabilities - .iter() - .any(|v| v.eq_ignore_ascii_case("MOVE")) - { - command(&mut wire, &format!("UID MOVE {set} {}", quote(target)?)).await?; - } else { - command(&mut wire, &format!("UID COPY {set} {}", quote(target)?)).await?; - command( - &mut wire, - &format!("UID STORE {set} +FLAGS.SILENT (\\Deleted)"), - ) - .await?; - command(&mut wire, &format!("UID EXPUNGE {set}")).await?; - } - } - // Invariant: Record only a fully acknowledged group. Keep the ledger - // outside this future so later errors and deadline cancellation - // cannot discard earlier successes or invite their retry. - if let Some(completed) = completed_folders.as_mut() { - completed.push(folder); - } + release(wire, key).await; + return Ok(json!({})); + } + let boxes = match planned { + Some(boxes) => boxes.clone(), + None => mailboxes(&mut wire, params).await?, + }; + let result = if let Some(groups) = groups { + let changes = plan(method, params, &boxes)?; + for (folder, uids) in groups { + apply_group(&mut wire, &folder, &uids, &boxes, &changes).await?; + // Invariant: only acknowledged groups enter the external ledger; + // later errors and cancellation must not invite retrying successes. + if let Some(completed) = completed_folders.as_mut() { + completed.push(folder); } - json!({}) - } else if let Some(body) = draft { - let folder = resolve(&boxes, "\\Drafts")?; - append(&mut wire, &folder, &body, "\\Draft").await?; - let warning = if let Some(id) = params["draftId"].as_str().filter(|id| !id.is_empty()) { - if let Ok((uid, previous_folder)) = message_id(id) - && previous_folder == folder - { - let cleanup = async { - command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; - delete_uid(&mut wire, uid).await - } - .await; - if cleanup.is_ok() { - "" - } else { - "The updated draft was saved, but the old copy could not be removed" - } - } else { - "The updated draft was saved, but the old copy could not be identified" - } - } else { - "" - }; - json!({"saved":true,"warning":warning}) - } else if let Some((uid, folder)) = deleting { - command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; - delete_uid(&mut wire, uid).await?; - json!({}) - } else { - return Err("method_not_found"); } + json!({}) + } else if let Some(body) = draft { + let folder = resolve(&boxes, "\\Drafts")?; + append(&mut wire, &folder, &body, "\\Draft").await?; + let warning = cleanup_previous_draft(&mut wire, params, &folder).await; + json!({"saved":true,"warning":warning}) + } else if let Some((uid, folder)) = deleting { + command(&mut wire, &format!("SELECT {}", quote(&folder)?)).await?; + delete_uid(&mut wire, uid).await?; + json!({}) + } else { + return Err("method_not_found"); }; release(wire, key).await; Ok(result) From 397985fab4b219643e85a1c844e081b674db448d Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 035/568] Model provider search and cache records explicitly --- src/providers/imap/mutation.rs | 36 ++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/providers/imap/mutation.rs b/src/providers/imap/mutation.rs index 002cd26e2..946a42afc 100644 --- a/src/providers/imap/mutation.rs +++ b/src/providers/imap/mutation.rs @@ -27,16 +27,25 @@ fn strings(params: &Value, key: &str) -> Result> { }) .collect() } -fn plan( - method: &str, - params: &Value, - boxes: &Mailboxes, -) -> Result<(Vec, Vec, Option)> { +#[derive(Default)] +struct Changes { + add_flags: Vec, + remove_flags: Vec, + destination: Option, +} +fn plan(method: &str, params: &Value, boxes: &Mailboxes) -> Result { if method == "imap.trash" { - return Ok((vec![], vec![], Some(resolve(boxes, "\\Trash")?))); + return Ok(Changes { + destination: Some(resolve(boxes, "\\Trash")?), + ..Changes::default() + }); } if method == "imap.untrash" { - return Ok((vec![], vec!["\\Deleted".into()], Some("INBOX".into()))); + return Ok(Changes { + remove_flags: vec!["\\Deleted".into()], + destination: Some("INBOX".into()), + ..Changes::default() + }); } let added = strings(params, "addLabelIds")?; let removed = strings(params, "removeLabelIds")?; @@ -76,7 +85,11 @@ fn plan( } } } - Ok((add, remove, destination)) + Ok(Changes { + add_flags: add, + remove_flags: remove, + destination, + }) } fn encoded_mailbox(name: &str) -> Result { if name.trim().is_empty() || name.len() > 4096 || !safe(name) { @@ -208,16 +221,15 @@ async fn apply_group( folder: &str, uids: &[u32], boxes: &Mailboxes, - changes: &(Vec, Vec, Option), + changes: &Changes, ) -> Result<()> { - let (add, remove, destination) = changes; command(wire, &format!("SELECT {}", quote(folder)?)).await?; let set = uids .iter() .map(u32::to_string) .collect::>() .join(","); - for (mode, flags) in [("+", add), ("-", remove)] { + for (mode, flags) in [("+", &changes.add_flags), ("-", &changes.remove_flags)] { if flags.is_empty() { continue; } @@ -227,7 +239,7 @@ async fn apply_group( ) .await?; } - if let Some(target) = destination + if let Some(target) = &changes.destination && target != folder { move_messages(wire, &set, target, boxes).await?; From eb714abe4eaef381749607e86e7fe0bae4aee496 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 036/568] Remove redundant provider syntax and helpers --- src/providers/imap/mod.rs | 3 +- src/providers/jmap/mailbox_tls_test.py | 211 ++++++++++++------------- 2 files changed, 106 insertions(+), 108 deletions(-) diff --git a/src/providers/imap/mod.rs b/src/providers/imap/mod.rs index 2b05325f2..7676de890 100644 --- a/src/providers/imap/mod.rs +++ b/src/providers/imap/mod.rs @@ -647,8 +647,7 @@ async fn execute( ) { return mutation::call(method, params, sent).await; } - // Invariant: Validate the entire batch and envelope before opening any socket. - credentials(params)?; + // Invariant: validate the entire batch and envelope before opening any socket. let folder = params["folder"].as_str().unwrap_or(""); let quoted = quote(folder)?; let commands = if method == "imap.request" { diff --git a/src/providers/jmap/mailbox_tls_test.py b/src/providers/jmap/mailbox_tls_test.py index a18e632dd..0e39bf028 100644 --- a/src/providers/jmap/mailbox_tls_test.py +++ b/src/providers/jmap/mailbox_tls_test.py @@ -1,5 +1,4 @@ """Synthetic native JMAP integration peer. All data and credentials are fictitious.""" -import contextlib import http.server import socketserver import json @@ -20,108 +19,108 @@ def server_bind(self): self.server_name, self.server_port = self.socket.getsockname()[:2] -with contextlib.nullcontext(pathlib.Path(__file__).parent.parent / "testdata" / "tls") as root: - requests = [] - email_gets = 0 - mode = "success" - def email(id): - folder = {"e1":"I", "e2":"S", "e3":"T"}.get(id,"I") - keywords = {"$seen":True} if id == "e1" else {"$flagged":True} if id == "e2" else {} - result = {"id":id,"threadId":"t1","mailboxIds":{folder:True},"keywords":keywords,"from":[{"email":"a@example.test","name":"Ada"}],"to":[{"email":"user@example.test"}],"subject":"Native test", "preview":"<3 native", "receivedAt":"2026-09-11T00:00:00Z", "bodyStructure":{"partId":"1","blobId":"tail","type":"text/plain","charset":"utf-8","size":13},"bodyValues":{"1":{"value":"short","isTruncated":True}}} - if scenario in ("occurrences", "member-bytes") and id == "e2": result["threadId"] = "t2" - if scenario == "roles": result["mailboxIds"] = {"NEW" if id == "e1" else "I": True} - if scenario == "empty": result["mailboxIds"] = {"S": True} - if scenario == "bad-membership": result["mailboxIds"] = {"I": "true"} - return result - def members(thread): - if scenario == "oversized-thread": return ["e1"] + ["m" + str(i) for i in range(2000)] - if scenario == "occurrences": return ["e1"] * (1000 if thread == "t1" else 1001) - if scenario == "member-bytes": return [("x" * 5990) + thread + str(i) for i in range(400)] - if scenario == "projection-bytes": return [("x" * 5990) + str(i) for i in range(400)] - if scenario == "projection-count": return ["e1", "e2", "e4"] + ["m" + str(i) for i in range(664)] - if scenario == "projection-at-limit": return ["e1", "e2"] + ["m" + str(i) for i in range(998)] - if scenario == "repeated": return ["e1", "e2"] - if scenario == "bad-member": return ["e1", 123] - return ["e1", "e2", "e3"] - class Handler(http.server.BaseHTTPRequestHandler): - def parse_request(self): - parsed = super().parse_request() - if parsed: - self.record = {"method":self.command,"path":self.path,"authorization":bool(self.headers.get("Authorization"))} - requests.append(self.record) - return parsed - def log_message(self,*_args): - pass - def answer(self,payload,status=200): - payload=json.dumps(payload).encode() if not isinstance(payload,bytes) else payload - self.send_response(status);self.send_header("Content-Length",str(len(payload)));self.end_headers();self.wfile.write(payload) - def do_GET(self): - if self.path=="/report": - # Invariant: Omit only this final harness read from the returned snapshot. - self.answer(requests[:-1]);threading.Thread(target=self.server.shutdown,daemon=True).start();return - if self.path=="/events": - payload=b'event: state\r\ndata: {"changed":{"account":{"Email":"e2","Mailbox":"m2"}}}\r\n\r\n' - self.send_response(200);self.send_header("Content-Type","text/event-stream");self.send_header("Content-Length",str(len(payload)));self.end_headers();self.wfile.write(payload);return - if self.path.startswith("/blob/"): self.answer(b"complete body") - else: self.answer({},404) - def do_POST(self): - global mode, email_gets - raw=self.rfile.read(int(self.headers.get("Content-Length","0"))) - if self.path=="/upload": - mode="fail" if b"Subject: fail" in raw else "importfail" if b"Subject: importfail" in raw else "uncertain" if b"Subject: uncertain" in raw else "success" - self.record["mode"]=mode;self.answer({"blobId":"uploaded"});return - if self.path=="/refused": - self.answer({},401);return - try: - body=json.loads(raw) - calls=body["methodCalls"] - if not isinstance(calls,list) or any(not isinstance(call,list) or len(call)!=3 for call in calls): raise ValueError("invalid methodCalls") - except (ValueError, KeyError, TypeError): - self.record["malformed"]=True;self.answer({},400);return - self.record["calls"]=calls - replies=[] - for method,args,id in body["methodCalls"]: - if method=="Email/query": - if "anchor" in args: replies.append(["error",{"type":"anchorNotFound"},id]);continue - result={"ids":["e1"],"position":0,"total":1,"queryState":"q1"} - elif method=="Email/get": - email_gets += 1 - if id=="3": replies.append(["error",{"type":"requestTooLarge"},id]);continue - result={"list":[email(v) for v in args.get("ids",["e1"])],"state":"e1"} - if scenario=="unsolicited-email": result["list"].append(email("unrequested")) - if scenario=="missing-email": result["list"]=[] - if scenario=="duplicate-email": result["list"].append(result["list"][0]) - if scenario=="bad-email": result["list"][0]["threadId"]=42 - if email_gets > 1: - if scenario=="unsolicited-member": result["list"].append(email("unrequested")) - if scenario=="missing-member": result["list"]=[] - if scenario=="duplicate-member": result["list"].append(result["list"][0]) - elif method=="Thread/get": - result={"list":[{"id":v,"emailIds":members(v)} for v in args.get("ids",["t1"])],"state":"t1"} - if scenario=="unsolicited-thread": result["list"].append({"id":"unrequested","emailIds":["e1"]}) - if scenario=="missing-thread": result["list"]=[] - if scenario=="duplicate-thread": result["list"].append(result["list"][0]) - elif method=="Identity/get": result={"list":[{"id":"identity","email":"user@example.test","name":"User"}]} - elif method=="Email/import": result={"notCreated":{"draft":{"type":"invalidEmail"}}} if mode=="importfail" else {"created":{"draft":{"id":"newdraft"}}} - elif method=="EmailSubmission/set" and mode=="uncertain": - self.connection.shutdown(socket.SHUT_RDWR);self.connection.close();return - elif method=="EmailSubmission/set": result={"notCreated":{"send":{"type":"forbiddenToSend"}}} if mode=="fail" else {"created":{"send":{"id":"submitted"}}} - elif method=="Email/set" and args.get("destroy")==["old-fail"]: result={"notDestroyed":{"old-fail":{"type":"forbidden"}}} - elif method=="Email/set" and scenario=="action-unknown" and "e2" in args.get("update",{}): result={"updated":[]} - elif method=="Email/set" and scenario=="action-failed": result={"notUpdated":{key:{"type":"forbidden","description":"synthetic-secret"} for key in args.get("update",{})}} - elif method=="Email/set" and scenario=="partial-action": result={"updated":{"e1":None},"notUpdated":{"e2":{"type":"notFound","description":"synthetic-secret"}}} - elif method=="Email/set": result={"updated":{key:None for key in args.get("update",{})},"destroyed":args.get("destroy",[])} - elif method=="Mailbox/get": - result={"list":[{"id":"I","role":"inbox"},{"id":"S","role":"sent"},{"id":"T","role":"trash"},{"id":"A","role":"archive"},{"id":"D","role":"drafts"}]} - if scenario!="default": result["list"].append({"id":"J","role":"junk"}) - missing={"no-archive":"archive","no-trash":"trash","no-inbox":"inbox"}.get(scenario) - result["list"]=[box for box in result["list"] if box["role"]!=missing] - if scenario=="roles": result["list"][0]["id"]="NEW" - else: replies.append(["error",{"type":"unknownMethod"},id]);continue - replies.append([method,result,id]) - self.answer({"methodResponses":None if scenario=="bad-envelope" else replies,"sessionState":"s1"}) - server=LoopbackServer(("127.0.0.1",0),Handler) - context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(root / "server.pem",root / "server-key.pem") - server.socket=context.wrap_socket(server.socket,server_side=True) - print(server.server_port,flush=True);print(root / "ca.pem",flush=True) - server.serve_forever(poll_interval=0.05);server.server_close() +root = pathlib.Path(__file__).parent.parent / "testdata" / "tls" +requests = [] +email_gets = 0 +mode = "success" +def email(id): + folder = {"e1":"I", "e2":"S", "e3":"T"}.get(id,"I") + keywords = {"$seen":True} if id == "e1" else {"$flagged":True} if id == "e2" else {} + result = {"id":id,"threadId":"t1","mailboxIds":{folder:True},"keywords":keywords,"from":[{"email":"a@example.test","name":"Ada"}],"to":[{"email":"user@example.test"}],"subject":"Native test", "preview":"<3 native", "receivedAt":"2026-09-11T00:00:00Z", "bodyStructure":{"partId":"1","blobId":"tail","type":"text/plain","charset":"utf-8","size":13},"bodyValues":{"1":{"value":"short","isTruncated":True}}} + if scenario in ("occurrences", "member-bytes") and id == "e2": result["threadId"] = "t2" + if scenario == "roles": result["mailboxIds"] = {"NEW" if id == "e1" else "I": True} + if scenario == "empty": result["mailboxIds"] = {"S": True} + if scenario == "bad-membership": result["mailboxIds"] = {"I": "true"} + return result +def members(thread): + if scenario == "oversized-thread": return ["e1"] + ["m" + str(i) for i in range(2000)] + if scenario == "occurrences": return ["e1"] * (1000 if thread == "t1" else 1001) + if scenario == "member-bytes": return [("x" * 5990) + thread + str(i) for i in range(400)] + if scenario == "projection-bytes": return [("x" * 5990) + str(i) for i in range(400)] + if scenario == "projection-count": return ["e1", "e2", "e4"] + ["m" + str(i) for i in range(664)] + if scenario == "projection-at-limit": return ["e1", "e2"] + ["m" + str(i) for i in range(998)] + if scenario == "repeated": return ["e1", "e2"] + if scenario == "bad-member": return ["e1", 123] + return ["e1", "e2", "e3"] +class Handler(http.server.BaseHTTPRequestHandler): + def parse_request(self): + parsed = super().parse_request() + if parsed: + self.record = {"method":self.command,"path":self.path,"authorization":bool(self.headers.get("Authorization"))} + requests.append(self.record) + return parsed + def log_message(self,*_args): + pass + def answer(self,payload,status=200): + payload=json.dumps(payload).encode() if not isinstance(payload,bytes) else payload + self.send_response(status);self.send_header("Content-Length",str(len(payload)));self.end_headers();self.wfile.write(payload) + def do_GET(self): + if self.path=="/report": + # Invariant: Omit only this final harness read from the returned snapshot. + self.answer(requests[:-1]);threading.Thread(target=self.server.shutdown,daemon=True).start();return + if self.path=="/events": + payload=b'event: state\r\ndata: {"changed":{"account":{"Email":"e2","Mailbox":"m2"}}}\r\n\r\n' + self.send_response(200);self.send_header("Content-Type","text/event-stream");self.send_header("Content-Length",str(len(payload)));self.end_headers();self.wfile.write(payload);return + if self.path.startswith("/blob/"): self.answer(b"complete body") + else: self.answer({},404) + def do_POST(self): + global mode, email_gets + raw=self.rfile.read(int(self.headers.get("Content-Length","0"))) + if self.path=="/upload": + mode="fail" if b"Subject: fail" in raw else "importfail" if b"Subject: importfail" in raw else "uncertain" if b"Subject: uncertain" in raw else "success" + self.record["mode"]=mode;self.answer({"blobId":"uploaded"});return + if self.path=="/refused": + self.answer({},401);return + try: + body=json.loads(raw) + calls=body["methodCalls"] + if not isinstance(calls,list) or any(not isinstance(call,list) or len(call)!=3 for call in calls): raise ValueError("invalid methodCalls") + except (ValueError, KeyError, TypeError): + self.record["malformed"]=True;self.answer({},400);return + self.record["calls"]=calls + replies=[] + for method,args,id in body["methodCalls"]: + if method=="Email/query": + if "anchor" in args: replies.append(["error",{"type":"anchorNotFound"},id]);continue + result={"ids":["e1"],"position":0,"total":1,"queryState":"q1"} + elif method=="Email/get": + email_gets += 1 + if id=="3": replies.append(["error",{"type":"requestTooLarge"},id]);continue + result={"list":[email(v) for v in args.get("ids",["e1"])],"state":"e1"} + if scenario=="unsolicited-email": result["list"].append(email("unrequested")) + if scenario=="missing-email": result["list"]=[] + if scenario=="duplicate-email": result["list"].append(result["list"][0]) + if scenario=="bad-email": result["list"][0]["threadId"]=42 + if email_gets > 1: + if scenario=="unsolicited-member": result["list"].append(email("unrequested")) + if scenario=="missing-member": result["list"]=[] + if scenario=="duplicate-member": result["list"].append(result["list"][0]) + elif method=="Thread/get": + result={"list":[{"id":v,"emailIds":members(v)} for v in args.get("ids",["t1"])],"state":"t1"} + if scenario=="unsolicited-thread": result["list"].append({"id":"unrequested","emailIds":["e1"]}) + if scenario=="missing-thread": result["list"]=[] + if scenario=="duplicate-thread": result["list"].append(result["list"][0]) + elif method=="Identity/get": result={"list":[{"id":"identity","email":"user@example.test","name":"User"}]} + elif method=="Email/import": result={"notCreated":{"draft":{"type":"invalidEmail"}}} if mode=="importfail" else {"created":{"draft":{"id":"newdraft"}}} + elif method=="EmailSubmission/set" and mode=="uncertain": + self.connection.shutdown(socket.SHUT_RDWR);self.connection.close();return + elif method=="EmailSubmission/set": result={"notCreated":{"send":{"type":"forbiddenToSend"}}} if mode=="fail" else {"created":{"send":{"id":"submitted"}}} + elif method=="Email/set" and args.get("destroy")==["old-fail"]: result={"notDestroyed":{"old-fail":{"type":"forbidden"}}} + elif method=="Email/set" and scenario=="action-unknown" and "e2" in args.get("update",{}): result={"updated":[]} + elif method=="Email/set" and scenario=="action-failed": result={"notUpdated":{key:{"type":"forbidden","description":"synthetic-secret"} for key in args.get("update",{})}} + elif method=="Email/set" and scenario=="partial-action": result={"updated":{"e1":None},"notUpdated":{"e2":{"type":"notFound","description":"synthetic-secret"}}} + elif method=="Email/set": result={"updated":{key:None for key in args.get("update",{})},"destroyed":args.get("destroy",[])} + elif method=="Mailbox/get": + result={"list":[{"id":"I","role":"inbox"},{"id":"S","role":"sent"},{"id":"T","role":"trash"},{"id":"A","role":"archive"},{"id":"D","role":"drafts"}]} + if scenario!="default": result["list"].append({"id":"J","role":"junk"}) + missing={"no-archive":"archive","no-trash":"trash","no-inbox":"inbox"}.get(scenario) + result["list"]=[box for box in result["list"] if box["role"]!=missing] + if scenario=="roles": result["list"][0]["id"]="NEW" + else: replies.append(["error",{"type":"unknownMethod"},id]);continue + replies.append([method,result,id]) + self.answer({"methodResponses":None if scenario=="bad-envelope" else replies,"sessionState":"s1"}) +server=LoopbackServer(("127.0.0.1",0),Handler) +context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(root / "server.pem",root / "server-key.pem") +server.socket=context.wrap_socket(server.socket,server_side=True) +print(server.server_port,flush=True);print(root / "ca.pem",flush=True) +server.serve_forever(poll_interval=0.05);server.server_close() From cd6b72a1d9632acc3a24560584fe3ef1efc76d96 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:24 +0100 Subject: [PATCH 037/568] Format provider cache and search changes --- src/providers/imap/read/search/tests/paging.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/providers/imap/read/search/tests/paging.rs b/src/providers/imap/read/search/tests/paging.rs index 5abc25f91..1a9b242d9 100644 --- a/src/providers/imap/read/search/tests/paging.rs +++ b/src/providers/imap/read/search/tests/paging.rs @@ -115,9 +115,10 @@ async fn peer(socket: TcpStream, state: Arc>) { Some(set.split(',').map(|s| s.parse().unwrap()).collect()) }; for (uid, _) in &state.folders[&folder] { - if wanted.as_ref().is_none_or(|uids| { - uids.contains(uid) && !state.missing.contains(uid) - }) { + if wanted + .as_ref() + .is_none_or(|uids| uids.contains(uid) && !state.missing.contains(uid)) + { data.push_str(&format!("* 1 FETCH (UID {uid})\r\n")); } } From 495646ab4a4298075242d1d10d913f2d43badcb5 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:50 +0100 Subject: [PATCH 038/568] website: Fix clipboard refusal with keyboard copy fallback --- Makefile | 1 + docs/index.html | 33 ++++++++++++++---- tests/test_website.js | 80 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 tests/test_website.js diff --git a/Makefile b/Makefile index 0ce72a471..e87eaa81a 100644 --- a/Makefile +++ b/Makefile @@ -115,6 +115,7 @@ backend: cargo build --locked --release --target-dir "$(CURDIR)/target" --bin omamail test-js: + node --test tests/test_website.js node ui/tests/test_inbox.js node ui/tests/test_display.js node app/tests/test_theme.js diff --git a/docs/index.html b/docs/index.html index a92c08b5d..47df7a389 100644 --- a/docs/index.html +++ b/docs/index.html @@ -831,7 +831,7 @@

Native
$ omarchy plugin add https://github.com/huacnlee/omamail.git --enable
- +
@@ -1167,18 +1167,39 @@

Run from source

} var copy = document.querySelector(".copy"); - if (copy && navigator.clipboard) { - copy.addEventListener("click", function () { - navigator.clipboard.writeText(copy.getAttribute("data-copy")).then(function () { + function selectCommand() { + var range = document.createRange(); + range.selectNodeContents(document.querySelector(".command .cmd")); + var selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + var shortcut = /mac/i.test(navigator.platform || "") ? "⌘C" : "Ctrl+C"; + copy.textContent = (lang === "zh" ? "按 " : "Press ") + shortcut; + copy.removeAttribute("data-state"); + copy.disabled = false; + } + function copyCommand() { + if (!navigator.clipboard || typeof navigator.clipboard.writeText !== "function") { + selectCommand(); + return; + } + copy.disabled = true; + copy.textContent = lang === "zh" ? "正在复制…" : "Copying…"; + try { + return navigator.clipboard.writeText(copy.getAttribute("data-copy")).then(function () { copy.textContent = copyLabels[lang]; copy.setAttribute("data-state", "done"); + copy.disabled = false; setTimeout(function () { copy.innerHTML = copy.getAttribute("data-" + lang); copy.removeAttribute("data-state"); }, 1600); - }); - }); + }, selectCommand); + } catch (error) { + selectCommand(); + } } + if (copy) copy.addEventListener("click", copyCommand); })(); diff --git a/tests/test_website.js b/tests/test_website.js new file mode 100644 index 000000000..3194c0087 --- /dev/null +++ b/tests/test_website.js @@ -0,0 +1,80 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const { test } = require("node:test"); + +const html = fs.readFileSync(path.join(__dirname, "../docs/index.html"), "utf8"); +const script = [...html.matchAll(/
" + "" diff --git a/ui/providers/OutlookAuth.qml b/ui/providers/OutlookAuth.qml index 785d4e56b..8841faa56 100644 --- a/ui/providers/OutlookAuth.qml +++ b/ui/providers/OutlookAuth.qml @@ -163,9 +163,9 @@ Item { var context = sessionContext() var waiting = graphWaiters graphWaiters = [] - for (var i = 0; i < waiting.length; i++) { + for (var itemIndex = 0; itemIndex < waiting.length; itemIndex++) { var current = isCurrent(context) && sessionEnabled - try { waiting[i](current ? token : "", current ? error : "Session changed") } + try { waiting[itemIndex](current ? token : "", current ? error : "Session changed") } catch (error) { /* Invariant: one consumer cannot strand another waiter. */ } } } @@ -381,13 +381,13 @@ Item { var context = sessionContext() var pending = tokenWaiters.slice() tokenWaiters = [] - for (var i = 0; i < pending.length; i++) { + for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { // A consumer can synchronously sign out or switch accounts. Remaining // callbacks still belong to the session captured above. var current = isCurrent(context) && sessionEnabled - try { pending[i](current ? (token || "") : "", + try { pending[itemIndex](current ? (token || "") : "", current ? safeError(error) : "Session changed") } - catch (e) { /* consumers own their callback errors */ } + catch (error) { /* consumers own their callback errors */ } } } @@ -535,16 +535,16 @@ Item { var id = ++tokenRequestCount var request = { abort: function() { var kept = [] - for (var i = 0; i < root.tokenRequests.length; i++) { - if (root.tokenRequests[i].id !== id) kept.push(root.tokenRequests[i]) + for (var itemIndex = 0; itemIndex < root.tokenRequests.length; itemIndex++) { + if (root.tokenRequests[itemIndex].id !== id) kept.push(root.tokenRequests[itemIndex]) } root.tokenRequests = kept } } tokenRequests = tokenRequests.concat([{ id: id, request: request }]) function finish(result, error) { var live = false - for (var i = 0; i < root.tokenRequests.length; i++) { - if (root.tokenRequests[i].id === id) live = true + for (var itemIndex = 0; itemIndex < root.tokenRequests.length; itemIndex++) { + if (root.tokenRequests[itemIndex].id === id) live = true } if (!live) return request.abort() @@ -830,8 +830,8 @@ Item { cancelDeviceLogin() var open = tokenRequests tokenRequests = [] - for (var i = 0; i < open.length; i++) { - if (open[i].request && open[i].request.abort) open[i].request.abort() + for (var itemIndex = 0; itemIndex < open.length; itemIndex++) { + if (open[itemIndex].request && open[itemIndex].request.abort) open[itemIndex].request.abort() } refreshBusy = false loginBusy = false From 373d3a949aac41c5d16689f326b3a2aa178c37da Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 109/568] Keep provider comments focused on session contracts --- ui/providers/Credentials.js | 235 ++--- ui/providers/Gmail.js | 2 +- ui/providers/GmailApi.js | 64 +- ui/providers/GmailApiClient.qml | 61 +- ui/providers/Hey.js | 2 +- ui/providers/HeyAuth.qml | 2 +- ui/providers/HeyCli.js | 326 ++++--- ui/providers/HeyClient.qml | 103 +- ui/providers/Imap.js | 2 +- ui/providers/ImapAuth.qml | 67 +- ui/providers/ImapProtocol.js | 600 ++++++------ ui/providers/Jmap.js | 2 +- ui/providers/JmapAuth.qml | 113 +-- ui/providers/JmapClient.qml | 2 +- ui/providers/JmapProtocol.js | 1580 +++++++++++++++---------------- ui/providers/JmapPush.qml | 2 +- ui/providers/JmapThreads.js | 224 ++--- ui/providers/MicrosoftOAuth.js | 67 +- ui/providers/OAuth.js | 91 +- ui/providers/Outlook.js | 3 +- ui/providers/OutlookAuth.qml | 123 +-- ui/providers/Secrets.js | 29 +- 22 files changed, 1773 insertions(+), 1927 deletions(-) diff --git a/ui/providers/Credentials.js b/ui/providers/Credentials.js index 66132b548..65accf25c 100644 --- a/ui/providers/Credentials.js +++ b/ui/providers/Credentials.js @@ -1,13 +1,10 @@ .pragma library -// Gmail has no shared public client the way Spotify does: every user brings -// their own Google Cloud OAuth client. This module turns whatever they have in -// hand — the JSON file the Cloud console hands out, a pasted client id, or an -// id and secret on two lines — into the one shape the rest of the plugin uses. +// Invariant: Client registration settings are separate from account-scoped grants. var CLIENT_ID_PATTERN = /^[0-9]+-[A-Za-z0-9_]+\.apps\.googleusercontent\.com$/ -// A client shipped with the plugin, so most people never see the setup at all. +// Invariant: A client shipped with the plugin, so most people never see the setup at all. // Empty until the project completes Google's OAuth verification: gmail.modify // and gmail.send are RESTRICTED scopes, and an unverified project is stuck in // "Testing", where Google issues refresh tokens that expire after seven days. @@ -43,9 +40,10 @@ function trimmed(value) { return String(value === undefined || value === null ? "" : value).trim() } -// The console wraps the credentials in "installed" for a desktop client and -// "web" for a web client. A web client cannot complete the loopback flow, so -// it is read but reported as the wrong type rather than silently half-working. +/** The console wraps the credentials in "installed" for a desktop client and + * "web" for a web client. A web client cannot complete the loopback flow, so + * it is read but reported as the wrong type rather than silently half-working. + */ function fromObject(raw) { if (!raw || typeof raw !== "object") return { ok: false, error: "Not a credentials file", credentials: empty() } var kind = "" @@ -89,8 +87,9 @@ function parseJson(text, fallback) { } } -// Accepts the downloaded JSON, or the id and secret typed in by hand on one or -// two lines. Anything else comes back as an error the panel can show verbatim. +/** Accepts the downloaded JSON, or the id and secret typed in by hand on one or + * two lines. Anything else comes back as an error the panel can show verbatim. + */ function parse(text) { var raw = String(text || "").trim() if (!raw) return { ok: false, error: "Paste the client ID, or the JSON file from Google Cloud", credentials: empty() } @@ -119,9 +118,7 @@ function parse(text) { } } -// ------------------------------------------------------------------- store -// -// Several accounts share one file, because a Cloud OAuth client belongs to a +// Invariant: Several accounts share one file, because a Cloud OAuth client belongs to a // project rather than to a mailbox: two accounts may legitimately run on one // client, and two others may each need their own. // @@ -144,8 +141,9 @@ function emptyStore() { return { accounts: [] } } -// The id is whatever the caller knows the account by — the address once a -// sign-in has produced one, "" for a file written before accounts had names. +/** The id is whatever the caller knows the account by — the address once a + * sign-in has produced one, "" for a file written before accounts had names. + */ function accountEntry(accountId, credentials) { var value = credentials || empty() return { @@ -164,8 +162,9 @@ function isStore(value) { return !!value && !!value.accounts && typeof value.accounts.length === "number" } -// Every entry point takes either a store or a single credentials object, so -// the single-account callers that predate this module's split keep working. +/** Every entry point takes either a store or a single credentials object, so + * the single-account callers that predate this module's split keep working. + */ function asStore(value) { if (!isStore(value)) return { accounts: [accountEntry("", value)] } var store = emptyStore() @@ -183,9 +182,10 @@ function accountIds(store) { return ids } -// Case folded, because an address is the usual id and a mailbox typed as -// Me@Gmail.com is the same account as me@gmail.com — two entries for it would -// mean two half-signed-in accounts. +/** Case folded, because an address is the usual id and a mailbox typed as + * Me@Gmail.com is the same account as me@gmail.com — two entries for it would + * mean two half-signed-in accounts. + */ function accountKey(accountId) { return trimmed(accountId).toLowerCase() } @@ -202,15 +202,16 @@ function forAccount(store, accountId) { var accounts = asStore(store).accounts var found = indexOfAccount(accounts, accountId) if (found >= 0) return credentialsOf(accounts[found]) - // The pre-accounts file holds one nameless entry. An account that has since + // Invariant: The pre-accounts file holds one nameless entry. An account that has since // learned its own address still has to find its client there, or the first // upgrade looks exactly like a missing client and asks for setup again. if (accounts.length === 1 && !accounts[0].id) return credentialsOf(accounts[0]) return empty() } -// Replaces in place rather than appending, so saving a client twice for one -// account does not push it to the end of the panel's list. +/** Replaces in place rather than appending, so saving a client twice for one + * account does not push it to the end of the panel's list. + */ function withAccount(store, accountId, credentials) { var next = asStore(store) var entry = accountEntry(accountId, credentials) @@ -232,9 +233,10 @@ function installedBlock(value) { } } -// Compact rather than indented, and one line whether it holds one account or -// six: it crosses a line-oriented pipe on the way to disk, whose `read` stops -// at the first newline. +/** Compact rather than indented, and one line whether it holds one account or + * six: it crosses a line-oriented pipe on the way to disk, whose `read` stops + * at the first newline. + */ function serialize(value) { var accounts = asStore(value).accounts if (accounts.length === 0) return JSON.stringify({ installed: installedBlock(empty()) }) @@ -248,8 +250,9 @@ function serialize(value) { return JSON.stringify({ version: FILE_VERSION, accounts: entries }) } -// A single account that fails to parse leaves the rest readable: one hand- -// edited entry should not sign every other account out. +/** A single account that fails to parse leaves the rest readable: one hand- + * edited entry should not sign every other account out. + */ function storeFromObject(raw) { var store = emptyStore() if (!raw || typeof raw !== "object") return store @@ -281,13 +284,14 @@ function load(text, accountId) { return forAccount(loadStore(text), accountId) } -// A Cloud OAuth client belongs to a project, not to a mailbox. One client signs -// in every account its owner has — which is exactly why the keyring keys tokens -// by account as well as by client — so an account with no client of its own -// borrows the one already set up. -// -// Without this, adding a second mailbox drops the user back on the console -// walkthrough they already completed, to make a second client they do not need. +/** A Cloud OAuth client belongs to a project, not to a mailbox. One client signs + * in every account its owner has — which is exactly why the keyring keys tokens + * by account as well as by client — so an account with no client of its own + * borrows the one already set up. + * + * Without this, adding a second mailbox drops the user back on the console + * walkthrough they already completed, to make a second client they do not need. + */ function sharedClient(store) { var accounts = asStore(store).accounts for (var itemIndex = 0; itemIndex < accounts.length; itemIndex++) { @@ -297,8 +301,9 @@ function sharedClient(store) { return empty() } -// The user's own client always wins: someone who went to the trouble of making -// one wants their own quota and their own consent screen, not the shipped one. +/** The user's own client always wins: someone who went to the trouble of making + * one wants their own quota and their own consent screen, not the shipped one. + */ function effective(fileText, accountId) { var store = loadStore(fileText) var own = forAccount(store, accountId) @@ -320,27 +325,26 @@ function path(home) { return (base || "~") + "/.config/omamail/credentials.json" } -// ----------------------------------------------------------------- keyring -// -// The refresh token is keyed by account as well as by client, because two +// Invariant: The refresh token is keyed by account as well as by client, because two // accounts may share one client: keyed by client alone, the second sign-in // would overwrite the first account's token and silently sign it out. var KEYRING_SERVICE = "omamail" var RENAMED_KEYRING_SERVICE = "omarchy-gmail" var KEYRING_KIND = "refresh-token" -// A token stored before Calendar support cannot prove it carries the new +// Invariant: A token stored before Calendar support cannot prove it carries the new // permission. A versioned lookup leaves that token untouched and presents the // sign-in flow again, where Google extends the existing grant. var KEYRING_GRANT = "calendar-events-v1" -// secret-tool reads an empty attribute value as "match anything", which would +// Invariant: secret-tool reads an empty attribute value as "match anything", which would // hand back some other account's token, so an account with no name yet gets a // literal one. No address can collide with it: every address has an "@". var UNNAMED_ACCOUNT = "default" -// Alternating name, value — the form secret-tool takes on its command line. -// An entry with no client id is not addressable at all, and asking for one -// would be a wildcard lookup over every token this plugin ever stored. +/** Alternating name, value — the form secret-tool takes on its command line. + * An entry with no client id is not addressable at all, and asking for one + * would be a wildcard lookup over every token this plugin ever stored. + */ function keyringAttributes(clientId, accountId) { var id = trimmed(clientId) if (!id) return [] @@ -353,9 +357,10 @@ function keyringAttributes(clientId, accountId) { ] } -// The account-keyed shape used before Calendar permission was added. It is -// looked up only to explain why sign-in is required again; its token is never -// refreshed as if it carried the current grant. +/** The account-keyed shape used before Calendar permission was added. It is + * looked up only to explain why sign-in is required again; its token is never + * refreshed as if it carried the current grant. + */ function previousGrantKeyringAttributes(clientId, accountId) { var id = trimmed(clientId) if (!id) return [] @@ -367,16 +372,17 @@ function previousGrantKeyringAttributes(clientId, accountId) { ] } -// What a single-account install stored before accounts existed. Such an entry -// has no "account" attribute. It is checked separately so the upgrade can -// explain why the broader grant needs a new sign-in. +/** What a single-account install stored before accounts existed. Such an entry + * has no "account" attribute. It is checked separately so the upgrade can + * explain why the broader grant needs a new sign-in. + */ function legacyKeyringAttributes(clientId) { var id = trimmed(clientId) if (!id) return [] return ["service", KEYRING_SERVICE, "kind", KEYRING_KIND, "client-id", id] } -// An IMAP account has no OAuth client to key on — it has a server and a +// Invariant: An IMAP account has no OAuth client to key on — it has a server and a // password. The attributes therefore key on the account alone, under a kind of // their own so an IMAP password and a Gmail refresh token for the same address // are two entries rather than one overwriting the other. @@ -384,14 +390,14 @@ var IMAP_KEYRING_KIND = "imap-password" function imapKeyringAttributes(accountId) { var id = accountKey(accountId) - // As above: an empty attribute value is a wildcard to secret-tool, which + // Invariant: As above: an empty attribute value is a wildcard to secret-tool, which // would hand back some other account's password. An account with no name yet // gets the literal placeholder, which no address can collide with. return ["service", KEYRING_SERVICE, "kind", IMAP_KEYRING_KIND, "account", id || UNNAMED_ACCOUNT] } -// A JMAP account has no OAuth client either, and its secret is an app password +// Invariant: A JMAP account has no OAuth client either, and its secret is an app password // or an API token rather than a password — one credential, whichever of the // two schemes turned out to work, so one entry keyed on the account alone. // @@ -405,14 +411,14 @@ var JMAP_KEYRING_KIND = "jmap-secret" function jmapKeyringAttributes(accountId) { var id = accountKey(accountId) - // As above: an empty attribute value is a wildcard to secret-tool, which + // Invariant: As above: an empty attribute value is a wildcard to secret-tool, which // would hand back some other account's secret. An account with no name yet // gets the literal placeholder, which no address can collide with. return ["service", KEYRING_SERVICE, "kind", JMAP_KEYRING_KIND, "account", id || UNNAMED_ACCOUNT] } -// An Outlook refresh token belongs to both the public OAuth client and the +// Invariant: An Outlook refresh token belongs to both the public OAuth client and the // mailbox that granted it. Keeping a separate kind prevents a Hotmail address // also added through Gmail or generic IMAP from sharing a secret by accident. var OUTLOOK_KEYRING_KIND = "outlook-refresh-token" @@ -429,8 +435,9 @@ function outlookKeyringAttributes(clientId, accountId) { ] } -// Entries from before the Omamail rename also predate Calendar permission. -// Their exact old shape lets the upgrade identify them without using them. +/** Entries from before the Omamail rename also predate Calendar permission. + * Their exact old shape lets the upgrade identify them without using them. + */ function renamedKeyringAttributes(clientId, accountId) { var attributes = previousGrantKeyringAttributes(clientId, accountId) if (attributes.length) attributes[1] = RENAMED_KEYRING_SERVICE @@ -443,9 +450,10 @@ function renamedLegacyKeyringAttributes(clientId) { return attributes } -// The restore stages are also the locations an invalid grant must be removed -// from. Returning the exact attribute vector keeps lookup and cleanup from -// drifting apart as old storage names are retired. +/** The restore stages are also the locations an invalid grant must be removed + * from. Returning the exact attribute vector keeps lookup and cleanup from + * drifting apart as old storage names are retired. + */ function refreshTokenAttributes(clientId, accountId, stage) { if (stage === 1) return previousGrantKeyringAttributes(clientId, accountId) if (stage === 2) return legacyKeyringAttributes(clientId) @@ -454,56 +462,59 @@ function refreshTokenAttributes(clientId, accountId, stage) { return keyringAttributes(clientId, accountId) } -// An omitted attribute is a wildcard too, not just an empty one. secret-tool -// matches any item carrying *at least* the attributes it was asked for, so -// both lookups above that leave "account" out match the account-keyed entries -// as well as the nameless one they are for. On an install where two mailboxes -// share one Cloud client, either can therefore hand back the *other* -// mailbox's token. -// -// Nothing about that fails loudly. The token refreshes, Google returns no new -// refresh token so the same one is carried through the response, and it is -// written back under this account's key. Both mailboxes end up holding one -// token, and the account you switch to shows the other one's inbox. -// -// So the legacy read asks first whether a legacy entry is there at all, with -// `secret-tool search --all` on the same attributes. That reports one record -// per match, but it prints the record to stdout and its attributes to -// *stderr*: -// -// stdout stderr -// [/12] attribute.service = omamail -// label = Omamail refresh token attribute.kind = refresh-token -// secret = 1//0the-token attribute.client-id = 1234-abc... -// created = 2026-08-21 13:01:00 attribute.account = one@gmail.com -// schema = org.freedesktop.Secret.Generic -// -// Two pipes, buffered independently, so which record an attribute line belongs -// to is not answerable from the outside: one stream can arrive whole after the -// other. Counting is, and counting is enough, because every match prints -// exactly one "account" attribute unless it has none. -// -// One line at a time rather than one buffer, so that no caller has to hold the -// stdout of a search that loaded every matching mailbox's token. +/** An omitted attribute is a wildcard too, not just an empty one. secret-tool + * matches any item carrying *at least* the attributes it was asked for, so + * both lookups above that leave "account" out match the account-keyed entries + * as well as the nameless one they are for. On an install where two mailboxes + * share one Cloud client, either can therefore hand back the *other* + * mailbox's token. + * + * Nothing about that fails loudly. The token refreshes, Google returns no new + * refresh token so the same one is carried through the response, and it is + * written back under this account's key. Both mailboxes end up holding one + * token, and the account you switch to shows the other one's inbox. + * + * So the legacy read asks first whether a legacy entry is there at all, with + * `secret-tool search --all` on the same attributes. That reports one record + * per match, but it prints the record to stdout and its attributes to + * *stderr*: + * + * stdout stderr + * [/12] attribute.service = omamail + * label = Omamail refresh token attribute.kind = refresh-token + * secret = 1//0the-token attribute.client-id = 1234-abc... + * created = 2026-08-21 13:01:00 attribute.account = one@gmail.com + * schema = org.freedesktop.Secret.Generic + * + * Two pipes, buffered independently, so which record an attribute line belongs + * to is not answerable from the outside: one stream can arrive whole after the + * other. Counting is, and counting is enough, because every match prints + * exactly one "account" attribute unless it has none. + * + * One line at a time rather than one buffer, so that no caller has to hold the + * stdout of a search that loaded every matching mailbox's token. + */ function isKeyringMatchLine(line) { return startsWithPrefix(line, "[") } -// Every entry this plugin stores carries a "service" attribute, and the search -// is keyed on it, so one of these stands for every match. Fewer of them than -// there are matches means the attribute stream did not account for all of -// them, and an attribute that was not read cannot be an attribute that is -// absent. +/** Every entry this plugin stores carries a "service" attribute, and the search + * is keyed on it, so one of these stands for every match. Fewer of them than + * there are matches means the attribute stream did not account for all of + * them, and an attribute that was not read cannot be an attribute that is + * absent. + */ function isKeyringAttributedLine(line) { return startsWithPrefix(line, "attribute.service = ") } var ACCOUNT_ATTRIBUTE_PREFIX = "attribute.account = " -// A mailbox that has not learned its address yet is stored under a literal -// stand-in rather than a blank, so that entry has an "account" attribute -// without having a name. It belongs to whichever mailbox was mid-setup, which -// on a single-entry install is the only one there is. +/** A mailbox that has not learned its address yet is stored under a literal + * stand-in rather than a blank, so that entry has an "account" attribute + * without having a name. It belongs to whichever mailbox was mid-setup, which + * on a single-entry install is the only one there is. + */ function isKeyringNamedLine(line) { if (!startsWithPrefix(line, ACCOUNT_ATTRIBUTE_PREFIX)) return false return String(line).substring(ACCOUNT_ATTRIBUTE_PREFIX.length) !== UNNAMED_ACCOUNT @@ -513,22 +524,24 @@ function startsWithPrefix(line, prefix) { return String(line === undefined || line === null ? "" : line).indexOf(prefix) === 0 } -// One match, every match accounted for, and no named account among them: the -// only shape where the entry a lookup is about to return is certainly the -// nameless one, because it is the only entry there is to return. -// -// Every other shape refuses. All-named is the case this exists for, where -// nothing nameless is there and the wildcard would take a mailbox's own token. -// A nameless entry beside named ones is left alone too. The lookup cannot tell -// which entry it would return. +/** One match, every match accounted for, and no named account among them: the + * only shape where the entry a lookup is about to return is certainly the + * nameless one, because it is the only entry there is to return. + * + * Every other shape refuses. All-named is the case this exists for, where + * nothing nameless is there and the wildcard would take a mailbox's own token. + * A nameless entry beside named ones is left alone too. The lookup cannot tell + * which entry it would return. + */ function hasLoneLegacyEntry(matches, attributed, named) { if (matches !== 1) return false if (attributed !== matches) return false return named === 0 } -// Shown under the client id in the panel so a user with several Cloud projects -// can tell which one is wired up without opening the file. +/** Shown under the client id in the panel so a user with several Cloud projects + * can tell which one is wired up without opening the file. + */ function describe(credentials) { if (!isConfigured(credentials)) return "" var id = trimmed(credentials.clientId) diff --git a/ui/providers/Gmail.js b/ui/providers/Gmail.js index 313ed0320..44a398728 100644 --- a/ui/providers/Gmail.js +++ b/ui/providers/Gmail.js @@ -1,6 +1,6 @@ .pragma library -// Provider presentation only. NativeDomain.js supplies all mail capabilities +// Invariant: Provider presentation only. NativeDomain.js supplies all mail capabilities // and mailbox queries; providers.resolve builds dynamic queries in Rust. var ID = "gmail" diff --git a/ui/providers/GmailApi.js b/ui/providers/GmailApi.js index 978eaf63d..1d6af8101 100644 --- a/ui/providers/GmailApi.js +++ b/ui/providers/GmailApi.js @@ -19,15 +19,13 @@ function localEditError(error) { return "Magpie could not confirm this change. Check the message’s current state before trying again." } -// URL construction and response shaping for the Gmail REST API. No transport -// lives here — GmailApi.qml owns XMLHttpRequest, this file owns every string -// and every decision about what a response means, which is what the tests can -// reach without a compositor. +// Invariant: Live Gmail transport belongs to Rust. The UI uses presentation helpers; +// legacy protocol builders remain available to the reference tests. var API_BASE = "https://gmail.googleapis.com/gmail/v1" var WEB_BASE = "https://mail.google.com/mail/u" -// System labels the panel treats as mailboxes. Gmail returns these ids for +// Invariant: System labels the panel treats as mailboxes. Gmail returns these ids for // every account regardless of language, unlike user labels whose names are // whatever the user typed. var SYSTEM_LABELS = { @@ -50,8 +48,9 @@ function encode(value) { return encodeURIComponent(String(value === undefined || value === null ? "" : value)) } -// Query values may repeat (metadataHeaders, labelIds), so an array value -// becomes one key=value pair per entry rather than a joined string. +/** Query values may repeat (metadataHeaders, labelIds), so an array value + * becomes one key=value pair per entry rather than a joined string. + */ function appendQuery(url, values) { if (!values) return url var parts = [] @@ -71,8 +70,9 @@ function appendQuery(url, values) { return url + (url.indexOf("?") < 0 ? "?" : "&") + parts.join("&") } -// Every request goes through here, so a path that somehow arrived from a -// response body cannot point the authenticated client at another host. +/** Every request goes through here, so a path that somehow arrived from a + * response body cannot point the authenticated client at another host. + */ function safeApiUrl(path) { var value = String(path || "") if (value.charAt(0) !== "/") return "" @@ -96,8 +96,9 @@ function redact(text) { .replace(/\bya29\.[A-Za-z0-9._-]+/g, "[redacted]") } -// Gmail's failures are worth translating: the raw messages are written for -// somebody reading a server log, not for somebody who just clicked Archive. +/** Gmail's failures are worth translating: the raw messages are written for + * somebody reading a server log, not for somebody who just clicked Archive. + */ function responseError(status, payload, fallback) { var detail = "" if (payload && payload.error) { @@ -128,8 +129,6 @@ function rateLimitSuffix(retryAfter) { return " (retry in " + Math.ceil(seconds / 60) + " min)" } -// ------------------------------------------------------------------ paths - function messagesPath() { return "/users/me/messages" } function messagePath(id) { return "/users/me/messages/" + encode(id) } function modifyPath(id) { return "/users/me/messages/" + encode(id) + "/modify" } @@ -182,7 +181,7 @@ function listQuery(query, maxResults, pageToken) { } } -// `metadata` is a quarter of the payload of `full` and is all a list row needs. +// Performance: `metadata` is a quarter of the payload of `full` and is all a list row needs. var LIST_HEADERS = ["From", "To", "Subject", "Date", "List-Unsubscribe"] function metadataQuery() { @@ -193,8 +192,6 @@ function fullQuery() { return { format: "full" } } -// ---------------------------------------------------------------- parsing - function arrayValues(value) { return Array.isArray(value) ? value : [] } @@ -214,7 +211,6 @@ function parseMessageList(payload) { ids: ids, threadIds: threadIds, nextPageToken: String(body.nextPageToken || ""), - // Gmail is explicit that this is an estimate; the panel labels it as one. estimate: Math.max(0, Math.floor(Number(body.resultSizeEstimate) || 0)) } } @@ -265,15 +261,16 @@ function parseProfile(payload) { } } -// Gmail's send-as collection includes the primary address and every custom -// address configured under "Send mail as". Pending custom addresses cannot be -// used yet, so they must not appear as choices in a compose window. -// -// Only `pending` is excluded, never "everything that is not `accepted`": -// verification applies to custom addresses alone, so an alias that never -// needed it — a Workspace alternate address, an alias domain — comes back with -// the field absent, and requiring `accepted` dropped exactly the addresses -// that were always usable. +/** Gmail's send-as collection includes the primary address and every custom + * address configured under "Send mail as". Pending custom addresses cannot be + * used yet, so they must not appear as choices in a compose window. + * + * Only `pending` is excluded, never "everything that is not `accepted`": + * verification applies to custom addresses alone, so an alias that never + * needed it — a Workspace alternate address, an alias domain — comes back with + * the field absent, and requiring `accepted` dropped exactly the addresses + * that were always usable. + */ function parseSendAs(payload) { var entries = arrayValues(payload && payload.sendAs) var aliases = [] @@ -332,14 +329,13 @@ function isSendAsAllowed(aliases, email) { return sendAsFor(aliases, email) !== null } -// --------------------------------------------------------------- browsing - -// Gmail's web UI addresses accounts by index, not address, and there is no way -// to map one to the other from the API. Index 0 is right for the common -// single-account case and wrong in a way the user can see and fix, which beats -// a link that silently opens somebody else's mailbox. -// The mailbox itself, rather than a message or a search in it. Gmail's web UI -// opens on whatever the user last had; there is nothing to point it at. +/** Gmail's web UI addresses accounts by index, not address, and there is no way + * to map one to the other from the API. Index 0 is right for the common + * single-account case and wrong in a way the user can see and fix, which beats + * a link that silently opens somebody else's mailbox. + * The mailbox itself, rather than a message or a search in it. Gmail's web UI + * opens on whatever the user last had; there is nothing to point it at. + */ function webHomeUrl(accountIndex) { var index = Math.max(0, Math.floor(Number(accountIndex) || 0)) return WEB_BASE + "/" + index + "/" diff --git a/ui/providers/GmailApiClient.qml b/ui/providers/GmailApiClient.qml index 35430f28e..fed8845fe 100644 --- a/ui/providers/GmailApiClient.qml +++ b/ui/providers/GmailApiClient.qml @@ -2,7 +2,7 @@ import QtQuick import "GmailApi.js" as Api -// Authenticated transport. It holds no state about the mailbox — only about +// Invariant: Authenticated transport. It holds no state about the mailbox — only about // requests in flight — so the service can cancel a page load without having to // know anything about how it was issued. Item { @@ -28,7 +28,7 @@ Item { } Component.onDestruction: invalidateBackend() - // Gmail returns IDs separately from message resources. A bounded group of + // Performance: Gmail returns IDs separately from message resources. A bounded group of // reads keeps queued work inside each request's deadline while rows arrive. property int inFlight: 0 readonly property bool busy: inFlight > 0 @@ -45,7 +45,7 @@ Item { backendEpoch++ var old = backendAccount backendAccount = "" - // Cache eviction only: queued requests and external keyring credentials + // Invariant: Cache eviction only: queued requests and external keyring credentials // are not revoked by this message. Epochs suppress stale UI delivery. if (old !== "" && usesBackend()) backend.call("gmail.invalidate", { accountId: old }, function() {}) @@ -108,7 +108,7 @@ Item { return handle } - // A message mutation answers with a ticket: the backend sends it from a + // Invariant: A message mutation answers with a ticket: the backend sends it from a // per-account queue, paced and retried, and announces the outcome as a // `gmail.settled` notification. The request stays in flight until then. property var parked: ({}) @@ -135,7 +135,6 @@ Item { else entry.deliver(null, { message: String(parameters.error || "gmail_queue_lost") }) } - // The backend that held the queue is gone with it. function settleAll(error) { var tickets = Object.keys(parked) for (var itemIndex = 0; itemIndex < tickets.length; itemIndex++) settle({ ticket: tickets[itemIndex], ok: false, error: error }) @@ -156,8 +155,6 @@ Item { handle.children = [] } - // ---------------------------------------------------------------- reads - function listMessages(query, maxResults, pageToken, callback, progress) { return backendRequest("gmail.list", { query: String(query || ""), pageToken: String(pageToken || ""), @@ -173,10 +170,11 @@ Item { } - // The octets of a part Gmail described but did not send. Every part the - // sender named comes back that way — an id, a type and a size — and the - // reader asks for one of them: the invitation, whose file has to be read - // before a meeting can be drawn or answered. + /** The octets of a part Gmail described but did not send. Every part the + * sender named comes back that way — an id, a type and a size — and the + * reader asks for one of them: the invitation, whose file has to be read + * before a meeting can be drawn or answered. + */ function getAttachment(messageId, attachmentId, callback) { return backendRequest("gmail.attachment", { messageId: String(messageId || ""), attachmentId: String(attachmentId || "") @@ -187,16 +185,17 @@ Item { } - // The counted members of a conversation, for the reader's conversation rail. - // - // Always empty, and Gmail is never asked: it declares `threads` — a - // server-side thread id exists — but not `conversations`, so its listing is - // one row per message and no row here carries member ids for a rail to draw. - // - // Deferred rather than answered on the spot even though the answer is in - // hand: every caller in this interface is written against a callback that - // arrives later, and running one partway through the function that started it - // is a re-entry no other read produces. + /** The counted members of a conversation, for the reader's conversation rail. + * + * Always empty, and Gmail is never asked: it declares `threads` — a + * server-side thread id exists — but not `conversations`, so its listing is + * one row per message and no row here carries member ids for a rail to draw. + * + * Deferred rather than answered on the spot even though the answer is in + * hand: every caller in this interface is written against a callback that + * arrives later, and running one partway through the function that started it + * is a re-entry no other read produces. + */ function getSummaries(ids, callback) { var handle = newHandle() Qt.callLater(function() { @@ -206,13 +205,14 @@ Item { return handle } - // Fetches up to four IDs at a time and calls back once, with results in the - // order the ids were given rather than the order Google answered in. A list - // search may also take `progress`, which receives the payloads as Google - // answers so cached rows can be filled in without waiting for the slowest - // request on the page. Answers close enough to share a frame are batched: - // repainting and sorting the whole list once per reply - // costs far more than the few milliseconds of extra latency reveal. + /** Fetches up to four IDs at a time and calls back once, with results in the + * order the ids were given rather than the order Google answered in. A list + * search may also take `progress`, which receives the payloads as Google + * answers so cached rows can be filled in without waiting for the slowest + * request on the page. Answers close enough to share a frame are batched: + * repainting and sorting the whole list once per reply + * costs far more than the few milliseconds of extra latency reveal. + */ function getMessages(ids, full, callback, existingHandle, progress) { var handle = existingHandle || newHandle() var list = Array.isArray(ids) ? ids : [] @@ -260,7 +260,7 @@ Item { for (var itemIndex = 0; itemIndex < results.length; itemIndex++) { if (results[itemIndex]) ordered.push(results[itemIndex]) } - // A partial page is still a failed page: hiding one failed request just + // Invariant: A partial page is still a failed page: hiding one failed request just // because another answered would let the caller keep a continuation // token beyond the missing row. callback(ordered, firstError) @@ -315,7 +315,7 @@ Item { } function getProfile(callback) { - // The native sign-in already verified this identity before storing its + // Invariant: The native sign-in already verified this identity before storing its // grant. A new account has no registry ID until this callback identifies it. if (auth && auth.loggedIn && auth.signedInProfile) { var handle = newHandle() @@ -340,7 +340,6 @@ Item { } - // Mail operations and draft resolution are owned by the persistent backend. function modifyMessage(id, addLabelIds, removeLabelIds, callback) { if (backend && backend.ready && Number(backend.apiVersion) >= 8) return localEdit([String(id || "")],addLabelIds || [],removeLabelIds || [],callback) diff --git a/ui/providers/Hey.js b/ui/providers/Hey.js index d632d87ee..1ced502fd 100644 --- a/ui/providers/Hey.js +++ b/ui/providers/Hey.js @@ -1,6 +1,6 @@ .pragma library -// Provider presentation only. NativeDomain.js supplies all mail capabilities +// Invariant: Provider presentation only. NativeDomain.js supplies all mail capabilities // and mailbox queries; providers.resolve builds dynamic queries in Rust. var ID = "hey" diff --git a/ui/providers/HeyAuth.qml b/ui/providers/HeyAuth.qml index 84f911432..ba6af4921 100644 --- a/ui/providers/HeyAuth.qml +++ b/ui/providers/HeyAuth.qml @@ -1,6 +1,6 @@ import QtQuick -// The backend supervises the official HEY CLI; that CLI owns its credentials. +// Invariant: The backend supervises the official HEY CLI; that CLI owns its credentials. Item { id: root visible: false diff --git a/ui/providers/HeyCli.js b/ui/providers/HeyCli.js index 1fc1f4571..6eb3a9fe6 100644 --- a/ui/providers/HeyCli.js +++ b/ui/providers/HeyCli.js @@ -1,41 +1,25 @@ .pragma library -// The HEY CLI, as a protocol. -// -// `hey` is the interface 37signals publish for HEY, and it is the only one this -// plugin will use: there is no IMAP, no POP and no public HTTP API, and driving -// app.hey.com's own endpoints would mean replaying a user's password against -// something carrying no compatibility promise. -// -// This file is the argument vectors and the answers, and nothing else. No -// process — `HeyClient.qml` owns that — and no message format, which is -// `Message.js`'s subject. Everything here is pure, so the node tests exercise -// the real strings that reach the real command. -// -// Every command is asked for `--json`, so nothing here ever parses a rendered -// table. The envelope is always `{ ok, data, summary, error, code }`, and a -// command that failed says so in `ok` while still exiting 0 for some errors — -// which is why `payload` checks the envelope rather than the exit status. - -// ---------------------------------------------------------------- the boxes - -// HEY's own boxes, by the `kind` its API answers with. `hey box` takes these +// Invariant: Rust supervises the official HEY CLI. This library supplies UI helpers +// and protocol reference functions; CLI envelopes can report failure with exit zero. + +// Invariant: HEY's own boxes, by the `kind` its API answers with. `hey box` takes these // names directly. Trash is deliberately not among them: HEY does not serve a // trash box, and the only way to see what is in it is a search. var BOXES = ["imbox", "feedbox", "asidebox", "laterbox", "trailbox", "bubblebox"] -// The virtual one. `box:trash` reads like the rest of the DSL and becomes +// Invariant: The virtual one. `box:trash` reads like the rest of the DSL and becomes // `hey search --in trash`, which is the only thing HEY answers for it. var TRASH = "trash" -// How many postings a query that has to count unseen mail reads. The unread +// Invariant: How many postings a query that has to count unseen mail reads. The unread // badge is a count of unseen postings in the Imbox and HEY serves no count of // its own, so the only way to have one is to list and tally — and a badge is // answering "is something waiting", which a hundred answers as well as a // thousand would. var UNSEEN_SCAN = 100 -// The ceiling `--limit` is given. HEY pages beyond this; the list asks for more +// Invariant: The ceiling `--limit` is given. HEY pages beyond this; the list asks for more // with the cursor the last answer carried. var MAX_LIMIT = 100 @@ -57,19 +41,18 @@ function boundedLimit(value, fallback) { return Math.max(1, Math.min(MAX_LIMIT, limit)) } -// ------------------------------------------------------------- the id pair - -// A HEY thread is addressed by two different numbers, and which one a command -// wants is not a detail anything above this file should have to know: -// -// - the **posting** id is the thread's place in a box, and it is what -// `seen`, `unseen`, `move`, `trash` and `spam` act on -// - the **topic** id is the conversation, and it is what `threads`, `reply` -// and `forward` read and write -// -// So a message id here carries both, the way an IMAP one carries its folder. A -// bare posting id could not be opened and a bare topic id could not be marked -// seen, and finding out which had been stored would be a round trip. +/** A HEY thread is addressed by two different numbers, and which one a command + * wants is not a detail anything above this file should have to know: + * + * - the **posting** id is the thread's place in a box, and it is what + * `seen`, `unseen`, `move`, `trash` and `spam` act on + * - the **topic** id is the conversation, and it is what `threads`, `reply` + * and `forward` read and write + * + * So a message id here carries both, the way an IMAP one carries its folder. A + * bare posting id could not be opened and a bare topic id could not be marked + * seen, and finding out which had been stored would be a round trip. + */ function messageId(postingId, topicId) { var posting = trimmed(postingId) var topic = trimmed(topicId) @@ -84,27 +67,26 @@ function postingIdOf(id) { function topicIdOf(id) { var parts = trimmed(id).split(":") - // One half only is what an id written before both were stored would look + // Invariant: One half only is what an id written before both were stored would look // like; reading it as the topic would open the wrong conversation, so it is // read as neither. return parts.length > 1 ? trimmed(parts[1]) : "" } -// ------------------------------------------------------------- the queries - -// The strings `Hey.js` produces and this file reads. Opaque everywhere else: -// upstream hands one back to the client that made it and uses it as a cache -// key. -// -// box:imbox a box, newest first -// box:imbox unseen the same box, only what has not been seen -// box:trash the Trash, which is a search because HEY has no box -// label:4711 one label's threads, by the id `hey labels` gave -// search:dentist free text, over every box -// -// `search:` takes the rest of the string verbatim, so a user who types -// `box:imbox` into the search field searches for that text rather than -// selecting a mailbox. +/** The strings `Hey.js` produces and this file reads. Opaque everywhere else: + * upstream hands one back to the client that made it and uses it as a cache + * key. + * + * box:imbox a box, newest first + * box:imbox unseen the same box, only what has not been seen + * box:trash the Trash, which is a search because HEY has no box + * label:4711 one label's threads, by the id `hey labels` gave + * search:dentist free text, over every box + * + * `search:` takes the rest of the string verbatim, so a user who types + * `box:imbox` into the search field searches for that text rather than + * selecting a mailbox. + */ function parseQuery(query) { var text = trimmed(query) if (text === "drafts:") { @@ -127,23 +109,22 @@ function parseQuery(query) { if (!isBox(box)) box = "imbox" return { kind: "box", box: box, label: "", text: "", unseen: unseen } } - // Anything unrecognised is the Imbox rather than an error: a query written by + // Invariant: Anything unrecognised is the Imbox rather than an error: a query written by // a newer build, or left in a cache file, still has to open a window. return { kind: "box", box: "imbox", label: "", text: "", unseen: false } } -// -------------------------------------------------------------- the paging - -// A page token here is an offset into one of HEY's pages, and HEY's own cursor -// for that page: "25|eyJ...". -// -// Both halves are needed because of how `--limit` works. The CLI reads pages -// until it has the number asked for, then truncates to it **and drops the -// cursor** — so a limited listing can never be continued. Asking for no limit -// gets HEY's own page with its cursor intact, which means the page size the -// user configured has to be applied here instead. The offset is where in that -// page this request starts; the same page is read again to serve the rest of -// it, exactly as the IMAP client re-runs its SEARCH. +/** A page token here is an offset into one of HEY's pages, and HEY's own cursor + * for that page: "25|eyJ...". + * + * Both halves are needed because of how `--limit` works. The CLI reads pages + * until it has the number asked for, then truncates to it **and drops the + * cursor** — so a limited listing can never be continued. Asking for no limit + * gets HEY's own page with its cursor intact, which means the page size the + * user configured has to be applied here instead. The offset is where in that + * page this request starts; the same page is read again to serve the rest of + * it, exactly as the IMAP client re-runs its SEARCH. + */ function pageToken(offset, cursor) { var at = Math.max(0, Math.floor(Number(offset)) || 0) var key = trimmed(cursor) @@ -164,18 +145,20 @@ function tokenCursor(token) { return bar < 0 ? "" : trimmed(text.slice(bar + 1)) } -// How many postings this query has to read in one command. Only the unseen -// filter names a number: the filtering happens here rather than on the server, -// so a page of one would find one unseen message at most however many are -// waiting — and that number is the unread badge. Everything else takes HEY's -// own page, because asking for a size is what throws the cursor away. +/** How many postings this query has to read in one command. Only the unseen + * filter names a number: the filtering happens here rather than on the server, + * so a page of one would find one unseen message at most however many are + * waiting — and that number is the unread badge. Everything else takes HEY's + * own page, because asking for a size is what throws the cursor away. + */ function scanLimit(parsed) { return parsed && parsed.unseen === true ? UNSEEN_SCAN : 0 } -// The argument vector for a list, after the binary. A box and a label take an -// opaque cursor out of the previous answer's `next_page`; a search takes a page -// number, because HEY's search is numbered and its box index is not. +/** The argument vector for a list, after the binary. A box and a label take an + * opaque cursor out of the previous answer's `next_page`; a search takes a page + * number, because HEY's search is numbered and its box index is not. + */ function listCommand(parsed, maxResults, pageToken) { var query = parsed || parseQuery("") var limit = scanLimit(query) @@ -209,13 +192,14 @@ function listCommand(parsed, maxResults, pageToken) { return box } -// Reading one thread. `--allow-partial` because a thread too long for the -// loader's own limits is refused outright without it — and a message that -// opens with a note about what is missing beats one that does not open. +/** Reading one thread. `--allow-partial` because a thread too long for the + * loader's own limits is refused outright without it — and a message that + * opens with a note about what is missing beats one that does not open. + */ function threadCommand(id) { var topic = topicIdOf(id) if (topic === "") return [] - // Both flags are asked for optimistically, and both are boolean, which is + // Invariant: Both flags are asked for optimistically, and both are boolean, which is // what makes `withoutFlag` a safe answer to a build that has neither. // // `--html` asks for the sender's own markup, which is what the reader wants: @@ -242,10 +226,11 @@ function draftShowCommand(id) { return draft === "" ? [] : ["draft", "show", draft, "--json"] } -// The flag `hey` said it did not know, out of its own usage error. A release -// older than a flag this plugin asks for refuses the whole command, so the -// client drops the flag and asks again — and remembers, so one round trip pays -// for the whole session rather than every read. +/** The flag `hey` said it did not know, out of its own usage error. A release + * older than a flag this plugin asks for refuses the whole command, so the + * client drops the flag and asks again — and remembers, so one round trip pays + * for the whole session rather than every read. + */ function unknownFlag(text) { var body = parseJson(text, null) var reported = body && typeof body === "object" ? trimmed(body.error) : trimmed(text) @@ -253,9 +238,10 @@ function unknownFlag(text) { return match ? match[1] : "" } -// A command without one boolean flag. Only ever used on the optional flags -// above, all of which are booleans — dropping a flag that took a value would -// leave its value behind as a positional argument. +/** A command without one boolean flag. Only ever used on the optional flags + * above, all of which are booleans — dropping a flag that took a value would + * leave its value behind as a positional argument. + */ function withoutFlag(command, flag) { var list = Array.isArray(command) ? command : [] var wanted = trimmed(flag) @@ -270,13 +256,14 @@ function hasFlag(command, flag) { return withoutFlag(command, flag).length !== (Array.isArray(command) ? command.length : 0) } -// What an action becomes. `MailAccount` speaks Gmail's vocabulary to every -// provider, so the label ids arrive here and become HEY's own verbs. -// -// A verb HEY does not have answers with an empty command rather than with -// something close to it: the panel already hides the buttons this provider does -// not declare, and a "close enough" move is the promise `Registry.capabilities` -// exists to stop being made. +/** What an action becomes. `MailAccount` speaks Gmail's vocabulary to every + * provider, so the label ids arrive here and become HEY's own verbs. + * + * A verb HEY does not have answers with an empty command rather than with + * something close to it: the panel already hides the buttons this provider does + * not declare, and a "close enough" move is the promise `Registry.capabilities` + * exists to stop being made. + */ function actionCommand(verb, ids) { var name = trimmed(verb) var postings = [] @@ -291,15 +278,16 @@ function actionCommand(verb, ids) { if (name === "markUnread") return ["unseen"].concat(postings) if (name === "trash") return ["trash"].concat(postings) if (name === "spam") return ["spam"].concat(postings) - // Not an archive — HEY has none — but the one move that puts a thread back + // Invariant: Not an archive — HEY has none — but the one move that puts a thread back // where a restored message belongs. if (name === "untrash") return ["move"].concat(postings, ["--to", "imbox"]) return [] } -// The label ids `MailAccount` asks for, as one verb. Only the pairs HEY can -// honour are named; everything else is nothing to do, which is what an -// undeclared capability produces anyway. +/** The label ids `MailAccount` asks for, as one verb. Only the pairs HEY can + * honour are named; everything else is nothing to do, which is what an + * undeclared capability produces anyway. + */ function verbForLabels(addLabelIds, removeLabelIds) { var add = Array.isArray(addLabelIds) ? addLabelIds : [] var remove = Array.isArray(removeLabelIds) ? removeLabelIds : [] @@ -309,12 +297,13 @@ function verbForLabels(addLabelIds, removeLabelIds) { return "" } -// Sending. HEY composes and replies for the user rather than accepting a -// message: a reply's recipients are the server's to decide, which is why the -// reply command takes a topic and a body and nothing else. -// -// The body crosses on stdin rather than in `-m`, so a message never reaches the -// process table and nothing has to be escaped on the way. +/** Sending. HEY composes and replies for the user rather than accepting a + * message: a reply's recipients are the server's to decide, which is why the + * reply command takes a topic and a body and nothing else. + * + * The body crosses on stdin rather than in `-m`, so a message never reaches the + * process table and nothing has to be escaped on the way. + */ function composeCommand(fields) { var values = fields || {} var thread = trimmed(values.threadId) @@ -333,8 +322,9 @@ function composeCommand(fields) { return command.concat(attachArgs(values.attachments)) } -// Saving has the same two shapes as sending, but a new draft needs no -// recipient. HEY keeps the body on stdin and answers the draft id. +/** Saving has the same two shapes as sending, but a new draft needs no + * recipient. HEY keeps the body on stdin and answers the draft id. + */ function draftCommand(fields) { var values = fields || {} var thread = trimmed(values.threadId) @@ -401,8 +391,6 @@ function labelsCommand() { return ["labels", "--json", "--all"] } -// ------------------------------------------------------------- the answers - function parseJson(text, fallback) { try { var parsed = JSON.parse(String(text || "")) @@ -412,9 +400,10 @@ function parseJson(text, fallback) { } } -// The envelope, unwrapped. `ok: false` is the CLI reporting a refusal it exited -// 0 for, so this is the check rather than the exit status — and an answer that -// is not JSON at all is a `hey` that failed before it could form one. +/** The envelope, unwrapped. `ok: false` is the CLI reporting a refusal it exited + * 0 for, so this is the check rather than the exit status — and an answer that + * is not JSON at all is a `hey` that failed before it could form one. + */ function payload(text) { var body = parseJson(text, null) if (!body || typeof body !== "object") { @@ -431,20 +420,22 @@ function envelopeNextPage(text) { return body && body.meta ? trimmed(body.meta.next_page) : "" } -// Whether what came back is a thread as HTML rather than the JSON envelope. -// `hey threads --html` writes a document; a build that does not serve one -// answers with the envelope, and the leading brace is the difference. +/** Whether what came back is a thread as HTML rather than the JSON envelope. + * `hey threads --html` writes a document; a build that does not serve one + * answers with the envelope, and the leading brace is the difference. + */ function isHtmlDocument(text) { var body = trimmed(text) return body !== "" && body.charAt(0) !== "{" } -// One posting, in the shape the client turns into a message. Field for field -// off HEY's own JSON, with the two names a thread goes by kept together. -// -// `seen` is absent rather than false on a posting nobody has read — the API -// omits an empty field — so unread is the absence of a true, not the presence -// of a false. +/** One posting, in the shape the client turns into a message. Field for field + * off HEY's own JSON, with the two names a thread goes by kept together. + * + * `seen` is absent rather than false on a posting nobody has read — the API + * omits an empty field — so unread is the absence of a true, not the presence + * of a false. + */ function posting(raw, boxKind) { var entry = raw || {} var contacts = Array.isArray(entry.contacts) ? entry.contacts : [] @@ -464,7 +455,7 @@ function posting(raw, boxKind) { topicId: topicIdFromUrl(entry.app_url), subject: trimmed(entry.name), snippet: trimmed(entry.summary), - // The name HEY shows in its own list. A newsletter sent by a machine at a + // Invariant: The name HEY shows in its own list. A newsletter sent by a machine at a // service's address is signed with the name the reader would recognise, // and that is the name the row should carry. from: { @@ -480,24 +471,24 @@ function posting(raw, boxKind) { } } -// The topic id, out of the posting's own app URL. HEY's box index answers a -// posting id and the address of the conversation it belongs to, and the number -// on the end of that address is the id every read of the thread takes. +/** The topic id, out of the posting's own app URL. HEY's box index answers a + * posting id and the address of the conversation it belongs to, and the number + * on the end of that address is the id every read of the thread takes. + */ function topicIdFromUrl(url) { var match = /\/topics\/(\d+)/.exec(trimmed(url)) return match ? match[1] : "" } -// `hey box`, `hey label` and `hey collection` all answer with a source and its -// postings; `hey search` answers with a flat list of threads. Both end up here -// as the same rows, so nothing downstream learns which command ran. +/** `hey box`, `hey label` and `hey collection` all answer with a source and its + * postings; `hey search` answers with a flat list of threads. Both end up here + * as the same rows, so nothing downstream learns which command ran. + */ function parseListing(data) { var rows = [] if (!data) return rows if (Array.isArray(data)) { - // A search result: a thread, its topic id beside it, and the messages that - // matched. There is no seen state on one, so a searched row claims none. for (var itemIndex = 0; itemIndex < data.length; itemIndex++) { var hit = data[itemIndex] || {} var messages = Array.isArray(hit.messages) ? hit.messages : [] @@ -515,7 +506,7 @@ function parseListing(data) { }, to: [], date: trimmed(hit.updated_at) || trimmed(newest.created_at), - // A search says nothing about what has been read, so a row from one + // Invariant: A search says nothing about what has been read, so a row from one // claims to be read rather than inventing a bold line the Imbox would // then disagree with. seen: true, @@ -582,12 +573,13 @@ function parseDraft(data) { } } -// What HEY offers after the page just read, in its own terms. A box and a label -// carry an opaque cursor; a search is numbered, so the number after this one is -// the answer. +/** What HEY offers after the page just read, in its own terms. A box and a label + * carry an opaque cursor; a search is numbered, so the number after this one is + * the answer. + */ function nextCursor(parsed, data, cursor, rowCount) { var query = parsed || parseQuery("") - // A scan that filtered on unseen read a fixed window rather than a page: past + // Invariant: A scan that filtered on unseen read a fixed window rather than a page: past // its end there is nothing to continue with, because continuing would page // the box while the filter kept discarding. if (query.unseen === true) return "" @@ -602,13 +594,14 @@ function nextCursor(parsed, data, cursor, rowCount) { return trimmed(data.next_page) } -// The rows this request is for, and the token that continues after them. -// -// HEY's page and the user's page size are two different numbers, and this is -// where they are reconciled: the command read one of HEY's pages, and the size -// the user configured decides how much of it a request gets. Load more asks for -// the same page again at a higher offset until it is used up, and only then -// moves on to HEY's next one. +/** The rows this request is for, and the token that continues after them. + * + * HEY's page and the user's page size are two different numbers, and this is + * where they are reconciled: the command read one of HEY's pages, and the size + * the user configured decides how much of it a request gets. Load more asks for + * the same page again at a higher offset until it is used up, and only then + * moves on to HEY's next one. + */ function pageOf(parsed, data, rows, maxResults, token) { var list = Array.isArray(rows) ? rows : [] var limit = boundedLimit(maxResults, 25) @@ -624,8 +617,9 @@ function pageOf(parsed, data, rows, maxResults, token) { return { rows: visible, nextPageToken: next, total: list.length } } -// The rows a query actually wanted. Only the unseen filter narrows anything; -// everything else is served by the command that ran. +/** The rows a query actually wanted. Only the unseen filter narrows anything; + * everything else is served by the command that ran. + */ function filterRows(parsed, rows) { var list = Array.isArray(rows) ? rows : [] if (!parsed || parsed.unseen !== true) return list @@ -636,10 +630,11 @@ function filterRows(parsed, rows) { return output } -// `hey labels`, as the shape the sidebar reads. HEY calls them folders and -// addresses them by id, so the id is what `rawName` carries — selecting one in -// the sidebar has to produce `label:`, which is the only thing `hey label` -// takes. +/** `hey labels`, as the shape the sidebar reads. HEY calls them folders and + * addresses them by id, so the id is what `rawName` carries — selecting one in + * the sidebar has to produce `label:`, which is the only thing `hey label` + * takes. + */ function parseLabels(data) { var output = [] var list = Array.isArray(data) ? data : [] @@ -661,9 +656,10 @@ function parseLabels(data) { return output } -// `hey accounts list`, as this mailbox's address. The list holds an "all" row -// that is a filter rather than an account, and the real ones beside it; the -// first real one is the identity this plugin signed in as. +/** `hey accounts list`, as this mailbox's address. The list holds an "all" row + * that is a filter rather than an account, and the real ones beside it; the + * first real one is the identity this plugin signed in as. + */ function parseAccountAddress(data) { var list = Array.isArray(data) ? data : [] for (var itemIndex = 0; itemIndex < list.length; itemIndex++) { @@ -680,9 +676,10 @@ function isAuthenticated(data) { return status.authenticated === true && status.expired !== true } -// The thread's entries, as one HTML document or as text. `--html` gives the -// sender's own markup, which is what the reader is built for; the JSON envelope -// a build without it answers with carries the same message as text. +/** The thread's entries, as one HTML document or as text. `--html` gives the + * sender's own markup, which is what the reader is built for; the JSON envelope + * a build without it answers with carries the same message as text. + */ function parseThread(text) { if (isHtmlDocument(text)) return { html: String(text || ""), text: "" } @@ -694,21 +691,16 @@ function parseThread(text) { var body = trimmed((entries[itemIndex] || {}).body) if (body !== "") parts.push(body) } - // Oldest first, which is the order HEY serves and the order a conversation + // Invariant: Oldest first, which is the order HEY serves and the order a conversation // reads in. The separator is what the CLI's own reader draws between entries. return { html: "", text: parts.join("\n\n───\n\n") } } -// The web address of one thread. HEY's box index hands over the conversation's -// own URL, and this rebuilds it for a row that came from a search. -// -// There is no box counterpart on purpose. HEY has a URL per box and none for a -// search or a label, so one would answer the Imbox for every mailbox that is -// not the Imbox — see the `webBox` capability, which is off for this provider. var WEB_BASE = "https://app.hey.com" -// The mailbox itself. HEY opens on the Imbox, which is where a link out of a -// settings row should land whichever mailbox the panel happens to be showing. +/** The mailbox itself. HEY opens on the Imbox, which is where a link out of a + * settings row should land whichever mailbox the panel happens to be showing. + */ function webHomeUrl() { return WEB_BASE } @@ -718,21 +710,21 @@ function webMessageUrl(id) { return topic === "" ? WEB_BASE : WEB_BASE + "/topics/" + topic } -// ----------------------------------------------------------------- safety - -// A bearer token, a cookie, or the URL either was pasted into. `hey` prints -// neither in the ordinary course of things, but a verbose failure could — and a -// notice is a place a stranger can read. +/** A bearer token, a cookie, or the URL either was pasted into. `hey` prints + * neither in the ordinary course of things, but a verbose failure could — and a + * notice is a place a stranger can read. + */ function redact(text) { return String(text === undefined || text === null ? "" : text) .replace(/(token|cookie|secret|password)([=:]\s*)\S+/gi, "$1$2[redacted]") .replace(/\bBearer\s+\S+/gi, "Bearer [redacted]") } -// What a failed invocation says. `hey` reports its own refusals in the -// envelope; a non-zero exit with nothing to read is the process itself. +/** What a failed invocation says. `hey` reports its own refusals in the + * envelope; a non-zero exit with nothing to read is the process itself. + */ function commandError(status, text, detail, fallback) { - // The envelope's own message when there is one. Read from the JSON directly + // Invariant: The envelope's own message when there is one. Read from the JSON directly // rather than through `payload`, whose "this could not be read" is about the // shape of the answer — and would shadow the real reason, which for a // command that never reached HEY is on stderr. diff --git a/ui/providers/HeyClient.qml b/ui/providers/HeyClient.qml index a177d5459..93dcbe653 100644 --- a/ui/providers/HeyClient.qml +++ b/ui/providers/HeyClient.qml @@ -2,7 +2,7 @@ import QtQuick import "HeyCli.js" as Cli -// Presentation adapter. Rust owns HEY commands, parsing and network work. +// Invariant: Presentation adapter. Rust owns HEY commands, parsing and network work. Item { id: root @@ -92,12 +92,13 @@ Item { return handle } - // The counted members of a conversation, for the reader's conversation rail. - // - // Always empty, and HEY is never asked: a HEY row already *is* a conversation - // and carries no member ids, so its `thread` block reports a count of 0 — - // unknown — and the rail draws nothing. The body on screen is the whole - // conversation here, which is the thing the rail would otherwise be for. + /** The counted members of a conversation, for the reader's conversation rail. + * + * Always empty, and HEY is never asked: a HEY row already *is* a conversation + * and carries no member ids, so its `thread` block reports a count of 0 — + * unknown — and the rail draws nothing. The body on screen is the whole + * conversation here, which is the thing the rail would otherwise be for. + */ function getSummaries(ids, callback) { var handle = newHandle() Qt.callLater(function() { @@ -107,13 +108,14 @@ Item { return handle } - // A whole page with no round trips at all: the listing that produced these - // ids carried every field a row needs, so this is the cache answering. - // - // Deferred rather than answered on the spot even though the answer is in - // hand. Every caller is written against a callback that arrives later, and - // running one partway through the function that started it is a re-entry the - // Gmail client never produces. + /** A whole page with no round trips at all: the listing that produced these + * ids carried every field a row needs, so this is the cache answering. + * + * Deferred rather than answered on the spot even though the answer is in + * hand. Every caller is written against a callback that arrives later, and + * running one partway through the function that started it is a re-entry the + * Gmail client never produces. + */ function getMessages(ids, full, callback, existingHandle, progress) { var handle = existingHandle || newHandle() var list = Array.isArray(ids) ? ids : [] @@ -197,10 +199,11 @@ Item { return handle } - // HEY serves a thread's files through a command of its own, which saves them - // to disk rather than handing over their octets. Nothing asks for one: the - // composed payload declares no attachment parts, so the reader lists none and - // the invitation reader never finds a part to fetch. + /** HEY serves a thread's files through a command of its own, which saves them + * to disk rather than handing over their octets. Nothing asks for one: the + * composed payload declares no attachment parts, so the reader lists none and + * the invitation reader never finds a part to fetch. + */ function getAttachment(messageId, attachmentId, callback) { var handle = newHandle() if (typeof callback !== "function") return handle @@ -211,9 +214,6 @@ Item { return handle } - // HEY's labels, in the shape the sidebar reads them in. Counts are left at - // zero: there is no command that answers one, and the sidebar is drawn before - // anyone has asked for a number on it. function getLabels(callback) { return backendRead("hey.labels", {}, callback, newHandle()) } @@ -224,8 +224,9 @@ Item { }, newHandle()) } - // HEY sends as the address it is signed in as. Returned in the same shape as - // Gmail's aliases so everything above the provider boundary stays neutral. + /** HEY sends as the address it is signed in as. Returned in the same shape as + * Gmail's aliases so everything above the provider boundary stays neutral. + */ function getSendAs(callback) { if (typeof callback !== "function") return newHandle() if (address !== "") { @@ -245,12 +246,11 @@ Item { }) } - // --------------------------------------------------------------- writes - - // `MailAccount` asks in Gmail's vocabulary whichever provider it holds, so - // the label ids arrive here and become HEY's own verbs. A pair HEY has no - // verb for is nothing to do rather than something close to it — the panel - // already hides the buttons this provider does not declare. + /** `MailAccount` asks in Gmail's vocabulary whichever provider it holds, so + * the label ids arrive here and become HEY's own verbs. A pair HEY has no + * verb for is nothing to do rather than something close to it — the panel + * already hides the buttons this provider does not declare. + */ function modifyMessage(id, addLabelIds, removeLabelIds, callback) { return batchModify([id], addLabelIds, removeLabelIds, callback) } @@ -260,8 +260,9 @@ Item { return act(verb, ids, callback) } - // HEY's labels are HEY's own. The capability is off, so no button reaches - // these; they exist so every client answers the same calls. + /** HEY's labels are HEY's own. The capability is off, so no button reaches + * these; they exist so every client answers the same calls. + */ function createLabel(name, callback) { return refuseLabelChange(callback) } function renameLabel(id, name, callback) { return refuseLabelChange(callback) } function deleteLabel(id, callback) { return refuseLabelChange(callback) } @@ -271,11 +272,12 @@ Item { return newHandle() } - // One id or a list of them. A HEY message id is `:`, and a - // conversation's members all share the topic — so a list arriving from a row - // that stands for a conversation can name the same posting more than once. - // `Cli.actionCommand` already keeps each posting once, which is why the list - // is handed straight to it rather than wrapped in another array. + /** One id or a list of them. A HEY message id is `:`, and a + * conversation's members all share the topic — so a list arriving from a row + * that stands for a conversation can name the same posting more than once. + * `Cli.actionCommand` already keeps each posting once, which is why the list + * is handed straight to it rather than wrapped in another array. + */ function trashMessage(id, callback) { return act("trash", Array.isArray(id) ? id : [id], callback) } @@ -284,8 +286,9 @@ Item { return act("untrash", Array.isArray(id) ? id : [id], callback) } - // One verb, however many threads: every HEY command takes a list of ids, so a - // batch is one invocation rather than one per message. + /** One verb, however many threads: every HEY command takes a list of ids, so a + * batch is one invocation rather than one per message. + */ function act(verb, ids, callback) { var handle = newHandle() if (usesBackend()) { @@ -298,10 +301,11 @@ Item { return handle } - // What this client believed about a thread, after it has been changed. Only - // the seen state is kept here and only two verbs move it, so the row is - // corrected rather than dropped: dropping it would leave the reader, which is - // already open on that message, with no headers on the next redraw. + /** What this client believed about a thread, after it has been changed. Only + * the seen state is kept here and only two verbs move it, so the row is + * corrected rather than dropped: dropping it would leave the reader, which is + * already open on that message, with no headers on the next redraw. + */ function forget(verb, ids) { if (verb !== "markRead" && verb !== "markUnread") return var list = Array.isArray(ids) ? ids : [ids] @@ -318,14 +322,13 @@ Item { messageResources = updated } - // ----------------------------------------------------------------- send - - // `MailAccount` builds the same payload for every provider: a base64url `raw` - // field, because that is what Gmail's send endpoint takes. HEY takes neither - // a raw message nor, for a reply, a recipient list — it decides who a reply - // goes to, which is the right answer and not one this plugin could improve - // on. So the message is taken apart again and handed over as the fields the - // command has. + /** `MailAccount` builds the same payload for every provider: a base64url `raw` + * field, because that is what Gmail's send endpoint takes. HEY takes neither + * a raw message nor, for a reply, a recipient list — it decides who a reply + * goes to, which is the right answer and not one this plugin could improve + * on. So the message is taken apart again and handed over as the fields the + * command has. + */ function messageParams(payload, draft) { var value = payload || {} var parameters = { raw: String(value.raw || ""), threadId: String(value.threadId || ""), diff --git a/ui/providers/Imap.js b/ui/providers/Imap.js index cb37a8679..d0a7794e2 100644 --- a/ui/providers/Imap.js +++ b/ui/providers/Imap.js @@ -1,6 +1,6 @@ .pragma library -// Provider presentation only. NativeDomain.js supplies all mail capabilities +// Invariant: Provider presentation only. NativeDomain.js supplies all mail capabilities // and mailbox queries; providers.resolve builds dynamic queries in Rust. var ID = "imap" diff --git a/ui/providers/ImapAuth.qml b/ui/providers/ImapAuth.qml index c69c19502..02f054d57 100644 --- a/ui/providers/ImapAuth.qml +++ b/ui/providers/ImapAuth.qml @@ -4,17 +4,8 @@ import Quickshell.Io import "ImapProtocol.js" as Imap -// An IMAP account's sign-in, which is a server address and a password. -// -// It is the counterpart to `AuthManager`, and deliberately the same shape from -// outside: `MailAccount` asks either of them whether it is `loggedIn`, and asks -// for a credential with one call whose callback takes `(value, error)`. What -// differs is everything inside — there is no browser, no token to refresh and -// nothing that expires. -// -// Where the secret lives follows the same rule as the refresh token: GNOME -// Keyring, written over stdin so it never reaches the process table, and keyed -// by account so two mailboxes cannot overwrite each other. +// Invariant: Passwords travel through the native credential API, never argv, and +// are scoped by account. Server verification must finish before a credential is stored. Item { id: root @@ -26,20 +17,15 @@ Item { property var backend: null property var platform: null - // Which mailbox this signs in. Unlike Gmail's, an IMAP account knows its own - // address from the moment it is created — the user typed it — so this is set - // before anything is asked of the server rather than after a profile read. property string accountId: "" - // Server settings, pushed down from the account entry. Held as the validated - // shape rather than as whatever was in the file. property var settings: Imap.normalizeSettings(null) readonly property string authMode: "password" readonly property bool configured: Imap.validateSettings(settings).ok - // The password, once the keyring has answered. Held in this process for as + // Performance: The password, once the keyring has answered. Held in this process for as // long as the account exists, exactly as the access token is: every request // needs it, and a keyring round trip per request would be both slow and a // stream of authorisation prompts on some setups. @@ -47,8 +33,6 @@ Item { property bool passwordChecked: false readonly property bool loggedIn: configured && password !== "" - // The same three names `AuthManager` exposes, because `MailAccount` reads - // them without knowing which provider it has. readonly property bool credentialsPresent: configured property bool loginBusy: false property int sessionGeneration: 0 @@ -60,7 +44,6 @@ Item { readonly property bool sessionBusy: credentialLookupBusy || credentialWriteBusy property string lastError: "" - // Native credential storage and network transport are backend capabilities. readonly property var requiredTools: [] property var missingTools: [] property bool toolsChecked: true @@ -84,13 +67,14 @@ Item { credentialWaiters = [] for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { try { pending[itemIndex](value || "", safeError(error)) } - catch (error) { /* consumers own their callback errors */ } + catch (error) { /* Invariant: one consumer must not prevent later waiters from completing. */ } } } - // The one entry point the transport uses. Hands back "user:password" — the - // single credential field the native client consumes — rather than the two halves, so nothing - // downstream has to know how they are joined. + /** The one entry point the transport uses. Hands back "user:password" — the + * single credential field the native client consumes — rather than the two halves, so nothing + * downstream has to know how they are joined. + */ function withCredentials(callback) { if (typeof callback !== "function") return if (!configured) { @@ -153,8 +137,6 @@ Item { var value = String(line || "") if (value === "") { finishWaiters("", "No password saved for this mailbox. Sign in again") - // Only a mailbox that is otherwise ready to go is worth complaining - // about: an account still being typed into has no password by design. if (configured) sessionUnavailable("Sign in to this mailbox") return } @@ -163,10 +145,11 @@ Item { loginSucceeded() } - // Called by the setup page once the user has filled the form in. The password - // is verified by using it — a mailbox that answers a NOOP is a mailbox that - // will answer everything else — rather than by being written down first and - // failing silently later. + /** Called by the setup page once the user has filled the form in. The password + * is verified by using it — a mailbox that answers a NOOP is a mailbox that + * will answer everything else — rather than by being written down first and + * failing silently later. + */ function signIn(secret) { if (loginBusy || credentialWriteBusy) return false if (platform && platform.canAccessCredentials === false) { @@ -177,7 +160,7 @@ Item { lastError = "Missing " + missingTools.join(", ") return false } - // Pasting from a line can include its trailing line break. Remove only + // Invariant: Pasting from a line can include its trailing line break. Remove only // that suffix; silently changing controls inside a password would verify // and save a different secret from the one the user entered. var value = String(secret || "").replace(/[\r\n]+$/, "") @@ -202,7 +185,6 @@ Item { return true } - // The client owns the transport, so it performs the check and reports back. signal verifyRequested(var settings, string credentials) function completeSignIn(ok, error, generation) { @@ -265,19 +247,21 @@ Item { loggedOut() } - // Kept so `MailAccount` can call the same thing on either provider. An IMAP - // password does not expire, so there is nothing to invalidate — but a server - // that has started rejecting it should not be asked a hundred more times - // with the same value. + /** Kept so `MailAccount` can call the same thing on either provider. An IMAP + * password does not expire, so there is nothing to invalidate — but a server + * that has started rejecting it should not be asked a hundred more times + * with the same value. + */ function invalidateAccessToken() { password = "" passwordChecked = false } - // The Gmail manager has these; an IMAP account reaches neither, and - // `MailAccount` should not have to ask which provider it holds before - // calling one. - function beginLogin() { /* the setup form drives sign-in, not a browser */ } + /** The Gmail manager has these; an IMAP account reaches neither, and + * `MailAccount` should not have to ask which provider it holds before + * calling one. + */ + function beginLogin() { } function cancelLogin() { sessionGeneration++ loginBusy = false @@ -286,9 +270,6 @@ Item { onAccountIdChanged: { cancelLogin() - // A different mailbox has a different password. Dropping the one in memory - // is what stops an account rename from leaving the previous account's - // credential in front of the new one's server. password = "" passwordChecked = false lookupHandled = false diff --git a/ui/providers/ImapProtocol.js b/ui/providers/ImapProtocol.js index 8093efafb..7e717ea97 100644 --- a/ui/providers/ImapProtocol.js +++ b/ui/providers/ImapProtocol.js @@ -2,42 +2,15 @@ .import "../account/Aliases.js" as Aliases -// The IMAP protocol, and nothing else. No transport lives here — `ImapClient.qml` -// owns the process that speaks to the server — and no message format lives here -// either: an RFC 822 message is `Message.js`'s subject, and this file hands one -// over as the raw bytes it arrived as. -// -// What this file does own is every string sent to a server and every decision -// about what came back, which is what the node tests can reach without a -// compositor or a mailbox. -// -// ## Why the responses arrive as a byte string -// -// IMAP measures a literal in octets: -// -// * 1 FETCH (UID 42 BODY[] {2048} -// <2048 bytes>) -// -// Read as UTF-8 text, 2048 octets of a message with an accent in it is fewer -// than 2048 characters, and the parser walks off the end of the literal into -// the middle of the next response. So the transport base64-encodes the whole -// conversation, and `decodeResponse` turns it back into a string with one -// character per octet. Counting characters is then exactly counting octets, -// binary attachment data survives the pipe, and nothing in the response can -// contain the newline the pipe splits on. - -// ------------------------------------------------------------------ servers +// Invariant: Rust owns live IMAP transport and mail operations. This library holds +// setup rules and protocol reference helpers exercised by the JavaScript tests. +// Protocol reference parsers use one character per octet for IMAP literal lengths. var DEFAULT_IMAP_PORT = 993 var DEFAULT_SMTP_PORT = 465 -// Known services, so the common case is an address and a password rather than -// four hostnames. The key is the mail domain; `presetFor` also matches the -// aliases, which is what makes hotmail.com find the Outlook entry. -// -// Every one of these is TLS on connect (imaps/smtps) rather than STARTTLS: the -// providers below all offer it, and a client that negotiates upward can be -// stripped back down by whatever is between it and the server. +// Invariant: Presets select provider-supported ports; the native backend enforces +// the required TLS mode for each connection. var PRESETS = [ { id: "gmail", @@ -45,7 +18,7 @@ var PRESETS = [ domains: ["gmail.com", "googlemail.com"], imapHost: "imap.gmail.com", imapPort: 993, smtpHost: "smtp.gmail.com", smtpPort: 465, - // Google turned off password sign-in for IMAP. An app password works only + // Invariant: Google turned off password sign-in for IMAP. An app password works only // with 2-Step Verification on, and that is the sentence users need to see // before they go looking for a setting that is not there — with the page // that walks them through it, because "app password" is not a term anyone @@ -109,7 +82,7 @@ var PRESETS = [ imapHost: "imap.gmx.com", imapPort: 993, smtpHost: "mail.gmx.com", smtpPort: 465 }, - // Here for the note rather than the servers: imap.163.com and smtp.163.com + // Invariant: Here for the note rather than the servers: imap.163.com and smtp.163.com // on the standard ports are exactly what `imap.` would have guessed. // What no address can imply is that the mailbox refuses the account // password, and a user who does not know that is told only that they were @@ -138,7 +111,7 @@ var PRESETS = [ id: "proton", name: "Proton Mail", domains: ["proton.me", "protonmail.com", "pm.me"], - // Proton speaks IMAP only through the Bridge, which listens on loopback + // Invariant: Proton speaks IMAP only through the Bridge, which listens on loopback // with STARTTLS and a self-signed certificate on this machine. imapHost: "127.0.0.1", imapPort: 1143, smtpHost: "127.0.0.1", smtpPort: 1025, @@ -167,10 +140,11 @@ function presetFor(address) { return null } -// What to put in the form before the user types anything. A domain nobody has -// heard of still gets a guess, because `imap.` is right far more often -// than an empty field is useful — and a wrong guess is visible and editable, -// which a blank one is not. +/** What to put in the form before the user types anything. A domain nobody has + * heard of still gets a guess, because `imap.` is right far more often + * than an empty field is useful — and a wrong guess is visible and editable, + * which a blank one is not. + */ function suggestedSettings(address) { var preset = presetFor(address) var domain = domainOf(address) @@ -184,8 +158,6 @@ function suggestedSettings(address) { insecure: preset.insecure === true, preset: preset.id, note: String(preset.note || ""), - // Where the note's instruction is spelled out, for the providers whose - // password is not the one the user knows. Empty for the rest. guideUrl: preset.guide ? String(preset.guide.url || "") : "", guideLabel: preset.guide ? String(preset.guide.label || "") : "" } @@ -204,14 +176,14 @@ function suggestedSettings(address) { } } -// A hostname, not a URL and not a host:port pair. Everything here ends up in a -// URL handed to the transport, so a value carrying a slash, a space or an "@" -// could point the authenticated client somewhere else entirely. +/** A hostname, not a URL and not a host:port pair. Everything here ends up in a + * URL handed to the transport, so a value carrying a slash, a space or an "@" + * could point the authenticated client somewhere else entirely. + */ function isValidHost(value) { var host = trimmed(value) if (host === "" || host.length > 253) return false if (/[\s/\\@:?#"'<>]/.test(host)) return false - // An IP literal is legitimate — Proton Bridge is one. if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true return /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(host) } @@ -223,12 +195,13 @@ function normalizedPort(value, fallback) { return port } -// A host name is case-insensitive, and lowercasing it here is what keeps every -// later reading of it the same one. `isLoopback` already compares lowercased, -// so a user who typed "LocalHost" was judged local up here and then failed to -// match the transport's own loopback patterns further down — which meant the -// local bridge, the one server that legitimately speaks plaintext, was the one -// refused for not offering TLS. +/** A host name is case-insensitive, and lowercasing it here is what keeps every + * later reading of it the same one. `isLoopback` already compares lowercased, + * so a user who typed "LocalHost" was judged local up here and then failed to + * match the transport's own loopback patterns further down — which meant the + * local bridge, the one server that legitimately speaks plaintext, was the one + * refused for not offering TLS. + */ function normalizeSettings(raw) { var values = raw || {} return { @@ -238,15 +211,14 @@ function normalizeSettings(raw) { smtpPort: normalizedPort(values.smtpPort, DEFAULT_SMTP_PORT), username: trimmed(values.username), aliases: Aliases.parse(values.aliases), - // Loopback only. A plaintext session to anywhere else is a password on the - // wire, and the one legitimate case — a local bridge — never leaves the - // machine. + // Invariant: The local certificate trust override applies only to loopback. + // Rust still determines and enforces the TLS mode. insecure: values.insecure === true && isLoopback(values.imapHost), send: normalizeSend(values.send) } } -// How a message leaves: SMTP, or Microsoft Graph's sendMail for a Microsoft +// Invariant: How a message leaves: SMTP, or Microsoft Graph's sendMail for a Microsoft // 365 tenant that has switched authenticated SMTP off. Graph takes the same // MIME the SMTP path builds and files the sent copy itself. Empty or missing // is SMTP, which is what every mailbox already on disk means. @@ -265,10 +237,11 @@ function isLoopback(host) { return name === "127.0.0.1" || name === "::1" || name === "localhost" } -// Turn the setup form's visible fields into the same validated shape every -// client call consumes. The server, not the mailbox's email domain, decides -// whether this is a local bridge: Proton can serve addresses on custom domains -// that never select its address preset. +/** Turn the setup form's visible fields into the same validated shape every + * client call consumes. The server, not the mailbox's email domain, decides + * whether this is a local bridge: Proton can serve addresses on custom domains + * that never select its address preset. + */ function setupSettings(raw) { var values = raw || {} return normalizeSettings({ @@ -283,8 +256,9 @@ function setupSettings(raw) { }) } -// Reported one at a time and in the order the form reads, so the message names -// the first field the user has to go back to rather than all of them at once. +/** Reported one at a time and in the order the form reads, so the message names + * the first field the user has to go back to rather than all of them at once. + */ function validateSettings(raw) { var settings = normalizeSettings(raw) if (settings.username === "") return { ok: false, error: "Add the username for this mailbox" } @@ -295,21 +269,8 @@ function validateSettings(raw) { return { ok: true, error: "", settings: settings } } -// The URL the transport connects with. Built here rather than in the shell -// script so the host has been through `isValidHost` on the way, and so the -// tests can see what a given account would dial. -// Which ports mean "connect in the clear, then upgrade". Naming the STARTTLS -// ports rather than the TLS ones is the whole of the difference between this -// and asking whether the port is 993: a server on 9993, or on whatever a -// hosting panel picked, speaks TLS from the first byte and has no STARTTLS to -// offer, so a client that inferred STARTTLS from "not 993" would simply stop -// connecting to it. These three are the ports the RFCs assign to the upgrade, -// and a server on any other one is dialled the way it was before this list -// existed. -// -// The upgrade is not optional once it is chosen: `mail-transport.sh` adds -// `ssl-reqd` to every non-loopback plaintext scheme, so a server that turns -// out not to offer STARTTLS is refused rather than spoken to in the clear. +// Invariant: These reference URL builders encode mailbox names as one path segment. +// The live native transport independently validates its destination. var STARTTLS_IMAP_PORTS = [143] var STARTTLS_SMTP_PORTS = [25, 587] @@ -328,9 +289,6 @@ function imapUrl(settings, folder) { var scheme = plain ? "imap" : "imaps" var url = scheme + "://" + values.imapHost + ":" + values.imapPort var box = trimmed(folder) - // The mailbox is a path segment, so anything that could end the segment or - // start a query has to be percent-encoded. Gmail's "[Gmail]/All Mail" is the - // everyday case with characters in it. if (box !== "") url += "/" + encodeURIComponent(box) return url } @@ -338,7 +296,7 @@ function imapUrl(settings, folder) { function smtpUrl(settings) { var values = normalizeSettings(settings) if (!isValidHost(values.smtpHost)) return "" - // IMAP and SMTP may name different hosts. The shared local-transport flag + // Invariant: IMAP and SMTP may name different hosts. The shared local-transport flag // cannot let a loopback IMAP server downgrade a remote SMTP connection. var local = values.insecure && isLoopback(values.smtpHost) var plain = local || usesStartTls(values.smtpPort, STARTTLS_SMTP_PORTS) @@ -346,13 +304,12 @@ function smtpUrl(settings) { return scheme + "://" + values.smtpHost + ":" + values.smtpPort } -// ------------------------------------------------------------- the query DSL -// -// `Provider.js` hands down strings like "folder:INBOX UNSEEN". They are opaque -// everywhere else — a cache key and nothing more — and this is the only reader. -// -// A folder may contain spaces ("[Gmail]/All Mail", "Sent Items"), so it is -// quoted when it does: folder:"Sent Items" UNSEEN. +/** `Provider.js` hands down strings like "folder:INBOX UNSEEN". They are opaque + * everywhere else — a cache key and nothing more — and this is the only reader. + * + * A folder may contain spaces ("[Gmail]/All Mail", "Sent Items"), so it is + * quoted when it does: folder:"Sent Items" UNSEEN. + */ function parseQuery(query) { var text = trimmed(query) @@ -364,25 +321,24 @@ function parseQuery(query) { folder = match[1] !== undefined ? match[1].replace(/\\(.)/g, "$1") : match[2] criteria = trimmed(match[3]) } else if (text !== "") { - // Not addressed to a folder at all. Treating it as criteria against the - // inbox is what a bare search term means, and is what the search box - // produces before `Provider.searchQuery` has shaped it. criteria = text } return { folder: folder === "" ? "INBOX" : folder, criteria: criteria } } -// A folder name from a query may be a SPECIAL-USE placeholder — "\Sent" rather -// than whatever this server calls its sent mail. `resolveFolder` swaps in the -// real name once a LIST has told us one. +/** A folder name from a query may be a SPECIAL-USE placeholder — "\Sent" rather + * than whatever this server calls its sent mail. `resolveFolder` swaps in the + * real name once a LIST has told us one. + */ function isSpecialUse(name) { return trimmed(name).charAt(0) === "\\" } -// Falls back to the placeholder's bare word ("\Sent" → "Sent"), which is the -// right guess on a server that answered LIST without any SPECIAL-USE flags at -// all — most of them, still. +/** Falls back to the placeholder's bare word ("\Sent" → "Sent"), which is the + * right guess on a server that answered LIST without any SPECIAL-USE flags at + * all — most of them, still. + */ function resolveFolder(name, folders) { var wanted = trimmed(name) if (!isSpecialUse(wanted)) return wanted @@ -392,15 +348,14 @@ function resolveFolder(name, folders) { return wanted.substring(1) } -// ------------------------------------------------------------- message ids -// -// Gmail's message id is unique across the whole mailbox. An IMAP UID is unique -// only within one folder, and is reissued by a server that has had its -// UIDVALIDITY reset — so "42" on its own names nothing, and two folders each -// holding a message 42 would collide in the body cache and in every list. -// -// The id therefore carries both. The UID is always digits, so splitting on the -// first colon is unambiguous however many colons a folder name contains. +/** Gmail's message id is unique across the whole mailbox. An IMAP UID is unique + * only within one folder, and is reissued by a server that has had its + * UIDVALIDITY reset — so "42" on its own names nothing, and two folders each + * holding a message 42 would collide in the body cache and in every list. + * + * The id therefore carries both. The UID is always digits, so splitting on the + * first colon is unambiguous however many colons a folder name contains. + */ function messageId(uid, folder) { var number = Math.floor(Number(uid)) @@ -414,9 +369,10 @@ function parseMessageId(id) { return { uid: Math.floor(Number(match[1])), folder: match[2] } } -// Grouped by folder, because every command this client sends operates on the -// folder the connection has selected: one round trip per folder rather than -// one per message, and a batch spanning two folders is two conversations. +/** Grouped by folder, because every command this client sends operates on the + * folder the connection has selected: one round trip per folder rather than + * one per message, and a batch spanning two folders is two conversations. + */ function groupByFolder(ids, maxPerGroup) { var list = Array.isArray(ids) ? ids : [] var order = [] @@ -445,26 +401,26 @@ function groupByFolder(ids, maxPerGroup) { return output } -// ----------------------------------------------------------------- quoting -// -// Every string that reaches a server goes through one of these. An unquoted -// folder name with a space in it is a syntax error; one with a quote in it is -// a way to end the argument early and append a command of somebody's choosing. +/** Every string that reaches a server goes through one of these. An unquoted + * folder name with a space in it is a syntax error; one with a quote in it is + * a way to end the argument early and append a command of somebody's choosing. + */ function quote(value) { return "\"" + String(value === undefined || value === null ? "" : value) - // A backslash and a double quote are the only two characters IMAP escapes. + // Invariant: A backslash and a double quote are the only two characters IMAP escapes. .replace(/\\/g, "\\\\") .replace(/"/g, "\\\"") - // CR and LF end a command. There is no escape for them inside a quoted + // Invariant: CR and LF end a command. There is no escape for them inside a quoted // string — the protocol's answer is a literal — so they are dropped: a // folder name or a search term containing one is not a thing worth // refusing to search over. .replace(/[\r\n]+/g, " ") + "\"" } -// A sequence set: "1,2,3" or "1:10". Built from numbers only, so nothing that -// arrived in a response can extend a command. +/** A sequence set: "1,2,3" or "1:10". Built from numbers only, so nothing that + * arrived in a response can extend a command. + */ function sequenceSet(uids) { var list = Array.isArray(uids) ? uids : [] var output = [] @@ -476,39 +432,39 @@ function sequenceSet(uids) { return output.join(",") } -// ---------------------------------------------------------------- commands -// -// Each returns the command *without* a tag: the transport is curl, which sends +// Invariant: Each returns the command *without* a tag: the transport is curl, which sends // one custom command per request and tags it itself. -// What a list row needs, and no more. BODY.PEEK rather than BODY so reading +// Invariant: What a list row needs, and no more. BODY.PEEK rather than BODY so reading // the list does not mark everything in it as seen — the single most common way // a hand-rolled IMAP client ruins a mailbox. var LIST_HEADERS = "HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID REPLY-TO LIST-UNSUBSCRIBE)" -// curl holds one IMAP response line in a 64 KiB buffer. SEARCH answers with -// every matching UID on one line, so an unbounded `UID SEARCH ALL` fails with -// CURLE_TOO_LARGE once a folder has around ten thousand messages. FETCH puts -// each UID on its own response line instead, which makes this the stable -// snapshot every listing starts from. +/** curl holds one IMAP response line in a 64 KiB buffer. SEARCH answers with + * every matching UID on one line, so an unbounded `UID SEARCH ALL` fails with + * CURLE_TOO_LARGE once a folder has around ten thousand messages. FETCH puts + * each UID on its own response line instead, which makes this the stable + * snapshot every listing starts from. + */ function uidListCommand() { return "UID FETCH 1:* (UID)" } -// An interactive search does not need every UID before it can begin: the UID -// of the last message by sequence number is the mailbox's upper boundary. The -// obvious `UID FETCH *:*` cannot be used through curl, which takes a FETCH of -// one message for a body fetch and routes its untagged answer where the -// transport never sees it. A range that starts with a number passes through -// intact; the count it starts from comes from STATUS on an earlier connection, -// and running the range up to `*` rather than back to the count keeps a -// message delivered between the two from sitting above the ceiling unseen. +/** An interactive search does not need every UID before it can begin: the UID + * of the last message by sequence number is the mailbox's upper boundary. The + * obvious `UID FETCH *:*` cannot be used through curl, which takes a FETCH of + * one message for a body fetch and routes its untagged answer where the + * transport never sees it. A range that starts with a number passes through + * intact; the count it starts from comes from STATUS on an earlier connection, + * and running the range up to `*` rather than back to the count keeps a + * message delivered between the two from sitting above the ceiling unseen. + */ function topUidCommand(count) { var messageCount = Math.floor(Number(count)) return isFinite(messageCount) && messageCount >= 1 ? "FETCH " + messageCount + ":* (UID)" : "" } -// A SEARCH over a known UID snapshot can be split without using message +// Invariant: A SEARCH over a known UID snapshot can be split without using message // sequence numbers. UIDs do not move when another client expunges a message, // and a message delivered after the snapshot has a UID above its last one. // @@ -518,11 +474,12 @@ function topUidCommand(count) { // at most 4096 existing messages lie between them. var SEARCH_WINDOW = 4096 -// One newest-first numeric UID range for an interactive search. A UID range of -// width 4096 can contain at most 4096 messages, so its one-line SEARCH answer -// stays bounded without first downloading the UID of every message. UIDs do -// not move when another client expunges mail, and the ceiling was read before -// the first range, so new delivery cannot enter it either. +/** One newest-first numeric UID range for an interactive search. A UID range of + * width 4096 can contain at most 4096 messages, so its one-line SEARCH answer + * stays bounded without first downloading the UID of every message. UIDs do + * not move when another client expunges mail, and the ceiling was read before + * the first range, so new delivery cannot enter it either. + */ function searchWindow(criteria, highestUid) { var text = trimmed(criteria) var last = Math.floor(Number(highestUid)) @@ -555,7 +512,7 @@ function searchCommands(criteria, snapshot, highestUid) { var commands = [] if (text === "" || uids.length === 0) return commands - // The first numeric window of an interactive search has already settled. + // Invariant: The first numeric window of an interactive search has already settled. // When it did not fill the page, its next lower UID is handed in here so the // snapshot fallback neither searches nor reports that newest prefix twice. var ceiling = Math.floor(Number(highestUid)) @@ -568,7 +525,7 @@ function searchCommands(criteria, snapshot, highestUid) { } if (uids.length === 0) return commands - // Interactive search can paint a page before every window has answered only + // Invariant: Interactive search can paint a page before every window has answered only // if no later answer can put a newer message in front of it. UIDs grow with // delivery, so walking the stable snapshot backwards makes every completed // window a final prefix of the result rather than a provisional one. @@ -581,10 +538,11 @@ function searchCommands(criteria, snapshot, highestUid) { return commands } -// The visible page after some or all SEARCH windows have answered. During a -// streamed search `hasUnscanned` keeps pagination alive even if the rows found -// so far happen to end exactly at the page boundary. The estimate is then a -// lower bound — Model already calls provider totals "about" for this reason. +/** The visible page after some or all SEARCH windows have answered. During a + * streamed search `hasUnscanned` keeps pagination alive even if the rows found + * so far happen to end exactly at the page boundary. The estimate is then a + * lower bound — Model already calls provider totals "about" for this reason. + */ function searchPage(uids, offset, maxResults, hasUnscanned) { var ordered = sortedUids(uids) ordered.reverse() @@ -605,8 +563,9 @@ function summaryFetchCommand(uids) { return "UID FETCH " + set + " (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[" + LIST_HEADERS + "])" } -// Takes one UID or a list of them, because opening a message and refilling a -// page of bodies from the cache are the same request at different sizes. +/** Takes one UID or a list of them, because opening a message and refilling a + * page of bodies from the cache are the same request at different sizes. + */ function fullFetchCommand(uids) { var set = sequenceSet(Array.isArray(uids) ? uids : [uids]) if (set === "") return "" @@ -618,7 +577,7 @@ function storeCommand(uids, addFlags, removeFlags) { if (set === "") return "" var add = Array.isArray(addFlags) ? addFlags : [] var remove = Array.isArray(removeFlags) ? removeFlags : [] - // One command each way. IMAP has no "add these and remove those" STORE, and + // Invariant: One command each way. IMAP has no "add these and remove those" STORE, and // the transport runs them in order on the same connection. var commands = [] if (add.length > 0) commands.push("UID STORE " + set + " +FLAGS.SILENT (" + add.join(" ") + ")") @@ -632,8 +591,9 @@ function copyCommand(uids, folder) { return "UID COPY " + set + " " + quote(folder) } -// MOVE (RFC 6851) where the server has it, COPY + \Deleted + EXPUNGE where it -// does not. The caller decides which by asking `hasCapability`. +/** MOVE (RFC 6851) where the server has it, COPY + \Deleted + EXPUNGE where it + * does not. The caller decides which by asking `hasCapability`. + */ function moveCommand(uids, folder) { var set = sequenceSet(uids) if (set === "") return "" @@ -642,7 +602,7 @@ function moveCommand(uids, folder) { function expungeCommand(uids) { var set = sequenceSet(uids) - // UID EXPUNGE (RFC 4315) removes only what was named. Plain EXPUNGE removes + // Invariant: UID EXPUNGE (RFC 4315) removes only what was named. Plain EXPUNGE removes // every \Deleted message in the folder, including ones another client marked // — which is somebody else's mail disappearing because this one archived. return set === "" ? "" : "UID EXPUNGE " + set @@ -675,27 +635,30 @@ function draftSaveResult(replaceError) { } } -// The folder a sent copy is filed in: the server's own Sent, learned from -// LIST like every folder name is. An empty answer means the server named -// none, and names are never guessed — a client that made one up would create -// folders rather than find them. +/** The folder a sent copy is filed in: the server's own Sent, learned from + * LIST like every folder name is. An empty answer means the server named + * none, and names are never guessed — a client that made one up would create + * folders rather than find them. + */ function sentFolder(special) { return (special || {})["\\sent"] || "" } -// curl's upload-flags names flags as bare words rather than as the -// parenthesised list IMAP puts on the APPEND line. A draft keeps its \Draft -// marker; a sent copy arrives seen, because its author has read it. +/** curl's upload-flags names flags as bare words rather than as the + * parenthesised list IMAP puts on the APPEND line. A draft keeps its \Draft + * marker; a sent copy arrives seen, because its author has read it. + */ function appendFlagWords(sent) { return sent === true ? "seen" : "draft" } -// What a finished send reports about the copy the mailbox keeps. The message -// itself is out either way, so a copy that did not land is a warning carried -// on a success, never a failure of the send. An empty folder name stands for -// every reason no folder was known — the server listed none, or the listing -// could not be asked — because what the user does about them is the same: -// nothing. +/** What a finished send reports about the copy the mailbox keeps. The message + * itself is out either way, so a copy that did not land is a warning carried + * on a success, never a failure of the send. An empty folder name stands for + * every reason no folder was known — the server listed none, or the listing + * could not be asked — because what the user does about them is the same: + * nothing. + */ function sentCopyResult(folder, filed) { if (String(folder || "") === "") return { sent: true, warning: "Sent, but no Sent folder was found to file a copy in" } @@ -714,61 +677,61 @@ function listCommand() { return "LIST \"\" \"*\"" } -// Asked alongside the folder listing rather than on its own: it costs nothing -// extra on a connection that is already open, and the one answer acted on — -// whether the server has MOVE — decides between one command and three. +/** Asked alongside the folder listing rather than on its own: it costs nothing + * extra on a connection that is already open, and the one answer acted on — + * whether the server has MOVE — decides between one command and three. + */ function capabilityCommand() { return "CAPABILITY" } -// RFC 2971's client identification, sent to any server that advertises ID. -// Most servers tolerate its absence, which is why it went missing for so long. -// Coremail does not: it answers every SELECT with "Unsafe Login" until this has -// arrived, and that is how the omission was found rather than what it is for. -// -// Delivered by the transport's `imap-id` mode, which is the only way to get a -// command in front of the SELECT curl derives from a URL's path. -// -// Sent only to a server that advertised ID: one that has never heard of it -// answers BAD, and the transport runs curl with --fail-early, so that single -// BAD would take every command after it. -// -// A name and nothing else. This string goes into someone else's server log, -// and the operating system, the hostname and the user are none of its -// business — RFC 2971 section 3.3 says as much. +/** RFC 2971's client identification, sent to any server that advertises ID. + * Most servers tolerate its absence, which is why it went missing for so long. + * Coremail does not: it answers every SELECT with "Unsafe Login" until this has + * arrived, and that is how the omission was found rather than what it is for. + * + * Delivered by the transport's `imap-id` mode, which is the only way to get a + * command in front of the SELECT curl derives from a URL's path. + * + * Sent only to a server that advertised ID: one that has never heard of it + * answers BAD, and the transport runs curl with --fail-early, so that single + * BAD would take every command after it. + * + * A name and nothing else. This string goes into someone else's server log, + * and the operating system, the hostname and the user are none of its + * business — RFC 2971 section 3.3 says as much. + */ function idCommand() { return "ID (\"name\" \"omamail\")" } - -// ------------------------------------------------------- search translation - -// The criteria a mailbox query carries are already IMAP's own words (UNSEEN, -// FLAGGED). A typed search arrives as TEXT "..." from `Provider.searchQuery`, -// already JSON-quoted — which is the same escaping IMAP uses for a quoted -// string, with one exception this fixes: JSON escapes a newline as \n, and -// IMAP has no such escape. +/** The criteria a mailbox query carries are already IMAP's own words (UNSEEN, + * FLAGGED). A typed search arrives as TEXT "..." from `Provider.searchQuery`, + * already JSON-quoted — which is the same escaping IMAP uses for a quoted + * string, with one exception this fixes: JSON escapes a newline as \n, and + * IMAP has no such escape. + */ function normalizeCriteria(criteria) { var text = trimmed(criteria) if (text === "") return "" return text.replace(/\\n|\\r|\\t/g, " ") } -// ------------------------------------------------------------- the response -// -// A tokenizer rather than a set of patterns, for the same reason `Html.js` is -// one: where a literal ends is the one thing this cannot be wrong about, and no -// regular expression can count octets. +/** A tokenizer rather than a set of patterns, for the same reason `Html.js` is + * one: where a literal ends is the one thing this cannot be wrong about, and no + * regular expression can count octets. + */ function decodeResponse(base64Text, base64ToBytes, bytesToLatin1) { if (typeof base64ToBytes !== "function" || typeof bytesToLatin1 !== "function") return "" return bytesToLatin1(base64ToBytes(String(base64Text || ""))) } -// One IMAP response line, with any literals folded into it. Returns a list of -// lines, each of which is a complete untagged or tagged response — so the -// callers below can look at "* 1 FETCH (...)" as a single string however many -// literals it ran through. +/** One IMAP response line, with any literals folded into it. Returns a list of + * lines, each of which is a complete untagged or tagged response — so the + * callers below can look at "* 1 FETCH (...)" as a single string however many + * literals it ran through. + */ function splitResponse(text) { var input = String(text || "") var lines = [] @@ -781,7 +744,7 @@ function splitResponse(text) { var line = input.substring(index, end) index = newline < 0 ? input.length : newline + 2 - // A line ending in a literal count continues into the next `count` octets, + // Algorithm: A line ending in a literal count continues into the next `count` octets, // whatever they contain — including CRLFs of their own. var literal = line.match(/\{(\d+)\+?\}$/) if (literal) { @@ -789,7 +752,7 @@ function splitResponse(text) { var payload = input.substr(index, size) index += size current += line + "\r\n" + payload - // curl removes the tagged completion and closing syntax around a custom + // Invariant: curl removes the tagged completion and closing syntax around a custom // IMAP request. With --next, another untagged FETCH can therefore begin // at the exact byte after the literal. The literal size is the boundary; // do not fold that next response into this one. @@ -809,8 +772,9 @@ function splitResponse(text) { return lines } -// `* SEARCH 1 4 9` — and nothing else, because a server may answer with no -// SEARCH line at all when nothing matched. +/** `* SEARCH 1 4 9` — and nothing else, because a server may answer with no + * SEARCH line at all when nothing matched. + */ function parseSearch(text) { var lines = splitResponse(text) var uids = [] @@ -826,9 +790,10 @@ function parseSearch(text) { return sortedUids(uids) } -// `UID FETCH 1:* (UID)` returns one FETCH response per message. The UID is the -// only data item it carries; sorting and de-duplicating here makes the snapshot -// independent of the order in which a server chose to report those responses. +/** `UID FETCH 1:* (UID)` returns one FETCH response per message. The UID is the + * only data item it carries; sorting and de-duplicating here makes the snapshot + * independent of the order in which a server chose to report those responses. + */ function parseUidList(text) { var entries = parseFetch(text) var uids = [] @@ -836,9 +801,10 @@ function parseUidList(text) { return sortedUids(uids) } -// Reads the value of one FETCH data item out of a response line. The items are -// unordered and a server may send ones nobody asked for, so each is found by -// name rather than by position. +/** Reads the value of one FETCH data item out of a response line. The items are + * unordered and a server may send ones nobody asked for, so each is found by + * name rather than by position. + */ function fetchItem(line, name) { var index = line.indexOf(name) if (index < 0) return "" @@ -854,7 +820,8 @@ function unquoteImap(value) { return text } -// The flag list of one FETCH response: FLAGS (\Seen \Flagged). +/** The flag list of one FETCH response: FLAGS (\Seen \Flagged). + */ function parseFlags(line) { var match = String(line || "").match(/FLAGS\s*\(([^)]*)\)/i) if (!match) return [] @@ -866,19 +833,19 @@ function parseFlags(line) { return output } -// The body of a FETCH item that arrived as a literal. Everything this client -// asks for — headers and whole messages — comes back that way, because servers -// send anything with a CRLF in it as a literal. +/** The body of a FETCH item that arrived as a literal. Everything this client + * asks for — headers and whole messages — comes back that way, because servers + * send anything with a CRLF in it as a literal. + */ function parseLiteralBody(line) { var match = String(line || "").match(/BODY\[[^\]]*\]\s*(?:<\d+>)?\s*\{(\d+)\+?\}\r\n([\s\S]*)$/) if (!match) { - // A short body may arrive as a quoted string instead. var quoted = String(line || "").match(/BODY\[[^\]]*\]\s*("(?:[^"\\]|\\.)*")/) return quoted ? unquoteImap(quoted[1]) : "" } var size = Math.floor(Number(match[1])) var payload = match[2] - // The closing ")" of the FETCH response follows the literal. Cutting to the + // Algorithm: The closing ")" of the FETCH response follows the literal. Cutting to the // declared size is what leaves it out — and is why the octet count had to // survive the transport intact. return payload.substring(0, size) @@ -887,7 +854,7 @@ function parseLiteralBody(line) { function parseInternalDate(line) { var value = unquoteImap(fetchItem(line, "INTERNALDATE")) if (value === "") return 0 - // "17-Jul-2026 09:02:11 +0800" is not a format Date parses anywhere, so it + // Invariant: "17-Jul-2026 09:02:11 +0800" is not a format Date parses anywhere, so it // is rearranged into one that is. var match = value.match(/^(\d{1,2})-(\w{3})-(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s*([+-]\d{4})?$/) if (!match) { @@ -900,10 +867,11 @@ function parseInternalDate(line) { return isNaN(parsed.getTime()) ? 0 : parsed.getTime() } -// One entry per message in a FETCH response, in the order the server sent -// them. The UID is what everything upstream calls an id: a sequence number -// changes when anything ahead of the message is expunged, so a client that -// keyed on one would act on whichever message had slid into that position. +/** One entry per message in a FETCH response, in the order the server sent + * them. The UID is what everything upstream calls an id: a sequence number + * changes when anything ahead of the message is expunged, so a client that + * keyed on one would act on whichever message had slid into that position. + */ function parseFetch(text) { var lines = splitResponse(text) var output = [] @@ -923,7 +891,8 @@ function parseFetch(text) { return output } -// `* STATUS "INBOX" (MESSAGES 42 UNSEEN 3)` +/** `* STATUS "INBOX" (MESSAGES 42 UNSEEN 3)` + */ function parseStatus(text) { var lines = splitResponse(text) var result = { messages: 0, unseen: 0 } @@ -938,9 +907,10 @@ function parseStatus(text) { return result } -// A mailbox name arrives quoted, as an atom, or — when it holds a character the -// server would rather not quote — as a literal, which `splitResponse` has -// already folded into the same string. All three have to end up as the name. +/** A mailbox name arrives quoted, as an atom, or — when it holds a character the + * server would rather not quote — as a literal, which `splitResponse` has + * already folded into the same string. All three have to end up as the name. + */ function folderName(value) { var text = trimmed(value) var literal = text.match(/^\{(\d+)\+?\}\r\n([\s\S]*)$/) @@ -948,7 +918,8 @@ function folderName(value) { return unquoteImap(text) } -// `* LIST (\HasNoChildren \Sent) "/" "Sent Items"` +/** `* LIST (\HasNoChildren \Sent) "/" "Sent Items"` + */ function parseList(text) { var lines = splitResponse(text) var output = [] @@ -966,7 +937,7 @@ function parseList(text) { name: name, delimiter: match[2] === "NIL" ? "" : unquoteImap(match[2]), flags: flags, - // \Noselect marks a container that holds folders but no mail — Gmail's + // Invariant: \Noselect marks a container that holds folders but no mail — Gmail's // "[Gmail]" is one, and selecting it is an error. selectable: flags.join(" ").toLowerCase().indexOf("\\noselect") < 0 }) @@ -974,9 +945,7 @@ function parseList(text) { return output } -// ------------------------------------------------- mailbox names on the wire -// -// A mailbox name is not text. RFC 3501 section 5.1.3 carries it in "modified +// Invariant: A mailbox name is not text. RFC 3501 section 5.1.3 carries it in "modified // UTF-7": everything outside printable US-ASCII is shifted into a base64 run // introduced by "&" and closed by "-", with "," standing in for base64's "/" // because "/" is a hierarchy delimiter, and "&-" spelling a literal "&". @@ -994,8 +963,9 @@ function parseList(text) { var MODIFIED_BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+," -// The base64 run holds UTF-16BE, so it decodes to whole code units — which is -// what a JavaScript string is made of, surrogate pairs included. +/** The base64 run holds UTF-16BE, so it decodes to whole code units — which is + * what a JavaScript string is made of, surrogate pairs included. + */ function decodeShift(chunk) { var bits = 0 var width = 0 @@ -1015,7 +985,7 @@ function decodeShift(chunk) { pending = -1 } } - // A trailing half of a code unit means the run was truncated, and the bits + // Algorithm: A trailing half of a code unit means the run was truncated, and the bits // left over past the last whole byte are the run's padding, which must be // zero. A run that yields no code unit at all is malformed too: the one // legitimately empty run is "&-", and that is an ampersand, handled above. @@ -1040,13 +1010,11 @@ function decodeMailbox(name) { } var close = text.indexOf("-", at + 1) if (close < 0) { - // An unterminated run is not a name this can improve on. output += text.substring(at) break } var chunk = text.substring(at + 1, close) if (chunk === "") { - // "&-" is how the protocol spells an ampersand. output += "&" } else { var decoded = decodeShift(chunk) @@ -1057,12 +1025,13 @@ function decodeMailbox(name) { return output } -// The other direction, for a name the user typed that is about to be sent in -// CREATE or RENAME: printable US-ASCII passes through, "&" is spelled "&-", -// and everything else goes into a base64 run of its UTF-16 code units with -// "," standing in for "/" and no padding — RFC 3501 section 5.1.3. What comes -// back from LIST decodes to the same text, and `tests/test_imap.js` holds the -// round trip. +/** The other direction, for a name the user typed that is about to be sent in + * CREATE or RENAME: printable US-ASCII passes through, "&" is spelled "&-", + * and everything else goes into a base64 run of its UTF-16 code units with + * "," standing in for "/" and no padding — RFC 3501 section 5.1.3. What comes + * back from LIST decodes to the same text, and `tests/test_imap.js` holds the + * round trip. + */ function encodeMailbox(name) { var text = String(name === undefined || name === null ? "" : name) var output = "" @@ -1100,13 +1069,14 @@ function encodeMailbox(name) { return output } -// The three commands that change the folder list. A name the server already -// has travels exactly as LIST spelled it — the wire name, encoded once by -// the server — and a name the user typed is encoded here. Encoding a wire -// name again turns its "&" into "&-" and names a folder that does not exist. -// A RENAME carries every folder beneath the old name with it, which is what -// moving a folder under another parent is. -// Refuse an unrepresentable identity before quoting or encoding can change it. +/** The three commands that change the folder list. A name the server already + * has travels exactly as LIST spelled it — the wire name, encoded once by + * the server — and a name the user typed is encoded here. Encoding a wire + * name again turns its "&" into "&-" and names a folder that does not exist. + * A RENAME carries every folder beneath the old name with it, which is what + * moving a folder under another parent is. + * Refuse an unrepresentable identity before quoting or encoding can change it. + */ function validFolderName(value) { var text = String(value === undefined || value === null ? "" : value) if (text === "" || /[\x00-\x1f\x7f]/.test(text)) return false @@ -1133,18 +1103,19 @@ function deleteCommand(wireName) { return validFolderName(wireName) ? "DELETE " + quote(wireName) : "" } -// The SPECIAL-USE attributes this plugin cares about, mapped to the folder the +// Invariant: The SPECIAL-USE attributes this plugin cares about, mapped to the folder the // server named. A server that advertises none leaves the map empty and // `resolveFolder` falls back to the plain word. var SPECIAL_USE = ["\\sent", "\\drafts", "\\trash", "\\junk", "\\archive", "\\all", "\\flagged"] -// Whether a folder is one of the ones the mailbox row already offers. The -// sidebar lists the rest underneath, so getting this wrong either hides every -// folder the user made or shows Sent and Trash twice. -// -// Judged on SPECIAL-USE and the name, never on the structural flags: every -// server sends \HasNoChildren on almost everything, so treating any flag as -// "system" hides the whole folder tree. +/** Whether a folder is one of the ones the mailbox row already offers. The + * sidebar lists the rest underneath, so getting this wrong either hides every + * folder the user made or shows Sent and Trash twice. + * + * Judged on SPECIAL-USE and the name, never on the structural flags: every + * server sends \HasNoChildren on almost everything, so treating any flag as + * "system" hides the whole folder tree. + */ function isSpecialFolder(folder, special) { var entry = folder || {} var name = trimmed(entry.name) @@ -1155,7 +1126,7 @@ function isSpecialFolder(folder, special) { if (SPECIAL_USE.indexOf(String(flags[itemIndex]).toLowerCase()) >= 0) return true } - // A server with no SPECIAL-USE at all still had its folders matched by name + // Invariant: A server with no SPECIAL-USE at all still had its folders matched by name // in `specialFolders`, and those are the same ones the mailbox row shows. var map = special || {} for (var key in map) { @@ -1175,7 +1146,7 @@ function specialFolders(folders) { if (!map[flag]) map[flag] = list[itemIndex].name } } - // Gmail's IMAP predates SPECIAL-USE on some accounts and answers with + // Invariant: Gmail's IMAP predates SPECIAL-USE on some accounts and answers with // "[Gmail]/Sent Mail" and friends under XLIST-style names instead. Matching // on the name is a guess, so it only fills gaps the flags left. for (var choiceIndex = 0; choiceIndex < list.length; choiceIndex++) { @@ -1184,7 +1155,7 @@ function specialFolders(folders) { if (!map["\\sent"] && /^sent( mail| items| messages)?$/.test(leaf)) map["\\sent"] = name if (!map["\\trash"] && /^(trash|deleted( items| messages)?)$/.test(leaf)) map["\\trash"] = name if (!map["\\drafts"] && /^drafts?$/.test(leaf)) map["\\drafts"] = name - // Exchange calls it "Junk Email", which is the one name in this list that + // Invariant: Exchange calls it "Junk Email", which is the one name in this list that // the bare word cannot stand in for: every other fallback below happens to // be what Exchange calls the folder anyway. if (!map["\\junk"] && /^(junk([ -]?e-?mail)?|spam|bulk mail)$/.test(leaf)) map["\\junk"] = name @@ -1193,12 +1164,11 @@ function specialFolders(folders) { return map } -// ------------------------------------------------------------ flags ↔ labels -// -// Everything above `MailAccount` reads a message through `Message.summarize`, -// which asks for Gmail label ids. Rather than teach every view a second -// vocabulary, an IMAP message is given the label ids its flags and its folder -// amount to — so a row, a star and an unread dot work unchanged. +/** Everything above `MailAccount` reads a message through `Message.summarize`, + * which asks for Gmail label ids. Rather than teach every view a second + * vocabulary, an IMAP message is given the label ids its flags and its folder + * amount to — so a row, a star and an unread dot work unchanged. + */ function labelIdsFor(flags, folder, special) { var list = Array.isArray(flags) ? flags : [] @@ -1206,7 +1176,7 @@ function labelIdsFor(flags, folder, special) { for (var itemIndex = 0; itemIndex < list.length; itemIndex++) lowered.push(String(list[itemIndex]).toLowerCase()) var ids = [] - // Unread is the *absence* of \Seen, which is the one inversion in the whole + // Invariant: Unread is the *absence* of \Seen, which is the one inversion in the whole // mapping and the easiest thing to get backwards. if (lowered.indexOf("\\seen") < 0) ids.push("UNREAD") if (lowered.indexOf("\\flagged") >= 0) ids.push("STARRED") @@ -1224,9 +1194,10 @@ function labelIdsFor(flags, folder, special) { return ids } -// The other direction: what an action asks the server to change. Returns the -// flags to add and remove, plus a folder to move to where the action is a move -// rather than a flag — which is the whole difference between IMAP and Gmail. +/** The other direction: what an action asks the server to change. Returns the + * flags to add and remove, plus a folder to move to where the action is a move + * rather than a flag — which is the whole difference between IMAP and Gmail. + */ function actionPlan(action, special) { var map = special || {} var verb = String(action || "") @@ -1235,9 +1206,6 @@ function actionPlan(action, special) { if (verb === "markUnread") return { add: [], remove: ["\\Seen"], move: "" } if (verb === "star") return { add: ["\\Flagged"], remove: [], move: "" } if (verb === "unstar") return { add: [], remove: ["\\Flagged"], move: "" } - // Archive is a move on IMAP. Without an archive folder there is nowhere for - // the message to go, and the caller turns the button off rather than - // silently deleting it. if (verb === "archive") return { add: [], remove: [], move: map["\\archive"] || "" } if (verb === "unarchive") return { add: [], remove: [], move: "INBOX" } if (verb === "trash") return { add: [], remove: [], move: map["\\trash"] || "" } @@ -1245,13 +1213,14 @@ function actionPlan(action, special) { return null } -// `MailAccount` does not know which provider it is driving: it asks for a -// label change, in Gmail's vocabulary, because that is the vocabulary every -// view already speaks. This is where that request becomes IMAP. -// -// Two of the mappings are not flags at all. Gmail archives by removing the -// INBOX label — one message, many labels — while IMAP has one folder per -// message, so the same request is a move. +/** `MailAccount` does not know which provider it is driving: it asks for a + * label change, in Gmail's vocabulary, because that is the vocabulary every + * view already speaks. This is where that request becomes IMAP. + * + * Two of the mappings are not flags at all. Gmail archives by removing the + * INBOX label — one message, many labels — while IMAP has one folder per + * message, so the same request is a move. + */ function flagPlanForLabels(addLabelIds, removeLabelIds, special) { var added = Array.isArray(addLabelIds) ? addLabelIds : [] var removed = Array.isArray(removeLabelIds) ? removeLabelIds : [] @@ -1265,12 +1234,9 @@ function flagPlanForLabels(addLabelIds, removeLabelIds, special) { return false } - // A move always adds its named destination while taking INBOX away. Read it - // before interpreting Gmail's system ids: an ordinary IMAP folder may itself - // be named "Starred", "Unread", "Trash", or "Spam". var destination = folderTarget(added, removed) - // The inversion again: Gmail's UNREAD is a label you add, IMAP's \Seen is a + // Invariant: The inversion again: Gmail's UNREAD is a label you add, IMAP's \Seen is a // flag you remove. Getting this backwards marks read what the user just // marked unread. if (destination === "" && has(added, "UNREAD")) plan.remove.push("\\Seen") @@ -1283,18 +1249,14 @@ function flagPlanForLabels(addLabelIds, removeLabelIds, special) { if (destination === "" && has(added, "TRASH")) plan.move = map["\\trash"] || "" if (destination === "" && has(added, "SPAM")) plan.move = map["\\junk"] || "" - // A named destination, which is the one case where the request is already - // IMAP: `getLabels` reports folder names as label ids, so a move asks for - // the folder by the name the server gave it. It is read last because such a - // request also removes INBOX -- the archive above is the default for "out of - // the inbox", and this is the same message with somewhere better to be. if (destination !== "") plan.move = destination return plan } -// The destination carried by a move. `labelChangesFor` shapes one as a label -// added while INBOX is removed; preserving that shape is what keeps a folder -// named like a Gmail system id from being mistaken for the system operation. +/** The destination carried by a move. `labelChangesFor` shapes one as a label + * added while INBOX is removed; preserving that shape is what keeps a folder + * named like a Gmail system id from being mistaken for the system operation. + */ function folderTarget(addLabelIds, removeLabelIds) { var added = Array.isArray(addLabelIds) ? addLabelIds : [] var removed = Array.isArray(removeLabelIds) ? removeLabelIds : [] @@ -1305,23 +1267,22 @@ function folderTarget(addLabelIds, removeLabelIds) { return "" } -// -------------------------------------------------------------- the errors -// -// A server's own text is written for whoever reads its logs. These are the -// four sentences a user can act on. +/** A server's own text is written for whoever reads its logs. These are the + * four sentences a user can act on. + */ function responseError(status, detail, fallback) { var text = trimmed(detail) var code = Math.floor(Number(status)) || 0 - // curl's own exit codes, which is what a transport failure arrives as. + // Invariant: curl's own exit codes, which is what a transport failure arrives as. if (code === 6) return "Could not find that mail server. Check the server address" if (code === 7) return "Could not reach the mail server. Check the address, the port, and the network" if (code === 28) return "The mail server did not answer in time" if (code === 35) return "A secure connection to the mail server could not be established" if (code === 60 || code === 51) return "The mail server's security certificate could not be verified" - // curl gives a refused SELECT the same exit code as a denied login — 67, with + // Invariant: curl gives a refused SELECT the same exit code as a denied login — 67, with // only "Select failed" against "Access denied" to tell them apart — and 21 to // a command the server answered BAD. Reading either as an authentication // failure sends someone off to change a password that was never the problem: @@ -1344,13 +1305,14 @@ function responseError(status, detail, fallback) { return fallback || "The mail server could not complete this request" } -// The error for a finished transport call, whichever half of it failed. -// -// curl's exit code says that something went wrong; the server's own tagged NO -// or BAD says what, and it is in the response even when curl exits non-zero. -// Preferring it is what keeps a refused command reported in the words the -// server chose rather than as whichever of curl's exit codes it happened to -// share with an unrelated failure. +/** The error for a finished transport call, whichever half of it failed. + * + * curl's exit code says that something went wrong; the server's own tagged NO + * or BAD says what, and it is in the response even when curl exits non-zero. + * Preferring it is what keeps a refused command reported in the words the + * server chose rather than as whichever of curl's exit codes it happened to + * share with an unrelated failure. + */ function transportError(status, response, detail, fallback) { if (isFailure(response)) { var served = failureDetail(response) @@ -1359,28 +1321,27 @@ function transportError(status, response, detail, fallback) { return responseError(status, detail, fallback) } -// A password can end up in a curl error line, in a server's echo of a failed -// LOGIN, or in a URL. Nothing that could carry one reaches a label without -// passing through here — the same gate `OAuth.redact` is for Google. +/** A password can end up in a curl error line, in a server's echo of a failed + * LOGIN, or in a URL. Nothing that could carry one reaches a label without + * passing through here — the same gate `OAuth.redact` is for Google. + */ function redact(text) { return String(text === undefined || text === null ? "" : text) - // "LOGIN user pass" and "AUTHENTICATE PLAIN ", whichever the - // server chose to quote back. .replace(/\b(LOGIN)\s+\S+\s+\S+/gi, "$1 [redacted]") .replace(/\b(AUTHENTICATE)\s+\w+\s+\S+/gi, "$1 [redacted]") - // A password inside a URL's userinfo, which is how curl prints one. .replace(/(imaps?|smtps?):\/\/[^\s/@]*:[^\s/@]*@/gi, "$1://[redacted]@") .replace(/(password|pass|pwd)\s*[=:]\s*\S+/gi, "$1=[redacted]") } -// Whether a tagged completion said NO or BAD. This has to inspect parsed IMAP -// responses rather than search the whole byte string: a FETCH response holds -// the message as a literal, and an ordinary message header such as -// `X-Spam-Flag: NO` is not the server refusing the command. +/** Whether a tagged completion said NO or BAD. This has to inspect parsed IMAP + * responses rather than search the whole byte string: a FETCH response holds + * the message as a literal, and an ordinary message header such as + * `X-Spam-Flag: NO` is not the server refusing the command. + */ function failureCompletion(text) { var lines = splitResponse(text) for (var itemIndex = 0; itemIndex < lines.length; itemIndex++) { - // A response containing a literal includes the literal's own lines in this + // Invariant: A response containing a literal includes the literal's own lines in this // string. Only its first protocol line can be a completion, and spaces or // tabs — not \s, which also crosses a newline — separate its fields. var first = String(lines[itemIndex] || "").split(/\r?\n/)[0] @@ -1399,12 +1360,11 @@ function failureDetail(text) { return completion ? completion.detail : "" } -// ------------------------------------------------------------- capabilities - -// `* CAPABILITY IMAP4rev1 MOVE UIDPLUS ...`, which decides whether an archive -// is one round trip or three. +/** `* CAPABILITY IMAP4rev1 MOVE UIDPLUS ...`, which decides whether an archive + * is one round trip or three. + */ function parseCapabilities(text) { - // Bounded to the line. `[\s\S]*` with the multiline flag is greedy across + // Invariant: Bounded to the line. `[\s\S]*` with the multiline flag is greedy across // newlines, which swallowed the tagged completion that follows and reported // "A1" and "OK" as capabilities. var match = String(text || "").match(/^\*\s+CAPABILITY\s+([^\r\n]*)/im) diff --git a/ui/providers/Jmap.js b/ui/providers/Jmap.js index d2044e4a9..1c1b6da69 100644 --- a/ui/providers/Jmap.js +++ b/ui/providers/Jmap.js @@ -1,6 +1,6 @@ .pragma library -// Provider presentation only. NativeDomain.js supplies all mail capabilities +// Invariant: Provider presentation only. NativeDomain.js supplies all mail capabilities // and mailbox queries; providers.resolve builds dynamic queries in Rust. .import "JmapProtocol.js" as Protocol diff --git a/ui/providers/JmapAuth.qml b/ui/providers/JmapAuth.qml index bc1e1b64b..34e6d0683 100644 --- a/ui/providers/JmapAuth.qml +++ b/ui/providers/JmapAuth.qml @@ -4,24 +4,8 @@ import Quickshell.Io import "JmapProtocol.js" as Jmap -// A JMAP account's sign-in, which is an address and one secret. -// -// Same shape from outside as `ImapAuth` and `AuthManager`: `MailAccount` asks -// whether it is `loggedIn` and asks for a credential with one call whose -// callback takes `(value, error)`. What differs is what a credential *is* -// here: a scheme, a username and a secret. Rust constructs and validates the -// Authorization header; QML never assembles one. -// -// The secret is an app password or an API token, and which of the two it is -// decides the scheme. That is detected rather than asked: the client sends the -// session GET with Basic and, only on a 401, once more with Bearer, and the -// scheme that answered is recorded on the account. Nothing here refreshes and -// nothing expires — a 401 afterwards is a credential that was revoked, which -// is the setup page's problem rather than a retry. -// -// Where the secret lives is the same rule as every other credential in this -// plugin: GNOME Keyring, written over stdin so it never reaches the process -// table, keyed by account so two mailboxes cannot overwrite each other. +// Invariant: Rust detects the credential scheme and constructs Authorization. +// Secrets travel through the native credential API and are scoped by account. Item { id: root @@ -33,27 +17,18 @@ Item { property var platform: null required property string pluginDir - // Which mailbox this signs in. Known from the moment the address is typed, - // as IMAP's is, rather than after a profile read. property string accountId: "" - // The address, which is what discovery has to go on when no server was - // typed and what the credential's username defaults to. property string address: "" - // The account's `jmap` block, pushed down from the account entry in the - // shape `Accounts.makeJmapSettings` normalises it to. Before the first - // sign-in the session URL is either empty — discovery has not run — or - // whatever the user typed into the disclosure, which is exactly what - // `Jmap.discoveryPlan` takes as its typed server. property var settings: ({ sessionUrl: "", username: "", authScheme: "basic", accountId: "" }) - // A mailbox this client knows where to talk to. Unlike IMAP's, this is not + // Invariant: A mailbox this client knows where to talk to. Unlike IMAP's, this is not // something the user typed: it is what sign-in learned and wrote down. readonly property bool configured: String((settings || {}).sessionUrl || "") !== "" && String((settings || {}).accountId || "") !== "" - // The secret, once the keyring has answered. Held for as long as the account + // Performance: The secret, once the keyring has answered. Held for as long as the account // exists, exactly as the IMAP password is: every request needs it, and a // keyring round trip per request would be both slow and a stream of // authorisation prompts on some setups. @@ -61,7 +36,6 @@ Item { property bool secretChecked: false readonly property bool loggedIn: configured && secret !== "" - // The three names `MailAccount` reads without knowing which provider it has. readonly property bool credentialsPresent: configured property bool loginBusy: false property int sessionGeneration: 0 @@ -73,13 +47,6 @@ Item { readonly property bool sessionBusy: credentialLookupBusy || credentialWriteBusy property string lastError: "" - // Which of the check's three waits is happening, 1 to 3, or 0 when nothing - // is. The client reports it as it goes, because the client is what knows — - // finding the server, checking the secret and reading the mailboxes are - // three requests that look identical from outside, and naming which one is - // running is the difference between "it is working" and "it is stuck". It - // reports through `reportProgress` rather than writing here: this object - // owns the value and is the one that clears it when the check ends. property int progressStep: 0 function reportProgress(step) { @@ -87,20 +54,15 @@ Item { progressStep = isFinite(value) && value > 0 ? value : 0 } - // Whether the last check ran out of places to look. The page opens its - // server field on this rather than by reading the sentence it printed: - // "nothing answered for that domain" is a state, and matching on the words - // would break the first time somebody reworded them. property bool serverNeeded: false - // Whether the credential that signed in may submit mail. A missing + // Invariant: Whether the credential that signed in may submit mail. A missing // submission capability does not fail sign-in — the mailbox reads perfectly // well — so the account signs in and the page says what it cannot do. The // standing refusal is the client's, read from the session (`Jmap.refusals`); // this is only what the last check found out, for the page's one sentence. property bool sendingOffered: true - // Native credential storage and network requests are backend capabilities. readonly property var requiredTools: [] property var missingTools: [] property bool toolsChecked: true @@ -115,22 +77,16 @@ Item { signal sessionUnavailable(string reason) signal credentialsSaved() - // What sign-in learned, for the account to write down: the session URL that - // answered, the scheme that worked, and the account id every later request - // names. `MailAccount` carries it up to the account list, which is the one - // owner of the entry this object's `settings` are read from — nothing here - // writes to itself, and the page only shows the URL. Emitted before - // `loginSucceeded`, so the settings are on the account by the time anything - // asks the client to fetch with them. signal sessionVerified(var result) function safeError(value) { return Jmap.redact(String(value || "")) } - // Three fields rather than one string. The script joins them into whichever - // header the scheme needs, and refuses a scheme it does not know before networking - // starts — so there is no place here where an `Authorization` value is built. + /** Three fields rather than one string. The script joins them into whichever + * header the scheme needs, and refuses a scheme it does not know before networking + * starts — so there is no place here where an `Authorization` value is built. + */ function credential() { var values = settings || {} var user = String(values.username || "") @@ -142,11 +98,12 @@ Item { credentialWaiters = [] for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { try { pending[itemIndex](value, safeError(error)) } - catch (error) { /* consumers own their callback errors */ } + catch (error) { /* Invariant: one consumer must not prevent later waiters from completing. */ } } } - // The one entry point the transport uses. + /** The one entry point the transport uses. + */ function withCredentials(callback) { if (typeof callback !== "function") return if (!configured) { @@ -209,8 +166,6 @@ Item { var value = String(line || "") if (value === "") { finishWaiters(null, "No app password saved for this mailbox. Sign in again") - // Only a mailbox that is otherwise ready to go is worth complaining - // about: an account still being typed into has no secret by design. if (configured) sessionUnavailable("Sign in to this mailbox") return } @@ -219,10 +174,11 @@ Item { loginSucceeded() } - // Called by the setup page once the form is filled in. The secret is - // verified by using it — discovery, the session GET under each scheme in - // turn, and one `Mailbox/get` — rather than being written down first and - // failing later on a page with no field to correct. + /** Called by the setup page once the form is filled in. The secret is + * verified by using it — discovery, the session GET under each scheme in + * turn, and one `Mailbox/get` — rather than being written down first and + * failing later on a page with no field to correct. + */ function signIn(value) { if (loginBusy || credentialWriteBusy) return false if (platform && platform.canAccessCredentials === false) { @@ -234,7 +190,7 @@ Item { return false } var typed = String(value || "") - // "Save changes" re-verifies, and the field it would have come from is + // Invariant: "Save changes" re-verifies, and the field it would have come from is // empty on a signed-in page: nothing ever writes a saved secret back into // a text box. The one already held is what the server is asked about. if (typed === "" && secret !== "") typed = secret @@ -255,13 +211,13 @@ Item { return true } - // The client owns the transport, so it performs the check and reports back. signal verifyRequested(var settings, string address, string secret) - // `result` is what the check learned when it succeeded: `sessionUrl`, - // `authScheme` and `accountId`. It is emitted before the secret is stored, - // because the keyring entry is named after the account and the account is - // not named until the page has written the address down. + /** `result` is what the check learned when it succeeded: `sessionUrl`, + * `authScheme` and `accountId`. It is emitted before the secret is stored, + * because the keyring entry is named after the account and the account is + * not named until the page has written the address down. + */ function completeSignIn(ok, result, error, needsServer, generation) { if (!loginBusy || (generation !== undefined && generation !== sessionGeneration)) return loginBusy = false @@ -280,7 +236,7 @@ Item { lastError = "" sessionVerified(result || {}) storeSecret() - // A tick later than the rest of this, and deliberately: `sessionVerified` + // Invariant: A tick later than the rest of this, and deliberately: `sessionVerified` // is what has the account list write the session URL, the scheme and the // account id onto the entry, and only then is this object `configured`. // Emitting in the same turn would have `MailAccount` start fetching @@ -335,19 +291,21 @@ Item { loggedOut() } - // Kept so `MailAccount` can call the same thing on any provider. An app - // password does not expire, so there is nothing to invalidate — but a server - // that has started refusing it should not be asked a hundred more times with - // the same value. + /** Kept so `MailAccount` can call the same thing on any provider. An app + * password does not expire, so there is nothing to invalidate — but a server + * that has started refusing it should not be asked a hundred more times with + * the same value. + */ function invalidateAccessToken() { secret = "" secretChecked = false } - // Gmail's manager has these; a JMAP account reaches neither, and - // `MailAccount` should not have to ask which provider it holds before - // calling one. - function beginLogin() { /* the setup form drives sign-in, not a browser */ } + /** Gmail's manager has these; a JMAP account reaches neither, and + * `MailAccount` should not have to ask which provider it holds before + * calling one. + */ + function beginLogin() { } function cancelLogin() { sessionGeneration++ pendingSecret = "" @@ -357,9 +315,6 @@ Item { onAccountIdChanged: { cancelLogin() - // A different mailbox has a different secret. Dropping the one in memory - // is what stops an account rename from leaving the previous account's - // credential in front of the new one's server. secret = "" secretChecked = false lookupHandled = false diff --git a/ui/providers/JmapClient.qml b/ui/providers/JmapClient.qml index 0d17e5852..021d0d8dd 100644 --- a/ui/providers/JmapClient.qml +++ b/ui/providers/JmapClient.qml @@ -1,7 +1,7 @@ import QtQuick import "JmapProtocol.js" as Jmap -// Presentation adapter: all credentials, sessions, HTTP, query planning, +// Invariant: Presentation adapter: all credentials, sessions, HTTP, query planning, // MIME conversion, conversation membership and mutations belong to Rust. Item { id: root diff --git a/ui/providers/JmapProtocol.js b/ui/providers/JmapProtocol.js index c3abb0fbe..91b874dad 100644 --- a/ui/providers/JmapProtocol.js +++ b/ui/providers/JmapProtocol.js @@ -2,49 +2,16 @@ .import "../message/Message.js" as Mail -// JMAP's own rules, and nothing else. No transport lives here — -// `scripts/jmap-transport.sh` runs the curl process and `JmapClient.qml` owns -// it — and no MIME parsing either: an RFC 822 message is `Message.js`'s -// subject, and this file never sees one. What it does own is the other -// direction, `toMessage`: a JMAP Email *composed* into the shared message -// resource, the way `HeyClient.toMessage` composes rather than parses. -// -// This is the JMAP seam and the one place a rule about JMAP goes, with one job -// beside it: `JmapThreads.js` holds the collapsed list read — the four chained -// calls a page of conversations is, the rule about which members a row counts, -// and the block a row draws from. `Jmap.js` is the provider *description* the -// registry reads — a name, a ceiling, the rail's rows — and holds no protocol. -// The client imports this file as `Jmap`, which is the name every call in it -// is read under: `Jmap.parseQuery`, `Jmap.toMessage`, `Jmap.refusals`. -// -// What this file owns is every decision about what came back, which is what -// the node tests reach without a compositor or a mailbox. -// -// ## Three levels of failure, and they are not the same question -// -// JMAP fails in three places and a client that flattened them would report the -// wrong thing at least a third of the time: -// -// - the *transport*: curl never connected, or the server answered with a -// status. `transportError` turns a curl exit and an HTTP status into a -// sentence. -// - the *request*: the server read the JSON and refused the whole document — -// an unknown capability, a size limit. `requestError` reads the -// problem-details object those come back as. -// - the *method*: the document was accepted and one invocation inside it -// answered `error`. `methodError` reads the first of those, unless the -// caller was expecting that type and has a branch for it. -// -// Every sentence is written for somebody who just clicked Archive rather than -// for somebody reading a server log, and anything that could carry a -// credential passes through `redact` before it can reach a label. +// Invariant: Rust owns live JMAP HTTP, query planning, MIME conversion and mutations. +// This library supplies presentation rules and protocol reference helpers for tests. +// Transport, request and method failures remain distinct in the reference contract. -// The ceiling on a blob download, fixed in the transport script as well: the +// Invariant: The ceiling on a blob download, fixed in the transport script as well: the // same figure `attachment.sh` will send up to. Exceeding it is curl exit 63 // rather than a 20 MB base64 line crossing a pipe. var MAX_BLOB_BYTES = 20971520 -// The three values the `authScheme` field may hold. The script builds the +// Invariant: The three values the `authScheme` field may hold. The script builds the // credential from one of these and refuses anything else, so QML never // assembles an Authorization value of its own. `none` is discovery's // well-known GET, on a URL the user did not type. @@ -52,17 +19,16 @@ var AUTH_BASIC = "basic" var AUTH_BEARER = "bearer" var AUTH_NONE = "none" -// What `maxConcurrentRequests` is worth when the session does not say. Read +// Invariant: What `maxConcurrentRequests` is worth when the session does not say. Read // from the session whenever it does; this is the floor under a server that // omits it, not an assumption about one that does. var DEFAULT_CONCURRENCY = 4 -// ------------------------------------------------------------------ redaction - -// A secret can end up in a curl error line, in a URL's userinfo, or in a -// server's echo of what it was sent. Nothing that could carry one reaches a -// label without passing through here — the same gate `OAuth.redact` is for -// Google and `Imap.redact` is for a password. +/** A secret can end up in a curl error line, in a URL's userinfo, or in a + * server's echo of what it was sent. Nothing that could carry one reaches a + * label without passing through here — the same gate `OAuth.redact` is for + * Google and `Imap.redact` is for a password. + */ function redact(text) { return String(text === undefined || text === null ? "" : text) .replace(/\bBearer\s+\S+/gi, "Bearer [redacted]") @@ -75,8 +41,9 @@ function trimmed(value) { return String(value === undefined || value === null ? "" : value).replace(/^\s+|\s+$/g, "") } -// Ids as a list — trimmed, without blanks or repeats, in first-appearance -// order. One id or an array of them, which is what every action takes. +/** Ids as a list — trimmed, without blanks or repeats, in first-appearance + * order. One id or an array of them, which is what every action takes. + */ function uniqueIds(ids) { var source = Array.isArray(ids) ? ids : [ids] var output = [] @@ -87,16 +54,18 @@ function uniqueIds(ids) { return output } -// A value that is there. JMAP's maps of keywords and of mailbox ids carry -// `true` for a member; RFC 8620 patches one out with `null`, and the reference -// server also accepts `false` — so all three read as absent. +/** A value that is there. JMAP's maps of keywords and of mailbox ids carry + * `true` for a member; RFC 8620 patches one out with `null`, and the reference + * server also accepts `false` — so all three read as absent. + */ function isSet(value) { return value !== undefined && value !== null && value !== false } -// A JMAP answer is an object or it is not an answer. `JSON.parse` accepting -// `4` or `"x"` is the difference between "the server sent JSON" and "the -// server sent a JMAP document". +/** A JMAP answer is an object or it is not an answer. `JSON.parse` accepting + * `4` or `"x"` is the difference between "the server sent JSON" and "the + * server sent a JMAP document". + */ function parseJson(text) { if (text === null || text === undefined) return null if (typeof text === "object") return text @@ -108,9 +77,10 @@ function parseJson(text) { } } -// JMAP names an error type with a URN — `urn:ietf:params:jmap:error:limit` at -// the request level, a bare `accountReadOnly` at the method level. The last -// segment is the name in both. +/** JMAP names an error type with a URN — `urn:ietf:params:jmap:error:limit` at + * the request level, a bare `accountReadOnly` at the method level. The last + * segment is the name in both. + */ function errorType(value) { var text = trimmed(value) if (text === "") return "" @@ -118,9 +88,10 @@ function errorType(value) { return parts[parts.length - 1] } -// RFC 7807 calls it `detail` and RFC 8620's method errors call it -// `description`. Both are read, because a server that chose the other word is -// still telling the user something. +/** RFC 7807 calls it `detail` and RFC 8620's method errors call it + * `description`. Both are read, because a server that chose the other word is + * still telling the user something. + */ function describedBy(payload) { if (!payload || typeof payload !== "object") return "" var described = trimmed(payload.description) @@ -128,9 +99,10 @@ function describedBy(payload) { return trimmed(payload.detail) } -// The existing suffix rule, in the words the Gmail client already uses: a -// number of seconds is not a sentence, and "try again shortly" without one is -// not an answer. +/** The existing suffix rule, in the words the Gmail client already uses: a + * number of seconds is not a sentence, and "try again shortly" without one is + * not an answer. + */ function rateLimitSuffix(retryAfter) { var seconds = Math.ceil(Number(retryAfter)) if (!isFinite(seconds) || seconds <= 0) return "" @@ -138,20 +110,19 @@ function rateLimitSuffix(retryAfter) { return " (retry in " + Math.ceil(seconds / 60) + " min)" } -// --------------------------------------------------------------- transport - -// The error for a finished transport call, whichever part of it failed. -// -// `exit` is curl's, `httpStatus` the code the script read with `--write-out`, -// `body` the response text (or null when there is none to read, which is what -// a blob download hands over), `stderr` whatever curl or the script itself -// said, and `retryAfter` the header value when a caller has one. An empty -// string means nothing went wrong. -// -// The exit code is asked first because a curl that never connected has no -// status to report — but a non-zero exit that *does* carry one defers to it, -// which is how the stream's `--fail` exit 22 becomes "the server rejected that -// username or password" on a 401 and a connection failure on anything else. +/** The error for a finished transport call, whichever part of it failed. + * + * `exit` is curl's, `httpStatus` the code the script read with `--write-out`, + * `body` the response text (or null when there is none to read, which is what + * a blob download hands over), `stderr` whatever curl or the script itself + * said, and `retryAfter` the header value when a caller has one. An empty + * string means nothing went wrong. + * + * The exit code is asked first because a curl that never connected has no + * status to report — but a non-zero exit that *does* carry one defers to it, + * which is how the stream's `--fail` exit 22 becomes "the server rejected that + * username or password" on a 401 and a connection failure on anything else. + */ function transportError(exit, httpStatus, body, stderr, retryAfter) { var code = Number(exit) if (!isFinite(code)) code = 0 @@ -163,7 +134,7 @@ function transportError(exit, httpStatus, body, stderr, retryAfter) { if (code === 28) return "The mail server took too long to answer" if (code === 35) return "Could not make a secure connection to the mail server" if (code === 63) return "The server's answer was larger than 20 MB" - // Exit 2 is the script's own refusal — a URL that is not https, an auth + // Invariant: Exit 2 is the script's own refusal — a URL that is not https, an auth // scheme it does not build — and it says so on stderr in words that are // already about this request. if (code === 2) { @@ -178,14 +149,14 @@ function transportError(exit, httpStatus, body, stderr, retryAfter) { } if (status === 404) return "The server has no such mailbox or message" if (status === 429) return "The server asked to slow down" + rateLimitSuffix(retryAfter) - // Never followed, so a redirect is reported as one. The credential goes to + // Invariant: Never followed, so a redirect is reported as one. The credential goes to // the session URL the user typed and to the URLs read from the session // fetched with it, and an address the server named at request time is // neither. if (status >= 300 && status < 400) return "The server tried to redirect, which this client refuses" if (status >= 500) return "The mail server had a problem" if (status >= 400) { - // A request-level error is a 400 with a problem-details body. It is a + // Invariant: A request-level error is a 400 with a problem-details body. It is a // JMAP failure rather than an HTTP one, so it is read as one. var payload = parseJson(body) if (payload && trimmed(payload.type) !== "") return requestError(payload) @@ -193,7 +164,7 @@ function transportError(exit, httpStatus, body, stderr, retryAfter) { return detail !== "" ? redact(detail) : "The server refused that request" } if (status >= 200 && status < 300) { - // A download's body is bytes rather than a document, and its caller passes + // Invariant: A download's body is bytes rather than a document, and its caller passes // nothing here. Anything that did pass a body expected JSON back. if (body === null || body === undefined) return "" if (!parseJson(body)) return "The server sent an answer this client could not read" @@ -203,18 +174,15 @@ function transportError(exit, httpStatus, body, stderr, retryAfter) { return "Could not reach the mail server" } -// The same, for the reply object the transport hands the client — `{ exit, -// status, redirect, body, stderr }` — so a caller does not spell the four -// fields out. +/** The same, for the reply object the transport hands the client — `{ exit, + * status, redirect, body, stderr }` — so a caller does not spell the four + * fields out. + */ function replyError(reply, retryAfter) { var source = reply && typeof reply === "object" ? reply : {} return transportError(source.exit, source.status, source.body, source.stderr, retryAfter) } -// A blob download's failure, which is `replyError` with the one answer that is -// about the attachment rather than the server: curl exit 63 is the 20 MB -// ceiling the script fixes. `body` is the problem document a failed download -// answers with, decoded by the caller from the bytes the verb answers in. var BLOB_TOO_LARGE = "This attachment is larger than 20 MB" function downloadError(reply, body) { @@ -223,14 +191,13 @@ function downloadError(reply, body) { return transportError(source.exit, source.status, body, source.stderr, "") } -// ------------------------------------------------------------ request level - -// The server read the document and refused the whole of it. `payload` is the -// problem-details object, parsed or not. +/** The server read the document and refused the whole of it. `payload` is the + * problem-details object, parsed or not. + */ function requestError(payload) { var body = parseJson(payload) if (!body) return "The mail server had a problem" - // A request that worked is not an error, and this is reached with one + // Invariant: A request that worked is not an error, and this is reached with one // whenever a caller asks about a document before looking inside it. A JMAP // problem-details object always names a `type`; a successful reply never // does and carries `methodResponses` instead — so a document with the one @@ -246,7 +213,7 @@ function requestError(payload) { if (limit !== "") return "The server's limit for " + redact(limit) + " was hit" return "The server's limit was hit" } - // `notRequest`, `notJSON` and `unknownCapability` are all this client + // Invariant: `notRequest`, `notJSON` and `unknownCapability` are all this client // sending something the server could not use, which is a bug here rather // than anything the reader can act on. The server's own words follow, so a // report of one carries what it said. @@ -255,13 +222,12 @@ function requestError(payload) { return "The mail server had a problem" } -// ------------------------------------------------------------- method level - -// Every invocation in a reply, as `{ name, arguments, callId }`. A JMAP -// response is a list of `[name, arguments, callId]` triples, and this is the -// one walk over it: a row that is not a triple is skipped rather than read, -// and an error is an invocation named `error` rather than a failure of the -// request that carried it. +/** Every invocation in a reply, as `{ name, arguments, callId }`. A JMAP + * response is a list of `[name, arguments, callId]` triples, and this is the + * one walk over it: a row that is not a triple is skipped rather than read, + * and an error is an invocation named `error` rather than a failure of the + * request that carried it. + */ function invocations(responses) { var list = responses && typeof responses === "object" && responses.length !== undefined ? responses : [] @@ -278,7 +244,8 @@ function invocations(responses) { return output } -// The first `error` invocation in a `methodResponses` array, or null. +/** The first `error` invocation in a `methodResponses` array, or null. + */ function firstMethodError(responses) { var list = invocations(responses) for (var itemIndex = 0; itemIndex < list.length; itemIndex++) { @@ -292,17 +259,19 @@ function firstMethodError(responses) { return null } -// The type of that error, so a caller with a branch for one can take it. The -// paging retry on `anchorNotFound` and the batch that tolerates `notFound` both -// need to know which error it was, not only that there was one. +/** The type of that error, so a caller with a branch for one can take it. The + * paging retry on `anchorNotFound` and the batch that tolerates `notFound` both + * need to know which error it was, not only that there was one. + */ function methodErrorType(responses) { var found = firstMethodError(responses) return found ? found.type : "" } -// The sentence for the first error invocation, or "" when there is none — or -// when it is one the caller said it expects. `expected` is a type name or an -// array of them. +/** The sentence for the first error invocation, or "" when there is none — or + * when it is one the caller said it expects. `expected` is a type name or an + * array of them. + */ function methodError(responses, expected) { var found = firstMethodError(responses) if (!found) return "" @@ -313,7 +282,7 @@ function methodError(responses, expected) { if (type === "forbidden") return "The server refused that request" if (type === "unsupportedFilter" || type === "unsupportedSort") return "The server cannot run that search" if (type === "requestTooLarge") return "That request is too large for the server" - // `serverFail`, `invalidArguments` and whatever a server invents: its own + // Invariant: `serverFail`, `invalidArguments` and whatever a server invents: its own // description if it wrote one, because a type name is not a sentence. var described = describedBy(found.arguments) if (described !== "") return redact(described) @@ -331,19 +300,18 @@ function expectsType(type, expected) { return String(expected) === type } -// ------------------------------------------------------------------- queue - -// The FIFO that keeps `call` and `upload` requests under the session's own -// concurrency limit. Pure, so the client holds one queue per limit and this -// file holds no processes. -// -// admit(entry) true when the entry starts now, false when it was queued -// release() one finished; returns the entry to start next, or null -// withdraw(e) removes a queued entry, so an aborted handle calls back -// nothing; false when it was not waiting -// -// An aborted in-flight request goes through `release` instead, because its -// process exit is what frees the slot. +/** The FIFO that keeps `call` and `upload` requests under the session's own + * concurrency limit. Pure, so the client holds one queue per limit and this + * file holds no processes. + * + * admit(entry) true when the entry starts now, false when it was queued + * release() one finished; returns the entry to start next, or null + * withdraw(e) removes a queued entry, so an aborted handle calls back + * nothing; false when it was not waiting + * + * An aborted in-flight request goes through `release` instead, because its + * process exit is what frees the slot. + */ function makeQueue(limit) { var cap = Math.floor(Number(limit)) if (!isFinite(cap) || cap < 1) cap = DEFAULT_CONCURRENCY @@ -384,15 +352,16 @@ function makeQueue(limit) { return queue } -// The waiting list behind a read many callers need and one performs — the -// session, the mailbox list, the identities. Pure, for the reason the queue -// is. -// -// join(callback) queues the callback; true for the caller that should -// perform the read, which is the first since the last -// `finish`, false for one that only waits -// finish(error) calls every waiter once with the answer, "" for none, -// and empties the list +/** The waiting list behind a read many callers need and one performs — the + * session, the mailbox list, the identities. Pure, for the reason the queue + * is. + * + * join(callback) queues the callback; true for the caller that should + * perform the read, which is the first since the last + * `finish`, false for one that only waits + * finish(error) calls every waiter once with the answer, "" for none, + * and empties the list + */ function makeWaiters() { var gate = { loading: false, waiting: [] } @@ -413,9 +382,10 @@ function makeWaiters() { return gate } -// The credential as the transport takes it: three fields rather than one -// string, because the script builds the `Authorization` value itself and -// nothing in QML ever assembles one. `none` is discovery's well-known GET. +/** The credential as the transport takes it: three fields rather than one + * string, because the script builds the `Authorization` value itself and + * nothing in QML ever assembles one. `none` is discovery's well-known GET. + */ function credential(scheme, username, secret) { var kind = trimmed(scheme).toLowerCase() return { @@ -425,12 +395,11 @@ function credential(scheme, username, secret) { } } -// ------------------------------------------------------------ download URLs - -// The session's `downloadUrl` template, filled. Every value is percent-encoded -// on the way in, so a blob id or a filename holding `/` or `?` — both of which -// a server may legitimately choose — cannot steer the request off the template -// and onto another path or another query. +/** The session's `downloadUrl` template, filled. Every value is percent-encoded + * on the way in, so a blob id or a filename holding `/` or `?` — both of which + * a server may legitimately choose — cannot steer the request off the template + * and onto another path or another query. + */ function downloadUrl(template, accountId, blobId, name, type) { var filled = String(template === undefined || template === null ? "" : template) if (filled === "") return "" @@ -441,35 +410,27 @@ function downloadUrl(template, accountId, blobId, name, type) { return filled } -// A replacement is data, not a pattern. `$&` and `$'` inside a filename would -// otherwise be expanded by `String.replace` into whatever surrounded the -// placeholder — and `encodeURIComponent` leaves `$` alone, so they survive -// that far. A function replacement is returned verbatim. +/** A replacement is data, not a pattern. `$&` and `$'` inside a filename would + * otherwise be expanded by `String.replace` into whatever surrounded the + * placeholder — and `encodeURIComponent` leaves `$` alone, so they survive + * that far. A function replacement is returned verbatim. + */ function fillTemplate(template, key, value) { var encoded = encodeURIComponent(String(value === undefined || value === null ? "" : value)) return template.replace(new RegExp("\\{" + key + "\\}", "g"), function () { return encoded }) } -// --------------------------------------------------------------- discovery -// -// Discovery starts at the address domain over HTTPS. A server without that +// Invariant: Discovery starts at the address domain over HTTPS. A server without that // endpoint is reached through the explicit server field. -// The order the setup page tries the two credential schemes in. -// -// Basic first: RFC 8620 section 8.2 names an app password as the Basic-auth -// credential, and a token sent as Basic is a rarer mistake than a password -// sent as Bearer. A server that takes only a token answers the first attempt -// with a 401 and the second one succeeds. Two requests with two credentials, -// from the setup page and nowhere else — it is a detection, not a retry, and a -// 401 from both is the rejected state. var AUTH_SCHEME_ORDER = [AUTH_BASIC, AUTH_BEARER] -// The same order for an account that has signed in before: the scheme it -// recorded first, then the rest. "Save changes" on a signed-in page re-verifies, -// and starting at Basic on a token-only server would buy a 401 before the -// scheme that has been working all along is tried. A scheme that is not one of -// the two — nothing recorded yet, or `none` — is the default order. +/** The same order for an account that has signed in before: the scheme it + * recorded first, then the rest. "Save changes" on a signed-in page re-verifies, + * and starting at Basic on a token-only server would buy a 401 before the + * scheme that has been working all along is tried. A scheme that is not one of + * the two — nothing recorded yet, or `none` — is the default order. + */ function schemeOrder(recorded) { var first = trimmed(recorded).toLowerCase() var output = [] @@ -480,41 +441,42 @@ function schemeOrder(recorded) { return output } -// What a discovery step is. `typed` is the URL built from what the user wrote, +// Invariant: What a discovery step is. `typed` is the URL built from what the user wrote, // and it is the only step when supplied; `well-known` starts at the address // domain so HTTPS authenticates any delegation to a different host. var STEP_TYPED = "typed" var STEP_WELL_KNOWN = "well-known" -// RFC 8620 section 2.2. The well-known URL is not the session object: it is +// Invariant: RFC 8620 section 2.2. The well-known URL is not the session object: it is // expected to redirect to one, which is the hop `redirectHop` allows. var WELL_KNOWN_PATH = "/.well-known/jmap" -// What a bare typed host means. Discovery has already failed by the time +// Invariant: What a bare typed host means. Discovery has already failed by the time // anybody types a host into that field, so this is a guess — but it is the path // the reference Stalwart serves, and that is the server the field exists for. var SESSION_PATH = "/jmap/session" -// A hostname, optionally with a port; not a URL and not a path. Everything -// here ends up in a URL an account password is sent to, so a value carrying a -// slash, a space, an "@" or a second colon could point the authenticated -// client somewhere else entirely. -// -// Deliberately a second copy of `ImapProtocol.isValidHost` rather than an -// import of it: one provider's rules are not the other's to change, and the -// day either grows a case the other must not follow, a shared function is the -// thing that carries it across. +/** A hostname, optionally with a port; not a URL and not a path. Everything + * here ends up in a URL an account password is sent to, so a value carrying a + * slash, a space, an "@" or a second colon could point the authenticated + * client somewhere else entirely. + * + * Deliberately a second copy of `ImapProtocol.isValidHost` rather than an + * import of it: one provider's rules are not the other's to change, and the + * day either grows a case the other must not follow, a shared function is the + * thing that carries it across. + */ function isValidHost(value) { var host = trimmed(value) if (host === "" || host.length > 253) return false if (/[\s/\\@:?#"'<>]/.test(host)) return false - // An IP literal is legitimate — a JMAP server on a machine with no name yet. if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true return /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(host) } -// A trailing dot is a fully qualified name to DNS and noise in a URL, and -// `dig` writes one on every target it prints. +/** A trailing dot is a fully qualified name to DNS and noise in a URL, and + * `dig` writes one on every target it prints. + */ function bareHost(value) { return trimmed(value).toLowerCase().replace(/\.+$/, "") } @@ -524,9 +486,10 @@ function isValidPort(value) { return isFinite(port) && port >= 1 && port <= 65535 } -// The domain half of an address, which is the whole of what discovery has to -// go on. An address that is not one has no domain rather than a wrong one: -// the setup page validates the address before it ever gets here. +/** The domain half of an address, which is the whole of what discovery has to + * go on. An address that is not one has no domain rather than a wrong one: + * the setup page validates the address before it ever gets here. + */ function addressDomain(address) { var text = trimmed(address) var at = text.lastIndexOf("@") @@ -540,7 +503,7 @@ function typedSessionUrl(server) { if (text === "") return "" if (/^https:\/\//i.test(text)) return text if (text.indexOf("://") >= 0) return "" - // A host with a path already says where the session is; only a bare host is + // Invariant: A host with a path already says where the session is; only a bare host is // guessed at. var slash = text.indexOf("/") if (slash >= 0) { @@ -558,29 +521,31 @@ function typedSessionUrl(server) { return isValidHost(bare) ? "https://" + bare + SESSION_PATH : "" } -// Which server, and as whom: the two settings that decide what a session is -// worth. A different URL is a different server and a different username is a -// different account on it, so a session read under one pair says nothing -// under another. The scheme and the account id are what sign-in *learns* from -// that pair, so a change to them alone — which is exactly what sign-in writes -// onto the account — is the same mailbox, and the session it just fetched -// still describes it. +/** Which server, and as whom: the two settings that decide what a session is + * worth. A different URL is a different server and a different username is a + * different account on it, so a session read under one pair says nothing + * under another. The scheme and the account id are what sign-in *learns* from + * that pair, so a change to them alone — which is exactly what sign-in writes + * onto the account — is the same mailbox, and the session it just fetched + * still describes it. + */ function serverIdentity(settings) { var values = settings || {} return trimmed(values.sessionUrl) + "\n" + trimmed(values.username) } -// Where this address's JMAP server is looked for, and in what order. -// -// { error, domain, steps: [ { kind, url } ] } -// -// `error` is the one refusal this can answer, and an errored plan has no -// steps. A typed server wins outright: somebody who filled that field in is -// answering a discovery that already failed, and walking the domain again -// afterwards would only fail again more slowly. -// -// Only HTTPS on the original address domain may delegate discovery. An -// unsigned SRV record cannot authorize sending a credential to another host. +/** Where this address's JMAP server is looked for, and in what order. + * + * { error, domain, steps: [ { kind, url } ] } + * + * `error` is the one refusal this can answer, and an errored plan has no + * steps. A typed server wins outright: somebody who filled that field in is + * answering a discovery that already failed, and walking the domain again + * afterwards would only fail again more slowly. + * + * Only HTTPS on the original address domain may delegate discovery. An + * unsigned SRV record cannot authorize sending a credential to another host. + */ function discoveryPlan(address, server) { var domain = addressDomain(address) if (trimmed(server) !== "") { @@ -590,9 +555,6 @@ function discoveryPlan(address, server) { } return { error: "", domain: domain, steps: [{ kind: STEP_TYPED, url: typed }] } } - // No server and no domain is nothing to look for. The page asks for the - // address first and validates it, so this is the empty form rather than a - // failure worth a sentence. if (domain === "") return { error: "", domain: "", steps: [] } return { error: "", @@ -603,9 +565,10 @@ function discoveryPlan(address, server) { } } -// Every step tried and none of them a session. The sentence names no provider, -// by the same instruction the setup page follows, and says what the server -// field wants rather than only that something failed. +/** Every step tried and none of them a session. The sentence names no provider, + * by the same instruction the setup page follows, and says what the server + * field wants rather than only that something failed. + */ function discoveryFailure(domain) { var name = trimmed(domain) return "No JMAP server answered for " + name @@ -613,20 +576,21 @@ function discoveryFailure(domain) { + " such as mail.example.org." } -// The one redirect hop discovery follows, taken from the reply's second line. -// -// The well-known URL is *expected* to redirect — Stalwart answers 307 to its -// own session path — and the transport follows nothing, so the decision is -// made here instead of by curl: exactly one hop, HTTPS only, and nothing at -// all from a status that is not a redirect. The unauthenticated GET is what -// makes that safe to follow; the credential goes only to the URL that finally -// answered with a session. +/** The one redirect hop discovery follows, taken from the reply's second line. + * + * The well-known URL is *expected* to redirect — Stalwart answers 307 to its + * own session path — and the transport follows nothing, so the decision is + * made here instead of by curl: exactly one hop, HTTPS only, and nothing at + * all from a status that is not a redirect. The unauthenticated GET is what + * makes that safe to follow; the credential goes only to the URL that finally + * answered with a session. + */ function redirectHop(status, redirectUrl) { var code = Number(status) if (!isFinite(code) || code < 300 || code >= 400) return "" var url = trimmed(redirectUrl) if (!/^https:\/\//i.test(url)) return "" - // Userinfo in the hop is the server's own string, and curl sends it as a + // Invariant: Userinfo in the hop is the server's own string, and curl sends it as a // Basic credential when the request carries none — which the unauthenticated // probe does not. Nothing of the user's could get there, but a URL that // carries a credential is not one this client follows. @@ -635,7 +599,7 @@ function redirectHop(status, redirectUrl) { } function discoveryHop(status, redirectUrl) { - // This Location came from the address domain's authenticated HTTPS + // Invariant: This Location came from the address domain's authenticated HTTPS // well-known response, so that response is the authority that delegates to // a hosted provider. `redirectHop` still requires HTTPS and no userinfo. return redirectHop(status, redirectUrl) @@ -654,7 +618,7 @@ function looksLikeJmapChallenge(body) { var type = trimmed(document.type) return type.indexOf("urn:ietf:params:jmap:error:") === 0 } - // Fastmail's session 401 is text/plain, not a problem document. + // Invariant: Fastmail's session 401 is text/plain, not a problem document. return text === "No Authorization header" } @@ -665,15 +629,13 @@ function sessionProbeAccepts(status, body) { return false } -// ------------------------------------------------------------ the session - -// The two capabilities a mailbox needs the server to have, and the key +// Invariant: The two capabilities a mailbox needs the server to have, and the key // `primaryAccounts` names the mail account under. var CAPABILITY_CORE = "urn:ietf:params:jmap:core" var CAPABILITY_MAIL = "urn:ietf:params:jmap:mail" var CAPABILITY_SUBMISSION = "urn:ietf:params:jmap:submission" -// The `using` array of every request this client sends, which is the list of +// Invariant: The `using` array of every request this client sends, which is the list of // capabilities the *request* needs rather than the list the server has. Named // here and built nowhere else: a vendor URN in one of these would make every // request refuseable by a server that had never heard of it, and a missing one @@ -704,18 +666,19 @@ function containsValue(list, value) { return false } -// Whether a 200 from the session URL is a mailbox this client can sign in to: -// -// { error, accountId } -// -// A 200 is not "signed in" by itself. Stalwart answers one with an empty -// `accounts` object when the Authorization header never arrives, so a check -// that stopped at the status would record an account with nothing in it and -// fail later, somewhere with no field to correct. -// -// Three refusals, each a sentence about what is missing rather than about -// JMAP. `accountId` on success is `primaryAccounts` for the mail capability, -// which is the id every later request names. +/** Whether a 200 from the session URL is a mailbox this client can sign in to: + * + * { error, accountId } + * + * A 200 is not "signed in" by itself. Stalwart answers one with an empty + * `accounts` object when the Authorization header never arrives, so a check + * that stopped at the status would record an account with nothing in it and + * fail later, somewhere with no field to correct. + * + * Three refusals, each a sentence about what is missing rather than about + * JMAP. `accountId` on success is `primaryAccounts` for the mail capability, + * which is the id every later request names. + */ function verifySession(session) { var document = parseJson(session) var notMail = { error: "The server answered, but not as a JMAP mail server", accountId: "" } @@ -732,7 +695,7 @@ function verifySession(session) { if (!accounts || countKeys(accounts) === 0 || !account) return noMailbox if (!hasCapability(account.accountCapabilities, CAPABILITY_MAIL)) return noMailbox - // Every query this client sends sorts by `receivedAt` descending, so an + // Invariant: Every query this client sends sorts by `receivedAt` descending, so an // account that cannot is one where every list would come back // `unsupportedSort` — refused here, where there is still a field to change, // rather than on the first mailbox anybody opens. RFC 8621 makes the list @@ -743,7 +706,7 @@ function verifySession(session) { if (!containsValue(sortOptions, "receivedAt")) { return { error: "The server cannot sort mail by date, which this client needs", accountId: "" } } - // The four addresses a credential is sent to, and every one of them written + // Invariant: The four addresses a credential is sent to, and every one of them written // by the server. The transport refuses anything but HTTPS before curl runs, // so nothing would have been sent either way; refusing here is the same // rule one gate earlier, where the session is still being judged and the @@ -759,38 +722,41 @@ function verifySession(session) { var SESSION_ADDRESSES = ["apiUrl", "downloadUrl", "uploadUrl", "eventSourceUrl"] -// Sending is the one capability sign-in reads and does not refuse the account -// over. A credential that cannot submit still reads mail perfectly well, so -// the account signs in and loses its send button instead. -// -// Asked of the *account* and not of the session, and this is the one place -// where the two must not be confused. The session's top-level list says the -// server was built with submission in it; `accountCapabilities` says this -// credential may use it, and RFC 8620 makes the second a subset of the first. -// Falling back to the session's list would answer yes for a read-only app -// password on a server that can submit for somebody else — a Send button that -// fails after the message is written, which is the promise this whole seam -// exists to stop being made. -// -// `accountId` is optional and names the account when the caller has one; with -// nothing it is the session's own primary mail account, which is the account -// every request from this client names anyway. +/** Sending is the one capability sign-in reads and does not refuse the account + * over. A credential that cannot submit still reads mail perfectly well, so + * the account signs in and loses its send button instead. + * + * Asked of the *account* and not of the session, and this is the one place + * where the two must not be confused. The session's top-level list says the + * server was built with submission in it; `accountCapabilities` says this + * credential may use it, and RFC 8620 makes the second a subset of the first. + * Falling back to the session's list would answer yes for a read-only app + * password on a server that can submit for somebody else — a Send button that + * fails after the message is written, which is the promise this whole seam + * exists to stop being made. + * + * `accountId` is optional and names the account when the caller has one; with + * nothing it is the session's own primary mail account, which is the account + * every request from this client names anyway. + */ function hasSubmission(session, accountId) { var account = accountFor(parseJson(session), accountId) return !!account && hasCapability(account.accountCapabilities, CAPABILITY_SUBMISSION) } -// The primary mail account of a session, which is the id `verifySession` -// records and every method call carries. +/** The primary mail account of a session, which is the id `verifySession` + * records and every method call carries. + */ function primaryAccountId(session) { var document = parseJson(session) if (!document || !document.primaryAccounts || typeof document.primaryAccounts !== "object") return "" return trimmed(document.primaryAccounts[CAPABILITY_MAIL]) } -// One account object out of a parsed session, by id or by primary. Null when -// the session names no such account, which is what a stale account id on a -// server that has been rebuilt looks like. +/** One account object out of a parsed session, by id or by primary. Null when + * the session names no such account, which is what a stale account id on a + * server that has been rebuilt looks like. + */ function accountFor(document, accountId) { if (!document || typeof document !== "object") return null var accounts = document.accounts && typeof document.accounts === "object" ? document.accounts : null @@ -802,43 +768,48 @@ function accountFor(document, accountId) { return account && typeof account === "object" ? account : null } -// One string off the session object, or "" — the shape every URL, template -// and state the session publishes is read in, and read by name here so the -// five readers below cannot disagree about what an absent one means. +/** One string off the session object, or "" — the shape every URL, template + * and state the session publishes is read in, and read by name here so the + * five readers below cannot disagree about what an absent one means. + */ function sessionField(session, name) { var document = parseJson(session) return document ? trimmed(document[name]) : "" } -// Where every method call goes. Read from the session rather than assumed: -// on the reference account the session is on one host and this URL is on -// another, and it is the second of the two places a credential may go. +/** Where every method call goes. Read from the session rather than assumed: + * on the reference account the session is on one host and this URL is on + * another, and it is the second of the two places a credential may go. + */ function apiUrl(session) { return sessionField(session, "apiUrl") } -// The template every blob is fetched through, read from the session for the -// same reason the API URL is: it is the third of the places a credential may -// go, and on the reference account it is a different host from the session's -// own. `downloadUrl` fills it; nothing else builds a download address. +/** The template every blob is fetched through, read from the session for the + * same reason the API URL is: it is the third of the places a credential may + * go, and on the reference account it is a different host from the session's + * own. `downloadUrl` fills it; nothing else builds a download address. + */ function downloadTemplate(session) { return sessionField(session, "downloadUrl") } -// The server's own word for "nothing has changed". A cached session is good -// for as long as this matches, and a push telling the client the state moved -// is what makes it refetch — so it is what a cache entry is keyed on. +/** The server's own word for "nothing has changed". A cached session is good + * for as long as this matches, and a push telling the client the state moved + * is what makes it refetch — so it is what a cache entry is keyed on. + */ function sessionState(session) { return sessionField(session, "state") } -// The state a reply says the session has moved to, or "" when it has not. -// -// Every API reply carries `sessionState` (RFC 8620 section 3.4), and one that -// differs from the held session's is the server saying its URLs, its limits or -// its accounts changed — so the held one is refetched. A reply carrying none -// says nothing, and a held session with no state of its own has nothing to -// compare, so neither moves anything. +/** The state a reply says the session has moved to, or "" when it has not. + * + * Every API reply carries `sessionState` (RFC 8620 section 3.4), and one that + * differs from the held session's is the server saying its URLs, its limits or + * its accounts changed — so the held one is refetched. A reply carrying none + * says nothing, and a held session with no state of its own has nothing to + * compare, so neither moves anything. + */ function movedSessionState(session, payload) { var document = parseJson(payload) var reported = document ? trimmed(document.sessionState) : "" @@ -847,15 +818,16 @@ function movedSessionState(session, payload) { return held !== "" && held !== reported ? reported : "" } -// The host a session URL names, which is what a user is shown afterwards: the -// mailboxes row's second line and the "Signed in" line both say the host -// rather than the whole URL, because the path is this client's business and -// the host is the thing somebody recognises. -// -// The port survives when there is one — `mail.example.org:8443` is a different -// server from `mail.example.org` and a line that hid the difference would be -// wrong on the machine most likely to need it. Any userinfo is dropped: it is -// not part of the address, and it is the half that could carry a secret. +/** The host a session URL names, which is what a user is shown afterwards: the + * mailboxes row's second line and the "Signed in" line both say the host + * rather than the whole URL, because the path is this client's business and + * the host is the thing somebody recognises. + * + * The port survives when there is one — `mail.example.org:8443` is a different + * server from `mail.example.org` and a line that hid the difference would be + * wrong on the machine most likely to need it. Any userinfo is dropped: it is + * not part of the address, and it is the half that could carry a secret. + */ function sessionHost(url) { var text = trimmed(url) var match = /^https:\/\/([^/?#]+)/i.exec(text) @@ -866,23 +838,23 @@ function sessionHost(url) { return authority.toLowerCase() } -// What the user calls the credential that worked. The scheme is detected, so -// this is the page telling them which of the two things they pasted turned out -// to be right — and it names no provider, as the rest of the page does not. +/** What the user calls the credential that worked. The scheme is detected, so + * this is the page telling them which of the two things they pasted turned out + * to be right — and it names no provider, as the rest of the page does not. + */ function schemeLabel(scheme) { return trimmed(scheme).toLowerCase() === AUTH_BEARER ? "API token" : "app password" } -// ------------------------------------------------------------ session limits - -// What `maxObjectsInGet` is worth when the session does not say. RFC 8620 +// Invariant: What `maxObjectsInGet` is worth when the session does not say. RFC 8620 // makes the figure mandatory, so this is the floor under a server that omitted // it rather than an assumption about one that stated it — the reference // Stalwart says 500 and Fastmail says something else, and neither is guessed. var DEFAULT_OBJECTS_IN_GET = 100 -// A positive whole number off the session's core capability, or 0 for one the -// session does not state. +/** A positive whole number off the session's core capability, or 0 for one the + * session does not state. + */ function coreLimit(session, name) { var document = parseJson(session) var core = document && document.capabilities && typeof document.capabilities === "object" @@ -891,7 +863,8 @@ function coreLimit(session, name) { return isFinite(value) && value > 0 ? value : 0 } -// The same, with the fallback for a session that does not state it. +/** The same, with the fallback for a session that does not state it. + */ function sessionLimit(session, name, fallback) { var value = coreLimit(session, name) if (value > 0) return value @@ -899,9 +872,10 @@ function sessionLimit(session, name, fallback) { return isFinite(floor) && floor > 0 ? floor : 1 } -// Ids split into requests no larger than the server will answer. One `Email/get` -// of 500 ids is one round trip; 500 of one id each is 500, and a page above the -// limit comes back `requestTooLarge` rather than short. +/** Ids split into requests no larger than the server will answer. One `Email/get` + * of 500 ids is one round trip; 500 of one id each is 500, and a page above the + * limit comes back `requestTooLarge` rather than short. + */ function chunked(ids, size) { var list = Array.isArray(ids) ? ids : [] var limit = Math.max(1, Math.floor(Number(size)) || 1) @@ -910,11 +884,12 @@ function chunked(ids, size) { return output } -// The arguments of the first invocation with this name in a reply. A JMAP -// response is a list of `[name, arguments, callId]` triples; the call id is the -// caller's own label and a request of one call is read by its method name. -// Null when the reply does not carry it, which is a different thing from an -// invocation that answered with an empty list. +/** The arguments of the first invocation with this name in a reply. A JMAP + * response is a list of `[name, arguments, callId]` triples; the call id is the + * caller's own label and a request of one call is read by its method name. + * Null when the reply does not carry it, which is a different thing from an + * invocation that answered with an empty list. + */ function responseArguments(responses, name) { var list = invocations(responses) var wanted = trimmed(name) @@ -924,19 +899,18 @@ function responseArguments(responses, name) { return null } -// ------------------------------------------------------------- known states -// -// The newest state the server has reported for each type, from any reply: -// -// { Email: "s41", Mailbox: "s7" } -// -// Push is the only reader. A `StateChange` naming a state this -// client has already been told is the echo of its own write, and refreshing the -// list on it is a round trip to fetch what is already on screen. -// -// `Email/query`'s `queryState` is deliberately not recorded here. That is the -// state of one query rather than of the type, a `StateChange` never names one, -// and filing it under `Email` would silence a real change. +/** The newest state the server has reported for each type, from any reply: + * + * { Email: "s41", Mailbox: "s7" } + * + * Push is the only reader. A `StateChange` naming a state this + * client has already been told is the echo of its own write, and refreshing the + * list on it is a round trip to fetch what is already on screen. + * + * `Email/query`'s `queryState` is deliberately not recorded here. That is the + * state of one query rather than of the type, a `StateChange` never names one, + * and filing it under `Email` would silence a real change. + */ function recordStates(known, responses) { var output = {} @@ -949,7 +923,7 @@ function recordStates(known, responses) { var slash = name.indexOf("/") if (slash <= 0) continue var parameters = list[itemIndex].arguments - // `newState` is where a `/set` left the type; `state` is where a `/get` + // Invariant: `newState` is where a `/set` left the type; `state` is where a `/get` // read it. Either is the newest this client has been told about. var state = trimmed(parameters.newState) !== "" ? trimmed(parameters.newState) : trimmed(parameters.state) if (state !== "") output[name.substring(0, slash)] = state @@ -957,9 +931,7 @@ function recordStates(known, responses) { return output } -// ------------------------------------------------------------ the event stream -// -// The stream is one `stream` request held open per account, and everything it +// Invariant: The stream is one `stream` request held open per account, and everything it // costs is decided here: which URL it opens, what a line off it means, what a // change notification amounts to for this account, and how long to wait before // opening it again. @@ -976,22 +948,24 @@ var EVENT_TYPES = "Email,Mailbox" var EVENT_CLOSE_AFTER = "no" var EVENT_PING_SECONDS = 30 -// The two types a `StateChange` may name that this account acts on. +// Invariant: The two types a `StateChange` may name that this account acts on. var TYPE_EMAIL = "Email" var TYPE_MAILBOX = "Mailbox" -// The template the session published, which is the only place an event-source -// address comes from — the same rule the API URL and the download template -// follow, and for the same reason: it is a URL a credential is sent to. +/** The template the session published, which is the only place an event-source + * address comes from — the same rule the API URL and the download template + * follow, and for the same reason: it is a URL a credential is sent to. + */ function eventSourceTemplate(session) { return sessionField(session, "eventSourceUrl") } -// The template, filled. Percent-encoded through `fillTemplate` exactly as a -// download URL is: `types` is a comma list and a server is free to publish a -// template whose variables sit in the path rather than the query, so a value -// that carried a `&`, a `/` or a `?` could otherwise steer the request off the -// address the session named. +/** The template, filled. Percent-encoded through `fillTemplate` exactly as a + * download URL is: `types` is a comma list and a server is free to publish a + * template whose variables sit in the path rather than the query, so a value + * that carried a `&`, a `/` or a `?` could otherwise steer the request off the + * address the session named. + */ function eventSourceUrl(template, types, ping) { var filled = String(template === undefined || template === null ? "" : template) if (filled === "") return "" @@ -1003,9 +977,7 @@ function eventSourceUrl(template, types, ping) { return filled } -// ------------------------------------------------------------- event lines -// -// `text/event-stream` is a line grammar: `field: value` lines, then a blank +// Invariant: `text/event-stream` is a line grammar: `field: value` lines, then a blank // line that ends the event. curl hands the transport's stdout over one line at // a time, so this is fed one line at a time and carries the half-read event // between calls rather than buffering the connection. @@ -1022,7 +994,7 @@ function eventSourceUrl(template, types, ping) { // says they are keep-alives; `retry:` is dropped because the reconnect table // below is this client's own and not the server's to set. -// A `StateChange` for one account naming two types is a few hundred bytes. The +// Performance: A `StateChange` for one account naming two types is a few hundred bytes. The // ceiling is not about Stalwart — it is that a half-read event is held in the // process that draws the desktop, and a server or a proxy that never sends the // blank line would otherwise grow it without end. @@ -1041,13 +1013,13 @@ function parseEventLine(state, line) { changed: null, interval: 0 } - // SplitParser splits on "\n", so a server writing CRLF leaves the CR on the + // Algorithm: SplitParser splits on "\n", so a server writing CRLF leaves the CR on the // end of every line — including the blank one that ends an event, which // would then never be recognised as blank. var text = String(line === undefined || line === null ? "" : line).replace(/\r+$/, "") if (text === "") { - // A blank line with nothing before it is the keep-alive between events, + // Algorithm: A blank line with nothing before it is the keep-alive between events, // not an event with no name. if (next.event === "" && next.data === "") return next next.kind = next.event !== "" ? next.event : "message" @@ -1070,14 +1042,14 @@ function parseEventLine(state, line) { var colon = text.indexOf(":") var field = colon < 0 ? text : text.substring(0, colon) - // "A single leading space after the colon is ignored", and only one. + // Algorithm: "A single leading space after the colon is ignored", and only one. var value = colon < 0 ? "" : text.substring(colon + 1) if (value.charAt(0) === " ") value = value.substring(1) if (field === "event") { next.event = value } else if (field === "data") { - // Data lines are joined with a newline, which is what the spec says and + // Algorithm: Data lines are joined with a newline, which is what the spec says and // what keeps a JSON document split across lines readable. next.data = next.data === "" ? value : next.data + "\n" + value if (next.data.length > MAX_EVENT_CHARS) { @@ -1085,22 +1057,20 @@ function parseEventLine(state, line) { next.data = "" } } - // `id`, `retry` and any field this client has not heard of fall through. return next } -// ---------------------------------------------------------- what a push means -// -// One rule over a `StateChange`'s `changed` map, and the whole of what the -// panel does with a push: -// -// null this event is not about this account, or the panel already -// holds every state it names — its own write, echoed back -// { mail, mailboxes } -// -// `mailboxes` re-reads the mailbox list, which is what re-binds the rail rows, -// the per-account refusals and the absent mailboxes; `mail` runs the account's -// own refresh, the same door the poll knocks on. +/** One rule over a `StateChange`'s `changed` map, and the whole of what the + * panel does with a push: + * + * null this event is not about this account, or the panel already + * holds every state it names — its own write, echoed back + * { mail, mailboxes } + * + * `mailboxes` re-reads the mailbox list, which is what re-binds the rail rows, + * the per-account refusals and the absent mailboxes; `mail` runs the account's + * own refresh, the same door the poll knocks on. + */ function refreshPlan(changed, accountId, knownStates) { var map = changed && typeof changed === "object" && !Array.isArray(changed) ? changed : null var wanted = trimmed(accountId) @@ -1114,7 +1084,7 @@ function refreshPlan(changed, accountId, knownStates) { for (var type in types) { var state = trimmed(types[type]) if (state === "") continue - // The echo. The server tells every connection about the panel's own write + // Invariant: The echo. The server tells every connection about the panel's own write // about a second after the action's callback has already revalidated, and // a state this client was handed by the reply it is the echo of is the one // thing a push can be that is worth nothing. @@ -1126,9 +1096,7 @@ function refreshPlan(changed, accountId, knownStates) { return { mail: mail, mailboxes: mailboxes } } -// --------------------------------------------------------------- reconnect -// -// curl's exit code says what happened to the stream, and the `http ` +// Invariant: curl's exit code says what happened to the stream, and the `http ` // trailer the `stream` verb prints says what the server answered before it // did. Together they are the whole of the decision: // @@ -1149,7 +1117,7 @@ var RECONNECT_BASE_MS = 1000 var RECONNECT_CAP_MS = 300000 var RECONNECT_AT_ONCE_MS = 0 -// Not a curl exit code: what the owner reports when it stopped a connection +// Invariant: Not a curl exit code: what the owner reports when it stopped a connection // curl was still perfectly happy with — the watchdog's two silent ping // intervals, or a credential that could not be read. curl's own code for a // process it was told to end says nothing about which of them ended it, and @@ -1157,7 +1125,7 @@ var RECONNECT_AT_ONCE_MS = 0 // Negative so it can never collide with one. var EXIT_STREAM_SILENT = -1 -// curl's own trailer, told from an event line. The `stream` verb ends its +// Invariant: curl's own trailer, told from an event line. The `stream` verb ends its // output with `http `, printed by `--write-out` once the transfer has // ended, and it arrives on the same stdout as the events — so it has to be // recognised, and it has to be recognised as *not* being the server talking. @@ -1179,31 +1147,32 @@ function streamTrailerStatus(line) { return isFinite(code) && code > 0 ? code : 0 } -// What the table below should read for a connection that has just ended. -// -// `heard` is whether the server said anything at all on it — an event, a ping, -// even a comment. A connection that ended having heard nothing is not a clean -// close, whatever curl exited with: the two at-once exits are the ones that -// mean "the server finished with this connection", and a server or a proxy -// answering 200 and closing immediately would otherwise be reopened every few -// milliseconds for as long as it kept doing it. Reading the decision's own -// "reset on the first event or ping" the other way round is what this is: a -// connection that never got one has nothing to reset. -// -// Every other exit keeps its meaning, which is what leaves the 401 alone — -// `--fail` writes no body, so a rejected credential is *always* a connection -// that heard nothing. -// Whether a connection has lived long enough to be believed. -// -// "Reset on the first line" read one way is the busy loop the table above -// exists to prevent: a server — or a proxy in front of one — that answers a -// comment and closes cleanly gives curl exit 0 in the time a TLS handshake -// takes, and a line arrived, so the backoff reset and the table said "at -// once". Measured: about sixty milliseconds per connection, with the -// per-connect refresh behind every one of them. A connection is settled once -// it has lasted a whole ping interval, which is the first moment the server -// has had to prove it will keep it open; until then a line is a line, and -// not a reason to forget how many times this has just failed. +/** What the table below should read for a connection that has just ended. + * + * `heard` is whether the server said anything at all on it — an event, a ping, + * even a comment. A connection that ended having heard nothing is not a clean + * close, whatever curl exited with: the two at-once exits are the ones that + * mean "the server finished with this connection", and a server or a proxy + * answering 200 and closing immediately would otherwise be reopened every few + * milliseconds for as long as it kept doing it. Reading the decision's own + * "reset on the first event or ping" the other way round is what this is: a + * connection that never got one has nothing to reset. + * + * Every other exit keeps its meaning, which is what leaves the 401 alone — + * `--fail` writes no body, so a rejected credential is *always* a connection + * that heard nothing. + * Whether a connection has lived long enough to be believed. + * + * "Reset on the first line" read one way is the busy loop the table above + * exists to prevent: a server — or a proxy in front of one — that answers a + * comment and closes cleanly gives curl exit 0 in the time a TLS handshake + * takes, and a line arrived, so the backoff reset and the table said "at + * once". Measured: about sixty milliseconds per connection, with the + * per-connect refresh behind every one of them. A connection is settled once + * it has lasted a whole ping interval, which is the first moment the server + * has had to prove it will keep it open; until then a line is a line, and + * not a reason to forget how many times this has just failed. + */ function connectionSettled(connectedAtMs, nowMs, pingSeconds) { var since = Number(nowMs) - Number(connectedAtMs) var interval = Math.floor(Number(pingSeconds)) @@ -1230,25 +1199,26 @@ function reconnectDelay(exit, status, attempt) { if (code === 0 || code === 28) return { delay: RECONNECT_AT_ONCE_MS, attempt: tries, stop: false, rejected: false } - // Doubling from a second, capped. `Math.pow` rather than a running multiply + // Algorithm: Doubling from a second, capped. `Math.pow` rather than a running multiply // so the caller holds a count rather than a duration, and a reset is one // assignment. var delay = Math.min(RECONNECT_BASE_MS * Math.pow(2, tries), RECONNECT_CAP_MS) return { delay: delay, attempt: tries + 1, stop: false, rejected: false } } -// A resume from suspend, told from a timer that simply fired late. -// -// Qt's timers run on the monotonic clock, which stops while the machine is -// suspended: a thirty-second timer that fires after a four-hour sleep has -// counted thirty seconds of running time and knows nothing has happened. The -// wall clock does know, so the two are compared — and the connection sitting -// underneath is dead however alive the socket still looks, because the server -// gave up on it hours ago. -// -// Twice the interval rather than any advance at all: a busy GUI thread delays -// a timer by tens of milliseconds routinely, and reconnecting the stream every -// time the desktop was busy would be worse than the problem. +/** A resume from suspend, told from a timer that simply fired late. + * + * Qt's timers run on the monotonic clock, which stops while the machine is + * suspended: a thirty-second timer that fires after a four-hour sleep has + * counted thirty seconds of running time and knows nothing has happened. The + * wall clock does know, so the two are compared — and the connection sitting + * underneath is dead however alive the socket still looks, because the server + * gave up on it hours ago. + * + * Twice the interval rather than any advance at all: a busy GUI thread delays + * a timer by tens of milliseconds routinely, and reconnecting the stream every + * time the desktop was busy would be worse than the problem. + */ function clockJumped(lastMs, nowMs, intervalMs) { var last = Number(lastMs) var now = Number(nowMs) @@ -1257,18 +1227,15 @@ function clockJumped(lastMs, nowMs, intervalMs) { return now - last > interval * 2 } -// ------------------------------------------------------------ mailbox roles -// -// A rail row is keyed on an RFC 8621 *role* rather than on a folder name, +// Invariant: A rail row is keyed on an RFC 8621 *role* rather than on a folder name, // because the role is the one stable name: the same row is "Junk Mail" on one // server and "Spam" on another, and both agree the role is `junk`. -// The six roles the rail resolves per account. RFC 8621 registers more — +// Invariant: The six roles the rail resolves per account. RFC 8621 registers more — // `important`, `all`, `subscribed` — and a mailbox carrying one of those is // drawn as an ordinary label under its own name. var RAIL_ROLES = ["inbox", "sent", "drafts", "archive", "junk", "trash"] -// What a sentence calls the row whose mailbox is missing. var ROLE_LABELS = { inbox: "Inbox", sent: "Sent", @@ -1278,16 +1245,13 @@ var ROLE_LABELS = { trash: "Trash" } -// The three rows that may be absent, and the rail *key* each answers to — -// which is not the role's own name. The row keyed "spam" is the mailbox whose -// role is `junk`, and `Registry.mailboxes` takes keys. var OPTIONAL_RAIL_ROWS = [ { role: "archive", key: "archive" }, { role: "junk", key: "spam" }, { role: "trash", key: "trash" } ] -// The same leaf-name guesses `ImapProtocol.specialFolders` makes, and +// Invariant: The same leaf-name guesses `ImapProtocol.specialFolders` makes, and // deliberately a second copy rather than an import of them: one provider's // guesses are not the other's to change, and a shared function is what would // carry the first divergence across. They are needed because a server may @@ -1307,16 +1271,17 @@ function mailboxArray(mailboxes) { return Array.isArray(mailboxes) ? mailboxes : [] } -// Which mailbox a rail role means on this account: the one carrying that role, -// else a top-level mailbox whose name is one of the guesses, else nothing. -// -// Inbox is never guessed. `role: "inbox"` is the one role RFC 8621 requires a -// server to set, so a name match there could only ever find a *second* folder -// somebody called "Inbox" — which is a folder, not the inbox. -// -// Top-level only for the guesses: an "Archive" under "Projects" is somebody's -// filing, and archiving into it because the account has no Archive role would -// be filing their mail for them. +/** Which mailbox a rail role means on this account: the one carrying that role, + * else a top-level mailbox whose name is one of the guesses, else nothing. + * + * Inbox is never guessed. `role: "inbox"` is the one role RFC 8621 requires a + * server to set, so a name match there could only ever find a *second* folder + * somebody called "Inbox" — which is a folder, not the inbox. + * + * Top-level only for the guesses: an "Archive" under "Projects" is somebody's + * filing, and archiving into it because the account has no Archive role would + * be filing their mail for them. + */ function resolveRole(role, mailboxes) { var wanted = trimmed(role).toLowerCase() if (wanted === "") return "" @@ -1335,14 +1300,15 @@ function resolveRole(role, mailboxes) { return "" } -// Every rail role resolved once, which is what a filter and a label id are both -// read through. A page of fifty messages then resolves six roles rather than -// three hundred, and the role a query names cannot disagree with the role a row -// was labelled from. -// -// { inbox, sent, drafts, archive, junk, trash } -// -// Each value is a mailbox id, or "" for a role this account has no mailbox for. +/** Every rail role resolved once, which is what a filter and a label id are both + * read through. A page of fifty messages then resolves six roles rather than + * three hundred, and the role a query names cannot disagree with the role a row + * was labelled from. + * + * { inbox, sent, drafts, archive, junk, trash } + * + * Each value is a mailbox id, or "" for a role this account has no mailbox for. + */ function roleMap(mailboxes) { var map = {} for (var itemIndex = 0; itemIndex < RAIL_ROLES.length; itemIndex++) { @@ -1351,13 +1317,14 @@ function roleMap(mailboxes) { return map } -// The rail rows this account has no mailbox for, as `Registry.mailboxes` takes -// them — and `null` while nothing has been read. -// -// Null rather than an empty list, because the two mean opposite things: with -// null the registry draws every row, which is right for a mailbox list still on -// its way, and an empty list is the positive answer that this account has all -// three. The client's list starts empty, so empty is "not read yet" here. +/** The rail rows this account has no mailbox for, as `Registry.mailboxes` takes + * them — and `null` while nothing has been read. + * + * Null rather than an empty list, because the two mean opposite things: with + * null the registry draws every row, which is right for a mailbox list still on + * its way, and an empty list is the positive answer that this account has all + * three. The client's list starts empty, so empty is "not read yet" here. + */ function absentMailboxes(mailboxes) { var list = mailboxArray(mailboxes) if (list.length === 0) return null @@ -1369,18 +1336,17 @@ function absentMailboxes(mailboxes) { return output } -// The sentence a user reads when a row, a button or a request needs a mailbox -// this account has not got. One wording wherever it is caught: the registry -// refuses the button with it and the client refuses the request with it, so the -// answer reads the same from either layer. +/** The sentence a user reads when a row, a button or a request needs a mailbox + * this account has not got. One wording wherever it is caught: the registry + * refuses the button with it and the client refuses the request with it, so the + * answer reads the same from either layer. + */ function missingMailboxError(role) { var label = ROLE_LABELS[trimmed(role).toLowerCase()] return "This account has no " + (label ? label : "such") + " mailbox" } -// ------------------------------------------------------------- the query DSL -// -// `Registry.js` hands down strings like "role:inbox unseen". They are opaque +// Invariant: `Registry.js` hands down strings like "role:inbox unseen". They are opaque // everywhere else — a cache key and the client's instruction, nothing more — // and this is the only reader. // @@ -1401,24 +1367,25 @@ function inboxQuery() { return { role: "inbox", mailboxId: "", criteria: "", text: "" } } -// The parse: -// -// { role, mailboxId, criteria, text } -// -// Exactly one of `role`, `mailboxId` and `text` is ever set; `criteria` is -// "unseen", "flagged" or "" and only ever accompanies a role. -// -// A prefix with nothing after it, and an empty string, are the inbox. That is -// not a case the panel produces — `searchQuery`, `labelQuery` and the rail's -// own rows write all three prefixes and never write an empty one — but a query -// that names nothing has to name something, and the inbox is the mailbox every -// other provider falls back to as well. -// -// A string that is none of the three is read as a search for those words. The -// only way to make one is a default query typed into settings, which is Gmail -// syntax by inheritance; searching for what somebody wrote shows them mail, -// where an inbox filtered by an operator this server never heard of shows them -// nothing and looks broken. +/** The parse: + * + * { role, mailboxId, criteria, text } + * + * Exactly one of `role`, `mailboxId` and `text` is ever set; `criteria` is + * "unseen", "flagged" or "" and only ever accompanies a role. + * + * A prefix with nothing after it, and an empty string, are the inbox. That is + * not a case the panel produces — `searchQuery`, `labelQuery` and the rail's + * own rows write all three prefixes and never write an empty one — but a query + * that names nothing has to name something, and the inbox is the mailbox every + * other provider falls back to as well. + * + * A string that is none of the three is read as a search for those words. The + * only way to make one is a default query typed into settings, which is Gmail + * syntax by inheritance; searching for what somebody wrote shows them mail, + * where an inbox filtered by an operator this server never heard of shows them + * nothing and looks broken. + */ function parseQuery(query) { var text = trimmed(query) var match = /^(role|mailbox|text):([\s\S]*)$/.exec(text) @@ -1441,15 +1408,16 @@ function parseQuery(query) { } } -// The parse plus the account's role map, as the JSON filter that goes to the -// server — or null when this account has no mailbox for the role, which the -// caller turns into `queryError`'s sentence and no rows. -// -// A search names no mailbox and excludes two: Junk and Trash. That is Gmail's -// rule and Fastmail's own web default, and it is why a typed search has to be -// built here rather than by the row that typed it. An account with neither -// mailbox needs no exclusion at all, and an empty `inMailboxOtherThan` is a -// condition some servers refuse. +/** The parse plus the account's role map, as the JSON filter that goes to the + * server — or null when this account has no mailbox for the role, which the + * caller turns into `queryError`'s sentence and no rows. + * + * A search names no mailbox and excludes two: Junk and Trash. That is Gmail's + * rule and Fastmail's own web default, and it is why a typed search has to be + * built here rather than by the row that typed it. An account with neither + * mailbox needs no exclusion at all, and an empty `inMailboxOtherThan` is a + * condition some servers refuse. + */ function filterFor(parsed, roles) { var query = parsed || {} var map = roles || {} @@ -1475,29 +1443,28 @@ function filterFor(parsed, roles) { if (resolved === "") return null var filter = { inMailbox: resolved } - // Unread is the absence of `$seen`, which is the one inversion in the whole + // Invariant: Unread is the absence of `$seen`, which is the one inversion in the whole // vocabulary and the easiest thing to write backwards. if (query.criteria === QUERY_UNSEEN) filter.notKeyword = "$seen" if (query.criteria === QUERY_FLAGGED) filter.hasKeyword = "$flagged" return filter } -// Why `filterFor` answered nothing. Only an unresolved role can produce one — a -// search and a mailbox id always build a filter — so the wording is the -// missing-mailbox sentence the button and the row already use. +/** Why `filterFor` answered nothing. Only an unresolved role can produce one — a + * search and a mailbox id always build a filter — so the wording is the + * missing-mailbox sentence the button and the row already use. + */ function queryError(parsed, roles) { if (filterFor(parsed, roles)) return "" return missingMailboxError((parsed || {}).role) } -// ------------------------------------------------------------------ paging - -// RFC 8621 section 4.4.2 makes `receivedAt` the one sort a server MUST support, +// Invariant: RFC 8621 section 4.4.2 makes `receivedAt` the one sort a server MUST support, // and sign-in refuses an account whose `emailQuerySortOptions` does not list it // — so this cannot come back `unsupportedSort` at runtime. var EMAIL_SORT = [{ property: "receivedAt", isAscending: false }] -// One row per conversation, on every query: rail rows, user folders and search +// Invariant: One row per conversation, on every query: rail rows, user folders and search // alike. `total` therefore counts conversations rather than messages, which is // what makes the Unread badge agree with the rows the Unread view draws. // @@ -1511,16 +1478,17 @@ function pageLimit(limit) { return isFinite(value) && value > 0 ? value : 25 } -// `|`, and it carries two values because the next page is -// *fetched* by anchor and *recovered* by position. -// -// Newest-first with mail arriving between pages is the common case, and an -// anchor keeps the seam exact through it where a bare position would repeat or -// skip a row. The one thing an anchor cannot survive is the anchor itself -// moving or being deleted, which the server answers `anchorNotFound` — so the -// position travels beside it and the retry costs a request only then. -// -// A JMAP id is `A-Za-z0-9_-` by RFC 8620, so the `|` can never be part of one. +/** `|`, and it carries two values because the next page is + * *fetched* by anchor and *recovered* by position. + * + * Newest-first with mail arriving between pages is the common case, and an + * anchor keeps the seam exact through it where a bare position would repeat or + * skip a row. The one thing an anchor cannot survive is the anchor itself + * moving or being deleted, which the server answers `anchorNotFound` — so the + * position travels beside it and the retry costs a request only then. + * + * A JMAP id is `A-Za-z0-9_-` by RFC 8620, so the `|` can never be part of one. + */ function pageToken(position, ids) { var list = Array.isArray(ids) ? ids : [] if (list.length === 0) return "" @@ -1534,8 +1502,9 @@ function parsePageToken(token) { return { position: Math.floor(Number(match[1])), anchor: match[2] } } -// The `Email/query` arguments for one page. `byPosition` is the retry after an -// `anchorNotFound`, and is the only thing that reads the token's first half. +/** The `Email/query` arguments for one page. `byPosition` is the retry after an + * `anchorNotFound`, and is the only thing that reads the token's first half. + */ function emailQuery(accountId, filter, limit, token, byPosition) { var page = parsePageToken(token) var parameters = { @@ -1544,7 +1513,7 @@ function emailQuery(accountId, filter, limit, token, byPosition) { sort: EMAIL_SORT, collapseThreads: COLLAPSE_THREADS, limit: pageLimit(limit), - // On every page, on both reference servers, and exact on both. RFC 8620 + // Invariant: On every page, on both reference servers, and exact on both. RFC 8620 // lets a server decline it, which is what `queryPage`'s second reading is // for rather than a reason not to ask. calculateTotal: true @@ -1558,23 +1527,24 @@ function emailQuery(accountId, filter, limit, token, byPosition) { return parameters } -// One `Email/query` reply as the page `listMessages` answers with: -// -// { ids, threadIds, nextPageToken, estimate } -// -// `estimate` is `total` where the server calculated one. Where it declined it -// is what has been seen so far plus one for a page that came back full — the -// same lower bound `ImapProtocol.searchPage` reports, and the reason the panel -// already words a provider total as "about". -// -// The token is empty at the end of the result under either reading: a page -// shorter than the limit, or a total already reached. A position past the end -// is an empty page rather than an error, which is verified on the server. -// -// `threadIds` stays empty, as IMAP's and HEY's do. The collapsed read knows -// every representative's thread id and hands it over on the summary instead; -// nothing above the seam reads the parallel array, and a second place to state -// a thread id is a second place for it to be wrong. +/** One `Email/query` reply as the page `listMessages` answers with: + * + * { ids, threadIds, nextPageToken, estimate } + * + * `estimate` is `total` where the server calculated one. Where it declined it + * is what has been seen so far plus one for a page that came back full — the + * same lower bound `ImapProtocol.searchPage` reports, and the reason the panel + * already words a provider total as "about". + * + * The token is empty at the end of the result under either reading: a page + * shorter than the limit, or a total already reached. A position past the end + * is an empty page rather than an error, which is verified on the server. + * + * `threadIds` stays empty, as IMAP's and HEY's do. The collapsed read knows + * every representative's thread id and hands it over on the summary instead; + * nothing above the seam reads the parallel array, and a second place to state + * a thread id is a second place for it to be wrong. + */ function queryPage(parameters, limit) { var body = parameters && typeof parameters === "object" ? parameters : {} var ids = [] @@ -1597,9 +1567,7 @@ function queryPage(parameters, limit) { } } -// -------------------------------------------------------- mailboxes as labels - -// What one `Mailbox/get` asks for: what the rail resolves roles from, what the +// Invariant: What one `Mailbox/get` asks for: what the rail resolves roles from, what the // sidebar prints, and what the counts are read out of, in one read rather than // three. var MAILBOX_PROPERTIES = [ @@ -1607,7 +1575,7 @@ var MAILBOX_PROPERTIES = [ "totalEmails", "unreadEmails", "unreadThreads" ] -// A parent chain that loops is a server bug; here it would be an infinite loop +// Invariant: A parent chain that loops is a server bug; here it would be an infinite loop // on the thread that draws the user's whole desktop. var MAX_MAILBOX_DEPTH = 16 @@ -1616,9 +1584,10 @@ function countOf(value) { return isFinite(number) && number > 0 ? number : 0 } -// "Parent / Child", walked up through `parentId`. The sidebar draws a flat -// list, so a nested folder that printed only its leaf would be two rows called -// "Receipts" with nothing to tell them apart. +/** "Parent / Child", walked up through `parentId`. The sidebar draws a flat + * list, so a nested folder that printed only its leaf would be two rows called + * "Receipts" with nothing to tell them apart. + */ function mailboxPath(box, byId) { var entry = box || {} var names = [trimmed(entry.name)] @@ -1637,22 +1606,23 @@ function mailboxPath(box, byId) { return names.join(" / ") } -// Every mailbox as a label, in the shape the sidebar and the cache already read -// Gmail's in. -// -// Every one of them, including the six the rail already draws: `system` says -// which those are and the sidebar lists the rest below, so a client that hid -// them here would have nothing to hand a view that wanted them. Subscription -// state is ignored, as IMAP ignores LSUB. -// -// `id` and `rawName` are both the mailbox id: one is the cache key, the other -// is what goes back in a filter, and only the printed name is a path — which is -// why nothing here has to be taken apart again on the way out. -// -// Ordered by the server's own `sortOrder` and then by the printed path, so a -// server that sorts nothing still comes back in a stable order rather than in -// hash order. This is the order the list is cached in, not the order it is -// drawn in: the rail and the move picker sort by name in `Model.railLabels`. +/** Every mailbox as a label, in the shape the sidebar and the cache already read + * Gmail's in. + * + * Every one of them, including the six the rail already draws: `system` says + * which those are and the sidebar lists the rest below, so a client that hid + * them here would have nothing to hand a view that wanted them. Subscription + * state is ignored, as IMAP ignores LSUB. + * + * `id` and `rawName` are both the mailbox id: one is the cache key, the other + * is what goes back in a filter, and only the printed name is a path — which is + * why nothing here has to be taken apart again on the way out. + * + * Ordered by the server's own `sortOrder` and then by the printed path, so a + * server that sorts nothing still comes back in a stable order rather than in + * hash order. This is the order the list is cached in, not the order it is + * drawn in: the rail and the move picker sort by name in `Model.railLabels`. + */ function mailboxLabels(mailboxes, roles) { var list = mailboxArray(mailboxes) var map = roles || {} @@ -1698,7 +1668,8 @@ function mailboxLabels(mailboxes, roles) { return output } -// One mailbox's counts, in the shape `getLabelCounts` answers with. +/** One mailbox's counts, in the shape `getLabelCounts` answers with. + */ function labelCounts(mailbox) { var box = mailbox && typeof mailbox === "object" ? mailbox : {} return { @@ -1709,19 +1680,11 @@ function labelCounts(mailbox) { } } -// ------------------------------------------------ an Email as a message row -// -// Every client hands back Gmail's message resource, and this composes one +// Invariant: Every client hands back Gmail's message resource, and this composes one // rather than parsing it — the way `HeyClient.toMessage` composes. The server // has already parsed the message; asking it for the raw blob as well would cost // a second round trip and a MIME parse to rebuild what is in hand. -// What a list row needs and nothing more. -// -// The three `header:…:asRaw` values are asked for by name because JMAP's parsed -// fields do not carry them: the unsubscribe path reads the two `List-` lines -// verbatim, and a `Date` header is what a reply quotes. Nothing is asked for -// that no row reads. `hasAttachment` identifies the list's paperclip. var LIST_PROPERTIES = [ "id", "blobId", "threadId", "mailboxIds", "keywords", "size", "receivedAt", "from", "to", "cc", "subject", "preview", "hasAttachment", @@ -1747,16 +1710,16 @@ function inMailbox(email, mailboxId) { return isSet(ids[id]) } -// The Gmail label ids a JMAP message amounts to, so a row, a star and an unread -// dot work unchanged above the seam. `roles` is the account's role map, which -// is the whole of what a membership means: a mailbox the rail does not draw — -// a user folder, or a role that resolved to nothing — contributes no id. -// -// A message in several mailboxes gets every matching id, as Gmail's does. +/** The Gmail label ids a JMAP message amounts to, so a row, a star and an unread + * dot work unchanged above the seam. `roles` is the account's role map, which + * is the whole of what a membership means: a mailbox the rail does not draw — + * a user folder, or a role that resolved to nothing — contributes no id. + * + * A message in several mailboxes gets every matching id, as Gmail's does. + */ function labelIdsFor(email, roles) { var map = roles || {} var ids = [] - // Unread is the *absence* of `$seen`. if (!hasKeyword(email, "$seen")) ids.push("UNREAD") if (hasKeyword(email, "$flagged")) ids.push("STARRED") if (hasKeyword(email, "$draft") || inMailbox(email, map.drafts)) ids.push("DRAFT") @@ -1779,9 +1742,10 @@ function addressHeaderValue(values) { return output.join(", ") } -// `messageId`, `inReplyTo` and `references` are bare ids in JMAP and -// angle-bracketed in a header. The bracketed form is what every reply writes -// back and what `Message.parseRfc822` reads, so the composer restores it. +/** `messageId`, `inReplyTo` and `references` are bare ids in JMAP and + * angle-bracketed in a header. The bracketed form is what every reply writes + * back and what `Message.parseRfc822` reads, so the composer restores it. + */ function angleBracketed(values) { var list = Array.isArray(values) ? values : [] var output = [] @@ -1793,23 +1757,25 @@ function angleBracketed(values) { return output.join(" ") } -// A raw header value, whichever key the server filed it under. -// -// RFC 8621 section 4.1.1 names the property `header:{field}:{form}` and a -// server is expected to echo that back — but the reference Stalwart answers -// `header:Date` for a request for `header:Date:asRaw`, dropping the form. Both -// are read because both are real, and a client that read only the asked-for -// name got no Date, no List-Unsubscribe and no unsubscribe link on the server -// this provider was written against. +/** A raw header value, whichever key the server filed it under. + * + * RFC 8621 section 4.1.1 names the property `header:{field}:{form}` and a + * server is expected to echo that back — but the reference Stalwart answers + * `header:Date` for a request for `header:Date:asRaw`, dropping the form. Both + * are read because both are real, and a client that read only the asked-for + * name got no Date, no List-Unsubscribe and no unsubscribe link on the server + * this provider was written against. + */ function rawHeader(email, name) { var source = email && typeof email === "object" ? email : {} var asked = trimmed(source["header:" + name + ":asRaw"]) return asked !== "" ? asked : trimmed(source["header:" + name]) } -// `Mail.decodeSnippet` unescapes Gmail's HTML-escaped snippet on the way to a -// row. A JMAP `preview` is plain text, so it is escaped on the way in or a -// sender writing "<3" loses it to a tag that never existed. +/** `Mail.decodeSnippet` unescapes Gmail's HTML-escaped snippet on the way to a + * row. A JMAP `preview` is plain text, so it is escaped on the way in or a + * sender writing "<3" loses it to a tag that never existed. + */ function escapedPreview(text) { return String(text === undefined || text === null ? "" : text) .replace(/&/g, "&") @@ -1817,8 +1783,9 @@ function escapedPreview(text) { .replace(/>/g, ">") } -// `receivedAt` is a UTC date-time string and `internalDate` is epoch -// milliseconds in a string, which is what every date in the panel is read from. +/** `receivedAt` is a UTC date-time string and `internalDate` is epoch + * milliseconds in a string, which is what every date in the panel is read from. + */ function receivedMillis(value) { var text = trimmed(value) if (text === "") return "" @@ -1826,7 +1793,7 @@ function receivedMillis(value) { return isFinite(parsed) && parsed > 0 ? String(parsed) : "" } -// A JMAP Email as the shared message resource, for a list row. +// Invariant: A JMAP Email as the shared message resource, for a list row. // // The body is empty and the mime type is `text/plain` with no data, which is // what Gmail's own metadata format hands over: a row draws from the headers, @@ -1867,15 +1834,16 @@ function composedHeaders(source) { return headers } -// Everything else the message carried, which is what `headers` is asked for on -// a full read and the reason a reply can find a `Reply-To` at all: JMAP has no -// parsed field for one, and `Message.summarize` reads it out of this array. -// Values are trimmed for the same reason the raw ones are — Stalwart writes the -// leading space RFC 5322 puts after the colon into the value. -// -// A name the composed list already wrote is dropped rather than repeated: a -// second `From` would be found by nothing and read by nobody, and a duplicate -// is how a header array starts disagreeing with itself. +/** Everything else the message carried, which is what `headers` is asked for on + * a full read and the reason a reply can find a `Reply-To` at all: JMAP has no + * parsed field for one, and `Message.summarize` reads it out of this array. + * Values are trimmed for the same reason the raw ones are — Stalwart writes the + * leading space RFC 5322 puts after the colon into the value. + * + * A name the composed list already wrote is dropped rather than repeated: a + * second `From` would be found by nothing and read by nobody, and a duplicate + * is how a header array starts disagreeing with itself. + */ function extraHeaders(email) { var list = email && Array.isArray(email.headers) ? email.headers : [] var written = {} @@ -1901,7 +1869,7 @@ function toMessage(email, roles, full) { parts: [] } - // A full read replaces that placeholder with the message's own MIME tree — + // Invariant: A full read replaces that placeholder with the message's own MIME tree — // and only when the server actually sent one, so a server that answered a // full read with list properties still opens as a row rather than as // nothing at all. @@ -1911,7 +1879,7 @@ function toMessage(email, roles, full) { partId: built.partId, mimeType: built.mimeType, filename: built.filename, - // The structure's root repeats the message's headers verbatim; the + // Invariant: The structure's root repeats the message's headers verbatim; the // composed ones are used instead so the reader and the row agree, with // the rest appended. headers: headers.concat(extraHeaders(source)), @@ -1921,7 +1889,7 @@ function toMessage(email, roles, full) { } return { - // The bare Email id, unique per account and stable across a move, so it + // Invariant: The bare Email id, unique per account and stable across a move, so it // needs no mailbox suffix as an IMAP UID does. id: trimmed(source.id), threadId: trimmed(source.threadId), @@ -1930,15 +1898,13 @@ function toMessage(email, roles, full) { sizeEstimate: countOf(source.size), hasAttachments: source.hasAttachment === true, payload: payload, - // The preview again, never rebuilt from the body: a reader that recomputed + // Invariant: The preview again, never rebuilt from the body: a reader that recomputed // it would show a different snippet from the row it was opened out of. snippet: escapedPreview(source.preview) } } -// ------------------------------------------------------------- a full read -// -// What the reader needs on top of a row: the message's own headers, the MIME +// Invariant: What the reader needs on top of a row: the message's own headers, the MIME // tree, and the text of the parts that are text. Never `fetchAllBodyValues` — // it also ships every text *attachment* inline, which the probe measured // (`notes.txt` arrived whole), and a text attachment may be 20 MB of somebody @@ -1949,7 +1915,7 @@ function toMessage(email, roles, full) { // on the value, and `truncatedParts` is what the client then fetches whole. var FULL_PROPERTIES = LIST_PROPERTIES.concat(["headers", "bodyStructure", "bodyValues"]) -// The part fields the composer builds a Gmail part out of. `cid` and `headers` +// Invariant: The part fields the composer builds a Gmail part out of. `cid` and `headers` // are both asked for: `cid` is the field a `cid:` source would one day be // resolved through, and `headers` is where `Content-ID` lives for anything // that looks for it there instead — so a JMAP message behaves as an IMAP one @@ -1959,13 +1925,14 @@ var BODY_PROPERTIES = [ "headers" ] -// Deep enough for any message a human wrote and shallow enough that a hostile +// Invariant: Deep enough for any message a human wrote and shallow enough that a hostile // one cannot walk the stack out. `Message.js` uses the same figure on the // parsing side. var MAX_PART_DEPTH = 12 -// The `Email/get` arguments for a list read or a full one, so the two requests -// are described in one place and a test can read exactly what crosses. +/** The `Email/get` arguments for a list read or a full one, so the two requests + * are described in one place and a test can read exactly what crosses. + */ function emailGet(accountId, ids, full) { var parameters = { accountId: trimmed(accountId), @@ -1983,15 +1950,16 @@ function isTextType(type) { return trimmed(type).toLowerCase().indexOf("text/") === 0 } -// A part's MIME type as a Gmail part states it, charset included, because -// `Message.decodePart` reads the charset off this string before it reads a -// header. Which charset that is depends on where the octets came from, and -// getting it wrong is a body of question marks: -// -// - a body value JMAP handed over has already been decoded, so it is UTF-8 -// whatever the sender wrote -// - a part delivered as a blob is the raw octets after content-transfer -// decoding, so it is still in the charset the sender declared +/** A part's MIME type as a Gmail part states it, charset included, because + * `Message.decodePart` reads the charset off this string before it reads a + * header. Which charset that is depends on where the octets came from, and + * getting it wrong is a body of question marks: + * + * - a body value JMAP handed over has already been decoded, so it is UTF-8 + * whatever the sender wrote + * - a part delivered as a blob is the raw octets after content-transfer + * decoding, so it is still in the charset the sender declared + */ function partMimeType(type, charset) { var mime = trimmed(type).toLowerCase() if (mime === "") mime = "application/octet-stream" @@ -2000,8 +1968,9 @@ function partMimeType(type, charset) { return set === "" ? mime : mime + "; charset=" + set } -// The part's headers as a Gmail part carries them: names and values, values -// trimmed of the leading space the server writes after the colon. +/** The part's headers as a Gmail part carries them: names and values, values + * trimmed of the leading space the server writes after the colon. + */ function partHeaders(part) { var list = part && Array.isArray(part.headers) ? part.headers : [] var output = [] @@ -2021,11 +1990,12 @@ function bodyValueFor(values, partId) { return found && typeof found === "object" ? found : null } -// How many bytes a base64 string stands for, without decoding it. The value -// has just been encoded from the body, and decoding it again to count the -// bytes would walk the whole message a second time for a number that is -// arithmetic. Both alphabets and either padding: the transport's answer is -// padded standard base64 and the composer's own is unpadded base64url. +/** How many bytes a base64 string stands for, without decoding it. The value + * has just been encoded from the body, and decoding it again to count the + * bytes would walk the whole message a second time for a number that is + * arithmetic. Both alphabets and either padding: the transport's answer is + * padded standard base64 and the composer's own is unpadded base64url. + */ function base64ByteLength(text) { var input = String(text === undefined || text === null ? "" : text) .replace(/=+$/, "") @@ -2036,18 +2006,19 @@ function base64ByteLength(text) { return whole } -// One node of `bodyStructure` as a Gmail part. -// -// A container keeps its children and nothing else. A leaf is one of two things -// and never both: -// -// - text whose value arrived, which gets `body.data` as base64url of the -// UTF-8 re-encoding and no attachment id — the reader decodes it in place -// - everything else, which gets `body.size` and `body.attachmentId` set to -// the part's `blobId` and no data at all. That is exactly the shape -// `Message.attachments`, `Calendar.pendingPart` and the open-attachment -// path already consume from Gmail, so a text attachment the server did not -// inline is listed as a file rather than drawn as the body. +/** One node of `bodyStructure` as a Gmail part. + * + * A container keeps its children and nothing else. A leaf is one of two things + * and never both: + * + * - text whose value arrived, which gets `body.data` as base64url of the + * UTF-8 re-encoding and no attachment id — the reader decodes it in place + * - everything else, which gets `body.size` and `body.attachmentId` set to + * the part's `blobId` and no data at all. That is exactly the shape + * `Message.attachments`, `Calendar.pendingPart` and the open-attachment + * path already consume from Gmail, so a text attachment the server did not + * inline is listed as a file rather than drawn as the body. + */ function toPart(part, values, depth) { var source = part && typeof part === "object" ? part : {} var type = trimmed(source.type) @@ -2060,7 +2031,7 @@ function toPart(part, values, depth) { body: { size: 0 }, parts: [] } - // Kept for the day a `cid:` source is resolved to bytes. Nothing reads it + // Invariant: Kept for the day a `cid:` source is resolved to bytes. Nothing reads it // today — no provider resolves one, and `Html.imageSourceKind` calls it // inline and keeps the tag — and keeping it here is what makes that a change // above the seam rather than a change to this provider. @@ -2075,7 +2046,7 @@ function toPart(part, values, depth) { var value = isTextType(type) ? bodyValueFor(values, source.partId) : null if (value && typeof value.value === "string") { - // `isEncodingProblem` is accepted as it stands: the server has already put + // Invariant: `isEncodingProblem` is accepted as it stands: the server has already put // U+FFFD where the sender's octets were not what they claimed to be, and // there is nothing better this end could do with them. var data = Mail.encodeBase64Url(value.value) @@ -2091,12 +2062,13 @@ function toPart(part, values, depth) { return node } -// The text parts a server truncated, which RFC 8621 lets it do whatever this -// client asked for. Each is fetched whole through the same download the -// attachment path uses and put back before the message is delivered, so the -// reader never shows a body that stops mid-sentence. -// -// A part with no `blobId` is not listed: there would be nothing to fetch. +/** The text parts a server truncated, which RFC 8621 lets it do whatever this + * client asked for. Each is fetched whole through the same download the + * attachment path uses and put back before the message is delivered, so the + * reader never shows a body that stops mid-sentence. + * + * A part with no `blobId` is not listed: there would be nothing to fetch. + */ function truncatedParts(email) { var source = email && typeof email === "object" ? email : {} var values = source.bodyValues @@ -2128,18 +2100,19 @@ function truncatedParts(email) { return output } -// The octets of a truncated part, put back where the short value was. -// -// The charset moves with them. The value that was there had been decoded to -// UTF-8 by the server; these are the sender's own octets in the sender's own -// charset, so a part that declared `iso-8859-1` has to go back to declaring it -// or the repair would read worse than the truncation. -// -// The size is what actually arrived rather than what the structure promised: -// the number on the part is the one the reader should be able to trust. -// -// Returns whether the part was found, so a caller can tell a substitution that -// happened from one that quietly did not. +/** The octets of a truncated part, put back where the short value was. + * + * The charset moves with them. The value that was there had been decoded to + * UTF-8 by the server; these are the sender's own octets in the sender's own + * charset, so a part that declared `iso-8859-1` has to go back to declaring it + * or the repair would read worse than the truncation. + * + * The size is what actually arrived rather than what the structure promised: + * the number on the part is the one the reader should be able to trust. + * + * Returns whether the part was found, so a caller can tell a substitution that + * happened from one that quietly did not. + */ function substitutePart(payload, part, data) { var wanted = trimmed(part && part.partId) var encoded = String(data === undefined || data === null ? "" : data) @@ -2165,9 +2138,7 @@ function substitutePart(payload, part, data) { return done } -// ------------------------------------------------------ actions as patches -// -// `MailAccount` does not know which provider it is driving: it asks for a +// Invariant: `MailAccount` does not know which provider it is driving: it asks for a // *label change*, in Gmail's vocabulary, because that is the vocabulary every // view already speaks. This is where that request becomes JMAP, exactly as // `ImapProtocol.flagPlanForLabels` is where it becomes IMAP. @@ -2178,33 +2149,18 @@ function substitutePart(payload, part, data) { // label, while a JMAP message holds a *set* of mailboxes — so those become // `mailboxIds` keys instead. -// How a key is taken out of a patch — a keyword, or a mailbox membership. RFC +// Invariant: How a key is taken out of a patch — a keyword, or a mailbox membership. RFC // 8620 patches a value out with `null`; the reference server also accepts // `false`, which is not used, because `null` is the form the RFC names and a // server entitled to refuse the other one is entitled to. var PATCH_REMOVE = null -// What `maxObjectsInSet` is worth when the session does not say, for the same +// Invariant: What `maxObjectsInSet` is worth when the session does not say, for the same // reason `DEFAULT_OBJECTS_IN_GET` exists: RFC 8620 makes the figure mandatory, // so this is the floor under a server that omitted it rather than an assumption // about one that stated it. The reference server says 500. var DEFAULT_OBJECTS_IN_SET = 100 -// Where each move goes and what it leaves behind. -// -// to the destination role, which has to resolve or the whole request -// fails here, before anything is sent. -// from the role the message stops being in, skipped when it resolves to -// nothing — leaving a mailbox this account has not got is not a -// thing that can happen, and `null` on an absent key is harmless. -// replace true where `mailboxIds` is written *whole* rather than patched, so -// the message is in exactly the one mailbox afterwards. -// -// Archive and unarchive are patches on purpose: a message may legitimately sit -// in a user folder as well as the Inbox, and archiving it should swap the one -// membership rather than file away the other. Trash and spam are replaces, -// which is what `Model.survivesAction` and `cachedSummaryInSearch` already -// assume about a message that has been thrown away or reported. var MOVES = { archive: { to: "archive", from: "inbox", replace: false }, unarchive: { to: "inbox", from: "archive", replace: false }, @@ -2221,48 +2177,45 @@ function hasLabel(list, id) { return false } -// Which move a set of label changes amounts to, or "" for a change that is only -// keywords. -// -// Named in the table's own order so a later move overrides an earlier one, and -// that is a rule rather than a tie-break: "report spam" arrives as add SPAM -// *and* remove INBOX, and reading the first of those as an archive would file -// the message on an account with an Archive mailbox and refuse the request on -// one without — for a user who asked to report junk. +/** Which move a set of label changes amounts to, or "" for a change that is only + * keywords. + * + * Named in the table's own order so a later move overrides an earlier one, and + * that is a rule rather than a tie-break: "report spam" arrives as add SPAM + * *and* remove INBOX, and reading the first of those as an archive would file + * the message on an account with an Archive mailbox and refuse the request on + * one without — for a user who asked to report junk. + */ function moveFor(added, removed) { var move = "" if (hasLabel(removed, "INBOX")) move = "archive" if (hasLabel(added, "INBOX")) move = "unarchive" - // Untrash arrives as its own verb rather than as a label change, and this is - // the Gmail vocabulary for it: a restored message is one the TRASH label came - // off. JMAP remembers no previous mailbox — a trashed Email carries - // `mailboxIds` and keywords and nothing else — so it goes to the Inbox, which - // is where `ImapClient.untrashMessage` moves one. if (hasLabel(removed, "TRASH")) move = "untrash" if (hasLabel(added, "TRASH")) move = "trash" if (hasLabel(added, "SPAM")) move = "spam" return move } -// Which members a move must leave alone, given where the message currently -// sits. -// -// An action on a conversation row is sent for every counted member, and two of -// these moves are wrong on a member that was never in the Inbox: archiving -// would *add* a sent reply — or a message a filter put in a user folder — to -// the Archive mailbox, and reporting spam would move the account's own replies -// into Junk and train the classifier on them. Gmail's archive is "remove -// INBOX", which does nothing to a message that has not got it; this is that -// rule written out, because JMAP's archive has to name a destination. -// -// `mailboxIds` is the client's membership map for this one id, and `null` means -// *unknown* rather than "not in the Inbox": an id the last list read did not -// carry gets the plain single-message patch, which is also the right answer -// for a lone message — a search hit in a user folder is "add Archive". -// -// A role that does not resolve skips nothing. There is no membership to test -// against, and a request that quietly did nothing is worse than one the server -// answers for. +/** Which members a move must leave alone, given where the message currently + * sits. + * + * An action on a conversation row is sent for every counted member, and two of + * these moves are wrong on a member that was never in the Inbox: archiving + * would *add* a sent reply — or a message a filter put in a user folder — to + * the Archive mailbox, and reporting spam would move the account's own replies + * into Junk and train the classifier on them. Gmail's archive is "remove + * INBOX", which does nothing to a message that has not got it; this is that + * rule written out, because JMAP's archive has to name a destination. + * + * `mailboxIds` is the client's membership map for this one id, and `null` means + * *unknown* rather than "not in the Inbox": an id the last list read did not + * carry gets the plain single-message patch, which is also the right answer + * for a lone message — a search hit in a user folder is "add Archive". + * + * A role that does not resolve skips nothing. There is no membership to test + * against, and a request that quietly did nothing is worse than one the server + * answers for. + */ function movesMember(move, mailboxIds, map) { if (!Array.isArray(mailboxIds)) return true var held = [] @@ -2281,27 +2234,25 @@ function movesMember(move, mailboxIds, map) { return true } -// One patch for one message, from the label ids to add and remove, the -// account's role map and — for a member of a conversation — where that message -// currently sits — **or an error sentence**, when the account has no mailbox -// for the move being asked for. The two are told apart by type: a patch is an -// object and a refusal is a string. -// -// The refusal is the point. IMAP's plan yields no move on an account with no -// Archive folder and the request quietly succeeds, having done nothing; here a -// destination that does not resolve is a failure before any request, so the -// account puts the row back and says which mailbox is missing. The alternative -// the server offers is worse: a `mailboxIds/: null` with nothing to take -// its place is refused as "Message has to belong to at least one mailbox". +/** One patch for one message, from the label ids to add and remove, the + * account's role map and — for a member of a conversation — where that message + * currently sits — **or an error sentence**, when the account has no mailbox + * for the move being asked for. The two are told apart by type: a patch is an + * object and a refusal is a string. + * + * The refusal is the point. IMAP's plan yields no move on an account with no + * Archive folder and the request quietly succeeds, having done nothing; here a + * destination that does not resolve is a failure before any request, so the + * account puts the row back and says which mailbox is missing. The alternative + * the server offers is worse: a `mailboxIds/: null` with nothing to take + * its place is refused as "Message has to belong to at least one mailbox". + */ function patchFor(addLabelIds, removeLabelIds, roles, mailboxIds) { var added = Array.isArray(addLabelIds) ? addLabelIds : [] var removed = Array.isArray(removeLabelIds) ? removeLabelIds : [] var map = roles && typeof roles === "object" ? roles : {} var patch = {} - // The inversion: Gmail's UNREAD is a label you *add*, JMAP's `$seen` is a - // keyword you *take away*. Getting this backwards marks read what the user - // has just marked unread. if (hasLabel(added, "UNREAD")) patch["keywords/$seen"] = PATCH_REMOVE if (hasLabel(removed, "UNREAD")) patch["keywords/$seen"] = true if (hasLabel(added, "STARRED")) patch["keywords/$flagged"] = true @@ -2314,7 +2265,7 @@ function patchFor(addLabelIds, removeLabelIds, roles, mailboxIds) { var to = trimmed(map[plan.to]) if (to === "") return missingMailboxError(plan.to) - // Where this member sits decides whether the move reaches it at all. The + // Invariant: Where this member sits decides whether the move reaches it at all. The // refusal above comes first on purpose: an account with no Archive mailbox is // told so whichever members the row counted. if (!movesMember(move, mailboxIds, map)) return patch @@ -2329,7 +2280,7 @@ function patchFor(addLabelIds, removeLabelIds, roles, mailboxIds) { if (from !== "" && from !== to) patch["mailboxIds/" + from] = PATCH_REMOVE } - // Reporting spam says something about the message as well as moving it. RFC + // Invariant: Reporting spam says something about the message as well as moving it. RFC // 8621 registers both keywords and the reference server writes `$junk` on a // message its own classifier caught; a server that ignores them loses // nothing, and one that learns from them is told. Nothing sets `$notjunk`, @@ -2341,25 +2292,27 @@ function patchFor(addLabelIds, removeLabelIds, roles, mailboxIds) { return patch } -// A patch that would change nothing, which is a request worth not making: a -// label change this provider has no mapping for should not cost a round trip -// and an `Email/set` that names every id and then asks for nothing. +/** A patch that would change nothing, which is a request worth not making: a + * label change this provider has no mapping for should not cost a round trip + * and an `Email/set` that names every id and then asks for nothing. + */ function patchIsEmpty(patch) { if (!patch || typeof patch !== "object") return true for (var key in patch) return false return true } -// The `Email/set` arguments for one patch over a list of ids, so the request an -// action becomes is described in one place and a test can read exactly what -// crosses. -// -// No `ifInState`, ever. A value the server never issued comes back as a -// request-level 400 `notRequest` on the reference server rather than the -// `stateMismatch` RFC 8620 describes, so a client that guessed one would fail -// every action outright; and an action is a change the user asked for rather -// than one conditional on the list being current. If refresh-by-delta ever -// adopts it, it may only ever carry a state the server returned. +/** The `Email/set` arguments for one patch over a list of ids, so the request an + * action becomes is described in one place and a test can read exactly what + * crosses. + * + * No `ifInState`, ever. A value the server never issued comes back as a + * request-level 400 `notRequest` on the reference server rather than the + * `stateMismatch` RFC 8620 describes, so a client that guessed one would fail + * every action outright; and an action is a change the user asked for rather + * than one conditional on the list being current. If refresh-by-delta ever + * adopts it, it may only ever carry a state the server returned. + */ function emailSet(accountId, ids, patch) { var update = {} var list = Array.isArray(ids) ? ids : [] @@ -2370,9 +2323,10 @@ function emailSet(accountId, ids, patch) { return { accountId: trimmed(accountId), update: update } } -// One `notUpdated` entry as a sentence, in the style of -// `ImapProtocol.responseError`: the server's own words are written for whoever -// reads its logs, and these are the ones a user can act on. +/** One `notUpdated` entry as a sentence, in the style of + * `ImapProtocol.responseError`: the server's own words are written for whoever + * reads its logs, and these are the ones a user can act on. + */ function setError(entry) { var source = entry && typeof entry === "object" ? entry : {} var type = errorType(source.type) @@ -2380,27 +2334,26 @@ function setError(entry) { if (type === "forbidden") return "The server refused that change" if (type === "tooLarge" || type === "overQuota") return "The mailbox is over its storage quota" if (type === "rateLimit") return "The mail server is busy. Try again shortly" - // `invalidProperties`, `invalidPatch` and whatever a server invents: its own - // description if it wrote one, because a type name is not a sentence. var described = describedBy(source) if (described !== "") return redact(described) return "The mail server could not complete this request" } -// What an `Email/set` reply amounts to: "" when everything the request named -// was updated, else the sentence for the first entry that was not. -// -// `tolerateNotFound` is the whole difference between a batch and one message. -// "Mark these read" over a page somebody else has been deleting from is not a -// failed request — what is still there was marked, and the next list load drops -// the rest — so a `notFound` inside a batch is passed over. One message the -// user pointed at is a different thing: there is nothing to report but the -// failure, and reporting success would leave the row moved. -// -// Application is per object, so the objects that were not refused have already -// been changed. The account restores its whole list on the error and the next -// poll or push corrects the rows that did change, which is the contract it -// already keeps for every provider. +/** What an `Email/set` reply amounts to: "" when everything the request named + * was updated, else the sentence for the first entry that was not. + * + * `tolerateNotFound` is the whole difference between a batch and one message. + * "Mark these read" over a page somebody else has been deleting from is not a + * failed request — what is still there was marked, and the next list load drops + * the rest — so a `notFound` inside a batch is passed over. One message the + * user pointed at is a different thing: there is nothing to report but the + * failure, and reporting success would leave the row moved. + * + * Application is per object, so the objects that were not refused have already + * been changed. The account restores its whole list on the error and the next + * poll or push corrects the rows that did change, which is the contract it + * already keeps for every provider. + */ function notUpdatedError(parameters, tolerateNotFound) { var source = parameters && typeof parameters === "object" ? parameters.notUpdated : null if (!source || typeof source !== "object") return "" @@ -2412,9 +2365,7 @@ function notUpdatedError(parameters, tolerateNotFound) { return "" } -// -------------------------------------------------------- sending and drafts -// -// A message leaves this client the way it arrived: as the raw RFC 5322 bytes +// Invariant: A message leaves this client the way it arrived: as the raw RFC 5322 bytes // `Message.buildRawMessage` produced. They are uploaded as a blob and turned // into an Email with `Email/import`, and no Email is ever built from parts — // which is what keeps the direction twin, the calendar reply and every nested @@ -2442,56 +2393,61 @@ function notUpdatedError(parameters, tolerateNotFound) { // imported id itself before reporting the error. A leftover would show up as a // duplicate draft on the next refresh. -// How many uploads may be in flight at once when the session did not say. RFC +// Invariant: How many uploads may be in flight at once when the session did not say. RFC // 8620 makes `maxConcurrentUpload` mandatory and requires at least one, so one // is the floor under a server that omitted it rather than a guess about one // that stated it. The reference server says four. var DEFAULT_CONCURRENT_UPLOAD = 1 -// The two creation ids the send request uses. They are this client's own +// Invariant: The two creation ids the send request uses. They are this client's own // labels, referenced as `#m` by the submission's `emailId` and as `#s` by the // `onSuccessUpdateEmail` key — which is keyed on the *submission's* creation // id, not the email's. var CREATE_EMAIL = "m" var CREATE_SUBMISSION = "s" -// The session's upload endpoint, read from the session for the same reason the -// API URL is: it is a fourth place a credential may go, and on the reference -// account it is a different host from the session's own. +/** The session's upload endpoint, read from the session for the same reason the + * API URL is: it is a fourth place a credential may go, and on the reference + * account it is a different host from the session's own. + */ function uploadTemplate(session) { return sessionField(session, "uploadUrl") } -// The template filled, with the account id percent-encoded on the way in — the -// same rule `downloadUrl` follows, for the same reason. +/** The template filled, with the account id percent-encoded on the way in — the + * same rule `downloadUrl` follows, for the same reason. + */ function uploadUrl(template, accountId) { var filled = String(template === undefined || template === null ? "" : template) if (filled === "") return "" return fillTemplate(filled, "accountId", accountId) } -// What an upload answers with: a small JSON object naming the blob the import -// then names. Anything else is an answer this client cannot use. +/** What an upload answers with: a small JSON object naming the blob the import + * then names. Anything else is an answer this client cannot use. + */ function uploadedBlobId(body) { var document = parseJson(body) return document ? trimmed(document.blobId) : "" } -// The server's own ceiling on an upload, or 0 for a server that did not say. -// RFC 8620 makes the figure mandatory, so 0 means "no ceiling was published" -// rather than "nothing may be sent" — refusing every message because a server -// omitted a number would be this client's failure, not the server's. +/** The server's own ceiling on an upload, or 0 for a server that did not say. + * RFC 8620 makes the figure mandatory, so 0 means "no ceiling was published" + * rather than "nothing may be sent" — refusing every message because a server + * omitted a number would be this client's failure, not the server's. + */ function uploadCeiling(session) { return coreLimit(session, "maxSizeUpload") } -// The three refusals that happen before any request, so a message too large or -// an account with nowhere to put the copy costs no round trip and leaves -// nothing behind. "" means nothing is wrong. -// -// Both roles exist on both target servers, so the mailbox pair guards -// misconfiguration — an account whose Sent folder was deleted since the last -// read — rather than a server this client expects to meet. +/** The three refusals that happen before any request, so a message too large or + * an account with nowhere to put the copy costs no round trip and leaves + * nothing behind. "" means nothing is wrong. + * + * Both roles exist on both target servers, so the mailbox pair guards + * misconfiguration — an account whose Sent folder was deleted since the last + * read — rather than a server this client expects to meet. + */ function sizeGuard(session, byteLength) { var ceiling = uploadCeiling(session) if (ceiling <= 0) return "" @@ -2509,7 +2465,8 @@ function sendGuard(session, roles, byteLength) { return "" } -// A draft never reaches Sent, so the Sent role is not its business. +/** A draft never reaches Sent, so the Sent role is not its business. + */ function saveGuard(session, roles, byteLength) { var refusal = sizeGuard(session, byteLength) if (refusal !== "") return refusal @@ -2518,12 +2475,13 @@ function saveGuard(session, roles, byteLength) { return "" } -// One header off a message this client just built, read without parsing it. -// -// The header block ends at the first blank line and an attachment is -// everything after that, so a full MIME parse to read one address would walk -// tens of megabytes for a value that is in the first few hundred bytes. -// Folded continuations are joined, because a long From list is folded. +/** One header off a message this client just built, read without parsing it. + * + * The header block ends at the first blank line and an attachment is + * everything after that, so a full MIME parse to read one address would walk + * tens of megabytes for a value that is in the first few hundred bytes. + * Folded continuations are joined, because a long From list is folded. + */ function messageHeader(message, name) { var text = String(message === undefined || message === null ? "" : message) var wanted = trimmed(name).toLowerCase() @@ -2550,10 +2508,11 @@ function messageHeader(message, name) { return value } -// The address inside a From header, lower-cased for comparison. `Name ` -// and a bare `a@b` are both written by `Mail.addressHeader`, and the phrase it -// quotes may itself contain an `@`, so the angle brackets win where there are -// any. +/** The address inside a From header, lower-cased for comparison. `Name ` + * and a bare `a@b` are both written by `Mail.addressHeader`, and the phrase it + * quotes may itself contain an `@`, so the angle brackets win where there are + * any. + */ function headerAddress(header) { var text = trimmed(header) if (text === "") return "" @@ -2564,15 +2523,16 @@ function headerAddress(header) { return text.toLowerCase() } -// The server's identities as the send-as list every composer already reads — -// Gmail's alias shape, so nothing above the provider boundary learns the word -// "identity". The one this account is signed in as is both primary and -// default; on Fastmail the list is every alias and the same code serves it. -// -// The rows keep the identity's `id`, which is the field `identityFor` chooses -// on and the only value `EmailSubmission/set` will take. Nothing above the -// seam reads it — the composer wants an address and a name — but a send that -// had to look the id up again would need a second copy of this decision. +/** The server's identities as the send-as list every composer already reads — + * Gmail's alias shape, so nothing above the provider boundary learns the word + * "identity". The one this account is signed in as is both primary and + * default; on Fastmail the list is every alias and the same code serves it. + * + * The rows keep the identity's `id`, which is the field `identityFor` chooses + * on and the only value `EmailSubmission/set` will take. Nothing above the + * seam reads it — the composer wants an address and a name — but a send that + * had to look the id up again would need a second copy of this decision. + */ function identityAliases(identities, address) { var list = Array.isArray(identities) ? identities : [] var own = trimmed(address).toLowerCase() @@ -2594,16 +2554,17 @@ function identityAliases(identities, address) { return output } -// Which identity a message goes out under: the one whose address the From -// header names, else the default, else the first there is. -// -// **A send never refuses for want of a match.** The RSVP and the unsubscribe -// both send from the address the mail arrived at, which may be an alias this -// server has no identity for; the server forces the envelope sender to the -// identity and delivers the header as written, which is what those two paths -// need. An empty list answers "" and the server refuses the submission with a -// sentence of its own, which is the honest answer for an account with no -// identity at all. +/** Which identity a message goes out under: the one whose address the From + * header names, else the default, else the first there is. + * + * **A send never refuses for want of a match.** The RSVP and the unsubscribe + * both send from the address the mail arrived at, which may be an alias this + * server has no identity for; the server forces the envelope sender to the + * identity and delivers the header as written, which is what those two paths + * need. An empty list answers "" and the server refuses the submission with a + * sentence of its own, which is the honest answer for an account with no + * identity at all. + */ function identityFor(identities, fromHeader) { var list = Array.isArray(identities) ? identities : [] var wanted = headerAddress(fromHeader) @@ -2620,8 +2581,9 @@ function identityFor(identities, fromHeader) { return fallback !== "" ? fallback : first } -// The import every outgoing message begins as: the blob, the Drafts mailbox, -// and the two keywords. A draft stops here; a send has the submission move it. +/** The import every outgoing message begins as: the blob, the Drafts mailbox, + * and the two keywords. A draft stops here; a send has the submission move it. + */ function importCall(accountId, blobId, draftsId, callId) { var mailboxes = {} var drafts = trimmed(draftsId) @@ -2638,14 +2600,15 @@ function importCall(accountId, blobId, draftsId, callId) { return ["Email/import", { accountId: trimmed(accountId), emails: emails }, callId] } -// The whole send, in the order the server applies it. +/** The whole send, in the order the server applies it. + */ function sendRequest(accountId, blobId, identityId, roles) { var map = roles && typeof roles === "object" ? roles : {} var account = trimmed(accountId) var drafts = trimmed(map.drafts) var sent = trimmed(map.sent) - // Where the copy ends up once the submission has been accepted: in Sent, + // Invariant: Where the copy ends up once the submission has been accepted: in Sent, // out of Drafts and no longer a draft. Written as a patch rather than a // whole `mailboxIds`, because the import put it in exactly one mailbox and // this is the pair of memberships that changes. @@ -2673,12 +2636,13 @@ function sendRequest(accountId, blobId, identityId, roles) { return calls } -// A draft save imports only. The client destroys the old copy in a separate -// call after confirming creation: method batches continue after failures. -// -// An Email is immutable apart from its keywords and its mailboxes — a subject -// patch is refused `invalidProperties` — so a saved draft is always a new id, -// as it is on IMAP. There is no `updateDraft`. +/** A draft save imports only. The client destroys the old copy in a separate + * call after confirming creation: method batches continue after failures. + * + * An Email is immutable apart from its keywords and its mailboxes — a subject + * patch is refused `invalidProperties` — so a saved draft is always a new id, + * as it is on IMAP. There is no `updateDraft`. + */ function saveRequest(accountId, blobId, roles) { var map = roles && typeof roles === "object" ? roles : {} var account = trimmed(accountId) @@ -2686,15 +2650,17 @@ function saveRequest(accountId, blobId, roles) { return calls } -// The follow-up a refused submission needs: the import stands, and nothing -// else will remove it. +/** The follow-up a refused submission needs: the import stands, and nothing + * else will remove it. + */ function destroyRequest(accountId, ids) { return [["Email/set", { accountId: trimmed(accountId), destroy: uniqueIds(ids) }, "0"]] } -// What a `create` map answered for one creation id: the new object's id, or -// the entry saying why there is none. Null rather than an empty object for the -// second, so "was it refused" is a question with an answer. +/** What a `create` map answered for one creation id: the new object's id, or + * the entry saying why there is none. Null rather than an empty object for the + * second, so "was it refused" is a question with an answer. + */ function createdId(parameters, creationId) { var source = parameters && typeof parameters === "object" ? parameters.created : null var entry = source && typeof source === "object" ? source[trimmed(creationId)] : null @@ -2707,7 +2673,7 @@ function notCreatedEntry(parameters, creationId) { return entry && typeof entry === "object" ? entry : null } -// One refused `create` as a sentence, in `setError`'s style: the server's own +// Invariant: One refused `create` as a sentence, in `setError`'s style: the server's own // words are written for whoever reads its logs, and these are the ones a user // can act on. // @@ -2722,8 +2688,6 @@ function submissionError(entry, fallback) { var source = entry && typeof entry === "object" ? entry : {} var type = errorType(source.type) if (type === "forbiddenFrom") return "This account may not send as that address" - // Also the server's answer to a malformed recipient address when the request - // carries no envelope, which is every request this client sends. if (type === "noRecipients") return "Add a recipient first" if (type === "tooLarge") return "The message is too large for this server" if (type === "tooManyRecipients") return "Too many recipients for this server" @@ -2736,7 +2700,7 @@ function submissionError(entry, fallback) { return last !== "" ? last : SEND_FAILED } -// What a save's reply amounts to, in `ImapProtocol.draftSaveResult`'s shape. +// Invariant: What a save's reply amounts to, in `ImapProtocol.draftSaveResult`'s shape. // // The draft was saved either way — the import is the first call and it // succeeded — so an old copy that would not go is a warning rather than a @@ -2759,9 +2723,7 @@ function draftSaveResult(parameters) { return { saved: true, warning: "" } } -// --------------------------------------------------- per-account refusals -// -// The provider's capability list is a ceiling and an account may withdraw from +// Invariant: The provider's capability list is a ceiling and an account may withdraw from // it, never add to it. `refusals` is that withdrawal: a plain object whose // *presence* of a key is the refusal and whose value is the sentence a user // reads. An absent key means "as the ceiling says". @@ -2771,7 +2733,7 @@ var REFUSAL_NO_JUNK = missingMailboxError("junk") var REFUSAL_NO_LEARNING = "This server is not known to learn from its Junk mailbox" var REFUSAL_NO_SEND = "This account cannot send mail" -// Where a move into Junk is known to train the server, and nowhere else. +// Invariant: Where a move into Junk is known to train the server, and nowhere else. // // RFC 8621 registers `$junk` and promises no training whatsoever, so a generic // JMAP server gets IMAP's answer: no button, because a button that quietly @@ -2800,9 +2762,10 @@ var LEARNS_FROM_JUNK = [ { server: "Fastmail", capability: "", apiHostSuffix: FASTMAIL_API_HOST_SUFFIX } ] -// The API URL's host without its port: `api.fastmail.com:443` is the same -// server as `api.fastmail.com`, and a bracketed IPv6 literal ends in "]" so it -// keeps every colon it has. +/** The API URL's host without its port: `api.fastmail.com:443` is the same + * server as `api.fastmail.com`, and a bracketed IPv6 literal ends in "]" so it + * keeps every colon it has. + */ function apiHost(session) { return sessionHost(apiUrl(session)).replace(/:\d+$/, "") } @@ -2828,14 +2791,15 @@ function learnsFromJunk(session, accountId) { return false } -// What this account withdraws from the provider's ceiling, or null. -// -// Null until both a session and a mailbox list are in hand, and that is the -// whole of the timing rule: with null the registry answers the ceiling, which -// is the right thing for a button while the list is still on its way. Between -// reads a button reflects the last known list, and a press against a mailbox -// deleted elsewhere lands on the client's own refusal at request time — two -// layers saying the same sentence, which is why the wording is shared. +/** What this account withdraws from the provider's ceiling, or null. + * + * Null until both a session and a mailbox list are in hand, and that is the + * whole of the timing rule: with null the registry answers the ceiling, which + * is the right thing for a button while the list is still on its way. Between + * reads a button reflects the last known list, and a press against a mailbox + * deleted elsewhere lands on the client's own refusal at request time — two + * layers saying the same sentence, which is why the wording is shared. + */ function refusals(session, accountId, mailboxes) { var list = mailboxArray(mailboxes) var document = parseJson(session) diff --git a/ui/providers/JmapPush.qml b/ui/providers/JmapPush.qml index 1621d833e..884affb2b 100644 --- a/ui/providers/JmapPush.qml +++ b/ui/providers/JmapPush.qml @@ -1,7 +1,7 @@ import QtQuick import "JmapProtocol.js" as Jmap -// The backend owns the socket, bounded event decoder, watchdog and reconnect +// Invariant: The backend owns the socket, bounded event decoder, watchdog and reconnect // backoff. This view only translates delivered changes into UI invalidations. Item { id: root diff --git a/ui/providers/JmapThreads.js b/ui/providers/JmapThreads.js index fd972f884..4a3c71c5a 100644 --- a/ui/providers/JmapThreads.js +++ b/ui/providers/JmapThreads.js @@ -2,7 +2,7 @@ .import "JmapProtocol.js" as Protocol -// One row per conversation. +// Invariant: One row per conversation. // // `JmapProtocol.js` is the protocol — every string sent to a server and every // decision about what came back. This is one job done with it, and it is a file @@ -35,25 +35,20 @@ var CALL_REPRESENTATIVES = "1" var CALL_THREADS = "2" var CALL_MEMBERS = "3" -// The representative read asks for `threadId` and nothing else. The row's own -// summary is fetched by `getMessages` with the full list property set a moment -// later, so asking for it twice would double the page's cost to save nothing. var REPRESENTATIVE_PROPERTIES = ["id", "threadId"] -// What a member is counted and read by: which mailboxes it sits in, for the -// Gmail rule below, and its keywords, for the row's unread and flagged. Not its -// subject, its sender or its preview — a member is a number on a row here, and -// the conversation rail asks for what it draws, when it draws it. var MEMBER_PROPERTIES = ["id", "threadId", "mailboxIds", "keywords"] -// A JMAP back-reference: "the value at this path in the result of that call". -// RFC 8620 section 3.7. `/list/*/threadId` is every `threadId` in a `/get`'s -// list, flattened, which is exactly the argument the next call wants. +/** A JMAP back-reference: "the value at this path in the result of that call". + * RFC 8620 section 3.7. `/list/*/threadId` is every `threadId` in a `/get`'s + * list, flattened, which is exactly the argument the next call wants. + */ function backReference(callId, name, path) { return { resultOf: String(callId), name: String(name), path: String(path) } } -// The four calls one collapsed page is read with. +/** The four calls one collapsed page is read with. + */ function listCalls(accountId, filter, limit, token, byPosition) { var account = Protocol.trimmed(accountId) return [ @@ -75,8 +70,9 @@ function listCalls(accountId, filter, limit, token, byPosition) { ] } -// The member read again, by id, for the follow-up after the server refused to -// answer the whole of it in one call. +/** The member read again, by id, for the follow-up after the server refused to + * answer the whole of it in one call. + */ function memberGet(accountId, ids) { return { accountId: Protocol.trimmed(accountId), @@ -85,14 +81,15 @@ function memberGet(accountId, ids) { } } -// The invocation the request labelled `callId`, as `{ name, arguments }`, or -// null when the reply carries none. -// -// Read by the label rather than by the method name, because two calls in this -// request are both `Email/get` and `responseArguments` would answer with the -// first of them for either question. A call the server refused answers under -// the same label with the name `error`, which is how the too-large member read -// is told from one that came back empty. +/** The invocation the request labelled `callId`, as `{ name, arguments }`, or + * null when the reply carries none. + * + * Read by the label rather than by the method name, because two calls in this + * request are both `Email/get` and `responseArguments` would answer with the + * first of them for either question. A call the server refused answers under + * the same label with the name `error`, which is how the too-large member read + * is told from one that came back empty. + */ function invocationAt(responses, callId) { var list = Protocol.invocations(responses) var wanted = Protocol.trimmed(callId) @@ -102,24 +99,27 @@ function invocationAt(responses, callId) { return null } -// The arguments of that invocation when it answered, and null when it was -// refused or is absent — so a caller never reads an `error`'s arguments as if -// they were a result. +/** The arguments of that invocation when it answered, and null when it was + * refused or is absent — so a caller never reads an `error`'s arguments as if + * they were a result. + */ function argumentsAt(responses, callId) { var found = invocationAt(responses, callId) if (!found || found.name === "" || found.name === "error") return null return found.arguments } -// The `list` of a `/get` reply, as an array. +/** The `list` of a `/get` reply, as an array. + */ function getList(parameters) { var body = parameters && typeof parameters === "object" ? parameters : {} return Array.isArray(body.list) ? body.list : [] } -// Every representative on the page and the thread it stands for, in page order: -// -// [{ id: "maaaaaf", threadId: "d" }, ...] +/** Every representative on the page and the thread it stands for, in page order: + * + * [{ id: "maaaaaf", threadId: "d" }, ...] + */ function representativeThreads(responses) { var list = getList(argumentsAt(responses, CALL_REPRESENTATIVES)) var output = [] @@ -133,10 +133,11 @@ function representativeThreads(responses) { return output } -// Thread id to its member ids, oldest first — which is the order `Thread/get` -// answers in (RFC 8621 section 3, `receivedAt` ascending). The conversation -// rail draws them the other way up; that is `Conversation.railOrder`'s -// decision, not this list's. +/** Thread id to its member ids, oldest first — which is the order `Thread/get` + * answers in (RFC 8621 section 3, `receivedAt` ascending). The conversation + * rail draws them the other way up; that is `Conversation.railOrder`'s + * decision, not this list's. + */ function threadMembers(responses) { var list = getList(argumentsAt(responses, CALL_THREADS)) var output = {} @@ -155,9 +156,10 @@ function threadMembers(responses) { return output } -// Every member id the threads on this page name, once each, in page order. -// This is what the fourth call asks for through its back-reference, and what -// the follow-up asks for by id when the server refuses to answer it in one go. +/** Every member id the threads on this page name, once each, in page order. + * This is what the fourth call asks for through its back-reference, and what + * the follow-up asks for by id when the server refuses to answer it in one go. + */ function memberIdsOf(representatives, threads) { var representativeRows = Array.isArray(representatives) ? representatives : [] var map = threads && typeof threads === "object" ? threads : {} @@ -175,7 +177,8 @@ function memberIdsOf(representatives, threads) { return output } -// Member id to the member itself. +/** Member id to the member itself. + */ function memberIndex(list) { var rows = Array.isArray(list) ? list : [] var output = {} @@ -186,28 +189,30 @@ function memberIndex(list) { return output } -// The one mailbox a query is a view of, or "" for a search — which is a view of -// the account rather than of a mailbox. `filterFor` already decides this for -// the request; asking it again is what keeps the counted-members rule and the -// filter from ever disagreeing about which mailbox is open. +/** The one mailbox a query is a view of, or "" for a search — which is a view of + * the account rather than of a mailbox. `filterFor` already decides this for + * the request; asking it again is what keeps the counted-members rule and the + * filter from ever disagreeing about which mailbox is open. + */ function viewedMailbox(parsed, roles) { var filter = Protocol.filterFor(parsed, roles) if (!filter || typeof filter.inMailbox !== "string") return "" return Protocol.trimmed(filter.inMailbox) } -// Gmail's rule: every member of the thread not in Junk or Trash, and in the -// Junk and Trash views only the members in that mailbox. -// -// `Thread/get` answers with the whole thread across every mailbox — the seeded -// thread's first message sits in the Inbox and in Drafts and is listed once — -// so a rule is needed and this is it. A sent reply counts, which is what makes -// the Sent view one row for a thread answered three times. A trashed message -// neither counts nor keeps a conversation unread. -// -// The view is taken from the query rather than from a role, so selecting the -// Junk mailbox out of the folder list means the same thing as the rail's own -// Junk row: both resolve to the same mailbox id. +/** Gmail's rule: every member of the thread not in Junk or Trash, and in the + * Junk and Trash views only the members in that mailbox. + * + * `Thread/get` answers with the whole thread across every mailbox — the seeded + * thread's first message sits in the Inbox and in Drafts and is listed once — + * so a rule is needed and this is it. A sent reply counts, which is what makes + * the Sent view one row for a thread answered three times. A trashed message + * neither counts nor keeps a conversation unread. + * + * The view is taken from the query rather than from a role, so selecting the + * Junk mailbox out of the folder list means the same thing as the rail's own + * Junk row: both resolve to the same mailbox id. + */ function countedMembers(members, roles, query) { var list = Array.isArray(members) ? members : [] var map = roles || {} @@ -232,16 +237,17 @@ function countedMembers(members, roles, query) { return output } -// The `thread` block a row carries: -// -// { id, count, unread, flagged, memberIds } -// -// `memberIds` are the counted members oldest first and `count` is their length. -// A count of 0 means unknown and draws no badge, which is what every provider -// that does not collapse its listing reports. `unread` is true when any counted -// member lacks `$seen`, `flagged` when any has `$flagged` — so the row tells the -// truth about the whole conversation rather than about the one message the -// server happened to return for it. +/** The `thread` block a row carries: + * + * { id, count, unread, flagged, memberIds } + * + * `memberIds` are the counted members oldest first and `count` is their length. + * A count of 0 means unknown and draws no badge, which is what every provider + * that does not collapse its listing reports. `unread` is true when any counted + * member lacks `$seen`, `flagged` when any has `$flagged` — so the row tells the + * truth about the whole conversation rather than about the one message the + * server happened to return for it. + */ function threadBlockFor(threadId, members, roles, query) { var counted = countedMembers(members, roles, query) var ids = [] @@ -261,13 +267,14 @@ function threadBlockFor(threadId, members, roles, query) { } } -// Representative id to its block, for every row on the page. -// -// A member id the read did not answer for is dropped rather than counted as -// unknown: `Thread/get` and the member read are the same request, so the only -// way one goes missing is a message destroyed between the two calls, and a row -// counting a message that no longer exists is worse than a row counting one -// fewer. +/** Representative id to its block, for every row on the page. + * + * A member id the read did not answer for is dropped rather than counted as + * unknown: `Thread/get` and the member read are the same request, so the only + * way one goes missing is a message destroyed between the two calls, and a row + * counting a message that no longer exists is worse than a row counting one + * fewer. + */ function threadBlocks(representatives, threads, members, roles, query) { var representativeRows = Array.isArray(representatives) ? representatives : [] var map = threads && typeof threads === "object" ? threads : {} @@ -284,7 +291,8 @@ function threadBlocks(representatives, threads, members, roles, query) { return output } -// The mailboxes one member sits in, as a plain list of ids. +/** The mailboxes one member sits in, as a plain list of ids. + */ function mailboxIdsOf(email) { var ids = (email || {}).mailboxIds var output = [] @@ -297,10 +305,11 @@ function mailboxIdsOf(email) { return output } -// Message id to the mailboxes it sits in, for every member the read answered -// with. The client keeps this across reads: an action on a conversation acts on -// members the list never drew a row for, and where each of them sits is what -// decides whether archiving the conversation should move it at all. +/** Message id to the mailboxes it sits in, for every member the read answered + * with. The client keeps this across reads: an action on a conversation acts on + * members the list never drew a row for, and where each of them sits is what + * decides whether archiving the conversation should move it at all. + */ function membershipsFrom(list) { var rows = Array.isArray(list) ? list : [] var output = {} @@ -312,13 +321,14 @@ function membershipsFrom(list) { return output } -// What the client keeps of the pages it has read, in entries. Both maps below +// Performance: What the client keeps of the pages it has read, in entries. Both maps below // are caches of the recent pages rather than a record of the account, so the // bound is a reset rather than an eviction queue: an entry old enough to be // dropped belongs to a row that left the window long ago. var MAX_REMEMBERED = 2000 -// One of those maps, merged with what a page just read. +/** One of those maps, merged with what a page just read. + */ function mergedInto(existing, additions, limit) { var source = existing && typeof existing === "object" ? existing : {} var extra = additions && typeof additions === "object" ? additions : {} @@ -337,26 +347,25 @@ function mergedInto(existing, additions, limit) { return output } -// ------------------------------------------------------ acting on a row - -// The `Email/set` groups one action over one or many ids amounts to. -// -// A batch is not always one patch. An action on a conversation is sent for -// every counted member, and `patchFor` answers per member — so archiving a -// thread whose reply is in Sent yields the archive patch for the members that -// were in the Inbox and nothing at all for the reply. Grouping by the patch, -// rather than sending one request per id, keeps "mark these read" over a page -// at one request per chunk and leaves the single-message case exactly one call. -// -// Returns an array of `{ ids, patch }` in first-appearance order, or the -// refusal sentence `patchFor` answered with — the same two types the caller -// already tells apart. Ids are deduped, a member the map excludes is dropped -// rather than sent an empty patch, and an action every member is excluded from -// is an empty plan and no request at all. +/** The `Email/set` groups one action over one or many ids amounts to. + * + * A batch is not always one patch. An action on a conversation is sent for + * every counted member, and `patchFor` answers per member — so archiving a + * thread whose reply is in Sent yields the archive patch for the members that + * were in the Inbox and nothing at all for the reply. Grouping by the patch, + * rather than sending one request per id, keeps "mark these read" over a page + * at one request per chunk and leaves the single-message case exactly one call. + * + * Returns an array of `{ ids, patch }` in first-appearance order, or the + * refusal sentence `patchFor` answered with — the same two types the caller + * already tells apart. Ids are deduped, a member the map excludes is dropped + * rather than sent an empty patch, and an action every member is excluded from + * is an empty plan and no request at all. + */ function patchPlan(ids, addLabelIds, removeLabelIds, roles, memberships) { var map = memberships && typeof memberships === "object" ? memberships : {} var list = Protocol.uniqueIds(ids) - // The membership map keeps archive and spam off the members a *row* action + // Invariant: The membership map keeps archive and spam off the members a *row* action // reached without being asked about — a sent reply, a message a filter // filed — and that is the only thing it is for. One id is the message the // user acted on, whether it came from a row of one or from the reader, and @@ -370,8 +379,6 @@ function patchPlan(ids, addLabelIds, removeLabelIds, roles, memberships) { var id = list[itemIndex] var known = expanded && Array.isArray(map[id]) ? map[id] : null var patch = Protocol.patchFor(addLabelIds, removeLabelIds, roles, known) - // One refusal is the whole action's: the destination mailbox is missing - // from the account rather than from this member. if (typeof patch === "string") return patch if (Protocol.patchIsEmpty(patch)) continue var key = JSON.stringify(patch) @@ -385,24 +392,25 @@ function patchPlan(ids, addLabelIds, removeLabelIds, roles, memberships) { return groups } -// One collapsed page reply, read whole: -// -// { page, blocks, memberships, pending } -// -// `page` is what `listMessages` answers with. `blocks` is representative id to -// the row's `thread` block, `memberships` is member id to its mailbox ids, and -// `pending` is the member ids still owed — non-empty only when the server -// refused the member call while answering the other three, which is what -// `requestTooLarge` on a page of long threads looks like. The client then -// fetches those ids in chunks and reads the same reply again with `members` -// supplied, so the page is delivered only once every row has its block. +/** One collapsed page reply, read whole: + * + * { page, blocks, memberships, pending } + * + * `page` is what `listMessages` answers with. `blocks` is representative id to + * the row's `thread` block, `memberships` is member id to its mailbox ids, and + * `pending` is the member ids still owed — non-empty only when the server + * refused the member call while answering the other three, which is what + * `requestTooLarge` on a page of long threads looks like. The client then + * fetches those ids in chunks and reads the same reply again with `members` + * supplied, so the page is delivered only once every row has its block. + */ function collapsedPage(responses, limit, roles, query, members) { var page = Protocol.queryPage(argumentsAt(responses, CALL_QUERY), limit) var representativeRows = representativeThreads(responses) var threads = threadMembers(responses) var supplied = Array.isArray(members) ? members : null var answered = argumentsAt(responses, CALL_MEMBERS) - // Refused, not empty: `argumentsAt` answers null for a call that came back an + // Invariant: Refused, not empty: `argumentsAt` answers null for a call that came back an // `error` and for one the reply never carried, and either is a member read // this page has not had. var owed = supplied === null && answered === null ? memberIdsOf(representativeRows, threads) : [] diff --git a/ui/providers/MicrosoftOAuth.js b/ui/providers/MicrosoftOAuth.js index 44f4619d5..391e8b71e 100644 --- a/ui/providers/MicrosoftOAuth.js +++ b/ui/providers/MicrosoftOAuth.js @@ -2,7 +2,7 @@ .import "OAuth.js" as OAuth -// Microsoft OAuth for installed applications. Outlook uses the device-code +// Invariant: Microsoft OAuth for installed applications. Outlook uses the device-code // flow: the client is public, carries no secret, and does not need a redirect // URI or a listener left on the desktop. @@ -11,7 +11,7 @@ var AUTHORITY = "https://login.microsoftonline.com/" + TENANT + "/oauth2/v2.0" var DEVICE_URL = AUTHORITY + "/devicecode" var TOKEN_URL = AUTHORITY + "/token" -// `openid` brings an id token with each mail token, naming the account by +// Invariant: `openid` brings an id token with each mail token, naming the account by // its object id: what the Graph sign-in's code is held to. var SCOPES = [ "openid", @@ -20,7 +20,7 @@ var SCOPES = [ "https://outlook.office.com/SMTP.Send" ] -// Sending through Microsoft Graph, for a work or school tenant that has +// Invariant: Sending through Microsoft Graph, for a work or school tenant that has // switched authenticated SMTP off. A token is for one resource, so this is a // second token — asked for with the same refresh token, which Microsoft lets // a public client exchange for any resource the registration was consented @@ -30,7 +30,7 @@ var GRAPH_SCOPES = [ "https://graph.microsoft.com/Calendars.ReadWrite" ] -// The tenant the sign-in is addressed to. Personal accounts live under +// Invariant: The tenant the sign-in is addressed to. Personal accounts live under // `consumers`; a Microsoft 365 mailbox lives under its own tenant, which // `organizations` finds from the address, or a tenant id or domain names // outright. Anything that is not one of those spellings is the consumer @@ -66,8 +66,6 @@ function authorityFor(tenant) { return "https://login.microsoftonline.com/" + normalizeTenant(tenant) + "/oauth2/v2.0" } -// The consumer tenant answers with the constants above, which is what lets a -// test point them at a server of its own. function deviceUrlFor(tenant) { if (normalizeTenant(tenant) === "consumers") return DEVICE_URL return authorityFor(tenant) + "/devicecode" @@ -78,7 +76,7 @@ function tokenUrlFor(tenant) { return authorityFor(tenant) + "/token" } -// A maintainer-owned public-client registration can make Outlook a one-click +// Invariant: A maintainer-owned public-client registration can make Outlook a one-click // setup later. Until then, each user supplies the Application (client) ID of // their own registration, just as Gmail users supply their own OAuth client. var BUILTIN_CLIENT_ID = "" @@ -101,7 +99,7 @@ function verificationUri(value) { var text = trimmed(value) var match = text.match(/^https:\/\/([^\/:?#]+)(?::443)?(?:[\/?#]|$)/i) if (!match) return "" - // The pages Microsoft sends people to: microsoft.com/devicelogin and + // Invariant: The pages Microsoft sends people to: microsoft.com/devicelogin and // www.microsoft.com/link for personal accounts, login.microsoft.com/device // for a work or school tenant, and the sign-in host itself. var host = match[1].toLowerCase() @@ -140,10 +138,11 @@ function graphRefreshBody(clientId, refreshToken) { return refreshTokenBody(clientId, refreshToken, GRAPH_SCOPES) } -// Whether a token answer lists a scope: by its full name or, as Microsoft -// lists Graph's, by the short one. An answer that lists none says nothing -// and is taken as granted — a permission truly missing is refused where it -// is used, not mistaken for consent to collect. +/** Whether a token answer lists a scope: by its full name or, as Microsoft + * lists Graph's, by the short one. An answer that lists none says nothing + * and is taken as granted — a permission truly missing is refused where it + * is used, not mistaken for consent to collect. + */ function scopeListed(granted, scope) { var text = String(granted || "").trim().toLowerCase() if (text === "") return true @@ -153,9 +152,6 @@ function scopeListed(granted, scope) { return have.indexOf(full) >= 0 || have.indexOf(short) >= 0 } -// Whether a Graph token answered with the scope sending needs, and whether -// with the one the calendar needs. A registration consented for one and -// not the other is told which. function missingGraphScope(granted) { return !scopeListed(granted, GRAPH_SCOPES[0]) } @@ -249,9 +245,9 @@ function parseTokenResponse(status, text, previousRefreshToken) { } } -// The account an id token names, lower-cased, or "" when it names none. The -// token is Microsoft's own answer over TLS, read for the name alone and not -// verified: it authorises nothing, it says who entered the code. +/** Decodes the claims payload returned by the trusted Microsoft token endpoint. + * Identity checks consume these claims; this function does not verify a JWT signature. + */ function base64UrlDecode(text) { var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" var input = String(text || "").replace(/=+$/, "") @@ -289,8 +285,9 @@ function signedInAs(idToken) { return "" } -// The account an id token names by tenant and object id — what does not -// change when a name does — or "" when it carries neither. +/** The account an id token names by tenant and object id — what does not + * change when a name does — or "" when it carries neither. + */ function accountKey(idToken) { var claims = idTokenClaims(idToken) if (!claims) return "" @@ -299,9 +296,10 @@ function accountKey(idToken) { return tenant !== "" && object !== "" ? tenant + "/" + object : "" } -// Whether the id token names the mailbox's own account: the one the mail -// session is, by id, where that is known; else by name against the -// address. A grant without either identity cannot be assigned to this mailbox. +/** Whether the id token names the mailbox's own account: the one the mail + * session is, by id, where that is known; else by name against the + * address. A grant without either identity cannot be assigned to this mailbox. + */ function sameAccount(idToken, email, mailKey) { var key = trimmed(mailKey) if (key !== "") return accountKey(idToken) === key @@ -324,20 +322,22 @@ function graphScopeNames() { return names.join(" and ") } -// What a Graph sign-in that did not go through leaves on the setup page: -// the mailbox is signed in, and how to ask again — or whom to ask, where -// Microsoft wanted an administrator's approval, which the refusal that -// started it cannot tell from consent nobody has given yet. +/** What a Graph sign-in that did not go through leaves on the setup page: + * the mailbox is signed in, and how to ask again — or whom to ask, where + * Microsoft wanted an administrator's approval, which the refusal that + * started it cannot tell from consent nobody has given yet. + */ function graphRefusedMessage(reason) { return "Microsoft Graph was not allowed: " + String(reason || "") + ". The mailbox is signed in; " + "Allow Microsoft Graph... in its settings asks again. If Microsoft asked for admin approval, " + "an administrator must grant the app registration " + graphScopeNames() + " first" } -// Microsoft's answer to an exchange for a resource the user has not -// consented this client to: a bad grant that a sign-in can mend, told apart -// from one that cannot — a revoked or expired session — by its sub-error or -// its code (AADSTS65001). +/** Microsoft's answer to an exchange for a resource the user has not + * consented this client to: a bad grant that a sign-in can mend, told apart + * from one that cannot — a revoked or expired session — by its sub-error or + * its code (AADSTS65001). + */ function consentRequired(payload) { if (!payload || typeof payload !== "object") return false var code = String(payload.error || "") @@ -357,7 +357,7 @@ function missingMailScopes(granted) { var missing = [] for (var itemIndex = 0; itemIndex < SCOPES.length; itemIndex++) { var scope = SCOPES[itemIndex] - // Not resource scopes: a token answer does not list them. + // Invariant: Not resource scopes: a token answer does not list them. if (scope === "offline_access" || scope === "openid") continue if (!scopeListed(granted, scope)) missing.push(scope) } @@ -375,9 +375,6 @@ function missingScopeMessage(missing) { + " permission. Check the app registration and sign in again" } -// A connection check reports capabilities, never provider diagnostics. Keep -// its wording here with the rest of Microsoft's presentation rules so the -// setup page only owns the asynchronous button state. function connectionStatus(report, graphSend, workAccount) { var value = report || {} return [ diff --git a/ui/providers/OAuth.js b/ui/providers/OAuth.js index 8a2c730a4..53ede82d4 100644 --- a/ui/providers/OAuth.js +++ b/ui/providers/OAuth.js @@ -1,6 +1,6 @@ .pragma library -// Google's OAuth 2.0 flow for installed apps: authorization code with PKCE, +// Invariant: Google's OAuth 2.0 flow for installed apps: authorization code with PKCE, // answered on a loopback listener. Everything here is pure string work so the // same code the shell runs is what the node tests exercise. // @@ -18,7 +18,7 @@ var REVOKE_URL = "https://oauth2.googleapis.com/revoke" var DEFAULT_PORT = 9481 var CALLBACK_PATH = "/oauth2callback" -// gmail.modify is read plus label/trash changes — it deliberately cannot +// Invariant: gmail.modify is read plus label/trash changes — it deliberately cannot // permanently delete. gmail.send is what reply and compose need. // calendar.events reads calendars and creates events without broader account // access. @@ -85,10 +85,10 @@ function authorizationUrl(options) { code_challenge_method: "S256", state: settings.state, access_type: "offline", - // Google joins these permissions to an existing grant. This matters when + // Invariant: Google joins these permissions to an existing grant. This matters when // an upgrade adds Calendar to a mailbox that already granted Gmail. include_granted_scopes: "true", - // Without this Google returns a refresh token only on the very first + // Invariant: Without this Google returns a refresh token only on the very first // consent, so a user who reinstalls the plugin would be stuck with an // access token that expires in an hour and never comes back. prompt: "consent", @@ -96,9 +96,9 @@ function authorizationUrl(options) { }) } -// The listener is a raw socat pipe, so the first request line is all there is -// to work with. Anything that is not the expected callback path is refused -// rather than guessed at. +/** Parses a reference OAuth callback request line and refuses unexpected paths. + * The native backend owns the live loopback listener. + */ function parseCallbackRequestLine(line, expectedPath) { var match = String(line || "").match(/^GET\s+([^\s]+)\s+HTTP\/\d(?:\.\d)?$/) if (!match) return { ok: false, error: "Invalid sign-in callback request" } @@ -145,8 +145,9 @@ function parseJson(text, fallback) { } } -// Anything that could carry a credential is scrubbed before it can reach a -// label. Errors from Google echo request parameters more often than not. +/** Anything that could carry a credential is scrubbed before it can reach a + * label. Errors from Google echo request parameters more often than not. + */ function redact(text) { return String(text === undefined || text === null ? "" : text) .replace(/(refresh_token|access_token|code_verifier|client_secret|id_token)=[^&\s"']+/gi, "$1=[redacted]") @@ -192,24 +193,27 @@ function parseTokenResponse(status, text, previousRefreshToken) { } } -// A saved grant stops being a session only when Google says the grant itself -// is invalid. Timeouts, transport failures and server errors leave it intact -// and must be retried when the network is usable again. +/** A saved grant stops being a session only when Google says the grant itself + * is invalid. Timeouts, transport failures and server errors leave it intact + * and must be retried when the network is usable again. + */ function refreshFailureDisposition(result) { return result && result.invalidGrant ? "signed_out" : "retry" } -// Start quickly for a network transition, then back off to one request every -// five minutes during a longer outage. A successful refresh resets the caller's -// attempt counter. +/** Start quickly for a network transition, then back off to one request every + * five minutes during a longer outage. A successful refresh resets the caller's + * attempt counter. + */ function refreshRetryDelay(attempt) { var count = Math.max(0, Math.floor(Number(attempt)) || 0) return Math.min(300000, 5000 * Math.pow(2, count)) } -// A grant is only useful if it came back with everything the panel needs. A -// user who unticks a checkbox on Google's consent screen gets a working token -// with a scope set that silently breaks half the actions. +/** A grant is only useful if it came back with everything the panel needs. A + * user who unticks a checkbox on Google's consent screen gets a working token + * with a scope set that silently breaks half the actions. + */ function requiredScopes(scopes) { var requested = Array.isArray(scopes) ? scopes : SCOPES return requested.filter(function(scope) { return OPTIONAL_SCOPES.indexOf(scope) < 0 }) @@ -239,11 +243,12 @@ function missingScopeMessage(missing) { + " permission. Sign in again and leave every checkbox ticked" } -// Content-Length is a BYTE count. The old page said "Returning to Omarchy -// Gmail\u2026", whose ellipsis is one JS character and three UTF-8 bytes, so -// the browser was told to expect a shorter response than it got and rendered -// a truncated page. Measuring properly means the copy is free to use any -// character it likes. +/** Content-Length is a BYTE count. The old page said "Returning to Omarchy + * Gmail\u2026", whose ellipsis is one JS character and three UTF-8 bytes, so + * the browser was told to expect a shorter response than it got and rendered + * a truncated page. Measuring properly means the copy is free to use any + * character it likes. + */ function byteLength(text) { var value = String(text || "") var bytes = 0 @@ -269,17 +274,18 @@ function defaultTheme() { } } -// The page the browser lands on after Google redirects. It is the only part of +// Invariant: The page the browser lands on after Google redirects. It is the only part of // this app that renders outside Quickshell, so it takes the active Omarchy // theme with it rather than inventing a look of its own: same monospace, same // square corners, same hairline border at 40% foreground. -// Everything the callback carries is attacker-controlled. The loopback listener -// answers whatever connects to it — it cannot tell Google's redirect from any -// other request to that port — so a crafted GET can put arbitrary text in -// error_description, and parseQuery hands it back percent-decoded. Interpolated -// raw, that text became markup in a page served from http://127.0.0.1, which is -// an origin the browser trusts as much as any other. +/** Everything the callback carries is attacker-controlled. The loopback listener + * answers whatever connects to it — it cannot tell Google's redirect from any + * other request to that port — so a crafted GET can put arbitrary text in + * error_description, and parseQuery hands it back percent-decoded. Interpolated + * raw, that text became markup in a page served from http://127.0.0.1, which is + * an origin the browser trusts as much as any other. + */ function escapeHtml(text) { return String(text === undefined || text === null ? "" : text) .replace(/&/g, "&") @@ -289,28 +295,31 @@ function escapeHtml(text) { .replace(/'/g, "'") } -// The palette crosses into a stylesheet rather than into text, where escaping -// does nothing: a value carrying "}" or "" would close the rule or the -// element and everything after it would be markup. It comes from the active -// Omarchy theme, which is a file the user installed rather than something a -// stranger sent — but this page is the one thing here a browser renders, and a -// colour that is not a colour has no business reaching it either way. +/** The palette crosses into a stylesheet rather than into text, where escaping + * does nothing: a value carrying "}" or "" would close the rule or the + * element and everything after it would be markup. It comes from the active + * Omarchy theme, which is a file the user installed rather than something a + * stranger sent — but this page is the one thing here a browser renders, and a + * colour that is not a colour has no business reaching it either way. + */ function cssColor(value, fallback) { var text = String(value === undefined || value === null ? "" : value).trim() return /^#[0-9A-Fa-f]{3,8}$/.test(text) ? text : fallback } -// Quoted in the stylesheet, so the quote itself is the character that must not -// survive. What is left is what a font is actually named. +/** Quoted in the stylesheet, so the quote itself is the character that must not + * survive. What is left is what a font is actually named. + */ function cssFontFamily(value) { var text = String(value === undefined || value === null ? "" : value) .replace(/[^A-Za-z0-9 _-]/g, "").trim() return text === "" ? "monospace" : text } -// `body` is markup by design — the success page carries a script that closes the -// tab — so it is the caller's job to have escaped anything untrusted inside it. -// Everything else this builds is escaped here. +/** `body` is markup by design — the success page carries a script that closes the + * tab — so it is the caller's job to have escaped anything untrusted inside it. + * Everything else this builds is escaped here. + */ function themedPage(theme, options) { var palette = theme || defaultTheme() var settings = options || {} diff --git a/ui/providers/Outlook.js b/ui/providers/Outlook.js index e18caf820..b365fcde4 100644 --- a/ui/providers/Outlook.js +++ b/ui/providers/Outlook.js @@ -1,6 +1,6 @@ .pragma library -// Provider presentation only. NativeDomain.js supplies all mail capabilities +// Invariant: Provider presentation only. NativeDomain.js supplies all mail capabilities // and mailbox queries; providers.resolve builds dynamic queries in Rust. .import "ImapProtocol.js" as Protocol @@ -14,7 +14,6 @@ var SUMMARY = "Outlook.com and Hotmail, signed in securely with Microsoft." var AUTH = "oauth" -// The Outlook.com envelope, square, so it serves the list row and the page. var MARK = "outlook.svg" var MAILBOXES = [ diff --git a/ui/providers/OutlookAuth.qml b/ui/providers/OutlookAuth.qml index 8841faa56..d04c9dbda 100644 --- a/ui/providers/OutlookAuth.qml +++ b/ui/providers/OutlookAuth.qml @@ -6,7 +6,7 @@ import "ImapProtocol.js" as Imap import "Outlook.js" as Outlook import "MicrosoftOAuth.js" as Microsoft -// Microsoft sign-in for the Outlook provider. The refresh token lives in +// Invariant: Microsoft sign-in for the Outlook provider. The refresh token lives in // GNOME Keyring; native backend clients handle OAuth, IMAP and SMTP networking. Item { id: root @@ -22,7 +22,7 @@ Item { property string configuredClientId: "" readonly property string clientId: Microsoft.effectiveClientId(configuredClientId) property string configuredEmail: "" - // The account entry's server settings. Outlook's servers are fixed by + // Invariant: The account entry's server settings. Outlook's servers are fixed by // `Outlook.settings` whatever these say; only two readings are taken from // them — the tenant the sign-in is addressed to, which `normalizeTenant` // keeps to one path segment of Microsoft's own URL, and whether the mailbox @@ -30,29 +30,20 @@ Item { property var entrySettings: null readonly property string tenant: Microsoft.normalizeTenant(entrySettings ? entrySettings.tenant : "") readonly property string configuredSend: entrySettings ? String(entrySettings.send || "") : "" - // Microsoft grants this token for its own mail service. Persisted generic + // Invariant: Microsoft grants this token for its own mail service. Persisted generic // IMAP settings must never select its destination or disable transport TLS. readonly property var settings: Outlook.settings(configuredEmail, tenant, configuredSend) property var scopes: Microsoft.SCOPES - // What the code on screen is for: the mail sign-in, or the second one - // that allows Microsoft Graph. A Graph exchange refused for want of consent - // sets `graphConsentNeeded`, and the next sign-in is the Graph one — - // offered on the setup page while the mail session stands. The Graph - // sign-in that follows a mail sign-in, for a tenant that sends through - // Graph, holds `loginSucceeded` until it is answered. property string devicePurpose: "mail" property bool graphConsentNeeded: false property bool graphRoundOfSignIn: false - // A Graph sign-in asked for from the setup page, on a mailbox that is + // Invariant: A Graph sign-in asked for from the setup page, on a mailbox that is // signed in and stays so: not `loginBusy`, which would take the mailbox // out of service for the code's duration. property bool graphRoundBusy: false - // Bumped when such a round is cut short, so its answers arriving after - // are let go of without touching anything of the mail session's; and - // counted grants, so a refusal answered after a grant does not undo it. property int graphRoundSerial: 0 property int graphGrants: 0 - // The mail session's account, by tenant and object id, from the id + // Invariant: The mail session's account, by tenant and object id, from the id // token that came with its token: what the Graph sign-in is held to. property string accountKey: "" @@ -95,18 +86,11 @@ Item { property double pendingExpiresIn: 0 property string pendingIdToken: "" - // The requests in flight, each answered on its own: a refresh and a Graph - // exchange may overlap, and neither's answer is dropped for the other's. - // `cancelLogin` lets go of them all, and an answer let go of is not - // delivered. property var tokenRequests: [] property int tokenRequestCount: 0 readonly property int tokenTimeoutMs: 30000 signal loginSucceeded() - // A Graph sign-in that did not go through, with what to do about it: for - // the setup page, since the mailbox itself is signed in and `lastError` - // is the mailbox's. signal graphRefused(string reason) signal loggedOut() signal sessionUnavailable(string reason) @@ -138,13 +122,10 @@ Item { graphAccessTokenExpiresAt = 0 graphConsentNeeded = false accountKey = "" - // A mailbox no longer signed in has no Graph code to finish. cancelGraphRound() } - // ------------------------------------------------------------- Graph - - // A token of Graph's audience, for a tenant that sends through Graph. The + // Invariant: A token of Graph's audience, for a tenant that sends through Graph. The // refresh token in the keyring is exchanged for it the same way the mail // token is refreshed, with Graph's scope in place of IMAP's; nothing new is // signed in to, and a rotated refresh token is stored back as before. @@ -170,9 +151,10 @@ Item { } } - // Native calendar work resolves its own tokens. Bind its consent result - // before it starts, so an old request cannot change a replacement session - // or undo the Graph device flow that completed while it was in flight. + /** Native calendar work resolves its own tokens. Bind its consent result + * before it starts, so an old request cannot change a replacement session + * or undo the Graph device flow that completed while it was in flight. + */ function graphConsentHandler() { var context = sessionContext() var requestedTenant = tenant @@ -209,7 +191,6 @@ Item { function startGraphLookup() { if (graphLookupProcess || graphWaiters.length === 0) return - // Behind a sign-in, the waiters are answered by whatever ends it. if (loginBusy || graphRoundBusy) return if (keyringJob || keyringJobs.length > 0) { graphQueued = true @@ -236,7 +217,7 @@ Item { function handleGraphLookup(raw, context) { if (!isCurrent(context) || !sessionEnabled) { - // A lookup from before a cancel, exiting now: waiters queued behind + // Invariant: A lookup from before a cancel, exiting now: waiters queued behind // it since are asked for again, or nothing would. if (sessionEnabled && graphWaiters.length > 0) Qt.callLater(root.startGraphLookup) return @@ -252,7 +233,7 @@ Item { Microsoft.graphRefreshBody(clientId, refreshToken), function(status, text) { if (!root.isCurrent(context) || !root.sessionEnabled) return - // A Graph sign-in went through while this was out: its answer is + // Invariant: A Graph sign-in went through while this was out: its answer is // the newer one, and this refusal or grant is of a token since // replaced. if (grants !== root.graphGrants && root.graphTokenIsFresh()) { @@ -262,18 +243,14 @@ Item { var result = Microsoft.parseTokenResponse(status, text, refreshToken) refreshToken = "" if (!result.ok) { - // For want of consent is the one refusal a sign-in mends; the - // setup page offers it while this is set. if (result.consentRequired) root.graphConsentNeeded = true - // A dead session is Microsoft's own words for it, not a missing + // Invariant: A dead session is Microsoft's own words for it, not a missing // permission. root.finishGraphWaiters("", root.safeError(result.consentRequired ? Microsoft.graphConsentMessage() : result.error)) return } if (Microsoft.missingGraphScope(result.scope)) { - // Issued without the permission: what a Graph sign-in collects. - // The refresh token it came with is the live one, whatever else. if (result.refreshToken) root.storeRefreshToken(result.refreshToken) root.graphConsentNeeded = true root.finishGraphWaiters("", Microsoft.graphConsentMessage()) @@ -292,11 +269,12 @@ Item { finishGraphWaiters(graphAccessToken, "") } - // Whether this client is consented for Graph is found out with the - // refresh token in hand, straight after the mail sign-in of a tenant that - // sends through Graph, and mended by a second code where it is not — - // rather than at the first send. Any other refusal is sending's to - // report: the mailbox is signed in. + /** Whether this client is consented for Graph is found out with the + * refresh token in hand, straight after the mail sign-in of a tenant that + * sends through Graph, and mended by a second code where it is not — + * rather than at the first send. Any other refusal is sending's to + * report: the mailbox is signed in. + */ function probeGraphConsent(refreshToken) { if (backend && (keyringJob || keyringJobs.length > 0)) { graphProbeQueued = true; return } var context = sessionContext() @@ -307,8 +285,6 @@ Item { if (!root.isCurrent(context) || !root.sessionEnabled) return var result = Microsoft.parseTokenResponse(status, text, refreshToken) refreshToken = "" - // Refused for want of consent, or issued without the permission: - // either is what the second code collects. if ((!result.ok && result.consentRequired) || (result.ok && Microsoft.missingGraphScope(result.scope))) { if (result.ok && result.refreshToken) root.storeRefreshToken(result.refreshToken) root.graphConsentNeeded = true @@ -329,11 +305,12 @@ Item { }) } - // The Graph sign-in answered: a token of Graph's audience, and a refresh - // token consented for both resources, kept in place of the mail one — - // the same user's and client's, and exchangeable for either. + /** The Graph sign-in answered: a token of Graph's audience, and a refresh + * token consented for both resources, kept in place of the mail one — + * the same user's and client's, and exchangeable for either. + */ function acceptGraphSignIn(result) { - // The mail sign-in is verified by logging in to the mailbox with its + // Invariant: The mail sign-in is verified by logging in to the mailbox with its // token; this one by the name on its id token, since a code entered // as someone else would file that someone's token as the mailbox's. if (!Microsoft.sameAccount(result.idToken, configuredEmail, accountKey)) { @@ -341,7 +318,7 @@ Item { return } if (Microsoft.missingGraphScope(result.scope)) { - // Issued to the right account without the permission: its refresh + // Invariant: Issued to the right account without the permission: its refresh // token is the live one all the same. if (result.refreshToken) storeRefreshToken(result.refreshToken) failGraphRound(Microsoft.graphScopeMessage()) @@ -357,8 +334,9 @@ Item { if (afterSignIn) loginSucceeded() } - // The Graph sign-in failing leaves the mail one as it was: the account is - // not told its session is gone, only what Graph will say when asked. + /** The Graph sign-in failing leaves the mail one as it was: the account is + * not told its session is gone, only what Graph will say when asked. + */ function failGraphRound(reason) { var message = Microsoft.graphRefusedMessage(safeError(reason || "Microsoft sign-in failed")) loginBusy = false @@ -382,12 +360,12 @@ Item { var pending = tokenWaiters.slice() tokenWaiters = [] for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { - // A consumer can synchronously sign out or switch accounts. Remaining + // Invariant: A consumer can synchronously sign out or switch accounts. Remaining // callbacks still belong to the session captured above. var current = isCurrent(context) && sessionEnabled try { pending[itemIndex](current ? (token || "") : "", current ? safeError(error) : "Session changed") } - catch (error) { /* consumers own their callback errors */ } + catch (error) { /* Invariant: one consumer must not prevent later waiters from completing. */ } } } @@ -426,7 +404,7 @@ Item { } function startSecretLookup() { - // A preceding store/clear must finish before a lookup can observe the key. + // Invariant: A preceding store/clear must finish before a lookup can observe the key. if (keyringJob || keyringJobs.length > 0) { restoreQueued = true return @@ -475,8 +453,9 @@ Item { enqueueKeyringJob("clear", [], "") } - // Jobs own immutable destinations. Serialize them so logout's clear cannot - // race a preceding store, even when the account host is reused meanwhile. + /** Jobs own immutable destinations. Serialize them so logout's clear cannot + * race a preceding store, even when the account host is reused meanwhile. + */ function enqueueKeyringJob(kind, attributes, token) { var next = keyringJobs.slice() next.push({ kind: kind, attributes: attributes.slice(), token: token, @@ -513,7 +492,7 @@ Item { root.runKeyringJob() } if (nativeStore) { - // Device grants and logout share the backend's account refresh lane. + // Invariant: Device grants and logout share the backend's account refresh lane. // A mail/Graph refresh already in flight must finish its rotation before // this newer grant replaces it, or the old grant can overwrite consent. var fields = { accountId: job.context.accountId, clientId: job.context.clientId } @@ -574,7 +553,7 @@ Item { function refreshWithToken(refreshToken, context) { if (backend && accountId) refreshToken = "" refreshBusy = true - // The mail scopes alone: a token is for one resource, and Microsoft + // Invariant: The mail scopes alone: a token is for one resource, and Microsoft // refuses a refresh that names two. The Graph exchange asks for its own. postForm(Microsoft.tokenUrlFor(tenant), Microsoft.refreshTokenBody(clientId, refreshToken, Microsoft.SCOPES), @@ -638,13 +617,8 @@ Item { : "Install or update the mail backend before signing in" return } - // Signed in for mail and refused Graph for want of consent: the code - // asked for is Graph's, and the mail session stands. A saved session - // not restored yet signs in for mail first, whatever Graph said. var forGraph = graphConsentNeeded && loggedIn if (forGraph) { - // The mailbox stays in service: nothing of the mail session is let - // go of, and only Graph's code is busy. lastError = "" graphRoundOfSignIn = false graphRoundBusy = true @@ -658,8 +632,9 @@ Item { startDeviceFlow("mail") } - // One device-code round: the code and the page to enter it on, then the - // poll until Microsoft answers with a token or a refusal. + /** One device-code round: the code and the page to enter it on, then the + * poll until Microsoft answers with a token or a refusal. + */ function startDeviceFlow(purpose) { var context = sessionContext() var round = graphRoundSerial @@ -726,8 +701,6 @@ Item { root.pendingRefreshToken = result.refreshToken root.pendingExpiresIn = result.expiresIn root.pendingIdToken = result.idToken - // The code has been entered: what the page shows from here is the - // mailbox being verified, or Graph's own code. root.deviceCode = "" root.userCode = "" root.verificationUri = "" @@ -753,8 +726,6 @@ Item { acceptToken(result) finishWaiters(accessToken, "") if (configuredSend === "graph") { - // The sign-in's tail is Graph's from here: cut short, the mail half - // is in and is said so. graphRoundOfSignIn = true probeGraphConsent(result.refreshToken) return @@ -790,14 +761,14 @@ Item { loginBusy = false cancelDeviceLogin() finishWaiters("", lastError) - // Graph's waiters were parked behind this sign-in. finishGraphWaiters("", lastError) sessionUnavailable(lastError) } - // A Graph sign-in asked for from the setup page, cut short: the code goes - // and its waiters are told, and nothing of the mail session — a refresh - // in flight, its waiters, a lookup — is touched. + /** A Graph sign-in asked for from the setup page, cut short: the code goes + * and its waiters are told, and nothing of the mail session — a refresh + * in flight, its waiters, a lookup — is touched. + */ function cancelGraphRound() { if (!graphRoundBusy) return graphRoundSerial++ @@ -807,7 +778,7 @@ Item { } function cancelLogin() { - // Cancel on a settings-page Graph code, the mailbox staying signed in, + // Invariant: Cancel on a settings-page Graph code, the mailbox staying signed in, // is that code's alone. Signing out or changing identity is everything's: // a mail refresh in flight would otherwise be left busy for good, its // answer refused for the session being over. @@ -818,12 +789,12 @@ Item { sessionGeneration++ var oldLookup = lookupProcess lookupProcess = null - // Async credential callbacks compare this sentinel and the generation; + // Invariant: Async credential callbacks compare this sentinel and the generation; // clearing it cancels their authority to update the session. restoreQueued = false graphProbeQueued = false refreshRetry.stop() - // Where what is cut short is the Graph tail of a sign-in — the check + // Invariant: Where what is cut short is the Graph tail of a sign-in — the check // or the second code — the mail half is in and is said so. var afterSignIn = graphRoundOfSignIn && sessionEnabled graphRoundOfSignIn = false @@ -837,8 +808,6 @@ Item { loginBusy = false graphRoundBusy = false finishWaiters("", "Sign-in cancelled") - // Graph's waiters, parked behind the sign-in or the Graph round's own, - // are answered either way. finishGraphWaiters("", "Sign-in cancelled") if (afterSignIn) loginSucceeded() } diff --git a/ui/providers/Secrets.js b/ui/providers/Secrets.js index b1978a3c2..56a8cd93f 100644 --- a/ui/providers/Secrets.js +++ b/ui/providers/Secrets.js @@ -1,19 +1,20 @@ .pragma library -// What comes back from `secret-tool`, and what it is safe to change about it. -// -// A secret is bytes the user chose and the keyring stored, so the only thing -// this may remove is punctuation the pipe added. `secret-tool lookup` writes -// the value with no trailing newline of its own — which is the bug this exists -// for, because a `SplitParser` splitting on "\n" then never fires at all and a -// stored password reads back as no password at all — but the shells and stores -// around it are not all so careful, and one trailing newline is the shape a -// line-oriented pipe can add. -// -// Exactly one, and only at the end. `trim()` looks like the same thing and is -// not: a password may legitimately begin or end with a space, and a client that -// quietly removed it would authenticate as a different string and report the -// password as wrong, with nothing the user could do about it from the interface. +/** What comes back from `secret-tool`, and what it is safe to change about it. + * + * A secret is bytes the user chose and the keyring stored, so the only thing + * this may remove is punctuation the pipe added. `secret-tool lookup` writes + * the value with no trailing newline of its own — which is the bug this exists + * for, because a `SplitParser` splitting on "\n" then never fires at all and a + * stored password reads back as no password at all — but the shells and stores + * around it are not all so careful, and one trailing newline is the shape a + * line-oriented pipe can add. + * + * Exactly one, and only at the end. `trim()` looks like the same thing and is + * not: a password may legitimately begin or end with a space, and a client that + * quietly removed it would authenticate as a different string and report the + * password as wrong, with nothing the user could do about it from the interface. + */ function fromKeyring(value) { var text = String(value === undefined || value === null ? "" : value) return text.charAt(text.length - 1) === "\n" ? text.substring(0, text.length - 1) : text From e2e86d6d41975d82051396ddaef94c9e96224921 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 110/568] Fix empty read completion after provider cancellation --- ui/providers/HeyClient.qml | 2 +- ui/tests/qml/tst_provider_session_callbacks.qml | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/ui/providers/HeyClient.qml b/ui/providers/HeyClient.qml index 93dcbe653..a76ffc026 100644 --- a/ui/providers/HeyClient.qml +++ b/ui/providers/HeyClient.qml @@ -126,7 +126,7 @@ Item { var remaining = list.length var firstError = "" if (remaining === 0) { - Qt.callLater(function() { if (root) callback([], "") }) + Qt.callLater(function() { if (root && !handle.aborted) callback([], "") }) return handle } for (var itemIndex = 0; itemIndex < list.length; itemIndex++) { diff --git a/ui/tests/qml/tst_provider_session_callbacks.qml b/ui/tests/qml/tst_provider_session_callbacks.qml index 5bc9c2df2..4ac9efacd 100644 --- a/ui/tests/qml/tst_provider_session_callbacks.qml +++ b/ui/tests/qml/tst_provider_session_callbacks.qml @@ -22,6 +22,7 @@ Item { } } Component { id: heyFactory; Providers.HeyAuth { pluginDir: "/synthetic" } } + Component { id: heyClientFactory; Providers.HeyClient {} } TestCase { name: "ProviderSessionCallbacks" function init() { fakeBackend.requests = [] } @@ -79,6 +80,15 @@ Item { fakeBackend.requests = [] return auth } + function test_cancelled_empty_hey_read_does_not_deliver() { + var auth = hey() + var client = createTemporaryObject(heyClientFactory, root, { auth: auth }) + var delivered = 0 + var handle = client.getMessages([], true, function() { delivered++ }) + client.abortRequest(handle) + wait(1) + compare(delivered, 0) + } function test_cancelled_hey_start_cannot_restart_polling() { var auth = hey() auth.beginLogin() From 6213ea3b2f88e1bd19a672ae04d0038f03f395f7 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 111/568] Flatten provider page request handling --- tests/test_hey_backend.js | 2 +- ui/providers/HeyClient.qml | 72 ++++++++++++++++---------------------- 2 files changed, 31 insertions(+), 43 deletions(-) diff --git a/tests/test_hey_backend.js b/tests/test_hey_backend.js index bb146f576..f0d61bc8e 100644 --- a/tests/test_hey_backend.js +++ b/tests/test_hey_backend.js @@ -16,7 +16,7 @@ const context = { } context.root = context vm.createContext(context) -for (const name of ["newHandle", "abortRequest", "usesBackend", "backendRead", "rememberResources", "listMessages", "getMessages", "getMessage", "forget"]) +for (const name of ["newHandle", "abortRequest", "usesBackend", "backendRead", "rememberResources", "listMessages", "readFullPage", "getMessages", "getMessage", "forget"]) vm.runInContext(method(name), context) let pending, request context.backend = { executable: "/bin/omamail", call(method, params, callback) { diff --git a/ui/providers/HeyClient.qml b/ui/providers/HeyClient.qml index a76ffc026..9d8a3d3c3 100644 --- a/ui/providers/HeyClient.qml +++ b/ui/providers/HeyClient.qml @@ -108,58 +108,46 @@ Item { return handle } - /** A whole page with no round trips at all: the listing that produced these - * ids carried every field a row needs, so this is the cache answering. - * - * Deferred rather than answered on the spot even though the answer is in - * hand. Every caller is written against a callback that arrives later, and - * running one partway through the function that started it is a re-entry the - * Gmail client never produces. + function readFullPage(ids, callback, handle, progress) { + var results = new Array(ids.length) + var remaining = ids.length + var firstError = "" + if (remaining === 0) { + Qt.callLater(function() { if (root && !handle.aborted) callback([], "") }) + return handle + } + function readAt(index) { + var child = root.getMessage(ids[index], true, function(payload, error) { + if (handle.aborted) return + if (error && !firstError) firstError = error + results[index] = payload + if (payload && typeof progress === "function") progress([payload]) + remaining-- + if (remaining > 0) return + callback(results.filter(function(message) { return !!message }), firstError) + }) + handle.children.push(child) + } + for (var index = 0; index < ids.length; index++) readAt(index) + return handle + } + + /** Full reads fetch bodies; summary reads use resources already supplied by the listing. + * Cached results are deferred to preserve the asynchronous callback contract. */ function getMessages(ids, full, callback, existingHandle, progress) { var handle = existingHandle || newHandle() var list = Array.isArray(ids) ? ids : [] if (typeof callback !== "function") return handle - - if (full === true) { - var results = new Array(list.length) - var remaining = list.length - var firstError = "" - if (remaining === 0) { - Qt.callLater(function() { if (root && !handle.aborted) callback([], "") }) - return handle - } - for (var itemIndex = 0; itemIndex < list.length; itemIndex++) { - (function(index) { - var child = root.getMessage(list[index], true, function(payload, error) { - if (handle.aborted) return - if (error && !firstError) firstError = error - results[index] = payload - if (payload && typeof progress === "function") progress([payload]) - remaining-- - if (remaining > 0) return - var ordered = [] - for (var nestedIndex = 0; nestedIndex < results.length; nestedIndex++) { - if (results[nestedIndex]) ordered.push(results[nestedIndex]) - } - callback(ordered, firstError) - }) - handle.children.push(child) - })(itemIndex) - } - return handle - } + if (full === true) return readFullPage(list, callback, handle, progress) Qt.callLater(function() { if (!root || handle.aborted) return var output = [] for (var itemIndex = 0; itemIndex < list.length; itemIndex++) { - if (root.usesBackend()) { - var resource = root.messageResources[String(list[itemIndex])] - if (resource) output.push(resource) - continue - } - + if (!root.usesBackend()) continue + var resource = root.messageResources[String(list[itemIndex])] + if (resource) output.push(resource) } if (output.length > 0 && typeof progress === "function") progress(output) callback(output, output.length > 0 || list.length === 0 ? "" From cfd350805c1afe3f4835981a34a487c375068a08 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 112/568] Remove unused provider shell imports --- ui/providers/ImapAuth.qml | 2 -- ui/providers/JmapAuth.qml | 2 -- ui/providers/OutlookAuth.qml | 2 -- 3 files changed, 6 deletions(-) diff --git a/ui/providers/ImapAuth.qml b/ui/providers/ImapAuth.qml index 02f054d57..dbfb4d111 100644 --- a/ui/providers/ImapAuth.qml +++ b/ui/providers/ImapAuth.qml @@ -1,6 +1,4 @@ import QtQuick -import Quickshell -import Quickshell.Io import "ImapProtocol.js" as Imap diff --git a/ui/providers/JmapAuth.qml b/ui/providers/JmapAuth.qml index 34e6d0683..edf4de5d2 100644 --- a/ui/providers/JmapAuth.qml +++ b/ui/providers/JmapAuth.qml @@ -1,6 +1,4 @@ import QtQuick -import Quickshell -import Quickshell.Io import "JmapProtocol.js" as Jmap diff --git a/ui/providers/OutlookAuth.qml b/ui/providers/OutlookAuth.qml index d04c9dbda..ea9525211 100644 --- a/ui/providers/OutlookAuth.qml +++ b/ui/providers/OutlookAuth.qml @@ -1,6 +1,4 @@ import QtQuick -import Quickshell -import Quickshell.Io import "ImapProtocol.js" as Imap import "Outlook.js" as Outlook From aacf886a8c02e6d664efb198b9e2f51755cb9ced Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 113/568] chore: Give Graph consent fixtures matching identities --- ui/tests/qml/tst_outlook_backend_consent.qml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ui/tests/qml/tst_outlook_backend_consent.qml b/ui/tests/qml/tst_outlook_backend_consent.qml index 6115bed26..3887299e9 100644 --- a/ui/tests/qml/tst_outlook_backend_consent.qml +++ b/ui/tests/qml/tst_outlook_backend_consent.qml @@ -17,6 +17,10 @@ Item { property string failure: "auth_consent_required" property bool hold: false property var pending: null + function identityToken() { + var claims = { preferred_username: "alice@example.test" } + return "h." + Qt.btoa(JSON.stringify(claims)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") + ".s" + } function call(method, params, callback) { calls = calls.concat([{method: method, params: params}]) if (method === "auth.store") { @@ -50,7 +54,7 @@ Item { } if (method === "auth.form" && params.endpoint === "token") { callback({status: 200, body: JSON.stringify({access_token: "graph-token", - refresh_token: "graph-refresh-token", expires_in: 3600, scope: Microsoft.GRAPH_SCOPES.join(" ")})}, null) + refresh_token: "graph-refresh-token", id_token: identityToken(), expires_in: 3600, scope: Microsoft.GRAPH_SCOPES.join(" ")})}, null) return } callback({}, null) @@ -164,7 +168,7 @@ Item { function test_graph_device_grant_uses_the_serialized_backend_store() { var auth = fresh() auth.acceptGraphSignIn({accessToken: "graph-token", refreshToken: "device-graph-refresh", - expiresIn: 3600, scope: Microsoft.GRAPH_SCOPES.join(" ")}) + expiresIn: 3600, idToken: fixture.identityToken(), scope: Microsoft.GRAPH_SCOPES.join(" ")}) compare(fixture.calls.length, 1) compare(fixture.calls[0].method, "auth.store") compare(fixture.calls[0].params.accountId, auth.accountId) From 0c52d8004e34f11a9faccd0ccfa49d97a7446b85 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 114/568] chore: Clarify provider authentication fixtures --- ui/tests/qml/tst_gmail_queue.qml | 2 +- ui/tests/qml/tst_jmap_failure_recovery.qml | 56 ++++++------- ui/tests/qml/tst_jmap_mark_all_read.qml | 17 +--- ui/tests/qml/tst_jmap_member_action.qml | 12 +-- ui/tests/qml/tst_jmap_push_action.qml | 21 +---- ui/tests/qml/tst_jmap_push_reconnect.qml | 78 +++++++++---------- .../qml/tst_jmap_queued_member_action.qml | 2 +- ui/tests/qml/tst_jmap_rejected_credential.qml | 31 +++----- ui/tests/qml/tst_jmap_request_queue.qml | 68 ++++++++-------- ui/tests/qml/tst_jmap_scheme_detection.qml | 2 - ui/tests/qml/tst_jmap_session_state.qml | 18 +---- ui/tests/qml/tst_jmap_sign_in.qml | 4 +- ui/tests/qml/tst_outlook_graph_consent.qml | 32 ++++---- ui/tests/qml/tst_outlook_security.qml | 14 ++-- 14 files changed, 146 insertions(+), 211 deletions(-) diff --git a/ui/tests/qml/tst_gmail_queue.qml b/ui/tests/qml/tst_gmail_queue.qml index 85bb0b014..0f6bf8db6 100644 --- a/ui/tests/qml/tst_gmail_queue.qml +++ b/ui/tests/qml/tst_gmail_queue.qml @@ -122,7 +122,7 @@ Item { var handle = api.getMessages(["a", "b", "c", "d", "e", "f"], false, function() { fail("aborted page delivered") }) api.abortRequest(handle) - for (var i = 0; i < 4; i++) api.backend.answer(i, { id: "ignored" }) + for (var itemIndex = 0; itemIndex < 4; itemIndex++) api.backend.answer(itemIndex, { id: "ignored" }) compare(api.backend.calls.length, 4) compare(api.inFlight, 0) } diff --git a/ui/tests/qml/tst_jmap_failure_recovery.qml b/ui/tests/qml/tst_jmap_failure_recovery.qml index f44c7aa67..4ce94d494 100644 --- a/ui/tests/qml/tst_jmap_failure_recovery.qml +++ b/ui/tests/qml/tst_jmap_failure_recovery.qml @@ -22,74 +22,74 @@ Item { TestCase { when: windowShown function setup() { - var f = createTemporaryObject(fixture, this) - Transports.install(f.api) - return f + var scenario = createTemporaryObject(fixture, this) + Transports.install(scenario.api) + return scenario } name: "JmapFailureRecovery" // Import, submission, cleanup and 404 retry ordering are native Rust // workflow tests. UI must preserve payload identity, propagate failure // once, and never compensate by issuing another mutation itself. function test_failed_draft_save_keeps_original_id_and_never_retries_or_destroys() { - var f = setup() + var scenario = setup() var answers = 0 var error = "" var payload = {draftId:"original",raw:"U3ViamVjdDogeA0KDQpib2R5"} - f.api.saveDraft(payload,function(result,failure) { answers++; error=failure; compare(result,null) }) - var request = Transports.transports(f.api)[0] + scenario.api.saveDraft(payload,function(result,failure) { answers++; error=failure; compare(result,null) }) + var request = Transports.transports(scenario.api)[0] compare(request.method, "jmap.saveDraft") compare(request.params.draftId,"original") compare(request.params.raw,payload.raw) Transports.reply(request,null,{message:"jmap_import_failed"}) compare(answers,1) verify(error.length > 0) - compare(Transports.transports(f.api).length,1) + compare(Transports.transports(scenario.api).length,1) compare(payload.draftId,"original") } function test_unconfirmed_send_is_reported_without_retry() { - var f = setup() + var scenario = setup() var error = "" - f.api.sendMessage({draftId:"original",raw:"U3ViamVjdDogeA0KDQpib2R5"},function(result,failure) { error=failure }) - var request=Transports.transports(f.api)[0] + scenario.api.sendMessage({draftId:"original",raw:"U3ViamVjdDogeA0KDQpib2R5"},function(result,failure) { error=failure }) + var request=Transports.transports(scenario.api)[0] compare(request.method,"jmap.send") compare(request.params.draftId,"original") Transports.reply(request,null,{message:"jmap_submission_unconfirmed"}) compare(error,"The server did not confirm sending. Check Sent before trying again") - compare(Transports.transports(f.api).length,1) + compare(Transports.transports(scenario.api).length,1) } function test_confirmed_save_preserves_backend_warning_and_identity() { - var f = setup() + var scenario = setup() var answer = null - f.api.saveDraft({draftId:"old",raw:"eA"},function(result,error) {compare(error,"");answer=result}) - Transports.complete(Transports.transports(f.api)[0], {id:"new",warning:"Original draft could not be removed"}) + scenario.api.saveDraft({draftId:"old",raw:"eA"},function(result,error) {compare(error,"");answer=result}) + Transports.complete(Transports.transports(scenario.api)[0], {id:"new",warning:"Original draft could not be removed"}) compare(answer.id,"new") verify(answer.warning.length > 0) - compare(Transports.transports(f.api).length,1) + compare(Transports.transports(scenario.api).length,1) } function test_stale_verification_cannot_restore_a_changed_account() { - var f=setup() + var scenario=setup() var answered=false - f.api.verifyCredentials({},"ada@example.org","synthetic-secret",function(){answered=true}) - var request=Transports.transports(f.api)[0] - f.api.forgetServer() + scenario.api.verifyCredentials({},"ada@example.org","synthetic-secret",function(){answered=true}) + var request=Transports.transports(scenario.api)[0] + scenario.api.forgetServer() Transports.reply(request,{session:{state:"old"},mailboxes:[],sessionUrl:"https://old.example.org/session",accountId:"old"},"") - compare(f.api.session,null) - compare(f.api.mailboxList.length,0) + compare(scenario.api.session,null) + compare(scenario.api.mailboxList.length,0) compare(answered,false) } function test_failed_discovery_never_replaces_session_or_starts_followup() { - var f=setup() - f.api.session={state:"original"} + var scenario=setup() + scenario.api.session={state:"original"} var failure="" - f.api.verifyCredentials({},"ada@example.org","synthetic-secret",function(result,error){failure=error}) - var request=Transports.transports(f.api)[0] + scenario.api.verifyCredentials({},"ada@example.org","synthetic-secret",function(result,error){failure=error}) + var request=Transports.transports(scenario.api)[0] compare(request.method,"jmap.verify") compare(request.params.address,"ada@example.org") Transports.reply(request,null,{message:"jmap_discovery_failed"}) - compare(f.api.session.state,"original") + compare(scenario.api.session.state,"original") verify(failure.length>0) - compare(f.api.credentialsRejected,false) - compare(Transports.transports(f.api).length,1) + compare(scenario.api.credentialsRejected,false) + compare(Transports.transports(scenario.api).length,1) } } } diff --git a/ui/tests/qml/tst_jmap_mark_all_read.qml b/ui/tests/qml/tst_jmap_mark_all_read.qml index 58bebe78b..bf26efa90 100644 --- a/ui/tests/qml/tst_jmap_mark_all_read.qml +++ b/ui/tests/qml/tst_jmap_mark_all_read.qml @@ -4,21 +4,8 @@ import "transports.js" as Transports import "NativeIntentFixture.js" as NativeIntentFixture import "../../account" as Account -// "Mark these read" reaches the rail and the open message, and comes back. -// -// The list's rows took the change and the rail's stops did not: every member -// summary the account held kept its dot, and nothing later re-reads a member -// it already has, so the stale dot lasted the session. The same batch now -// marks every held member, gives a representative its row's own recomputed -// summary, and reads the open message the same way — and an error puts all -// three back with the rows. -// -// Why Qt rather than node: the batch is one function over four properties of -// one account, and the failure this is written against was the function -// touching three of them. The account is a real `MailAccount` on the real -// `JmapClient`; its transport is the stubbed `Process` under -// `tests/qml/imports`, which never exits on its own, so the request stays in -// flight until this test ends it. +// Invariant: A failed native mutation restores the conversation row, held member +// summaries and the open message together. The fixture controls RPC completion. Item { width: 400 height: 300 diff --git a/ui/tests/qml/tst_jmap_member_action.qml b/ui/tests/qml/tst_jmap_member_action.qml index ebef79aca..4de963365 100644 --- a/ui/tests/qml/tst_jmap_member_action.qml +++ b/ui/tests/qml/tst_jmap_member_action.qml @@ -4,14 +4,8 @@ import "transports.js" as Transports import "NativeIntentFixture.js" as NativeIntentFixture import "../../account" as Account -// An action from a stop on the rail names one message on the wire. -// -// A verb on a conversation row reaches every counted member: the account -// expands the row to its block and hands the client the flat list. A stop is -// one message, and the same verb from its menu must name that message alone — -// including when the stop is the representative, whose id is also a row's. -// `MailAccount.act`'s fourth argument is what says so, and what has to be seen -// here is the `Email/set` the transport is handed: one id, then three. +// Invariant: A conversation action names every counted member. A reader-rail +// action names only the selected member, including a representative that is also a row. Item { width: 400 height: 300 @@ -71,7 +65,7 @@ Item { { id: "b", name: "Trash", role: "trash", parentId: null, totalEmails: 0, unreadEmails: 0 } ] - // The ids an `Email/set` request named, read off the transport line. + // Invariant: Native mutations preserve the selected member IDs. function updatedIds(process) { verify(process.method === "jmap.trash" || process.method === "jmap.batchModify") compare(process.params.accountId, "jmap:ada@example.org") diff --git a/ui/tests/qml/tst_jmap_push_action.qml b/ui/tests/qml/tst_jmap_push_action.qml index b71669b1c..d134b3db0 100644 --- a/ui/tests/qml/tst_jmap_push_action.qml +++ b/ui/tests/qml/tst_jmap_push_action.qml @@ -4,25 +4,8 @@ import "transports.js" as Transports import "NativeIntentFixture.js" as NativeIntentFixture import "../../account" as Account -// A push that lands while an action is still in the air. -// -// The mechanism is the one the account already had, and that is the point: a -// JMAP change notification goes through `refresh()`, which is the poll's own -// door, so `loadMessages` defers it exactly as it defers a poll tick — and the -// action's own callback replays it afterwards. Nothing about push is special -// here except how fast it arrives. -// -// Why this needs Qt rather than a node test: the deferral is three objects -// agreeing. The client's `remoteChanged` signal, the handler `MailAccount` -// wires it to, and the pending-action state the optimistic update left behind -// only meet inside a live component tree. A JavaScript test could assert each -// of the three and still not catch the wiring being absent, which is the -// failure this is written against. -// -// The account is a real `MailAccount` on the real `JmapClient`. Its transport -// is the stubbed `Process` under `tests/qml/imports`, which never exits on its -// own — so a request stays in flight until this test ends it, which is what -// makes "while an action is pending" a state the test can stand still in. +// Invariant: A push arriving during an optimistic mutation waits for that mutation, +// then starts the deferred refresh even if the mutation failed. RPC replies are controlled. Item { width: 400 height: 300 diff --git a/ui/tests/qml/tst_jmap_push_reconnect.qml b/ui/tests/qml/tst_jmap_push_reconnect.qml index 0b1b487e3..2fef182a0 100644 --- a/ui/tests/qml/tst_jmap_push_reconnect.qml +++ b/ui/tests/qml/tst_jmap_push_reconnect.qml @@ -56,57 +56,57 @@ Item { name: "JmapPushBackendLifetime" when: windowShown function test_stale_open_is_closed_without_starting_poll() { - var f = createTemporaryObject(fixture, this) - f.auth.loggedIn = true - compare(f.calls.length, 1) - compare(f.calls[0].method, "jmap.watch") - compare(f.calls[0].params.accountId, "jmap:ada@example.org") - compare(f.calls[0].params.credential, undefined) - f.auth.loggedIn = false - f.calls[0].callback({opened:true}, "") - compare(f.calls.length, 3) - compare(f.calls[1].method, "jmap.cancel") - compare(f.calls[2].method, "jmap.stream.close") - compare(f.calls[2].params.streamId, f.calls[0].params.streamId) - compare(f.push.streamId, "") + var scenario = createTemporaryObject(fixture, this) + scenario.auth.loggedIn = true + compare(scenario.calls.length, 1) + compare(scenario.calls[0].method, "jmap.watch") + compare(scenario.calls[0].params.accountId, "jmap:ada@example.org") + compare(scenario.calls[0].params.credential, undefined) + scenario.auth.loggedIn = false + scenario.calls[0].callback({opened:true}, "") + compare(scenario.calls.length, 3) + compare(scenario.calls[1].method, "jmap.cancel") + compare(scenario.calls[2].method, "jmap.stream.close") + compare(scenario.calls[2].params.streamId, scenario.calls[0].params.streamId) + compare(scenario.push.streamId, "") } function test_poll_stops_when_account_logs_out_and_stale_reply_is_ignored() { - var f = createTemporaryObject(fixture, this) - f.auth.loggedIn = true - f.calls[0].callback({opened:true}, "") - compare(f.calls[1].method, "jmap.stream.poll") - var id = f.calls[1].params.streamId - f.auth.loggedIn = false - compare(f.calls[2].method, "jmap.stream.close") - compare(f.calls[2].params.streamId, id) - f.calls[1].callback({events:[{kind:"connected"}], closed:false}, "") + var scenario = createTemporaryObject(fixture, this) + scenario.auth.loggedIn = true + scenario.calls[0].callback({opened:true}, "") + compare(scenario.calls[1].method, "jmap.stream.poll") + var id = scenario.calls[1].params.streamId + scenario.auth.loggedIn = false + compare(scenario.calls[2].method, "jmap.stream.close") + compare(scenario.calls[2].params.streamId, id) + scenario.calls[1].callback({events:[{kind:"connected"}], closed:false}, "") wait(0) - compare(f.calls.length, 3) - compare(f.push.streamId, "") + compare(scenario.calls.length, 3) + compare(scenario.push.streamId, "") } function test_rejected_credential_closes_without_reopening() { - var f = createTemporaryObject(fixture, this) + var scenario = createTemporaryObject(fixture, this) var rejected = 0 - f.push.secretRejected.connect(function() { rejected++ }) - f.auth.loggedIn = true - f.calls[0].callback({opened:true}, "") - f.calls[1].callback({events:[{kind:"rejected"}], closed:false}, "") + scenario.push.secretRejected.connect(function() { rejected++ }) + scenario.auth.loggedIn = true + scenario.calls[0].callback({opened:true}, "") + scenario.calls[1].callback({events:[{kind:"rejected"}], closed:false}, "") compare(rejected, 1) - compare(f.calls[2].method, "jmap.stream.close") + compare(scenario.calls[2].method, "jmap.stream.close") wait(0) - compare(f.calls.length, 3) + compare(scenario.calls.length, 3) } function test_poll_delivery_continues_on_same_stream() { - var f = createTemporaryObject(fixture, this) + var scenario = createTemporaryObject(fixture, this) var changes = 0 - f.push.remoteChanged.connect(function() { changes++ }) - f.auth.loggedIn = true - f.calls[0].callback({opened:true}, "") - f.calls[1].callback({events:[{kind:"connected"}], closed:false}, "") + scenario.push.remoteChanged.connect(function() { changes++ }) + scenario.auth.loggedIn = true + scenario.calls[0].callback({opened:true}, "") + scenario.calls[1].callback({events:[{kind:"connected"}], closed:false}, "") compare(changes, 1) - tryVerify(function() { return f.calls.length === 3 }) - compare(f.calls[2].method, "jmap.stream.poll") - compare(f.calls[2].params.streamId, f.calls[1].params.streamId) + tryVerify(function() { return scenario.calls.length === 3 }) + compare(scenario.calls[2].method, "jmap.stream.poll") + compare(scenario.calls[2].params.streamId, scenario.calls[1].params.streamId) } } } diff --git a/ui/tests/qml/tst_jmap_queued_member_action.qml b/ui/tests/qml/tst_jmap_queued_member_action.qml index 93edc6bbd..34b709b24 100644 --- a/ui/tests/qml/tst_jmap_queued_member_action.qml +++ b/ui/tests/qml/tst_jmap_queued_member_action.qml @@ -69,7 +69,7 @@ Item { { id: "b", name: "Trash", role: "trash", parentId: null, totalEmails: 0, unreadEmails: 0 } ] - // The ids an `Email/set` request named, read off the transport line. + // Invariant: Native mutations preserve the selected member IDs. function updatedIds(process) { verify(process.method === "jmap.trash" || process.method === "jmap.batchModify") compare(process.params.accountId, "jmap:ada@example.org") diff --git a/ui/tests/qml/tst_jmap_rejected_credential.qml b/ui/tests/qml/tst_jmap_rejected_credential.qml index c09c396f9..1eb232519 100644 --- a/ui/tests/qml/tst_jmap_rejected_credential.qml +++ b/ui/tests/qml/tst_jmap_rejected_credential.qml @@ -3,21 +3,8 @@ import QtTest 1.3 import "transports.js" as Transports import "../../account" as Account -// A refused credential is not sent again until somebody has typed one. -// -// A 401 raises the client's `credentialsRejected`, which the setup page draws -// its re-entry card from and the event stream reads to stop. Every *request* -// went on regardless: the queue, the session fetch and a blob download all -// asked the auth object for the credential and sent it, so the poll carried -// the refused secret to the server every two minutes for as long as the -// account stood — the retry that locks an app password, which spec story 62 -// exists to prevent. This is the assertion that no verb carries the secret -// while the flag is up, and that sign-in — the one request that clears the -// flag — still goes out and opens the door again. -// -// Why Qt rather than node: the flag is a property of the client, the poll's -// door is `MailAccount.refresh()`, and the four paths are four methods on the -// real objects with the transport stubbed. +// Invariant: After a native credential rejection, mailbox reads and writes stay +// blocked until sign-in verifies a replacement. No request may retry the rejected grant. Item { width: 400 height: 300 @@ -77,11 +64,11 @@ Item { sessionState: "s0" }) - function carriesSecret(process) { + function mailboxRequest(process) { return process.method !== "jmap.verify" } - function test_no_verb_carries_a_refused_secret_until_sign_in_clears_it() { + function test_no_mailbox_request_retries_after_rejection_until_sign_in() { verify(!!account.auth && !!account.api) Transports.install(account.api) account.auth.secret = "app-password" @@ -91,8 +78,8 @@ Item { // The poll's first request — a session GET, since nothing is held yet, // and already in flight from the tick that fires on ready — and the // server refuses it. - var first = Transports.transports(account.api).filter(carriesSecret) - verify(first.length > 0, "the first poll carries the secret, as it must") + var first = Transports.transports(account.api).filter(mailboxRequest) + verify(first.length > 0, "the first mailbox read reaches the native backend") var before compare(first[0].params.credential, undefined) // Several native startup reads may already be pending. Their terminal @@ -123,10 +110,10 @@ Item { account.api.session = null account.api.ensureSession(function(error) { answers.push(["session", error]) }) compare(Transports.newSince(account.api, before).length, 0, - "a call, an upload, a download and a session fetch all start no process") + "a call, an upload, a download and a session fetch all start no native request") compare(answers.length, 4, "and each answers its caller at once") - for (var i = 0; i < answers.length; i++) - compare(answers[i][1], "Sign in to this mailbox again", answers[i][0] + " says why") + for (var itemIndex = 0; itemIndex < answers.length; itemIndex++) + compare(answers[itemIndex][1], "Sign in to this mailbox again", answers[itemIndex][0] + " says why") compare(account.api.busy, false, "nothing is in flight") // Sign-in is the one request that still goes out, because it is what diff --git a/ui/tests/qml/tst_jmap_request_queue.qml b/ui/tests/qml/tst_jmap_request_queue.qml index 67be80b30..08932e2c6 100644 --- a/ui/tests/qml/tst_jmap_request_queue.qml +++ b/ui/tests/qml/tst_jmap_request_queue.qml @@ -22,66 +22,66 @@ Item { TestCase { when: windowShown function setup() { - var f = createTemporaryObject(fixture, this) - Transports.install(f.api) - return f + var scenario = createTemporaryObject(fixture, this) + Transports.install(scenario.api) + return scenario } name: "JmapNativeRequestLifetime" function test_abandoned_requests_cancel_by_id_and_late_reply_cannot_apply_state() { - var f = setup() + var scenario = setup() var called = 0 - for (var i = 0; i < 4; i++) { - var before = Transports.transports(f.api) - var handle = f.api.getMessage("m" + i, true, function() { called++ }) - var request = Transports.newSince(f.api, before)[0] + for (var itemIndex = 0; itemIndex < 4; itemIndex++) { + var before = Transports.transports(scenario.api) + var handle = scenario.api.getMessage("m" + itemIndex, true, function() { called++ }) + var request = Transports.newSince(scenario.api, before)[0] compare(request.method, "jmap.read") compare(request.params.accountId, "jmap:ada@example.org") compare(request.params.credential, undefined) - compare(f.api.inFlight, 1) - f.api.abortRequest(handle) - var cancel = f.api.backend.testCalls.slice(-1)[0] + compare(scenario.api.inFlight, 1) + scenario.api.abortRequest(handle) + var cancel = scenario.api.backend.testCalls.slice(-1)[0] compare(cancel.method, "jmap.cancel") compare(cancel.params.requestId, request.params.requestId) - f.api.abortRequest(handle) - compare(f.api.backend.testCalls.slice(-1)[0], cancel) - Transports.complete(request, {id:"m" + i}, {session:{state:"stale"},mailboxes:[]}) - compare(f.api.inFlight, 0) + scenario.api.abortRequest(handle) + compare(scenario.api.backend.testCalls.slice(-1)[0], cancel) + Transports.complete(request, {id:"m" + itemIndex}, {session:{state:"stale"},mailboxes:[]}) + compare(scenario.api.inFlight, 0) compare(called, 0) - compare(f.api.session, null) + compare(scenario.api.session, null) } - var before = Transports.transports(f.api) - f.api.getMessage("next", true, function(result,error) { compare(error, ""); called++ }) - Transports.complete(Transports.newSince(f.api,before)[0], {id:"next"}) + var before = Transports.transports(scenario.api) + scenario.api.getMessage("next", true, function(result,error) { compare(error, ""); called++ }) + Transports.complete(Transports.newSince(scenario.api,before)[0], {id:"next"}) compare(called, 1) - compare(f.api.inFlight, 0) + compare(scenario.api.inFlight, 0) } function test_server_change_ignores_pending_result_and_completes_busy_accounting() { - var f = setup() + var scenario = setup() var called = false - f.api.getLabels(function() { called = true }) - var request = Transports.transports(f.api)[0] - f.api.forgetServer() + scenario.api.getLabels(function() { called = true }) + var request = Transports.transports(scenario.api)[0] + scenario.api.forgetServer() Transports.complete(request, [], {session:{state:"old"},mailboxes:[{id:"old"}]}) compare(called, false) - compare(f.api.session, null) - compare(f.api.mailboxList.length, 0) - compare(f.api.inFlight, 0) + compare(scenario.api.session, null) + compare(scenario.api.mailboxList.length, 0) + compare(scenario.api.inFlight, 0) } function test_attachment_callback_receives_the_base64_string_not_the_wire_object() { - var f = setup() + var scenario = setup() var got = [] - var before = Transports.transports(f.api) - f.api.getAttachment("m1", "blob1", function(data, error) { got.push([data, error]) }) - var request = Transports.newSince(f.api, before)[0] + var before = Transports.transports(scenario.api) + scenario.api.getAttachment("m1", "blob1", function(data, error) { got.push([data, error]) }) + var request = Transports.newSince(scenario.api, before)[0] compare(request.method, "jmap.attachment") Transports.complete(request, {data: "aGk", size: 2}) compare(got.length, 1) compare(got[0][0], "aGk") compare(got[0][1], "") - before = Transports.transports(f.api) - f.api.getAttachment("m1", "blob2", function(data, error) { got.push([data, error]) }) - Transports.reply(Transports.newSince(f.api, before)[0], null, {message: "attachment_data_invalid"}) + before = Transports.transports(scenario.api) + scenario.api.getAttachment("m1", "blob2", function(data, error) { got.push([data, error]) }) + Transports.reply(Transports.newSince(scenario.api, before)[0], null, {message: "attachment_data_invalid"}) compare(got.length, 2) compare(got[1][0], "") verify(got[1][1] !== "") diff --git a/ui/tests/qml/tst_jmap_scheme_detection.qml b/ui/tests/qml/tst_jmap_scheme_detection.qml index e840821f9..566ad0593 100644 --- a/ui/tests/qml/tst_jmap_scheme_detection.qml +++ b/ui/tests/qml/tst_jmap_scheme_detection.qml @@ -84,8 +84,6 @@ Item { sessionState: "s0" }) - - function test_a_recorded_scheme_is_tried_first_and_only_the_last_refusal_counts() { verify(!!tokenAccount.auth && !!tokenAccount.api) tokenAccount.auth.secret = "old-token" diff --git a/ui/tests/qml/tst_jmap_session_state.qml b/ui/tests/qml/tst_jmap_session_state.qml index bc948fae9..1f61d8c98 100644 --- a/ui/tests/qml/tst_jmap_session_state.qml +++ b/ui/tests/qml/tst_jmap_session_state.qml @@ -3,20 +3,8 @@ import QtTest 1.3 import "transports.js" as Transports import "../../account" as Account -// A reply that names a newer session state has the session fetched again. -// -// Every API reply carries `sessionState`, and one that differs from the held -// session's is the server saying its URLs, its limits or its accounts changed -// without moving. The client held the session from sign-in or from the cache -// and noticed a change only when a request came back 404; a server that kept -// its API URL and changed a limit was never re-read. One reply naming a new -// state now costs one session GET, and the held session is replaced by what it -// answers — not dropped first, so nothing in flight waits on it. -// -// Why Qt rather than node: `Jmap.movedSessionState` is asserted on its own in -// `tests/test_jmap.js`; what has to be seen here is the client acting on it -// from inside `readCall`, once per state, on the real objects with the -// transport stubbed. +// Invariant: Rust returns the authoritative refreshed session. The UI applies its +// changed state and limits without issuing another discovery request. Item { width: 400 height: 300 @@ -78,8 +66,6 @@ Item { }) } - - // Rust refreshes the authoritative session before returning state. The // adapter applies the refreshed limits and never launches a second GET. function countUnder(state) { diff --git a/ui/tests/qml/tst_jmap_sign_in.qml b/ui/tests/qml/tst_jmap_sign_in.qml index c7056628d..117c6a0bf 100644 --- a/ui/tests/qml/tst_jmap_sign_in.qml +++ b/ui/tests/qml/tst_jmap_sign_in.qml @@ -101,8 +101,8 @@ Item { if (!item) return null if (item.objectName === objectName) return item var values = item.children || [] - for (var i = 0; i < values.length; i++) { - var found = named(values[i], objectName) + for (var itemIndex = 0; itemIndex < values.length; itemIndex++) { + var found = named(values[itemIndex], objectName) if (found) return found } return null diff --git a/ui/tests/qml/tst_outlook_graph_consent.qml b/ui/tests/qml/tst_outlook_graph_consent.qml index cd3031dc6..af4fd6b71 100644 --- a/ui/tests/qml/tst_outlook_graph_consent.qml +++ b/ui/tests/qml/tst_outlook_graph_consent.qml @@ -83,13 +83,13 @@ Item { onLoginSucceeded: successes++ onSessionUnavailable: unavailable++ function fields(body) { - var out = {} + var output = {} var pairs = String(body).split("&") - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i].split("=") - out[decodeURIComponent(pair[0])] = decodeURIComponent((pair[1] || "").replace(/\+/g, " ")) + for (var itemIndex = 0; itemIndex < pairs.length; itemIndex++) { + var pair = pairs[itemIndex].split("=") + output[decodeURIComponent(pair[0])] = decodeURIComponent((pair[1] || "").replace(/\+/g, " ")) } - return out + return output } function mailScopes() { return "https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send" } function graphScopes() { @@ -163,9 +163,9 @@ Item { return auth } function grants(auth) { - var out = [] - for (var i = 0; i < auth.requests.length; i++) out.push(auth.requests[i].grant || auth.requests[i].url.replace(/.*\//, "")) - return out + var output = [] + for (var itemIndex = 0; itemIndex < auth.requests.length; itemIndex++) output.push(auth.requests[itemIndex].grant || auth.requests[itemIndex].url.replace(/.*\//, "")) + return output } // The mail half of a sign-in: the code, the token, the mailbox verified. function signInForMail(auth) { @@ -186,17 +186,17 @@ Item { // The newest live request is the one just made by this action; a fresh // object's cancelled restore remains in the fake only to exercise stale // callback handling. - for (var i = credentialPlatform.lookups.length - 1; i >= 0; i--) - if (credentialPlatform.lookups[i].running) return credentialPlatform.lookups[i] + for (var itemIndex = credentialPlatform.lookups.length - 1; itemIndex >= 0; itemIndex--) + if (credentialPlatform.lookups[itemIndex].running) return credentialPlatform.lookups[itemIndex] fail("No pending credential lookup") } function storedSecrets(auth) { - var out = [] - for (var i = 0; i < credentialPlatform.writes.length; i++) - if (credentialPlatform.writes[i].secret !== "") out.push(credentialPlatform.writes[i].secret) - for (var j = 0; j < auth.keyringJobs.length; j++) - if (auth.keyringJobs[j].token !== "") out.push(auth.keyringJobs[j].token) - return out + var output = [] + for (var itemIndex = 0; itemIndex < credentialPlatform.writes.length; itemIndex++) + if (credentialPlatform.writes[itemIndex].secret !== "") output.push(credentialPlatform.writes[itemIndex].secret) + for (var nestedIndex = 0; nestedIndex < auth.keyringJobs.length; nestedIndex++) + if (auth.keyringJobs[nestedIndex].token !== "") output.push(auth.keyringJobs[nestedIndex].token) + return output } function test_a_mailbox_that_sends_by_smtp_signs_in_with_one_code() { diff --git a/ui/tests/qml/tst_outlook_security.qml b/ui/tests/qml/tst_outlook_security.qml index 251d35762..406befd8a 100644 --- a/ui/tests/qml/tst_outlook_security.qml +++ b/ui/tests/qml/tst_outlook_security.qml @@ -82,8 +82,8 @@ Item { return auth } function lookupProcess(auth) { - for (var i = credentialPlatform.lookups.length - 1; i >= 0; i--) - if (credentialPlatform.lookups[i].running) return credentialPlatform.lookups[i] + for (var itemIndex = credentialPlatform.lookups.length - 1; itemIndex >= 0; itemIndex--) + if (credentialPlatform.lookups[itemIndex].running) return credentialPlatform.lookups[itemIndex] fail("No pending keyring lookup") } function deliverLookup(auth) { @@ -92,8 +92,8 @@ Item { process.exited(0) } function finishJob(auth) { - for (var i = 0; i < credentialPlatform.writes.length; i++) { - var child = credentialPlatform.writes[i] + for (var itemIndex = 0; itemIndex < credentialPlatform.writes.length; itemIndex++) { + var child = credentialPlatform.writes[itemIndex] if (child.running) { var command = child.command.slice() child.started() @@ -146,8 +146,8 @@ Item { auth.accountId = "outlook:bob@hotmail.com" auth.configuredEmail = "bob@hotmail.com" auth.logout() - for (var i = 0; i < credentialPlatform.writes.length; i++) { - var child = credentialPlatform.writes[i] + for (var itemIndex = 0; itemIndex < credentialPlatform.writes.length; itemIndex++) { + var child = credentialPlatform.writes[itemIndex] if (child.running && child.action === "clear") { compare(child.command[child.command.length - 1], "outlook:bob@hotmail.com", "Sign-out must clear Bob's token, not Alice's previous lookup key") @@ -168,7 +168,7 @@ Item { function test_empty_lookup_completes_all_waiting_requests() { var auth = startLookup() var calls = 0 - for (var i = 0; i < 2; i++) auth.withCredentials(function(token, error) { + for (var itemIndex = 0; itemIndex < 2; itemIndex++) auth.withCredentials(function(token, error) { compare(token, "") verify(error !== "") calls++ From 3e8ad12507c755026ae134f7f1f178bee20d7d3e Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:17:18 +0100 Subject: [PATCH 115/568] Fix credential waiters invalidating later login callbacks --- ui/providers/ImapAuth.qml | 7 +++++-- ui/providers/JmapAuth.qml | 7 +++++-- ui/tests/qml/tst_password_sign_in_lifecycle.qml | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/ui/providers/ImapAuth.qml b/ui/providers/ImapAuth.qml index dbfb4d111..0d4066753 100644 --- a/ui/providers/ImapAuth.qml +++ b/ui/providers/ImapAuth.qml @@ -61,10 +61,12 @@ Item { } function finishWaiters(value, error) { + var context = { account: accountId, generation: sessionGeneration } var pending = credentialWaiters.slice() credentialWaiters = [] for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { - try { pending[itemIndex](value || "", safeError(error)) } + var current = context.account === accountId && context.generation === sessionGeneration + try { pending[itemIndex](current ? value : "", current ? safeError(error) : "The mailbox changed during this request") } catch (error) { /* Invariant: one consumer must not prevent later waiters from completing. */ } } } @@ -139,8 +141,9 @@ Item { return } password = value + var generation = sessionGeneration finishWaiters(settings.username + ":" + password, "") - loginSucceeded() + if (generation === sessionGeneration && loggedIn) loginSucceeded() } /** Called by the setup page once the user has filled the form in. The password diff --git a/ui/providers/JmapAuth.qml b/ui/providers/JmapAuth.qml index edf4de5d2..964a8d5ce 100644 --- a/ui/providers/JmapAuth.qml +++ b/ui/providers/JmapAuth.qml @@ -92,10 +92,12 @@ Item { } function finishWaiters(value, error) { + var context = { account: accountId, generation: sessionGeneration } var pending = credentialWaiters.slice() credentialWaiters = [] for (var itemIndex = 0; itemIndex < pending.length; itemIndex++) { - try { pending[itemIndex](value, safeError(error)) } + var current = context.account === accountId && context.generation === sessionGeneration + try { pending[itemIndex](current ? value : null, current ? safeError(error) : "The mailbox changed during this request") } catch (error) { /* Invariant: one consumer must not prevent later waiters from completing. */ } } } @@ -168,8 +170,9 @@ Item { return } secret = value + var generation = sessionGeneration finishWaiters(credential(), "") - loginSucceeded() + if (generation === sessionGeneration && loggedIn) loginSucceeded() } /** Called by the setup page once the form is filled in. The secret is diff --git a/ui/tests/qml/tst_password_sign_in_lifecycle.qml b/ui/tests/qml/tst_password_sign_in_lifecycle.qml index 258972d2a..1793bef1a 100644 --- a/ui/tests/qml/tst_password_sign_in_lifecycle.qml +++ b/ui/tests/qml/tst_password_sign_in_lifecycle.qml @@ -112,6 +112,22 @@ Item { compare(successes, 0) compare(objects.auth.sessionBusy, false) } + function test_waiter_logout_blocks_later_secret_delivery_data() { return providers() } + function test_waiter_logout_blocks_later_secret_delivery(data) { + var objects = pair(data.protocol) + var successes = 0 + var second = null + objects.auth.loginSucceeded.connect(function() { successes++ }) + objects.auth.withCredentials(function() { objects.auth.logout() }) + objects.auth.withCredentials(function(value, error) { second = { value: value, error: error } }) + credentials.lookups[0]("old-account-secret", "") + verify(second !== null) + verify(!second.value, "no secret is delivered after an earlier waiter signs out") + verify(second.error !== "") + compare(objects.auth.loggedIn, false) + compare(successes, 0, "a keyring completion must not announce sign-in after a waiter signs out") + compare(credentials.writes.length, 0) + } function test_busy_sign_in_cannot_replace_the_pending_secret_data() { return providers() } function test_busy_sign_in_cannot_replace_the_pending_secret(data) { var objects = pair(data.protocol) From 7a0c0c954198c1cbbccfcc0755ee9183324bd5b4 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 116/568] Fix recovered attachment imports and send readiness --- ui/components/ComposeView.qml | 16 +- .../qml/tst_compose_attachment_recovery.qml | 138 ++++++++++++++++++ 2 files changed, 149 insertions(+), 5 deletions(-) create mode 100644 ui/tests/qml/tst_compose_attachment_recovery.qml diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 4f9ac61af..a78721532 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -116,8 +116,12 @@ DropArea { if (mode !== "reply" && mode !== "replyAll") return "" return Agent.replyOnly(bodyEdit.text, bodyQuote) !== bodyEdit.text ? bodyQuote : "" } + readonly property bool attachmentsReady: !forwardAttachmentsLoading + && forwardAttachmentError === "" && !attachmentHostPending + && !attachmentReadPending && attachJobs.length === 0 + function outgoingEnvelope() { - if (forwardAttachmentsLoading || forwardAttachmentError !== "" || attachmentHostPending || attachmentReadPending || attachJobs.length > 0) return null + if (!attachmentsReady) return null return {accountId: accountId, draftKey: draftKey, from: fromEmail, to: toField.text, cc: ccField.text, bcc: bccField.text, replyTo: replyToField.text, subject: subjectField.text, body: bodyEdit.text, @@ -436,7 +440,8 @@ DropArea { var recover = [] for (var i = 0; i < listed.length; i++) { var file = listed[i] || ({}) - if (String(file.path || "") !== "" && String(file.data || "") === "") + if (String(file.path || "") !== "" && String(file.data || "") === "" + && String(file.handle || "") === "") recover.push(file) else kept.push(file) } @@ -918,7 +923,7 @@ DropArea { // also covers the calendar event form — a composer that is not open must // not answer it, or a draft parked for the undo window would send twice. if (!opened || !service) return - if (forwardAttachmentsLoading || forwardAttachmentError !== "") return + if (!attachmentsReady) return var accepted = service.send(({ // The mailbox this draft belongs to, named rather than inferred. Without // it the service fell back to matching `from` against each account in @@ -994,7 +999,8 @@ DropArea { var rest = root.attachJobs.slice(1) root.attachJobs = rest root.attaching = true - if (job.mode === "read" || job.mode === "forget") { + if (job.mode === "read" || job.mode === "recover" || job.mode === "recover-owned" + || job.mode === "forget") { if (!root.service || !root.service.backend || !root.service.backend.ready) { finishAttach(job.mode, JSON.stringify({ ok: false, error: "Mail backend unavailable" }), owner) return @@ -2069,7 +2075,7 @@ DropArea { foreground: root.textColor fontFamily: root.panelFontFamily enabled: !!root.service - && !root.forwardAttachmentsLoading && root.forwardAttachmentError === "" + && root.attachmentsReady onClicked: root.submit() } diff --git a/ui/tests/qml/tst_compose_attachment_recovery.qml b/ui/tests/qml/tst_compose_attachment_recovery.qml new file mode 100644 index 000000000..cb9f54b0d --- /dev/null +++ b/ui/tests/qml/tst_compose_attachment_recovery.qml @@ -0,0 +1,138 @@ +import QtQuick +import QtTest +import "../../components" as Omamail + +Item { + width: 900 + height: 600 + + QtObject { + id: backend + property bool ready: true + property int apiVersion: 8 + property var pending: [] + property var calls: [] + function call(method, parameters, callback) { + if (method === "message.composeText") { + callback({body: "", quote: ""}, null) + return + } + calls = calls.concat([{method: method, parameters: parameters}]) + if (method === "attachment.forget") { + callback({ok: true}, null) + return + } + pending = pending.concat([{callback: callback, parameters: parameters}]) + } + function finish() { + var request = pending[0] + pending = pending.slice(1) + request.callback({ok: true, filename: "notes.txt", mimeType: "text/plain", + size: 4, data: "dGVzdA==", path: request.parameters.path, handle: "retained-file"}, null) + } + } + + QtObject { + id: mail + property var backend: backend + property string composeAccountId: "writer@example.test" + property string activeAccountId: composeAccountId + property var recipientContacts: [] + property var sendAsAliases: [] + property var sendIdentities: [] + property var senderSources: [] + property var sent: [] + property var errors: [] + function signatureFor(account) { return "" } + function preferredSendAs(recipients) { return {email: composeAccountId} } + function refreshRecipientContacts() {} + function findAccount(account) { return {providerId: "gmail"} } + function fail(message) { errors = errors.concat([message]) } + function send(fields) { sent = sent.concat([fields]); return "send-1" } + } + + Omamail.ComposeView { + id: compose + anchors.fill: parent + service: mail + textColor: "#eeeeee" + backgroundColor: "#222222" + accentColor: "#e9a35f" + dimColor: "#aaaaaa" + dimmerColor: "#888888" + popupBackgroundColor: "#333333" + popupBorderColor: "#777777" + panelFontFamily: "monospace" + } + + TestCase { + name: "ComposeAttachmentRecovery" + when: windowShown + function init() { + backend.pending = [] + backend.calls = [] + compose.attachmentReadPending = false + compose.attachmentHostPending = false + compose.reset() + mail.sent = [] + mail.errors = [] + backend.calls = [] + compose.begin("new", null, "", []) + } + function test_restored_files_are_imported_for_the_owning_draft_data() { + return [{tag: "borrowed", owned: false}, {tag: "owned", owned: true}] + } + function test_restored_files_are_imported_for_the_owning_draft(data) { + compose.restoreDraft({accountId: mail.composeAccountId, draftKey: "recovered-draft", + draftAttachments: [{path: "/synthetic/notes.txt", owned: data.owned}]}) + compare(backend.calls.length, 1) + compare(backend.calls[0].method, "attachment.import") + compare(backend.calls[0].parameters.accountId, mail.composeAccountId) + compare(backend.calls[0].parameters.draftKey, "recovered-draft") + backend.finish() + compare(compose.draftAttachments.length, 1) + compare(compose.draftAttachments[0].owned, data.owned) + compare(mail.errors.length, 0) + } + function test_retained_attachment_handles_do_not_reread_the_original_file() { + compose.restoreDraft({accountId: mail.composeAccountId, draftKey: "recovered-draft", + draftAttachments: [{path: "/removed/original.txt", handle: "retained-file", owned: false}]}) + compare(backend.calls.length, 0) + compare(compose.draftAttachments.length, 1) + compare(compose.draftAttachments[0].handle, "retained-file") + compare(mail.errors.length, 0) + } + function test_submit_waits_for_attachment_import() { + compose.enqueueAttach("read", "/synthetic/notes.txt") + compare(backend.pending.length, 1) + compose.submit() + compare(mail.sent.length, 0, "Send must not dispatch while the attachment is absent") + verify(compose.opened) + backend.finish() + compose.submit() + compare(mail.sent.length, 1) + compare(mail.sent[0].attachments.length, 1) + } + function test_send_click_waits_for_import() { + compose.enqueueAttach("read", "/synthetic/notes.txt") + var button = findChild(compose, "compose-send-button") + verify(button) + mouseClick(button, button.width / 2, button.height / 2) + compare(mail.sent.length, 0) + backend.finish() + mouseClick(button, button.width / 2, button.height / 2) + compare(mail.sent.length, 1) + compare(mail.sent[0].attachments.length, 1) + } + function test_submit_waits_for_host_picker() { + compose.attachmentHostPending = true + compose.submit() + compare(mail.sent.length, 0) + } + function test_submit_waits_for_queued_attachment() { + compose.attachJobs = [{mode: "read", path: "/synthetic/notes.txt"}] + compose.submit() + compare(mail.sent.length, 0) + } + } +} From 467f26ad6ae450319c833bb2da59406a4624f81c Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 117/568] Pass menu rows directly to navigation rules --- ui/components/AddressMenu.qml | 11 ++--------- ui/components/AppMenu.qml | 9 +-------- ui/components/LabelMenu.qml | 11 ++--------- ui/components/MessageMenu.qml | 11 ++--------- ui/components/SubjectMenu.qml | 11 ++--------- ui/components/TextMenu.qml | 11 ++--------- 6 files changed, 11 insertions(+), 53 deletions(-) diff --git a/ui/components/AddressMenu.qml b/ui/components/AddressMenu.qml index fecf440e7..7538b8016 100644 --- a/ui/components/AddressMenu.qml +++ b/ui/components/AddressMenu.qml @@ -62,14 +62,7 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } - function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) } + function moveCursor(step) { cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) } function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } @@ -89,7 +82,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - root.cursorIndex = Menu.firstSelectable(root.selectableRows()) + root.cursorIndex = Menu.firstSelectable(root.menuRows) root.place() } background: Rectangle { diff --git a/ui/components/AppMenu.qml b/ui/components/AppMenu.qml index ba1e62b49..fce783038 100644 --- a/ui/components/AppMenu.qml +++ b/ui/components/AppMenu.qml @@ -70,15 +70,8 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } function moveCursor(step) { - cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) + cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) if (cursorIndex < 0) return var row = menuRows[cursorIndex] if (row.y < menuScroll.contentY) menuScroll.contentY = row.y diff --git a/ui/components/LabelMenu.qml b/ui/components/LabelMenu.qml index 2e2acd05e..bc66537d9 100644 --- a/ui/components/LabelMenu.qml +++ b/ui/components/LabelMenu.qml @@ -62,14 +62,7 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } - function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) } + function moveCursor(step) { cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) } function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } @@ -85,7 +78,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - root.cursorIndex = Menu.firstSelectable(root.selectableRows()) + root.cursorIndex = Menu.firstSelectable(root.menuRows) root.place() } background: Rectangle { diff --git a/ui/components/MessageMenu.qml b/ui/components/MessageMenu.qml index 8103ee6d9..636940113 100644 --- a/ui/components/MessageMenu.qml +++ b/ui/components/MessageMenu.qml @@ -109,14 +109,7 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } - function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) } + function moveCursor(step) { cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) } function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } @@ -147,7 +140,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - root.cursorIndex = Menu.firstSelectable(root.selectableRows()) + root.cursorIndex = Menu.firstSelectable(root.menuRows) root.place() } background: Rectangle { diff --git a/ui/components/SubjectMenu.qml b/ui/components/SubjectMenu.qml index abdad2ca6..066f7d224 100644 --- a/ui/components/SubjectMenu.qml +++ b/ui/components/SubjectMenu.qml @@ -55,14 +55,7 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } - function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) } + function moveCursor(step) { cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) } function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } @@ -76,7 +69,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - root.cursorIndex = Menu.firstSelectable(root.selectableRows()) + root.cursorIndex = Menu.firstSelectable(root.menuRows) root.place() } background: Rectangle { diff --git a/ui/components/TextMenu.qml b/ui/components/TextMenu.qml index 9a93a9bc5..ecdb2771e 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -69,14 +69,7 @@ Item { menu.y = placed.y } - function selectableRows() { - var values = [] - for (var i = 0; i < menuRows.length; i++) values.push({ - selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled - }) - return values - } - function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) } + function moveCursor(step) { cursorIndex = Menu.nextSelectable(menuRows, cursorIndex, step) } function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } @@ -107,7 +100,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - root.cursorIndex = Menu.firstSelectable(root.selectableRows()) + root.cursorIndex = Menu.firstSelectable(root.menuRows) root.place() } background: Rectangle { From 2b37a311c08f759e749783955ea90f52fef0c04e Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 118/568] Fix reader image completion after selection changes --- ui/components/MessageReader.qml | 17 +- ui/tests/qml/tst_reader_image_lifecycle.qml | 182 ++++++++++++++++++++ 2 files changed, 196 insertions(+), 3 deletions(-) create mode 100644 ui/tests/qml/tst_reader_image_lifecycle.qml diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml index 645aeb976..89071b5e6 100644 --- a/ui/components/MessageReader.qml +++ b/ui/components/MessageReader.qml @@ -101,7 +101,18 @@ Item { root.service.openExternal(opened) } + property int imageRequestSerial: 0 + readonly property var imageOwner: service ? service.reading : null + onImageOwnerChanged: resetImageMarker() + onVisibleChanged: if (!visible) resetImageMarker() + + function resetImageMarker() { + imageRequestSerial++ + imagePopover.close() + } + function openImageMarker(source) { + var requestSerial = ++imageRequestSerial var wanted = String(source || "") if (Html.isRasterDataImage(wanted)) { imagePopover.show(wanted) @@ -112,7 +123,7 @@ Item { return } root.service.fetchDisplayImage(wanted, function(data) { - if (!root) return + if (!root || requestSerial !== root.imageRequestSerial) return imagePopover.showPrepared(wanted, data) }) } @@ -142,8 +153,8 @@ Item { property int attachmentPreviewSerial: 0 property bool attachmentPreviewBusy: false property int attachmentPreviewBytes: 0 - onSelectedIdChanged: resetAttachments() - onServiceChanged: resetAttachments() + onSelectedIdChanged: { resetAttachments(); resetImageMarker() } + onServiceChanged: { resetAttachments(); resetImageMarker() } onAttachmentsChanged: resetAttachments() function resetAttachments() { diff --git a/ui/tests/qml/tst_reader_image_lifecycle.qml b/ui/tests/qml/tst_reader_image_lifecycle.qml new file mode 100644 index 000000000..92b3a9016 --- /dev/null +++ b/ui/tests/qml/tst_reader_image_lifecycle.qml @@ -0,0 +1,182 @@ +import "../../settings" +import QtQuick 2.15 +import QtTest 1.3 +import qs.Commons +import "../../components" as Omamail +import "../../message/Html.js" as Html + +// Three ways of reading one message, and the two things that must stay true +// while moving between them: nothing is asked of the network, and the message +// on screen is still the message that was open. +// +// The reading column is here too, because how wide it is and where it sits are +// decided against a font Qt measures — which is the half of that decision no +// node test can make. +Item { + width: MailStyle.space(900) + height: 600 + + readonly property string senderHtml: '' + + '' + + '
' + + 'Activity on Sprint board
Person 1 moved 4 cards. ' + + 'Open the board
' + + readonly property var rendered: Html.sanitize(senderHtml, ({ withReader: true })) + + QtObject { + id: mailService + + // Every trip to the network a body could cause. Reading mode is built + // beside the other two off one parse, so choosing between them must move + // none of these. + property var reading: ({accountId: "account-a"}) + property var callbacks: [] + function fetchDisplayImage(source, callback) { callbacks = callbacks.concat([{source: source, done: callback}]) } + property int fetches: 0 + property int renders: 0 + + property string selectedId: "message-9" + property var selectedMessage: ({ + id: "message-9", + subject: "Activity on Sprint board", + from: ({ display: "Boards", email: "boards@example.com" }), + to: [({ display: "Reader", email: "reader@example.com" })], + fullTime: "24 August 2026", + starred: false + }) + property bool detailLoading: false + property bool detailPainted: true + property bool selectedHasHtml: rendered.html !== "" + property var selectedDocument: rendered.document + property var selectedReaderDocument: rendered.reader.document + property bool selectedReaderTooHeavy: rendered.reader.tooHeavy + property bool selectedReaderEmpty: rendered.reader.empty + property int selectedRemoteImages: rendered.remoteImages + property bool remoteImagesAllowed: false + property bool selectedTooHeavy: rendered.tooHeavy + property string unsubscribeLabel: "" + property string unsubscribeDetail: "" + property bool unsubscribing: false + property var selectedBody: ({ text: "[image 1]", source: "html" }) + property var selectedImages: ["https://images.example.com/first.png"] + property var selectedInvite: null + property string selectedResponse: "" + property bool canRespondToInvite: false + property bool rsvpSending: false + property bool canArchive: true + property bool canOpenOnWeb: false + property var selectedAttachments: [] + + function getMessage() { fetches++ } + function showRemoteImages() { renders++ } + } + + Omamail.MessageReader { + id: reader + // Sized rather than anchored: the panel's width is what these tests move. + width: MailStyle.space(900) + height: 600 + service: mailService + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + linkColor: Qt.rgba(0.3, 0.7, 1, 1) + dimColor: Qt.rgba(0.67, 0.67, 0.67, 1) + popupBackgroundColor: Qt.rgba(0.13, 0.13, 0.13, 1) + popupBorderColor: Qt.rgba(0.47, 0.47, 0.47, 1) + leadingBoundaryOverlap: 0 + dimmerColor: Qt.rgba(0.47, 0.47, 0.47, 1) + panelFontFamily: "monospace" + bodyMode: "plain" + onBodyModeRequested: function(mode) { reader.bodyMode = mode } + } + + TestCase { + name: "ReaderImageLifecycle" + when: windowShown + + readonly property string raster: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + + function childOfType(item, type) { + if (item.toString().indexOf(type) === 0) return item + var children = item.children || [] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + var found = childOfType(children[childIndex], type) + if (found) return found + } + return null + } + + function popover() { return childOfType(reader, "ImagePopover") } + + function init() { + popover().close() + wait(1) + mailService.selectedId = "message-9" + mailService.reading = ({accountId: "account-a"}) + mailService.callbacks = [] + reader.visible = true + } + + function cleanup() { popover().close(); wait(1) } + + function test_old_account_cannot_open_image() { + reader.openImageMarker("https://images.example.com/first.png") + mailService.reading = ({accountId: "account-b"}) + mailService.callbacks[0].done(raster) + compare(popover().requested, "") + compare(popover().source, "") + } + + function test_old_message_cannot_open_image() { + reader.openImageMarker("https://images.example.com/first.png") + mailService.selectedId = "message-10" + mailService.callbacks[0].done(raster) + compare(popover().requested, "") + compare(popover().source, "") + } + + function test_latest_image_request_wins() { + reader.openImageMarker("https://images.example.com/first.png") + reader.openImageMarker("https://images.example.com/second.png") + mailService.callbacks[1].done(raster) + mailService.callbacks[0].done(raster) + compare(popover().requested, "https://images.example.com/second.png") + } + + function test_account_change_closes_prepared_image() { + reader.openImageMarker(raster) + verify(popover().source !== "") + mailService.reading = ({accountId: "account-b"}) + tryCompare(popover(), "source", "") + } + + function test_hidden_reader_cannot_open_image() { + reader.openImageMarker("https://images.example.com/first.png") + reader.visible = false + mailService.callbacks[0].done(raster) + compare(popover().requested, "") + } + + function test_click_image_marker_opens_prepared_bytes() { + var body = childOfType(reader, "QQuickTextEdit") + verify(body) + var position = null + for (var y = 1; y < body.height && !position; y += 3) { + for (var x = 1; x < body.width; x += 3) { + if (body.linkAt(x, y) === "omarchy-image:1") { position = {x: x, y: y}; break } + } + } + verify(position, "The plain message contains a clickable image marker") + var character = body.positionToRectangle(4) + mouseClick(body, character.x + 2, character.y + character.height / 2) + compare(mailService.callbacks.length, 1) + compare(popover().source, "") + mailService.callbacks[0].done(raster) + compare(popover().requested, "https://images.example.com/first.png") + compare(popover().source, raster) + } + } +} From 8eb5fca1b3188769ff72578f85c48982c8cb2cd9 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 119/568] Fix calendar day highlight after midnight --- ui/components/CalendarView.qml | 4 ++-- ui/tests/qml/tst_calendar_detail_refresh.qml | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index 22a9aceae..5a3310f57 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -104,7 +104,7 @@ Item { readonly property var monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] readonly property var weekdayNames: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] - readonly property string todayIso: Calendar.isoDate(new Date()) + readonly property string todayIso: Calendar.isoDate(new Date(controller ? controller.nowMs : Date.now())) readonly property var viewOptions: ["Day", "Week", "Month", "Agenda"].map(function(label) { var binding = Keymap.bindingsFor("calendar").filter(function(row) { return row.id === "calendar" + label })[0] return { mode: label.toLowerCase(), label: label + " (" + Keymap.displayFor(binding) + ")" } @@ -118,7 +118,7 @@ Item { Binding { target: root.controller property: "clockRunning" - value: root.visible && root.viewMode !== "month" + value: root.visible when: root.controller !== null } diff --git a/ui/tests/qml/tst_calendar_detail_refresh.qml b/ui/tests/qml/tst_calendar_detail_refresh.qml index 39f2a1c3b..fb03d3925 100644 --- a/ui/tests/qml/tst_calendar_detail_refresh.qml +++ b/ui/tests/qml/tst_calendar_detail_refresh.qml @@ -91,6 +91,19 @@ Item { reply(0,"first",2) compare(view.detailOpen,false) } + function test_month_today_follows_the_running_clock() { + view.setView("month") + verify(fixture.clockRunning, "A visible month keeps the current-date clock running") + fixture.nowMs = new Date(2026, 9, 20, 23, 59).getTime() + compare(view.todayIso, "2026-10-20") + fixture.nowMs = new Date(2026, 9, 21, 0, 0).getTime() + compare(view.todayIso, "2026-10-21") + view.visible = false + compare(fixture.clockRunning, false) + view.visible = true + fixture.nowMs = Date.now() + } + function test_agenda_model_survives_a_clock_tick() { view.visibleMonth = new Date(2026,9,1) fixture.nowMs = Date.UTC(2026,9,20) From 7f2c474332820f45643906520be118b62d41fb3b Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 120/568] Fix rich-text interpretation of runtime and search labels --- ui/components/BackendSetup.qml | 3 +++ ui/components/ReaderBlankSlate.qml | 2 ++ ui/tests/qml/tst_backend_setup.qml | 33 +++++++++++++++++++++++++ ui/tests/qml/tst_reader_blank_slate.qml | 20 +++++++++++++++ 4 files changed, 58 insertions(+) diff --git a/ui/components/BackendSetup.qml b/ui/components/BackendSetup.qml index 42370797a..bee744073 100644 --- a/ui/components/BackendSetup.qml +++ b/ui/components/BackendSetup.qml @@ -35,6 +35,7 @@ Column { spacing: MailStyle.space(8) Text { id: versionLabel + textFormat: Text.PlainText objectName: "backend-version-label" width: Math.min(implicitWidth, Math.max(0, parent.width - checkButton.width - parent.spacing)) y: (parent.height - height) / 2 @@ -67,6 +68,7 @@ Column { Text { width: parent.width wrapMode: Text.WordWrap + textFormat: Text.PlainText text: root.runtime && root.runtime.bundled ? "Included with this app. Reinstall this version if the bundled backend is missing or damaged." : root.runtime && root.runtime.development @@ -79,6 +81,7 @@ Column { Text { width: parent.width visible: text !== "" + textFormat: Text.PlainText wrapMode: Text.WordWrap text: root.runtime && root.runtime.error ? root.runtime.error : root.backendError color: root.textColor diff --git a/ui/components/ReaderBlankSlate.qml b/ui/components/ReaderBlankSlate.qml index 055f6b37b..731b6c759 100644 --- a/ui/components/ReaderBlankSlate.qml +++ b/ui/components/ReaderBlankSlate.qml @@ -75,6 +75,7 @@ Item { text: root.searching && root.service ? "\"" + Model.truncate(root.service.searchQuery, 36) + "\"" : root.mailboxName + textFormat: Text.PlainText color: root.textColor font.family: root.panelFontFamily font.pixelSize: MailStyle.subtitle @@ -172,6 +173,7 @@ Item { horizontalAlignment: Text.AlignHCenter visible: root.showVersion text: root.versionText + textFormat: Text.PlainText color: root.dimmerColor font.family: root.panelFontFamily font.pixelSize: MailStyle.caption diff --git a/ui/tests/qml/tst_backend_setup.qml b/ui/tests/qml/tst_backend_setup.qml index 663d38e08..c6cd7c1ba 100644 --- a/ui/tests/qml/tst_backend_setup.qml +++ b/ui/tests/qml/tst_backend_setup.qml @@ -11,6 +11,7 @@ Item { property string installedVersion: "0.9.0" property string requiredVersion: "0.9.0" property string error: "" + property string developmentExecutable: "" property bool development: false property bool busy: false property bool canInstall: false @@ -50,12 +51,44 @@ Item { runtime.state = "ready" } function init() { + runtime.error = "" + runtime.installedVersion = "0.9.0" + runtime.developmentExecutable = "" + runtime.development = false runtime.cliInstalled=false runtime.installs=0 runtime.busy=false page.visible=true wait(0) } + function renderedText(item, value) { + if (item.text !== undefined && item.text === value && item.textFormat !== undefined) return item + var children = item.children || [] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + var match = renderedText(children[childIndex], value) + if (match) return match + } + return null + } + function test_runtime_values_are_literal_text_data() { + return [{tag: "error", field: "error"}, {tag: "version", field: "installedVersion"}, + {tag: "development-path", field: "developmentExecutable"}] + } + function test_runtime_values_are_literal_text(data) { + var markup = 'runtime' + var original = runtime[data.field] + runtime[data.field] = markup + runtime.development = data.field === "developmentExecutable" + var expected = data.field === "error" ? markup + : data.field === "installedVersion" ? "Backend " + markup + " is installed." + : "Development executable: " + markup + ". Build the required version, then check again." + var label = renderedText(page, expected) + verify(label) + compare(label.textFormat, Text.PlainText) + for (var x = 1; x < label.width; x += 3) compare(label.linkAt(x, label.height / 2), "") + runtime[data.field] = original + runtime.development = false + } function test_check_is_ghost_beside_version() { var check=findChild(page,"backend-refresh") var version=findChild(page,"backend-version-label") diff --git a/ui/tests/qml/tst_reader_blank_slate.qml b/ui/tests/qml/tst_reader_blank_slate.qml index 212ed8411..f2033e54d 100644 --- a/ui/tests/qml/tst_reader_blank_slate.qml +++ b/ui/tests/qml/tst_reader_blank_slate.qml @@ -98,12 +98,32 @@ Item { } function init() { + mailService.searchQuery = "" mailService.pluginName = "Omamail" mailService.version = "0.7.0" blankSlateLoader.width = MailStyle.space(400) blankSlateLoader.height = MailStyle.space(400) } + function textLabel(item, value) { + if (item.text !== undefined && item.text === value && item.textFormat !== undefined) return item + var children = item.children || [] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + var match = textLabel(children[childIndex], value) + if (match) return match + } + return null + } + function test_query_markup_is_literal_text() { + mailService.searchQuery = 'Search terms' + var label = textLabel(slate(), '\"Search terms\"') + verify(label) + compare(label.textFormat, Text.PlainText) + } + function test_manifest_markup_is_literal_text() { + mailService.pluginName = 'Mail' + compare(version().textFormat, Text.PlainText) + } function test_names_the_running_version() { var label = version() compare(label.text, "Omamail 0.7.0") From 19499ae5d27494d38c3a18d9b3ed2c9518ca8b9d Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 121/568] Fix signature import ownership after account changes --- ui/components/SettingsPage.qml | 6 +- ui/tests/qml/tst_settings_name.qml | 1 + .../qml/tst_signature_import_lifecycle.qml | 142 ++++++++++++++++++ 3 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 ui/tests/qml/tst_signature_import_lifecycle.qml diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index d206f3c57..9009c33cf 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -149,6 +149,7 @@ Column { }) } property bool importing: false + property string importingAccountId: "" property string importNote: "" property bool importFailed: false property string importStage: "" @@ -163,7 +164,8 @@ Column { } function importSignature() { - if (importing || !service) return + if (importing || !service || selectedSignatureAccountId === "") return + importingAccountId = selectedSignatureAccountId importing = true importNote = "" importFailed = false @@ -213,7 +215,7 @@ Column { importFailed = true return } - var accountId = selectedSignatureAccountId + var accountId = importingAccountId service.backend.call("message.signatureImport", { kind: kind, data: kind === "html" ? Qt.atob(String(result.data || "")) : String(result.data || "") }, function(imported, error) { diff --git a/ui/tests/qml/tst_settings_name.qml b/ui/tests/qml/tst_settings_name.qml index c045590bf..bedd75475 100644 --- a/ui/tests/qml/tst_settings_name.qml +++ b/ui/tests/qml/tst_settings_name.qml @@ -133,6 +133,7 @@ Item { fakeService.signatureHtml = "" page.selectedSignatureAccountId = "a@example.org" page.importStage = "read" + page.importingAccountId = "a@example.org" page.importing = true page.finishImport(JSON.stringify({ok: true, mimeType: "image/png", data: "iVBORw0KGgoAAA=="})) compare(fakeBackend.method, "message.signatureImport") diff --git a/ui/tests/qml/tst_signature_import_lifecycle.qml b/ui/tests/qml/tst_signature_import_lifecycle.qml new file mode 100644 index 000000000..1ca6c08ad --- /dev/null +++ b/ui/tests/qml/tst_signature_import_lifecycle.qml @@ -0,0 +1,142 @@ +import QtQuick 2.15 +import QtTest 1.3 +import "../../components" as Omamail + +// Naming a mailbox. +// +// The field draws a box whether or not it can be typed into, which is how it +// shipped unusable twice. This types into it the way a person does — a click, +// then keys — rather than assigning `text` from the test, which would pass +// against a field nothing can reach. +Item { + width: 700 + height: 500 + + QtObject { + id: fakeBackend + property bool ready: true + property string method: "" + property var params: null + property var callback: null + function call(method, params, callback) { + fakeBackend.method = method; fakeBackend.params = params; fakeBackend.callback = callback + } + } + QtObject { + id: fakeService + + property string activeAccountId: "a@example.org" + property var accountSummaries: [] + property var accountSignatures: [ + { id: "a@example.org", email: "a@example.org", label: "", signature: "", + provider: "imap", senderName: "" }, + { id: "b@example.net", email: "b@example.net", label: "Work", signature: "", + provider: "gmail", senderName: "" }, + { id: "c@example.com", email: "c@example.com", label: "", signature: "", + provider: "outlook", senderName: "Jane Example" } + ] + property bool backendCanNameSender: true + property int undoSendSeconds: 10 + property bool unifiedCalendarView: false + property bool notifyNewMail: true + property string contentDirection: "auto" + property var auth: null + property var backend: fakeBackend + property var pickerCallback: null + function chooseFiles(callback) { pickerCallback = callback } + property string signatureId: "" + property string signatureHtml: "" + function setAccountSignatureHtml(id, html) { signatureId = id; signatureHtml = html } + + // What the page wrote, and for which mailbox. + property string namedId: "" + property string namedText: "" + property int nameWrites: 0 + + function setAccountLabel(id, text) { + namedId = String(id || "") + namedText = String(text || "") + nameWrites += 1 + } + + property string senderNamedId: "" + property string senderNamedText: "" + property int senderNameWrites: 0 + + function setAccountSenderName(id, text) { + senderNamedId = String(id || "") + senderNamedText = String(text || "") + senderNameWrites += 1 + } + + function setAccountSignature(_id, _text) {} + function setUndoSendSeconds(_value) {} + function setUnifiedCalendarView(_value) {} + function setNotifyNewMail(_value) {} + function setContentDirection(_value) {} + function setAlwaysRenderHeavyMessages(_value) {} + } + + Omamail.SettingsPage { + id: page + width: parent.width + service: fakeService + calendarController: null + textColor: Qt.rgba(0.1, 0.1, 0.1, 1) + dimColor: Qt.rgba(0.45, 0.45, 0.45, 1) + accentColor: Qt.rgba(0.8, 0.4, 0, 1) + urgentColor: Qt.rgba(0.8, 0.1, 0.1, 1) + panelFontFamily: "monospace" + } + + TestCase { + name: "SignatureImportLifecycle" + when: windowShown + function init() { + page.importing = false + page.selectedSignatureAccountId = "a@example.org" + fakeService.signatureId = "" + fakeService.signatureHtml = "" + fakeBackend.callback = null + } + function picked() { fakeService.pickerCallback({ok: true, paths: ["/synthetic/signature.png"]}) } + function read() { fakeBackend.callback({ok: true, mimeType: "image/png", data: "iVBORw0KGgoAAA=="}, null) } + function imported() { fakeBackend.callback({html: "

signature

", plain: "", images: 1, dropped: 0, problem: ""}, null) } + function test_picker_completion_keeps_the_original_account() { + page.importSignature() + page.selectSignatureAccount("b@example.net") + picked() + compare(fakeBackend.method, "attachment.read") + read() + compare(fakeBackend.method, "message.signatureImport") + imported() + compare(fakeService.signatureId, "a@example.org") + compare(page.selectedSignatureAccountId, "b@example.net") + compare(page.importing, false) + } + function test_file_read_completion_keeps_the_original_account() { + page.importSignature() + picked() + page.selectSignatureAccount("b@example.net") + read() + imported() + compare(fakeService.signatureId, "a@example.org") + } + function test_repeated_import_does_not_replace_the_owner() { + page.importSignature() + page.selectSignatureAccount("b@example.net") + page.importSignature() + picked() + read() + imported() + compare(fakeService.signatureId, "a@example.org") + } + function test_cancelled_picker_does_not_write() { + page.importSignature() + fakeService.pickerCallback({ok: false, error: "cancelled"}) + compare(fakeService.signatureId, "") + compare(fakeBackend.callback, null) + compare(page.importing, false) + } + } +} From 03b7e2848f3c28563963566d8972eb467622de72 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 122/568] Fix rich-text interpretation of account setup labels --- ui/components/ImapSetupPage.qml | 1 + ui/components/SetupPage.qml | 3 + ui/tests/qml/tst_setup_plaintext.qml | 89 ++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 ui/tests/qml/tst_setup_plaintext.qml diff --git a/ui/components/ImapSetupPage.qml b/ui/components/ImapSetupPage.qml index da532dd14..4d360d05c 100644 --- a/ui/components/ImapSetupPage.qml +++ b/ui/components/ImapSetupPage.qml @@ -340,6 +340,7 @@ Column { Text { id: errorText objectName: "imap-error" + textFormat: Text.PlainText width: parent.width visible: text !== "" text: "" diff --git a/ui/components/SetupPage.qml b/ui/components/SetupPage.qml index 759713d18..fea01a812 100644 --- a/ui/components/SetupPage.qml +++ b/ui/components/SetupPage.qml @@ -304,6 +304,7 @@ Column { width: parent.width visible: !!root.service && root.service.signInProgress !== "" text: root.service ? root.service.signInProgress : "" + textFormat: Text.PlainText color: root.dimColor font.family: root.panelFontFamily font.pixelSize: MailStyle.caption @@ -381,6 +382,7 @@ Column { Text { width: parent.width visible: root.detailVisible + textFormat: Text.PlainText text: "In Google Cloud, pick or create a project. Under APIs and Services, enable the Gmail API. " + "On the consent screen add the Gmail address you want to read as a test user, then press Publish app. " + "Under Credentials, create an OAuth client with application type Desktop app, and paste its client ID above.\n\n" @@ -464,6 +466,7 @@ Column { Text { width: parent.width text: step.done && step.doneSummary !== "" ? step.doneSummary : step.title + textFormat: Text.PlainText color: step.done ? root.dimColor : root.textColor font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall diff --git a/ui/tests/qml/tst_setup_plaintext.qml b/ui/tests/qml/tst_setup_plaintext.qml new file mode 100644 index 000000000..bc60601d6 --- /dev/null +++ b/ui/tests/qml/tst_setup_plaintext.qml @@ -0,0 +1,89 @@ +import QtQuick +import QtTest +import "../../components" as Views + +Item { + width: 700 + height: 900 + QtObject { + id: auth + property bool loggedIn: false + property bool loginBusy: false + property bool toolsChecked: true + property bool credentialsPresent: true + property bool credentialsWriteBusy: false + property var missingTools: [] + property string lastError: "" + property string clientId: "client" + property string clientDescription: "client" + property string credentialsPath: "/synthetic/credentials.json" + property var credentials: null + property var settings: ({username: "", aliases: [], imapHost: "", imapPort: 993, smtpHost: "", smtpPort: 465}) + } + QtObject { + id: service + property var auth: auth + property string accountAddress: "" + property string accountEmail: "" + property string accountName: "" + property string accountSenderName: "" + property bool backendCanNameSender: false + property string signInProgress: "" + } + Views.ImapSetupPage { + id: imap + width: 600 + service: service + textColor: "#eeeeee" + dimColor: "#aaaaaa" + dangerColor: "#ff6666" + accentColor: "#e9a35f" + panelFontFamily: "monospace" + } + Views.SetupPage { + id: gmail + width: 600 + service: service + textColor: "#eeeeee" + dimColor: "#aaaaaa" + dangerColor: "#ff6666" + accentColor: "#e9a35f" + panelFontFamily: "monospace" + } + TestCase { + name: "SetupPlainText" + when: windowShown + readonly property string markup: 'setup' + function labelContaining(item, value) { + if (item.text !== undefined && String(item.text).indexOf(value) >= 0 && item.textFormat !== undefined) return item + var children = item.children || [] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + var label = labelContaining(children[childIndex], value) + if (label) return label + } + return null + } + function init() { + auth.lastError = "" + auth.clientDescription = "client" + auth.credentialsPath = "/synthetic/credentials.json" + service.signInProgress = "" + } + function test_imap_server_error_is_literal() { + auth.lastError = markup + compare(findChild(imap, "imap-error").textFormat, Text.PlainText) + } + function test_gmail_runtime_values_are_literal_data() { + return [{tag: "progress", field: "signInProgress", serviceField: true}, + {tag: "client", field: "clientDescription", serviceField: false}, + {tag: "path", field: "credentialsPath", serviceField: false}] + } + function test_gmail_runtime_values_are_literal(data) { + var owner = data.serviceField ? service : auth + owner[data.field] = markup + var label = labelContaining(gmail, markup) + verify(label) + compare(label.textFormat, Text.PlainText) + } + } +} From 847d1d39d0ce5dba2e576ba2a3971e49092e8a2f Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 123/568] Fix disguised SVG avatar data admission --- ui/components/MailboxIdentity.js | 4 +++- ui/tests/test_inbox.js | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ui/components/MailboxIdentity.js b/ui/components/MailboxIdentity.js index 03dfb05d8..743c39f22 100644 --- a/ui/components/MailboxIdentity.js +++ b/ui/components/MailboxIdentity.js @@ -1,4 +1,6 @@ .pragma library + +.import "../message/Html.js" as Html function icon(label) { var name = String(label || "").toLowerCase() if (name === "personal") return "home" @@ -12,5 +14,5 @@ function initial(sender) { } function image(value) { var text = String(value || "") - return /^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(text) ? text : "" + return Html.isRasterDataImage(text) ? text : "" } diff --git a/ui/tests/test_inbox.js b/ui/tests/test_inbox.js index a3afa6243..fb7bde762 100644 --- a/ui/tests/test_inbox.js +++ b/ui/tests/test_inbox.js @@ -14,5 +14,8 @@ assert.equal(I.icon('Webscape'),'tree');assert.equal(I.icon('Personal'),'home'); assert.equal(I.initial({display:'Élodie'}),'É'); assert.equal(I.image('https://example.com/track.png'),'');assert.equal(I.image('file:///etc/passwd'),''); assert.equal(I.image('data:image/svg+xml;base64,PHN2Zz4='),''); -assert.equal(I.image('data:image/png;base64,YWJj'),'data:image/png;base64,YWJj'); +const raster = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC'; +assert.equal(I.image(raster), raster); +assert.equal(I.image('data:image/png;base64,YWJj'), ''); +assert.equal(I.image('data:image/png;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg=='), ''); console.log('Inbox date, identity and image boundary tests passed'); From 8472d670555167fc9439352401e8e4cd1ffda9ec Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 124/568] Clarify view state and remove redundant projections --- ui/components/AddressMenu.qml | 8 +- ui/components/AppMenu.qml | 34 +-- ui/components/CalendarEventComposer.qml | 80 ++----- ui/components/CalendarView.qml | 52 +--- ui/components/ComposeView.qml | 197 ++++----------- ui/components/HeySetupPage.qml | 35 +-- ui/components/ImapSetupPage.qml | 60 +---- ui/components/LabelMenu.qml | 13 +- ui/components/LabelMovePicker.qml | 7 +- ui/components/MailboxSidebar.qml | 54 +---- ui/components/MailboxTabs.qml | 21 +- ui/components/Menu.js | 12 +- ui/components/MessageList.qml | 32 +-- ui/components/MessageMenu.qml | 45 +--- ui/components/MessageReader.qml | 306 ++++-------------------- ui/components/ReaderBlankSlate.qml | 17 +- ui/components/SettingsPage.qml | 157 +++--------- ui/components/SetupPage.qml | 69 +----- ui/components/SubjectMenu.qml | 14 +- ui/components/TextMenu.qml | 16 +- 20 files changed, 225 insertions(+), 1004 deletions(-) diff --git a/ui/components/AddressMenu.qml b/ui/components/AddressMenu.qml index 7538b8016..23e938e44 100644 --- a/ui/components/AddressMenu.qml +++ b/ui/components/AddressMenu.qml @@ -5,9 +5,6 @@ import qs.Commons import qs.Ui import "Menu.js" as Menu -// The menu an address opens on a right-click in the reader's header: copy -// it, or find the mail from it or to it. A line with several addresses asks -// which one first, then offers the same three rows for it. Item { id: root @@ -17,7 +14,6 @@ Item { required property color popupBorderColor required property string panelFontFamily - // [{ name, email }] — what the line held. One means straight to the rows. property var addresses: [] property string chosen: "" property bool canSearch: true @@ -108,7 +104,8 @@ Item { } } - // The address the rows are about. A stranger wrote it. + // Invariant: sender-controlled addresses must remain plain text to prevent Qt resource + // loading. Text { width: menu.width - menu.leftPadding - menu.rightPadding leftPadding: MailStyle.space(9) @@ -122,7 +119,6 @@ Item { elide: Text.ElideMiddle } - // Choosing: one row per address on the line. Column { id: pickRows visible: root.choosing diff --git a/ui/components/AppMenu.qml b/ui/components/AppMenu.qml index fce783038..4372deb2a 100644 --- a/ui/components/AppMenu.qml +++ b/ui/components/AppMenu.qml @@ -6,7 +6,6 @@ import qs.Commons import qs.Ui import "Menu.js" as Menu -// Links out, plus the handful of actions that have no natural home on screen. Item { id: root @@ -15,18 +14,11 @@ Item { required property color popupBorderColor required property string panelFontFamily property bool signedIn: false - // Whether this mailbox has a web address for what is on screen. Off, the row - // goes rather than opening something else's inbox. property bool canOpenWebInbox: false - // The rail carries the switcher, and the rail is gone at a narrow window — - // so at that size this menu is the only way left to reach it. + // Invariant: the account switcher remains reachable through this menu when the sidebar is hidden. property int accountCount: 1 - // The menu is opened from wherever the account lives — the sidebar's user - // bar, or the status bar when the sidebar is hidden — so it carries no - // trigger of its own by default. property bool showTrigger: false - // Only the standalone host owns the application process. A plugin menu - // must never offer to terminate the shell that loaded it. + // Invariant: only the standalone host may offer Quit; a plugin must not terminate its shell. property bool canQuit: false property bool singlePane: true property bool hasAgent: true @@ -40,9 +32,6 @@ Item { signal overviewRetryRequested() readonly property bool opened: menu.opened - // Positioned against the window rather than a button, and flipped when it - // would run off the bottom, since it opens from a bar at the bottom. - // Where the menu was asked to appear, kept because it cannot be placed yet. property real anchorX: 0 property real anchorY: 0 property int cursorIndex: -1 @@ -57,11 +46,7 @@ Item { place() } - // A Popup does not build its contents until it is first opened, so on the - // very first click its height is still zero: the "does it fit below?" test - // passed trivially and the menu was placed at the click and then grew off the - // bottom. That matters more now the trigger sits on the status line, where - // below is where there is no room at all. + // Invariant: popup content is created lazily; position again after its first height is known. function place() { if (!menu.visible) return var tall = menu.height > 0 ? menu.height : menu.implicitHeight @@ -84,9 +69,6 @@ Item { signal markAllReadRequested() signal openWebRequested() signal shortcutsRequested() - // The two places the window is for, as a pair. The sidebar has both, but - // a narrow window has no sidebar, and then these rows are the only way - // from one to the other. signal inboxRequested() signal calendarRequested() signal setupRequested() @@ -127,11 +109,7 @@ Item { closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside onHeightChanged: root.place() onOpened: { - // No row lit until a key asks for one. Opening with the first row - // highlighted read as "this is where you are" once the first row - // became Inbox — on the calendar, a menu saying Inbox was selected. - // j/k from nowhere start at the first or last row, so the keyboard - // loses nothing. + // Invariant: opening the menu must not imply that Inbox is the current view. root.cursorIndex = -1 root.place() } @@ -247,8 +225,6 @@ Item { MenuRow { id: markRow - // "These" and not "all": it marks the messages that are loaded, which - // is what you are looking at, not every message the mailbox holds. text: "Mark these read" enabled: root.signedIn onActivated: { menu.close(); root.markAllReadRequested() } @@ -309,8 +285,6 @@ Item { } } - // `enabled` is Item's own, and it already stops the handlers below from - // firing, so a disabled row only has to look disabled. component MenuRow: MenuActionRow { width: menu.width - menu.leftPadding - menu.rightPadding textColor: root.textColor diff --git a/ui/components/CalendarEventComposer.qml b/ui/components/CalendarEventComposer.qml index dbe213e9d..878e39537 100644 --- a/ui/components/CalendarEventComposer.qml +++ b/ui/components/CalendarEventComposer.qml @@ -40,7 +40,7 @@ Rectangle { function chooseGuestSuggestion() { guestSuggestionsList.acceptSelection() } function dismissGuestSuggestions() { guestSuggestionsDismissed = true } function acceptGuest(contact) { - // Calendar's guest payload accepts addresses, not mail's display-name syntax. + // Invariant: calendar guests accept addresses only, not mail display-name syntax. guestsField.text = Recipients.accept(guestsField.text, { email: contact.email }) + ", " guestsField.forceActiveFocus() } @@ -52,15 +52,12 @@ Rectangle { readonly property var chosenSource: controller && typeof controller.findSource === "function" ? controller.findSource(selectedSourceId) : null property string recurrenceFrequency: "WEEKLY" - // Set while an existing event is being changed rather than a new one made. - // Calendar changes select a transfer destination; they are committed on Save. property var editingEvent: null property bool loadingSeries: false property bool transferring: false property bool transferNeedsRefresh: false property int editGeneration: 0 - // Google's options travel only through the API 6 backend; an older one - // would save the event without them, so the controls are not offered. + // Invariant: Google-specific write options require API6; older backends would silently omit them. readonly property bool googleWrites: !!chosenSource && chosenSource.kind === "google" && !!controller && !!controller.service && controller.service.backendCanGoogleCalendars === true readonly property bool guestUpdate: editing && googleWrites @@ -69,8 +66,6 @@ Rectangle { || guestsField.text.trim() !== "") property string editingSourceId: "" readonly property bool editing: editingEvent !== null - // Nothing typed and nothing being edited: a form that can be replaced - // without losing anyone anything. readonly property bool pristine: !editing && !writePending && String(titleField.text || "") === "" && String(locationField.text || "") === "" && String(notesField.text || "") === "" && String(guestsField.text || "").trim() === "" @@ -86,12 +81,10 @@ Rectangle { value: root.opened && !root.pristine when: !!root.controller } - // Set when this form's own write is in flight. A completion is answered only - // while it is: a write the user cancelled out of — Escape, then a newer - // edit — must not close or report into this one. + // Invariant: only this form’s pending write may close it; cancelled older edits must not affect a + // newer form. property bool writePending: false - // An all-day event is edited as the dates it spans; the time fields stand - // down, because writing them back would turn the event into a timed one. + // Invariant: all-day edits preserve date spans instead of converting them to timed events. property bool allDay: false readonly property bool editingAllDay: allDay readonly property var dateRange: Calendar.editorDateRange(dateField.text, startField.text, @@ -262,34 +255,27 @@ Rectangle { recurring = false recurrenceFrequency = "WEEKLY" resultText.text = "" - // The mailbox being read is the one the event most likely belongs to, and - // under the unified view it is not the first group: `groupByAccount` walks - // the stored accounts in their own order, so "Create event..." from mailbox - // B would otherwise open with A's calendar chosen and write there unless - // the user noticed the picker. + // Invariant: new events prefer the selected mailbox’s calendar, not the first account in stored + // order. selectedSourceId = preferredCalendarId() timeZoneField.text = chosenSource ? String(chosenSource.timeZone || "") : "" opened = true Qt.callLater(titleField.forceActiveFocus) } + function preferredCalendarIn(group) { + var calendars = group.calendars || [] + for (var calendarIndex = 0; calendarIndex < calendars.length; calendarIndex++) { + if (calendars[calendarIndex].preferred) return String(calendars[calendarIndex].id) + } + return calendars.length ? String(calendars[0].id) : "" + } + function preferredCalendarId() { var groups = controller ? controller.writableSourceGroups : [] if (!groups.length) return "" - // `groupByAccount` names an account's group "account:" + its id, which is - // the only place the owner survives into the group. - var wanted = controller ? String(controller.accountId || "") : "" - if (wanted !== "") { - for (var i = 0; i < groups.length; i++) { - if (String(groups[i].id || "") !== "account:" + wanted) continue - for (var c = 0; c < groups[i].calendars.length; c++) { - if (groups[i].calendars[c].preferred) return String(groups[i].calendars[c].id) - } - if (groups[i].calendars && groups[i].calendars.length) - return String(groups[i].calendars[0].id) - } - } - return String(groups[0].calendars[0].id) + var owned = calendarOf(controller ? String(controller.accountId || "") : "") + return owned || String(groups[0].calendars[0].id) } function beginEdit(sourceId, event) { @@ -322,8 +308,7 @@ Rectangle { dateField.text = localDate(start) startField.text = localTime(start) endField.text = localTime(end) - // The stored all-day end is the exclusive midnight after the last shown - // day, so the field shows a millisecond before it. + // Invariant: stored all-day ends are exclusive; the field displays the preceding date. endDateField.text = event.start.allDay && event.end ? localDate(new Date(Number(event.end.ms) - 1)) : localDate(end) locationField.text = String(event.location || "") @@ -349,18 +334,14 @@ Rectangle { } - // What the form holds, for a test to read without reaching into fields. function titleText() { return String(titleField.text || "") } function whenText() { return dateField.text + " " + startField.text + " " + endField.text } function locationText() { return String(locationField.text || "") } function notesText() { return String(notesField.text || "") } - // Open with fields already filled — a suggestion from a message — for the - // owner to look over and put on the calendar of their choice. Nothing is - // written until they say so, which is the point of opening here. + // Invariant: suggestions only prefill this form; writing requires human submission. function beginWith(prefill) { var fields = prefill || {} - // A form the owner is in the middle of is not replaced. if (opened && !pristine) return false if (fields.editingEvent) { beginReschedule(fields.editingEvent, Number(fields.startMs), Number(fields.endMs)) @@ -377,8 +358,6 @@ Rectangle { titleField.text = String(fields.title || "") locationField.text = String(fields.location || "") notesField.text = String(fields.description || "") - // The calendar of the mailbox the message was read in, when it has - // one: under the merged view that is not always the open account. var owner = calendarOf(String(fields.accountId || "")) if (owner !== "") selectedSourceId = owner return true @@ -387,12 +366,10 @@ Rectangle { function calendarOf(accountId) { var groups = controller ? controller.writableSourceGroups : [] if (!accountId || !groups) return "" - for (var i = 0; i < groups.length; i++) { - if (String(groups[i].id || "") !== "account:" + accountId) continue - for (var c = 0; c < groups[i].calendars.length; c++) { - if (groups[i].calendars[c].preferred) return String(groups[i].calendars[c].id) - } - if (groups[i].calendars && groups[i].calendars.length) return String(groups[i].calendars[0].id) + for (var groupIndex = 0; groupIndex < groups.length; groupIndex++) { + if (String(groups[groupIndex].id || "") !== "account:" + accountId) continue + var preferred = preferredCalendarIn(groups[groupIndex]) + if (preferred !== "") return preferred } return "" } @@ -462,9 +439,8 @@ Rectangle { function submit(sendUpdates) { if (!controller) return - // Create, update and delete share one controller write slot. Do not mark - // this form pending unless that slot is free: otherwise an older write's - // completion could be mistaken for this form's and close it. + // Invariant: create/update/delete share one write slot; an older completion must not be + // attributed to this form. if (controller.creatingEvent || controller.eventWriting || loadingSeries || transferring || transferNeedsRefresh) return if (!dateRange.ok) return var fields = { @@ -737,7 +713,6 @@ Rectangle { onClicked: root.allDay = !root.allDay } - // Labelled above like every other field, so the form has one left edge. FieldLabel { text: "Starts" } Row { width: parent.width @@ -1081,7 +1056,6 @@ Rectangle { return busy ? "Creating" : "Create event" } iconName: root.editing ? "check" : "plus" - // The Enter action: accent edge and text, not a solid fill. foreground: root.accentColor accent: root.accentColor fontFamily: root.panelFontFamily @@ -1112,9 +1086,7 @@ Rectangle { Connections { target: root.controller - // A completion is answered only while this form's own write is in flight: - // one the user cancelled out of belongs to no edit, and its failure is - // already on the view's banner. + // Invariant: a cancelled form must not consume another edit’s completion. function onComposeRequested(prefill) { root.beginWith(prefill) } function onEventCreated(ok, error) { if (!root.writePending) return diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index 5a3310f57..bf290e427 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -55,8 +55,7 @@ Item { } onViewModeChanged: { monthOverflow.close(); monthHoverDelay.stop(); hoveredMonthDay = null; syncAgenda() } onDaysChanged: syncAgenda() - // The agenda's clock ticks every minute to drop finished events. Its model - // changes only when the list does, so a tick leaves the scroll where it was. + // Invariant: retain an unchanged agenda model so clock ticks do not reset its scroll. property var agendaEvents: [] function syncAgenda() { var next = viewMode === "agenda" ? visibleEvents() : [] @@ -233,7 +232,6 @@ Item { }) } - // Escape's first answer while the busy-day preview is up. function dismissPreview() { if (!monthOverflow.opened) return false monthOverflow.close() @@ -477,7 +475,6 @@ Item { ActionIcon { anchors.centerIn: parent name: "refresh" - // The same size as the chevrons beside it and Check mail above. iconSize: Style.font.icon color: root.accentColor @@ -583,12 +580,9 @@ Item { border.width: 1 border.color: root.urgentColor - readonly property bool apiDisabled: root.controller - && root.controller.lastErrorKind === "googleApiDisabled" - Text { anchors.left: parent.left - anchors.right: errorActions.visible ? errorActions.left : parent.right + anchors.right: parent.right anchors.top: parent.top anchors.bottom: parent.bottom anchors.leftMargin: MailStyle.space(10) @@ -602,36 +596,7 @@ Item { textFormat: Text.PlainText } - Row { - id: errorActions - anchors.right: parent.right - anchors.rightMargin: MailStyle.space(4) - anchors.verticalCenter: parent.verticalCenter - spacing: MailStyle.space(4) - visible: calendarError.apiDisabled - IconTextButton { - objectName: "calendarErrorCopy" - text: "Copy" - tooltipText: "Copy this error" - foreground: root.textColor - accent: root.accentColor - fontFamily: root.panelFontFamily - fontSize: MailStyle.caption - onClicked: root.copyRequested(root.controller.lastError) - } - - IconTextButton { - objectName: "calendarApiEnable" - text: "Enable API..." - tooltipText: "Open Google Cloud Calendar API setup..." - foreground: root.textColor - accent: root.accentColor - fontFamily: root.panelFontFamily - fontSize: MailStyle.caption - onClicked: root.openRequested(Calendar.googleCalendarApiUrl()) - } - } } Text { @@ -705,7 +670,6 @@ Item { readonly property real weekHeight: height / (root.days.length / 7) readonly property real eventTop: MailStyle.space(10) + monthFontMetrics.height readonly property real eventPitch: MailStyle.space(25) - // Leave space for an overflow link even when spanning events fill a week. readonly property int spanLimit: Math.max(0, Math.floor( (weekHeight - eventTop - MailStyle.space(5) - monthFontMetrics.height) / eventPitch)) function visibleLanes(week) { return Math.min(spanLimit, root.monthSpans.laneCounts[week] || 0) } @@ -1085,11 +1049,8 @@ Item { } } - // A hover preview, not a QQC.Popup: an open Popup takes every key before the - // window's shortcuts see it, focused or not (tst_popup_keys), so resting the - // pointer on a busy day would silence j, k and every view key until it left. - // An item drawn above the window keeps the keyboard with KeyRouter; Escape - // reaches it through goBack(). + // Invariant: QQC.Popup consumes window shortcuts even without focus; a hover preview must leave + // KeyRouter active (tst_popup_keys). Rectangle { id: monthOverflow objectName: "calendar-month-overflow" @@ -1121,8 +1082,7 @@ Item { } onOpenedChanged: if (opened) place() onHeightChanged: if (opened) place() - // Swallows clicks that miss an event, as the popup's background did, so - // one never lands on the month cell drawn underneath. + // Invariant: clicks between preview events must not activate the month cell below. MouseArea { anchors.fill: parent; acceptedButtons: Qt.AllButtons; onWheel: function(wheel) { wheel.accepted = true } } Item { anchors.fill: parent @@ -1318,8 +1278,6 @@ Item { dimColor: root.dimColor panelFontFamily: root.panelFontFamily onClosed: root.closeDetail() - // Editing replaces the detail: the composer covers the view, and the - // event it rewrites is not the one these labels would go on showing. onEditRequested: function(sourceId, event) { root.closeDetail() root.editRequested(sourceId, event) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index a78721532..fdef844a5 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -13,14 +13,6 @@ import "../compose/Recipients.js" as Recipients import "../compose/Senders.js" as Senders import "../agent/Agent.js" as Agent -// Composing takes over the whole content area of the one window rather than -// opening a second one: Omarchy's panel mechanism would give an extra window -// its own region, which is not what a reply is. Two mail accounts would -// justify two windows; a reply does not. -// -// Compose, reply, reply-all and forward are the same form with different -// starting values, so `begin()` fills the fields and everything after that is -// one code path. DropArea { id: root @@ -42,43 +34,26 @@ DropArea { property bool opened: false property bool userModified: false property bool settingBodyText: false - // Drafts parked for their send's undo window, oldest first, each beside - // the name of the send it belongs to. The timer owns them while the - // visible composer stays free for the next message. + // Invariant: undo-window drafts remain paired with their outbox send IDs in dispatch order. property var parkedDrafts: [] readonly property bool parkedForSend: parkedDrafts.length > 0 - // The timer owns this draft while the visible composer remains free. - // The newest parked draft: what recovery keeps, and what Undo takes back. readonly property var pendingDraft: parkedDrafts.length > 0 ? parkedDrafts[parkedDrafts.length - 1].draft : null - // Undo temporarily replaces a newer draft. Closing or resending returns here. property var interruptedDraft: null - // A failed provider save stays reachable after Back or Escape. property var recoveryDrafts: [] property string accountId: "" - // The provider message that this form replaces when it is saved. property string sourceDraftId: "" - // The sign-off of the mailbox this draft belongs to, read when a draft is - // started rather than bound into the editor: the text is the user's to edit - // once it is in there, and a binding would overwrite what they had changed. - // - // The draft's own account, not the active one. `begin` sets `accountId` - // first, so a reply owned by B is signed by B even while A is on screen — - // otherwise one identity's name and contact details go out over another's. + // Invariant: draft ownership determines the signature; binding it to the active mailbox can send + // another identity’s details and overwrite manual edits. readonly property string accountSignature: root.service ? String(root.service.signatureFor(root.accountId) || "") : "" - // The body exactly as `placeBody` left it, plus whether the editor has seen a - // user edit. Equality alone is not an edit history: somebody can type and - // delete back to the same text. Together they separate an abandoned compose - // from a body the user has taken ownership of. + // Invariant: text equality cannot detect an edit later undone; track edit history before + // replacing the placed body. property string placedBody: "" property bool bodyWasEdited: false - // What it was built from, so it can be built again for another mailbox. property string bodyPrefix: "" property string bodyQuote: "" - // Both popups reparent themselves into the window overlay, so their state is - // not reachable by walking this view's children. Named here so the tests can - // ask whether a control put its own popup away. + // Docs: overlay popups are exposed because they are not children of this view. readonly property bool fromMenuOpened: fromMenu.opened readonly property bool contactsPickerOpened: contactsPicker.opened property int restoreRevision: 0 @@ -88,19 +63,13 @@ DropArea { property string inReplyTo: "" property bool ccVisible: false property bool bccVisible: false - // Where answers should go when that is not the sender. Hidden like Bcc - // until asked for: most mail has no use for it. property bool replyToVisible: false - // The agent's card over this draft: whether it is up, working, or wants - // the owner — all facts the window passes down. property bool agentOpen: false property bool agentWorking: false property bool agentAttention: false signal agentRequested(real sceneX, real sceneY) - // What the agent is handed, and how its answer lands. Replacing the body - // counts as an edit — it is one — so the signature is not placed over it. property string draftKey: newDraftKey() function newDraftKey() { return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2) } function currentFields() { @@ -144,8 +113,7 @@ DropArea { } function sendProposal(envelope, proposalId, parentId) { if (!service || proposalRoutingChanged(envelope)) return false - // Prepare a real recovery draft before dispatch, without replacing newer - // manual edits. Undo and failures use the same parked-draft path as Send. + // Invariant: create recovery state before dispatch without replacing newer manual edits. var draft = Agent.proposalDraft(envelope, parentId, String(envelope.draftKey || newDraftKey())) var accepted = service.sendAgentProposal(proposalId, fieldsForDraft(draft)) if (!accepted) return false @@ -155,8 +123,8 @@ DropArea { function proposalRoutingChanged(envelope) { if (!opened || !envelope) return false - // An unrelated parked draft does not own a reader's proposal. A matching - // draft/reply does: never send its old routing after the owner edits it. + // Invariant: a matched draft owns its current routing; a proposal must not restore stale + // recipients. var sameDraft = envelope.draftKey ? String(envelope.draftKey) === draftKey : replyMessageId !== "" && String(envelope.replyMessageId || "") === replyMessageId if (!sameDraft) return false @@ -242,9 +210,8 @@ DropArea { return root.service.sendAsAliases } - // Filtered against the mailbox this draft belongs to rather than the visible - // one, so a reply raised from a merged list offers the aliases of the - // mailbox it arrived in. + // Invariant: send-as choices belong to the draft’s mailbox, including replies from the merged + // list. readonly property var fromIdentities: Senders.visible( root.service ? root.service.sendIdentities : [], root.accountId !== "" ? root.accountId @@ -278,9 +245,8 @@ DropArea { draftKey = newDraftKey() forwardLoadSerial++ fromMenu.close() - // Both of these live in the window overlay, and this view is hidden rather - // than destroyed — so a popup left open outlives the draft it belonged to - // and sits over the message list. + // Invariant: popups live in the window overlay and must close when this persistent composer is + // hidden. contactsPicker.close() toField.text = "" ccField.text = "" @@ -319,9 +285,8 @@ DropArea { if (forgetAttachments) forgetOwned(owned) } - // Rebuilt rather than patched: the signature is not at a known offset once - // the quote is under it, and searching for the old one to swap would find a - // sign-off the user had quoted from somebody else. + // Invariant: replacing a signature by text search could change a sign-off inside the quoted + // message. property int composeTextSerial: 0 property var pendingQuoteSummary: null property string pendingQuoteText: "" @@ -355,9 +320,7 @@ DropArea { }) } - // From reaches every mailbox, and choosing one switches the active account - // under the open window. The sign-off has to follow it — but only while the - // body is still the one placed, or this would overwrite what was typed. + // Invariant: changing From may rebuild only an untouched placed body, never the user’s edits. onAccountSignatureChanged: { if (!opened || mode === "draft") return if (bodyWasEdited || bodyEdit.text !== placedBody) return @@ -484,12 +447,8 @@ DropArea { if (typeof root.service.switchTo === "function") root.service.switchTo(accountId) } - // When a control opens a popup that closes on a press outside itself, the - // press that reaches the control has already closed it — so by the time the - // release becomes a click, `opened` reads false and the toggle opens it - // straight back up. The control could never be used to put its own popup - // away, and it flickers instead. The moment it closed is what tells "the - // user wants this open" apart from "this just closed under the same press". + // Invariant: outside-press closes the popup before the trigger’s click; remember closure time to + // avoid reopening it on the same press. property double fromMenuClosedAt: 0 function reopeningAfterOutsidePress(closedAt) { @@ -617,11 +576,7 @@ DropArea { agentParentJobId = "" replyMessageId = summary && (nextMode === "reply" || nextMode === "replyAll") ? String(summary.id || "") : "" mode = String(nextMode || "new") - // The mailbox the message being answered arrived in, not the one that - // happens to be active. In a merged list those differ, and a reply sent - // from the wrong mailbox with nothing on screen saying so is the failure - // this view most has to avoid. `composeAccountId` is the active account - // whenever there is no selection, so a new message is unchanged. + // Invariant: replies use the message’s owning mailbox even when another mailbox is active. accountId = root.service ? String(root.service.composeAccountId || "") : "" opened = true var quoted = "" @@ -629,9 +584,8 @@ DropArea { if (summary && mode !== "new") { threadId = summary.threadId inReplyTo = summary.messageId - // Cc as well as To: an alias is just as often the address a thread - // copied you on as the one it was sent to, and answering from the - // account's default instead is how a thread ends up split in two. + // Invariant: Cc may name the addressed send-as alias, so both recipient fields determine the + // default sender. if (mode === "reply" || mode === "replyAll") { replyRecipients = (Array.isArray(summary.to) ? summary.to : []) .concat(Array.isArray(summary.cc) ? summary.cc : []) @@ -661,13 +615,10 @@ DropArea { if (root.service) root.service.refreshRecipientContacts() userModified = false - // Focus is not placed here. Opening this changes the window's key context, - // and the context is what moves the keyboard — one mechanism, so the two - // cannot disagree about where the typing goes. + // Invariant: the window’s keyboard context owns focus placement; begin must not compete with + // it. } - // A mailto: link is a new message with the fields already named. Reply and - // forward stay on `begin`; they fill from a message, not from a URL. function beginDraft(draft, messageId, attachments) { begin("new", null, "", []) var values = draft || ({}) @@ -684,8 +635,7 @@ DropArea { replyToVisible = replyToField.text !== "" subjectField.text = String(values.subject || "") if (mode === "draft") { - // Somebody wrote this and it was saved. None of it was placed, so all of - // it is theirs — including the sign-off it already carries. + // Invariant: a restored draft is authored text, including its existing signature. root.setBodyText(String(values.body || "")) placedBody = "" bodyWasEdited = true @@ -705,8 +655,6 @@ DropArea { userModified = false } - // Where the keyboard goes when composing becomes the context. A reply starts - // in the body above the quote; a new message starts at the address. function takeFocus() { if (mode === "reply" || mode === "replyAll") { bodyEdit.forceActiveFocus() @@ -720,13 +668,6 @@ DropArea { } } - // The Back control asks the window to resolve user changes. Discard stays local and - // destructive. The window owns the save because it owns the provider. - // Which way what is being written runs. Qt resolves an editable field from - // the text already in it, so Auto needs nothing added; a direction the writer - // has chosen has to be carried to the fields, including the empty ones — a - // reply begun in a right-to-left mailbox should put the caret on the right - // before there is any text to work it out from. property string contentDirection: Direction.MODE_DEFAULT readonly property string writingDirection: Direction.forced(root.contentDirection) readonly property var composeAlignment: Direction.hasAnswer(root.writingDirection) @@ -841,18 +782,16 @@ DropArea { function parkDraftForSend(sendId, draft) { var parked = parkedDrafts.slice() - // A card can appear in both the reader and composer. The outbox send ID - // also identifies its one recovery draft. + // Invariant: the outbox send ID identifies one recovery draft even when its proposal appears in + // two views. if (parked.some(function(entry) { return entry.sendId === String(sendId) })) return parked.push({ sendId: String(sendId || ""), draft: draft }) parkedDrafts = parked draftChanged() } - // The parked draft a send names — or, for a caller that does not name its - // sends, the newest for an undo and the oldest for an answer, since sends - // go in the order they were asked. A name that is not parked here belongs - // to no draft: answering with another's would restore the wrong words. + // Invariant: an unknown named send must not restore another parked draft; unnamed legacy answers + // follow dispatch order. function takeParked(sendId, oldest) { if (parkedDrafts.length === 0) return null var parked = parkedDrafts.slice() @@ -919,16 +858,13 @@ DropArea { } function submit() { - // The send key is answered by action id, and the compose keyboard context - // also covers the calendar event form — a composer that is not open must - // not answer it, or a draft parked for the undo window would send twice. + // Invariant: the shared compose keyboard context also covers calendar forms; a hidden mail + // composer must not dispatch. if (!opened || !service) return if (!attachmentsReady) return var accepted = service.send(({ - // The mailbox this draft belongs to, named rather than inferred. Without - // it the service fell back to matching `from` against each account in - // turn, so two mailboxes sharing a send-as alias sent B's draft from - // whichever of them came first. + // Invariant: account ownership cannot be inferred from a send-as alias shared by multiple + // mailboxes. accountId: root.accountId, draftKey: root.draftKey, from: root.fromEmail, @@ -939,11 +875,9 @@ DropArea { subject: subjectField.text, body: bodyEdit.text, attachments: root.allOutgoingAttachments(), - // The draft this form was opened from, which sending replaces. A save - // has always named it; a send dropped it, and the draft stayed in the - // list after the message it had become was already gone. + // Invariant: sending an existing provider draft must identify the draft it replaces. draftId: root.sourceDraftId, - // A forward starts a new conversation; a reply must stay in the old one. + // Invariant: forwarding starts a new conversation; replying preserves its thread. threadId: root.mode === "forward" ? "" : root.threadId, inReplyTo: root.mode === "forward" ? "" : root.inReplyTo })) @@ -1048,8 +982,8 @@ DropArea { try { result = JSON.parse(String(text || "")) } catch (e) { result = null } - // Helpers outlive the form they started from. A late read/picker/paste - // must not put an old draft's file or clipboard text into the next one. + // Invariant: attachment helpers outlive the form; stale completions must not enter the next + // draft. if (mode !== "forget" && owner !== undefined && owner !== root.draftKey) { if (mode === "clipboard" && result && result.ok === true && result.path) root.forgetOwned([{owned:true,path:result.path}]) @@ -1157,11 +1091,6 @@ DropArea { } } - // ----------------------------------------------------------- header - // - // One compact title band. Back is the exit path and the title names the - // draft; splitting them into two stacked bands gave one short decision the - // hierarchy of a whole settings page. Item { id: head anchors.top: parent.top @@ -1201,10 +1130,6 @@ DropArea { } } - // ----------------------------------------------------------- fields - // - // A label column wide enough for the longest of To / Cc / Subject keeps - // the three inputs aligned without a grid. Column { id: fields @@ -1212,9 +1137,8 @@ DropArea { anchors.top: head.bottom anchors.left: parent.left anchors.right: parent.right - // Suggestions extend below this column into the message body. Raising only - // the row cannot cross the sibling boundary, so the body painted over the - // popup even though the popup itself had a high z value. + // Invariant: recipient suggestions must cross the body’s sibling boundary, so their containing + // column needs the higher z. z: 10 Item { @@ -1234,10 +1158,6 @@ DropArea { font.pixelSize: MailStyle.caption } - // Sized to the address rather than to the row: a full-width trigger puts - // the chevron a screen away from the name it belongs to. The extra width - // is the room the chevron is drawn into, over the button's own trailing - // padding, so the two read as one control. Widgets.Button { id: fromButton objectName: "compose-from-button" @@ -1262,9 +1182,6 @@ DropArea { enabled: root.canChooseFrom onClicked: root.toggleFromMenu() - // The kit's own chevron is a font glyph, which at this size renders - // thinner than every other mark in the window. This is the app's drawn - // set, at the size the rest of the icons use. ActionIcon { anchors.right: parent.right anchors.rightMargin: fromButton.horizontalPadding @@ -1287,10 +1204,7 @@ DropArea { Item { width: parent.width z: root.toSuggestions.length > 0 ? 100 : 0 - // The field plus the same breathing room it carries inside itself, so - // its border is not crowded against the rules above and below. Derived - // rather than a fixed height: the field grows with the theme's font - // scale, and a fixed row would scale that growth a second time. + // Invariant: derive row height from the scaled field to avoid applying font scale twice. implicitHeight: toField.implicitHeight + MailStyle.space(14) Text { @@ -1426,10 +1340,7 @@ DropArea { visible: root.ccVisible width: parent.width z: root.ccSuggestions.length > 0 ? 100 : 0 - // The field plus the same breathing room it carries inside itself, so - // its border is not crowded against the rules above and below. Derived - // rather than a fixed height: the field grows with the theme's font - // scale, and a fixed row would scale that growth a second time. + // Invariant: derive row height from the scaled field to avoid applying font scale twice. implicitHeight: ccField.implicitHeight + MailStyle.space(14) Text { @@ -1634,10 +1545,7 @@ DropArea { Item { width: parent.width - // The field plus the same breathing room it carries inside itself, so - // its border is not crowded against the rules above and below. Derived - // rather than a fixed height: the field grows with the theme's font - // scale, and a fixed row would scale that growth a second time. + // Invariant: derive row height from the scaled field to avoid applying font scale twice. implicitHeight: subjectField.implicitHeight + MailStyle.space(14) Text { @@ -1881,10 +1789,6 @@ DropArea { } } - // ------------------------------------------------------------- body - // - // The kit has no multi-line field, so this is a TextEdit on the plain - // window ground; the rows above already carry the structure. Flickable { id: bodyFlick @@ -1910,10 +1814,8 @@ DropArea { TextMenuTrigger {} activeFocusOnTab: true width: bodyFlick.width - // Tall enough to fill the visible area even when the draft is short. - // A TextEdit sized to its text leaves the space below it belonging to - // the Flickable, so clicking into the empty part of a mostly-empty - // message does nothing at all. + // Invariant: the editor must fill the viewport so clicking below a short draft still places + // the cursor. height: Math.max(implicitHeight, bodyFlick.height) selectByMouse: true wrapMode: TextEdit.Wrap @@ -2044,7 +1946,6 @@ DropArea { } } - // ---------------------------------------------------------- actions Item { id: actions @@ -2069,8 +1970,8 @@ DropArea { iconName: "send" objectName: "compose-send-button" tooltipText: "Send · ctrl+enter" - // A send in flight or parked is no reason to hold the next: each is - // parked in its account's line and goes in turn. + // Invariant: a queued send does not lock the composer; each draft has its own recovery + // state. text: "Send" foreground: root.textColor fontFamily: root.panelFontFamily @@ -2101,12 +2002,8 @@ DropArea { } - // -------------------------------------------------------------- text menu - // - // One menu for every field: the trigger names the field it sits in, and - // Paste takes the route Ctrl+V takes — the clipboard is tried for an image - // first, and text goes into whichever field has focus, so the clicked one - // is given it before the ask. + // Invariant: context-menu Paste follows the image-aware clipboard path and focuses the clicked + // field first. component TextMenuTrigger: MouseArea { anchors.fill: parent acceptedButtons: Qt.RightButton diff --git a/ui/components/HeySetupPage.qml b/ui/components/HeySetupPage.qml index 202293466..2de113ece 100644 --- a/ui/components/HeySetupPage.qml +++ b/ui/components/HeySetupPage.qml @@ -3,16 +3,7 @@ import "../controls" as Widgets import "../settings" import qs.Commons import qs.Ui -import "../providers/Registry.js" as Provider - -// Connecting a HEY mailbox, which is a program and a button. -// -// There is no form here at all, and that is the point: HEY publishes no IMAP -// and no API this plugin could sign in to, so Magpie reads it through `hey`, -// the command line client 37signals ship — and `hey` owns the sign-in, the -// token and the keyring entry it lives in. Everything this page can do is say -// whether the program is there, start its browser flow, and be honest about -// what HEY is not. + Column { id: root @@ -32,14 +23,12 @@ Column { readonly property bool signedIn: !!auth && auth.loggedIn readonly property bool busy: !!auth && auth.loginBusy - // The one line somebody has to run. Written out rather than run from here: - // this window would be piping a script from the internet into a shell on the - // user's behalf, which is a thing to decide in a terminal you are looking at. + // Invariant: this is a displayed installation command, not permission to pipe a remote script + // into a shell. readonly property string installCommand: "curl -fsSL https://hey.com/install-cli | bash" spacing: MailStyle.space(16) - // ------------------------------------------------------------------ hero ProviderHero { width: parent.width @@ -52,17 +41,12 @@ Column { onWebsiteRequested: if (root.service) root.service.openProviderWebsite("hey") } - // --------------------------------------------------------- install first Column { width: parent.width visible: root.checked && !root.installed spacing: MailStyle.space(10) - // The name of the thing to install is also where to read about it. Split - // rather than set as rich text: only the client's name is the link, and a - // whole heading that opened a browser would be a heading somebody made - // clickable by accident. Row { spacing: 0 @@ -94,8 +78,6 @@ Column { wrapMode: Text.WordWrap } - // Selectable, because the whole point of the box is to get the line into a - // terminal. Read-only: nothing here runs what it holds. Rectangle { width: parent.width implicitHeight: commandText.implicitHeight + MailStyle.space(20) @@ -141,7 +123,6 @@ Column { } } - // ---------------------------------------------------------- then sign in Column { width: parent.width @@ -198,7 +179,6 @@ Column { } } - // ------------------------------------------------------------- connected Column { width: parent.width @@ -239,11 +219,6 @@ Column { wrapMode: Text.WordWrap } - // ------------------------------------------------------- what HEY is not - // - // Said here rather than discovered later. Every one of these is a button this - // provider does not draw, and somebody who came from Gmail will look for two - // of them within a minute. Column { width: parent.width @@ -290,8 +265,8 @@ Column { } } - // The sign-out above is `hey`'s own, because the token is `hey`'s. Said next - // to the button rather than after it has been pressed. + // Invariant: signing out affects the shared HEY CLI credential, including other applications that + // use it. Text { width: parent.width visible: root.signedIn diff --git a/ui/components/ImapSetupPage.qml b/ui/components/ImapSetupPage.qml index 4d360d05c..23b5f4691 100644 --- a/ui/components/ImapSetupPage.qml +++ b/ui/components/ImapSetupPage.qml @@ -7,14 +7,6 @@ import "../providers/ImapProtocol.js" as Imap import "../account/Accounts.js" as Accounts import "../account/Aliases.js" as Aliases -// Connecting an ordinary mailbox: an address, a password, and — only if the -// guess was wrong — the servers. -// -// The Gmail page next door is a walkthrough because Google genuinely requires -// one. This is not that: for a known provider it is two fields, because the -// hostnames are already known and typing them out is a way to get them wrong. -// The servers are filled in from the address and shown behind a disclosure, so -// they can be corrected without being in anyone's way. Column { id: root @@ -35,8 +27,6 @@ Column { readonly property bool busy: !!auth && auth.loginBusy readonly property bool toolsMissing: !!auth && auth.toolsChecked && auth.missingTools.length > 0 - // Recomputed as the address is typed, and only ever used to *fill* the - // fields — never to override something already typed into them. readonly property var suggestion: Imap.suggestedSettings(addressField.text) spacing: MailStyle.space(16) @@ -53,16 +43,13 @@ Column { }) } - // The address drives the servers until the user takes them over. Once a field - // has been edited by hand, a later change of address must not overwrite it — - // which is what `touched` records. + // Invariant: automatically suggested servers must not overwrite fields the user edited. property bool serversTouched: false function applySuggestion() { if (serversTouched) return - // onTextChanged runs before the readonly binding above is guaranteed to - // have observed the last keystroke. Derive from the field here, or typing - // the final "m" in .com can leave the server suggestion ending in .co. + // Invariant: onTextChanged can precede the suggestion binding; derive from the field’s current + // text. var current = Imap.suggestedSettings(addressField.text) imapHostField.text = current.imapHost imapPortField.text = String(current.imapPort) @@ -87,24 +74,14 @@ Column { imapPortField.text = String(settings.imapPort) smtpHostField.text = settings.smtpHost smtpPortField.text = String(settings.smtpPort) - // Settings that came off disk are the user's own, so the address must not - // overwrite them. + // Invariant: persisted server settings are user choices and must not be overwritten by + // address suggestions. serversTouched = true } } - // The address is this mailbox's identity, not just a label on it: - // `Accounts.accountId` derives the account id from it, and anything that is - // not an address derives the empty id a pending row carries. That row then - // looks saved and behaves like a draft — it cannot be selected, switched to, - // signed, or removed, and there is no way back to it from inside the window. - // `validateSettings` cannot catch this: `setupSettings` folds the address - // into `username` and hands on no address at all. So it is checked here, - // against the same predicate that derives the id, while it is still a typo - // the user can see. - // - // Checked before the server settings because the form reads address first, - // and an error should name the first field to go back to. + // Invariant: setupSettings omits the address; validate it before accountId can turn an invalid + // address into a pending mailbox. function validatedAddress() { var address = addressField.text.trim() if (Accounts.isValidEmail(address)) return address @@ -114,8 +91,8 @@ Column { return "" } - // Saved before the password is tried, so a mailbox that the server rejects - // still has its settings to correct rather than an empty form to fill again. + // Invariant: save configuration before trying credentials so rejected sign-in leaves an editable + // mailbox. function save() { if (!service) return var address = validatedAddress() @@ -164,7 +141,6 @@ Column { } } - // ------------------------------------------------------------------ hero Column { width: parent.width @@ -215,7 +191,6 @@ Column { } } - // -------------------------------------------------------------- the form Column { width: parent.width @@ -253,13 +228,6 @@ Column { onAccepted: passwordField.forceActiveFocus() } - // What a provider wants instead of the website password. Shown as soon as - // the address names one, because someone typing their everyday password - // into this box will otherwise be told only that it was rejected. A box - // rather than a line of caption: a Gmail user who has just been refused by - // Google is about to be refused again, and this is the sentence that - // stops it — so it is drawn in body text, with the page that explains the - // app password one tap away. Rectangle { width: parent.width visible: root.suggestion.note !== "" @@ -309,9 +277,6 @@ Column { id: passwordField anchors.left: parent.left anchors.right: parent.right - // Masked by default: this window is shoulder-surfable. Readable on - // demand, because an app password is a 16-character string nobody can - // check by memory. password: !root.passwordVisible rightPadding: horizontalPadding + MailStyle.space(26) foreground: root.textColor @@ -351,10 +316,6 @@ Column { } } - // ------------------------------------------------------------ the servers - // - // Behind a disclosure, because for a known provider they are already right - // and four more fields on screen would suggest otherwise. Column { width: parent.width @@ -424,9 +385,6 @@ Column { } } - // Only for the servers where the login name is not the address, which is - // common enough on self-hosted mail to be worth a field and rare enough - // to keep out of the way. Widgets.TextField { id: usernameField width: parent.width diff --git a/ui/components/LabelMenu.qml b/ui/components/LabelMenu.qml index bc66537d9..42a58506c 100644 --- a/ui/components/LabelMenu.qml +++ b/ui/components/LabelMenu.qml @@ -5,11 +5,6 @@ import qs.Commons import qs.Ui import "Menu.js" as Menu -// The menu a label opens on a right-click: what can be done to the label -// itself, as opposed to the messages in it. Every row that changes the -// server's list is offered only where the provider can be asked -// (`canManage`); an ancestor no label names (`labelId` empty) offers only the -// two rows that make something beneath or beside it. Item { id: root @@ -21,8 +16,7 @@ Item { required property string panelFontFamily property string labelId: "" - // Whose label this is: the account open when the popup opened, by id, - // so the answer goes to it even if the window has moved on since. + // Invariant: label mutations retain the account that owned the popup when it opened. property string accountId: "" property string labelPath: "" property bool monitored: false @@ -33,7 +27,7 @@ Item { readonly property bool real: labelId !== "" signal renameRequested(string labelId) - // `beneath` false means beside: under the same parent this label has. + // Docs: beneath=false creates a sibling under the label’s existing parent. signal createRequested(string labelPath, bool beneath) signal moveRequested(string labelId) signal monitorToggled(string labelId) @@ -66,8 +60,6 @@ Item { function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } - // The parent a new sibling goes under: the label's own parent, which is - // the path with its last segment taken off by whoever handles the signal. QQC.Popup { id: menu width: MailStyle.space(220) @@ -104,7 +96,6 @@ Item { } } - // The label's name, so the menu says which one it is about. Text { width: menu.width - menu.leftPadding - menu.rightPadding leftPadding: MailStyle.space(9) diff --git a/ui/components/LabelMovePicker.qml b/ui/components/LabelMovePicker.qml index cc240aa97..601393f3c 100644 --- a/ui/components/LabelMovePicker.qml +++ b/ui/components/LabelMovePicker.qml @@ -5,11 +5,7 @@ import QtQuick.Controls as QQC import qs.Commons import qs.Ui import "../account/Model.js" as Model -import "Menu.js" as Menu -// Where a label goes: the top level, or under another label. The rows are -// `Model.labelMoveTargets` — not the label itself, nothing beneath it, not -// the parent it already has — walked with j/k and taken with Enter or o. Item { id: root @@ -21,8 +17,7 @@ Item { required property string panelFontFamily property string labelId: "" - // Whose label this is: the account open when the popup opened, by id, - // so the answer goes to it even if the window has moved on since. + // Invariant: label mutations retain the account that owned the popup when it opened. property string accountId: "" property var targets: [] property int cursorIndex: 0 diff --git a/ui/components/MailboxSidebar.qml b/ui/components/MailboxSidebar.qml index 56b3f7cb3..6a97e367a 100644 --- a/ui/components/MailboxSidebar.qml +++ b/ui/components/MailboxSidebar.qml @@ -5,14 +5,7 @@ import QtQuick.Controls import qs.Commons import qs.Ui import "../account/Model.js" as Model -import "../providers/Registry.js" as Provider - -// The left column: the mailboxes this account's provider has, then whatever -// labels or folders the server reported, A to Z. -// -// Icon-first, and narrow enough to leave open: the longest mailbox name is -// "All mail". Collapsing it to a strip of icons is one click away, and the -// tooltips carry the names either way, so the collapsed rail stays usable. + Item { id: root @@ -28,23 +21,16 @@ Item { signal mailboxSelected(string key) signal labelSelected(string labelId, string name) signal folderToggled(string path) - // A right-click on a label row: the label's id ("" for an ancestor no label - // names), its path, and where the menu goes. signal labelMenuRequested(string labelId, string path, real sceneX, real sceneY) signal calendarRequested() - // The numbered list App.qml also gives the keys, so a badge and the key that - // opens the row it sits on cannot disagree. + // Invariant: the sidebar and keyboard router share one numbered row projection. property var slots: [] property bool numbersVisible: false - // The labels as a tree: a child indented under its parent, a parent that - // folds. Model.labelTree decides the shape; this draws it. readonly property var userLabels: root.service ? Model.labelTree(root.service.labels, root.service.collapsedFolders) : [] - // The rail's own edge. The list already draws one on its far side, so - // without this the icons sit on the same surface as the messages. PanelSeparator { id: edge anchors.right: parent.right @@ -76,19 +62,13 @@ Item { spacing: MailStyle.space(1) Repeater { - // The account's own list. A provider with no All mail must not be - // offered one, and an IMAP account's Flagged is not Gmail's Starred. + // Invariant: display only the resolved mailboxes supported by this account’s provider. model: root.service ? root.service.mailboxes : [] Entry { required property var modelData label: modelData.label icon: modelData.icon - // No count on the mailboxes. An inbox that is thousands of messages - // deep reports "999+" forever, which is a number that never changes - // and therefore says nothing. The bar's dot carries whether anything - // is waiting; the labels below still count, because those are lists - // the user built and their sizes mean something. count: 0 selected: !root.calendarSelected && !!root.service && root.service.mailboxKey === modelData.key @@ -125,10 +105,6 @@ Item { Entry { required property var modelData label: modelData.name - // One tag for every user label. An initial letter fails the moment a - // label is not written in the Latin alphabet — a Chinese label would - // put a single hanzi in a 16px slot, which is neither an icon nor a - // readable name. The tooltip carries the name instead. icon: modelData.selectable && !!root.service && (root.service.monitoredLabelIds || []).indexOf(modelData.id) >= 0 ? "eye" : "label" depth: modelData.depth @@ -157,7 +133,6 @@ Item { } } - // Calendar stays fixed at the foot of the rail while mailbox labels scroll. Column { id: footer anchors.left: parent.left @@ -179,8 +154,6 @@ Item { } - // One row: an icon that is always there, a name that appears when there is - // room, and a count that survives the collapse as a dot. component Entry: Rectangle { id: entry required property string label @@ -188,9 +161,6 @@ Item { property int count: 0 property bool selected: false property int slotNumber: 0 - // A label under another is stepped in one indent per level; a parent - // carries a chevron that folds its children. An ancestor no label names - // is drawn dim and opens nothing — tapping it folds instead. property int depth: 0 property bool foldable: false property bool expanded: true @@ -199,12 +169,9 @@ Item { signal activated() signal foldRequested() signal menuRequested(real sceneX, real sceneY) - // Watched for new mail: the row keeps its count in the accent even while - // it is not the one open, and the glyph says so. property bool monitored: false - // The badge names the key: Ctrl and the digit. A row past the ninth has - // no key and no badge — `Ctrl+0` is reset zoom, not a tenth row. + // Invariant: rows after the ninth have no digit shortcut; Ctrl+0 resets zoom. readonly property bool showsNumber: root.numbersVisible && slotNumber > 0 readonly property string numberText: String(slotNumber) @@ -229,8 +196,6 @@ Item { objectName: "mailbox-entry-icon" } - // The fold, at the end of the row so the name keeps its column. Its own - // tap target, so folding a parent does not also open it. Item { id: fold objectName: "fold" @@ -252,7 +217,6 @@ Item { TapHandler { onTapped: entry.foldRequested() } } - // Modifier hints sit above the icon at the corner of a collapsed row. Rectangle { id: slotChip objectName: "mailbox-shortcut-chip" @@ -265,9 +229,6 @@ Item { width: MailStyle.space(root.collapsed ? 10 : 16) height: width radius: Style.cornerRadius - // This names a shortcut; it is not another selected state layered over - // the selected mailbox row. The lighter normal fill stays legible on - // dark themes without becoming a stack of grey tabs on Lupine. color: Style.normalFillFor(root.textColor, root.accentColor) Text { @@ -325,9 +286,8 @@ Item { } HoverHandler { id: hover } - // The fold's handler sits inside this one and both see the same tap, - // so the row asks where it landed before opening anything: folding a - // parent must not also open it. + // Invariant: nested fold and row handlers see the same tap; folding must not also open the + // mailbox. TapHandler { onTapped: function(eventPoint) { var at = eventPoint.position @@ -344,8 +304,6 @@ Item { } } - // The tooltip is how the rail stays usable while collapsed, and it carries - // the count too, which the dot can only hint at. Widgets.PanelToolTip { objectName: "label-tooltip" visible: hover.hovered diff --git a/ui/components/MailboxTabs.qml b/ui/components/MailboxTabs.qml index eb29b3a38..a25b8fdb6 100644 --- a/ui/components/MailboxTabs.qml +++ b/ui/components/MailboxTabs.qml @@ -4,12 +4,7 @@ import "../settings" import QtQuick.Controls as QQC import qs.Commons import qs.Ui -import "../account/Model.js" as Model -// The mailboxes, as one row of chips. What they are depends on the provider — -// Gmail's are searches, so "Unread" and "All mail" sit next to "Inbox" without -// needing a different mechanism; an IMAP account's are folders. The account -// hands the list down already resolved, so this only draws it. Flickable { id: root @@ -17,8 +12,7 @@ Flickable { required property color accentColor required property string panelFontFamily property string current: "inbox" - // Provider-specific, and handed down rather than looked up: this row must - // never offer a mailbox the account on screen does not have. + // Invariant: only resolved mailboxes from the current account may become destinations. property var allMailboxes: [] property int unread: 0 property int cursorIndex: -1 @@ -26,8 +20,8 @@ Flickable { signal selected(string key) signal chipHovered(int index, bool isHovered) - // Keep every destination reachable, including folders excluded from search. - // Narrow windows scroll the row instead of hiding Archive, Junk and Trash. + // Invariant: overflow scrolls rather than hiding destinations, including folders excluded from + // search. readonly property var mailboxes: Array.isArray(root.allMailboxes) ? root.allMailboxes : [] width: parent ? parent.width : 0 @@ -66,13 +60,8 @@ Flickable { onCurrentChanged: Qt.callLater(revealCurrent) onWidthChanged: Qt.callLater(revealCurrent) - // One segmented control rather than loose chips. Separate chips left the - // selected one's fill floating at a different left edge from the logo above - // and the message text below; a single track has one edge, and that edge is - // the one everything else lines up on. Rectangle { id: track - // Centre when there is room; overflowing rows start at the left edge. x: Math.max(0, (root.width - width) / 2) width: chips.implicitWidth height: chips.implicitHeight @@ -98,8 +87,6 @@ Flickable { implicitWidth: chip.implicitWidth implicitHeight: chip.implicitHeight - // Segments share an edge instead of standing apart, so the row reads - // as one control with a current position. Rectangle { visible: segment.index > 0 width: 1 @@ -110,8 +97,6 @@ Flickable { Widgets.Button { id: chip anchors.fill: parent - // Only the unread mailbox carries a count: repeating it on Inbox - // says the same number twice, and the bar already says it once. text: segment.modelData.key === "unread" && root.unread > 0 ? segment.modelData.label + " " + root.unread : segment.modelData.label diff --git a/ui/components/Menu.js b/ui/components/Menu.js index 9d231355d..c1467bb7e 100644 --- a/ui/components/Menu.js +++ b/ui/components/Menu.js @@ -6,7 +6,7 @@ function selectable(entry) { function firstSelectable(entries) { var values = Array.isArray(entries) ? entries : [] - for (var i = 0; i < values.length; i++) if (selectable(values[i])) return i + for (var rowIndex = 0; rowIndex < values.length; rowIndex++) if (selectable(values[rowIndex])) return rowIndex return -1 } @@ -14,11 +14,11 @@ function nextSelectable(entries, current, step) { var values = Array.isArray(entries) ? entries : [] if (values.length === 0) return -1 var direction = Number(step) < 0 ? -1 : 1 - var at = Math.floor(Number(current)) - if (!isFinite(at) || at < 0 || at >= values.length) at = direction > 0 ? -1 : 0 - for (var i = 0; i < values.length; i++) { - at = (at + direction + values.length) % values.length - if (selectable(values[at])) return at + var selectedIndex = Math.floor(Number(current)) + if (!isFinite(selectedIndex) || selectedIndex < 0 || selectedIndex >= values.length) selectedIndex = direction > 0 ? -1 : 0 + for (var attempt = 0; attempt < values.length; attempt++) { + selectedIndex = (selectedIndex + direction + values.length) % values.length + if (selectable(values[selectedIndex])) return selectedIndex } return -1 } diff --git a/ui/components/MessageList.qml b/ui/components/MessageList.qml index 88791d887..5cc97b955 100644 --- a/ui/components/MessageList.qml +++ b/ui/components/MessageList.qml @@ -18,8 +18,7 @@ ListView { required property string panelFontFamily property string snoozeId: "" property string cursorId: "" - // The rows ticked for a bulk action, by id. Held above the list, like the - // cursor, because a reload rebuilds every row. + // Invariant: checked IDs live above recycled rows so list reloads preserve the selection. property var checkedIds: [] property bool ctrlHeld: false @@ -27,8 +26,8 @@ ListView { signal checkToggled(string id) signal checkRangeRequested(string id) signal agentRequested(string id, real sceneX, real sceneY) - // A row's own star, archive and trash buttons. Routed up rather than - // straight to the service so a ticked row's button means the selection. + // Invariant: route row actions through the window so an action on a checked row applies to the + // selection. signal snoozeRequested(string id, real sceneX, real sceneY) signal rowActionRequested(string id, string action) signal menuRequested(string id, real sceneX, real sceneY) @@ -72,18 +71,20 @@ ListView { delegate: MessageRow { width: root.width required property int index - // The array and its count change together, but a row's binding can be - // asked between the two; an empty summary for that instant draws an - // empty row rather than throwing on every field. + // Invariant: the summary array and count can update between bindings; recycled rows need an + // empty summary during that transition. readonly property var modelData: root.service.messages[index] || ({}) + readonly property var overviewDetails: root.service.inboxTools + ? root.service.inboxTools.overviewFor(modelData) : ({}) + attachmentIndicatorEnabled: !!root.service.backend && root.service.backend.ready && Number(root.service.backend.apiVersion) >= 8 snoozeOpen: root.snoozeId === modelData.id avatarData: root.service.inboxTools ? root.service.inboxTools.avatarFor(modelData) : "" - overview: root.service.inboxTools ? String(root.service.inboxTools.overviewFor(modelData).text || "") : "" - overviewReason: root.service.inboxTools ? (root.service.inboxTools.available === false ? (!root.service.backend || !root.service.backend.ready ? "mail backend is disconnected" : "backend update required") : String(root.service.inboxTools.overviewFor(modelData).reason || "")) : "" - overviewState: root.service.inboxTools ? (root.service.inboxTools.available === false ? "unavailable" : root.service.inboxTools.paused === true ? "paused" : String(root.service.inboxTools.overviewFor(modelData).state || "")) : "" + overview: root.service.inboxTools ? String(overviewDetails.text || "") : "" + overviewReason: root.service.inboxTools ? (root.service.inboxTools.available === false ? (!root.service.backend || !root.service.backend.ready ? "mail backend is disconnected" : "backend update required") : String(overviewDetails.reason || "")) : "" + overviewState: root.service.inboxTools ? (root.service.inboxTools.available === false ? "unavailable" : root.service.inboxTools.paused === true ? "paused" : String(overviewDetails.state || "")) : "" onUnreadRequested: root.rowActionRequested(modelData.id, "markUnread") onSnoozeRequested: function(x,y) { root.snoozeRequested(modelData.id,x,y) } summary: modelData @@ -124,8 +125,6 @@ ListView { textColor: root.textColor } - // Three states share this slot, and only one of them is an error: still - // loading, loaded and empty, or nothing loaded yet. Item { width: parent.width visible: root.service.messages.length === 0 @@ -146,13 +145,6 @@ ListView { } } - // Pagination is the only thing this footer needs to say. A result estimate - // promoted an unreliable server number into interface hierarchy it did not - // deserve, and repeated it again in the window status line. - // - // The next page is asked for as the list is scrolled to its foot, so the - // button is for the page that did not come — a refusal, a slow server — - // rather than the way every page is reached. Item { width: parent.width visible: root.service.hasMore @@ -191,8 +183,6 @@ ListView { function loadMoreSoon() { Qt.callLater(root.loadMoreIfAtFoot) } function continueAfterLoad(startCount) { - // MailAccount ends the loading state before it applies the summaries. - // Judge growth after that callback has finished, when the page is visible. Qt.callLater(function() { if (!root.service || root.service.messages.length <= startCount) return root.loadMoreIfAtFoot() diff --git a/ui/components/MessageMenu.qml b/ui/components/MessageMenu.qml index 636940113..30e44fbb8 100644 --- a/ui/components/MessageMenu.qml +++ b/ui/components/MessageMenu.qml @@ -6,9 +6,7 @@ import qs.Ui import "Menu.js" as Menu import "../account/Model.js" as Model -// The list's right-click menu. It is a Popup rather than a child of the row -// because the list scrolls inside a clipping Flickable, which would cut the -// menu off at the column edge. +// Invariant: the list’s clipping Flickable would cut off a child menu; use a popup. Item { id: root @@ -21,10 +19,8 @@ Item { required property string panelFontFamily property string messageId: "" - // Opened from a stop on the conversation rail rather than from a row. A stop - // is one message: its summary is among the account's member summaries, and - // what it asks for reaches that message alone, where a row's menu reaches - // every counted member of the conversation the row stands for. + // Invariant: a rail stop targets one member, while a conversation row targets its counted + // members. property bool memberOnly: false property real anchorX: 0 property real anchorY: 0 @@ -32,13 +28,8 @@ Item { readonly property var menuRows: [continueRow, replyRow, replyAllRow, forwardRow, archiveRow, unarchiveRow, moveRow, trashRow, spamRow, readRow, starRow, browserRow, aiRow] - // Whether this message is archived — out of the inbox and not somewhere - // that has its own verb. Read off the summary the menu was opened on rather - // than asked of the service, because the menu is about one message. IMAP - // synthesises all four of these from the folder, so one rule serves both - // kinds of provider. Spam counts as "its own verb" only where a spam verb - // exists: an IMAP Junk folder has no report-spam inverse to offer instead, - // so a Junk message there is the one spam case "Move to Inbox" still means. + // Invariant: spam has its own inverse only where the provider supports it; IMAP Junk otherwise + // remains eligible for Move to Inbox. readonly property var messageHost: !root.service ? null : typeof root.service.hostForId === "function" ? root.service.hostForId(root.messageId) : root.service @@ -49,10 +40,6 @@ Item { && root.summary.isSent !== true && root.summary.isDraft !== true - // Whether the list it was opened from is a label's, and whether that label - // is one a message can be taken out of — which is the same question - // `labelChangesFor` asks, so the wording cannot promise a removal that does - // not happen. readonly property bool inLabelView: !!root.service && !!root.service.hasLabels && String(root.service.rawLabelId || "") !== "" @@ -65,7 +52,6 @@ Item { for (var i = 0; i < list.length; i++) { if (list[i].id === messageId) return list[i] } - // A member the list drew no row for: the rail's own summaries. var members = service.memberSummaries if (members && typeof members === "object" && members[messageId]) return members[messageId] return null @@ -74,8 +60,6 @@ Item { signal agentRequested(string id, real sceneX, real sceneY) signal composeRequested(string mode, string id) signal actionRequested(string action, string id) - // The same two, from a menu opened on a rail stop, so the owner can keep the - // list cursor where it is and scope the action to the one message. signal memberComposeRequested(string mode, string id) signal memberActionRequested(string action, string id) @@ -182,25 +166,14 @@ Item { lineColor: root.textColor } - // Hidden rather than disabled where the provider has no such verb. IMAP - // archives by moving to a folder that may not exist, and has no junk - // verb the server learns anything from — a "Report spam" that quietly - // meant "move to a folder" would be a promise this cannot keep. MenuRow { id: archiveRow visible: (!root.service || root.service.canArchive) && !root.archived text: "Archive" onActivated: root.run("archive") } - // The other direction, and only where it would be the truth. - // - // `inInbox === false` alone put this row in Spam, Trash, Drafts and - // Sent, where adding INBOX is not what "move to the inbox" means: - // `labelChangesFor` removes neither SPAM nor TRASH, so a spam message - // would carry INBOX *and* SPAM and stay in Spam while the row claimed - // otherwise, and on IMAP the same press physically relocates a draft - // out of the Drafts folder. Spam has its own verb and trash has its own - // endpoint, for exactly this reason; archived mail is what is left. + // Invariant: adding INBOX does not remove SPAM or TRASH and can relocate IMAP drafts; this + // action applies only to archived mail. MenuRow { id: unarchiveRow visible: (!root.service || root.service.canArchive) && root.archived @@ -209,8 +182,6 @@ Item { } MenuRow { id: moveRow - // A member of a conversation is not a row the picker can move on - // its own; the row above it is. visible: !!root.service && root.service.canMoveToLabel && !root.memberOnly text: "Move to..." onActivated: root.run("moveToLabel") @@ -260,8 +231,6 @@ Item { } } - // Only where there is a web mailbox to open. An IMAP account has no - // address this plugin could know. MenuRow { id: browserRow visible: !root.service || root.service.canOpenOnWeb diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml index 89071b5e6..857138563 100644 --- a/ui/components/MessageReader.qml +++ b/ui/components/MessageReader.qml @@ -11,10 +11,8 @@ import "../message/Mailto.js" as Mailto import "../message/AttachmentPreview.js" as Preview import "../account/Model.js" as Model -// The right column. The body goes through Qt's own rich text engine — a real -// HTML renderer, not a browser — after Html.sanitize has removed what Qt would -// render badly and the remote images that would otherwise fire every tracking -// pixel in the message the instant it opens. +// Invariant: only sanitized message documents may reach Qt rich text; raw sender markup can fetch +// tracking or local-network resources. Item { id: root @@ -29,17 +27,10 @@ Item { required property real leadingBoundaryOverlap required property color dimmerColor required property string panelFontFamily - // Which of the three ways of reading a message this window is set to. The - // window's preference, not this message's: it may not be the one on screen, - // because a message can be too heavy to draw the chosen way. property string bodyMode: "reader" property real zoom: 1.0 property bool alwaysRenderHeavyMessages: false - // How the direction of a message's own text is arrived at: read off the text, - // or fixed by the reader. Not the direction itself — that is per message. property string contentDirection: Direction.MODE_DEFAULT - // Set by the reader itself when a document is too heavy to lay out, and - // cleared by the user asking for it anyway. property bool forceRichAnyway: false signal memberRequested(string id) @@ -52,39 +43,19 @@ Item { signal snoozeRequested(real sceneX, real sceneY) signal actionRequested(string action) signal agentRequested(real sceneX, real sceneY) - // A right-click on the From line or the To line: the addresses on it, and - // where the menu goes. What is done with them is the window's decision. signal addressMenuRequested(var addresses, real sceneX, real sceneY) - // Whether the agent popup is up for this message, and whether a job is - // running on it — passed down like every other fact the reader draws. property bool agentOpen: false property bool agentWorking: false property bool agentAttention: false - // ------------------------------------------------------- the conversation - // The rail down the right edge: every counted member of the open message's - // conversation, oldest first, as a stop that opens in this same reader. - // - // Drawn above the seam for any provider that collapses its listing, off the - // block the row was opened with — so a count of 0, which is what a provider - // that does not collapse reports and what HEY reports for rows that already - // are conversations, draws nothing at all. The account owns both decisions; - // this asks. readonly property bool showsRail: !!service && service.showsRail === true readonly property var conversationStops: !root.showsRail ? [] : (service.conversationProjection ? service.conversationProjection.stops || [] : []) readonly property string conversationCaption: !root.showsRail ? "" : (service.conversationProjection ? service.conversationProjection.caption || "" : "") - // The member the rail should have on screen, revealed with the smallest - // scroll — the list cursor's rule. Watched rather than called from the click, - // because `n` and `p` move the reader from the keyboard and a stop opened - // from off the bottom of the rail has to come into view either way. - // - // Deferred a turn: a conversation opened for the first time changes the stops - // and lays them out in the same frame, and a scroll computed before the - // Column has heights is a scroll to the wrong place. + // Invariant: defer rail scrolling until the new conversation’s Column has laid out its stops. onConversationStopsChanged: if (root.showsRail) Qt.callLater(root.revealOpenStop) function revealOpenStop() { if (root.showsRail && root.service) rail.reveal(root.service.selectedId) @@ -137,12 +108,8 @@ Item { readonly property var summary: service ? service.selectedMessage : null readonly property bool isDraft: !!summary && summary.isDraft === true - // The id the service answers to, which is not always the one on the summary. - // A list made of several mailboxes addresses a row by mailbox and id, and the - // account that owns the message only ever knows its own half of that — so a - // call made with the summary's own id reaches no mailbox at all. This is the - // composed id where there is one and the same string everywhere else, which - // is what the list and the compose view already hand back. + // Invariant: use the service’s composed selection ID; a provider-local summary ID can address the + // wrong mailbox in unified views. readonly property string selectedId: service ? String(service.selectedId || "") : "" readonly property var attachments: service ? service.selectedAttachments || [] : [] @@ -221,67 +188,36 @@ Item { attachmentFlick.contentX = Math.max(0, right - attachmentFlick.width) } - // Which way this message runs. - // - // The subject is asked separately from the body, and not as an optimisation: - // they can disagree honestly. A reply prefix is Latin whatever the thread is - // written in, so `Re: مرحبا` needs the prefix set aside before the question - // is asked, while the body has no such wrapper around it. - // - // The body is read from the message's plain text rather than from its markup. - // That is the same text in all three view modes, so switching between them - // never changes which way the message reads — and it is the message's own - // words rather than a template's, which is what the direction is a fact - // about. - // - // What comes back is the document's base direction, which a sender's own - // `dir` still overrides element by element. It is a default for the parts of - // the message that state nothing, not a ruling over the parts that do. + // Invariant: subject and body direction are independent; sender element-level direction remains + // authoritative. readonly property string subjectDirection: Direction.forced(root.contentDirection) || String(root.summary ? root.summary.subjectDirection || "" : "") readonly property string bodyDirection: Direction.forced(root.contentDirection) || String(root.service && root.service.selectedBody ? root.service.selectedBody.bodyDirection || "" : "") - // The header lines below the subject carry a name, an address and a date, all - // of which Qt lays out correctly from their own first strong character. There - // is nothing to add on Auto, and a chosen direction still has to reach them. readonly property string headerDirection: Direction.forced(root.contentDirection) - // `undefined` rather than a default: a `Text` whose alignment is never set - // follows the direction of its own text, and that is the behaviour to leave - // in place wherever there is no answer to give it. Assigning Qt's own default - // back would render the same and would be one more thing to keep true. + // Invariant: undefined alignment preserves Qt’s first-strong-character default when no direction + // is forced. readonly property var subjectAlignment: Direction.hasAnswer(root.subjectDirection) ? (Direction.isRightToLeft(root.subjectDirection) ? Text.AlignRight : Text.AlignLeft) : undefined readonly property var headerAlignment: Direction.hasAnswer(root.headerDirection) ? (Direction.isRightToLeft(root.headerDirection) ? Text.AlignRight : Text.AlignLeft) : undefined - // Already sanitised by the service, remote images and all removed. Qt's rich - // text engine fetches an for real, so leaving them in - // would fire every tracking pixel in the message the instant it opened, and - // would let a crafted one aim a request at whatever is listening on this - // machine. They come back only when the reader asks, for this message alone. + // Invariant: Qt rich text fetches remote img sources; only explicitly prepared raster bytes may + // restore blocked images. readonly property bool hasHtml: !!service && !!service.selectedHasHtml - // The parsed form of the same document. Fitting it to this window is done on - // the way out, so this is rebuilt on every relayout without being reparsed. + // Performance: relayout reuses the parsed document rather than reparsing sender HTML. readonly property var bodyDocument: service ? service.selectedDocument : null - // The same message rebuilt for reading: paragraphs, headings, lists and - // links, with none of the sender's presentation in it. Built beside the one - // above off the same parse, so changing mode costs neither a fetch nor a - // reparse — which is also why all three are available at once here. + // Performance: all reading modes share one parse and require neither refetch nor reparse when + // switched. readonly property var readerDocument: service ? service.selectedReaderDocument : null - // The blocked pictures of the reading actually on screen. Reading mode - // shows fewer of a sender's images than the sanitised document does, and a - // notice that counted the other one's would offer to load what is not there. readonly property int remoteImages: !service ? 0 : root.shownMode === "reader" ? service.selectedReaderRemoteImages : service.selectedRemoteImages readonly property bool remoteImagesAllowed: !!service && service.remoteImagesAllowed - // What this message can actually be drawn as, which is the question - // `Html.resolveBodyMode` answers the chosen mode against. `forced` is the - // reader having insisted on a document the bounds refused. readonly property var bodyOffer: ({ html: root.hasHtml, reader: !!root.readerDocument && !!root.service && !root.service.selectedReaderEmpty, @@ -289,58 +225,36 @@ Item { originalHeavy: !!root.service && root.service.selectedTooHeavy, forced: root.alwaysRenderHeavyMessages || root.forceRichAnyway }) - // The mode on screen, which is the chosen one unless this message cannot be - // drawn that way. readonly property string shownMode: Html.resolveBodyMode(root.bodyMode, root.bodyOffer) readonly property bool richBody: root.shownMode !== "plain" - // Plain text nobody asked for, which is one of the two the notices explain. readonly property bool tooHeavy: Html.bodyModeRefused(root.bodyMode, root.bodyOffer) - // And the other: reading was asked for and there was nothing to rebuild. readonly property bool readingEmpty: Html.bodyModeEmptied(root.bodyMode, root.bodyOffer) - // Empty for everything that is not a mailing list. The label carries its own - // trailing "..." when the only way off this list is a page in a browser, - // because that is the same decision as which way off it there is — and the - // service is where it is made. readonly property string unsubscribeLabel: service ? service.unsubscribeLabel : "" readonly property string unsubscribeDetail: service ? service.unsubscribeDetail : "" readonly property bool unsubscribing: !!service && service.unsubscribing - // Image markers only mean something when the plain text was made from the - // HTML: a message that shipped its own text/plain part never had images in - // it, and anything looking like a marker there is the sender's own words. + // Invariant: image markers apply only to HTML-derived plain text; a native text/plain marker is + // literal sender content. readonly property string bodySource: service && service.selectedBody ? String(service.selectedBody.source || "") : "" readonly property var imageSources: service ? service.selectedImages : [] - // At a narrow window the reader gives up most of its own gutter, and the - // sender's horizontal padding is stripped as well. Keyed off the flickable's - // width rather than the text's, so the inset cannot feed back into itself. + // Invariant: the inset depends on the Flickable width, not the resulting text width, to avoid a + // layout feedback loop. readonly property bool narrowBody: bodyFlick.width > 0 && bodyFlick.width < MailStyle.space(420) - // One inset for the whole page. Giving the body a narrower one bought a few - // pixels and cost the alignment: the message text started to the left of the - // subject above it and the toolbar below, which reads as a mistake long - // before it reads as extra room. The space is reclaimed from the sender's own - // padding instead, which is where it was being wasted. readonly property int pageInset: narrowBody ? MailStyle.space(8) : MailStyle.space(14) readonly property int bodyInset: pageInset readonly property int bodyWidth: Math.max(80, bodyFlick.width - bodyInset * 2) - // Zoom changes the message type without changing the surrounding chrome. readonly property int bodyFontSize: Math.max(7, Math.round(MailStyle.messageSize * root.zoom)) - // All three modes share the same maximum; narrow panels use what fits. readonly property int contentWidthLimit: Html.readingColumnWidth(root.bodyWidth, MailStyle.space(800)) readonly property int preferredBodyWidth: root.shownMode === "original" ? Html.preferredContentWidth(root.bodyDocument, root.contentWidthLimit) : root.contentWidthLimit - // Reading mode centres its column in whatever the panel has spare. The other - // two start at the page inset, because the sender's own layout and a - // plain-text body both begin at the left edge. readonly property int bodyOffset: root.shownMode === "reader" ? Html.readingColumnOffset(root.bodyWidth, root.preferredBodyWidth) : 0 - // Quantised, because this is a dependency of the document itself: bound to - // the exact width, dragging the splitter would rebuild and re-lay-out the - // whole message on every frame. + // Performance: quantize render width so splitter drags do not rebuild the document every frame. readonly property int imageWidth: Math.round(root.preferredBodyWidth / 20) * 20 ReaderBlankSlate { @@ -354,8 +268,6 @@ Item { panelFontFamily: root.panelFontFamily } - // Nothing known at all, which after the reader learned to open on the list's - // own row is only a message that is not in the list. ReaderSkeleton { anchors.fill: parent visible: !root.summary && !!root.service && root.service.detailLoading @@ -363,14 +275,6 @@ Item { panelFontFamily: root.panelFontFamily } - // The headers are known and the body is not, which is every message being - // opened for the first time. Over the body alone, so the sender and the - // subject stay readable while it arrives — a whole-reader skeleton would - // hide the very thing that just became available. - // - // `z` rather than declaration order: this has to sit above the body it - // stands in for, and being above it should not depend on where in the file - // the two happen to be written. ReaderSkeleton { anchors.fill: bodyFlick z: 1 @@ -380,7 +284,6 @@ Item { panelFontFamily: root.panelFontFamily } - // --------------------------------------------------------------- headers Item { id: headerBlock @@ -451,9 +354,8 @@ Item { id: subjectLine objectName: "reader-subject" width: parent.width - // A stranger wrote this. Qt's default AutoText switches a string that - // looks like markup into rich text, and rich text with an in it is - // a fetch — the same beacon the message body is stripped of. + // Invariant: sender-controlled headers must remain plain text to prevent Qt resource + // loading. textFormat: Text.PlainText text: root.summary ? root.summary.subject : "" color: root.textColor @@ -468,8 +370,6 @@ Item { acceptedButtons: Qt.RightButton onTapped: function(eventPoint) { if (!root.summary) return - // Anchor to the line's own lower edge, not the pointer, so the menu - // lands in the same place however the line was pressed. var scene = subjectLine.mapToGlobal(0, subjectLine.height) subjectMenu.openAt(root.summary.subject, scene.x, scene.y) } @@ -499,8 +399,6 @@ Item { } } - // Everyone the message went to — To, Cc and Bcc, which a sent message - // carries — so a right-click on the line can name any of them. Text { id: toLine width: parent.width @@ -527,20 +425,11 @@ Item { } } - // ------------------------------------------------------------------ rail - // The rail keeps its width against the body rather than shrinking with it, so - // there is a pane width at which the two of them together leave the message - // nothing. That width is not a designed layout: it is where the reader has - // already replaced the list, and the fallback if this proves too tight is the - // prototype's variant A — lines under the header — rather than a rail three - // words wide. Until then the rail simply goes, and nothing else moves. + // Invariant: hide the fixed-width conversation rail when it would leave the body below its + // minimum reading width. readonly property bool fitsRail: width >= rail.implicitWidth + MailStyle.space(260) - // From the header's bottom edge to the footer, its own scroll owner beside - // the body — the way the list is beside the reader. It takes width and never - // height: the message keeps its reading measure and a long conversation - // scrolls inside the rail rather than lengthening the page. ConversationRail { id: rail objectName: "conversationRail" @@ -564,13 +453,7 @@ Item { } } - // --------------------------------------------------------------- notices - // Why this message does not look the way its sender meant it to, and the one - // thing that would change that. A column rather than a chain of anchors: - // three of these can be up at once, and each anchoring to whichever of the - // others happened to be visible is a rule that has to be rewritten every - // time a fourth is added. Column { id: notices anchors.top: headerBlock.bottom @@ -578,8 +461,6 @@ Item { anchors.right: rail.visible ? rail.left : parent.right anchors.leftMargin: root.pageInset anchors.rightMargin: root.pageInset - // No gap where there is nothing to separate. An empty Column is zero high, - // and a margin above it would still push the message down. anchors.topMargin: height > 0 ? MailStyle.space(8) : 0 spacing: MailStyle.space(6) @@ -605,13 +486,7 @@ Item { panelFontFamily: root.panelFontFamily } - // A message with nothing in it is a real answer, and an empty reader on its - // own does not look like one — it looks like something failed. HEY's own - // sign-up mail is the case this exists for: the CLI serves those threads - // with no body at all, so there is genuinely nothing to draw. - // - // Waits for the read to be done before saying it, because "no text" is only - // true once nothing more is coming. + // Invariant: an empty-body notice is valid only after detail loading has finished. ReaderNotice { width: parent.width visible: !!root.summary && !!root.service @@ -619,8 +494,6 @@ Item { && root.bodySource === "" && !root.hasHtml && (root.service.selectedAttachments || []).length === 0 text: "This message has no text to show" - // Only where there is somewhere to go and read it. The service decides - // that, and the "..." is there because what it opens is a browser. actionLabel: !root.service || root.service.canOpenOnWeb ? "Open on the web..." : "" textColor: root.textColor dimColor: root.dimColor @@ -629,18 +502,12 @@ Item { onActivated: if (root.service && root.summary) root.service.openInBrowser(root.selectedId) } - // Under the heavy-document notice when both are up: one says why the - // message looks plain, the other why it looks bare, and they are different - // answers to different questions. ReaderNotice { width: parent.width visible: !!root.summary && root.richBody && !root.remoteImagesAllowed && root.remoteImages > 0 text: (root.remoteImages === 1 ? "1 image is blocked" : root.remoteImages + " images are blocked") + ": loading them tells the sender this message was opened" - // What the button does is turn them on for every message, and Settings - // is where that is turned back off — so it says "always" rather than - // letting somebody find out afterwards. actionLabel: "Always show" textColor: root.textColor dimColor: root.dimColor @@ -649,15 +516,8 @@ Item { onActivated: if (root.service) root.service.showRemoteImages() } - // Last of the three, because it is the only one that is not about how the - // message is being drawn. The label carries its own "..." when what it - // opens is a browser — the service decides that, since it is the same - // decision as which of the three ways off a list this sender offers. ReaderNotice { width: parent.width - // Stays up after the deed is done, saying what was done. A control that - // vanishes under the pointer reads as a misclick, and "did that work?" - // is a question the user may come back to this message to ask. visible: !!root.summary && root.unsubscribeDetail !== "" text: root.unsubscribeDetail actionLabel: root.unsubscribeLabel @@ -671,7 +531,6 @@ Item { } } - // ------------------------------------------------------------------ body Flickable { id: bodyFlick @@ -680,7 +539,6 @@ Item { WheelScroller { view: bodyFlick } anchors.top: notices.bottom anchors.left: parent.left - // The content limit uses the space remaining beside the conversation rail. anchors.right: rail.visible ? rail.left : parent.right anchors.bottom: footerBackdrop.visible ? footerBackdrop.top : parent.bottom contentWidth: width @@ -690,16 +548,11 @@ Item { visible: !!root.summary ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } - // The meeting in the message, drawn as a meeting. Inside the flickable - // rather than pinned above it: a recurring invitation with a dozen guests - // is taller than the panel, and a card that cannot scroll would leave the - // message itself with nowhere to be. + // Invariant: invitation cards must scroll with the message; long guest lists can exceed the + // viewport. InviteCard { id: inviteCard objectName: "eventCard" - // This is application UI built from the calendar part, not content from - // the sender's HTML. Reader mode narrows the mail below it, while this - // card keeps the panel's full content width in every mode. x: root.bodyInset y: MailStyle.space(24) width: root.bodyWidth @@ -718,13 +571,9 @@ Item { if (root.service) root.service.rsvp(answer) } onMailOnlyRequested: function(answer) { if (root.service) root.service.rsvpMailOnly(answer) } - // The same rule the body's own links obey: this leaves the app, and it - // leaves it through the desktop's browser rather than anything here. onOpenRequested: function(url) { root.openLink(url) } } - // What the agent found in the message, if the owner asked it to look: - // a card per event, with the calendar's composer one press away. EventSuggestionCard { id: suggestionCard objectName: "eventSuggestions" @@ -753,15 +602,9 @@ Item { readOnly: true selectByMouse: true wrapMode: TextEdit.Wrap - // Rich text for all three, because all three are documents by the time - // they get here. textFormat: TextEdit.RichText - // Three documents, one parse. The reading one was rebuilt out of what the - // message says and carries no sender markup at all; the formatted one is - // the sender's own, sanitised; the plain one is built here from escaped - // text, line breaks and marker links and nothing else, so it stays cheap - // to lay out even for the messages whose own markup was too heavy to draw - // in the first place. + // Invariant: formatted/reader documents are sanitized; plain mode is built only from escaped + // text and image markers. text: root.shownMode === "reader" ? Html.readerDocumentFor(root.readerDocument, ({ foreground: root.textColor, @@ -794,28 +637,21 @@ Item { selectionColor: Style.selectionFillFor(root.textColor, root.accentColor) selectedTextColor: root.textColor font.family: MailStyle.messageFamily - // Body text, where the chrome around it is bodySmall: this is the one - // long-form thing in the window and the only one that is read rather than - // scanned. At bodySmall it was 11px against the 9pt — twelve — of the - // terminal beside it, so the message was the smallest text on a screen - // whose owner had already said what size they read at. font.pixelSize: root.bodyFontSize onLinkActivated: function(link) { var image = Html.imageLinkIndex(link) if (image > 0) { var sources = root.imageSources - // The marker names the sender's src. Qt must not fetch that URL - // itself: the account prepares raster bytes, or the popover refuses. + // Invariant: an image marker must never hand a sender URL to Qt; the account supplies + // prepared raster bytes. if (image <= sources.length) root.openImageMarker(sources[image - 1]) return } root.openLink(link) } - // Only the right button, so selecting text still works: the left one - // passes through to the TextEdit. The hover half turns the I-beam into - // a hand while a link is under the pointer; the press half opens the - // text menu, naming the link the click landed on if there is one. + // Invariant: only right-button presses are intercepted so normal TextEdit selection remains + // available. MouseArea { anchors.fill: parent acceptedButtons: Qt.RightButton @@ -836,18 +672,14 @@ Item { } } - // ---------------------------------------------------------------- footer - // The toolbar sits on its own ground rather than on whatever happens to be - // scrolled behind it. Transparent, the message ran underneath the icons and - // through the rule, which read as text overlapping the controls. + // Invariant: the footer needs an opaque surface to prevent scrolled message text overlapping + // controls. Rectangle { id: footerBackdrop anchors.left: parent.left - // The reader begins after the splitter's forgiving hit target, while its - // visible rule sits at that target's leading edge. Extend only the surface - // boundary across the gap so the two rules meet; footer content remains - // aligned inside the reader and the splitter stays above it for input. + // Invariant: extend only the footer’s surface across the splitter hit target; preserve aligned + // content and splitter input. anchors.leftMargin: -root.leadingBoundaryOverlap anchors.right: parent.right anchors.bottom: parent.bottom @@ -855,8 +687,6 @@ Item { color: root.backgroundColor visible: footer.visible - // Edge to edge, not inset with the buttons: it separates the toolbar from - // the message, and that division runs the full width of the window. PanelSeparator { anchors.left: parent.left anchors.right: parent.right @@ -870,9 +700,6 @@ Item { anchors.bottom: parent.bottom anchors.left: parent.left anchors.right: parent.right - // Control frames share the status bar's eight-pixel chrome inset. The - // page content keeps its wider reading inset; applying that to buttons as - // well made their glyphs sit visibly farther inward than the chrome below. anchors.leftMargin: MailStyle.space(8) anchors.rightMargin: MailStyle.space(8) anchors.bottomMargin: MailStyle.space(4) @@ -955,20 +782,11 @@ Item { } } - // Icons rather than labels: six actions fit where six words would not. - // - // Split in two. What you do to the message — answer it, file it, throw it - // away — sits on the left where reading ends. How you look at it is not - // something you do to it, so it goes to the far right, out of the path of - // the actions that change something. Item { id: actionsRow objectName: "readerToolbar" width: parent.width - // The mode picker takes its own line when the two of them will not fit - // across the panel. A row of controls that overlaps another row of - // controls is worse than a taller toolbar, and the reader can be as - // narrow as its own minimum beside the list. + // Invariant: put the mode picker on a separate line when both control groups cannot fit. readonly property bool stacked: messageActions.visible && messageActions.implicitWidth + viewTools.implicitWidth + MailStyle.space(24) > width implicitHeight: stacked @@ -1013,15 +831,8 @@ Item { onClicked: root.composeRequested("forward") } - // Answering a message and disposing of one are different intentions, and - // one of them cannot be undone from here. The gap is wide enough that a - // hand aiming at Forward cannot land on Archive. - // - // As tall as the buttons it stands between, taken from one of them rather - // than from a constant: IconButton sizes itself from its icon, so a hard - // number drifts. A one-pixel-high item in a Row aligns to the row's top - // edge, which left the rule floating above the icons instead of level - // with them. + // Invariant: keep destructive actions separated from reply/forward, with separator height + // derived from the buttons. Item { id: actionGap x: forwardButton.x + forwardButton.width + messageActions.gap @@ -1038,9 +849,7 @@ Item { } } - // No archive button where the account has nowhere to archive to. On - // IMAP that is a move to a folder, and a server without one would have - // this quietly do nothing — or worse, delete. + // Invariant: an account with no archive capability must not expose the archive action. IconButton { iconSize: Style.font.icon * 2.5 id: archiveButton @@ -1051,8 +860,6 @@ Item { foreground: root.dimColor; hoverColor: root.textColor; fontFamily: root.panelFontFamily onClicked: root.actionRequested("archive") } - // Archive under a label, or move to a folder: the same picker `v` - // opens, one press away in the reader too. IconButton { iconSize: Style.font.icon * 2.5 id: moveButton @@ -1082,19 +889,8 @@ Item { } - // The distance across the bar is the separation here, so these need no rule - // of their own. - // - // Named rather than iconed. There is no drawing that says "the message as - // its sender laid it out" and is not a guess of one, and telling the three - // apart is the whole point of having them — so they say what they are, and - // the one in use wears the kit's selected surface and its border rather - // than only a colour. - // - // In a slot rather than anchored itself, because it sits beside the actions - // at a comfortable width and under them at a narrow one, and an anchor - // cannot be two things. The slot is what holds the position, so no binding - // in here reads the Row's own height while the Row is still deciding it. + // Invariant: the mode-picker slot owns placement; reading the Row’s own unresolved height + // creates a binding loop. Item { id: viewTools objectName: "readerViewTools" @@ -1110,9 +906,6 @@ Item { || Math.abs((modeTrack.y + modeTrack.height / 2) - (openWebButton.y + openWebButton.height / 2)) < 1 - // Three names for one setting, so they share a track, an outside edge - // and the seams between them. The selected fill belongs to one segment - // of one control rather than to a loose button beside two others. Rectangle { id: modeTrack objectName: "bodyModeTrack" @@ -1148,8 +941,6 @@ Item { } } - // A separate action on the same toolbar. Its centre follows the mode - // control's centre even where their natural heights differ. IconButton { iconSize: Style.font.icon * 2.5 id: openWebButton @@ -1167,16 +958,11 @@ Item { } } - // One of the three ways of reading a message. `selected` is the window's - // choice rather than what is on screen: a message too heavy to draw the - // chosen way says so in its own notice, and a picker that quietly moved to - // the mode it fell back to would leave nothing saying the choice still - // stands for the next message. + // Invariant: the picker retains the user’s requested mode when a heavy message temporarily falls + // back. component ModeButton: Widgets.Button { required property string mode property bool firstSegment: false - // Nothing to choose between where there is no markup: the text is then the - // message rather than one reading of it. visible: root.hasHtml selected: root.bodyMode === mode bordered: false @@ -1196,8 +982,6 @@ Item { } } - // The body's own menu: Copy, and the link under the pointer. Placed here - // rather than in App so the menu can be tested with the body it reads. TextMenu { id: textMenu objectName: "reader-text-menu" @@ -1211,8 +995,6 @@ Item { onOpenLinkRequested: function(url) { root.openLink(url) } } - // The subject's own menu: one row, the subject as written. Beside the - // body's menu for the same reason that menu lives here. SubjectMenu { id: subjectMenu objectName: "reader-subject-menu" diff --git a/ui/components/ReaderBlankSlate.qml b/ui/components/ReaderBlankSlate.qml index 731b6c759..ea9db833f 100644 --- a/ui/components/ReaderBlankSlate.qml +++ b/ui/components/ReaderBlankSlate.qml @@ -6,12 +6,6 @@ import "../account/Model.js" as Model import "../providers/Registry.js" as Provider import "../keys/Keymap.js" as Keymap -// What the reader shows before a message is picked. -// -// An empty pane is a chance to teach, not to decorate: this says which mailbox -// is open and how much is in it, then lists the keys that do something right -// now. Everything here is either state the user wanted to know or a shortcut -// they can use without moving the pointer. Item { id: root @@ -28,17 +22,13 @@ Item { : (service ? Provider.mailboxFor(service.providerId, service.mailboxKey).label : "Inbox") readonly property bool empty: !!service && service.listLoaded && service.messages.length === 0 - // The legend is the first thing to go when the pane gets tight: the heading - // above it is the part that carries information. readonly property bool showLegend: height > MailStyle.space(300) && width > MailStyle.space(320) readonly property string versionText: !!service && service.version ? String(service.pluginName || "Magpie") + " " + String(service.version) : "" - // The column above is centred, so what is left under it is half the leftover - // height — and that has to hold the label, its margin, and a gap wide enough - // that the two do not read as one block. A constant threshold cannot do this: - // the column is more than twice as tall with the shortcut legend as without. + // Invariant: available space below the centered column controls version visibility; a fixed + // threshold overlaps the variable-height legend. readonly property bool showVersion: versionText !== "" && (height - centeredColumn.height) / 2 >= versionLabel.implicitHeight + MailStyle.space(12) + MailStyle.space(12) @@ -160,9 +150,6 @@ Item { } } - // Not part of the column above: the legend hides itself on a narrow pane and - // the version has no reason to move when it does. Quietest thing on screen — - // it is there to be found, not read. Text { id: versionLabel objectName: "reader-version" diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index 9009c33cf..922494ca0 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -9,14 +9,6 @@ import "../settings/Appearance.js" as Appearance import "../message/Html.js" as Html import "../account/Accounts.js" as Accounts -// Where mailboxes are managed. -// -// Adding one used to drop the user on the first-run walkthrough, which by then -// had nothing left to ask: the client was connected and an account was already -// signed in, so the page showed a finished setup for the *other* mailbox and -// there was no way forward. Adding a mailbox belongs here, next to the ones -// that already exist, and signing it in happens on its own row rather than by -// sending the window somewhere else. Column { id: root @@ -35,16 +27,12 @@ Column { signal calendarSignInRequested(int index) readonly property var accounts: service ? service.accountSummaries : [] - // A separate list on purpose: accountSummaries carries live mailbox state and - // is replaced on a poll, which would rebuild the field being typed in. + // Invariant: live account summaries change during polling; a stable signature list preserves the + // field being edited. readonly property var signatureAccounts: service && Array.isArray(service.accountSignatures) ? service.accountSignatures : [] property string selectedSignatureAccountId: "" - // The page's sections and where each begins, for the rail beside it. Read - // off the headings themselves, so a section that grows moves the ones - // below it in the rail's map as well as on screen. The calendars section - // is a component with its own heading, so its top stands in. readonly property var sections: { var values = [{ key: "display", title: "Layout and fonts", y: displaySettings.y }, { key: "backend", title: "Mail backend", y: backendSetup.y }] if (!root.service || root.service.hasTray !== false) @@ -70,31 +58,19 @@ Column { return null } - function signatureOptions() { - var out = [] - for (var i = 0; i < signatureAccounts.length; i++) - out.push({ value: signatureAccounts[i].id, label: signatureAccounts[i].email }) - return out - } + readonly property var accountOptions: signatureAccounts.map(function(account) { + return { value: account.id, label: account.email } + }) property string selectedNameAccountId: "" - function nameOptions() { - var out = [] - for (var i = 0; i < signatureAccounts.length; i++) - out.push({ value: signatureAccounts[i].id, label: signatureAccounts[i].email }) - return out - } - function saveName() { if (service && selectedNameAccountId !== "") service.setAccountLabel(selectedNameAccountId, nameEdit.text) } - // Whether the selected mailbox takes its From name from here. The others - // are named by their server, and a field that changed nothing on the sent - // message would be a promise the page could not keep. So would one on a - // backend too old to write the name. + // Invariant: sender-name controls require both provider support and the backend revision that + // writes them. readonly property bool senderNameEditable: { var entry = signatureAccount(selectedNameAccountId) return !!(service && service.backendCanNameSender && entry @@ -130,7 +106,6 @@ Column { showNameAccount(signatureAccount(activeId) || signatureAccounts[0]) } - // The imported markup for the selected mailbox, and the import in flight. readonly property string selectedSignatureHtml: { var entry = signatureAccount(selectedSignatureAccountId) return entry ? String(entry.signatureHtml || "") : "" @@ -267,9 +242,8 @@ Column { ensureSignatureAccount() ensureNameAccount() } - // The page is built with the window, before `service` is bound, and either - // half of the answer can change from a terminal while the window is open — - // so ask whenever the page comes into view, not once. + // Invariant: the service is bound after construction and default-mail settings can change + // externally; refresh when the page becomes visible. function refreshDefaultMailClient() { if (visible && service && typeof service.refreshDefaultMailClient === "function") service.refreshDefaultMailClient() @@ -317,10 +291,6 @@ Column { font.bold: true } - // ------------------------------------------------------------ appearance - // - // Standalone only. The plugin's palette is the shell's, and the row would - // have nothing to change. Text { id: appearanceHeading @@ -392,7 +362,6 @@ Column { } } - // ------------------------------------------------------------------- bar Text { id: barHeading @@ -431,10 +400,6 @@ Column { textFormat: Text.PlainText } - // Says what turning it off costs, and what it does not: mail is still - // checked and still notifies. The keybinding is the part worth naming, - // because without one the window is only reachable from a terminal — - // which is true, and is why this does not claim there is no way back. Text { width: parent.width text: "Mail is still checked and still notifies; only the envelope goes. " @@ -472,11 +437,6 @@ Column { } } - // --------------------------------------------------- default mail client - // - // Omarchy opens HEY's web app on SUPER+SHIFT+E, and mailto: links go to - // whatever claimed them. scripts/default-mail.sh moves both, and undoing it - // gives the key back to Omarchy. Text { id: mailClientHeading @@ -562,7 +522,6 @@ Column { } } - // --------------------------------------------------------------- reading Text { id: readingHeading @@ -599,8 +558,6 @@ Column { Text { width: parent.width - // The cost, in the words of what it actually tells whom. Off, the - // reader asks about each message and the answer covers that one. text: "Loading an image tells its host that this address opened the " + "message, and when" color: root.dimColor @@ -622,8 +579,6 @@ Column { } } - // Showing a message as the cursor reaches it, and the dwell that keeps that - // from reading a mailbox by holding an arrow key down. Rectangle { width: parent.width implicitHeight: Math.max(heavyText.implicitHeight, heavySwitch.implicitHeight) @@ -697,9 +652,6 @@ Column { Text { width: parent.width - // Says what Auto does rather than only naming it: a reader whose mail - // is already laid out correctly has no way to tell whether that is the - // setting working or the setting being unnecessary. text: "Auto reads it from the message's own text. The interface is unaffected." color: root.dimColor font.family: root.panelFontFamily @@ -708,8 +660,6 @@ Column { } } - // Three names for one setting, sharing a track and the seams between them, - // the way the reader's own view modes do. Rectangle { id: directionTrack objectName: "contentDirectionTrack" @@ -727,9 +677,8 @@ Column { id: directionSegments spacing: 0 - // The labels are the stored values: the shell hands a plugin the words - // the schema lists rather than a key behind them, so spelling them - // anywhere but Direction.js would be a second place to keep them right. + // Invariant: the shell persists direction labels as values, so use the canonical Direction + // constants. DirectionButton { text: Direction.AUTO; mode: Direction.AUTO; firstSegment: true } @@ -750,9 +699,8 @@ Column { panelFontFamily: root.panelFontFamily } - // A look at every message opened, on the owner's behalf. Off until it is - // turned on, because the message text leaves the window for the system - // AI; the switch says in a word which way it stands. + // Invariant: event suggestions send message text to the selected AI, so they require explicit + // opt-in. Rectangle { objectName: "settings-suggest-events" visible: !!root.service && root.service.hasAgent !== false @@ -792,7 +740,6 @@ Column { textFormat: Text.PlainText } - // Availability follows the connected backend's API, not release labels. Text { objectName: "suggestEventsNeedsUpdate" width: parent.width @@ -833,7 +780,6 @@ Column { } } - // -------------------------------------------------------- notifications Text { id: notificationsHeading @@ -907,7 +853,6 @@ Column { textFormat: Text.PlainText } - // --------------------------------------------------------------- writing Text { id: writingHeading @@ -972,16 +917,10 @@ Column { } } - // A signature signs a mailbox, not a window. Only the selected mailbox is - // expanded here: a long account list should not turn Writing into a stack of - // editors, and switching is an explicit answer to which identity is edited. Column { objectName: "settings-signature-section" width: parent.width spacing: MailStyle.space(2) - // The heading and the note below belong to the fields. With no mailbox - // signed in there are none, and first run would otherwise show an - // explanation with nothing between it and the heading. visible: root.signatureAccounts.length > 0 Text { @@ -998,7 +937,7 @@ Column { width: parent.width showLabel: false value: root.selectedSignatureAccountId - options: root.signatureOptions() + options: root.accountOptions foreground: root.textColor accent: root.accentColor fontFamily: root.panelFontFamily @@ -1012,9 +951,8 @@ Column { radius: Style.cornerRadius color: Style.normalFillFor(root.textColor, root.accentColor) - // The padding is part of the field visually, so it is part of its click - // target too. Kept behind the editor so clicks on text still place the - // cursor normally. + // Invariant: place the padding click target behind the editor to preserve normal cursor + // placement. MouseArea { anchors.fill: parent onClicked: signatureEdit.forceActiveFocus() @@ -1035,8 +973,7 @@ Column { font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall - // The editor survives account-list updates and routine mailbox polls. - // Its text changes only when the selected identity changes. + // Invariant: polling must not replace the selected signature editor’s text. onActiveFocusChanged: if (!activeFocus) root.saveSignature() } @@ -1052,11 +989,8 @@ Column { } } - // A signature from a file: a picture, or markup another tool wrote. What - // is imported is rebuilt by Signature.js — scripts, styles, handlers, - // frames, forms, remote images and unknown attributes do not survive — - // and the preview draws what was stored, so it is the sent thing that is - // shown. The words go into the plain editor above for text-only clients. + // Invariant: signature previews use the backend-sanitized document; sender markup must not + // reach Qt directly. Row { width: parent.width spacing: MailStyle.space(8) @@ -1122,7 +1056,6 @@ Column { color: root.textColor font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall - // The stored markup, and nothing else: the same string that is sent. text: root.selectedSignatureDocument ? Html.documentFor(root.selectedSignatureDocument, { foreground: root.textColor, background: "transparent", link: root.accentColor }) : "" } @@ -1141,7 +1074,6 @@ Column { Component.onDestruction: root.saveSignature() } - // ------------------------------------------------------------- mailboxes Text { id: mailboxesHeading @@ -1152,24 +1084,12 @@ Column { font.letterSpacing: 1 } - // What to call a mailbox, which the list below draws and the switcher and - // every merged row draw too. Two of these can differ only in their domain - // and elide to the same handful of characters, so a name is the one thing - // that tells them apart at a glance. - // - // A picker and one field rather than a field on each row: the rows carry - // live mailbox state and are rebuilt whenever a poll changes an unread - // count, which would take the field apart while it was being typed into. - // This is the same reason the signature editor is shaped this way. + // Invariant: editable account names must outlive live mailbox-summary rows rebuilt by polling. Column { width: parent.width spacing: MailStyle.space(6) visible: root.signatureAccounts.length > 0 - // Two questions, one under the other, each with its own label: which - // mailbox, and what to call it. They were one block under a single "Name" - // heading, which read as though the address in the picker *was* the name - // and left nothing that looked like somewhere to type. Text { width: parent.width visible: root.signatureAccounts.length > 1 @@ -1185,7 +1105,7 @@ Column { width: parent.width showLabel: false value: root.selectedNameAccountId - options: root.nameOptions() + options: root.accountOptions foreground: root.textColor accent: root.accentColor fontFamily: root.panelFontFamily @@ -1206,11 +1126,8 @@ Column { font.pixelSize: MailStyle.bodySmall } - // The kit's own single-line input, which is what every other field on - // this page is: it carries the focus ring, the selection colours and a - // real placeholder, and it takes a click without one being arranged for - // it. A hand-built Rectangle around a bare TextInput drew the same box - // and could not be typed into. + // Invariant: use the native field; a Rectangle around a bare TextInput previously drew a box + // that could not receive typing. Widgets.TextField { id: nameEdit objectName: "settings-name-editor" @@ -1220,9 +1137,8 @@ Column { font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall - // Saved on the way out rather than on every keystroke, so the account - // file is written once per edit and the field is never rebuilt from - // under the cursor. + // Performance: persist the completed name edit on focus loss or acceptance, not on each + // keystroke. onActiveFocusChanged: if (!activeFocus) root.saveName() onAccepted: root.saveName() } @@ -1297,11 +1213,6 @@ Column { implicitHeight: Math.max(rowText.implicitHeight, rowActions.implicitHeight) + MailStyle.space(16) radius: Style.cornerRadius - // Which mailbox the window is showing is not a fact about this page. - // Nothing here acts on it — `Edit...` acts on its own row, and the - // signature section names the mailbox it signs — and the row answers - // no click, so marking it borrowed the switcher's "you are here, click - // another" fill for a row that switches nothing. color: Style.normalFillFor(root.textColor, root.accentColor) Column { @@ -1316,9 +1227,6 @@ Column { Text { width: parent.width textFormat: Text.PlainText - // The name if one was given, so this list and the switcher agree - // about what each mailbox is called. The address is on the line - // below either way, which keeps the row identifiable. text: { var named = row.modelData.name !== undefined && String(row.modelData.name) !== "" @@ -1333,8 +1241,8 @@ Column { Text { width: parent.width - // The address and whatever a server had to say are both in here, - // and Qt's default would run the rich text engine over either. + // Invariant: server errors and account addresses must remain plain text to prevent Qt + // resource loading. textFormat: Text.PlainText text: { if (row.modelData.error !== undefined && row.modelData.error !== "") @@ -1343,9 +1251,6 @@ Column { var count = row.modelData.unread var unread = count === 0 ? "No unread mail" : (count === 1 ? "1 unread message" : count + " unread messages") - // A named row has put its name on the line above, so the address - // belongs here — otherwise nothing on the row says which mailbox - // it is. var named = row.modelData.name !== undefined && String(row.modelData.name) !== "" return named ? String(row.modelData.email) + " · " + unread : unread @@ -1357,9 +1262,6 @@ Column { elide: Text.ElideRight } - // What kind of mailbox this is, where the kind is not obvious from - // the address. Only the providers with something to add answer here, - // so the row gains a line rather than every row gaining a blank one. Text { width: parent.width visible: text !== "" @@ -1430,7 +1332,6 @@ Column { foreground: root.textColor } - // ---------------------------------------------------------- oauth client Text { id: oauthHeading @@ -1465,8 +1366,6 @@ Column { Text { width: parent.width - // Every mailbox signs in through this one client, which is why adding - // an account never asks for another. text: "Advanced setup · shared by Gmail and Google Calendar accounts" color: root.dimColor font.family: root.panelFontFamily @@ -1486,7 +1385,6 @@ Column { } } - // One of the three palettes the standalone window can draw with. component AppearanceButton: Widgets.Button { required property string mode property bool firstSegment: false @@ -1509,7 +1407,6 @@ Column { } } - // One of the three ways a message's direction is arrived at. component DirectionButton: Widgets.Button { required property string mode property bool firstSegment: false diff --git a/ui/components/SetupPage.qml b/ui/components/SetupPage.qml index fea01a812..b782ce4b3 100644 --- a/ui/components/SetupPage.qml +++ b/ui/components/SetupPage.qml @@ -3,16 +3,7 @@ import "../controls" as Widgets import "../settings" import qs.Commons import qs.Ui -import "../providers/Registry.js" as Provider - -// Connecting a mailbox, as two steps instead of a wall of instructions. -// -// Gmail has no shared application to sign in through — Google issues API -// access per project — so there is genuinely a setup to do. The page shows one -// step at a time: whichever is finished collapses to a single line with a -// check, and only the one that needs the user is open. The detail most people -// skip lives behind a disclosure, except the one piece that decides whether -// the session lasts, which sits beside the button it affects. + Column { id: root @@ -25,9 +16,8 @@ Column { property int accountCount: 1 property bool secretVisible: false property bool detailVisible: false - // A finished step can be reopened — the client changes when somebody moves - // Cloud projects. Kept here rather than assigned onto the step, which would - // break the binding that closes it again. + // Invariant: keep reopen state separate from the step’s done binding so saving can close it + // again. property bool clientStepReopened: false signal removeRequested() @@ -35,16 +25,12 @@ Column { readonly property var auth: service ? service.auth : null readonly property bool configured: !!auth && auth.credentialsPresent readonly property bool signedIn: !!auth && auth.loggedIn - // A further mailbox signs in with the client that is already set up, so the - // page is an account chooser rather than the console walkthrough. readonly property bool addingMailbox: configured && !signedIn && !!service && service.accountEmail === "" readonly property bool toolsMissing: !!auth && auth.toolsChecked && auth.missingTools.length > 0 spacing: MailStyle.space(16) - // The fields show what is on disk, so the page always says what the app is - // actually using rather than going blank after a save. function syncFromStore() { nameField.syncFromStore() if (!auth) return @@ -52,8 +38,6 @@ Column { clientSecretField.text = auth.credentials ? String(auth.credentials.clientSecret || "") : "" } - // The name goes on the entry whenever the page acts — saving the client, - // or signing in — since either may be the only button pressed. function saveName() { if (service && nameField.value() !== String(service.accountName || "")) service.configureCurrentAccount({ label: nameField.value() }) @@ -69,8 +53,8 @@ Column { if (!auth) return saveName() var secret = clientSecretField.text.trim() - // The secret stays in the field. Clearing it on success looked exactly - // like losing it, which is a bad thing for a credential to look like. + // Invariant: retain the saved client secret in the masked field; clearing it falsely implied + // the credential was lost. auth.saveCredentials(clientIdField.text.trim() + (secret === "" ? "" : "\n" + secret)) } @@ -86,18 +70,10 @@ Column { } } - // Hidden only during first run, when there is genuinely no page behind this - // one — the mailbox does not exist yet. On its own line rather than inline - // beside the hero, because that is where it sits on the reader and the - // compose form, and a control that moves between pages reads as a different - // control on each of them. - // ------------------------------------------------------------------ hero ProviderHero { width: parent.width providerId: "gmail" - // The brand is in the heading because the heading is half the link, and - // "Connect your mailbox" named no service at all. title: root.addingMailbox ? "Add a Gmail mailbox" : "Connect your Gmail mailbox" detail: "Google issues Gmail API access per project, so this app signs in with an OAuth client you own. About two minutes, once." textColor: root.textColor @@ -106,9 +82,8 @@ Column { onWebsiteRequested: if (root.service) root.service.openProviderWebsite("gmail") } - // Above the steps rather than in one: the OAuth client is shared by every - // Gmail mailbox and its step folds away once it exists, which is exactly - // when a second mailbox is being added and wants a name. + // Invariant: the mailbox name sits outside the shared-client step because that step is already + // complete when adding another Gmail account. AccountNameField { id: nameField service: root.service @@ -118,8 +93,6 @@ Column { font.pixelSize: MailStyle.bodySmall } - // Missing dependencies come first: neither step below can finish without - // them, so offering the steps first would waste the user's time. Rectangle { width: parent.width visible: root.toolsMissing @@ -146,7 +119,6 @@ Column { } } - // ------------------------------------------------------- step 1: client Step { number: "1" @@ -206,9 +178,6 @@ Column { id: clientSecretField anchors.left: parent.left anchors.right: parent.right - // Masked by default, because a credential on a shoulder-surfable - // window is a worse default — but readable on demand, so it can be - // checked against the console. password: !root.secretVisible rightPadding: horizontalPadding + MailStyle.space(26) foreground: root.textColor @@ -245,7 +214,6 @@ Column { } } - // ------------------------------------------------------- step 2: sign in Step { number: "2" @@ -258,9 +226,8 @@ Column { width: parent.width spacing: MailStyle.space(10) - // The one piece of the walkthrough that cannot be hidden: a project left - // in Testing is issued seven-day refresh tokens, so the app would sign - // the user out every week. It belongs beside the button it affects. + // Invariant: a Google Cloud project left in Testing issues seven-day refresh tokens; keep + // that setup constraint visible beside sign-in. Text { width: parent.width text: "Press \"Publish app\" on your project first, or Google expires the session every seven days. An \"unverified app\" warning is expected — you are the developer." @@ -316,10 +283,6 @@ Column { Row { visible: root.signedIn || root.accountCount > 1 spacing: MailStyle.space(8) - // An unbordered button carries its padding inside an invisible box, so - // standing first in the row it looks indented. Pulled left by that much - // whenever it is first, so its text sits on the content edge like - // everything above it. anchors.left: parent.left anchors.leftMargin: signOutButton.visible ? 0 : -removeButton.horizontalPadding @@ -344,10 +307,7 @@ Column { } } - // ------------------------------------------------------------- footnotes - // Whatever went wrong. Without this a rejected client ID looks exactly like - // a button that does nothing. Text { width: parent.width visible: !!root.auth && root.auth.lastError !== "" @@ -364,9 +324,6 @@ Column { foreground: root.textColor } - // Padding kept — without it the hover box hugs the text — and the button - // pulled left by the same amount, so the text still sits on the content - // edge with the paragraphs above it. Widgets.Button { id: detailToggle text: root.detailVisible ? "Hide the details" : "Need more detail?" @@ -397,9 +354,6 @@ Column { wrapMode: Text.WordWrap } - // A step is a number, a title, and a body that is only present while this is - // the step that needs the user. Finished steps collapse to one line, so the - // page never shows more than one thing to do. component Step: Item { id: step required property string number @@ -474,9 +428,8 @@ Column { elide: Text.ElideRight } - // Sized from its one child rather than childrenRect: the child sizes - // itself to this holder's width, so asking childrenRect for the height - // closes a loop through the step's own implicitHeight. + // Invariant: use the single child’s implicitHeight; childrenRect closes a sizing loop through + // this holder. Item { id: bodyHolder width: parent.width diff --git a/ui/components/SubjectMenu.qml b/ui/components/SubjectMenu.qml index 066f7d224..bc151f3cf 100644 --- a/ui/components/SubjectMenu.qml +++ b/ui/components/SubjectMenu.qml @@ -5,11 +5,6 @@ import qs.Commons import qs.Ui import "Menu.js" as Menu -// The menu a right-click on the reader's subject opens: the subject as -// written, copied whole. One row, the way AddressMenu is one pattern — Copy -// goes out as a signal because the host owns the platform clipboard. The -// empty subject refuses an open, the way AddressMenu refuses a line that -// held no addresses. Item { id: root @@ -18,13 +13,13 @@ Item { required property color popupBorderColor required property string panelFontFamily - // The subject the click landed on, set at open time rather than bound. + // Invariant: copy the subject selected when the menu opened, not a later message’s subject. property string subject: "" property int cursorIndex: -1 readonly property bool opened: menu.opened readonly property var menuRows: [copyRow] readonly property alias copyRow: copyRow - // Exposed so a test can assert where the menu landed, the way copyRow is. + // Docs: popup geometry is exposed for placement regressions. readonly property alias popup: menu signal copyRequested(string subject) @@ -37,9 +32,8 @@ Item { function openAt(text, sceneX, sceneY) { subject = String(text || "") - // A subject of only spaces is one the reader cannot show anything for; it - // is refused like an empty one. The text is still copied verbatim, so a - // real subject keeps the spacing it was sent with. + // Invariant: reject whitespace-only subjects but preserve the original spacing of copyable + // subjects. if (subject.trim() === "") return var local = root.mapFromGlobal(sceneX, sceneY) anchorX = local.x diff --git a/ui/components/TextMenu.qml b/ui/components/TextMenu.qml index ecdb2771e..1d848da1a 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -5,14 +5,8 @@ import qs.Commons import qs.Ui import "Menu.js" as Menu -// The menu a right-click opens on text. A reader gets Copy; an editor gets -// Cut, Paste and Select all around it; a click on a link adds Open and Copy -// URL to either. The text item is handed in at open time rather than bound, -// so one menu serves every field of a form. -// -// Copy goes out as a signal rather than through the item's own copy(), -// because the host owns the platform clipboard — the same reason -// AddressMenu hands an address up instead of setting it here. +// Invariant: the host owns the platform clipboard, so Copy is emitted rather than delegated to the +// text item. Item { id: root @@ -21,11 +15,8 @@ Item { required property color popupBorderColor required property string panelFontFamily - // Whether the text can be changed: shows Cut, Paste and Select all. property bool editable: false - // The TextEdit or TextField the menu was opened on. property var target: null - // The link under the pointer when it opened, or "" for none. property string link: "" property int cursorIndex: -1 readonly property bool opened: menu.opened @@ -40,8 +31,7 @@ Item { readonly property alias copyLinkRow: copyLinkRow signal copyRequested(string text) - // Paste is the owner's: a compose form tries the clipboard for an image - // before it pastes text, and only it knows how. + // Invariant: the owner’s Paste path imports clipboard images before falling back to text. signal pasteRequested(var target) signal openLinkRequested(string url) From 717bead86bc9e16d773e71c3d3f9e34dcde4ce04 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 125/568] chore: Use theme values in new UI fixtures --- ui/tests/qml/tst_compose_attachment_recovery.qml | 14 +++++++------- ui/tests/qml/tst_setup_plaintext.qml | 16 ++++++++-------- ui/tests/qml/tst_signature_import_lifecycle.qml | 7 ------- 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/ui/tests/qml/tst_compose_attachment_recovery.qml b/ui/tests/qml/tst_compose_attachment_recovery.qml index cb9f54b0d..9d71ef921 100644 --- a/ui/tests/qml/tst_compose_attachment_recovery.qml +++ b/ui/tests/qml/tst_compose_attachment_recovery.qml @@ -55,13 +55,13 @@ Item { id: compose anchors.fill: parent service: mail - textColor: "#eeeeee" - backgroundColor: "#222222" - accentColor: "#e9a35f" - dimColor: "#aaaaaa" - dimmerColor: "#888888" - popupBackgroundColor: "#333333" - popupBorderColor: "#777777" + textColor: Qt.rgba(238/255, 238/255, 238/255, 1) + backgroundColor: Qt.rgba(34/255, 34/255, 34/255, 1) + accentColor: Qt.rgba(233/255, 163/255, 95/255, 1) + dimColor: Qt.rgba(170/255, 170/255, 170/255, 1) + dimmerColor: Qt.rgba(136/255, 136/255, 136/255, 1) + popupBackgroundColor: Qt.rgba(51/255, 51/255, 51/255, 1) + popupBorderColor: Qt.rgba(119/255, 119/255, 119/255, 1) panelFontFamily: "monospace" } diff --git a/ui/tests/qml/tst_setup_plaintext.qml b/ui/tests/qml/tst_setup_plaintext.qml index bc60601d6..f1efbb7fc 100644 --- a/ui/tests/qml/tst_setup_plaintext.qml +++ b/ui/tests/qml/tst_setup_plaintext.qml @@ -34,20 +34,20 @@ Item { id: imap width: 600 service: service - textColor: "#eeeeee" - dimColor: "#aaaaaa" - dangerColor: "#ff6666" - accentColor: "#e9a35f" + textColor: Qt.rgba(238/255, 238/255, 238/255, 1) + dimColor: Qt.rgba(170/255, 170/255, 170/255, 1) + dangerColor: Qt.rgba(255/255, 102/255, 102/255, 1) + accentColor: Qt.rgba(233/255, 163/255, 95/255, 1) panelFontFamily: "monospace" } Views.SetupPage { id: gmail width: 600 service: service - textColor: "#eeeeee" - dimColor: "#aaaaaa" - dangerColor: "#ff6666" - accentColor: "#e9a35f" + textColor: Qt.rgba(238/255, 238/255, 238/255, 1) + dimColor: Qt.rgba(170/255, 170/255, 170/255, 1) + dangerColor: Qt.rgba(255/255, 102/255, 102/255, 1) + accentColor: Qt.rgba(233/255, 163/255, 95/255, 1) panelFontFamily: "monospace" } TestCase { diff --git a/ui/tests/qml/tst_signature_import_lifecycle.qml b/ui/tests/qml/tst_signature_import_lifecycle.qml index 1ca6c08ad..3999a8443 100644 --- a/ui/tests/qml/tst_signature_import_lifecycle.qml +++ b/ui/tests/qml/tst_signature_import_lifecycle.qml @@ -2,12 +2,6 @@ import QtQuick 2.15 import QtTest 1.3 import "../../components" as Omamail -// Naming a mailbox. -// -// The field draws a box whether or not it can be typed into, which is how it -// shipped unusable twice. This types into it the way a person does — a click, -// then keys — rather than assigning `text` from the test, which would pass -// against a field nothing can reach. Item { width: 700 height: 500 @@ -48,7 +42,6 @@ Item { property string signatureHtml: "" function setAccountSignatureHtml(id, html) { signatureId = id; signatureHtml = html } - // What the page wrote, and for which mailbox. property string namedId: "" property string namedText: "" property int nameWrites: 0 From 6f4686e2e31c954e3df862064fc5468e8251de09 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 126/568] Fix calendar palette evaluation loops --- .../qml/tst_calendar_palette_bindings.qml | 58 +++++++++++++++++++ ui/components/CalendarPalette.qml | 2 - 2 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 app/tests/qml/tst_calendar_palette_bindings.qml diff --git a/app/tests/qml/tst_calendar_palette_bindings.qml b/app/tests/qml/tst_calendar_palette_bindings.qml new file mode 100644 index 000000000..36bba7bc0 --- /dev/null +++ b/app/tests/qml/tst_calendar_palette_bindings.qml @@ -0,0 +1,58 @@ +import QtQuick +import QtTest +import Quickshell +import "../../../ui/components" as Components + +TestCase { + id: testCase + name: "CalendarPaletteBindings" + when: windowShown + width: 700 + height: 600 + visible: true + HostFixture { id: host } + Component { + id: detailComponent + Components.CalendarEventDetail { + width: 700 + height: 600 + controller: null + event: null + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + urgentColor: Qt.rgba(1, 0.2, 0.2, 1) + dimColor: Qt.rgba(0.67, 0.67, 0.67, 1) + panelFontFamily: "monospace" + } + } + Component { + id: composerComponent + Components.CalendarEventComposer { + width: 700 + height: 600 + controller: null + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + urgentColor: Qt.rgba(1, 0.2, 0.2, 1) + dimColor: Qt.rgba(0.67, 0.67, 0.67, 1) + panelFontFamily: "monospace" + } + } + function test_calendar_colors_initialize_without_binding_loops_data() { + return [{tag: "details", component: detailComponent}, + {tag: "composer", component: composerComponent}] + } + function test_calendar_colors_initialize_without_binding_loops(data) { + Quickshell.fileStore = host + failOnWarning(/Binding loop detected/) + var view = createTemporaryObject(data.component, testCase) + verify(view) + wait(0) + if (view.eventColor !== undefined) compare(view.eventColor, view.accentColor) + view.accentColor = Qt.rgba(0.1, 0.6, 0.9, 1) + wait(0) + if (view.eventColor !== undefined) compare(view.eventColor, view.accentColor) + } +} diff --git a/ui/components/CalendarPalette.qml b/ui/components/CalendarPalette.qml index d460a2384..c1aad2922 100644 --- a/ui/components/CalendarPalette.qml +++ b/ui/components/CalendarPalette.qml @@ -27,8 +27,6 @@ QtObject { function reload() { paletteFile.reload() } - onAccentColorChanged: reload() - property FileView paletteFile: FileView { path: root.palettePath watchChanges: true From 3f067180a284cdc87cd5c0e22129cc2aa93c0261 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 127/568] Fix negative list cache bounds during layout --- ui/components/MessageList.qml | 2 +- ui/tests/qml/tst_message_list_geometry.qml | 40 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 ui/tests/qml/tst_message_list_geometry.qml diff --git a/ui/components/MessageList.qml b/ui/components/MessageList.qml index 5cc97b955..0c6c59b43 100644 --- a/ui/components/MessageList.qml +++ b/ui/components/MessageList.qml @@ -38,7 +38,7 @@ ListView { clip: true boundsBehavior: Flickable.StopAtBounds reuseItems: true - cacheBuffer: height + cacheBuffer: Math.max(0, height) topMargin: MailStyle.space(6) bottomMargin: MailStyle.space(6) model: root.service ? root.service.messages.length : 0 diff --git a/ui/tests/qml/tst_message_list_geometry.qml b/ui/tests/qml/tst_message_list_geometry.qml new file mode 100644 index 000000000..fb5cde442 --- /dev/null +++ b/ui/tests/qml/tst_message_list_geometry.qml @@ -0,0 +1,40 @@ +import QtQuick +import QtTest +import "../../components" as Components + +TestCase { + id: testCase + name: "MessageListGeometry" + when: windowShown + width: 600 + height: 400 + QtObject { + id: mail + property var messages: [] + property bool listLoaded: true + property bool hasMore: false + property bool listLoading: false + } + Component { + id: listComponent + Components.MessageList { + service: mail + height: 200 + textColor: Qt.rgba(1, 1, 1, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + dimColor: Qt.rgba(0.6, 0.6, 0.6, 1) + urgentColor: Qt.rgba(1, 0.2, 0.2, 1) + panelFontFamily: "monospace" + } + } + function test_transient_negative_height_keeps_a_valid_cache_buffer() { + var list = createTemporaryObject(listComponent, testCase) + verify(list) + compare(list.cacheBuffer, 200) + failOnWarning(/Cannot set a negative cache buffer/) + list.height = -20 + compare(list.cacheBuffer, 0) + list.height = 300 + compare(list.cacheBuffer, 300) + } +} From a0b5f36d29938d0536bb27993563390483c81046 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 128/568] Fix compose editor height reentrancy --- ui/components/ComposeView.qml | 5 ++- ui/tests/qml/tst_compose_geometry.qml | 46 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 ui/tests/qml/tst_compose_geometry.qml diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index fdef844a5..d7f8792cd 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -1816,7 +1816,10 @@ DropArea { width: bodyFlick.width // Invariant: the editor must fill the viewport so clicking below a short draft still places // the cursor. - height: Math.max(implicitHeight, bodyFlick.height) + Binding on height { + value: Math.max(bodyEdit.implicitHeight, bodyFlick.height) + delayed: true + } selectByMouse: true wrapMode: TextEdit.Wrap textFormat: TextEdit.PlainText diff --git a/ui/tests/qml/tst_compose_geometry.qml b/ui/tests/qml/tst_compose_geometry.qml new file mode 100644 index 000000000..b46d5540f --- /dev/null +++ b/ui/tests/qml/tst_compose_geometry.qml @@ -0,0 +1,46 @@ +import QtQuick +import QtTest +import "../../components" as Components + +TestCase { + id: testCase + name: "ComposeGeometry" + when: windowShown + width: 900 + height: 600 + visible: true + Component { + id: composeComponent + Components.ComposeView { + width: 900 + height: 600 + service: null + opened: true + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + dimColor: Qt.rgba(0.6, 0.6, 0.6, 1) + dimmerColor: Qt.rgba(0.4, 0.4, 0.4, 1) + popupBackgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + popupBorderColor: Qt.rgba(0.4, 0.4, 0.4, 1) + panelFontFamily: "monospace" + } + } + function test_body_tracks_small_and_large_viewports_without_binding_loops() { + failOnWarning(/Binding loop detected/) + var compose = createTemporaryObject(composeComponent, testCase, {width: 0, height: 0}) + verify(compose) + var editor = findChild(compose, "compose-body-editor") + var viewport = findChild(compose, "compose-body") + for (var dimensions of [[900,600], [0,0], [360,200], [900,600]]) { + compose.width = dimensions[0] + compose.height = dimensions[1] + editor.text = "Line one\nLine two\nLine three" + wait(0) + verify(editor.height >= viewport.height) + verify(editor.height >= editor.contentHeight) + } + mouseClick(editor, 5, 5) + verify(editor.activeFocus) + } +} From 1e0bae858b3bf62d8ac9c67f568cc0546108c10b Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 129/568] chore: Assert forbidden Qt resource requests for labels and avatars --- tests/test_view_resources.py | 151 +++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 tests/test_view_resources.py diff --git a/tests/test_view_resources.py b/tests/test_view_resources.py new file mode 100644 index 000000000..db515d615 --- /dev/null +++ b/tests/test_view_resources.py @@ -0,0 +1,151 @@ +"""Render hostile settings labels and avatar bytes without Qt resource requests.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +ROOT = Path(__file__).resolve().parents[1] +requests = [] + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + requests.append(self.path) + self.send_response(404) + self.end_headers() + + +QML = r''' +import QtQuick +import QtTest +import @COMPONENTS@ as Views +Item { + id: root + width: 800; height: 900 + property string endpoint: @ENDPOINT@ + function payload(name) { return '' } + QtObject { + id: runtime + property string state: "ready" + property string installedVersion: root.payload("backend-version") + property string requiredVersion: "0.9.0" + property string error: root.payload("backend-error") + property string developmentExecutable: root.payload("backend-path") + property bool development: true + property bool busy: false + property bool canInstall: false + property bool cliInstalled: false + function refresh() {} + } + QtObject { + id: auth + property bool loggedIn: false + property bool loginBusy: false + property bool toolsChecked: true + property bool credentialsPresent: true + property bool credentialsWriteBusy: false + property var missingTools: [] + property string lastError: root.payload("imap-error") + property string clientId: "client" + property string clientDescription: root.payload("oauth-client") + property string credentialsPath: root.payload("oauth-path") + property var credentials: null + property var settings: ({username: "", aliases: [], imapHost: "", imapPort: 993, smtpHost: "", smtpPort: 465}) + } + QtObject { + id: service + property var auth: auth + property string accountAddress: "" + property string accountEmail: "" + property string accountName: "" + property string accountSenderName: "" + property bool backendCanNameSender: false + property string signInProgress: root.payload("oauth-progress") + property string providerId: "gmail" + property string mailboxKey: "inbox" + property string searchQuery: root.payload("search-query") + property bool listLoaded: true + property bool listLoading: false + property var messages: [] + property string pluginName: root.payload("manifest-name") + property string version: root.payload("manifest-version") + } + Views.BackendSetup { + width: 700; runtime: runtime + textColor: "white"; dimColor: "gray"; accentColor: "orange"; panelFontFamily: "monospace" + } + Views.ImapSetupPage { + width: 700; service: service + textColor: "white"; dimColor: "gray"; dangerColor: "red"; accentColor: "orange"; panelFontFamily: "monospace" + } + Views.SetupPage { + id: gmail + width: 700; service: service + textColor: "white"; dimColor: "gray"; dangerColor: "red"; accentColor: "orange"; panelFontFamily: "monospace" + } + Views.ReaderBlankSlate { + width: 700; height: 900; service: service + textColor: "white"; dimColor: "gray"; dimmerColor: "gray"; accentColor: "orange"; panelFontFamily: "monospace" + } + Views.SenderAvatar { + id: avatar + width: 64; height: 64 + foreground: "white"; accent: "orange"; fontFamily: "monospace" + sender: ({display: "Synthetic sender"}) + imageData: "data:image/png;base64," + Qt.btoa('') + } + Text { text: root.payload("control") } + TestCase { + name: "ViewResources" + when: windowShown + function test_sender_bytes_never_reach_the_image_decoder() { + compare(avatar.safeImage, "") + compare(String(avatar.children[1].source), "") + verify(avatar.children[0].visible) + } + function test_labels_make_no_requests() { + auth.lastError = "" + auth.lastError = root.payload("imap-error") + gmail.detailVisible = true + wait(500) + } + } +} +''' + + + +def main(): + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory(prefix="omamail-view-resources-") as directory: + fixture = Path(directory) / "tst_plain_labels.qml" + endpoint = f"http://127.0.0.1:{server.server_port}" + fixture.write_text(QML.replace("@ENDPOINT@", json.dumps(endpoint)) + .replace("@COMPONENTS@", json.dumps((ROOT / "ui/components").as_uri()))) + environment = dict(os.environ, QT_QPA_PLATFORM="offscreen", + QT_QUICK_CONTROLS_STYLE="Basic", + QT_QUICK_CONTROLS_FALLBACK_STYLE="Basic", + QT_QUICK_BACKEND="software", QT_QPA_PLATFORMTHEME="", + NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost") + result = subprocess.run([ + sys.argv[1], "-import", str(ROOT / "ui/tests/qml/imports"), "-input", str(fixture) + ], env=environment, timeout=30) + assert requests == ["/control"], f"Unexpected label requests: {requests}" + result.check_returncode() + print("Observed native image control; settings labels and rejected avatar bytes made no requests") + finally: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + main() From b7c6e0e045e34a6f3d10202d650b91a780353ace Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 130/568] Fix Magpie logo contrast in light themes --- ui/components/MagpieLogo.qml | 28 +++++++++++++++++++++++----- ui/tests/qml/tst_magpie_logo.qml | 18 +++++++++++++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/ui/components/MagpieLogo.qml b/ui/components/MagpieLogo.qml index 614626709..4861d7222 100644 --- a/ui/components/MagpieLogo.qml +++ b/ui/components/MagpieLogo.qml @@ -9,11 +9,29 @@ Item { implicitHeight: implicitWidth Accessible.role: Accessible.Graphic Accessible.name: "Magpie" - Image { + Canvas { + id: ink anchors.fill: parent - source: "../assets/magpie.svg" - sourceSize.width: width * 2 - sourceSize.height: height * 2 - fillMode: Image.PreserveAspectFit + antialiasing: true + readonly property url source: "../assets/magpie.svg" + onImageLoaded: requestPaint() + onWidthChanged: requestPaint() + onHeightChanged: requestPaint() + Component.onCompleted: loadImage(source) + Connections { + target: root + function onForegroundChanged() { ink.requestPaint() } + } + onPaint: { + if (!isImageLoaded(source)) return + var context = getContext("2d") + context.reset() + context.clearRect(0, 0, width, height) + var size = Math.min(width, height) + context.drawImage(source, (width - size) / 2, (height - size) / 2, size, size) + context.globalCompositeOperation = "source-in" + context.fillStyle = root.foreground + context.fillRect(0, 0, width, height) + } } } diff --git a/ui/tests/qml/tst_magpie_logo.qml b/ui/tests/qml/tst_magpie_logo.qml index 72a57c0c4..b69743581 100644 --- a/ui/tests/qml/tst_magpie_logo.qml +++ b/ui/tests/qml/tst_magpie_logo.qml @@ -2,7 +2,9 @@ import QtQuick import QtTest import "../../components" as Components -Item { +Rectangle { + id: host + color: "white" width: 180 height: 140 Components.MagpieLogo { @@ -14,6 +16,20 @@ Item { TestCase { name: "MagpieLogo" when: windowShown + function test_ink_uses_the_supplied_foreground() { + logo.foreground = Qt.rgba(0.1, 0.2, 0.3, 1) + wait(50) + var rendered = grabImage(logo) + var x = Math.floor(logo.width * 39 / 64) + var y = Math.floor(logo.height * 24 / 64) + verify(Math.abs(rendered.red(x, y) - 26) <= 1) + verify(Math.abs(rendered.green(x, y) - 51) <= 1) + verify(Math.abs(rendered.blue(x, y) - 77) <= 1) + logo.foreground = Qt.rgba(0.8, 0.9, 1, 1) + wait(50) + rendered = grabImage(logo) + verify(Math.abs(rendered.red(x, y) - 204) <= 1) + } function test_identity_is_static_and_labeled() { compare(logo.animated, false) compare(logo.Accessible.name, "Magpie") From f8af29d6d1a0b7cc4cb4c1d9c57837e8ed2604ad Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 131/568] chore: Verify signature imports through the current backend fixture --- ui/tests/qml/tst_signature_import_lifecycle.qml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/ui/tests/qml/tst_signature_import_lifecycle.qml b/ui/tests/qml/tst_signature_import_lifecycle.qml index 3999a8443..a73c1255d 100644 --- a/ui/tests/qml/tst_signature_import_lifecycle.qml +++ b/ui/tests/qml/tst_signature_import_lifecycle.qml @@ -86,6 +86,8 @@ Item { name: "SignatureImportLifecycle" when: windowShown function init() { + page.y = 0 + fakeService.pickerCallback = null page.importing = false page.selectedSignatureAccountId = "a@example.org" fakeService.signatureId = "" @@ -95,6 +97,17 @@ Item { function picked() { fakeService.pickerCallback({ok: true, paths: ["/synthetic/signature.png"]}) } function read() { fakeBackend.callback({ok: true, mimeType: "image/png", data: "iVBORw0KGgoAAA=="}, null) } function imported() { fakeBackend.callback({html: "

signature

", plain: "", images: 1, dropped: 0, problem: ""}, null) } + function test_import_button_starts_the_owned_request() { + var trigger = findChild(page, "settings-signature-import") + verify(trigger) + page.y = 20 - trigger.mapToItem(page, 0, 0).y + waitForRendering(trigger) + mouseClick(trigger, trigger.width / 2, trigger.height / 2) + verify(fakeService.pickerCallback) + compare(page.importingAccountId, "a@example.org") + picked(); read(); imported() + compare(fakeService.signatureId, "a@example.org") + } function test_picker_completion_keeps_the_original_account() { page.importSignature() page.selectSignatureAccount("b@example.net") From 1c5eb9b7bdbcc6e5c66d535753644f6a2370fa4b Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 132/568] Remove redundant component narration and unused imports --- ui/components/AccountNameField.qml | 4 -- ui/components/AccountSwitcher.qml | 98 ++++---------------------- ui/components/ActionIcon.qml | 8 +-- ui/components/AgentPrompt.qml | 7 +- ui/components/BackBar.qml | 11 --- ui/components/CalendarEventDetail.qml | 14 +--- ui/components/CalendarPalette.qml | 3 +- ui/components/CalendarSettings.qml | 24 +------ ui/components/ComposeAgent.qml | 1 - ui/components/ComposeExitDialog.qml | 8 +-- ui/components/ConfirmDeleteDialog.qml | 10 +-- ui/components/ContactsPicker.qml | 6 +- ui/components/ConversationRail.qml | 87 ++--------------------- ui/components/EventSuggestionCard.qml | 11 +-- ui/components/IconButton.qml | 16 ----- ui/components/IconTextButton.qml | 22 +----- ui/components/Icons.js | 2 +- ui/components/ImagePopover.qml | 21 ++---- ui/components/InviteCard.qml | 39 ++-------- ui/components/JmapSetupPage.qml | 93 ++++-------------------- ui/components/KeyRouter.qml | 31 +------- ui/components/LabelPicker.qml | 43 ++--------- ui/components/LinkLabel.qml | 11 +-- ui/components/ListSkeleton.qml | 3 +- ui/components/MenuActionRow.qml | 6 +- ui/components/MessageRow.qml | 72 ++++--------------- ui/components/NamePrompt.qml | 8 +-- ui/components/OutlookSetupPage.qml | 16 +---- ui/components/ProviderHero.qml | 23 +----- ui/components/ProviderLogo.qml | 35 ++------- ui/components/ProviderPicker.qml | 21 ------ ui/components/ReaderNotice.qml | 13 ---- ui/components/ReaderSkeleton.qml | 11 +-- ui/components/RecipientSuggestions.qml | 4 +- ui/components/SearchBar.qml | 27 +------ ui/components/SenderNameField.qml | 5 -- ui/components/SettingsSidebar.qml | 14 +--- ui/components/ShortcutHelp.qml | 49 ++----------- ui/components/SwitcherSearch.qml | 8 --- ui/components/UndoSendToast.qml | 2 - ui/components/WeekCalendarView.qml | 7 +- ui/components/WheelScroller.qml | 24 ++----- ui/components/WindowMoveArea.qml | 5 +- ui/controls/Button.qml | 33 +-------- ui/controls/PanelActionButton.qml | 23 ------ ui/controls/PanelSectionHeader.qml | 11 +-- ui/controls/PanelToolTip.qml | 15 +--- ui/controls/TextField.qml | 20 +----- 48 files changed, 124 insertions(+), 901 deletions(-) diff --git a/ui/components/AccountNameField.qml b/ui/components/AccountNameField.qml index af8eb08f1..bb282a067 100644 --- a/ui/components/AccountNameField.qml +++ b/ui/components/AccountNameField.qml @@ -3,10 +3,6 @@ import "../controls" as Widgets import qs.Commons import qs.Ui -// The name a mailbox is listed by, asked for where the mailbox is set up -// rather than only in the settings list afterwards. Optional: two mailboxes -// that differ only in their domain are told apart by a name, and one on its -// own has no need of one. Empty is not a name and puts the address back. Widgets.TextField { id: root diff --git a/ui/components/AccountSwitcher.qml b/ui/components/AccountSwitcher.qml index 5e399e298..1df2d62c6 100644 --- a/ui/components/AccountSwitcher.qml +++ b/ui/components/AccountSwitcher.qml @@ -6,12 +6,6 @@ import qs.Ui import "../account/Model.js" as Model import "Menu.js" as Menu -// The list of mailboxes, opened from the user bar. -// -// Switching is meant to be instant, which it is because every account keeps its -// own cache. It says which is being checked right now and keeps a mailbox that -// has not finished signing in visible, because otherwise a half-added mailbox -// becomes invisible and unfixable. Item { id: root @@ -23,37 +17,22 @@ Item { required property color popupBorderColor required property string panelFontFamily - // [{ id, email, label, unread, active, signedIn, busy, error }] property var accounts: [] - // What has been typed, and the mailboxes it leaves — matched on the name - // they were given and their address — best first; every one, in order, - // with nothing typed. The combined row is offered only then: it is not a - // mailbox anyone types the name of. property string query: "" readonly property var shownAccounts: Model.filterRows(accounts, query) - // Typing puts the cursor on the best match; typing it all away puts it - // back where it rests, on the mailbox in use. onQueryChanged: if (query.trim() === "") restCursorOnActive(); else cursorIndex = 0 readonly property bool opened: menu.opened - // A popup builds its contents outside this item's own children, so nothing - // walking the tree from here finds a row. This is the handle that does — - // the same reason `opened` is exposed rather than reached for. + // Docs: popup delegates are in the overlay, so expose their content item for geometry tests. readonly property alias menuRows: rows - // Where the keyboard is standing, which is not where the mouse is: hover is - // drawn by the row itself and never written here. Qt re-reports hover when - // content moves under a still pointer, and a hover that moved this would drag - // the cursor back to whatever the pointer happened to rest on. + // Invariant: keyboard position must not follow passive hover; Qt replays hover when content moves + // beneath a stationary pointer. property int cursorIndex: 0 - // Whether the mailbox on screen is the merge of all of them, drawn the way - // an active account is drawn because it is the same kind of choice. property bool unifiedActive: false - // One mailbox has nothing to combine, so the row is not offered: choosing it - // would land on the same list under a different name. readonly property int accountRowCount: root.shownAccounts.length readonly property bool unifiedOffered: (root.accounts ? root.accounts.length : 0) > 1 && root.query.trim() === "" readonly property int rowOffset: unifiedOffered ? 1 : 0 @@ -67,7 +46,6 @@ Item { anchors.fill: parent z: 45 - // Where the menu was asked to appear, kept because it cannot be placed yet. property real anchorX: 0 property real anchorY: 0 @@ -79,12 +57,8 @@ Item { place() } - // A Popup does not build its contents until it is first opened, so on the - // very first click its height is still zero — the "does it fit below?" test - // passed trivially and the menu was placed at the click, then grew off the - // bottom of the window. Placing again whenever the height changes is what - // makes the first open behave like every one after it, and it also re-places - // the menu when a row is added or removed. + // Invariant: popup content is lazy; re-place it after the first height calculation and subsequent + // filtering. function place() { if (!menu.visible) return var tall = menu.height > 0 ? menu.height : menu.implicitHeight @@ -93,9 +67,6 @@ Item { menu.y = placed.y } - // Opened from a menu rather than from a click on the rail, so there is no - // pointer position to hang it off. Centring is the honest answer: anywhere - // else would be pretending it belongs to something on screen. function openCentered() { anchorX = Math.max(0, (root.width - menu.width) / 2) anchorY = Math.max(0, (root.height - menu.implicitHeight) / 2) @@ -110,8 +81,6 @@ Item { cursorIndex = Model.wrappedIndex(cursorIndex, delta, root.rowCount) } - // The combined row is first, so the accounts sit one further down than their - // own indices. Everything above this component still counts accounts. function chooseCursor() { if (cursorIndex < 0 || cursorIndex >= root.rowCount) return menu.close() @@ -122,15 +91,13 @@ Item { root.accountChosen(root.shownAccounts[cursorIndex - root.rowOffset].sourceIndex) } - // Opening puts the keyboard on the mailbox you are already in, so the first - // `j` is one step away from it rather than back at the top of the list. function restCursorOnActive() { if (root.unifiedActive && root.unifiedOffered) { cursorIndex = 0 return } - // Read afresh rather than through `shownAccounts`: called as the query - // changes, when that binding may not have caught up yet. + // Invariant: query-change handlers run before shownAccounts necessarily updates; derive the new + // filtered rows directly. var accounts = Model.filterRows(root.accounts, root.query) var offset = (root.accounts ? root.accounts.length : 0) > 1 && root.query.trim() === "" ? 1 : 0 for (var i = 0; i < accounts.length; i++) { @@ -161,26 +128,14 @@ Item { border.color: root.popupBorderColor } - // The one place in this window that answers keys itself, and the reason is - // the opposite of the rule it breaks. `Keys` handlers are banned everywhere - // else because a window `Shortcut` beats them, so a local one looks live - // and never runs. Inside an open `QQC.Popup` it is the other way round: the - // popup takes every key before the shortcut map sees it — with `focus` true - // or false, bare or modified — so a `KeyRouter` binding is the thing that - // would look live and never run. The keys live on the search line at the - // top, which takes focus as the popup opens; the column forwards to it. - // `tst_account_switcher.qml` holds both halves of that, so the next person - // to reach for `survivesOverlay` finds out from a test rather than from a - // menu that does not move. + // Invariant: QQC.Popup consumes window shortcuts; its focused search field must handle + // navigation locally (tst_account_switcher). contentItem: Column { id: rows spacing: MailStyle.space(2) - // A key that reaches the column — the field lost focus to a click on - // the padding, say — still goes to the search line. + // Invariant: keys from popup padding still forward to its search field. Keys.forwardTo: [search] - // Every mailbox at once, above the mailboxes it is made of: it is the - // widest of the choices here, and a list is read from the top. SwitcherSearch { id: search width: menu.width - menu.leftPadding - menu.rightPadding @@ -220,8 +175,6 @@ Item { radius: width / 2 color: Style.selectedFillFor(root.textColor, root.accentColor) - // Not a letter: this row stands for no address, and an initial - // taken from one of them would claim it belonged to that mailbox. ActionIcon { anchors.centerIn: parent name: "inbox" @@ -241,7 +194,6 @@ Item { Text { width: parent.width textFormat: Text.PlainText - // The same string the status line shows, from one place. text: Model.UNIFIED_LABEL color: root.textColor font.family: root.panelFontFamily @@ -281,15 +233,9 @@ Item { readonly property bool hasCursor: root.cursorIndex === row.index + root.rowOffset - // Whether this mailbox was given a name, which decides what the two - // lines hold. `label` cannot answer it: it falls through to the - // local part, so it is never empty. readonly property bool named: modelData.name !== undefined && String(modelData.name) !== "" - // What the two lines hold, decided here rather than inside the - // bindings that draw them: it is one choice with two halves, and - // splitting it across two `Text` elements hid that. readonly property string primaryText: { if (row.named) return String(modelData.name) return modelData.email !== "" ? modelData.email : "New account" @@ -300,16 +246,11 @@ Item { return String(modelData.error) if (!modelData.signedIn) return "Signed out" if (modelData.busy) return "Checking" - // A named mailbox puts its address here, which keeps the name from - // hiding which account it stands for. An unnamed one has already - // said everything it has to say on the line above. return row.named ? String(modelData.email || "") : "" } - // Whether this is the mailbox being read, which is not the same as - // being the active account: the combined view leaves one active - // underneath because compose still needs an address to send from. - // Drawing both as in use said the window was in two places. + // Invariant: unified view retains an active sending account; only the unified row is + // selected for reading. readonly property bool inUse: modelData.active && !root.unifiedActive width: menu.width - menu.leftPadding - menu.rightPadding @@ -319,9 +260,8 @@ Item { ? Style.selectedFillFor(root.textColor, root.accentColor) : (rowHover.hovered || hasCursor ? Style.hoverFillFor(root.textColor, root.accentColor) : "transparent") - // A border rather than a third fill: the mailbox you are in already - // owns the selected one, and the keyboard has to be visible standing - // on that row too. + // Invariant: draw the keyboard cursor with a border so it remains distinct on the + // selected account. border.width: hasCursor ? Style.normalBorderWidth : 0 border.color: Style.hoverBorderFor(root.textColor, root.accentColor) @@ -358,14 +298,6 @@ Item { anchors.verticalCenter: parent.verticalCenter spacing: MailStyle.space(1) - // A name if one was chosen, and the address otherwise. - // - // The address used to be the only thing here, because the only - // name available was the local part and two mailboxes easily - // share one across different domains. A name somebody typed is - // the opposite: it exists precisely to tell them apart, and it - // wins over an address that elides to `patryk.bartkow…` in a list - // this narrow. The address is not lost — it moves below. Text { width: parent.width textFormat: Text.PlainText @@ -377,8 +309,6 @@ Item { elide: Text.ElideMiddle } - // Says why an account is not usable, rather than leaving it looking - // identical to one that is. Text { width: parent.width visible: text !== "" diff --git a/ui/components/ActionIcon.qml b/ui/components/ActionIcon.qml index 569a78fd1..d55a65912 100644 --- a/ui/components/ActionIcon.qml +++ b/ui/components/ActionIcon.qml @@ -9,14 +9,12 @@ Item { property string name: "" property color color: Commons.Color.foreground - // Magpie keeps the envelope in the foreground and gives its M the active - // theme accent. Provider artwork uses ProviderLogo instead of this mark. property color markColor: color property bool brand: false property bool filled: false property real iconSize: Style.font.icon property string fontFamily: MailStyle.family - // Stroke weight of the drawn mark only, relative to its 16-unit grid. + // Docs: strokeScale is measured against the 16-unit vector grid. property real strokeScale: 1.4 readonly property bool drawsMark: brand && name === "gmail" @@ -62,10 +60,6 @@ Item { ctx.lineCap = "round" ctx.lineJoin = "round" - // The Gmail mark: the envelope body, with the M fold inset inside it. A - // plain envelope with a V fold is the generic mail glyph — the M is the - // whole difference. The two are stroked separately so the M can carry - // the theme accent while the envelope stays in the foreground colour. ctx.strokeStyle = root.color ctx.beginPath() ctx.rect(1 * s, 3 * s, 14 * s, 10 * s) diff --git a/ui/components/AgentPrompt.qml b/ui/components/AgentPrompt.qml index e02911ebf..7c7fb006d 100644 --- a/ui/components/AgentPrompt.qml +++ b/ui/components/AgentPrompt.qml @@ -8,8 +8,6 @@ import "../agent/Agent.js" as Agent import "../agent" as AI import "../agent/ChatText.js" as ChatText -// A contextual conversation. The system AI streams public output in the -// background; applying a suggestion remains an explicit owner action. FocusScope { id: root required property color textColor @@ -251,7 +249,6 @@ FocusScope { function chooseCommand(index) { if (!commandsOpen) return false var command = commandMatches[typeof index === "number" ? index : commandIndex] - // History takes no argument, so choosing it opens the list at once. if (field.text.trim() === command || command === "/history") { field.text = command return submitCurrent() @@ -383,8 +380,8 @@ FocusScope { } function applyAnswer(replace) { if (!composer || !job || answer === "") return false - // Re-resolve ownership immediately before editing, even if a From menu - // or a restored draft changed under the response. + // Invariant: re-resolve draft ownership before applying a suggestion; a restored draft or From + // change may have replaced it. var matches = service.agentJobsForDraft(composer.currentFields()) if (!matches.some(function(candidate) { return String(candidate.id) === String(root.job.id) })) return false if (replace) composer.replaceBody(answer) diff --git a/ui/components/BackBar.qml b/ui/components/BackBar.qml index be711d5cf..1182170cb 100644 --- a/ui/components/BackBar.qml +++ b/ui/components/BackBar.qml @@ -3,12 +3,6 @@ import "../settings" import qs.Commons import qs.Ui -// The way out of a second-level page. -// -// Reading a message, composing one, and the OAuth setup are all pages the -// window goes *into*, and every one of them needs the same way back in the -// same place. One component so the three cannot drift apart, and so the escape -// is never something that only exists at some window widths. Item { id: root @@ -19,11 +13,6 @@ Item { signal activated() - // Outlined rather than flat. A flat button has to choose between aligning its - // glyph with the text below — which pushes the hover fill out past the - // content edge — and aligning the fill, which indents the glyph. An outline - // makes the box itself the aligned edge, so both states sit on the same line - // as everything under them. implicitWidth: button.implicitWidth implicitHeight: button.implicitHeight diff --git a/ui/components/CalendarEventDetail.qml b/ui/components/CalendarEventDetail.qml index 655c1bce9..2490ead38 100644 --- a/ui/components/CalendarEventDetail.qml +++ b/ui/components/CalendarEventDetail.qml @@ -41,13 +41,8 @@ Rectangle { } return null } - // The button rule: an operation that cannot really run is not drawn. A - // read-only calendar draws neither button. Google writes against the item - // id; CalDAV against the event's href, a recurring one is one ICS with - // state this panel does not re-serialize — and a modified occurrence - // carries only a RECURRENCE-ID, but its href is the series' shared file — - // and an href that resolves outside the source's own origin is refused by - // the same rule the controller applies before any credential is read. + // Invariant: CalDAV recurring occurrences share a series href that this panel cannot safely + // rewrite; refuse recurring deletes and cross-origin hrefs before credentials are read. readonly property bool canDelete: !!root.source && !!event && root.source.readOnly !== true && (root.source.kind === "google" ? String(event.googleId || "") !== "" @@ -64,8 +59,6 @@ Rectangle { && event.conferenceData.createRequest && event.conferenceData.createRequest.status ? event.conferenceData.createRequest.status.statusCode || "" : "") readonly property string locationLink: httpLink(event ? event.location : "") - // The location as written. One that is not a link is a place, and a place - // is something to copy into a message or to look up on a map. readonly property string locationText: String(event && event.location || "").trim() readonly property bool locationIsPlace: locationText !== "" && locationLink === "" readonly property string mapLink: locationIsPlace @@ -454,9 +447,6 @@ Rectangle { onClicked: if (root.controller) root.controller.openExternal(root.providerLink) } - // One quiet trigger; which delete — telling guests or not, one - // occurrence or the series — is chosen in the confirmation, where the - // event is named. IconTextButton { visible: root.canDelete objectName: "event-delete" diff --git a/ui/components/CalendarPalette.qml b/ui/components/CalendarPalette.qml index c1aad2922..4dd2a48a5 100644 --- a/ui/components/CalendarPalette.qml +++ b/ui/components/CalendarPalette.qml @@ -12,8 +12,7 @@ QtObject { property var values: ({}) readonly property var slots: Palette.keys() - // The shell decides whether an Omarchy palette exists. Standalone hosts - // leave this empty and use the semantic colours supplied by App.qml. + // Invariant: the shell owns the optional palette path; other hosts use App’s semantic colors. property string palettePath: "" function colorFor(key) { diff --git a/ui/components/CalendarSettings.qml b/ui/components/CalendarSettings.qml index 05563251c..bcfcdab80 100644 --- a/ui/components/CalendarSettings.qml +++ b/ui/components/CalendarSettings.qml @@ -74,16 +74,13 @@ Column { root.service && Array.isArray(root.service.accountSummaries) ? root.service.accountSummaries : []) } - // A hand-added calendar is removed here; one that came with a mailbox is - // refreshed by discovery instead — unless the mailbox is gone, when there - // is nothing left to refresh it and this is the only way to be rid of it. + // Invariant: discovery owns account calendars while their account exists; only manual and + // orphaned sources can be removed here. function removable(source) { var value = source || {} return (value.kind === "caldav" && value.discovered !== true) || root.orphaned(value) } - // Calendars listed under their mailbox's row: the provider and the address - // are on that row already, so only what sets this calendar apart is left. function nestedDetail(source) { var value = source || {} var parts = [] @@ -92,8 +89,6 @@ Column { return parts.join(" · ") } - // Google names a mailbox's own calendar after its address, which the row - // above already shows; beside it the calendar is simply the primary one. function displayName(source) { var value = source || {} var name = String(value.name || value.id || "Calendar") @@ -107,16 +102,12 @@ Column { }) } - // Hand-added CalDAV calendars and ones whose mailbox is gone or cannot be - // discovered here: nothing above lists them, so they are listed on their own. readonly property var otherSources: settingsSources.filter(function(source) { var account = String(source.accountId || "") return account === "" || root.orphaned(source) || !root.discoverableAccounts().some(function(value) { return String(value.id) === account }) }) - // One default per account, asked only where the account has more than one - // calendar to put a new event in. readonly property var defaultChoices: Sources.writableGroups(Sources.groupByAccount( { sources: writableSources }, service ? service.accountSummaries : [])) .filter(function(group) { return group.calendars.length > 1 }) @@ -153,8 +144,6 @@ Column { width: parent ? parent.width : implicitWidth spacing: MailStyle.space(16) - // One settings row, the shape every other row on this page has: a title and - // a caption on the left, the control that changes it on the right. component SettingRow: Rectangle { id: settingRow property string title: "" @@ -208,8 +197,6 @@ Column { font.letterSpacing: 1 } - // A calendar: its colour, its name and whether it is shown. The colour and - // password editors open beneath the row they belong to. component CalendarRow: Column { id: calendarRow property var source: ({}) @@ -227,7 +214,6 @@ Column { id: colorButton objectName: "calendar-source-color" focusable: true - // The dot's left edge sits on the same line as the titles above it. anchors.left: parent.left anchors.leftMargin: MailStyle.space(12) - (width - MailStyle.space(10)) / 2 anchors.verticalCenter: parent.verticalCenter @@ -432,7 +418,6 @@ Column { } } - // --------------------------------------------------------------- calendars Column { width: parent.width @@ -739,8 +724,7 @@ Column { Text { id: resultText - // Whether the text reports success, said by the reporter rather than - // read back out of the words: an error can begin with anything. + // Invariant: success is explicit state, never inferred from server-controlled error wording. property bool ok: false width: parent.width visible: text !== "" @@ -774,7 +758,6 @@ Column { onClicked: root.openCalendarRequested() } - // -------------------------------------------------------------- new events Column { width: parent.width @@ -811,7 +794,6 @@ Column { } } - // --------------------------------------------------------------- reminders Column { width: parent.width diff --git a/ui/components/ComposeAgent.qml b/ui/components/ComposeAgent.qml index 4beb97128..8fcc4cec9 100644 --- a/ui/components/ComposeAgent.qml +++ b/ui/components/ComposeAgent.qml @@ -1,4 +1,3 @@ import QtQuick -// Draft assistance shares the mail popup's state, errors and result controls. AgentPrompt {} diff --git a/ui/components/ComposeExitDialog.qml b/ui/components/ComposeExitDialog.qml index bf2ad1a9f..7d221e2e6 100644 --- a/ui/components/ComposeExitDialog.qml +++ b/ui/components/ComposeExitDialog.qml @@ -23,8 +23,8 @@ Item { signal saveRequested(string draftKey) signal discardRequested(string draftKey) - // A failed send can replace the composer while this modal owns the focus. - // Its choice belongs to the draft that opened it, not the next visible one. + // Invariant: a send failure can replace the composer while this modal is open; its decision + // belongs to the draft that opened it. onCurrentDraftKeyChanged: { if (requestedDraftKey !== "" && requestedDraftKey !== currentDraftKey) close() } @@ -88,8 +88,8 @@ Item { } contentItem: Column { spacing: MailStyle.space(14) - // A popup consumes keys before the window shortcuts. Keep its button - // activation here, with the focus cycle contained by KeyNavigation. + // Invariant: popups consume window shortcuts; local key handling and KeyNavigation contain + // the focus cycle. Keys.onPressed: function(event) { if (event.key !== Qt.Key_Return && event.key !== Qt.Key_Enter) return event.accepted = true diff --git a/ui/components/ConfirmDeleteDialog.qml b/ui/components/ConfirmDeleteDialog.qml index af866aced..ab01588d0 100644 --- a/ui/components/ConfirmDeleteDialog.qml +++ b/ui/components/ConfirmDeleteDialog.qml @@ -5,9 +5,6 @@ import QtQuick.Controls as QQC import qs.Commons import qs.Ui -// The one confirmation for destructive writes. A calendar event is gone for -// good once the server says so, so it asks first: the opener names the target -// in the request, and only the answer here reaches the controller. Item { id: root @@ -22,10 +19,6 @@ Item { signal confirmed(var request) - // A request may carry `choices`, each a delete that differs in consequence - // — without telling guests, or the whole series. Every one is its own - // button, the last is the default, and the answer travels back as - // `request.choice`. A request without choices is a plain Delete. readonly property var choices: request && Array.isArray(request.choices) && request.choices.length > 0 ? request.choices : [{ value: "", label: "Delete" }] @@ -48,7 +41,6 @@ Item { confirmed(answered) } - // Cancel, then the choices left to right: the order Tab walks. function buttonsInOrder() { var ordered = [cancelButton] for (var i = 0; i < choiceButtons.count; i++) ordered.push(choiceButtons.itemAt(i)) @@ -83,7 +75,7 @@ Item { } contentItem: Column { spacing: MailStyle.space(14) - // Popups consume keys before the window shortcut map. + // Invariant: popups consume keys before the window shortcut map. Keys.onPressed: function(event) { if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { event.accepted = true diff --git a/ui/components/ContactsPicker.qml b/ui/components/ContactsPicker.qml index 5f77358fa..56049d719 100644 --- a/ui/components/ContactsPicker.qml +++ b/ui/components/ContactsPicker.qml @@ -58,10 +58,8 @@ Item { menu.close() } - // The popup closes on a press outside itself, and the control that opens it - // is outside it — so the press that looks like "close this" has already done - // so, and a plain `opened ? close() : openAt()` would reopen it on the - // release every time. The moment it closed is what separates the two. + // Invariant: outside-press closes the popup before the trigger’s release; retain close time to + // avoid immediately reopening it. property double closedAt: 0 function toggleAt(sceneX, sceneY) { diff --git a/ui/components/ConversationRail.qml b/ui/components/ConversationRail.qml index c569fe127..29fbc2010 100644 --- a/ui/components/ConversationRail.qml +++ b/ui/components/ConversationRail.qml @@ -4,30 +4,12 @@ import QtQuick.Controls import qs.Commons import "../account/Model.js" as Model -// The conversation beside the message, as a timeline down the right edge of the -// reader. -// -// A row stands for a conversation and opens one member of it; this is the rest -// of the conversation, newest first, every member a stop that opens in the same -// reader. It takes width from the body and never height: the message keeps its -// reading measure and the rail scrolls in a viewport of its own, the way the -// list scrolls beside the reader. -// -// It decides nothing. `account/Conversation.js` says which stops there are and -// what each of them shows; this draws them and reports which one was asked for. Item { id: root - // `Conversation.stops`: one entry per member, newest first, each carrying - // whether its summary has arrived, whether it is the open message, and the - // mailbox name it needs when it sits outside the one on screen. required property var stops - // "3 messages · 1 unread", from the same file. required property string caption required property color textColor - // The panel behind the rail, which is what a hollow node is filled with. A - // literal would be a colour this file chose; the theme's is the one the - // message beside it is drawn on. required property color backgroundColor required property color accentColor required property color dimColor @@ -35,18 +17,11 @@ Item { required property string panelFontFamily signal memberActivated(string id) - // A right-click on a stop: the member's own menu, the one a row opens, at - // the pointer. The rail reports the member and where; the reader passes it - // up, and the App opens the menu it already has for rows. signal memberMenuRequested(string id, real sceneX, real sceneY) - // About two hundred pixels: wide enough for a date, a name and a mailbox - // under it, narrow enough that the reading measure beside it survives. implicitWidth: MailStyle.space(200) - // One animation for every skeleton on the rail, for the reason - // `ReaderSkeleton` has one for the whole reader: a timer per bar puts a dozen - // of them on the thread that draws the desktop. + // Performance: one animation drives all skeletons instead of creating one timer per bar. property real pulse: 0.5 SequentialAnimation on pulse { @@ -64,14 +39,6 @@ Item { return false } - // Where one stop sits in the rail's own content, `{ y, height }`, or null for - // an id that is not a stop. The same question `MessageList.boundsFor` answers - // for a row, for the same reason: this is a Column in a Flickable, so there - // is no index to position by and geometry is what a reveal has to go on. - // - // `node` and `line` are the stop's circle and its piece of the timeline in - // the same coordinates, `{ top, bottom }` each, so a test can say where the - // line begins and ends without reaching into the delegate. function boundsFor(id) { var wanted = String(id || "") for (var i = 0; i < stopColumn.children.length; i++) { @@ -88,10 +55,6 @@ Item { return null } - // Bring one stop on screen with the smallest scroll, and no scroll at all - // while it is already there — the list cursor's own rule, called rather than - // copied, because recentring on every step would drag the rail under - // somebody walking one stop down it exactly as it would drag the list. function reveal(id) { var bounds = boundsFor(id) if (!bounds) return @@ -99,10 +62,6 @@ Item { bounds.y, bounds.height, railFlick.contentHeight, MailStyle.space(8)) } - // The rule separating the rail from the message, the full height of the pane. - // Not a `PanelSeparator`: that one is a horizontal divider and fixes its own - // height, which is the wrong half of the geometry to have decided for a rule - // that runs down the edge. The tint is the same alpha-on-foreground. Rectangle { id: edge anchors.left: parent.left @@ -121,8 +80,6 @@ Item { anchors.leftMargin: MailStyle.space(12) anchors.rightMargin: MailStyle.space(10) anchors.topMargin: MailStyle.space(14) - // Generated here out of a count, not written by a sender — but the rule is - // cheap and the file it sits in draws senders two lines down. textFormat: Text.PlainText text: root.caption color: root.dimColor @@ -158,30 +115,20 @@ Item { } } - // One member. Not a button: it is a place on a timeline that can be gone to, - // and the open one wears the list's own selected fill rather than a pressed - // state. component Stop: Rectangle { id: stop required property var modelData required property int index readonly property string memberId: String(modelData.id || "") - // The ends of the timeline. The line joins the stops; it does not run in - // from above the first circle or out below the last, because there is - // nothing at either end for it to be going to. readonly property bool first: index === 0 readonly property bool last: index === (root.stops || []).length - 1 readonly property real nodeTop: node.y readonly property real nodeBottom: node.y + node.height readonly property real lineTop: first ? nodeBottom : 0 readonly property real lineBottom: last ? nodeTop : height - // One axis for every stop, whatever size its circle is. The open circle is - // wider than the others, and a segment centred on its own circle sat a - // pixel to the side of the segments above and below it, which read as a - // line that broke at the open message. The circle and the segment are - // both centred on this instead, and the segment lands on a whole pixel so - // it is one pixel wide rather than two half-shaded ones. + // Invariant: every stop shares one pixel-aligned axis, including larger selected nodes, so + // timeline segments remain continuous. readonly property real axis: MailStyle.space(10) + MailStyle.space(11) / 2 readonly property real lineWidth: Math.max(1, MailStyle.space(1)) readonly property real lineX: Math.round(axis - lineWidth / 2) @@ -211,11 +158,6 @@ Item { } } - // The timeline itself, drawn per stop rather than once behind them: the - // rail scrolls, and a single rule sized to the content would have to be - // kept in step with the Column. One segment per stop is the same line and - // needs nothing kept true — the first stop's begins under its circle and - // the last stop's ends above its own. Rectangle { id: segment objectName: "rail-segment" @@ -226,10 +168,6 @@ Item { color: Qt.rgba(root.textColor.r, root.textColor.g, root.textColor.b, 0.14) } - // Filled with the accent while the member is unread, hollow once it has - // been read, and heavier for the open one — three states, none of them - // carried by colour alone: the open stop also has the selected fill behind - // it and the word "open" beside its sender. Rectangle { id: node x: stop.axis - width / 2 @@ -251,13 +189,6 @@ Item { anchors.verticalCenter: parent.verticalCenter spacing: MailStyle.space(2) - // The date leads, because the rail is a timeline and the date is where a - // stop sits on it. The flag rides beside it: it belongs to the message - // rather than to the person, and it is state the sender's own line must - // not be able to imitate. The mailbox name, when the member has one to - // show, takes the rest of this line rather than a line of its own — a - // line that appeared when the summary landed moved every stop below it, - // and in a search that was every stop. Item { width: parent.width implicitHeight: Math.max(dateText.implicitHeight, flagIcon.height, @@ -297,10 +228,6 @@ Item { fontFamily: root.panelFontFamily } - // Where to find this member, when it is not where the reader is - // looking. The account's own name for the mailbox, the one the sidebar - // draws, against the right edge and elided rather than the date: the - // date is where the stop sits and always fits. Text { id: mailboxText visible: stop.modelData.mailbox !== "" @@ -329,9 +256,7 @@ Item { anchors.left: parent.left anchors.right: openMark.visible ? openMark.left : parent.right anchors.rightMargin: openMark.visible ? MailStyle.space(5) : 0 - // A stranger wrote this name. AutoText would promote anything - // tag-shaped in it to rich text, and Qt's rich text engine fetches an - // for real. + // Invariant: sender names must remain plain text to prevent Qt resource loading. textFormat: Text.PlainText text: stop.modelData.sender color: root.textColor @@ -350,9 +275,7 @@ Item { height: MailStyle.space(9) } - // The word, not only the fill: a theme whose selected surface is faint - // would otherwise leave nothing at all saying which of these is the - // message on screen. + // Invariant: the selected stop has a visible word as well as a theme-dependent fill. Text { id: openMark visible: stop.modelData.open && stop.modelData.known diff --git a/ui/components/EventSuggestionCard.qml b/ui/components/EventSuggestionCard.qml index b3fcc27bd..95a393301 100644 --- a/ui/components/EventSuggestionCard.qml +++ b/ui/components/EventSuggestionCard.qml @@ -4,11 +4,8 @@ import qs.Commons import qs.Ui import "../agent/Agent.js" as Agent -// What the agent found in the message: one row per event — what, when, -// where — with Add and Dismiss. Add opens the calendar's composer with the -// fields filled in; nothing is written from here. Every string on the card -// came out of the agent's answer, which came out of the message, so it is -// drawn as text and only text. +// Invariant: suggestions only prefill a human-submitted event; all model-supplied strings remain +// plain text. Rectangle { id: root @@ -24,9 +21,6 @@ Rectangle { signal dismissRequested(string key) readonly property var rows: Array.isArray(suggestions) ? suggestions : [] - // Folded until asked: a guess about somebody else's mail is a line above - // the message, not a panel over it. The heading says how many were found - // and opens on a click; a new look's findings fold again. property bool expanded: false readonly property string lookId: rows.length > 0 ? String(rows[0].jobId || "") : "" onLookIdChanged: expanded = false @@ -143,7 +137,6 @@ Rectangle { IconTextButton { objectName: "suggestionAdd" iconName: "plus" - // The composer opens, so the label says so before it is pressed. text: "Add to calendar..." foreground: root.textColor accent: root.accentColor diff --git a/ui/components/IconButton.qml b/ui/components/IconButton.qml index 9c51bfbb6..b79fc2e33 100644 --- a/ui/components/IconButton.qml +++ b/ui/components/IconButton.qml @@ -5,9 +5,6 @@ import qs.Commons import qs.Commons as Commons import qs.Ui -// A drawn icon on the kit's shared hover/cursor surface. qs.Ui's -// PanelActionButton takes a font glyph, and this app's icons are vector images, -// so this is that button with the glyph swapped for an ActionIcon. Item { id: root @@ -18,17 +15,8 @@ Item { property color accent: Commons.Color.accent property bool filled: false property bool hasCursor: false - // Held down for as long as a menu this button opened is on screen. A trigger - // that looks untouched while its own popup is up leaves the popup looking - // unattached to anything. property bool selected: false - // Working on the thing the button asks for — checking for mail, say. The - // glyph turns while it is, and stays at full strength: a button that only - // went dim said "you cannot" when the truth was "already doing it". property bool busy: false - // Something behind this button wants the owner — an agent's question, a - // job that finished unseen. A slow pulse of the accent around the glyph, - // and nothing else changes: the button still says what it always said. property bool attention: false property real iconSize: Style.font.icon property real size: Math.max(MailStyle.space(24), iconSize + Style.spacing.sm * 2) @@ -62,8 +50,6 @@ Item { height: size opacity: enabled || busy ? 1.0 : 0.4 - // The pulse: a ring of the accent that breathes while attention is asked - // for, drawn under the fill so a hover still reads as a hover. Rectangle { id: halo anchors.fill: parent @@ -101,8 +87,6 @@ Item { color: root.hot || root.selected ? root.hoverColor : root.foreground filled: root.filled - // A full turn a second, and back to upright the moment the work ends so - // the glyph never rests at a tilt. RotationAnimation on rotation { running: root.busy loops: Animation.Infinite diff --git a/ui/components/IconTextButton.qml b/ui/components/IconTextButton.qml index be1b6a483..e5210c4d0 100644 --- a/ui/components/IconTextButton.qml +++ b/ui/components/IconTextButton.qml @@ -5,11 +5,6 @@ import qs.Commons import qs.Commons as Commons import qs.Ui -// A bordered button carrying a drawn icon beside its label. -// -// qs.Ui's Button takes a font glyph for its icon, and this app's icons are -// vector images. This is that button with the glyph slot replaced, using the same -// state fills, border, padding and height as the rest of the kit. Rectangle { id: root @@ -19,24 +14,10 @@ Rectangle { property color foreground: Commons.Color.foreground property color accent: Commons.Color.accent property bool bordered: true - // Reserve the normal border but leave the field clear until interaction. property bool outline: false - // The look of the icon buttons it may stand beside: no fill and no border - // at rest, a fill on hover, and the icon and label brightening to - // `hoverColor` — so a labelled action in a row of icon buttons reads as - // one of them. `bordered: false` alone keeps its own hover border, which - // the tab bars rely on. property bool ghost: false property color hoverColor: foreground - // A ghost stands in a row of IconButtons, so it takes their glyph size - // and their height; a bordered button is a form control and keeps the - // kit's control height and the smaller glyph that fits beside a label. property real iconSize: ghost ? Style.font.icon : Style.font.iconSmall - // Held while this button is the chosen one of a set — the RSVP row, where - // three buttons stand for three answers and one of them is the answer given. - // Never the only sign of it: the caller shows a check glyph too, because a - // theme can put the selected fill close enough to the normal one that - // colour alone says nothing. property bool selected: false property string fontFamily: MailStyle.family property real fontSize: MailStyle.bodySmall @@ -96,8 +77,7 @@ Rectangle { Text { anchors.verticalCenter: parent.verticalCenter visible: root.text !== "" - // A label is words, never markup — and one of them carries a server's - // host name, which a stranger chose. + // Invariant: labels can contain server-controlled host names and must remain plain text. textFormat: Text.PlainText text: root.text color: root.ghost && (root.hot || root.selected) ? root.hoverColor : root.foreground diff --git a/ui/components/Icons.js b/ui/components/Icons.js index a0ae36785..cf3d09284 100644 --- a/ui/components/Icons.js +++ b/ui/components/Icons.js @@ -1,6 +1,6 @@ .pragma library -// Lucide geometry and license provenance: ../assets/lucide/README.md. +// Docs: Lucide geometry and license provenance: ../assets/lucide/README.md. var LUCIDE = { home: "house", tree: "tree-pine", diff --git a/ui/components/ImagePopover.qml b/ui/components/ImagePopover.qml index 57842548f..b681bef5b 100644 --- a/ui/components/ImagePopover.qml +++ b/ui/components/ImagePopover.qml @@ -5,12 +5,6 @@ import qs.Commons import qs.Ui import "../message/Html.js" as Html -// One image, floated over the reader. -// -// Plain text has nowhere to put a picture, so the body carries a marker where -// each image was and this is what the marker opens. It deliberately does not -// scale the image up: an image smaller than the window is shown at its own size -// rather than blown up to fill a frame it was never meant to fill. Item { id: root @@ -21,12 +15,9 @@ Item { required property string panelFontFamily property string source: "" - // What the marker pointed at, shown whether or not it was fetched, so a - // refusal names the thing it refused. property string requested: "" - // A sender's src is not a picture until it has been prepared as raster - // bytes. Qt fetches a remote Image source itself, so an http(s) address - // is refused here even if a caller forgets to go through the worker. + // Invariant: Qt fetches Image sources directly; accept only prepared raster data, never a sender + // URL. property bool refused: false anchors.fill: parent @@ -77,9 +68,7 @@ Item { id: frame spacing: MailStyle.space(6) - // Sized from the image's own dimensions, bounded by the window. Bounding - // it against the popup instead would be a loop: the popup is sized from - // this. + // Invariant: bound the image against the window, not the popup sized from that image. Image { id: picture source: root.source @@ -113,8 +102,8 @@ Item { color: root.dimColor font.family: root.panelFontFamily font.pixelSize: MailStyle.caption - // The sender wrote this. Left as AutoText, a src with a tag in it is - // markup Qt would lay out — and an in it a fetch it would make. + // Invariant: sender-controlled source labels must remain plain text to prevent Qt resource + // loading. textFormat: Text.PlainText elide: Text.ElideMiddle } diff --git a/ui/components/InviteCard.qml b/ui/components/InviteCard.qml index 133ee18be..df0ee2b51 100644 --- a/ui/components/InviteCard.qml +++ b/ui/components/InviteCard.qml @@ -4,26 +4,10 @@ import qs.Commons import qs.Ui import "../message/Calendar.js" as Calendar -// The meeting inside the message, drawn as the thing it is. -// -// A Google Calendar invitation reads badly as mail: the HTML part is a table -// of the same facts laid out for a browser, and the times in it are the -// organiser's, in the organiser's words. This is those facts read out of the -// `text/calendar` part instead — one clock, the reader's own — with the three -// buttons that answer it. -// -// It scrolls with the body rather than sitting above it. A recurring meeting -// with a dozen guests is taller than the panel, and pinning it would leave the -// message with nowhere to be. Rectangle { id: root - // The parsed invitation, or null. Everything here is derived from it, so a - // message with none draws nothing and takes no height. property var invite: null - // What this account has answered, as one of "accepted", "tentative" and - // "declined" — or empty, which is a guest who has not answered rather than - // one who said no. property string response: "" property bool canRespond: false property bool sending: false @@ -58,7 +42,6 @@ Rectangle { anchors.margins: MailStyle.space(12) spacing: MailStyle.space(6) - // ------------------------------------------------------------ heading Row { spacing: MailStyle.space(6) @@ -79,8 +62,8 @@ Rectangle { } } - // The organiser wrote this. Qt's AutoText would promote a summary with a - // tag in it to rich text, and rich text with an in it is a fetch. + // Invariant: organizer-controlled summaries must remain plain text to prevent Qt resource + // loading. Text { width: parent.width textFormat: Text.PlainText @@ -89,9 +72,6 @@ Rectangle { font.family: root.panelFontFamily font.pixelSize: MailStyle.body font.bold: true - // A cancelled meeting keeps its name legible rather than striking it - // through: the heading above already says what happened, and struck text - // at this size is hard to read on half the themes. wrapMode: Text.WordWrap } @@ -122,7 +102,6 @@ Rectangle { wrapMode: Text.WordWrap } - // --------------------------------------------------------------- where Item { width: 1; height: MailStyle.space(2); visible: whereRow.visible } @@ -151,7 +130,6 @@ Rectangle { } } - // -------------------------------------------------------------- people Row { width: parent.width @@ -183,8 +161,8 @@ Rectangle { } } - // Six of them, and then a count. A meeting with forty guests would - // otherwise be a card longer than the message it came in. + // Invariant: cap the visible guest list so large invitations do not occupy the entire message + // viewport. Column { width: parent.width spacing: MailStyle.space(2) @@ -226,7 +204,6 @@ Rectangle { font.pixelSize: MailStyle.caption } - // --------------------------------------------------------------- join Item { width: 1; height: MailStyle.space(4); visible: joinButton.visible || rsvpRow.visible } @@ -234,7 +211,6 @@ Rectangle { id: joinButton visible: !!root.invite && String(root.invite.meetLink || "") !== "" && !root.cancelled iconName: "video" - // A browser opens, so the label says so before it is pressed. text: root.invite && String(root.invite.meetLink || "").indexOf("meet.google.com") > 0 ? "Join with Google Meet..." : "Join the call..." @@ -245,7 +221,6 @@ Rectangle { onClicked: if (root.invite) root.openRequested(String(root.invite.meetLink || "")) } - // --------------------------------------------------------------- RSVP Row { id: rsvpRow @@ -272,8 +247,7 @@ Rectangle { anchors.verticalCenter: parent.verticalCenter enabled: !root.sending selected: root.response === modelData.answer - // The fill alone must never carry this: a theme can put the selected - // colour close enough to the normal one to say nothing at all. + // Invariant: the selected response needs a glyph as well as theme-dependent fill. iconName: root.response === modelData.answer ? "check" : "" text: modelData.label foreground: root.textColor @@ -324,9 +298,6 @@ Rectangle { } } - // What was answered, where there is no answering to be done — somebody - // else's reply, a cancelled meeting, an invitation this account is the - // organiser of. Text { width: parent.width visible: !root.canRespond && root.response !== "" diff --git a/ui/components/JmapSetupPage.qml b/ui/components/JmapSetupPage.qml index 69a52bc70..81efad4b8 100644 --- a/ui/components/JmapSetupPage.qml +++ b/ui/components/JmapSetupPage.qml @@ -6,19 +6,6 @@ import qs.Ui import "../providers/JmapProtocol.js" as Jmap import "../account/Accounts.js" as Accounts -// Connecting a mailbox on a server that speaks JMAP: an address, a secret, and -// — only if the address does not lead anywhere — the server. -// -// The page names no service. A JMAP server is one thing today and something -// else next year, and a form that told the user where to find their app -// password on two named providers would be wrong about the third. What it can -// say honestly is what kind of credential to bring. -// -// Two fields is the whole of it in the good case: the server is found from the -// address's domain, and which of Basic and Bearer the secret is happens to be -// is detected rather than asked. The disclosure holds the server for the case -// where discovery finds nothing, which on a self-hosted server is the ordinary -// case rather than the exception. Column { id: root @@ -39,13 +26,9 @@ Column { readonly property bool busy: !!auth && auth.loginBusy === true readonly property bool toolsMissing: !!auth && auth.toolsChecked === true && auth.missingTools !== undefined && auth.missingTools.length > 0 - // The client's own flag, forwarded through the account. A 401 raises it and - // a successful check clears it, so the card below is the state of the - // credential rather than a memory of one failed press. readonly property bool rejected: !!service && service.credentialsRejected === true readonly property int step: auth && auth.progressStep !== undefined ? auth.progressStep : 0 - // What sign-in found out about the server, for the two lines that report it. readonly property var settings: auth && auth.settings ? auth.settings : null readonly property string host: settings ? Jmap.sessionHost(settings.sessionUrl) : "" readonly property string schemeLabel: settings ? Jmap.schemeLabel(settings.authScheme) : "" @@ -62,12 +45,7 @@ Column { if (String(values.sessionUrl || "") !== "") serverField.text = String(values.sessionUrl) } - // Neither of these places the keyboard. The page is a component in the - // setup context and the context owns the focus — it parks the keyboard here, - // because a form is typed into by the field that was clicked — so a field - // that took focus on a state change would be the second mechanism that - // design replaces. The field is emptied, or revealed, and left for the - // person to pick up. + // Invariant: the window’s setup context owns focus; account state changes must not steal it. function clearSecret() { secretField.text = "" } @@ -76,11 +54,8 @@ Column { serversVisible = true } - // The address is this mailbox's identity rather than a label on it: - // `Accounts.accountId` derives the account id from it, and anything that is - // not an address derives the empty id a pending row carries. Checked here, - // against the same predicate that derives the id, while it is still a typo - // the user can see. + // Invariant: validate the address before accountId can turn an invalid address into a pending + // mailbox. function validatedAddress() { var address = addressField.text.trim() if (Accounts.isValidEmail(address)) return address @@ -90,11 +65,8 @@ Column { return "" } - // Written down before the secret is tried, so a mailbox the server refuses - // still has its address and its server to correct rather than an empty form. - // The session URL kept here is the typed server until sign-in replaces it - // with whatever actually answered — which is the same value `discoveryPlan` - // reads as its typed server, so a saved one is not discovered again. + // Invariant: persist editable server configuration before trying credentials so refusal does not + // erase it. function settingsFrom(typedServer) { var values = root.settings || {} return { @@ -112,8 +84,6 @@ Column { openServerField() return null } - // A typed server is the one step there is; anything else is discovery, - // which has no URL to write down yet. var first = plan.steps.length > 0 ? plan.steps[0] : null return first && first.kind === Jmap.STEP_TYPED ? first.url : "" } @@ -133,9 +103,8 @@ Column { }, secretField.text) } - // Save changes re-verifies: everything on this page is something the server - // has to agree with, so writing it down without asking would leave a mailbox - // that says it is signed in and answers nothing. + // Invariant: saving server settings re-verifies the connection; persisted values alone do not + // prove sign-in. function save() { signIn() } @@ -153,13 +122,12 @@ Column { function onLastErrorChanged() { if (root.auth && root.auth.lastError !== "") errorText.text = root.auth.lastError } - // Nothing answered for the domain. The server field is the way forward, so - // it is opened rather than described. + // Invariant: failed automatic discovery must expose the server field needed to continue. function onServerNeededChanged() { if (root.auth && root.auth.serverNeeded) root.openServerField() } - // The check has written the session URL down; the field should show what - // the account is actually using rather than what was typed at it. + // Invariant: successful discovery replaces the typed server with the session URL actually in + // use. function onSessionVerified(result) { errorText.text = "" var url = result ? String(result.sessionUrl || "") : "" @@ -167,7 +135,6 @@ Column { } } - // ------------------------------------------------------------------ hero ProviderHero { width: parent.width @@ -205,7 +172,6 @@ Column { } } - // -------------------------------------------------------------- the form Column { width: parent.width @@ -232,10 +198,6 @@ Column { onAccepted: secretField.forceActiveFocus() } - // Always shown, and naming nobody. Somebody about to paste the password - // they sign in to a website with is about to be refused, and this is the - // sentence that stops it — in body text rather than a caption, because it - // is the one thing on the page that is worth reading before typing. Rectangle { width: parent.width implicitHeight: noteText.implicitHeight + MailStyle.space(20) @@ -267,8 +229,6 @@ Column { objectName: "jmap-secret-field" anchors.left: parent.left anchors.right: parent.right - // Masked by default: this window is shoulder-surfable. Readable on - // demand, because a pasted token is a string nobody can check by eye. password: !root.secretVisible rightPadding: horizontalPadding + MailStyle.space(26) foreground: root.textColor @@ -308,11 +268,6 @@ Column { } } - // --------------------------------------------------------- what it is doing - // - // Three waits that look identical from outside. Naming which one is running - // is the difference between "it is working" and "it is stuck", and a check - // beside the ones already past is what says the next one is not the first. Column { id: progress @@ -347,9 +302,6 @@ Column { Text { anchors.verticalCenter: parent.verticalCenter visible: !line.done - // A bullet rather than a spinner: nothing here animates, and a row - // that reserved the icon's width would leave the three lines - // ragged. text: "·" color: line.running ? root.accentColor : root.dimColor font.family: root.panelFontFamily @@ -369,7 +321,6 @@ Column { } } - // ------------------------------------------------------------- signed in Column { width: parent.width @@ -389,10 +340,7 @@ Column { elide: Text.ElideRight } - // A missing submission capability does not fail sign-in — the mailbox - // reads perfectly well — so the account signs in and this says what it - // cannot do, rather than a Send button that fails after the message is - // written. + // Invariant: lack of submission support does not invalidate a mailbox’s read capability. Text { width: parent.width visible: root.sendingRefused @@ -404,20 +352,12 @@ Column { } } - // -------------------------------------------------------------- rejected - // - // The server refused the credential. Nothing here is signed out: the account, - // its server and its cache are all still right, and the one wrong thing is a - // string that has to be typed again. Rectangle { width: parent.width visible: root.rejected implicitHeight: rejectedText.implicitHeight + MailStyle.space(20) radius: Style.cornerRadius - // The same surface every other note on this page draws on, with the - // sentence in the danger colour rather than the box: colour alone never - // carries state here, and the words are what says what happened. color: Style.normalFillFor(root.textColor, root.accentColor) border.width: 1 border.color: Style.hoverBorderFor(root.textColor, root.accentColor) @@ -436,11 +376,6 @@ Column { } } - // ------------------------------------------------------- server settings - // - // Behind a disclosure, because the address is enough wherever the domain - // publishes a record or serves the well-known URL. Opened by the page when - // it is not, which is the only time most people will see these fields. Column { width: parent.width @@ -473,9 +408,6 @@ Column { placeholderText: "Server — mail.example.org, or the full session URL" } - // Only for the servers where the login name is not the address, which is - // common enough on self-hosted mail to be worth a field and rare enough - // to keep out of the way. Widgets.TextField { id: usernameField objectName: "jmap-username-field" @@ -530,8 +462,7 @@ Column { onClicked: root.save() } - // No sign-out while the credential is being re-entered: signing out would - // throw away the keyring entry and the cache to fix a string in a field. + // Invariant: sign-out must not race a credential write in progress. Widgets.Button { visible: root.signedIn && !root.rejected text: "Sign out" diff --git a/ui/components/KeyRouter.qml b/ui/components/KeyRouter.qml index 5f4d5dfe3..4de52e6e7 100644 --- a/ui/components/KeyRouter.qml +++ b/ui/components/KeyRouter.qml @@ -2,41 +2,14 @@ import QtQuick import QtQml import "../keys/Keymap.js" as Keymap -// Turns the key table into live Shortcuts, and reports what was pressed by id. -// -// The keyboard belongs to the application, and the context says what a key -// means where — actions are scoped, the way a TUI or GPUI scopes them. One -// place decides whether a binding is live, so there is no per-line `enabled:` -// expression to copy wrongly. Escape is routed here like every other key -// rather than through Keys.onEscapePressed, so it does not depend on which -// item happens to hold the focus. -// -// An Instantiator rather than a Repeater: a Shortcut is a QtObject, and a -// Repeater only builds Items, so a Repeater here creates nothing at all and -// every key silently goes dead. -// -// This component draws nothing and deliberately imports no theme, so it can be -// instantiated without the shell's singletons and exercised in tests/qml. Item { id: root - // Where the window is: one of Keymap.CONTEXTS. It is the only thing that - // decides what is live — a text-entry context binds no bare keys, so there is - // no separate "are they typing" question to keep in step with this one. property string context: "list" - // Something is covering the window and should be dismissed before anything - // else acts. Popups are excluded on purpose: a QQC.Popup with CloseOnEscape - // consumes its own keys, so the router never sees them. property bool overlay: false - // The sequence travels with the id, because one row can bind several keys - // that differ in what they mean: `Ctrl+1`…`Ctrl+9` are one binding and nine - // mailboxes. signal triggered(string id, string sequence) - // Native TextArea accepts ShortcutOverride for editing keys before a window - // Shortcut can run. Decode those forwarded events, then use the same table - // and context as the Shortcut path. Unbound events remain normal text input. function routeKeyEvent(event) { var key = "" if (event.key === Qt.Key_Up) key = "Up" @@ -68,8 +41,8 @@ Item { delegate: Shortcut { required property var modelData sequence: modelData.sequence - // Window-scoped so mailbox keys cannot match or ambiguously consume the - // standalone close chord, which is application-wide on purpose. + // Invariant: mailbox shortcuts remain window-scoped; only the standalone close chord is + // application-wide. context: Qt.WindowShortcut enabled: Keymap.isSequenceEnabled(modelData.binding, modelData.sequence, root.context, root.overlay) diff --git a/ui/components/LabelPicker.qml b/ui/components/LabelPicker.qml index 3f08bdb75..71d7a9515 100644 --- a/ui/components/LabelPicker.qml +++ b/ui/components/LabelPicker.qml @@ -6,13 +6,6 @@ import qs.Commons import qs.Ui import "../account/Model.js" as Model -// Where a message goes when it leaves the inbox with somewhere to be. -// -// The rail already names the mailboxes a key can reach; this is the rest of -// them, and on an account with thirty labels a list is only usable if it is -// narrowed by typing. So the field owns the focus from the moment it opens and -// the keyboard walks the list underneath it -- the destination is picked by -// typing three letters and pressing Return, never by arrowing through thirty. Item { id: root @@ -23,10 +16,7 @@ Item { required property color popupBorderColor required property string panelFontFamily - // [{ id, name, system, unread, total }], as the provider reported them. property var labels: [] - // The raw label or folder view already on screen, which cannot be its own - // move destination. property string currentLabelId: "" property string searchQuery: "" @@ -35,9 +25,6 @@ Item { readonly property var matchingLabels: Model.movableLabels( root.labels, root.searchQuery, root.currentLabelId) - // Where the keyboard is standing. Reset to the top on every keystroke - // because the list underneath it has changed: holding an index still would - // leave the cursor on whatever row happened to inherit that position. property int cursorIndex: 0 signal labelChosen(string labelId) @@ -54,10 +41,8 @@ Item { searchField.forceActiveFocus() } - // A Popup does not build its contents until it is first opened, so on the - // first open its height is still zero and centring it lands it high. Placing - // again on every height change is what makes the first open sit where all - // the later ones do, and it re-centres the card as typing shortens the list. + // Invariant: popup content is lazy; re-center after its initial height and after filtering + // changes it. function place() { if (!menu.visible) return var menuHeight = menu.height > 0 ? menu.height : menu.implicitHeight @@ -123,11 +108,8 @@ Item { } } - // The field answers the keys itself. Inside an open `QQC.Popup` a - // `KeyRouter` binding is the thing that would look live and never run -- - // the popup takes every key before the shortcut map sees it -- and this - // one has to intercept the arrows and Return before the text cursor - // does, while leaving every printable key to the filter. + // Invariant: QQC.Popup consumes window shortcuts; the filter handles navigation before + // text-cursor keys while preserving printable input. Widgets.TextField { id: searchField width: parent.width @@ -151,8 +133,7 @@ Item { root.chooseCursor() event.accepted = true } - // Escape is not here: the popup's own CloseOnEscape is already the - // one mechanism that closes it, and a second would be one too many. + // Invariant: CloseOnEscape is the sole Escape owner for this popup. } } @@ -166,8 +147,6 @@ Item { model: root.matchingLabels currentIndex: root.cursorIndex highlightMoveDuration: 0 - // Keeps the keyboard's row on screen once the list is longer than the - // card, which is the case this whole component exists for. onCurrentIndexChanged: positionViewAtIndex(currentIndex, ListView.Contain) QQC.ScrollBar.vertical: QQC.ScrollBar { policy: QQC.ScrollBar.AsNeeded } @@ -186,8 +165,6 @@ Item { border.width: labelRow.hasCursor ? Style.normalBorderWidth : 0 border.color: Style.hoverBorderFor(root.textColor, root.accentColor) - // A child steps in under its parent, and is named by its own - // leaf; a match to typed letters shows its whole path, flat. Text { anchors.left: parent.left anchors.leftMargin: MailStyle.space(10) + Math.min(8, Number(labelRow.modelData.depth) || 0) * MailStyle.space(12) @@ -206,10 +183,8 @@ Item { MouseArea { anchors.fill: parent - // A click moves the same cursor the arrow keys do. Activation is - // deliberately a second gesture — Return or a double-click — so - // a pointer user can inspect the highlighted destination before - // moving mail there. + // Invariant: a pointer click only selects a destination; Return or a double-click + // commits the move. onClicked: { root.cursorIndex = labelRow.index } @@ -221,10 +196,6 @@ Item { } } - // An account with no labels yet -- and a provider that has none at all -- - // would otherwise open an empty card that looks broken rather than - // empty, and typing past every match is the same picture arrived at a - // different way. Text { width: parent.width visible: root.matchingLabels.length === 0 diff --git a/ui/components/LinkLabel.qml b/ui/components/LinkLabel.qml index 0698daa5a..0b059ce90 100644 --- a/ui/components/LinkLabel.qml +++ b/ui/components/LinkLabel.qml @@ -3,15 +3,8 @@ import "../controls" as Widgets import qs.Commons import qs.Ui -// One word or phrase inside a line of text that is a link out of the window. -// -// Underlined, always: the affordance has to be there before the pointer is, and -// colour alone must never carry it — some themes put the accent close enough to -// the foreground that a recolour says nothing at all. -// -// The pointing-hand cursor is reserved for real links, which this is. Native -// controls elsewhere in the panel keep the arrow, and `tests/test_source.sh` -// enforces that for the files that hold them. +// Invariant: real links stay underlined and use a pointing cursor; color alone must not convey the +// affordance. Text { id: root diff --git a/ui/components/ListSkeleton.qml b/ui/components/ListSkeleton.qml index 00e434aa2..7c444f221 100644 --- a/ui/components/ListSkeleton.qml +++ b/ui/components/ListSkeleton.qml @@ -2,8 +2,7 @@ import QtQuick import "../settings" import qs.Commons -// Rows shaped like the message summaries that will replace them. One shared -// pulse keeps initial mailbox loading calm and cheap on the shell's GUI thread. +// Performance: one shared pulse drives all loading rows. Column { id: root diff --git a/ui/components/MenuActionRow.qml b/ui/components/MenuActionRow.qml index ce941a93f..8423fbd79 100644 --- a/ui/components/MenuActionRow.qml +++ b/ui/components/MenuActionRow.qml @@ -45,10 +45,8 @@ Rectangle { } HoverHandler { id: hover } - // The exclusive grab on press, not a passive one: a menu can sit over a - // message row, whose MouseArea takes the exclusive grab if this does not, - // and the release then opens the message under the menu instead of - // running the row that was clicked. + // Invariant: take the exclusive pointer grab on press so an underlying message row cannot consume + // the release. TapHandler { gesturePolicy: TapHandler.ReleaseWithinBounds onTapped: root.activated() diff --git a/ui/components/MessageRow.qml b/ui/components/MessageRow.qml index e02b4c8a8..051afedc4 100644 --- a/ui/components/MessageRow.qml +++ b/ui/components/MessageRow.qml @@ -7,9 +7,8 @@ import "../message/Direction.js" as Direction import "../account/Model.js" as Model import "../keys/Keymap.js" as Keymap -// One message in the list. Unread is carried by weight and by the dot on the -// left, never by colour alone — the accent is a theme value that some themes -// put close to the foreground. +// Invariant: unread state uses weight and a dot because theme accent alone may be +// indistinguishable. Rectangle { id: root @@ -21,27 +20,16 @@ Rectangle { required property string panelFontFamily property bool canArchive: true property bool attachmentIndicatorEnabled: true - // Whether this row stands for a conversation rather than for one message. - // Grouping is a panel rule gated on the provider's `conversations` - // capability; a row is told, and asks nobody. property bool conversations: false property bool hasCursor: false property bool selected: false - // Ticked for a bulk action. Not `selected`: that is the message the reader - // shows, and the two are different things for the same reason the cursor is. property bool checked: false - // What the agent is doing with this message, if anything: "", "running", - // "question", "done", "failed" or "cancelled". State, so it shows whether - // or not the row is hot, like the star. property string agentState: "" - // The agent's last line while it works on this message, for the tooltip. property string agentProgress: "" property bool agentAttention: false property bool selectionActive: false property bool ctrlHeld: false readonly property bool selectionMode: selectionActive || checked || ctrlHeld - // How the direction of this message's own text is arrived at. Passed down - // like every other fact a row draws, because a row decides nothing. property string contentDirection: Direction.MODE_DEFAULT signal activated() @@ -60,37 +48,22 @@ Rectangle { signal trashRequested() signal menuRequested(real sceneX, real sceneY) - // Hovered by a handler rather than by the MouseArea's `containsMouse`: a - // button on the row has a MouseArea of its own, and the pointer moving onto - // one took the row's hover away — the extra buttons hid, the lane closed, - // the button slid out from under the pointer, the row was hovered again, - // and the lane flickered open and shut. A HoverHandler is passive and stays - // hovered whatever the pointer is over inside the row. + // Invariant: a passive HoverHandler keeps the action lane open while the pointer enters child + // buttons; MouseArea hover would flicker as buttons move. readonly property bool hot: rowHover.hovered || hasCursor HoverHandler { id: rowHover } - // How many messages the conversation holds, for the badge — and zero for a - // row that draws none, which `Model.badgeCount` decides: a provider that does - // not group its listing, a conversation of one, a summary cached before rows - // carried a block at all. readonly property int threadCount: Model.badgeCount(root.summary) - // The subject is asked on its own account: a reply prefix is Latin whatever - // the thread is written in, so `Re: مرحبا` reads left-to-right to anything - // that takes the first strong character at face value — which is every - // message in a thread after the first. - // - // The sender and the snippet are not. Qt resolves both correctly from their - // own text, so on Auto there is nothing to add; only a direction the reader - // has actually chosen has to be carried to them. + // Invariant: Latin reply prefixes must not determine subject direction; sender and snippet still + // use their own first strong character. readonly property var subjectAlignment: alignmentFor( Direction.forced(root.contentDirection) || String(root.summary.subjectDirection || "")) readonly property var textAlignment: alignmentFor( Direction.forced(root.contentDirection)) - // `undefined` leaves a Text following the direction of its own text, which is - // what should happen wherever there is no answer to give it. + // Invariant: undefined alignment preserves Qt’s content-derived direction. function alignmentFor(direction) { if (!Direction.hasAnswer(direction)) return undefined return Direction.isRightToLeft(direction) ? Text.AlignRight : Text.AlignLeft @@ -99,7 +72,6 @@ Rectangle { width: parent ? parent.width : 0 implicitHeight: body.implicitHeight + MailStyle.space(14) radius: Style.cornerRadius - // The checkbox identifies bulk selection independently of the reader fill. color: selected || hasCursor || checked ? Style.selectedFillFor(textColor, accentColor) : (hot ? Style.hoverFillFor(textColor, accentColor) : "transparent") @@ -107,9 +79,8 @@ Rectangle { MouseArea { id: mouse anchors.fill: parent - // HoverHandler already owns `hot`. hoverEnabled here re-enters every row - // when the window moves under a still pointer, which is extra scene work - // during a system drag. + // Performance: HoverHandler owns hover; duplicate MouseArea hover re-enters every row during + // native window movement. hoverEnabled: false acceptedButtons: Qt.LeftButton | Qt.MiddleButton | Qt.RightButton onWheel: function(wheel) { wheel.accepted = false } @@ -118,12 +89,8 @@ Rectangle { var scene = mapToGlobal(event.x, event.y) root.menuRequested(scene.x, scene.y) } else if (event.button === Qt.MiddleButton) { - // Middle-click archives: the one triage action worth having without - // moving the pointer to a button. root.archiveRequested() } else if (event.modifiers & Qt.ShiftModifier) { - // Shift selects or clears the range from the cursor to here; - // Ctrl toggles this row on its own. root.checkRangeRequested() } else if (event.modifiers & Qt.ControlModifier) { root.checkToggled() @@ -153,13 +120,10 @@ Rectangle { anchors.left: parent.left anchors.right: parent.right anchors.leftMargin: MailStyle.space(14) + avatar.width + MailStyle.space(10) - // Align text with the action glyph, rather than its padded hit target. anchors.rightMargin: MailStyle.space(6) + (MailStyle.space(24) - Style.font.iconSmall) / 2 anchors.verticalCenter: parent.verticalCenter spacing: MailStyle.space(2) - // The sender and optional conversation count share the first line with - // the date, which keeps the full row edge while actions appear below. Item { width: parent.width implicitHeight: Math.max(sender.implicitHeight, time.implicitHeight) @@ -179,12 +143,6 @@ Rectangle { horizontalAlignment: root.textAlignment } - // How long the conversation is, beside who wrote it — where Gmail puts - // it, and the one place on the row that is about the thread rather than - // about the message the server returned for it. - // - // Drawn only where the model gave it a number: two or more, on a provider - // that groups its listing. Text { id: count objectName: "message-conversation-count" @@ -217,7 +175,7 @@ Rectangle { id: subject objectName: "message-subject" width: Math.max(0, parent.width - (actions.visible ? actions.width + MailStyle.space(4) : 0)) - // Sender-controlled text must never activate Qt's rich-text loader. + // Invariant: sender-controlled labels must never activate Qt’s rich-text loader. textFormat: Text.PlainText text: root.summary.subject color: root.textColor @@ -266,9 +224,6 @@ Rectangle { } } - // Row actions appear on hover or under the keyboard cursor. A starred - // message keeps its star visible either way, because that is state rather - // than an affordance. Row { id: actions objectName: "message-actions" @@ -305,9 +260,8 @@ Rectangle { } IconButton { - // No archive button where the account has nowhere to archive to. On IMAP - // that is a move to a folder, and a server without one would have this - // quietly do nothing. + // Invariant: an account without an archive destination must not expose an action that cannot + // move the message. visible: root.hot && root.canArchive && !root.selectionMode iconName: "archive" tooltipText: "Archive · e" @@ -332,8 +286,6 @@ Rectangle { onClicked: root.trashRequested() } - // The selection target stays on the same right edge, even while the - // other actions make room for a selection being built across rows. Item { id: checkControl objectName: "message-check" diff --git a/ui/components/NamePrompt.qml b/ui/components/NamePrompt.qml index 8d5f6cd9a..351521c74 100644 --- a/ui/components/NamePrompt.qml +++ b/ui/components/NamePrompt.qml @@ -5,9 +5,6 @@ import QtQuick.Controls as QQC import qs.Commons import qs.Ui -// One name, asked for: a new label's, or a label's new one. A small modal -// popup rather than a page, because the answer is a word and the place it -// applies to is still on screen behind it. Item { id: root @@ -18,11 +15,8 @@ Item { required property color accentColor required property string panelFontFamily - // What the answer is for, handed back with it so one prompt serves every - // caller: `kind` names the operation, `subject` the label it is about. property string kind: "" - // Whose label this is: the account open when the popup opened, by id, - // so the answer goes to it even if the window has moved on since. + // Invariant: the prompt retains the account that owned the label when it opened. property string accountId: "" property string subject: "" property string title: "" diff --git a/ui/components/OutlookSetupPage.qml b/ui/components/OutlookSetupPage.qml index f3450c7cb..96d3760bb 100644 --- a/ui/components/OutlookSetupPage.qml +++ b/ui/components/OutlookSetupPage.qml @@ -7,9 +7,8 @@ import "../providers/Outlook.js" as Outlook import "../providers/MicrosoftOAuth.js" as Microsoft import "../account/Accounts.js" as Accounts -// Outlook.com and Hotmail use Microsoft OAuth. The app registration is a -// public client: its ID is configuration, not a secret, and the account -// password is entered only on Microsoft's own page. +// Invariant: Microsoft registration uses a public client ID; the account password belongs only on +// Microsoft’s sign-in page. Column { id: root @@ -26,8 +25,6 @@ Column { readonly property var auth: service ? service.auth : null readonly property bool signedIn: !!auth && auth.loggedIn readonly property bool busy: !!auth && (auth.loginBusy || auth.graphRoundBusy === true) - // Signed in for mail, and Microsoft refused Graph for want of consent: - // the sign-in button stays, as the Graph sign-in. readonly property bool graphConsentNeeded: root.signedIn && !!auth && auth.graphConsentNeeded === true readonly property bool usingBuiltinClient: Microsoft.isValidClientId(Microsoft.BUILTIN_CLIENT_ID) readonly property bool toolsMissing: !!auth && auth.toolsChecked && auth.missingTools.length > 0 @@ -85,8 +82,6 @@ Column { function signIn() { if (root.busy) return if (root.graphConsentNeeded) { - // Nothing to save: the mailbox is set up and signed in. The code - // asked for is Graph's. errorText.text = "" auth.beginLogin() return @@ -124,8 +119,7 @@ Column { graphSwitch.checked = !!auth && String(auth.configuredSend || "") === "graph" } - // The auth object is rebuilt when the entry is saved, so the switches are - // read again from whichever one is current. + // Invariant: saving an account rebuilds auth; refresh switches from the current instance. onAuthChanged: { connectionSerial++ connectionBusy = false @@ -222,9 +216,6 @@ Column { onAccepted: root.signIn() } - // A work or school mailbox lives in its own tenant rather than the - // consumer one, and submits through Microsoft 365's SMTP host — or, where - // the tenant has switched authenticated SMTP off, through Graph. Row { width: parent.width spacing: MailStyle.space(10) @@ -246,7 +237,6 @@ Column { font.pixelSize: MailStyle.bodySmall } - // The slider alone does not say which way is on. Text { anchors.verticalCenter: parent.verticalCenter text: workSwitch.checked ? "On" : "Off" diff --git a/ui/components/ProviderHero.qml b/ui/components/ProviderHero.qml index 45ad6d0bc..f6da5c39f 100644 --- a/ui/components/ProviderHero.qml +++ b/ui/components/ProviderHero.qml @@ -6,22 +6,6 @@ import qs.Ui import "../providers/Registry.js" as Provider import "../account/Model.js" as Model -// What a setup page opens with: the service's own mark, its name, and one line -// saying what connecting it involves. -// -// The mark and the brand word in the heading are one link to the service's -// website, because that is where everything this window deliberately does not -// do still lives — HEY's Screener, Gmail's filters and forwarding. Only the -// brand word: a heading that is entirely a link reads as one somebody made -// clickable by accident, and the sentence around it is not about the website. -// -// It is also the one place in the panel where a pointing-hand cursor is right. -// This is a link in the ordinary sense rather than a native control, and it is -// underlined for the same reason — the affordance has to be there before the -// pointer is, and colour alone must never carry it. -// -// Shared by both setup pages rather than written twice: they ask the same -// question in the same place, and the two heroes had already drifted once. Item { id: root @@ -36,7 +20,6 @@ Item { readonly property string website: Provider.webHomeUrl(providerId) readonly property bool linked: website !== "" - // The heading, cut around the one word in it that is the link. readonly property var parts: Model.splitBrand(title, Provider.badge(providerId)) implicitHeight: Math.max(logo.height, heroText.implicitHeight) @@ -73,9 +56,8 @@ Item { anchors.top: parent.top spacing: MailStyle.space(4) - // No spacing: the gaps around the brand word are the ones the sentence - // already had, and a Row that added its own would space "Add a HEY mailbox" - // twice. + // Invariant: the sentence already contains the spaces around its linked brand word; Row spacing + // would double them. Row { spacing: 0 @@ -101,7 +83,6 @@ Item { onActivated: root.websiteRequested() } - // The same word, plain, for a provider with no website to point at. Text { anchors.verticalCenter: parent.verticalCenter visible: root.parts.brand !== "" && !root.linked diff --git a/ui/components/ProviderLogo.qml b/ui/components/ProviderLogo.qml index 96eaa30be..e2831a37c 100644 --- a/ui/components/ProviderLogo.qml +++ b/ui/components/ProviderLogo.qml @@ -4,32 +4,13 @@ import qs.Commons import qs.Commons as Commons import qs.Ui -// The mark of the service a setup page is about. -// -// It answers "which mailbox am I adding" before any of the words do, which is -// the one question a setup page opens with. A provider with no mark of its own -// — IMAP is a protocol rather than a brand — draws nothing and takes no room, -// so the page above it needs no branch of its own. -// -// The file comes from `Registry.logo`, and the directory from here: the source -// is resolved against this component's own URL, so it is right whether the -// plugin was cloned into the Omarchy plugins directory or symlinked from a -// checkout. Nothing has to be told where it was installed. Item { id: root - // A file name in `assets/`, or "" for a provider that has none. required property string logo - // The height. Width follows from the artwork, because a brand's own lockup - // decides its own proportions: Gmail's mark is square, HEY's is a wordmark - // more than twice as wide as it is tall, and forcing either into the other's - // box would either crop it or strand it in empty space. + // Invariant: provider artwork retains its own proportions; only its height is constrained. property real size: MailStyle.space(40) - // What to draw for a provider with no artwork of its own. An envelope, in the - // theme's colour, because that is what IMAP honestly is: a mailbox somewhere, - // and no brand this could put a name to. Left empty where a missing mark - // should simply take no room. property string fallbackIcon: "" property color fallbackColor: Commons.Color.foreground @@ -49,16 +30,13 @@ Item { anchors.fill: parent visible: root.drawn source: root.drawn ? "../assets/" + root.logo : "" - // Only the height is asked for, so the width — and with it `aspect` — comes - // from the file rather than from an assumption here. Twice the drawn size, - // because letting Qt scale the whole image down instead is how a logo comes - // out soft on a HiDPI screen. + // Invariant: load at twice the drawn height for HiDPI clarity while deriving width from the + // artwork. sourceSize.height: Math.round(root.size * 2) fillMode: Image.PreserveAspectFit smooth: true - // Loaded on the spot rather than asynchronously: these are a few kilobytes - // each, and an async load reports no size for a frame — which is a logo - // that starts square and jumps to its real width once the page is drawn. + // Invariant: these small bundled assets load synchronously to avoid a zero-size frame and + // layout jump. asynchronous: false cache: true } @@ -67,9 +45,6 @@ Item { anchors.centerIn: parent visible: !root.drawn && root.fallbackIcon !== "" name: root.fallbackIcon - // A shade under the slot, so a drawn glyph and a piece of artwork carry the - // same weight in a row: the artwork fills its box and a stroked glyph does - // not. iconSize: Math.round(root.size * 0.8) color: root.fallbackColor } diff --git a/ui/components/ProviderPicker.qml b/ui/components/ProviderPicker.qml index 36ef8e7a2..6b19bf219 100644 --- a/ui/components/ProviderPicker.qml +++ b/ui/components/ProviderPicker.qml @@ -4,17 +4,6 @@ import qs.Commons import qs.Ui import "../providers/Registry.js" as Provider -// Which kind of mailbox is being added, asked once and before anything else. -// -// It exists because the two setups have nothing in common: one is a Google -// Cloud walkthrough and the other is an address and a password. Guessing from -// the address would be worse than asking — a Gmail address is a legitimate -// IMAP account, and picking the wrong one for the user costs them the whole -// setup before they find out. -// -// A provider with nothing behind it is listed and disabled rather than hidden. -// Somebody looking for HEY should find the answer here, not conclude the app -// forgot about it. Column { id: root @@ -71,16 +60,8 @@ Column { : Style.normalFillFor(root.textColor, root.accentColor) border.width: 1 border.color: Style.hoverBorderFor(root.textColor, root.accentColor) - // Not greyed out with a literal colour — the theme owns those. Reduced - // opacity says "not available" without inventing a grey that some - // themes render as ordinary body text. opacity: card.connectable ? 1.0 : 0.55 - // The service's own icon, so the row is recognisable before it is read. - // A provider with no artwork gets an envelope in the theme's colour - // rather than nothing at all: an empty slot would leave its text - // hanging out of line with the rows above it, which reads as a fault - // rather than as "this one has no logo". ProviderLogo { id: cardMark anchors.left: parent.left @@ -114,8 +95,6 @@ Column { Text { width: parent.width textFormat: Text.PlainText - // The summary for a provider that works, and the reason for one - // that does not. Never both, and never a card that says nothing. text: card.connectable ? Provider.summary(card.modelData) : Provider.unavailableReason(card.modelData) diff --git a/ui/components/ReaderNotice.qml b/ui/components/ReaderNotice.qml index 2931eb3e5..a2ff7cee8 100644 --- a/ui/components/ReaderNotice.qml +++ b/ui/components/ReaderNotice.qml @@ -5,20 +5,11 @@ import QtQuick.Controls import qs.Commons import qs.Ui -// A line above the message saying why it does not look the way the sender -// meant it to, and offering the one thing that would change that. -// -// There are three of these and they stack, which is the reason this is a type -// rather than three near-identical rectangles: they have to be the same height, -// the same fill and the same distance apart, or a message that trips two of -// them looks like a bug rather than like two answers to two questions. Rectangle { id: root property string text: "" property string actionLabel: "" - // While the action is in flight. The button says so rather than disappearing, - // because a control that vanishes under the pointer reads as a misclick. property bool busy: false property string busyLabel: "" required property color textColor @@ -40,10 +31,6 @@ Rectangle { anchors.right: action.visible ? action.left : parent.right anchors.rightMargin: MailStyle.space(6) anchors.verticalCenter: parent.verticalCenter - // A stranger's mail decides when this shows but never what it says, so the - // string is this app's own — plain text all the same, because the rule - // that every Text in the reader declares its format has no exceptions - // worth remembering. textFormat: Text.PlainText text: root.text color: root.dimColor diff --git a/ui/components/ReaderSkeleton.qml b/ui/components/ReaderSkeleton.qml index e97ba8a3d..e6cb084ec 100644 --- a/ui/components/ReaderSkeleton.qml +++ b/ui/components/ReaderSkeleton.qml @@ -3,19 +3,13 @@ import "../settings" import qs.Commons import qs.Ui -// What the reader shows while a message is on its way. -// -// Shaped like the thing that is coming — a subject, a sender, a meta line, -// then body — so the pane does not jump when the real message lands. A word -// like "Opening…" tells you nothing you did not already know from clicking. Item { id: root required property color textColor required property string panelFontFamily - // One animation drives every bar. Running it per bar would put a dozen - // timers on the GUI thread to say a single thing. + // Performance: one animation drives all bars rather than adding one GUI-thread timer per bar. property real pulse: 0.5 SequentialAnimation on pulse { @@ -32,13 +26,11 @@ Item { anchors.margins: MailStyle.space(14) spacing: MailStyle.space(8) - // Subject: two lines, the second short, the way a long subject wraps. Bar { widthFactor: 0.82; barHeight: MailStyle.space(13) } Bar { widthFactor: 0.46; barHeight: MailStyle.space(13) } Item { width: 1; height: MailStyle.space(4) } - // Sender, then the recipients-and-date line under it. Bar { widthFactor: 0.38; barHeight: MailStyle.space(9) } Bar { widthFactor: 0.52; barHeight: MailStyle.space(8) } @@ -51,7 +43,6 @@ Item { Item { width: 1; height: MailStyle.space(6) } - // Body: paragraphs of a few lines each, with a short last line. Repeater { model: [0.96, 0.99, 0.72, 0.0, 0.94, 0.88, 0.97, 0.54, 0.0, 0.92, 0.63] diff --git a/ui/components/RecipientSuggestions.qml b/ui/components/RecipientSuggestions.qml index cbf274993..e796099ac 100644 --- a/ui/components/RecipientSuggestions.qml +++ b/ui/components/RecipientSuggestions.qml @@ -42,8 +42,8 @@ Rectangle { implicitHeight: Math.min(suggestions.contentHeight, MailStyle.space(210)) + MailStyle.space(4) height: implicitHeight radius: Style.cornerRadius - // Theme popup colors may carry transparency for floating shell panels. - // This menu sits over form rows, so preserve its hue but make it opaque. + // Invariant: theme popup colors may be transparent; this menu needs an opaque surface above form + // rows. color: Qt.rgba(popupBackgroundColor.r, popupBackgroundColor.g, popupBackgroundColor.b, 1) border.width: 1 border.color: popupBorderColor diff --git a/ui/components/SearchBar.qml b/ui/components/SearchBar.qml index fbe8d057c..11963075d 100644 --- a/ui/components/SearchBar.qml +++ b/ui/components/SearchBar.qml @@ -4,8 +4,6 @@ import "../settings" import qs.Commons import qs.Ui -// Gmail's own operator syntax goes straight through — `from:`, `has:attachment`, -// `older_than:7d`. Translating it would only take away what people already know. Item { id: root @@ -14,19 +12,13 @@ Item { required property string panelFontFamily property bool serverSearching: false - // Keep the words while the field has room for both them and the query. The - // rotating refresh remains at narrow widths, where a status sentence would - // leave almost no editable field behind. readonly property bool showServerLabel: width >= MailStyle.space(260) signal submitted(string query) signal cleared() - // The window's single-letter shortcuts stand down while this has focus. readonly property bool fieldFocused: field.activeFocus - // What Escape has to decide between clearing and leaving alone. The window - // owns that decision now: a window Shortcut beats a focused item's Keys - // handler, so a local one here would look live and never run. + // Invariant: window shortcuts own Escape; a focused-item Keys handler would never receive it. readonly property string queryText: field.text implicitHeight: field.implicitHeight @@ -41,9 +33,6 @@ Item { root.cleared() } - // A search the app built shows its words here, so the field and the list - // agree about what is on screen. Nothing is submitted: the caller has run - // the search already. function setQuery(text) { field.text = String(text || "") } @@ -53,9 +42,6 @@ Item { anchors.fill: parent foreground: root.textColor accent: root.accentColor - // The operator examples earn their place: they are the whole reason the - // field takes Gmail syntax straight through, and nowhere else says so at - // the moment you would use it. placeholderText: "Search..." font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall @@ -63,23 +49,12 @@ Item { + (root.serverSearching ? serverState.width + MailStyle.space(7) : 0) onAccepted: root.submitted(text.trim()) - // Quieter than the kit's own control surface, which outlines the field at - // rest. Nothing in the header is used less often than search, and an - // outlined box that wide was the loudest thing in a row of dim icons. It - // draws itself when the pointer is on it and commits to a border only once - // it has focus, which is the moment the outline is actually telling you - // something. The padding is unchanged either way, so nothing shifts. background: Rectangle { radius: Style.cornerRadius color: field.activeFocus || field.hovered ? Style.hoverFillFor(root.textColor, root.accentColor) : Style.normalFillFor(root.textColor, root.accentColor) border.width: 1 - // A divider's weight, not a control's. The kit's control border is what - // made this the loudest thing in a row of dim icons; the rail's edge is - // drawn at 0.12 of the foreground and is present without announcing - // itself, which is what a field nobody uses on most visits should be. - // Focus still gets the real border, because then it is saying something. border.color: field.activeFocus ? Style.hoverBorderFor(root.textColor, root.accentColor) : Qt.rgba(root.textColor.r, root.textColor.g, root.textColor.b, 0.12) diff --git a/ui/components/SenderNameField.qml b/ui/components/SenderNameField.qml index 8ed29ae7f..942d100a5 100644 --- a/ui/components/SenderNameField.qml +++ b/ui/components/SenderNameField.qml @@ -3,10 +3,6 @@ import "../controls" as Widgets import qs.Commons import qs.Ui -// The name recipients see beside this mailbox's address, asked for where the -// mailbox is set up so its first message is not sent nameless. Only on the -// pages for mailboxes whose server does not name the sender -// (`Accounts.namesSender`), and only on a backend that writes it. Widgets.TextField { id: root @@ -18,7 +14,6 @@ Widgets.TextField { placeholderText: "Your name (optional) — shown to recipients as the sender" function syncFromStore() { text = service ? String(service.accountSenderName || "") : "" } - // Left out of the form while unavailable, so the entry keeps what it has. function value() { return available ? String(text || "").trim() : undefined } Component.onCompleted: syncFromStore() diff --git a/ui/components/SettingsSidebar.qml b/ui/components/SettingsSidebar.qml index e1ee70740..673064a93 100644 --- a/ui/components/SettingsSidebar.qml +++ b/ui/components/SettingsSidebar.qml @@ -3,20 +3,9 @@ import "../settings" import qs.Commons import qs.Ui -// The rail beside the settings page: its section names, one highlighted. -// -// It is for getting about a page that is long, not for splitting it into -// pages that are short. A click scrolls the page to the section; the -// highlight follows wherever the page is scrolled to, by whatever means. The -// page owns the scroll and the rules (`Model.activeSettingsSection`) decide -// the highlight, so this draws what it is given: the names, and which one. -// -// The rows look like the mailbox rail's, on purpose. A second kind of -// sidebar in the same window would be a second thing to learn. Column { id: root - // [{ key, title, y }], in the order the page shows them. property var sections: [] property string activeKey: "" required property color textColor @@ -57,8 +46,7 @@ Column { color: entry.selected ? root.textColor : root.dimColor font.family: root.panelFontFamily font.pixelSize: MailStyle.bodySmall - // Weight as well as fill, so a theme whose selected fill is close to - // the rail's ground still shows which row is current. + // Invariant: selected sections use font weight as well as theme-dependent fill. font.bold: entry.selected elide: Text.ElideRight } diff --git a/ui/components/ShortcutHelp.qml b/ui/components/ShortcutHelp.qml index c43d4722a..ce32a1e3d 100644 --- a/ui/components/ShortcutHelp.qml +++ b/ui/components/ShortcutHelp.qml @@ -6,18 +6,6 @@ import qs.Ui import "../keys/Keymap.js" as Keymap import "../account/Model.js" as Model -// The reference sheet behind ?. A plain list rather than a dialog because it -// never needs an answer — Esc, ? again, or a click puts it away. -// -// **Wide and short, in as many columns as the window has room for.** One narrow -// column was taller than a short window, so it scrolled — and because the -// Flickable was only as wide as that column, its scrollbar rode the column's -// own edge and drew a bar down the middle of the screen. The Flickable fills -// the sheet now, which puts the scrollbar where a scrollbar belongs, and at two -// or three columns there is usually nothing left to scroll. -// -// The Flickable stays for the case that remains: a narrow window, where one -// column is all that fits and every binding still has to be reachable. Rectangle { id: root @@ -29,12 +17,6 @@ Rectangle { signal dismissed() - // The keyboard's answer to a sheet that scrolls. `j`/`k` survive the overlay - // for this and nothing else, so the reference sheet is not the one screen in - // the window that needs a mouse to read. - // The third copy of the same clamp, and now the same one the wheel and - // `contentYToReveal` use: a range that knows about margins and `originY` - // rather than assuming 0 to `contentHeight - height`. function scrollBy(steps) { if (!scroller.interactive) return scroller.contentY = Model.clampContentY( @@ -43,21 +25,10 @@ Rectangle { scroller.height, scroller.topMargin, scroller.bottomMargin)) } - // How wide one column of keys and their labels wants to be, and how many of - // them this window can hold. Three is the ceiling: past that the sheet is - // wider than it is readable, and the eye has to travel further to cross it - // than to scroll it. readonly property real columnWidth: MailStyle.space(330) readonly property int columnCount: Math.max(1, Math.min(3, Math.floor((width - MailStyle.space(60)) / columnWidth))) - // From the table, so this sheet cannot drift from what the keys actually do. - // It used to be written by hand, and had: Esc listed twice, no `u` and no - // `?`, and "Right-click a row" among the keyboard shortcuts. - // - // The split into columns is the table's too: balancing it here would put a - // layout decision in a view, and the rule — in order, a heading counts as a - // line — is worth a test. readonly property var columns: Keymap.helpColumns(columnCount, hiddenBindings) color: Qt.rgba(backgroundColor.r, backgroundColor.g, backgroundColor.b, 0.96) @@ -71,9 +42,8 @@ Rectangle { id: scroller WheelScroller { view: scroller } - // Filling the sheet rather than hugging the content is the whole of the - // scrollbar fix: a Flickable sized to its column puts the bar at that - // column's edge, which on a wide window is the middle of the screen. + // Invariant: the Flickable fills the sheet so its scrollbar stays at the window edge, not an + // interior column. anchors.fill: parent anchors.margins: MailStyle.space(20) contentWidth: width @@ -84,19 +54,13 @@ Rectangle { interactive: contentHeight > height ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } - // An interactive Flickable accepts the press itself, so the dismiss - // MouseArea underneath stops seeing clicks on the sheet — which is exactly - // the tall list this Flickable exists for. A tap is not a drag: a flick - // scrolls and does not close. + // Invariant: a Flickable consumes presses; distinguish a dismissing tap from a scrolling drag. TapHandler { onTapped: root.dismissed() } - // A Flickable reparents its children, so an x written against the - // Flickable's own width lands before that reparenting settles. The holder - // owns the width, and the sheet centres inside it — and stays centred - // vertically too for as long as it fits, which is what it did when the - // Flickable was the size of its content. + // Invariant: a Flickable reparents children; center the sheet against a stable holder width + // after reparenting. Item { id: holder width: scroller.width @@ -171,9 +135,6 @@ Rectangle { Text { anchors.left: parent.left anchors.verticalCenter: parent.verticalCenter - // Keeps its share of the column rather than a fixed - // measure: at three columns a fixed one left the label - // no room at all. width: Math.round(parent.width * 0.54) text: Keymap.keycapLabel(modelData.keys) color: root.textColor diff --git a/ui/components/SwitcherSearch.qml b/ui/components/SwitcherSearch.qml index 5b297793f..946dc6853 100644 --- a/ui/components/SwitcherSearch.qml +++ b/ui/components/SwitcherSearch.qml @@ -3,20 +3,12 @@ import "../controls" as Widgets import qs.Commons import qs.Ui -// The line at the top of a switcher that typing goes into. Letters narrow -// the rows to the ones they name; the arrows, or Ctrl with J, K, N or P, -// walk what is left; Enter opens the row the cursor is on. Where the rows -// carry numbers, a bare digit with nothing typed opens the row that -// carries it — and only when a row does carry it, so a name of numbers can -// still be typed. The account switcher's rows carry none. Widgets.TextField { id: root signal moved(int delta) signal chosen() signal numbered(int number) - // The numbers the rows on show carry, or none: a digit is a key only - // for one of these, and a letter otherwise. property var numbers: [] objectName: "switcher-search" diff --git a/ui/components/UndoSendToast.qml b/ui/components/UndoSendToast.qml index 23ae49a74..d73959ea9 100644 --- a/ui/components/UndoSendToast.qml +++ b/ui/components/UndoSendToast.qml @@ -8,8 +8,6 @@ Rectangle { id: root required property int secondsRemaining - // How many sends are parked. Past one, the countdown is the newest's and - // Undo says so. property int queuedCount: 1 property bool awaitingConnection: false required property color textColor diff --git a/ui/components/WeekCalendarView.qml b/ui/components/WeekCalendarView.qml index c1cad15f2..4695522f9 100644 --- a/ui/components/WeekCalendarView.qml +++ b/ui/components/WeekCalendarView.qml @@ -341,9 +341,6 @@ Item { } } - // Read off the rail rather than off the line: the hour labels stop at the - // hour, so a line between two of them otherwise says only "somewhere in - // here". Hidden when today is not the week on screen. Rectangle { readonly property real offset: Calendar.weekNowOffset( root.days, root.firstHour, root.lastHour, timeline.hourHeight, root.nowMs) @@ -586,8 +583,8 @@ Item { } } - // Keep the line behind event text; the gutter time and dot remain - // visible without striking through a meeting's title. + // Invariant: keep the current-time line behind event text so it cannot strike through a + // meeting title. Item { readonly property real offset: Calendar.nowOffset( dayColumn.modelData, root.firstHour, root.lastHour, diff --git a/ui/components/WheelScroller.qml b/ui/components/WheelScroller.qml index 05cdc15cd..e7a5f9229 100644 --- a/ui/components/WheelScroller.qml +++ b/ui/components/WheelScroller.qml @@ -1,24 +1,8 @@ import QtQuick import "../account/Model.js" as Model -// Wheel scrolling for a Flickable, because the Flickable's own is wrong on a -// mouse that reports finely — and, on a laptop, on two-finger scroll too. -// -// A Flickable answers each wheel event with a flick it then decelerates, so -// the distance depends on how the turn was chopped up rather than on how far -// the fingers or the wheel went. Chromium and the terminal compensate; -// this window did not, and crawled. The handler takes the event from -// anything under the pointer (`CanTakeOverFromAnything`) and moves -// `contentY` on the same frame by `Model.wheelPixels`. -// -// `pixelDelta` wins when the device reports it. Otherwise the notch mapping -// still applies, doubled so a 2x panel travels about as far as Chromium. -// -// A handler rather than an Item wrapping one. A Flickable reparents its -// visual children into its content, so an Item dropped inside would be a -// zero-sized thing scrolling along with the list and its handler would never -// see a wheel event. A handler is not reparented: it attaches to the -// Flickable, which is exactly what has to be got in front of. +// Invariant: attach the handler directly to the Flickable; visual children would be reparented into +// scrolling content and miss wheel events. WheelHandler { id: root @@ -35,8 +19,8 @@ WheelHandler { Model.wheelPixels(event.angleDelta.y, event.pixelDelta.y), root.view.contentHeight, root.view.height, root.view.originY, root.view.topMargin, root.view.bottomMargin) - // Not dead despite `blocking`: a flick already in flight from a drag - // goes on decelerating from where it was and fights every turn after. + // Invariant: cancel an active drag flick before applying wheel motion so its deceleration + // cannot fight the new position. root.view.cancelFlick() } } diff --git a/ui/components/WindowMoveArea.qml b/ui/components/WindowMoveArea.qml index 83dc20844..00a5e3366 100644 --- a/ui/components/WindowMoveArea.qml +++ b/ui/components/WindowMoveArea.qml @@ -1,8 +1,7 @@ import QtQuick -// Keep this below header controls so their pointer handlers win. Empty -// title-bar space delegates movement to the compositor; retaining a QML -// MouseArea grab while moving the native window makes it trail the pointer. +// Invariant: header controls retain pointer priority; native system movement must not retain a QML +// pointer grab. MouseArea { id: root required property var nativeWindow diff --git a/ui/controls/Button.qml b/ui/controls/Button.qml index f2ddf9372..0f726ea6b 100644 --- a/ui/controls/Button.qml +++ b/ui/controls/Button.qml @@ -4,21 +4,6 @@ import "../settings" import QtQuick.Controls import qs.Commons -// The button. One component for every clickable thing in the kit. -// States compose independently and are applied in priority order: -// -// pressed (mouse down) pressed fill -// activeFocus (Tab focus) focus fill + focus border token -// hasCursor || hover hover-cursor fill (+ border if `bordered`) -// selected selected fill + optional selected border -// active selected fill -// idle transparent or normal border if `bordered` -// -// All fills/borders come from `qs.Commons.Style` tokens, so themes -// control the look via [controls] in shell.toml. -// -// Emits `hovered(bool)` so panels with their own keyboard cursor model -// can update state on mouse enter/leave. BorderSurface { id: root @@ -26,19 +11,16 @@ BorderSurface { property string iconText: "" property string tooltipText: "" - // State flags (see comment above for paint priority). property bool selected: false property bool active: false property bool hasCursor: false property bool focusable: false property bool bordered: false - // Colors. Defaults track the theme; per-instance overrides are honored. property color foreground: Color.foreground property color background: "transparent" property color accent: Color.accent - // Sizing. property string fontFamily: MailStyle.family property real fontSize: MailStyle.body property real iconSize: Style.font.icon @@ -53,9 +35,6 @@ BorderSurface { topPadding: verticalPadding bottomPadding: verticalPadding - // Tooltip palette. Auto-rendered if tooltipText is set. Defaults pull - // from [tooltip] in shell.toml; override per-instance only when a button - // intentionally wants a tooltip that diverges from the theme. property color tooltipBackground: Color.tooltip.background property color tooltipForeground: Color.tooltip.text property color tooltipBorder: Color.tooltip.border @@ -82,9 +61,8 @@ BorderSurface { root.clicked() } - // Reserve the largest border any visual state can paint. Otherwise a - // borderless idle button grows by a pixel per side on hover/focus and - // relayouts neighboring controls. + // Invariant: reserve the largest possible border so hover and focus do not relayout neighboring + // controls. implicitWidth: row.implicitWidth + horizontalPadding * 2 + _reservedBorderLeft + _reservedBorderRight implicitHeight: row.implicitHeight + verticalPadding * 2 + _reservedBorderTop + _reservedBorderBottom radius: Style.cornerRadius @@ -131,13 +109,6 @@ BorderSurface { : active ? Style.selectedFillFor(root.foreground, root.accent) : background - // Border follows the same state precedence as fill. Buttons stay - // borderless at rest unless `bordered` is set, but hover-cursor/focus - // always use the shared cursor border so the keyboard target is visible - // and consistent with the rest of the kit. Selected borders are off by - // default for plain buttons; explicitly bordered buttons keep their - // normal border when selected unless selected-border-width opts in to a - // dedicated selected border. borderSpec: _borderSpec Behavior on color { ColorAnimation { duration: 120 } } diff --git a/ui/controls/PanelActionButton.qml b/ui/controls/PanelActionButton.qml index 0c8f21725..617cc379c 100644 --- a/ui/controls/PanelActionButton.qml +++ b/ui/controls/PanelActionButton.qml @@ -4,29 +4,6 @@ import qs.Ui import "../settings" import qs.Commons -// Small (22×22 by default) icon button used at the right edge of panel rows -// for inline actions — forget network, confirm passphrase, unpair device, -// etc. Two visual modes are supported via `hoverColor`: -// - default: hoverColor === foreground → subtle foreground-tint hover -// - urgent: hoverColor === bar.urgent → red-tint hover for destructive -// actions like forget/unpair -// -// `enabled` gates clicks and dims the icon. The component owns its own -// hover state visuals; mouse hover does NOT update any panel cursor state -// here because action buttons are not cursor targets — the row they live -// in is. -// -// Set `focusable: true` to make the button keyboard-tabbable with the -// shared hover-cursor/focus tokens. Use this -// in form contexts where Tab walks a list -// of controls; leave it false for the right-edge actions on panel rows -// where the row's CursorSurface owns the keyboard cursor. -// -// Set `hasCursor: true` to have the button render the same hover state as -// mouse hover — so a panel's keyboard cursor lands on it identically. -// Use this when a PanelActionButton is itself the cursor target (rather -// than living inside a CursorSurface row). Emits `hovered(bool)` on -// pointer enter/leave so the panel can update its cursor state to match. BorderSurface { id: root diff --git a/ui/controls/PanelSectionHeader.qml b/ui/controls/PanelSectionHeader.qml index 40c634216..8d01144dc 100644 --- a/ui/controls/PanelSectionHeader.qml +++ b/ui/controls/PanelSectionHeader.qml @@ -3,9 +3,6 @@ import qs.Ui import "../settings" import qs.Commons -// Small-caps-style label that introduces a panel section ("DNS provider", -// "Wi-Fi networks", "Output device", "Paired devices"). Sits between a -// PanelSeparator and the content rows. Text { textFormat: Text.PlainText id: root @@ -19,11 +16,7 @@ Text { font.pixelSize: fontSize font.bold: true - // Glyphs can paint above the box Text reserves for them: JetBrainsMono Nerd - // Font's outlines run 10% of the em past its own ascent, and a patched or - // user-chosen family can be worse. That sliver is invisible in normal flow, - // but a header sitting at the top of a clipping list — bluetooth's device - // list, network's station list — loses it to the clip and renders beheaded. - // Reserve the overshoot here so every panel is covered at once. + // Invariant: reserve font ascent overshoot so clipped lists do not cut off tall Nerd Font + // outlines. topPadding: Math.ceil(fontSize * 0.15) } diff --git a/ui/controls/PanelToolTip.qml b/ui/controls/PanelToolTip.qml index 46b4ceea6..c3d8d2079 100644 --- a/ui/controls/PanelToolTip.qml +++ b/ui/controls/PanelToolTip.qml @@ -4,19 +4,8 @@ import "../settings" import QtQuick.Controls import qs.Commons -// Styled wrapper around Qt Quick Controls ToolTip. Drop-in: declare inside -// the hovered item and bind `visible` to the hover state, e.g. -// PanelToolTip { -// visible: mouse.containsMouse -// text: "Forget network" -// } -// -// Defaults pull from [tooltip] in shell.toml via Color.tooltip.*. Override -// the panel* properties per-instance only when you need a tooltip that -// intentionally diverges from the theme. -// -// Property names are prefixed `panel*` to avoid clashing with ToolTip's -// built-in `background`/`font` properties. +// Docs: panel-prefixed styling properties avoid collisions with ToolTip’s built-in background and +// font properties. ToolTip { id: root diff --git a/ui/controls/TextField.qml b/ui/controls/TextField.qml index 9a1c864ca..47119d4ef 100644 --- a/ui/controls/TextField.qml +++ b/ui/controls/TextField.qml @@ -4,19 +4,6 @@ import "../settings" import QtQuick.Controls import qs.Commons -// Single-line text input with the kit's focus + selection styling. Inherits -// from Qt Quick Controls TextField so the underlying type's API (text, -// placeholderText, accepted, editingFinished, validator, ...) is available -// to callers without re-exposing each property. -// -// Defaults bind to qs.Commons.Color so a caller with no theme overrides -// just works; foreground / accent / selectionTint can be overridden per -// instance. activeFocus and mouse hover / panel cursor use the same -// hover-cursor defaults, so text inputs match Button, Toggle, and Dropdown. -// -// Sizing is driven by font.pixelSize + verticalPadding. The default 30px -// implicitHeight fits dialog forms; inline callers (wifi's row-embedded -// passphrase prompt) drop verticalPadding to match a 22-26px row. TextField { id: root @@ -27,11 +14,8 @@ TextField { property real horizontalPadding: Style.spacing.controlPaddingX property real verticalPadding: Style.spacing.inputPaddingY - // Panel-cursor flag. When true (and the field isn't already focused), - // the background paints the shared hover/cursor state. - // For mouse-enter/leave the consumer reads QQC TextField's inherited - // `hovered` property (via onHoveredChanged) — we don't add a sibling - // signal because the inherited property would shadow it. + // Invariant: QQC.TextField already defines hovered; consumers must use it rather than introducing + // a shadowing signal. property bool hasCursor: false readonly property bool _focused: activeFocus From 4016ec9d37fa0a65a330d820523d71362d336b31 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 133/568] Remove unreachable Calendar API recovery controls --- ui/components/CalendarView.qml | 2 -- 1 file changed, 2 deletions(-) diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index bf290e427..155a59787 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -109,8 +109,6 @@ Item { return { mode: label.toLowerCase(), label: label + " (" + Keymap.displayFor(binding) + ")" } }) signal createAt(double startMs) - signal copyRequested(string text) - signal openRequested(string url) signal editRequested(string sourceId, var event) signal deleteRequested(string sourceId, var event) From b520648e6f051c010307f7d23c4d3d43c6f8388c Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 134/568] Name private view and layout values --- ui/components/AccountSwitcher.qml | 4 +- ui/components/ActionIcon.qml | 32 ++++++------ ui/components/AddressMenu.qml | 8 +-- ui/components/AgentPrompt.qml | 18 +++---- ui/components/CalendarEventComposer.qml | 8 +-- ui/components/CalendarEventDetail.qml | 4 +- ui/components/CalendarSettings.qml | 12 ++--- ui/components/CalendarView.qml | 14 +++--- ui/components/ComposeView.qml | 66 ++++++++++++------------- ui/components/ConfirmDeleteDialog.qml | 8 +-- ui/components/ConversationRail.qml | 8 +-- ui/components/DisplaySettings.qml | 2 +- ui/components/KeyRouter.qml | 4 +- ui/components/LocalMailStatus.qml | 6 +-- ui/components/MailboxTabs.qml | 6 +-- ui/components/Menu.js | 10 ++-- ui/components/MessageMenu.qml | 4 +- ui/components/SettingsPage.qml | 8 +-- 18 files changed, 111 insertions(+), 111 deletions(-) diff --git a/ui/components/AccountSwitcher.qml b/ui/components/AccountSwitcher.qml index 1df2d62c6..cb5653949 100644 --- a/ui/components/AccountSwitcher.qml +++ b/ui/components/AccountSwitcher.qml @@ -100,8 +100,8 @@ Item { // filtered rows directly. var accounts = Model.filterRows(root.accounts, root.query) var offset = (root.accounts ? root.accounts.length : 0) > 1 && root.query.trim() === "" ? 1 : 0 - for (var i = 0; i < accounts.length; i++) { - if (accounts[i].active) { cursorIndex = i + offset; return } + for (var entryIndex = 0; entryIndex < accounts.length; entryIndex++) { + if (accounts[entryIndex].active) { cursorIndex = entryIndex + offset; return } } cursorIndex = 0 } diff --git a/ui/components/ActionIcon.qml b/ui/components/ActionIcon.qml index d55a65912..0a0036c2e 100644 --- a/ui/components/ActionIcon.qml +++ b/ui/components/ActionIcon.qml @@ -52,23 +52,23 @@ Item { } onPaint: { - var ctx = getContext("2d") - ctx.reset() - var s = width / 16 - if (s <= 0) return - ctx.lineWidth = Math.max(1, root.strokeScale * s) - ctx.lineCap = "round" - ctx.lineJoin = "round" + var context = getContext("2d") + context.reset() + var scale = width / 16 + if (scale <= 0) return + context.lineWidth = Math.max(1, root.strokeScale * scale) + context.lineCap = "round" + context.lineJoin = "round" - ctx.strokeStyle = root.color - ctx.beginPath() - ctx.rect(1 * s, 3 * s, 14 * s, 10 * s) - ctx.stroke() - ctx.strokeStyle = root.markColor - ctx.beginPath() - ctx.moveTo(3.6 * s, 13 * s); ctx.lineTo(3.6 * s, 5.6 * s); ctx.lineTo(8 * s, 9.3 * s) - ctx.lineTo(12.4 * s, 5.6 * s); ctx.lineTo(12.4 * s, 13 * s) - ctx.stroke() + context.strokeStyle = root.color + context.beginPath() + context.rect(1 * scale, 3 * scale, 14 * scale, 10 * scale) + context.stroke() + context.strokeStyle = root.markColor + context.beginPath() + context.moveTo(3.6 * scale, 13 * scale); context.lineTo(3.6 * scale, 5.6 * scale); context.lineTo(8 * scale, 9.3 * scale) + context.lineTo(12.4 * scale, 5.6 * scale); context.lineTo(12.4 * scale, 13 * scale) + context.stroke() } } } diff --git a/ui/components/AddressMenu.qml b/ui/components/AddressMenu.qml index 23e938e44..98dc0a9f1 100644 --- a/ui/components/AddressMenu.qml +++ b/ui/components/AddressMenu.qml @@ -35,11 +35,11 @@ Item { var rows = [] var seen = {} var given = Array.isArray(list) ? list : [] - for (var i = 0; i < given.length; i++) { - var email = String(given[i] && given[i].email ? given[i].email : "").trim() + for (var entryIndex = 0; entryIndex < given.length; entryIndex++) { + var email = String(given[entryIndex] && given[entryIndex].email ? given[entryIndex].email : "").trim() if (email === "" || seen[email]) continue seen[email] = true - rows.push({ name: String(given[i].name || given[i].display || ""), email: email }) + rows.push({ name: String(given[entryIndex].name || given[entryIndex].display || ""), email: email }) } if (rows.length === 0) return addresses = rows @@ -133,7 +133,7 @@ Item { onItemRemoved: function(index, item) { pickRows.rows = collect() } function collect() { var out = [] - for (var i = 0; i < pickRepeater.count; i++) out.push(pickRepeater.itemAt(i)) + for (var entryIndex = 0; entryIndex < pickRepeater.count; entryIndex++) out.push(pickRepeater.itemAt(entryIndex)) return out } diff --git a/ui/components/AgentPrompt.qml b/ui/components/AgentPrompt.qml index 7c7fb006d..9fa1e2df5 100644 --- a/ui/components/AgentPrompt.qml +++ b/ui/components/AgentPrompt.qml @@ -31,7 +31,7 @@ FocusScope { ? (service.agentShownProposals || []) : [] onProposalsChanged: syncConversation() function proposalFor(id) { - for (var i = 0; i < proposals.length; i++) if (String(proposals[i].id) === id) return proposals[i] + for (var entryIndex = 0; entryIndex < proposals.length; entryIndex++) if (String(proposals[entryIndex].id) === id) return proposals[entryIndex] return ({subject:"",body:"",applicable:false}) } signal applyProposalRequested(var envelope, string parentId) @@ -82,7 +82,7 @@ FocusScope { if (drafts.length > 0) return drafts[0] if (composer.agentParentJobId) { var all = service.agentAllJobs || [] - for (var i = 0; i < all.length; i++) if (String(all[i].id) === composer.agentParentJobId && Agent.canUseDraftChat(all[i], fields)) return all[i] + for (var entryIndex = 0; entryIndex < all.length; entryIndex++) if (String(all[entryIndex].id) === composer.agentParentJobId && Agent.canUseDraftChat(all[entryIndex], fields)) return all[entryIndex] } var reader = fields.replyMessageId ? service.agentJobFor(fields.replyMessageId, fields.accountId) : null return Agent.canUseDraftChat(reader, fields) ? reader : null @@ -103,7 +103,7 @@ FocusScope { : (defaultJob ? [defaultJob] : []) readonly property var job: { if (viewedJobId !== "") { - for (var i=0; i rows.length) chatModel.remove(rows.length, chatModel.count - rows.length) - for (var i = 0; i < rows.length; i++) { - if (i >= chatModel.count) chatModel.append({entryRole: rows[i].role, entryText: rows[i].text}) + for (var entryIndex = 0; entryIndex < rows.length; entryIndex++) { + if (entryIndex >= chatModel.count) chatModel.append({entryRole: rows[entryIndex].role, entryText: rows[entryIndex].text}) else { - if (chatModel.get(i).entryRole !== rows[i].role) chatModel.setProperty(i, "entryRole", rows[i].role) - if (chatModel.get(i).entryText !== rows[i].text) chatModel.setProperty(i, "entryText", rows[i].text) + if (chatModel.get(entryIndex).entryRole !== rows[entryIndex].role) chatModel.setProperty(entryIndex, "entryRole", rows[entryIndex].role) + if (chatModel.get(entryIndex).entryText !== rows[entryIndex].text) chatModel.setProperty(entryIndex, "entryText", rows[entryIndex].text) } } } diff --git a/ui/components/CalendarEventComposer.qml b/ui/components/CalendarEventComposer.qml index 878e39537..375e7a936 100644 --- a/ui/components/CalendarEventComposer.qml +++ b/ui/components/CalendarEventComposer.qml @@ -126,7 +126,7 @@ Rectangle { textRole: "label" valueRole: "value" currentIndex: { - for (var i = 0; i < model.length; i++) if (model[i].value === value) return i + for (var entryIndex = 0; entryIndex < model.length; entryIndex++) if (model[entryIndex].value === value) return entryIndex return -1 } onActivated: function(index) { chosen(String(model[index].value)) } @@ -391,7 +391,7 @@ Rectangle { root.loadingSeries = false if (error) { resultText.text = error; return } var payload - try { payload = JSON.parse(result.body) } catch (e) { resultText.text = "Could not read the series"; return } + try { payload = JSON.parse(result.body) } catch (parseError) { resultText.text = "Could not read the series"; return } var events = Calendar.eventsFromGoogle({ items: [payload] }, source.id) if (events.length !== 1) { resultText.text = "The series is no longer available"; return } root.beginEdit(source.id, events[0]) @@ -537,8 +537,8 @@ Rectangle { root.editing && root.controller && typeof root.controller.findSource === "function" ? root.controller.findSource(root.editingSourceId) : null, root.editingEvent) currentIndex: { - for (var i = 0; i < model.length; i++) - if (String(model[i].source.id) === root.selectedSourceId) return i + for (var entryIndex = 0; entryIndex < model.length; entryIndex++) + if (String(model[entryIndex].source.id) === root.selectedSourceId) return entryIndex return -1 } onActivated: function(index) { root.chooseCalendar(String(model[index].source.id)) } diff --git a/ui/components/CalendarEventDetail.qml b/ui/components/CalendarEventDetail.qml index 2490ead38..c4ae04b47 100644 --- a/ui/components/CalendarEventDetail.qml +++ b/ui/components/CalendarEventDetail.qml @@ -36,8 +36,8 @@ Rectangle { var sources = controller && controller.availableSources ? controller.availableSources.sources : [] var sourceId = String(event && event.sourceId || "") - for (var i = 0; i < sources.length; i++) { - if (String(sources[i].id || "") === sourceId) return sources[i] + for (var entryIndex = 0; entryIndex < sources.length; entryIndex++) { + if (String(sources[entryIndex].id || "") === sourceId) return sources[entryIndex] } return null } diff --git a/ui/components/CalendarSettings.qml b/ui/components/CalendarSettings.qml index bcfcdab80..b8b573ef6 100644 --- a/ui/components/CalendarSettings.qml +++ b/ui/components/CalendarSettings.qml @@ -29,7 +29,7 @@ Column { var groups = Sources.groupByAccount(controller ? controller.availableSources : null, service ? service.accountSummaries : []) var values = [] - for (var i = 0; i < groups.length; i++) values = values.concat(groups[i].calendars) + for (var entryIndex = 0; entryIndex < groups.length; entryIndex++) values = values.concat(groups[entryIndex].calendars) return values } readonly property var writableSources: settingsSources.filter(function(source) { @@ -38,7 +38,7 @@ Column { function accountIndex(id) { var accounts = root.service ? root.service.accountSummaries : [] - for (var i = 0; i < accounts.length; i++) if (accounts[i].id === id) return i + for (var entryIndex = 0; entryIndex < accounts.length; entryIndex++) if (accounts[entryIndex].id === id) return entryIndex return -1 } @@ -62,9 +62,9 @@ Column { var wanted = String(source && source.accountId || "") var accounts = root.service && Array.isArray(root.service.accountSummaries) ? root.service.accountSummaries : [] - for (var i = 0; i < accounts.length; i++) { - if (String(accounts[i] && accounts[i].id || "") === wanted) - return String(accounts[i].email || accounts[i].label || "") + for (var entryIndex = 0; entryIndex < accounts.length; entryIndex++) { + if (String(accounts[entryIndex] && accounts[entryIndex].id || "") === wanted) + return String(accounts[entryIndex].email || accounts[entryIndex].label || "") } return "" } @@ -781,7 +781,7 @@ Column { }) value: { var values = defaultGroup.modelData.calendars - for (var i = 0; i < values.length; i++) if (values[i].preferred) return values[i].id + for (var entryIndex = 0; entryIndex < values.length; entryIndex++) if (values[entryIndex].preferred) return values[entryIndex].id return values.length ? values[0].id : "" } foreground: root.textColor diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index 155a59787..9e7914449 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -197,8 +197,8 @@ Item { var values = visibleEvents() if (values.length === 0) { selectedEventId = ""; return } var index = -1 - for (var i = 0; i < values.length; i++) { - if (Calendar.eventKey(values[i]) === selectedEventId) { index = i; break } + for (var entryIndex = 0; entryIndex < values.length; entryIndex++) { + if (Calendar.eventKey(values[entryIndex]) === selectedEventId) { index = entryIndex; break } } if (index < 0) index = Number(offset) < 0 ? values.length : -1 index = Math.max(0, Math.min(values.length - 1, index + Number(offset))) @@ -223,7 +223,7 @@ Item { root.detailLoading = false if (error) { root.detailError = error; return } var resource - try { resource = JSON.parse(result.body) } catch (e) { root.detailError = "Could not read the event details"; return } + try { resource = JSON.parse(result.body) } catch (parseError) { root.detailError = "Could not read the event details"; return } var values = Calendar.eventsFromGoogle({items:[resource]}, source.id) if (values.length === 1 && Calendar.eventKey(values[0]) === Calendar.eventKey(event)) root.detailEvent = values[0] else root.detailError = "This event is no longer available" @@ -253,9 +253,9 @@ Item { function activateSelection() { var values = visibleEvents() - for (var i = 0; i < values.length; i++) { - if (Calendar.eventKey(values[i]) === selectedEventId) { - activateEvent(values[i]) + for (var entryIndex = 0; entryIndex < values.length; entryIndex++) { + if (Calendar.eventKey(values[entryIndex]) === selectedEventId) { + activateEvent(values[entryIndex]) return } } @@ -336,7 +336,7 @@ Item { controller.nativeRequest(source, "get", { eventId: requested.substring(separator + 1) }, function(result, error) { if (!root.waitingForEvent || root.selectedEventId !== requested || error) return var resource - try { resource = JSON.parse(result.body) } catch (e) { return } + try { resource = JSON.parse(result.body) } catch (parseError) { return } var events = Calendar.eventsFromGoogle({ items: [resource] }, source.id) if (events.length === 1) { root.waitingForEvent = false; root.activateEvent(events[0], true) } }) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index d7f8792cd..7c5c2ae13 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -230,9 +230,9 @@ DropArea { function forgetOwned(attachments) { var owned = Array.isArray(attachments) ? attachments : [] - for (var i = 0; i < owned.length; i++) { - if (owned[i] && owned[i].owned && owned[i].path) - enqueueAttach("forget", owned[i].path) + for (var entryIndex = 0; entryIndex < owned.length; entryIndex++) { + if (owned[entryIndex] && owned[entryIndex].owned && owned[entryIndex].path) + enqueueAttach("forget", owned[entryIndex].path) } } @@ -401,8 +401,8 @@ DropArea { var listed = draftAttachments.slice() var kept = [] var recover = [] - for (var i = 0; i < listed.length; i++) { - var file = listed[i] || ({}) + for (var entryIndex = 0; entryIndex < listed.length; entryIndex++) { + var file = listed[entryIndex] || ({}) if (String(file.path || "") !== "" && String(file.data || "") === "" && String(file.handle || "") === "") recover.push(file) @@ -410,18 +410,18 @@ DropArea { } if (recover.length === 0) return draftAttachments = kept - for (var r = 0; r < recover.length; r++) - enqueueAttach(recover[r].owned === true ? "recover-owned" : "recover", - String(recover[r].path || "")) + for (var recoveryIndex = 0; recoveryIndex < recover.length; recoveryIndex++) + enqueueAttach(recover[recoveryIndex].owned === true ? "recover-owned" : "recover", + String(recover[recoveryIndex].path || "")) } function reset() { clearCurrentDraft(true) - for (var p = 0; p < parkedDrafts.length; p++) - forgetOwned(parkedDrafts[p].draft ? parkedDrafts[p].draft.draftAttachments : []) + for (var candidateIndex = 0; candidateIndex < parkedDrafts.length; candidateIndex++) + forgetOwned(parkedDrafts[candidateIndex].draft ? parkedDrafts[candidateIndex].draft.draftAttachments : []) forgetOwned(interruptedDraft ? interruptedDraft.draftAttachments : []) - for (var i = 0; i < recoveryDrafts.length; i++) - forgetOwned(recoveryDrafts[i] ? recoveryDrafts[i].draftAttachments : []) + for (var entryIndex = 0; entryIndex < recoveryDrafts.length; entryIndex++) + forgetOwned(recoveryDrafts[entryIndex] ? recoveryDrafts[entryIndex].draftAttachments : []) parkedDrafts = [] interruptedDraft = null recoveryDrafts = [] @@ -482,15 +482,15 @@ DropArea { if (!root.service) return [] var own = [{email: root.service.accountEmailFor(root.accountId)}] var sources = Senders.asList(root.service.senderSources) - for (var i = 0; i < sources.length; i++) { - if (String(sources[i].id || "") !== root.accountId) continue - own.push({email: sources[i].email}) - own = own.concat(Senders.asList(sources[i].aliases)) + for (var entryIndex = 0; entryIndex < sources.length; entryIndex++) { + if (String(sources[entryIndex].id || "") !== root.accountId) continue + own.push({email: sources[entryIndex].email}) + own = own.concat(Senders.asList(sources[entryIndex].aliases)) } var identities = Senders.asList(root.service.sendIdentities) - for (var j = 0; j < identities.length; j++) { - if (String(identities[j].accountId || "") === root.accountId) - own.push(identities[j]) + for (var identityIndex = 0; identityIndex < identities.length; identityIndex++) { + if (String(identities[identityIndex].accountId || "") === root.accountId) + own.push(identities[identityIndex]) } return own } @@ -716,9 +716,9 @@ DropArea { var forwarded = draft.mode === "forward" && Array.isArray(draft.forwardedAttachments) ? draft.forwardedAttachments : [] var owned = Array.isArray(draft.draftAttachments) ? draft.draftAttachments : [] - var i - for (i = 0; i < forwarded.length; i++) attachments.push(forwarded[i]) - for (i = 0; i < owned.length; i++) attachments.push(owned[i]) + var entryIndex + for (entryIndex = 0; entryIndex < forwarded.length; entryIndex++) attachments.push(forwarded[entryIndex]) + for (entryIndex = 0; entryIndex < owned.length; entryIndex++) attachments.push(owned[entryIndex]) return ({ accountId: String(draft.accountId || ""), draftKey: String(draft.draftKey || ""), @@ -798,9 +798,9 @@ DropArea { var index = -1 var id = String(sendId || "") if (id !== "") { - for (var i = 0; i < parked.length; i++) { - if (parked[i].sendId === id) { - index = i + for (var entryIndex = 0; entryIndex < parked.length; entryIndex++) { + if (parked[entryIndex].sendId === id) { + index = entryIndex break } } @@ -887,9 +887,9 @@ DropArea { function allOutgoingAttachments() { var out = [] var forwarded = root.mode === "forward" ? root.forwardedAttachments : [] - var i - for (i = 0; i < forwarded.length; i++) out.push(forwarded[i]) - for (i = 0; i < root.draftAttachments.length; i++) out.push(root.draftAttachments[i]) + var entryIndex + for (entryIndex = 0; entryIndex < forwarded.length; entryIndex++) out.push(forwarded[entryIndex]) + for (entryIndex = 0; entryIndex < root.draftAttachments.length; entryIndex++) out.push(root.draftAttachments[entryIndex]) return out } @@ -980,7 +980,7 @@ DropArea { function finishAttach(mode, text, owner) { var result = null try { result = JSON.parse(String(text || "")) } - catch (e) { result = null } + catch (parseError) { result = null } // Invariant: attachment helpers outlive the form; stale completions must not enter the next // draft. @@ -1004,8 +1004,8 @@ DropArea { && Array.isArray(result.paths))) { root.attaching = root.attachJobs.length > 0 if (result && result.ok === true && Array.isArray(result.paths)) { - for (var p = 0; p < result.paths.length; p++) - enqueueAttach("read", String(result.paths[p] || "")) + for (var candidateIndex = 0; candidateIndex < result.paths.length; candidateIndex++) + enqueueAttach("read", String(result.paths[candidateIndex] || "")) } pumpAttach() return @@ -1058,8 +1058,8 @@ DropArea { function attachDroppedUrls(urls) { var list = urls || [] - for (var i = 0; i < list.length; i++) { - var url = String(list[i] || "") + for (var entryIndex = 0; entryIndex < list.length; entryIndex++) { + var url = String(list[entryIndex] || "") var path = url.indexOf("file://") === 0 ? decodeURIComponent(url.substring(7)) : url if (path !== "") enqueueAttach("read", path) } diff --git a/ui/components/ConfirmDeleteDialog.qml b/ui/components/ConfirmDeleteDialog.qml index ab01588d0..9b5166d1d 100644 --- a/ui/components/ConfirmDeleteDialog.qml +++ b/ui/components/ConfirmDeleteDialog.qml @@ -43,13 +43,13 @@ Item { function buttonsInOrder() { var ordered = [cancelButton] - for (var i = 0; i < choiceButtons.count; i++) ordered.push(choiceButtons.itemAt(i)) + for (var entryIndex = 0; entryIndex < choiceButtons.count; entryIndex++) ordered.push(choiceButtons.itemAt(entryIndex)) return ordered } function moveFocus(step) { var ordered = buttonsInOrder() var at = 0 - for (var i = 0; i < ordered.length; i++) if (ordered[i] && ordered[i].activeFocus) at = i + for (var entryIndex = 0; entryIndex < ordered.length; entryIndex++) if (ordered[entryIndex] && ordered[entryIndex].activeFocus) at = entryIndex var next = ordered[(at + step + ordered.length) % ordered.length] if (next) next.forceActiveFocus() } @@ -85,8 +85,8 @@ Item { if (event.key !== Qt.Key_Return && event.key !== Qt.Key_Enter) return event.accepted = true if (cancelButton.activeFocus) { root.close(); return } - for (var i = 0; i < choiceButtons.count; i++) - if (choiceButtons.itemAt(i).activeFocus) root.confirm(root.choices[i].value) + for (var entryIndex = 0; entryIndex < choiceButtons.count; entryIndex++) + if (choiceButtons.itemAt(entryIndex).activeFocus) root.confirm(root.choices[entryIndex].value) } Text { diff --git a/ui/components/ConversationRail.qml b/ui/components/ConversationRail.qml index 29fbc2010..98188b63d 100644 --- a/ui/components/ConversationRail.qml +++ b/ui/components/ConversationRail.qml @@ -33,16 +33,16 @@ Item { readonly property bool hasSkeleton: { var list = root.stops || [] - for (var i = 0; i < list.length; i++) { - if (!list[i].known) return true + for (var entryIndex = 0; entryIndex < list.length; entryIndex++) { + if (!list[entryIndex].known) return true } return false } function boundsFor(id) { var wanted = String(id || "") - for (var i = 0; i < stopColumn.children.length; i++) { - var stop = stopColumn.children[i] + for (var entryIndex = 0; entryIndex < stopColumn.children.length; entryIndex++) { + var stop = stopColumn.children[entryIndex] if (!stop || stop.memberId !== wanted) continue return { y: stop.y, height: stop.height, diff --git a/ui/components/DisplaySettings.qml b/ui/components/DisplaySettings.qml index 12da919d8..a122c7c0b 100644 --- a/ui/components/DisplaySettings.qml +++ b/ui/components/DisplaySettings.qml @@ -15,7 +15,7 @@ Column { readonly property var families: { var result = ["System UI font"] var installed = Qt.fontFamilies() - for (var i = 0; i < installed.length; i++) result.push(installed[i]) + for (var entryIndex = 0; entryIndex < installed.length; entryIndex++) result.push(installed[entryIndex]) return result } diff --git a/ui/components/KeyRouter.qml b/ui/components/KeyRouter.qml index 4de52e6e7..c38fa3750 100644 --- a/ui/components/KeyRouter.qml +++ b/ui/components/KeyRouter.qml @@ -24,8 +24,8 @@ Item { if (event.modifiers & Qt.MetaModifier) sequence += "Meta+" sequence += key var entries = Keymap.sequencesFor(root.context) - for (var i = 0; i < entries.length; i++) { - var entry = entries[i] + for (var entryIndex = 0; entryIndex < entries.length; entryIndex++) { + var entry = entries[entryIndex] if (entry.sequence !== sequence || !Keymap.isSequenceEnabled(entry.binding, sequence, root.context, root.overlay)) continue event.accepted = true diff --git a/ui/components/LocalMailStatus.qml b/ui/components/LocalMailStatus.qml index dc84e974a..ea23d6ed8 100644 --- a/ui/components/LocalMailStatus.qml +++ b/ui/components/LocalMailStatus.qml @@ -66,7 +66,7 @@ Column { Widgets.Button { readonly property string ticket: { var entries = root.mailbox ? root.mailbox.edits : [] - for (var i=0;i=0;i--) - if (entries[i].state === "queued") return String(entries[i].ticket) + for (var entryIndex=entries.length-1;entryIndex>=0;entryIndex--) + if (entries[entryIndex].state === "queued") return String(entries[entryIndex].ticket) return "" } visible: ticket !== "" diff --git a/ui/components/MailboxTabs.qml b/ui/components/MailboxTabs.qml index a25b8fdb6..05a6e8848 100644 --- a/ui/components/MailboxTabs.qml +++ b/ui/components/MailboxTabs.qml @@ -46,9 +46,9 @@ Flickable { } function revealCurrent() { - for (var i = 0; i < mailboxes.length; i++) { - if (mailboxes[i].key !== current) continue - var chip = segments.itemAt(i) + for (var entryIndex = 0; entryIndex < mailboxes.length; entryIndex++) { + if (mailboxes[entryIndex].key !== current) continue + var chip = segments.itemAt(entryIndex) if (!chip) return var left = track.x + chip.x var right = left + chip.width diff --git a/ui/components/Menu.js b/ui/components/Menu.js index c1467bb7e..249f606d5 100644 --- a/ui/components/Menu.js +++ b/ui/components/Menu.js @@ -24,9 +24,9 @@ function nextSelectable(entries, current, step) { } function position(anchorX, anchorY, width, height, containerWidth, containerHeight) { - var x = Math.max(0, Math.min(Number(anchorX), Number(containerWidth) - Number(width))) - var y = Number(anchorY) - if (y + height > containerHeight) y = y - height - if (y + height > containerHeight) y = containerHeight - height - return { x: Math.max(0, x), y: Math.max(0, y) } + var positionX = Math.max(0, Math.min(Number(anchorX), Number(containerWidth) - Number(width))) + var positionY = Number(anchorY) + if (positionY + height > containerHeight) positionY = positionY - height + if (positionY + height > containerHeight) positionY = containerHeight - height + return { x: Math.max(0, positionX), y: Math.max(0, positionY) } } diff --git a/ui/components/MessageMenu.qml b/ui/components/MessageMenu.qml index 30e44fbb8..3e9c424b2 100644 --- a/ui/components/MessageMenu.qml +++ b/ui/components/MessageMenu.qml @@ -49,8 +49,8 @@ Item { readonly property var summary: { if (!service || messageId === "") return null var list = service.messages - for (var i = 0; i < list.length; i++) { - if (list[i].id === messageId) return list[i] + for (var entryIndex = 0; entryIndex < list.length; entryIndex++) { + if (list[entryIndex].id === messageId) return list[entryIndex] } var members = service.memberSummaries if (members && typeof members === "object" && members[messageId]) return members[messageId] diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index 922494ca0..54b24759b 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -52,9 +52,9 @@ Column { readonly property var auth: service ? service.auth : null function signatureAccount(id) { - for (var i = 0; i < signatureAccounts.length; i++) - if (String(signatureAccounts[i].id || "") === String(id || "")) - return signatureAccounts[i] + for (var entryIndex = 0; entryIndex < signatureAccounts.length; entryIndex++) + if (String(signatureAccounts[entryIndex].id || "") === String(id || "")) + return signatureAccounts[entryIndex] return null } @@ -154,7 +154,7 @@ Column { function finishImport(text) { var result = null - try { result = JSON.parse(String(text || "")) } catch (e) { result = null } + try { result = JSON.parse(String(text || "")) } catch (parseError) { result = null } if (!result || result.ok !== true) { var reason = result && result.error ? String(result.error) : "" importing = false From 136d7663d7fd9399a3a7234aed9e0bb9e3f4cc94 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 135/568] Name recipient, message and dropdown loop values --- ui/components/ComposeView.qml | 14 +++++++------- ui/components/ContactsPicker.qml | 8 ++++---- ui/components/MessageList.qml | 2 +- ui/controls/Dropdown.qml | 16 ++++++++-------- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 7c5c2ae13..0534f8f12 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -469,13 +469,13 @@ DropArea { var global = fromButton.mapToGlobal(0, 0) var at = root.mapFromGlobal(global.x, global.y) var tall = fromMenu.height > 0 ? fromMenu.height : fromMenu.implicitHeight - var x = Math.max(0, Math.min(at.x, root.width - fromMenu.width)) - var y = at.y + fromButton.height - if (y + tall > root.height) y = at.y - tall - if (y + tall > root.height) y = root.height - tall - if (y < 0) y = 0 - fromMenu.x = x - fromMenu.y = y + var menuX = Math.max(0, Math.min(at.x, root.width - fromMenu.width)) + var menuY = at.y + fromButton.height + if (menuY + tall > root.height) menuY = at.y - tall + if (menuY + tall > root.height) menuY = root.height - tall + if (menuY < 0) menuY = 0 + fromMenu.x = menuX + fromMenu.y = menuY } function ownReplyAddresses() { diff --git a/ui/components/ContactsPicker.qml b/ui/components/ContactsPicker.qml index 56049d719..2586eea1a 100644 --- a/ui/components/ContactsPicker.qml +++ b/ui/components/ContactsPicker.qml @@ -73,10 +73,10 @@ Item { function place() { if (!menu.visible) return - var x = Math.max(MailStyle.space(8), Math.min(anchorX, root.width - menu.width - MailStyle.space(8))) - var y = Math.max(MailStyle.space(8), Math.min(anchorY, root.height - menu.implicitHeight - MailStyle.space(8))) - menu.x = x - menu.y = y + var menuX = Math.max(MailStyle.space(8), Math.min(anchorX, root.width - menu.width - MailStyle.space(8))) + var menuY = Math.max(MailStyle.space(8), Math.min(anchorY, root.height - menu.implicitHeight - MailStyle.space(8))) + menu.x = menuX + menu.y = menuY } QQC.Popup { diff --git a/ui/components/MessageList.qml b/ui/components/MessageList.qml index 0c6c59b43..bb4cc79de 100644 --- a/ui/components/MessageList.qml +++ b/ui/components/MessageList.qml @@ -86,7 +86,7 @@ ListView { overviewReason: root.service.inboxTools ? (root.service.inboxTools.available === false ? (!root.service.backend || !root.service.backend.ready ? "mail backend is disconnected" : "backend update required") : String(overviewDetails.reason || "")) : "" overviewState: root.service.inboxTools ? (root.service.inboxTools.available === false ? "unavailable" : root.service.inboxTools.paused === true ? "paused" : String(overviewDetails.state || "")) : "" onUnreadRequested: root.rowActionRequested(modelData.id, "markUnread") - onSnoozeRequested: function(x,y) { root.snoozeRequested(modelData.id,x,y) } + onSnoozeRequested: function(sceneX, sceneY) { root.snoozeRequested(modelData.id, sceneX, sceneY) } summary: modelData textColor: root.textColor accentColor: root.accentColor diff --git a/ui/controls/Dropdown.qml b/ui/controls/Dropdown.qml index b306d5521..0a4b02a50 100644 --- a/ui/controls/Dropdown.qml +++ b/ui/controls/Dropdown.qml @@ -59,8 +59,8 @@ Item { return (o && typeof o === "object") ? String(o.label) : String(o) } function currentLabel() { - for (var i = 0; i < options.length; i++) { - if (optionValue(options[i]) === value) return optionLabel(options[i]) + for (var optionIndex = 0; optionIndex < options.length; optionIndex++) { + if (optionValue(options[optionIndex]) === value) return optionLabel(options[optionIndex]) } return value } @@ -198,17 +198,17 @@ Item { model: root.options currentIndex: -1 - function indexOfValue(v) { - for (var i = 0; i < root.options.length; i++) - if (root.optionValue(root.options[i]) === v) return i + function indexOfValue(selectedValue) { + for (var optionIndex = 0; optionIndex < root.options.length; optionIndex++) + if (root.optionValue(root.options[optionIndex]) === selectedValue) return optionIndex return -1 } function selectCurrent() { if (currentIndex < 0 || currentIndex >= root.options.length) return - var v = root.optionValue(root.options[currentIndex]) - root.value = v - root.changed(v) + var selectedValue = root.optionValue(root.options[currentIndex]) + root.value = selectedValue + root.changed(selectedValue) popup.close() } From 29c66d2bfaa65c205ff4b337d1f0394a55b1a84b Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 136/568] chore: Wait for rendered icon pixels before comparison --- ui/tests/qml/tst_action_icon.qml | 10 +++++----- ui/tests/qml/tst_backend_setup.qml | 2 +- ui/tests/qml/tst_magpie_logo.qml | 12 ++++++------ 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/ui/tests/qml/tst_action_icon.qml b/ui/tests/qml/tst_action_icon.qml index fa978abae..bf5d72ff6 100644 --- a/ui/tests/qml/tst_action_icon.qml +++ b/ui/tests/qml/tst_action_icon.qml @@ -20,9 +20,9 @@ Rectangle { function ink(image) { var count = 0 - for (var y = 0; y < image.height; y++) - for (var x = 0; x < image.width; x++) - if (image.red(x, y) > 0) count++ + for (var pixelY = 0; pixelY < image.height; pixelY++) + for (var pixelX = 0; pixelX < image.width; pixelX++) + if (image.red(pixelX, pixelY) > 0) count++ return count } @@ -34,7 +34,7 @@ Rectangle { var icon = createTemporaryObject(iconComponent, stage, {name: data.name}) verify(icon) waitForRendering(icon) - verify(ink(grabImage(icon)) > 0, data.name + " renders without an icon font") + tryVerify(function() { return ink(grabImage(icon)) > 0 }, 5000, data.name + " renders without an icon font") } function test_selected_star_and_theme_change_pixels() { @@ -43,7 +43,7 @@ Rectangle { var outline = ink(grabImage(icon)) icon.filled = true waitForRendering(icon) - verify(ink(grabImage(icon)) > outline, "the selected star fills its outline") + tryVerify(function() { return ink(grabImage(icon)) > outline }, 5000, "the selected star fills its outline") icon.color = "transparent" waitForRendering(icon) compare(ink(grabImage(icon)), 0, "transparent theme colors stay transparent") diff --git a/ui/tests/qml/tst_backend_setup.qml b/ui/tests/qml/tst_backend_setup.qml index c6cd7c1ba..d7f9ffaf5 100644 --- a/ui/tests/qml/tst_backend_setup.qml +++ b/ui/tests/qml/tst_backend_setup.qml @@ -85,7 +85,7 @@ Item { var label = renderedText(page, expected) verify(label) compare(label.textFormat, Text.PlainText) - for (var x = 1; x < label.width; x += 3) compare(label.linkAt(x, label.height / 2), "") + for (var pixelX = 1; pixelX < label.width; pixelX += 3) compare(label.linkAt(pixelX, label.height / 2), "") runtime[data.field] = original runtime.development = false } diff --git a/ui/tests/qml/tst_magpie_logo.qml b/ui/tests/qml/tst_magpie_logo.qml index b69743581..2715f2991 100644 --- a/ui/tests/qml/tst_magpie_logo.qml +++ b/ui/tests/qml/tst_magpie_logo.qml @@ -20,15 +20,15 @@ Rectangle { logo.foreground = Qt.rgba(0.1, 0.2, 0.3, 1) wait(50) var rendered = grabImage(logo) - var x = Math.floor(logo.width * 39 / 64) - var y = Math.floor(logo.height * 24 / 64) - verify(Math.abs(rendered.red(x, y) - 26) <= 1) - verify(Math.abs(rendered.green(x, y) - 51) <= 1) - verify(Math.abs(rendered.blue(x, y) - 77) <= 1) + var sampleX = Math.floor(logo.width * 39 / 64) + var sampleY = Math.floor(logo.height * 24 / 64) + verify(Math.abs(rendered.red(sampleX, sampleY) - 26) <= 1) + verify(Math.abs(rendered.green(sampleX, sampleY) - 51) <= 1) + verify(Math.abs(rendered.blue(sampleX, sampleY) - 77) <= 1) logo.foreground = Qt.rgba(0.8, 0.9, 1, 1) wait(50) rendered = grabImage(logo) - verify(Math.abs(rendered.red(x, y) - 204) <= 1) + verify(Math.abs(rendered.red(sampleX, sampleY) - 204) <= 1) } function test_identity_is_static_and_labeled() { compare(logo.animated, false) From 9b05d7adb197a3c649e45aa089eee1bc9806ae96 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:18:48 +0100 Subject: [PATCH 137/568] Keep dropdown comments focused on keyboard invariants --- ui/controls/Dropdown.qml | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/ui/controls/Dropdown.qml b/ui/controls/Dropdown.qml index 0a4b02a50..4efb6efa2 100644 --- a/ui/controls/Dropdown.qml +++ b/ui/controls/Dropdown.qml @@ -4,19 +4,7 @@ import "../settings" import QtQuick.Controls import qs.Commons -// Themed single-select dropdown. Trigger row paints with the kit's focus -// chrome; the popup anchors below and uses Color.popups.background + -// Color.popups.border so it reads as a panel surface rather than the -// platform-native ComboBox look. -// -// `options` accepts either a plain string[] or an array of -// { value, label } objects (label is what we render; value is what we -// emit). Mixing is fine — each row is interpreted independently. -// -// Keyboard: Tab to focus the trigger, Enter/Space opens, Esc closes, -// j/k or Up/Down walks options inside the open popup, Enter selects. -// A sibling SearchableDropdown reuses the same visuals but adds an -// embedded filter input — keep the two separate so each stays simple. +// Docs: options accept strings or objects with distinct value and label fields. Item { id: root @@ -34,16 +22,9 @@ Item { property int popupRowHeight: Math.max(Style.spacing.popupRowHeight, MailStyle.body + 18) property bool showLabel: true - // Panel-cursor flag. When true, the trigger renders the shared - // hover-cursor state. Active Qt focus defaults to the same visuals. - // Emits `hovered(bool)` on pointer enter/leave so the panel can keep - // its cursor state in sync with the mouse. property bool hasCursor: false - // popupOpen + open()/close()/toggle() let a parent panel know when the - // dropdown owns keys (its embedded ListView is active) and suspend its - // own keyCatcher so j/k inside the popup don't double-drive the panel - // cursor. + // Invariant: parent shortcut handling must stand down while popupOpen owns navigation. readonly property bool popupOpen: popup.opened function open() { popup.open() } function close() { popup.close() } From a4837fcadbc88efe5a3566602dcf50b184ac1c36 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:20:33 +0100 Subject: [PATCH 138/568] chore: Clarify QML benchmark inputs and measurement labels --- ui/tests/bench.sh | 14 +++-------- ui/tests/bench_cases.js | 53 +++++++++++++---------------------------- 2 files changed, 20 insertions(+), 47 deletions(-) diff --git a/ui/tests/bench.sh b/ui/tests/bench.sh index 48edb80b5..c69e6cab2 100755 --- a/ui/tests/bench.sh +++ b/ui/tests/bench.sh @@ -1,9 +1,5 @@ #!/usr/bin/env bash -# Both halves of the benchmark, one after the other. -# -# The QML column is the one that matters — the shell runs that engine, not -# node's — so this is worth running on the machine the shell runs on rather -# than wherever the code was written. +# Diagnostic Node and QML columns use the same synthetic fixtures. set -euo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/../.." @@ -24,13 +20,9 @@ if [[ -z $runtime ]]; then fi printf '\n' -# QML's console.log is qDebug, and on a systemd desktop Qt sends that to the -# journal rather than to stderr unless it is told otherwise — so the column that -# matters printed nothing at all and exited 0, which reads exactly like a -# benchmark with no rows in it. +# Keep Qt diagnostics in this command's output instead of the desktop journal. export QT_FORCE_STDERR_LOGGING=1 -# A benchmark, not a test: a QML runtime that will not start is worth saying out -# loud, but it is not a reason to fail the target. +# The Node-only diagnostic remains useful when Qt is unavailable. if ! "$runtime" ui/tests/bench_html.qml; then printf '\nThe QML column did not run: %s exited non-zero above.\n' "$runtime" printf 'On a machine where the shell itself runs, that is worth looking into.\n' diff --git a/ui/tests/bench_cases.js b/ui/tests/bench_cases.js index 30b8001a9..a63241a4e 100644 --- a/ui/tests/bench_cases.js +++ b/ui/tests/bench_cases.js @@ -1,22 +1,11 @@ -// The benchmark itself, kept apart from the two things that run it. -// -// Every number this project has argued about so far came out of node, and node -// is V8. The shell runs QML's own engine, so the same fixtures and the same -// loops are run there too — `make bench` prints both, side by side, and the -// difference between the columns is the only honest answer to "how much does it -// cost to have written this in JavaScript". -// -// Written in the same ES5 the QML engine is fed everywhere else in this -// repository, and it reaches Html.js through a plain object of functions rather -// than an import, so neither runner needs anything the other does not have. +.pragma library -// A marketing mail shaped like the real thing: a card behind nine layout -// tables, because that is what this mailbox actually receives. `cards` is the -// only knob; roughly 0.8 KB of source per card. +// Shared Node/QML fixtures and timers measure JavaScript preparation only. +// Each synthetic card nests nine layout tables to exercise flattening limits. function outlookMail(cards) { var out = "Newsletter" + "
preheader text nobody reads
" - for (var i = 0; i < cards; i++) { + for (var cardIndex = 0; cardIndex < cards; cardIndex++) { var open = "" var close = "" for (var depth = 0; depth < 9; depth++) { @@ -25,17 +14,17 @@ function outlookMail(cards) { close = "" + close } out += open - + "\"ab\">" - + "

Headline " + i + "

" + + "\"ab\">" + + "

Headline " + cardIndex + "

" + "

Body copy & more of it, " - + "read on.

" - + "" + + "read on.

" + + "" + close } return out + "" } -function kb(measured) { +function kibibytes(measured) { return (measured.length / 1024).toFixed(0) } @@ -56,10 +45,7 @@ function timed(run) { return (Date.now() - started) / runs } -// What opening a message costs: the body is parsed once, and all three ways of -// reading it come off that parse — the sanitised document, the rebuilt reading -// document, and the plain-text reading. The reader then builds the document for -// whichever mode is on, which is reading mode by default. +// Parse once, prepare all three content modes, then build the reader document. function openOnce(html, source, palette) { var ready = html.sanitize(source, { allowRemoteImages: false, withPlainText: true, withReader: true }) @@ -67,10 +53,8 @@ function openOnce(html, source, palette) { return ready } -// Which bound refused it, because "too heavy" is four different bounds and -// which one bites is the thing worth knowing when tuning them. function refusedBy(size, limits) { - if (size.length > limits.richText) return "too long (" + kb(size) + " KB)" + if (size.length > limits.richText) return "too long (" + kibibytes(size) + " KiB)" if (size.tags > limits.elements) return "too many elements (" + size.tags + ")" if (size.tables > limits.tables) return "too many tables (" + size.tables + ")" if (size.tableDepth > limits.tableDepth) return "tables too deep (" + size.tableDepth + ")" @@ -88,8 +72,8 @@ function run(html, log) { log(" " + pad("", 68).replace(/ /g, "-")) var sizes = [6, 24, 90, 240] - for (var i = 0; i < sizes.length; i++) { - var source = outlookMail(sizes[i]) + for (var caseIndex = 0; caseIndex < sizes.length; caseIndex++) { + var source = outlookMail(sizes[caseIndex]) var ready = openOnce(html, source, palette) var open = timed(function() { openOnce(html, source, palette) }) @@ -101,15 +85,12 @@ function run(html, log) { }) palette.maxImageWidth = 380 - // Which bound bit is asked of the mode that is on. Reading mode is a - // different document from the sanitised one and is not heavy for the same - // reasons — it is flat, and the reason this column is worth having is that - // it stays inside the bounds on mail the formatted view refuses. + // Reader and formatted documents have independent complexity budgets. var refused = ready.reader.tooHeavy ? refusedBy(ready.reader.complexity, html.limits) : (ready.tooHeavy ? "formatted view only (" + refusedBy(ready.complexity, html.limits) + ")" : "") - log(" " + pad(kb(source) + " KB", 8) - + pad(kb(ready.html) + " KB", 9) + log(" " + pad(kibibytes(source) + " KiB", 8) + + pad(kibibytes(ready.html) + " KiB", 9) + pad(ready.complexity.tags, 10) + pad(ready.reader.complexity.tags, 9) + pad(open.toFixed(2) + "ms", 10) @@ -118,7 +99,7 @@ function run(html, log) { } log("") - log(" source the sender's HTML, as Gmail handed it over") + log(" source the synthetic HTML input") log(" to Qt what the renderer is given for the formatted view") log(" elements the formatted view's element count") log(" reading the rebuilt reading document's, off the same parse") From e9ce156760cea7131ba9048962eb4ce42261b37c Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:20:33 +0100 Subject: [PATCH 139/568] chore: Verify actual IMAP label response fields --- src/providers/imap/read/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/providers/imap/read/tests.rs b/src/providers/imap/read/tests.rs index 24b3f37c4..b9b444113 100644 --- a/src/providers/imap/read/tests.rs +++ b/src/providers/imap/read/tests.rs @@ -26,6 +26,8 @@ fn list_handles_literals_noselect_special_use_and_modified_utf7() { let value = folders_value(&boxes); assert_eq!(value["labels"].as_array().unwrap().len(), 2); assert_eq!(value["labels"][1]["name"], "日本語"); + assert_eq!(value["labels"][1]["id"], "&ZeVnLIqe-"); + assert_eq!(value["labels"][1]["rawName"], "&ZeVnLIqe-"); } #[test] fn date_pages_are_descending_unique_with_uid_tiebreaker() { From e96462b93689b713fa9125fec2b438cc36c350f9 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:20:33 +0100 Subject: [PATCH 140/568] Name backend polling state independently of visual enabled state --- ui/account/BackendSync.qml | 10 +++++----- ui/account/MailAccount.qml | 2 +- ui/tests/qml/tst_backend_sync.qml | 16 ++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/ui/account/BackendSync.qml b/ui/account/BackendSync.qml index 4bbdc3bd4..d4729a29f 100644 --- a/ui/account/BackendSync.qml +++ b/ui/account/BackendSync.qml @@ -5,7 +5,7 @@ import QtQuick Item { id: root property var backend: null - property bool enabled: false + property bool watchEnabled: false property string accountId: "" property string query: "" property int intervalSec: 120 @@ -44,7 +44,7 @@ Item { function reconcile() { if (unregistering) return - if (!enabled || !backend || !backend.ready || !accountId) { stop(); return } + if (!watchEnabled || !backend || !backend.ready || !accountId) { stop(); return } var key = JSON.stringify([accountId, query, intervalSec, pageSize]) if (registeredBackend === backend && registrationKey === key) return retryTimer.stop() @@ -60,7 +60,7 @@ Item { if (mine !== root.epoch) return if (error) { root.registrationKey = "" - if (root.enabled && root.backend && root.backend.ready) retryTimer.restart() + if (root.watchEnabled && root.backend && root.backend.ready) retryTimer.restart() return } root.accept(result) @@ -68,7 +68,7 @@ Item { } function accept(snapshot) { - if (!enabled || !snapshot || snapshot.accountId !== accountId + if (!watchEnabled || !snapshot || snapshot.accountId !== accountId || typeof snapshot.sequence !== "number" || snapshot.sequence <= sequence) return sequence = snapshot.sequence updated(snapshot) @@ -80,7 +80,7 @@ Item { registeredBackend.call("mail.check", { accountId: registeredAccount }, function() {}) } - onEnabledChanged: scheduleReconcile() + onWatchEnabledChanged: scheduleReconcile() onBackendChanged: scheduleReconcile() onAccountIdChanged: scheduleReconcile() onQueryChanged: scheduleReconcile() diff --git a/ui/account/MailAccount.qml b/ui/account/MailAccount.qml index 1f41a522e..68a319d02 100644 --- a/ui/account/MailAccount.qml +++ b/ui/account/MailAccount.qml @@ -2934,7 +2934,7 @@ Item { BackendSync { id: backendSync backend: root.backend - enabled: root.ready && root.nativePolling && !localMailbox.available + watchEnabled: root.ready && root.nativePolling && !localMailbox.available accountId: root.accountId query: Provider.unreadQuery(root.providerId) intervalSec: root.refreshIntervalSec diff --git a/ui/tests/qml/tst_backend_sync.qml b/ui/tests/qml/tst_backend_sync.qml index d4309ddee..25a119c1c 100644 --- a/ui/tests/qml/tst_backend_sync.qml +++ b/ui/tests/qml/tst_backend_sync.qml @@ -27,7 +27,7 @@ Item { name: "BackendSync" when: windowShown function init() { - sync.enabled = false + sync.watchEnabled = false sync.reconcile() if (backend.pendingStop) { var done = backend.pendingStop; backend.pendingStop = null; done() } backend.ready = true @@ -40,7 +40,7 @@ Item { wait(10) } function test_registers_without_a_window_and_deduplicates_events() { - sync.enabled = true + sync.watchEnabled = true tryVerify(function() { return backend.calls.length > 0 }) compare(backend.calls[0].method, "mail.watch") backend.notification("mail.updated", {accountId:"a@example.org",sequence:1,estimate:2,messages:[],error:""}) @@ -52,13 +52,13 @@ Item { compare(backend.calls[backend.calls.length - 1].method, "mail.check") } function test_disabling_and_reenabling_waits_for_unwatch() { - sync.enabled = true + sync.watchEnabled = true sync.reconcile() - sync.enabled = false + sync.watchEnabled = false sync.reconcile() compare(backend.calls[backend.calls.length - 1].method, "mail.unwatch") var count = backend.calls.length - sync.enabled = true + sync.watchEnabled = true sync.reconcile() compare(backend.calls.length, count) var done = backend.pendingStop @@ -67,7 +67,7 @@ Item { tryCompare(backend, "calls", backend.calls.concat([{method:"mail.watch",params:{accountId:"a@example.org",query:"is:unread",intervalSec:120,pageSize:25}}])) } function test_disconnect_drops_registration_and_reconnects() { - sync.enabled = true + sync.watchEnabled = true sync.reconcile() backend.ready = false compare(sync.registeredAccount, "") @@ -75,7 +75,7 @@ Item { compare(backend.calls[backend.calls.length - 1].method, "mail.watch") } function test_page_size_updates_native_prefetch_without_unwatch_race() { - sync.enabled = true + sync.watchEnabled = true sync.reconcile() compare(backend.calls[backend.calls.length - 1].params.pageSize, 25) var count = backend.calls.length @@ -87,7 +87,7 @@ Item { } function test_failed_registration_can_be_retried() { backend.failWatch = true - sync.enabled = true + sync.watchEnabled = true sync.reconcile() compare(sync.registrationKey, "") backend.failWatch = false From b0227b9103e000887e8ee55581fb1fdf65acccdc Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:20:33 +0100 Subject: [PATCH 141/568] chore: Match shell fixture focus, hover and password behavior --- ui/tests/qml/imports/qs/Ui/Button.qml | 11 +++- ui/tests/qml/imports/qs/Ui/TextField.qml | 1 + ui/tests/qml/tst_shell_fixtures.qml | 69 ++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 ui/tests/qml/tst_shell_fixtures.qml diff --git a/ui/tests/qml/imports/qs/Ui/Button.qml b/ui/tests/qml/imports/qs/Ui/Button.qml index 3645a18fa..8f1893b73 100644 --- a/ui/tests/qml/imports/qs/Ui/Button.qml +++ b/ui/tests/qml/imports/qs/Ui/Button.qml @@ -1,6 +1,7 @@ import QtQuick Rectangle { + id: root property string text: "" // The kit's Button renders one when it is set; a stub only has to accept it, // because a property the real component has and this one does not is a @@ -41,6 +42,14 @@ Rectangle { MouseArea { id: mouseArea anchors.fill: parent - onClicked: parent.clicked() + hoverEnabled: true + onClicked: { + if (root.focusable) root.forceActiveFocus() + root.clicked() + } + } + + HoverHandler { + onHoveredChanged: root.hovered(hovered) } } diff --git a/ui/tests/qml/imports/qs/Ui/TextField.qml b/ui/tests/qml/imports/qs/Ui/TextField.qml index 77eb61f65..847a40bcd 100644 --- a/ui/tests/qml/imports/qs/Ui/TextField.qml +++ b/ui/tests/qml/imports/qs/Ui/TextField.qml @@ -6,6 +6,7 @@ QQC.TextField { property color foreground: Qt.rgba(1, 1, 1, 1) property color accent: Qt.rgba(1, 0.5, 0, 1) property real verticalPadding: 5 + echoMode: password ? TextInput.Password : TextInput.Normal color: foreground topPadding: verticalPadding bottomPadding: verticalPadding diff --git a/ui/tests/qml/tst_shell_fixtures.qml b/ui/tests/qml/tst_shell_fixtures.qml new file mode 100644 index 000000000..e2bf5a9b1 --- /dev/null +++ b/ui/tests/qml/tst_shell_fixtures.qml @@ -0,0 +1,69 @@ +import QtQuick +import QtTest +import qs.Ui as Widgets + +Item { + id: root + width: 400 + height: 200 + property var hoveredStates: [] + + Widgets.Button { + id: button + x: 20 + y: 20 + width: 160 + height: 40 + text: "Test action" + focusable: true + onHovered: function(value) { root.hoveredStates = root.hoveredStates.concat([value]) } + } + + Widgets.TextField { + id: passwordField + x: 20 + y: 100 + width: 250 + height: 40 + password: true + text: "synthetic-password" + } + + TestCase { + name: "ShellFixtures" + when: windowShown + + function init() { + mouseMove(root, 390, 190) + passwordField.forceActiveFocus() + root.hoveredStates = [] + passwordField.password = true + } + + function test_button_hover_reaches_the_cursor_owner() { + mouseMove(button, 30, 20) + tryCompare(button, "hot", true) + compare(root.hoveredStates.length, 1) + compare(root.hoveredStates[0], true) + mouseMove(root, 390, 190) + tryCompare(button, "hot", false) + compare(root.hoveredStates.length, 2) + compare(root.hoveredStates[1], false) + } + + function test_clicking_a_focusable_button_moves_keyboard_focus() { + verify(passwordField.activeFocus) + mouseClick(button, 30, 20) + tryVerify(function() { return button.activeFocus }) + verify(!passwordField.activeFocus) + } + + function test_password_display_hides_the_value_until_revealed() { + compare(passwordField.text, "synthetic-password") + verify(passwordField.displayText !== passwordField.text) + compare(passwordField.displayText.length, passwordField.text.length) + passwordField.password = false + compare(passwordField.displayText, passwordField.text) + } + } +} From cde73c269e39c05a68d02075ca96e681aa658b4c Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:20:33 +0100 Subject: [PATCH 142/568] chore: Extract the native intent fixture bridge --- ui/tests/qml/NativeIntentBridge.qml | 37 +++++++++++++++++++++++ ui/tests/qml/NativeIntentFixture.js | 27 ++++++++++------- ui/tests/qml/imports/qs/Commons/Style.qml | 18 ++++------- 3 files changed, 59 insertions(+), 23 deletions(-) create mode 100644 ui/tests/qml/NativeIntentBridge.qml diff --git a/ui/tests/qml/NativeIntentBridge.qml b/ui/tests/qml/NativeIntentBridge.qml new file mode 100644 index 000000000..3f2deeb4c --- /dev/null +++ b/ui/tests/qml/NativeIntentBridge.qml @@ -0,0 +1,37 @@ +import QtQuick +import Quickshell + +QtObject { + id: bridge + + signal notification(string method, var params) + property bool ready: true + property int serial: 0 + property var pending: [] + property string endpoint: Quickshell.env("OMAMAIL_TEST_BACKEND_URL") + + function call(method, params, callback) { + if (method !== "providers.resolve" && method !== "model.intent" + && method !== "model.apply" && method !== "model.unified" + && method !== "agent.jobsProjection") { + Qt.callLater(function() { callback(null, "unsupported_test_method") }) + return + } + if (!endpoint) throw new Error("Run this suite through tests/run_qml_native.py") + + var request = new XMLHttpRequest() + pending = pending.concat([request]) + request.open("POST", endpoint) + request.onreadystatechange = function() { + if (request.readyState !== XMLHttpRequest.DONE || !bridge) return + bridge.pending = bridge.pending.filter(function(entry) { return entry !== request }) + if (request.status !== 200) { + callback(null, "native_test_bridge_failed") + return + } + var reply = JSON.parse(request.responseText) + callback(reply.result, reply.error || "") + } + request.send(JSON.stringify({ jsonrpc: "2.0", id: ++serial, method: method, params: params })) + } +} diff --git a/ui/tests/qml/NativeIntentFixture.js b/ui/tests/qml/NativeIntentFixture.js index 3b55680e8..7773cf921 100644 --- a/ui/tests/qml/NativeIntentFixture.js +++ b/ui/tests/qml/NativeIntentFixture.js @@ -1,9 +1,12 @@ .pragma library +.import QtQml 2.15 as Qml .import "BackendFixture.js" as BackendFixture -// Real native ledger; the loopback bridge admits only pure model RPC methods. +// Invariant: the loopback bridge admits only pure model RPC methods. function backend(parent) { - return Qt.createQmlObject('import QtQuick; import Quickshell; QtObject { id: bridge; signal notification(string method,var params); property bool ready: true; property int serial: 0; property var pending: []; property string endpoint: Quickshell.env("OMAMAIL_TEST_BACKEND_URL"); function call(method, params, callback) { if (method !== "providers.resolve" && method !== "model.intent" && method !== "model.apply" && method !== "model.unified" && method !== "agent.jobsProjection") { Qt.callLater(function(){callback(null,"unsupported_test_method")}); return } if (!endpoint) throw new Error("Run this suite through tests/run_qml_native.py"); var xhr = new XMLHttpRequest(); pending = pending.concat([xhr]); xhr.open("POST",endpoint); xhr.onreadystatechange = function() { if(xhr.readyState!==XMLHttpRequest.DONE || !bridge)return; bridge.pending=bridge.pending.filter(function(x){return x!==xhr}); if(xhr.status!==200){callback(null,"native_test_bridge_failed");return} var reply=JSON.parse(xhr.responseText); callback(reply.result,reply.error || "") }; xhr.send(JSON.stringify({jsonrpc:"2.0",id:++serial,method:method,params:params})); } }',parent) + var component = Qt.createComponent(Qt.resolvedUrl("NativeIntentBridge.qml")) + if (component.status !== Qml.Component.Ready) throw new Error(component.errorString()) + return component.createObject(parent) } function install(service) { @@ -11,19 +14,21 @@ function install(service) { var pipe = BackendFixture.findPipe(service.backend) if (!pipe) throw new Error("No backend fixture pipe") var listener = Qt.createQmlObject('import QtQuick; Connections { target:null; property var handler; function onWrittenChanged() {handler(target.written)} }', service) - var offset=pipe.written.length - listener.handler=function(written) { - var lines=written.slice(offset).split("\n") - offset=written.length-lines[lines.length-1].length - for(var i=0;i Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 143/568] Name direction policy local scan counters --- ui/message/Direction.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ui/message/Direction.js b/ui/message/Direction.js index b53c68181..f45f1558d 100644 --- a/ui/message/Direction.js +++ b/ui/message/Direction.js @@ -101,8 +101,8 @@ var FIRST_STRONG_ISOLATE = 0x2068 var POP_DIRECTIONAL_ISOLATE = 0x2069 function isRtlCode(code) { - for (var i = 0; i < RTL_RANGES.length; i++) { - if (code >= RTL_RANGES[i][0] && code <= RTL_RANGES[i][1]) return true + for (var rangeIndex = 0; rangeIndex < RTL_RANGES.length; rangeIndex++) { + if (code >= RTL_RANGES[rangeIndex][0] && code <= RTL_RANGES[rangeIndex][1]) return true } return false } @@ -187,16 +187,16 @@ function strongDirectionOf(text) { var source = String(text === undefined || text === null ? "" : text) var depth = 0 - for (var i = 0; i < source.length; i++) { - var code = source.charCodeAt(i) + for (var characterIndex = 0; characterIndex < source.length; characterIndex++) { + var code = source.charCodeAt(characterIndex) // A surrogate pair is one character. Reading its halves as two would put // an Adlam or Kharoshthi message on the wrong side of the window. - if (code >= 0xD800 && code <= 0xDBFF && i + 1 < source.length) { - var low = source.charCodeAt(i + 1) + if (code >= 0xD800 && code <= 0xDBFF && characterIndex + 1 < source.length) { + var low = source.charCodeAt(characterIndex + 1) if (low >= 0xDC00 && low <= 0xDFFF) { code = (code - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000 - i++ + characterIndex++ } } @@ -256,7 +256,7 @@ function withoutReplyPrefixes(subject) { var text = String(subject === undefined || subject === null ? "" : subject) // Bounded rather than `while (true)`: the expression can match empty on a // pathological subject, and a body of mail is not the place to find out. - for (var i = 0; i < 12; i++) { + for (var index = 0; index < 12; index++) { var stripped = text.replace(REPLY_PREFIX, "") if (stripped === text) break text = stripped From 35d1e564b570a1f9d48cc30eac281545e5a428c7 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 144/568] Fix first-strong text direction with pinned Unicode classes --- data/unicode/DerivedBidiClass-17.0.0.txt.gz | Bin 0 -> 43595 bytes data/unicode/LICENSE.txt | 39 ++ scripts/generate-direction-data.py | 88 +++ src/message/direction.rs | 100 ++-- src/message/direction/data.rs | 624 +++++++++++++++++++ ui/message/Direction.js | 118 +--- ui/message/DirectionData.js | 626 ++++++++++++++++++++ ui/tests/test_direction.js | 37 +- 8 files changed, 1475 insertions(+), 157 deletions(-) create mode 100644 data/unicode/DerivedBidiClass-17.0.0.txt.gz create mode 100644 data/unicode/LICENSE.txt create mode 100644 scripts/generate-direction-data.py create mode 100644 src/message/direction/data.rs create mode 100644 ui/message/DirectionData.js diff --git a/data/unicode/DerivedBidiClass-17.0.0.txt.gz b/data/unicode/DerivedBidiClass-17.0.0.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..76cd9318d4b250653767e34d8f31e182e834d87e GIT binary patch literal 43595 zcmV(}K+wM*iwFP!00002|E#_1j^wy{6>dcgKbgAm> z#zLdkOs$#1>gk%(U9;>tZ*=~ghuBYcB7(Z`rmSpl_h2$BNyf)}Fh~X?{$Z0peSQA> z(@*L1PtV!s$8X&-uG^2gVwKW*Ht8{BTATi5@W&35}I$NiJB~1j`S$d*`Q`QXw{L&?*MI%b|NPIp-v#{L%h#X(m8d?w{Ph!1 z-Tm_V>*t$)kcyuD^7!@fM@WP1@c5Ur{7+_ zzJB}H*RQ_+uQ!13@89_kX|R7b)Ipnn`V7tX{N?AVm{>OKu7BD5_4(=ZPaFSFRGfjm z-~59QKdvg*KU1|oKmYA%Y~bI%zWny|^%Yw9UpBvgfqb8T{sKKk?eg2p^Ox6e*fW3m z{PN@9z5(smr*BVRVH|D#3XSvi`R89=Z(m<-KR^BTb@T1Vug||ha_sY;VXS@GJUvqu ze}DY^`_s2gy8#k*_!mIIep}BBhe7uH*RM}se*9z8{qgHxUOs;lC6KT&5dm*_KaGu_ zo?aiHAuTow#{XZxK0_AJf}fwiKmq>p^!epK@2KZ{h+Qeb>o1S5fb`eL-#@=@USBq8 zz4_(w@6cRdo^aS9?q6R%0}=u+t@kGyG8>p@MER-u`OC}K$G?1j`ji3qrxSvYN$Qs` zKTab~i5;u)`1$iR`e7&nGSV>!l#BW0<#qG)U%$cVe}4V^#|FpB*ef`MKG6_DIx73p zSO@5-PyNfM7Q1fqPltcLL-eVk{shy0yS=+}wgvqAH#IdT+y)6mZ-b)Pluv*8`t+YF z@f`ba8zMnk#30fTk+&g`GH96RA2BSVu*ffdgX|xHEj_AAGFOiO*Xz@lpPqjDlu|UK=)#Oxpxw?~);kDvcp$)QM{T##Fusz|Y;i+ri9iTjDIA`9Zo)&T!!$aygm z+mJc-U%@XTrz+k|V!?C75Oin^W`F$l_4(x$`s(v%ScSg+Arkl^0gT4#S70_!;7@?_ zs~DD!7zywN^X2sT`PV<7zn?@zEFu^TcYu3+e4^0}AzVb@Bz}Y?S%fB{Ac+Gwzq~xb z0`fe?xFQCMc=+R|IaHJ@fpT@vKjF9#!6MfLM)>jR>&r8am+~3@`uX!8zy0z}q+udW zA*F$l`VAO6#WPV92GDz8lrP_YdHv;C#E8l=sBH83r%&C>@2|gnqE;PC#YFZj5eaHo z`LqO?NKnw^eg;N7HA^aTO`)3X?@!-er(jXf6x;ucSmU6pp%YFpdVZN;Q&F%qGE@EX z`SI_f^r@dSqDAt!*z8~#6T_5?2H?;D?eD)nf2u)j z`U>@57!O2>YH;A)=coS%mMJ}7e~P!3pNp>J7Vem7NJ~;{4T^D*bEjeS^G{}LE{UwA zDLfI4oZe19C$N_x646YQVff?cUw;28Vp0*4155Y?gotmyPNS^g)8f40pa1w(UzrwA z`v~A-fbclSi3bh$Y5)AU$G`nf!;cFFz;QyepFThSszOh+S!jpOA`zY91o#P8?dLxp z|8E=ye|h@)O~YCeTbf2mn2Cfd^$`P==Qv|tUtfNO_3Ki$OY%3e%>$8eC0j0Vq=9&R z1QF|3SOk7V?!2s&wq;kQf1?~?2y%OO{&%+*LN@$&O}5)^eFr3pZNN}O1<`Nw51Ye3 zZZ;p?@XwnA>#KT`u~XHv!{)&Ip0^uzcV`X%09YYmMeA7IksVAVB@}TOA&7q?&dd0- z;K!=2YQAaOys9Dls?Mv7^-T+OX<*R(mL+sq|B&fh1QE7{gvwX4fIw~EiF8TKb&jm zY=`>H$vmwf3*4AI=QV<6hbr4^NG*r56$k!a#3HBvZ;BR&GBg!t5MljR zN>$(Uwg+NcPD&N}p{*g^SdXIW%Cc$p8&>Dzpm1@CgU?vX^H;1?^5@O5$*ZCQlo3oI zmv?veh%=(4h?Y4zT4bV)Ma!Dwk(rP!hbnej6(NJ1ikll5xRwmsiq*T}z*@-UfPJi| zDA}Pfl0hb%GU2|SNwC%?J7%qfh+L}*=f-sWbz*rMP~Hsbfp6HU!6|tvVX%0#fAu2I zGADN}=X-s;m%N7}iYS%ow^_-mY}2vhsY2k8fFm8)T>(A;U3or0D*`tgTf&l!nGEw{ zt8E}4&ZlO_fmt7qyr#mXRJdF(oHrFtYxBcUv!3HBb7Y(Dd`z2zTDm!94xM8sz-)`v zWz5M9t-63A3tEn(I4dRE!@mA0V; zyw*TCmX|p?3)`-gceu8^ZP@@k^ANrWH28R}Ij9>a#Ib9qCYn39hyc`&9c|t9k~Pq> zxx35GZFM-{w2=q-zB!#>T>G)Bw`DgiwKHK~HbV!TxEp04KW2Dl=N4KyLSX+hky(_s z-&D&ozg94Q808J#WxUQgh)#irvSAPyLJh2#ti}1pOzG(i^KUJ(;3c32$?BAz33dK< z;6*REaa+|p1fiw~q^3C0QX5J|TezWAB$lQyqbpbmp@)yG1<4?w6S^RdwR-xF1ZG<` z)ygU<&Xp=51+h`<(~Dl~VmM69KiPVE`s0t|&z#@0n(bIy(ZJZ;R~>7242e(xNxVcA zKt2Y*@+Bf=Xh1ufQ6++T=`|&|ZysRiP&t~0BU!#GMCt`+_Y63<$PC#+;%~Lgkd4_h zV`{;rm)A9T@ybLB<%Qnp#DjN`0l(NuK-8Ixx3ldddvLovOoUejE0C=#y zrs0|+CPk*7gpStF&eqn?KUll?zR4IefdeqOB&2Z@2KsDL>y<+jsaT`fK@kWO5{%S5 z^-pH8U~#Yd%?IA9Z7qUvp9o0Nc6GK$B+6VCJTi%#Rqmn>zp~oF1U<0~SPHK0NbO<` z;;r7WfvsW3Ap=d4@_GlY31ag*9DK1r@hrn+N-4U%9=dzhN&wn?jspV9^bJM404*DH zEoAOs#3>Lb*;+Ox8WlHi7}hAkWi?^3)-J9I&=>$U)&!^PHc5>VLHC=H*?h4SV{~cv$3&>MB`zWU}9idL`d<4F(i?2D-d;E zmJ(2Q9Z+KjLgtt8Ydc_HB0~Ui1E}(7brqRs%>ab;4pvLC9w#}TCM0?O_Hb=m%V?pV z$Z5!PN5}9CjPv=zV#vurGB!%eKg8*_P?O z15GxQER0qU8U}>G@x~k*i`CO}Zerk6We###=GwTdp1x^J3}m#-MMld!8>7|JpDcC3 zhG(8j7~U0iIan|b2Lhos^};Ja?kyl)Ngy$SBv*iR77&4fJegTV%Q?Nqlx^Y2m05sd zB?~gks-ow;FH2kdQUeF;tW+l`Fg*!Y%qm#T>17tA1qvR-NVs8<+U66~^E?op8MuHK`?2}Mwcxe)v;WP=e(iSiXI` z5pb`@=&YD==ZbEdq>i>VTV9q(7)d0I+xfvrr}6_OaO4NY_QI4N32alkNZzjcbTf#Z zpKfvFrd!*7sA;P+(|1Es;LH_LTBFmgZ7(F!FDya%E$xF+TBK9!BCXJH4Fgx_lvd}| zx;iU~8;uwlKuXJUYF(C<#3#M@IQ3InkW=e|tRz0@)HLZ+T8dN8HtE%-(#fg!E*$8{ zy*JPG)Z?r3QxGT<{RZ`Rt|veakoveeO8t0sK&e|JGgksh2_(A)q_Kej8%TrbjiT$D zn>4`9O&a8H^<~={LxEa1pfMcURy8FxZENf^0jC0q6sc9D5JWQnkV6FXNX-+PP8}7~ z4j{Fh$fzl&yI-sw$tbCOw={2FMB<`l88IWgLH=Q2Es#zHoa6ek<$T((^koOYrW`Vt zqG!kIptBniLeki_B@pQscBA~p%|J?*9I1KU;%UTOBc^egP!pK9$i7D0XvBLgc9IY= zvy3h!F>IeS@{Gu{H(F^-{EiZfS{85Sb=LFh@n|5WyPA~wZ_?KWJ(0&m&faQdgZf0& zRCrww`snDHA9ZS)gsGsm9R!QSnk-`kVn=6qy^?0`H6VipgN9m0^VmEm@+=_S0zyMB zqt(fji)>@+E2W-b}YGMQDD83`orq6A3N zOt!^Am^oH1qY!Z&1v@=+kk4eMJY$eIIyp)-8A&vmao6O8I{C?{1Wuvsf>YR(9%9WqqRJIAV?Cb)KD)6qnxA1lxx(UPCcs?h!-qeF$v zdZ?gR-Grd2ec?z!?a753r0ctkiA39HWT`PYk6+eFuysihG0O~=Bh^gVn=G|k<2qUR zJ!QZ-NH;;5^(M$h!L4PWu|msymZjGrHCCXe0ic{ZT-K>IfTT5i!C{rUwr6zHljZ!v z@Ygt~HhS=QG@~Py%zDJKGWC#guFXoEmLzjzR+(cWlUb)4HuBDbmMdBAFiJ%&`mQSP z*>N~jXPrR}Czh8-RznQpd2bGQA%8T-6!oolGvC{=w7KV-w%V2b%{HgwnB00Cb7Tj0 zhX0Q`Ai=GY+-jpwMa9M-J$ ze_gMS4TL1wGPlZ>T~(JrrLst5-b%#CB9V3HBrWDisLNRK0ygVUGCJZ)I^Z$ceT?9?(=Ggu$&usN%H_KtxdIKihL!KW5>uF=A#_ze3Oz_4St3+6iaTq)0C zrX>L^&qB+&xkh`xQjTK5qPZkL4Vby!L?iPyeqgsJ7!MMp6pbqCkR~6~06aYb%5&pP zD7M1y7!>bP1~_!;VPA~)JDd(%xPD>s(Z?ea;Bqik8FCO(sfO{5duuhgBf$rd=<y|2UU~7{Hl8t=Je-%`<7lQmC(jG( zZ_`IaLdM z3SYt=Q5`D>c*k2m-jfM4*7AOHn|~PcP200ww>fec*5U*Yan@G`v%XY4Bnqf*(S^1= zG`prhpZK^FhC++%mwGXLkpao7jE&>2g9>hTP_E4_aw|cA*)htl(6bAd?1;Y2VFc%U zpxkBEZplfDq`zv06+tT<@M-17BeBAel`t`i3p#!;QH#d+M{&xpM`k|~g$7&i4UVJ4`$#JkE1*h6u@89I+KQl3WI;~rdQ#fGJnqK&k z?J{N>R?`jZ0wZ077WCMp2(>eik6vgXh^tUFjII(2^Wc2B7gGjQ4YM)LXg0>db+ZW8 zr2z%9f*uPN=Bag{HQOQMc}K)rAYj$YTn zv}iW%I~>t;&RNKpkmh_-XcqQlpw>;hNe3~`ZujLGUosb&D5o)@UE73)nYv6~+oZ+> zyKX=xPpeUp`?`FjGu^b?vs-+31(X%BU93T^G2QIYba;A~wmF0DKI7jLo9=cj6^x#a zV2eD~D+8+-o%7um;>H9vr`@QJ2a6gnY!Tzjzoy6Okkeq!nN8S}i+SKIM;sUk5TtQg zO3}BhI%r95oY8EVYn;j9kp{E|PEBdPX+dlN1UDrFo951xT#_q#e3r)~DD_&v*?P|U zA&^PJks^MRLOCV{3M#U9smNJVcTEjD;E_e~oEB)Q;Pw-2q-c3f z>hVD8VlhJBc8+V-KqBYEQXsO$K@(O=u;-go*1Yh;Sa8rZH>2a&=6{ zZigeQP(ER>x5vvoGzD-7>b{BXW723wwq==EbB{a{I?7{@2!hmFRgvFFf z;n-K23L-aH!GsHwdKNK6V~SKB65VYP{C#%7hsD57Z=9_#)RzU8xB5HYv^(2dePF|D zab<(m&!TmU4=aRcEKHVvHyz_hn2(m$^q2UaR0~__=Q}?HDbjVl_K5)Rlt6Mkm9Qe= z-)JieD6^|AuFOa^Bg$M@bF-P@&#Ir~A3Znu^QI(QG_VzF zI*$A4eRbx|{_c+VW!0SUo_sog_yJjvOY5`i+g2(YNo7ZZ!Qj%m>;|@@cnb-#ep_&Z zNbxFvu#r$bXvKAdE9+6NRHUSukO4$DjxD#sCQWLs$a^YOOofWCE7W^?nch>8h;6yX zS)b?GkZNm@_EaQ1_k+*isv_;}McPx5(wLC=RsFqxZ!gn(?C)&*9sRu*O`B0YvMcMc z(zbiixEa+X4=u0yO_~R5MI^giSR=gaaXei);bUNJn-5mR9ahsr1qJxLu9`c0Eq7Q+ z&!Hme>Wm*lYms(4Ynh5OmWif^7sk3spU6l;jvw`V=3pyZ^}+-Jqf9%iLYqG`rC4@p zv75t|o8v_d*YU_SsTUU(#Z$9J9Zy-Ga)3UrbSyOZ$OZt3z(D5E1 z3TpqtFgztgs3u~#grvkEo{uNTPN*F!eGIYDGFHRhdp>KfvJQ{aEuk4}+ltg!aK9IZ z`MS{|3-S0)8VUL8ifSQT%-8^BfwhQ?&WfzH_yO5PZn{IG)=GRcR4Q&1ZfvE@)x zslr~XQqi({j{~RM^BzQ%F1vBa^t%%|jzxW;XFGOicFJoQB?R{_krP}{`WMMZO`qeC zpPC#=aNtCqk!ND&IjX&&Mj1#)L)|n==H}t{ocWYo&m14j!DnbW13Q(~p*o$=+NiB( zrRdQ(j?%vo9l1n-ttr!?ta90&i~O5vLX0^w&Y2y0$*@aV{lL_YP=d|`f#WNR>@Snl z^al$DvJo=t??i^iaDa-9<&i7LcOsywbACdrVs$_6iGIL?yeJLVRT_yEj|j!8QA-43gUMNW9QG54xK9{{Jv(sNy3{=) zz+~)L53pKR)n-2oB?3jOI}eHO!1u7nY%qOH8MDh7r~G_I(;;$Mn&vnRJwmL%^^(%F zd$vb~MpE|yDza-Gaohe{P$_z`Qi#}5#}3lRj&*+y`E?T!A!Ru`GRzNWMQpqz@cfJUSu#1Y8ZU?DG$}H#_=17x zHxUkmK*rYNBGA`tyF}ESFN#E?>0oGRVNE@8xL$Fz-CP~h@deTCL@CO6cPHXzTe48X z#KkkZ#0@Pklq94@QQrte_LR5@p`?~WCqd8+>AR*v3xqRkpRkN5++`$W-#+mi3&R`9 z6dRQbnjBp32#Tuc#g;Qe3r%l_Iv^5iG&_nhy+wzENE9s&DMWC9gw7+9FxR_{-UZ@A z1LfLQ31Kkz6S8cdM7H^*rk+kdEukUc&^%38s-Gr6r`P;JU=1@F8J$Cue3rOF^8g)) zZ9_vn$r6i*E7K|06Z9wAbmTP-PdVLu#DD7oI32PjR^=I)NN#>JeC&kWnAP<(tCa$j zv+8hzbi!{4b3)6rrF7T{S5(|9GQh*K7OZyNS2GhWlBbMtq7F?2=N2>KJK^8>cO@2V5ZLq){ zaDuSVc^g2{Is+2q4lMMoPnsM!$w9#f*5gF=fnIDlB_TwMAg`);&`yBf?WyD1n2drj_$~ zGIc`@HJxWa(Cr?81LR0WBb#k4g55&3Z0(FNn*YqXB5Q5=gKmWufDJyc~Pb z&o5xK{J=Q2###dO9)S&PZiUvH<;WOEw#aB6F`Ka!qX9_I&Is*jK9Xdq*gaVulFSs! zD-tbqoHi*<8y;As-i2a%4T%G!XZzVk4$$)pc3~;4s&bWbk)Q1*-bi0f`Ke-F%K7zq zVj1z7418McI8%BYwatO`Q-0XTHQHfC_EcmG7q8=w9Su@zw41~9y?{g+=)| zD2EAc1N;VtD>{?1r|92d%aNp>r5ANejy=0?2eg2EK~-io5o(`gDGikLq9({H0>367 zMOQ@l-OI8_?~GVx#BzfRmeLLFSy?5_B+yhH!}T3UZ|<#L0g7k+Vt!X;SKc$+zK-@7 ztlU;m(5VE2Ekk?HM2LJ(fXA3nYXri5e#UJ^ccrWsV+SCUw7UjP(n1AoDehra9TQ0Y z&mapL*M(=%Je6Qd{=O=j_9)JR7i$Jml4Y+%o3!@*(Ds?wCzXziHeuX<}LvaA^J9#q~0m zC28bJA4AV{swDxBu9}9l%i8MHs}r9N`STE$lU(;#Mb~B)k7xtGvr4MCU-BZ!JhwcjRn{!*M$<*ch1d7x|FSCD5xnk|K6)2w*g#TEWt zt+X1?Phh=2vQ!V|gYpI}Js^#TuNh&DbP7Qf#gFKV(b0=nkB1rmw3PL5rwT9sG{}H&UZBd7z(0$R-#nShnNzJx0 zuJ~>od}GEWLlvp7WgK|cPL;gMQI}GtieEjuTfl`3vo)!pAn1h!J~MrEMQ;|wtn<1r zyi?nBYPS51ZZs%J-LS~~H{1s5lby!RmF+bXt+rN1t(9HbS_{W{v#pk-dcEl`sL0oy zM5;^D>=W?5Wm$Q))^kaOcM)fhK$J<5Qzi3smCvn!y5mZp)7FUiS3GwaLl@qI@$lY#@`Ih~4dbN*7jD2%U z=aRx+kGs9#q^ldCD5ETA6N-?!`0rBJK#ki#S9#Jw;*lf`+GWYb^|d{|zj2+dyUKTj zV13*5?T{^Pn<3HqBMUwpxOnyl+c3%iO5r+=r;lhny_3s?hmcAcfz}DWvv4&MC6u8d zm7qg3E79rh&K}VMn(KdO5k4T%x|7tV6t_*7Dqc-R+M~DH)`5_zHQn68{Pz5CU)AHY zSt|f`om(J)=UaH0()?WOjs|E^#}Gba%dVEeq?t85bNJOyik(2PE;Us(Zc9g34b9MI z9Mfl%jmh?xIYnT3rxFi zI&M5REl?L0_Puz5ATe1rq2(tkLJ!#2;k)WR@-2>4KI&zbvXsj1d9X^jqibd9&MHh` z=$)YP@Fb{0Z(>t(R<|j~SN8T;lEeTu30AwsPWZ#Xpg4YlL)4d53aL1_r^L&?8up%D z^#Kp0%|^qcg{sXC_E?zYAMOmEZh&6Y@LfA< z_OhOyeFA%^@!VbuMm4@$$MyUmjN%)YPVU_-N;U7jXhUdsV5k7soBn&*he7iYub!NY za|248MH%7e7SHDw7p`~ao_|8WM_7)q+}Db|^;UNL-RSuCfpxRT;pWuSn+xjoJp)dX zq24@vatmJ?lWVwHdp`9I2_0k&mRAd~a^|C?+p&5FBAT0_h~}zid((Wi=a)7mt6B)( zuV$qrxpC=q%+1}4Z!p!-Dnzi`r;X(ynJRr8j&#({Xn7L2}9L<`*2m&Oq}MqlqY{8YDKQGV|fjp|L;9 z!q-%8&IpQK_t>%PtWaHtO@dl9@Oj-cIx^903r3`r%9LJLrVsX4XCFQg5|t^vwoK(p zp-RNcs8rdN&qB}kXQ4EBGAdPe<%2^z(w>lVDpP)4ncmxx-U}ouQ+{2Uc6Ov4AbHzu zusSuWoHz7p4zECZbjUf+1fUC7&+TQp$!g3*WpECXA9Skmg&moJ^0uyXcL$$|E_95~ zjz53|p-MKY(uCOEPFVj=P8`86ql zjMf3vP*^oNgD!XQECfCsizy0ufU>&A3r(!{p{n;2o4LDNNi^oTV1YcM*@K&h%=5!hU$fgc<7&TF<_m<~cdTTJdiG$iZkWbypGJW-GOPHIZ3cjK3D!+4CIwZ>xz)rfuoeky z5>XkV`kK{7Qdn6dJT~~0a@yA|;bH>0cvA+Sg+87@%${hZm*Y(>4uCctdW+)=?wE$- z!Q@#_2HAwv9P)lmw6c_q*1lSB2`yW07(iX{inDK8j`DbqF4Nn5I_UA-n6i&;y z#<6!GLzLw_FACL-xPx{Lrc%yR1r=JT`!=WS28dE5mHo(5Sras7E|LK^-_-2LH?V>0 zaGN)VKcqm;DQ9{8=%#mJZ&!ewMW_%z1zad!K;#&JG|L4sS=cl*sy5s25bNfrcPYIwTYkgN8K`2SwW+wtX@z)sW*b!Rwnn_; z1Hy5FvuV5$m8?9KHOJ#rBsqLBi@*Zvj&Pf5-4OzBxo2{VL%vEty}JRrbu&duV&Sy{ zpMwFBLs>euMM%vdZ_pA5n=+<>`mUjjUBa*$uD#c+h~KM5#DR(tZE90~GV?z&z2X#{ zH-O|*DMI~P-47)VLG3W-13w0TW$I zidK%50_G2^+KXf+0?&^D8IMZg({{$Us(Mt?vO*Ubt7*EX5GuHk2cyz++cVpg9fzZA zqCoz=uYef+6u@Vpov=GP@v+gVn_bx)0Ra!{;4`wkIuZo+I|jX3P4qtuyjvu47P&|t zh1!M3$5jm_zQgmv$s#mfy;x7@vj*BGGLNNJRlkM~(>qw0SXVuB?W$+_aJ1$<>_IVViglapDwIA{_81aWgV=eB%rkF<8)hRzv z9f}K<<>jO9s-8P0Z;%o26KttXkC7)CW&Nj=$t>W zbGNCGKBiJ8*YKFJyrtZ9Ybu0?YRCEkgsX;Hm#rRBzkS_tL;xJJ@z$}N%&k>(ZY!AL zu&^|Jg;t!~YEdo#K#yPpi=MxYWUwPOh!hbLvt01nNYLShEgaY)f+6FNUDtB7Z6nH7 zzzEBwD!R6pg9?rOP*;Of+#~|lx-#+_S%W3PD+l-tEZ)9rU{WP2ghTh)eSTY07~Z4+ zKBP<{%OQshG2)H~19Hp>_JzD`4*3`hm?VP4k^E_JxPI^CQ1foA9K=2VK(_TN3z$lSuFL+AE+Cjlo zty=&fCs>;(Em7sT9aeCrLt%^n7}^}fRwD*7k^GQN4;F%HOaez-L>8_8oZrK?a>v?g z)eY_4ot{XFT-*Ud1~Fx0v)H2}oQAGERXA{@81kZkIO!^Tmr|FU<IBj!ON;N$31T#Je1Z|sU)dudEGygEUZZn!ikim0>bv_a89p0o^R>NyERU{ z$OSYSU}<_aCO*iwW9AjGVb~J3IB-)MbeYWu=uE3WLgw@YSpvt`pL^VXB$-2Sx$fP^ zQ(CV;ADb<}>`=d8ju>U96FQ1LRUJQY?89vR#$G8vi-q7Ppdij`Hy<-o$WvMi9H(?n zEtA`(qm*xsCo^pip98**?UYu5NT^1Aiywf^IgjhK`uHfsT|P0rWuGVhoRj#_)IOh4v?(<8}0x^ivFQNTz0MR1wlnaI!dqexo~2#FAXHjuOnQz!RV*~NO1vRxAEkKnMUvihV@SIK!&BZ2f12uE@di0D7%E{^A!_v zQtE*-0|5mhcEL9KoP1P*fnD^#iFah~cMx?X;;uH^Tfmgi@4!9ti@>M|D4>a7aP}S0$fhrX*J#BLK-Ya0 zS=c_WkR-c~jUI;Mrh-3!gcg_7zFCw>lzpNZAw++A$dX5zGi+Fbok-H}ot2;2e3UeY zl~s9@M=8N%w$rqc;2pG)IDBeu&%Bv|mT=N!yybwFrHED-R(O|lF4SQVRCUFN`nHA7 z!-6@-p740+|0qU!QJ&|Mql?N&n;SP65Po&kM>d%rEjv&040zhvH77>1)XuYz13!extr^u6= zBBk=H3-CWG_ifrOU!mWlPZ3=YXpVB9{`p=jBaNpdx!w zc>0os=95ti=b_4xw_EL%0O92n9{}Gc{NNgVo!MTDN9-^}Y;zO5{WD$h3R+z`^noVF zTI{q+0Q!Y3u}ObfI~vib9TMFHw;x<8E4x(G8c@+e9()!yMRb#J)XbK(wk@g9Tm7w( z6f#3?m!e2*#@`p1kw+BxzOR+>RlRC)E?$r^3HY?#D6NsQbySXsj1Y_OKpYvSJ+eX2 zoQj!$PchFIFwZ!?aw@2~%k&`3%BH~##%-f<}xDU zyKVf+jorG93>fK$6~xGg1)UHJLiBUP37U<}-EKat)H-qKtO>A$t6uVhD?|DUq_AVT zMJrBbXq+HUEN}{@EM24}HBpS~(Q%VPLR8R~(B`;%-gO{g!IlMGfnvfH*^2QUYF*Pt zb$Ld35Kcd3GY)n-kjApT;2@Zs+^9NevRYEqMkY8WA2rQMA6N}SiK;(K-pv4JL@NxF zzf++}V;weH9Y?L*e#Sg<*5Nvc+Qd1&_QhC)jA^{ndl5|mLRk7BH3xB0OKO63bF5&^ z7%dEL9pRPJ!E0nm4;m{7o4l&)n+^oTE}QPJa^CfA#mF0y5&gjK&ro)%t1J55O)}$d z@^H>n2QF&Bd!!aFPu+ZLNPK81TA@}0hG9TAwVq%so>Lf4JDNj2nJ8F5%s?1!h~o+z z*E8O?NF>U`IZJp^75$mesJA>{t(LpBl?r{x?V4WFaXPW8?MvYk+;`UA0ID=%6cU9i z@=lC936-K{6>@qt5PqQPWFTkP=R4UaKsv!ryeLrnBNjD3@%AY7M=e@W4Xvo&Vpw@e zZkR|NP(h)WP!1=kh925==w;rM-mYnEU?w02l2`Y@fzS)A@FNJk+cS*wj%DpgZXH#s zj4*Qa?2)@l_$rJ}FhK^?3;2*T8(KOHFpo=w%vU*~Or_T*cc>tFpgxHV)Pl&|%@V%! zuP^4C?-$0|1h5R=^4`$P#QhjrBpIVs`&SQ$8H_&c)xJh;-wsW0E|dPmIc&!pfT+(* z(hNZt_5yDXlJ@x57_I$^7+_KNGhJT`BFTK13>PVC;VuqdI`>HSZ!w;3E(buAO)L0P-T|ult2J4XJ1=sLcR`JONnUtk7?9`PF8c^&eDfF!XaK(qO4t*H+>dxU67M&9a!)LCyy)!xM_ zo@m8%#7ov&Q9XX;Yj~ms(^TMP>n*6BhOWVh*2~0LEX+C5H+d=P#NFMg0mOhpF-ghc zq;xdoIJ5jasei)u#+e1*DKHFu01>Vww^5+3o~~YaMs5L_#%q*r6)SGOyOu%zVS0zXmcjjG zsurc|DI0R94PQ*HNAgxZ&TF}h=5ey2J&>dK?W#wDmX$|SrId)=YlvpM)42D8TA*ZQ z_@$Bw6vNYF#57D{UGLekI&5lGKLRX2BFJSoxp++xl%odk_)FIMI5hpxAqF0G;a6e$ zZy7OU?=5nWSaqRe972d(W0$;E{_*w8dId#-hR}nxOVl-D)SL#wc(sG}40_+}pjdPe zD~xlrkznB;YCuWkBz(Y^YiJpcsWqQlW@uFrj_A}hHvOU+6pamr(fB0h3SXH;)0QY$ zikEg3llGir3>Vv>IfCHwHRF;a(I{!o={aSeIfiD^)cT6^@-a}+FGuq4$Q3Ho+|z)} zMNjZpWx~*r9l8$dnj`9WE|-MBjcgG|MregVD@?&uAyTy5&4_WbID!i}+Od~M4$9g7 zxE#<5?Kdf;L|<$`nO)E{!{n;Z7RT{uf=g!^vW6KFXgX#~&{Sqx)bPcyP0I|Et9>~J zs&4|3-d}yosZ{hZ)|6af!B=Qg7u0GhHJ4ofig2Rq^1T5m}< zO;f@4oZP~wrqaqhN(q~$dd}8H+LWH}8MRHGzF9l@Eeld)Z(&OhW-xs&>QfkRb*A)L zQ}i<{DiNUlpCMkviZ*K-MH zIY*bgvg;I$4Thu-*9+Et$`ge;QC+nBgQOIEdL#`M~{<_eM7&AIUoiIgZGSgy_-Elgy~1qipu z-7|qP_$?7){0nK%wMcslk@8kf3mqA$x21XHZOwUvuXy^>cuT4TFRQXgu2|tKGj9V% zilv3LkozVR_Y{OfJ?uH=?9ixCvsQ=3rtt)m^4!=s+t89Xje$V>RnMid?s;2da%ss= zW@SjQ@&tSGJnyYq983hkDLqd#sFxV(;(GI$5T!uK*QU7Ix6`{*B;g{{Vs$uZL(~#X zo#4|d=J~$i+}=VlSaGId(Y6E_3BdT8lF4I3ecpo*sX)q&iD)5_$B4QXc)|9q<|XOO z3!=3(W=h9~(frQDalC+J3NLh4J6}jwhoQePpJ+mbVkm~*H4QhDUhEM8ES4ZIP7Ge$ z4~OBl2TA|H)Z}`1TN?xlL5GNtbR` zmnSg_)hK#uf$B+>my1ry<2S%W_Z%hj0+x8(!&h^X8$5xbN#%RKad=$w2U!G=e^TT4 zV!iX1bLV*)P+D#D>tQtLeQ^Th`;IY4^z@AhK|2E9UmgCGUK>HaSeAUB8DjC0eA%{- zVX)N{#Z3iqVYsfPgky)&-?p8ExX*?!QwS9FlKdwHjG~`U-eKV@HHLynEJn^~p^kzK z<0eSHdU`-4Ro$T(W4X{I;Q9K}rVSC{W^$RwOKU2wEgfI1LcV?)j%>VYOPE6RZV64$ zi(kr^6N0^OISZeX>rB@S79%fBRym1DLd`D@zWtP&?9!5VWzAa*+01z>Z++Be#8Uh$ zFrW9y6wAP!f_L}ibs0#*b(8yJv)e{&w!TP?WF#~B;*7|*oDogwl;qme4zOE2eyV{-kR&P)EhO9uL|q-E>t}BxiPqJD zI9d$yNU;LpN|lh$zm}}!J@9x9NfuN)GR{Uem3fVZaaeb8@$H1JIn(j>R6g&JehT3%^aQPEPIOAF^`jm}ofwj*arny2 zhdo;Q#)P2m3%%9uqx4$eg<=yG>K7VQsmJw!{gqF2LjVRA!N5ZIs>EBdb=<#ax-_SBE8&oQ;tS=rr}kYj>2A; z#_O-B$4lrMi%4Bj0M``o zh*Y&gX9NIHK(D_Ei11?W+AHH3;ju$IhoRlT7-SMRXcasov??7ljqDoHF(ieqjLIhj-*d1m-H0Ao%AFfLqm z046GyJPs}4lg>BbkVuqlL*tZJCLjOav7L$0|eRQZo>4V=M zMQu#aLg33hD_sMuRspFCjFaSLN=a0sTKWN4x2RWfO;?{-;j3fFppwpT6TbQi%phAd4HE8MlbNDz zFxsrMo=@2;Y-(Vz?dr|N2UfF`eLz!8!nwt4k`l>?t+4IFR=$jE#URso%fW;v87@YJ$Cr0 zqh`rVxNaLg(^3Ub8bM;Q~ERzeHxfc#gtm>N?S1XU_djGY1cvMXhF*t zJ8lYEX*$t+$?C<~M6P#QLY#^vnW>61QqXZm-<5o~6oSG=e%+NUC#3wXRwSzFke(&9 zC1uPtj&i5;b0>{Ynv(wxa$^_bL)ELhxvMeASYu3n@q1o}=qTR#n3h_o4=88RiUK~|dafKA}Zuw>9 z5;{Jp?CA0Lv_xc)C|BfI)PCEni=Y$mtti;%J z+Oet?Fi|j)l5%fr=q%X5h83`$WRu*#psy`cO&8d?7|^-xkXRv5&K4~(0ER}CJJ||! zG+n!DEmG7tAx*bD@lDm9HA1tTx*#|D#J1`yDTEqp&Xd&>a+Qv5_;RsJ%`NY!)ztD( zvc*h8Nk~O`9vdd3h2eH6?y_j%t$-QYwk0Cv$*Rp#iAD$^oQ^%|cn7~y^FCE4DS5_7 zokEHj(EK{$h?BqEa`Go9SI+;9@UcO-z~Y5#n3*|30Xj*JA^s(T&~Q7JgcpIJHXpT2 zN!1%mOK3wlk-&*9OO2p7v97C*DI@!eW7v2^G9GCIPGLM_lw9XNj7>YSsbcG`KdE~# z25zyX1D!%uIVD5+lw5vJ_n`3O!l7lb@H7(+zDl{*NZ-}8log)HS3mc2M{468o)$LW zsxX1Z1zPbY8n=KU&ntZA?RMLfd_$>;`xL77%F=9;COrPFxI7$pu)@$c0*O_nu&gQq zNOAe`ppEk)T@~+SAB|@*GK9omK3YVOZPGr?@PRRQ_|S0qrSc8TOst?FeilSJ*1Vj+Ib)>_=8+@;U<#oM8UWGm;sLPxUHLr@MJdvihQAEz&pn@$ftN`dIZD2V$uEPS*6|@`po?;g&3C*TTH+^;F z9h%j|E04iwx(`DzCJ`>8@~R{MxY(ct>5aNYp>m4^UCf?OZF37-;AXO_k{#&{zAeIW zd_+UXarosL{Lx0_t)Y2a*l>7axOl#DDe)1XJpWm^F2rUoE0{^U!}(Nh7?sWzbH9aU z2oQZwATC@5U$&B!eJk1IvYsUO){c!s{DB?N8Skt?f?3g)3%)|rII;zWJfx-vR`2b( zJisv80Ql&t5`anAgqkRZ!(eI!)(mb(3TqUi+@QK4L550^KL#=0&H`s{4%YUzM+M&Y z#t9ul459Ijjn!^I-!y1w<*2-+umq#b89MZeA*6@6x}LjCW4~@c>(KUOCFSIaLVGq@ zPJ&QHIU_9lvE8kXQ!3ITm>JZAnmU?g#z@;F2#6_zJjT zyz$sJiz^b4LZqL3kEEd>4K4egR@0=Ie~;B+As4iTDFI>HQHKZrR8)0Cvb73dsaoDB z!L_R1b;~oB54al1As>i76ZBR!5=yP=kw`&P(Q|>o&B2%g*JiK=l=E(?uF1=)7F;1r z5v;9$OZvs(u@j0@$S}2NdYxFw9?DI5M4?y6FMG~YJld2Zma&@QmL^Q;LKMDIV{uaG z#zzjw_VEha9#?RFB+N`;YPR=$8|M2n5N+!IeRXex710H&QUn&`G?f;zUsr*#Kpp2+ z)GCEpOhq;Hz~&CHl!c+a4WJ3uR7OmitU7M`uDRa;H$&P$)W9OpDYWwVvqX%eFbz^d zTNH-t=`=iMOg{q#1%(!Y> zXrw*Q9Ht!<075E&GQ;$)kvX2l8fEGj>j@_pIOYRtjo>_-Dj7xNn7QDXd1Tp0EHv_N zLJJ*792d>aBU8BtmOT#hG;d8?&qp+azQn2)p%66|s7a{qJvNjIhXAY42ll|xy^ z%43y}!IY(#B(%dFoiJgje13-uV?pP4Az81M>{8(lTF#riAh}xMIrcm(%oG_T7#FR; z9b-1)+CKD~s-KMIjBaa(t{k*b0`k_*zi_*jl@+UW35{d##$jSWFr%C3bWFA64x3pJ*XEIaDLNqJKp>|oa&#FvT16hG_cWhG z9=XVao2%PZAXn!Gvo{sPBz0V+&E3Q?bDK2GxrskTJ;3suI^OD$>1?WBu{MX7*{Luq z1YfRclif;%4scgu1YWRyaBK5CAW9MXR0`d!pk?SRrLf1;2uFee>?cxn>yNI(i3v)R zLnJnXf%pbB1_&t&nRdeR=M6dmY|e|_((>+351Q`XkBB77ltr0w>O7Od=&RmOeudiV zLsOH+2G3w?BcY3AtnXP?;-G@*2(xfBOPFS{$S5|I1vCWmjK{K}=LR@MO{Y5unh4Ou zeEhAK9vGq>lVaMoc_6%OZM!j3i4()|EmGT{Ic=a@JzJgWl*4CO0-#ys?PiwcXn8El zxU!QY6aUT73k|C^{~wnVd;oNDx}6n^ndgqUDWHGA)vm73o0<suZPe#Kb=3hkFxlAZf6cT*DFA{~aa(?D4$ZA&WMw4rD2JSKh+IQAe6^%(*uelA4It-Df1y&vf$ea$%Y{)j z`0@?2{~9rCPkgtlV7zRGlL0No;*AI)XN0_5^menVh)N6F5fEx&tmch5o;Z3R0P%{U zjdDQa1iF|`B+$Sdrzf6|%5w(hzCz_SY=h~HICtsHEO&FyFut{C`@Xra_OlKC=|V~i zrneHD6B-w2g^6}#XJPeRf>OgI9FLA4b1#Zj9K2g;2AtZvP21!`$44>>2At?{7Ls#O zp~=Zy99ZXm;Hy^E$!K7YXR+e=J|#(iGP8?ClOjj20%CdHA!-m3YN8lO{untLszO+4 zsFRpFWs10@R0&^&VR-oxX?7VoM`UKmM*lc#zO0i{Wf`#+pM~F5sCSnOwI}36AZvD} z{maPpW#k_SSu~_-5u3c?Tq5o4$fJ#9#7)!hX+}X<5FxQOKl2O|-Rp$qrQ+Z`@yQNi z9&7{k+$Ok$deTsf7H0I&&W!+4A0S2om|gA}oi=|1dq>#R6oKQb*zp_K@7}=1eh-{b zU}u+`S*PvZz&;Z;jj6y>$CSHPZqeF0FB#R?yS^Q=z1rsV+#0_4iTAXUL=@vCnGiJto8E3xB~X}&>fjlwPQzoD3A-qgFGqZ zbAXQlN=djqct9^sAZeGV2v$^GkFL=8d$d|2MRL@S&lz1f=WOxu*Dc0Smej0jHz^*2 zh@!NO*tB&jX4-Nn`-ZV(R6!c6cI-#2a7+!lwX zX-@}+>TVBEsS3^e05(lu7JJJ6%F)VysE+Bln;h>sl-MR4_n`dLAh~GZAJm&d1ke7Bmu{3P)qW_KNUsEdO|; znzGhf3B@5vUbxhsg{z6hp*4?u_FsNm^3j$1=rH|KgW1yGIDAVwM|>OR%H3IL@#&JC z>Eb_=M3l=ZK%!xk;po_XdVI^p@fep>s%F<4^|@ku91f>}W#z!foBY{D!`sn4bWY7(W~wmtO|RSy%fE><6Qta{JEyiKEFyO?)+|)GeS+zMgi_5}?&7PF+?EnIG@VsyX3;Ffq=uM2%Q$ zctcpRz%s4hnKZkhMGuT+`LF`{zzH%Jklg6IRmdaWgIwfrvXr4d|)r*4w#ayz5u#Qv14x+E_`Mega-Od%_ zX1H*e>aI9+&>HCo@>XtB{5`Tw5V%luF5IoF-X>X7Vfj7U8rtz?=tz-S2K$a1SNMc?Vb`R* zitybCg<*SPMxvESgt~DVS;KSFSkcx0=#y&C8fA0=7Ljh?6K&kN8COJ>k3kgqtFVG* zB@&Tt;1eH6f-s{PJNOv+WH(}sGF^v7q#O7w2$m~u-9ZdrZv#QH770K%Zb4gdw_s}1 z2L6bOnno}g)9O(5XPI0OUQPm_H=gKU&+!zc!H<4|SKaoqd6&inA>DWmxuy0zKT;lS z#eT9n)JB?>NJP3RM9u~Lo7*G9Rt^GuYWTl?`}+L%$JeLZ-@iTGQriExyHf*^@;`3S zgQV~tioY-8h_pJ8p!|=Un}68!zdUUo|MK$pr_FC)Uw(V~`ufM_?~k8t>+8+UR<@uEP1&MM_tT^n#X**P zQ1nHP><3odpwCu=>Sdkk#5(>1QhDD))iniD4n!G#4<$ZiD_Jq1(a|l*+S`D$g?8RG zjI^^|PF~#IsbM|42M7$`28F9akT^3YKR0BthM^Y7f-yOFJ6AcqnH!H2An^@4yd_Xy zs}r(zOPx>`0$(B8qq>rvtK-c!LQxw&lLd6yrR>!m*7BRgd!S-SYcv$vf5EhpJhA+G z2Mah_cG^a$EefB3L_H}8VtSI|QNIsF*#=J#P9-0aP(@UYKscuN__9MoB6Od3M%#Lr zmQ&WnlD7L%$~te_=Ez4!V;Io0jh#Rr9(W1|=~_}9oks}Tz&3(=hLa+8 z){DH5=w~hbM1o)sV&r+~0mb$I8z{p14@2_!zd>FBp-1f?Y|t#jk;LGIP?=@?hao33 z-_~eW*NhDS>=SSh>kUlD=CCgpB5Ik(0L5Ci{*HJOz<&!MN9 z$anyhA+#6j(4Nk_x)Nk@aXN>8k(!g5;sbDqF-Z<0Vpjq@x^IKeOy_HX4&U=$Ce^Xg zMpv$5^DEo)$d4K+ju`lK^kTVsv5?VUC>9J%zAtrfkHGym!N~~N=EN`MpvEG4Na)3d zu`sr1ht9{W(9>YS^++@=h$`YX2EGEd*r9kCT{Zo(4Q1j{v=W9EUx7Ma>l2fpAp%CZ zdP=Ue(J~13wrn2=g${DJv3SC&G`T_W-iAVc=VLFsy6_*Uwq$D%Sch78d|_k~z=BvE zPx!6|wf2CcEexn<4~VAttx_0}K{z=J5C>q${6s;Dc~PEjs0>osZq-_3&uhtzh z=i?|e>Um;^a|$~Z8B>ERz@xuR4;?P@6% z-npG~xkPt&YCwk6iupWcPLGL&Og|jh!}L-ELPn}ZVP&a;J!#vZ0pd!!T-!1_(1b6~*kGCjWIxFW zCBL+Q5D1`11@de_nHA`rz#&%6w1pp!ZB2^Ny|EsAFG?il3-e=xvq~hAnzj^b8+a@b zctNagn^in{CqlyTN*un{pdJ%zC=<_*l=_lxOf!I>2Fq|NaS+_Vu14aX4tY4EC-Csa zjVWo;%ENgzwx|jk%`94FURGK%Su`KDBY@ySqj_MX&NXZ)Ep;wM(X6o_7*#nDRZg@u z$Ft$;Rkp^?%f2w;0bkniCM76XAxe2=AD31$;(?Y%mg&N9C+#RF67f7ar}SbcmvgIw7WyVv1WiHDSiNf7%!P4@~3ehq}s7{MWK~&DydemxJiNtv^+HM7KVS!|u zYTO_I_QdXa*DK4c7Esg$gYK`4KD?Yrv}r1&?9?V@+sPGK z`>iCh#GMLmkw&I;r{k0dc3-_w8zs$HnMhP7db=`$`chr=6iQVD6G#(BtqK~K>FC}0 zN+nie$Kof6K+V+A=$ojrV>J_%9IF8X?l^gO7(6O`TxylG5**{mbsg$Em znLu$R4MfG7XeNldVLzZ4DvbMXM`OHmqmtirN@(_!HJlbT6okm2%cbJN031$-DwEAf zY=se*Z62=`L+?{d=u(833$VFAyXlNxkev=gHy)IWfMZpUAwVunwrn|5w?23cdFCG~ z$(Hb;g8iQshBKFLaqYKFW9kw%JiJz#fUaHf%Q3bZY8D4}oY};NrOiFp3vq7x#d+g! zBn?qY2-y_lU7)ij0`78iVY0-C;|Ab^BB$8~V9%-pX5)}_RJftKz1gbSn4+Kvw~54s z8?B9LrF`?jBFHAUIn;n8)IyA~A~sh5q#n+@a%e5pRwE9a_*@Z(0xU5YzeFQT8l+ph z5;t>yL>8l<$TaZ_Eq9hp%etf4J7$Dfo(g&y2VbeNfJh{A7g&R(WkZ;o*%pO)2FDL) z`807X+8jD{3Q3H&=O#y8NpafCW2LenU!XL{>zr@))t>E#YB|6}%bF01o79!~a0?qX zJck3=NT8dCT`IM-E3-w6YJuWph$p_Mu&59Q5X*5+>YS3egNRbqsd2*yIO!Un6g0B& zp^-;$;W3I!r!tFQLLyQe6G|ad9Re=s3*$0Yq@Fyo$OfW>$fCyoFo5(s7wk&K0CyWY z{|&VOFZ7)M0i6K;I~MHm%cuJHU;py-_2y2-CFLCx2cOnsV5W7 z4;ltk$rcYy`v-F5AqCK39*`#TmC*tqT!$>_8_bTBDdE#vM*hCX@tTW`WOhs2UZv!h zQc!)|ZM40vI0%Tz{kuE(OpNM>YW0z+sr4W8!_^f&b%4pBwU!Kk6oo^|HIB7mG2KIz;~Fb9rXDIL)z;;xbG#kx%t&QIKHHpn zdX@ysnapRDaLM1|!fUgPwz}|@nB|)dkSNN`YM>}x9%b}mHxk0_0uyX)kL6Ss4pQu~ zshbW;%N6uOyp4b_rgf$x&mg%&7IN_}2S9{#oFcW=wBuyfLaVACN~Kv*DvIL&N#@Z# z{r33v@%4rHhnp%>r<){AvX?o@n3yg%(k<#oBnjS<1d7v((ez4nNS(V#BCH%d!Ndd; zufU`>kW__m9e2HQlDu4`ZnB&vOV_0}A12FPt%6x$2k zw9IKKi(-4B!xjo9o0ZY${!b3R{^{$l&tK-zr?x|{_#YfE1;+8`8!5ZRJMQ7YmXyId zCXBL-kCvbzDWi3e1v)4S!E-v?nM^uJ+jMIdW47BgntB;iI%Z0FV%jb;u9YaHpN)~C6tWyZ526A%l zUFes-WEEa8wY<*GlR|vTO4vR}`GuP7%OhUtXoPLW55V<25-mL6=vOrPtaat+c<R_r>l2ltgvQ{ZK~_pR|J@ z@Fu=9!DiyX@h-6c{#F%9i7%=9*x6ako{lM2vG^($i}euvl8u-msky1-wGlZ$EG=)8 zmfs{0L(1eAgT^l_?{-r>4eom`baw#ahzmH z9{M)$45V>I4O2TR)&Uq&!jrAzQ7lzQ^D<{Cud9mEod}zMlQD~3DpI;IR*ov8i3r#X zTOQp{$cwRF969N;c-fD#$p^20Ve%E1zujMPfU?gY{^Qr5=ZjxP*05P1&n|XRW|Me{ zkt|wUNs8~QGK#Gw^l8BD301b!P|bJprEA&JZ43|K12K_sZCF2a+!&)RkM2@X zHT`uQC^^VXN*GkJ&UgvA# zA_jHP!aRs-yN+T%@(S0tr=|jtHwa?3h7?oufP@%0b>9Cuoj}hR=i<1bt0ivC6)NRQ z5yVD8RIlKr2%|RoC`b|qX1)oiITGOpffonMw1^{0kODQMdo?x115eZYcyZ|9ELs^2 z?N||1)B(rCBUqe0QCpkGxlqk$U5D(kCXv8}D^L0ttl%pw+`oVR@W(&QMI0E^705@_ zsq}9@fBOB)=TE;qW39ho-Rhyb71j+)T=*fk>Y^=&RyQosGfMk6N7!xpNITo~Z@6Z6 zcHQ@XO!+lBCR`Y2-o3yg{(|xCKmPrnAAkR1jjlmmzcgYy8r|Zdx&@7H{Yc%g{@X%_ z{|c7)@{eD?eEg~ZZCUV=?+tz;UU&^6YDZPUIfH%Q_8yw*OpBbn9{pR4d!qf&sH=gY6N{9m*FP= zM6~>-`b!G8zhJuBFCY{CbouySUp{~MjgGI7jwb1w)*5n=`&jYaD1$1=yKWF=1fKiA z8QPzt*aSk1=9^`WxPVcEK`u3V5TU@@+oJkM-4(~K&)oXcQP&T=YkH(SE|#nH{M@Kx zHYOIP9Gj?KuhPX}{Jm$majR>?9%D=KZZ1N2bp8uO)@*x(jMpAiUZ3F-UXscF0HA4c zXP|^9x^f0bh;q489e)SY!8fy%kyiIc)@^`0ApL(T!9;r$FY!)>^=r2Y#ShSP?2+Pwk>4E=2RmQJJ~XEav9fS^R+tcTtIg;dOTp30Ez-l(%u|XQlmuFT+saKXua@y(@2uy3*&vl~$_0Cbjw7Qe`uis{m`-J z*@>I1cI--+`Uj&M!b%en6)#e(gH~L|Fj;ljXx_C=iE$SJs#@9k7Swo=38pyC5P9rJ zwL5;EzTxnjQ|zCjd6_%~ah@!92p??b2>4=&$9cMTLLvaPK|ZY}7+>D30?gW}@fIEN zOGcW| z+z}h?r?7GaCf&8@WMY(~od<@ZZ1MESPzM2jYah{*>X1Ceq>!hpS4E21rpG`F6h>|7 z@Kp5&*n+4m?8ailPn$#Yz5qzRy9;?e;av=K&9k=^>OAv$MTWs(3MvOl3p@XE;S`S{ zr+5rI=YW-wBvihYf*mpKEtg>#Tmh<}7#T&qbw({y8vBZ=Srz|gy-==BFLP{}d;wv+ z2$yJg4}aZb7lXX<)3_hCB25}3Ns%+h&YlFhFtGVpr@dY*|LZ{ zGzF&^4yZ@okNZtGuzkPTqiG*N7R&PQA|&e(vV5>jMtO?yuWGY;uuUBj+6-fgMoHP+ zjmZ%vTq?TSKwb=l;MTn7gBEyA`vfa#cnXssSmq=pyD&0@6-JRw*(;tBX1kS3iO^Ei z7o0G?kY46 z+toI|rf2U9f1&V+r;*FX8Mo%AV%O&@xxBU|8gfuc466#U?^}K&`74gca)><|3SnO@tKG zvF2+Cjs6)(=^ucEQWMrSUzT{d@4wp8uB1$*NldY@41OsmJEH{Je-0bTaU&2(QDy7i+a zPD++ITOXU8P7Ha)Em_A2X17eQnmt2F!~CnjCszDF6OW~$SVBaL!ceJdov1n511Xa% zki|N=@KKW*S(;R3!~q8Z?i+HokXa@{c%Y}rkf36pG)W_b9+3#EMp+H~rWj8r8o(rd zl^#|&?tC{kC$ybPvezkDE$AGnPeY4(VF#>MwxLAEmvE)#?$KFdkEY9ttDJ85iV-be zxilTLW(x=~@rsJ^WyG61zV1TBWLe`osfW~bVSQTBDR+8^=HlW`YlaZSPEJg6mOY|X zMXzql%VE4vQ^$NN-#vD6tLT+b!y2^eKYpRvMPqE7zEoA z*v{875IkNnQlf;f8Qh322i{+0>*sUgpYPthsae@KaC4rBO=yj& zkZPK$B>mCKigkHLX}=%OXPF>H(xxS?nNx28%9YFewQFI64mT-Pg-NmUjw4!`-ZQa! zNi(1NcV`O6_ zMT4}F0!W&)t#{I7f2Fbk-L1?L^0$h@9d&2toi}7cFASOz8c!+32@WH4pa7W?yt~5z ze!OZrRoZ=MiwOta3{4%_6+Q)<)w-T{LKgYv2S>&aD8||89Qh6dw)i1xJb(!illq9U8?3wbEcE+o zT+DJrm%V}x9WEy_+)bD3V`7t`t-N{G5ZlVjt-V^UHG*MWqp+-;+kL1L^1j)>XM1;I z)We+zaY;vmdE?d>wRxvmU)(FrRJ3!eaD6^?1oLd_rHCqeXfAE2c$qWL184&!4^5a2 zMO>zieRHL_jNMaF`f_N784m{2i{S9KTBocl?n)8nh7?8r%^U03LLUV}R$KG@LlkE} zQuG0IPk8g@JwAFXH}^e8IxR3(a|1#|OoCY)xPl8_ARBh(!*mM4s#nKc9Ne?LDS30k z*E6Vk*X~BE%kH41#AsNtxQBGAiF`N?9Ss_Kq!#Tk!1k6@bZB#F7PTGbWQtj4xKbj8r zxJ@fs{M=o)nE=x$m{zSnLkJ+_xO|hyc_ztW69^tRbnMFCH{%)lAQaH}xKweF^SQEX z><=JjU^#RvA(1^vm~XkYr5X?XuPFsyc@*~FQIZkxHn+uK921pzL^Jd^liiph-J*n} z7?{+KOdUlwG8wksPG&QIe2P-ys%c@}ReuP#F*2R+(b@3@wqK8NH_%vO((l47oS=*L zHdQhG0d=ur&mv}F1s3nZGHZgd!goNHuU&Ee%oznlC6oJT_{;DfZOfpzxYF7_hbXw4 zuT`5efnH38;2B~^308vkx*bE!XIj%3)UIf>{ZWF@-kdQD-I2gE6HG2jQI>IgigD=* zf_oJfykj?vXFB%iqJ&{qCZEJCtJmzA5CHZ|cU9GMYLq!_Aj9l+c&q7eKw&9NY%p31 zZ8<@X7#l!>h9yy+<<8=yAblMm*z<|Csf#xpr${zj61rj1Xy)097$6&WI31j+41)t8 z_=;#C!5w9i0nhF>U!T}8aJ+P`5>nhHWJa`3Qu)w`ES$gwrs}c5c?8wU8wJcLigkAt z_XfUtnKXg#0R_H}Fb}?lKu=He@T(~EVTxA7uQ~Cl|Fkp^#mgiKM3T4M$CNy_+YH-c z13~)Wep|+XGE%;a?PD^g_%4@y!G_Jk(MX5zVjWHOHiwso26rg<|?5-Mo0S@(oG9r~BM^Yqw%+g9KyXI13K+)SAjp>A;=XQ1ZsA?LH zp?7#dngY(Qt{&D`U?OUOyQ$X_aX?L{GO@}+qzI1OO9cRnpi7+fgZ^-% zMCl0;tgYsXI@W@MS{07j0fhvfeRX{AInEm;Tt3=yf6%TOMUoQsZ2gJN5pp!t);GkN z6VB476;|H8~}fjMNH+wOV*8Fx?HWTJu7p5sC2L#7{^Xh$|Q!#L@Q(1ca5AbGW?9<~zQ zGiuhsCU(Mu_^wU!0$_5dK_9sqczWONcojaQQQi8iQaje5Ass$IcGvdAj1iS+G0|Fo zZTrR=#@(G>nQ$6C>|TEsAy?uk$esw%4(pb8$ddr=x#@eWnY)JGE3mj9c$hhZ4a|#I z4RAO#cP)hr#Wch|g(Dyf^JNbgd1$xAsrhc?%DDw#wnV_rw}&QkJeu#WEg1UVV(LQd z!KFMP{ECC4G*%X}>g2!=Fe~#S*t^s#Vc#g87{J_{A9O>&ht%tV-jwGdzHf)W3@T>F z%dIp*wWJJIX~9o;Jn|^GL%l9d7-rTy3h$A>0=uGc#)}IzO(q3%pQ9DsGQw!S*c#A^ z8d=`Aylt&0j}5B{8!o$d|AQ0ah28qis6*vpAJ!mzp({znmY;+dbxA|DW-W?cOf0ZRg`eey~_@XHj8NS6`Ns&+h$XMj(Fy9{t* zd`WmW9!;eJ&+#OB$RlUPt%hTEX82n>gNk=W=)Tyww4lZ-8nvSM(_Jv9wk3OUGS=m( z*G5i6Lb$SFxM|vXQB1<8Q$f7%$nS_fBJ7Fp{2v-Th*a`8WzftA@h;5YIcXvyEA-ui zx*BB;$kVTKQJKN>uV`FO=!|6hH8eO_cI&*DHj?Wg!Be)*k7ZO0$3KFvg=o^P$$V{= zclq*iv(@q*bfgbT48dJDY0NoWzCD8AR0*9uzjB7gVR{+60tT{(;;s$lc4uNJ52QLb zik{(`bUk4-3`%h}pb$m5lA^k@%+=uPjTuWp0Q$a}5QwCnW?6k22Sh{f2({~Fi|+_} zShY%Xs+j%56xZ<&fUBGhr*dX5s z5)ossSM{H^*rrF!vL!J%+Uc9>beti@ zvDXz)S-TiJN9Xex&PYU=6{&AIsy!x~ewFsg92-D$_y<-l;gQ*w9i^jZ2#6i8H%}~%AE#6)nqOnjMa>pVbmB=Wd2$^vs^bfbYARciZ78~%lZWKh1tKFcd(kGyhNP2+tql+>5vcqbw0K;W{mGMo;D3fmvZb_ zL6jB`Q7Xvko9`V;Mb`5;Dv8F@>)j{WQ6dBpHN5f?H`(A$$GW#$-q!#vz((fm6MWTyQau4OC>Fa)p} zy=;<}-(kKQAtmE~nm1dP7+FVtTNcvs#!;C@j52yFkzu=a|^W~zN< zHxAt4iRE~0VY#75rm%pRr_+g+cxXtFr!a=M=CZkZgDQ&1h$=qdGj!xUg-C=J!<<^I zoye9uw?$M`>1s-U7{cX%vn-FOe^KZ=4{ThRjRM0#0*9aCI=U@twNCUncY*bgd#r^P z!#N_D8(Elbqb<<7jSBBhyq(&i*<4^nHxw67#)x_j(ZOZmTLMTi2_yW?eY&yhf$jU} zE1TlhU^Zfzc3gcTxkD)>4y<}&MTR-;i>!ELOofaM(waMvQiz6cPjykoZ{E~J75VPH zG7{gE81^kYofrr@&+Nq56cTVw=6hndLjzFH9Xp)a;i<0T6*D34qCG{g+0SX%+aok{+*um|Ls&JMy0RN8g@4}V9i8?s!2Zg>7W8-bbt;QHM zR&KE|&*`$g+ZmWz=AWS+i_as~WVZ`7gdwYHm)8?Rwc(4V$NXH-gqq}w{4dVWo(1v# zJuVkoH%~REY@WWivs?tLfT>i;mOF8HOe{!p^*gmphF^Q%*Z!P>Hmssrzbyjl6&>Rp z)XSI2V<~X&RwVm%+**_{VV!~-gZr*649;K!gD3Gg`^I%*q5H-aZJGoFzHeQ|4#M5H z5xAh>0L1JYDP6`~d>hG&nlnIMek0LqxT|j?+p9YTwEP=MUcy^{8@V>VB=|-;9faXG zZY@(^TYKLiU$?g$jPYM_p1Ej~zvL`)@nWV#o@732jGp)GO!}3{Luo2O&~M~(mbwxU zek-GMG47~$URympzR-S11{|DR(CDn0!Vm&^EqZ8RO!ltxG*wxUXKte zxd%08tby7Y5}0~}jEdS;$Usr(+y`s#qpX<`TA3Bpt52^gYM67Wcor^CsFrF;7ATDfz$FBo`4Si@^360xa%#2M zg8;w1w*>9{LI6|TgE2E6)ipk=!e4JTsyR!Z8-#iOX1x{wvW!sX>nODW)C%XURe)jT zwP*%$*Lc15_BsQ4)_EPQWU|tzoTj>7v-#7K63)D$#sq!v*PGo+@0Gbg<}Yr>E5KGG z&L~(Paf=6;X&3c1u_o$S18?(tZ&Z4BK%AAk8k63hGq=%|99dd79i0|Hu4K#7x;h;v zbrL+%l#xNJuG7Z{)MABox)S_n1~s#40n{r-(`k`E(xNb`gWC1OU2{Dk>pBY_C)5kS za=PQ|n}F9(crAZvovqlv&Cp)Cwa!)yN@rNVh+5MLQD@$;_kOaaYG?lFdxNWM9z8O7 zQ)Vv!h#y(cGHVx9U$LZ_t81y!0A#xiGIs|BN)_Zst!4z?Q5tdA0VnyHfx1~Rg+KUX8)<5S^F+v!i~xUc|9 zWSR~!vW9vT{0$$YrnvvOM6L(%Iy8`*jh^JpsRQRcbQt|}@S$*XzF>k8z@Lg{wpKQm zWXcR6y>8|NkeDFJNSP+n#{-rfA=~aOO?R%4-6$HFj;Om8ClUTn=JY{47`hdI3X7;I zUBUY~Z1GH`BxlA_F75*v>KDU*w@o!c?8KO(xqv}Gx~#OQRqpxs1H1Gp_-zkoxH5eJ zIL!cHp+VtXHL!8h9a;d{X_59F73iVmFma8uLIAFaX`~B0PHmkvoP=mkw_!yA$9`j2 zp0IAuX{^ZpnqFX0mD*9nFUFTjYHe0>;k2)<*OvMCG$G){&eJP?eK zY8ZJD9}pV#s!mUSP7$pCcBDATVVF@yclaq?gKR6MjIiicF>CZ>E-K3NOVge7y2{-~ zg}DjC8l!#UPw5VrNY_L*)fawJ37nlKl|YR3!3 zCkKQzBfNF#z83WtcATSzUE0}8GAt`W564i58a)X{DJ@PdoJeg6jSbJS5&mv+%oO<* zo)7~OKs&*(K*n1}$MzHqT#|6&~Te3+v`YSQ=KpG z8bVeF%OTrjj6=GVx*_STJT74sq9lMn%smMy{2Q9>N?%ccl|kg@LQ2;Icp@6%DoU)y zmSu{UziSa}I*$cBzGI8e%>_fF+xa=@`7csiV#Y3kG~H^`69_> zwWib|_zy%2IQC`)OpBC2^8>>W{^|EOu-5P{v*NI;Ir!au+=_D^EQbxna5Y|*$ zRA0ay)vF1^g@R6s7IlbbQTS840T`qs_qmi8iODo{JktdY&vZn=s>KG+tUuzt;5fG! zkt7N~si#FWROZUTMx0_J#!z*NONMFZ!~t2yH8TaZG=$;2l_!#m*%|IA9VVEI>q1no zEfX+UmHgbkZDvETx*6VI83<4q5$AU0&*3u&Xx4q~blFg13mm0>ieezyttZFJDeYv`YOoB&P!O=NEd}UP(Mq~=Q>)IcXza$yonU`Klwt#J zx49b%U5^DiqZj%&khqH}n2%OZ%LxPg=q5Wb*TyDyqDkZw2In?<;hPmLgb*5XQluzS zG`~zabO3K5&=;OnAV8-p+ms^)V>Qe%Y~0K?bG{QmTnhYU_+Z)5RrC-KDnuWRH>U6qvBT%EcJrnAPU@gJF$^iYAlK$Via~1-xto*sFLOK zJ~m~2Q}<5bAZTTLsvBhWOsq7PS<{a9=YA zm|ejzmNq6U;F!3q8;25)LADhjTjoZ_zqQXdOr`{LP@o|+R^wE=v~F4{DjPZw@bLPI zox{`su#R|l?JyA}f^1jx*bVFlGVvEjB@>xkSyj6C=(Z~v@@q04M`ys|L?9LAk!75@ zYrDTvTu+Qf)AaaijUm|3qX_E@uzKtAjas}uoZ7K6R_1l=54cATq%x`tu_OwN)~Cy@ zNv^aGLeDthEm)>s5D7cPE1r?BKpLK_Is}hxV0dEqu@wtDm1k!iqaH5V^^|FaoBefjX)=I2kpeBAu;>DS-C{P}-3 z*%q$(@af-Q`F{vg{QAqUKb60I`18+yFFyU(@4tNb{69ZkKK|F2&mVq!dJ5C}gu>W~}DRHD}%BJ6Hu;`jMw7 z2q^n$P}y)Oi%S`tUg^I2b^lBxSg$iH|z(n!YKf0DwW3 zx-|bT|NU>DKmPgg^M8N*74h5z>Zr{916$A`}!e*W_D^E1}P$*~GK%uvluhbVL0wb8n? z&joP6qjYwxDOdpf-P(Pp)jahb>tWM+0jy{E%L%-8z+LL0u1h`q-`}3XqNMvX{KVFn zio`b^8d6kr*s($Reu(?l6@&%50*G7vz^|y0%wy6>=FGyobu^L%-(!SUj_Pac6TUx) z08N+|yQagb7T1=w9*5p8hoaAsKomWKDDonT1fp0ViXTA~dlAI~Q6dl}k046Ch!TM) z6^PPD5T#y3sX&woMA;*VGB2V`Aj$=z{1HUC7f~({Z3Uw3BZ#(ML|cJqClKu(LA3KC z+6hEVAYzXoVqQc{ASwi+;t@oJ7f~S)l>$-u2%^%9s1%4Qfr#T-Y9WekM3q7`aVP@& z+Y|nTi=6R@c7il_(}UY z8Mz}D{b&NbT|-5#uHyQoqoQJQ^^v&pNBi*|+VuAD1DCs}AVWPD z{AJEa;#FEcsE|&&M;iuoaBPK(es0A1llC96tznDe=ZL^pX@YaXGMQWMG- zCqxKCf9%JOSzRX3o^u>hywe96PuvDGUxP~jEgl`*?`Kw3IGQ{sv|I0Talvl<;KO!l zTci;a`oZ7IMV3s+`1v~AHn@p8iU}yA6dE|O7@y>xg4_(GWX+Pyyyl%Hc0B+%zM}U;zHqyWQ@i@YOD5pnJaXXQPOyilb4Y@DuN_;+K)kj#`&riGWxGe&wtlf}C3Foe%+oTk3) zIoV@Q4i3R~hr4gPtG$CMx5O1jahNs;DXwVq$}l5hA8%0+7;IJ6QGKB&zI|M?u5Xrh zv*gV60TFXN)OUe%G||;x!m1SW?0lB|_05}#zk{8yhk=ySd>Q+93_1ADbS{KZ$Aj8n6+4O?NpIemU#Jj}t?nNaM9vAL-NTYQ?VFS0EglhBPROHm-k~`7kTi*MknF)&uQP=DS^_8V&Y(aEk?j8;&Sx zRg~NHZt1JSkCGO}>V`MFG)+G3c($~;5`W>fX*lwnmya4IBaE-5vJ{fn79uSBSef4`ESB5OgkYmXN4AXxv-cegtlrY zEcRk9X)%`zi`k_|Tg@vUVL6wp;^C29E+Ce87*V-;_84$#mNEPz{H?rQP!Re&j1+r( zMl_8oG5m6Y;d?M?qp|iChJ(B=;ICgQIHQJ(q2gzC3*d#(tf-G%6{Fl!#pNSS7@1E* z|6T0p%zT=@Lkq;hs|6N5Lz`^eTduS6YL%7SgezKT;Z_R^ceTya9hzvqR+n$zT;RIx zTfSAv9))A4=M#g29XnG|XR5@n=8#YtsYgD59MJU7R}2F8=FMW2D`TP#Hj+I+nueij z_Dn~>QhmAbu<=KgEp!yMQJefN`MCA z3&LOS9U26p$f4LQKME`}e;ep9^1V854Jvw4q;r;hWl0Ppv0x9J8Z2-rP}Vd&ZB`FiMJ zvD7*8tUBkemNuD3$QA-*F%@)gc@H8ulC|kz!fJf*gujXRs^h^p1y^ro%tR(`xC+z6UaG8pV<+8!;djl{bb4opPkM6{6eae$BK38w)ZisuW^Q<5uG1h+9Xh(%&Mr zn7lQp-G%=H`VcOHUT$m!aov2+t7nS&graR-W)DoZG;q1H>dZF#ilJw2gjSIKI z!7!ciL^F1#r*s?vRU8qj+928M&_cS!7Si2n3k#>}%2)IjPw7oO^NZt4q_q=ymz568 zwa|?$$jQYzPaa(adtNZ$>K$KN4@VFe4jYdC+pG7q1^Rl7q%+L}BB2-r+w9R%CIoyE z0~adPWTAIM{M7?Q&VXe*Udjd|e_apg$tGethr#XdC11Fxv3P3NJ2V4AAXCk&*n7}v5a)61 z0cdFPaMQ{QGzT~f-kMj{W6iSxfJ#Q@!sr9G4g9L+*?dwkDi}+iB6(2y869p z6nX?(ThqDSM}rO)fQ4Akc8T>&Sme2kFAwzmP_WZjF`ZnyhKP_N>Onhf_Yk!WWmmX-dS zrw3FgUtdzn+9+gX;!Vy-HVX^-}bo;s~t{PmZRQC(t)91&@#n=ZbEaz_sjDAV1a*2yW zoj8wG;)}9I(7P}^gXHl{ae@?iN>0 z61!1s-qQ$pN(}ICen1N`bmT4KH7&ad)4}D9~@Z3}b~c z#92NsRUa zh<)MAYnvCW3PneQ@COcpMS^meB9+ z&}+b+g^ke?W3A&<%$8|Hp@j>hIML=WW54D}g2}yoneb@OFBnh?F;spr?HvdJ z;x>sxgLh3#2{jj9fvq18geIY=P#$Z_35`^Ay&XI8?{ia8Vm_3#n!!X2{8s!6Z6wZ3 z*I)v@$x&HCU;wFzn%#P(60O;HP0uh!nbnr@4TL^2%u;b;&~Le1T|XLgEB?U0AJs((P>)!K@jmG!+e{O|3zPquX}=VJ*n3m zJJ%?`i1=#rcTDBEqg0-Lo$*ZMLs>o7sxRdCWLZ`}w6dpBdiVYek{HX-1`hs4cUJW5 z@WU^r(~Wlyl;@7+p92jg)LiAgLoH9{2vQS#0Xd`bPx_Q3Fx#P%V&=2QUR_MMEgo1* zm`<^#A*;g$spUNCH#K@bI=0_kDoiHo{W^?C%<&0(h;4&t)mK8xohP0x;6Nkg1wdx6 zf;^z$HV|O(D!@r!!pP(w{`&P(2Bc|cu=I%|&hmBC$b`LI>rhEq1Q*<=dImSJ{xEdR zl5nkZ-By5YkwdYqJLNxM1SRc!oo%u8cwycOg8X+Fxbc8g*Y&F{>fvV1b`gk$@VD}c znBp;HvS%JSn!m^*DVm&aY;!%e*8}u(hwt@lmxf*~ZO7lDrpMHo$U;kA?En{Ey5O&0 z+I$N=H}714We@XUeh~L9wkzV5!7)KfUVBi$wMk7U zl&0Wsy^ccwh{(&bNHcl?G-dcm?2iEruWkw+D zrAh?fv%PyLHG<`bLuK<(cmX;3)V$YCH3CjLWB4gOV{+r~o2t>)zVOi(lkI#Iey<8I zMaBc$ja_oLt()9lq- zvNx-@sn0{SyXBX7@OqQb$;l zpemKCKMeBVv1YLs(r;ykjj4H&6~?|7JI&7+gd_Nz%VMQcOYPLu&NlQZ?2U97DiYg~ zH4}Hx2doej7nzTX2^jP0>K3926=2v2M9k}s&v){6Fl3C4I5Hb2D;ZM1$J{2y5^1L+A zscjf1D<_G9FrD`RD5Dh-XQk(j&j@No;C>~W`L%DpN5r`pHTP^veTbFJ?n5iTU8$3W z7_Bn!2r$EV8lMNa@0{G=6pP<Aq-jBD(!wW#_f1tD9QQ^~spi~>xJrSt@(B(S*dsXT zU$l;ixEVmx8-!jsb+i&xRcln~YkYbU@poDKj{H80X{lwg?`*=97q*Y6RYY4V zi>oyQV$YG7#WXls5_nCUD@$C~aC8-!bXNimE7r7)$IjC-tL}jqcO(QUL>4`Ftx>ei zqs!eLG&Iyj{t&Th=JRlcQg&$9Y%%1!$nRvsG@1CZCsCB0msae?x z0cqzIkgDb#?>7vy8JcZltbXg0DR=GG#8@46I^%aq{1}8uK3Q+Uk5BP*q11)GU|I`b z4F0)8rvv;cJR`G!fG?sZ#cBu!6nE7aWl~++4zIpIgGc z6S#d#Xbo6*E?uan2Yi4g1Z!sT_K{wQ*QIv? zri_vUhisR5%;FTFJyXK3aYpP+(QYe{?tBt}1hV9D4VyNAMHbvw7uZ8ZQFQRfColUH zAl$0~nFY!s%U(sr6lf|8OG>JTwy>W2VR2y15pMbR>xj2}5{?P$R$#3>>&gqwb*%P$ zl{*@+lI34)A>cvPQz;pHl+}v%Odu^bvQty z7ZpuRkqS)N3MT7BG>XmBu!?D?SFvxWqZc4%JKeXJ%28-9e$@3iRm|43iVGMxL6(BB z%G=K+!kQJrT0%?WO_ikHsa--lI%w4iSgkQx6Q*OB&X|BGUl;s%RZHXLEruO&hlPT< zEqtU?yxOH}5#4l9doNYH{87-U@4TjSlh=uNj*i%SJFb9Rip#JTy0+S@Ydf+RU#Pyh zSnEbDG@W(qdo?Bq>p|Bl(id;NrdYE9Idvn6?m*~DpgLuDYU=`JoUD<<_qXeSPicpS zckTXkyTVb~bRDK$o${WZZiEIe32~C9p0_J68kLT*f?3}Kzhh`ta;3zC!<#pcfINj6 zEE8xp3!|OK(0Y$a$@iNhCXKcEjOUvn3S{E-Bcr^WzSx#Cw8a+PZ^NNI!IcQ}nlsA( z2tSF}1FY|X7v1r|SBgSO# z9wac3AgqcUo`mq+vGQDEOo^1`loBc1`8@6yUHdwIZci;*8r`iE zQ{tt9TG>WE{nZi%<@>T&;nY&}@axx#vYq1}(v2nlvo$SU9Z zUT);&vMKQWWwAbQX0 ztq?*3T;xiJpKSfP?!+*J#Go0&y&sL`)kmaR8) z;N6IAU`7P^iNaU*qo)KiYc*~#ZrDN;ix!gAXH^gUoq-bP7Wy|K_DnRgZky<7q+M^M zCJ#&=Z0lF~7#V*2#SKp5ZtQyy%APfU9>5#YnFK$+WpueU?8q^&zz7G=$fb-y=GHK4 zYo9^D;}KhXLTv{rdjN}5M%)O52Fdv2vu=E0m+~MbjA6XKd7~E`fg@m-5`iJ{Vz@A1 zSLji#6qo1mfC7V4-jBn00BkAVvGAw%#W6l@=!}+_(7;S9XpRjCGCbq)x>@$Eos9Ug zcJ^3peAj^5L|x{k&ZvD8X5-Vp(I1^>b^2IiEy$8wq)LV#-&#TU448xF$d03KbSSOC z2F@=%8jY{kQZ8%I*e*e3Is7nRhM)?glESsDmXbdwQ!`O4Zb!ga0!o<{T4VD=glV^Z zrqsFD!a7Q`g#=?!kmY|tf-&~_!+-qx^G~ObU%q_&{PYxLfnm%Jt4XG$)-o$~?1mK! zx8l#LV!b~o`z)+lIaRNpOq>-yOwQ?AgDfoW!k|xN3GyIitty@BQw}~eA(V)!oP`yo zxvFjaC=jW1N0(~T*06fMS6X%X;k%LdS}K?Q2Qc?|Ng19c{}4$zAoCb24?kFx$RaOa-Sg<&TUh z1~A0_O_qP}?2+iy8k?&?6O`^Ct4pVe*lwaf07I3T7Ds2jB)LE&}zU?|liv8Q`jyIgR{IR97@~m9t_f@QaOZP!suISHKu1Iw@f8$CS<8VwzIBN>5S|; zUdmwHLQnDo6&r6CP&P!Gpr2mkDXo3mzP)xkB?+o%i<=2i= zQ2WiLA@xtmN@o)*5k&{To><8b?Ww}IB7mv{F|{?0u}MsgSuLBNrerIS}=ZO1F|pf%3|rrd6a zp*>UP1A894UvL73+vIhP$RoZu7bXgzh8Q9N)kINjQ4~59%{@{&qLmrLpHI6pa9Mt4Vr?T6op!kK1$Y_ZO9@|CTU$E!7Iv z=~lenz)^NU%aih&?pLfL=;EuO=|+z5hE>RYc#M(=JW@@3l79`f?0B;K8sM8)G)eI_ zz#z^LFfnPK)Qcj957;=LeHG-8ree3H5AHSz+_P#Gxm=HF@-_XY!y#Z^0txAQKauJvhOb3VI-w!6HMQtEiooy>6ao1d^$e z-39!x$M}{8&+gKAl*2%;TRe{z)f5Zxc=5Z}h8*f#u-`m?Z8ugJu+|Z|u5)pQXj=fXcUXepB3LvtA z%xYo?@fGkNA2%QV+gh{ z-#>lX{PydgUq1e_`Nzl4AK&;N6T>_X|ANQF)5rh!<)`7(Pu;J7|Hqe~+W-Fe`SY*8 ze0+L}Wb9S72Ton9Yr)Y%?RjXQMbsyZW!p6sUwHTYE9eyT0ii^&L8lQ|t2-HV5`9Q0 zg|PY;&}oh*|L1>v{N+1%??=H|>d%QOGKPi6h<=Rd#v)PMQ>>G!`IL>likb#D+^ nH(fta5U5#a|1VsdI+;6jaW-p<^8reETR;7O5P2Ysd8GmX#r_TQ literal 0 HcmV?d00001 diff --git a/data/unicode/LICENSE.txt b/data/unicode/LICENSE.txt new file mode 100644 index 000000000..56da58912 --- /dev/null +++ b/data/unicode/LICENSE.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/scripts/generate-direction-data.py b/scripts/generate-direction-data.py new file mode 100644 index 000000000..b3127762b --- /dev/null +++ b/scripts/generate-direction-data.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Regenerate both first-strong lookup tables from the pinned Unicode database.""" +import argparse +import gzip +import hashlib +from pathlib import Path +import re +import sys + +ROOT = Path(__file__).resolve().parents[1] +VERSION = "17.0.0" +SOURCE = ROOT / "data/unicode" / f"DerivedBidiClass-{VERSION}.txt.gz" +SHA256 = "4867b4b7f0731ed1bfcd34cc6251211ff1542541fce0734b6fbda139ee80b3a4" +CODE_POINTS = 0x110000 +ENTRY = r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*([A-Za-z_]+)" + + +def direction(name): + if name in ("L", "Left_To_Right"): + return 1 + if name in ("R", "AL", "Right_To_Left", "Arabic_Letter"): + return 2 + return 0 + + +def classes(): + source = gzip.decompress(SOURCE.read_bytes()) + if hashlib.sha256(source).hexdigest() != SHA256: + raise ValueError("Pinned Unicode source hash mismatch") + text = source.decode("utf-8") + result = bytearray([1]) * CODE_POINTS + # Unicode's missing defaults apply before any explicit class assignment. + for pattern in (r"^# @missing:\s*" + ENTRY, r"^" + ENTRY): + for match in re.finditer(pattern, text, re.MULTILINE): + start = int(match[1], 16) + end = int(match[2] or match[1], 16) + result[start:end + 1] = bytes([direction(match[3])]) * (end - start + 1) + return result + + +def ranges(values): + result = [] + start = 0 + for end in range(1, len(values) + 1): + if end < len(values) and values[start] == values[end]: + continue + if values[start] != 1: + result.append((start, end - 1, "rtl" if values[start] == 2 else "")) + start = end + return result + + +def outputs(values): + header = (f"// Generated by scripts/generate-direction-data.py; Unicode {VERSION}.\n" + f"// DerivedBidiClass SHA-256: {SHA256}\n" + "// Unicode data license: data/unicode/LICENSE.txt.\n") + rows = ranges(values) + javascript = ".pragma library\n\n" + header + "var RANGES = [\n" + javascript += ",\n".join(f' [0x{start:X}, 0x{end:X}, "{value}"]' for start, end, value in rows) + javascript += "\n]\n" + rust = header + "pub(super) const RANGES: &[(u32, u32, &str)] = &[\n" + rust += "".join(f' (0x{start:X}, 0x{end:X}, "{value}"),\n' for start, end, value in rows) + rust += "];\n" + return {ROOT / "ui/message/DirectionData.js": javascript, + ROOT / "src/message/direction/data.rs": rust} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--check", action="store_true", help="verify checked-in tables without writing") + mode.add_argument("--classes", action="store_true", help="emit one class byte per code point for exhaustive tests") + args = parser.parse_args() + values = classes() + if args.classes: + sys.stdout.buffer.write(values) + return + for path, content in outputs(values).items(): + if args.check: + if not path.exists() or path.read_text() != content: + raise SystemExit("Generated direction table differs: " + str(path.relative_to(ROOT))) + continue + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/src/message/direction.rs b/src/message/direction.rs index bf62d7f2f..77d5b8f28 100644 --- a/src/message/direction.rs +++ b/src/message/direction.rs @@ -1,6 +1,7 @@ //! Mail direction rules shared by summaries, rendering and outgoing MIME. use regex::Regex; use std::sync::LazyLock; +mod data; pub const AUTO: &str = "Auto"; pub const LTR: &str = "ltr"; pub const RTL: &str = "rtl"; @@ -17,55 +18,17 @@ pub fn forced(mode: &str) -> &'static str { _ => "", } } -fn neutral(code: u32) -> bool { - (code <= 0x0040) - || (0x005B..=0x0060).contains(&code) - || (0x007B..=0x00BF).contains(&code) - || (code == 0x00D7 || code == 0x00F7) - || (0x0600..=0x0605).contains(&code) - || (0x0660..=0x066C).contains(&code) - || (code == 0x06DD || code == 0x08E2) - || (0x06F0..=0x06F9).contains(&code) - || (0x10E60..=0x10E7E).contains(&code) - || (0x0300..=0x036F).contains(&code) - || (0x2000..=0x2BFF).contains(&code) - || (0x2E00..=0x2E7F).contains(&code) - || (0x3000..=0x303F).contains(&code) - || (0xFE00..=0xFE0F).contains(&code) - || (0xFF01..=0xFF20).contains(&code) - || (0xFF3B..=0xFF40).contains(&code) - || (0xFF5B..=0xFF65).contains(&code) - || (code == 0xFEFF) - || (0x1F000..=0x1F0FF).contains(&code) - || (0x1F1E6..=0x1F1FF).contains(&code) - || (0x1F300..=0x1FAFF).contains(&code) -} pub fn direction_of_code(code: u32) -> &'static str { - if code == 0x200f || code == 0x061c { - RTL - } else if code == 0x200e { - LTR - } else if neutral(code) { - "" - } else if [ - (0x0590, 0x05FF), - (0x0600, 0x07BF), - (0x07C0, 0x085F), - (0x0860, 0x08FF), - (0xFB1D, 0xFB4F), - (0xFB50, 0xFDFF), - (0xFE70, 0xFEFC), - (0x10800, 0x10CFF), - (0x10D00, 0x10FFF), - (0x1E800, 0x1EFFF), - ] - .iter() - .any(|(a, b)| (*a..=*b).contains(&code)) + if char::from_u32(code).is_none() { + return ""; + } + let index = data::RANGES.partition_point(|&(_, end, _)| end < code); + if let Some(&(start, _, direction)) = data::RANGES.get(index) + && start <= code { - RTL - } else { - LTR + return direction; } + LTR } pub fn strong_direction(text: &str) -> &'static str { let mut depth = 0usize; @@ -157,6 +120,51 @@ pub fn end_edge(direction: &str) -> &'static str { mod tests { use super::*; use serde_json::{Value, json}; + #[test] + fn unicode_classes_drive_first_strong_direction() { + for code in [0x05b0, 0x064b, 0x037e, 0x10d40, 0x20c1] { + let prefix = char::from_u32(code).unwrap(); + assert_eq!(direction_of_code(code), "", "non-strong U+{code:04X}"); + assert_eq!(strong_direction(&format!("{prefix}hello")), LTR); + assert_eq!(strong_direction(&format!("{prefix}שלום")), RTL); + } + for code in [0x00aa, 0x2102, 0x1f1e6] { + assert_eq!(direction_of_code(code), LTR, "strong L U+{code:04X}"); + } + for code in [0x0590, 0x086b, 0x10ec0] { + assert_eq!( + direction_of_code(code), + RTL, + "reserved default U+{code:04X}" + ); + } + } + + #[test] + fn every_scalar_matches_pinned_unicode_classes() { + let output = std::process::Command::new("python3") + .args(["scripts/generate-direction-data.py", "--classes"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout.len(), 0x110000); + for (code, expected) in output.stdout.into_iter().enumerate() { + let code = code as u32; + let direction = if char::from_u32(code).is_none() { + "" + } else { + ["", LTR, RTL][usize::from(expected)] + }; + assert_eq!(direction_of_code(code), direction, "U+{code:04X}"); + } + assert_eq!(direction_of_code(0x110000), ""); + assert_eq!(direction_of_code(u32::MAX), ""); + } + #[test] fn existing_direction_suite_is_a_live_golden_oracle() { let script = r#"const loader=require('./ui/tests/load');const load=loader.load;const rows=[];loader.load=function(p){const m=load(p);if(p==='message/Direction.js')for(const name of ['attributeFor','endEdge','forced','hasAnswer','isRightToLeft','normalizeMode','resolve','resolveBody','resolveSubject','startEdge','strongDirectionOf','subjectDirectionOf']){const f=m[name];m[name]=function(...args){const result=f(...args);rows.push({name,args,result});return result;};}return m;};console.log=()=>{};require('./ui/tests/test_direction');process.stdout.write(JSON.stringify(rows));"#; diff --git a/src/message/direction/data.rs b/src/message/direction/data.rs new file mode 100644 index 000000000..29d34520c --- /dev/null +++ b/src/message/direction/data.rs @@ -0,0 +1,624 @@ +// Generated by scripts/generate-direction-data.py; Unicode 17.0.0. +// DerivedBidiClass SHA-256: 4867b4b7f0731ed1bfcd34cc6251211ff1542541fce0734b6fbda139ee80b3a4 +// Unicode data license: data/unicode/LICENSE.txt. +pub(super) const RANGES: &[(u32, u32, &str)] = &[ + (0x0, 0x40, ""), + (0x5B, 0x60, ""), + (0x7B, 0xA9, ""), + (0xAB, 0xB4, ""), + (0xB6, 0xB9, ""), + (0xBB, 0xBF, ""), + (0xD7, 0xD7, ""), + (0xF7, 0xF7, ""), + (0x2B9, 0x2BA, ""), + (0x2C2, 0x2CF, ""), + (0x2D2, 0x2DF, ""), + (0x2E5, 0x2ED, ""), + (0x2EF, 0x36F, ""), + (0x374, 0x375, ""), + (0x37E, 0x37E, ""), + (0x384, 0x385, ""), + (0x387, 0x387, ""), + (0x3F6, 0x3F6, ""), + (0x483, 0x489, ""), + (0x58A, 0x58A, ""), + (0x58D, 0x58F, ""), + (0x590, 0x590, "rtl"), + (0x591, 0x5BD, ""), + (0x5BE, 0x5BE, "rtl"), + (0x5BF, 0x5BF, ""), + (0x5C0, 0x5C0, "rtl"), + (0x5C1, 0x5C2, ""), + (0x5C3, 0x5C3, "rtl"), + (0x5C4, 0x5C5, ""), + (0x5C6, 0x5C6, "rtl"), + (0x5C7, 0x5C7, ""), + (0x5C8, 0x5FF, "rtl"), + (0x600, 0x607, ""), + (0x608, 0x608, "rtl"), + (0x609, 0x60A, ""), + (0x60B, 0x60B, "rtl"), + (0x60C, 0x60C, ""), + (0x60D, 0x60D, "rtl"), + (0x60E, 0x61A, ""), + (0x61B, 0x64A, "rtl"), + (0x64B, 0x66C, ""), + (0x66D, 0x66F, "rtl"), + (0x670, 0x670, ""), + (0x671, 0x6D5, "rtl"), + (0x6D6, 0x6E4, ""), + (0x6E5, 0x6E6, "rtl"), + (0x6E7, 0x6ED, ""), + (0x6EE, 0x6EF, "rtl"), + (0x6F0, 0x6F9, ""), + (0x6FA, 0x710, "rtl"), + (0x711, 0x711, ""), + (0x712, 0x72F, "rtl"), + (0x730, 0x74A, ""), + (0x74B, 0x7A5, "rtl"), + (0x7A6, 0x7B0, ""), + (0x7B1, 0x7EA, "rtl"), + (0x7EB, 0x7F3, ""), + (0x7F4, 0x7F5, "rtl"), + (0x7F6, 0x7F9, ""), + (0x7FA, 0x7FC, "rtl"), + (0x7FD, 0x7FD, ""), + (0x7FE, 0x815, "rtl"), + (0x816, 0x819, ""), + (0x81A, 0x81A, "rtl"), + (0x81B, 0x823, ""), + (0x824, 0x824, "rtl"), + (0x825, 0x827, ""), + (0x828, 0x828, "rtl"), + (0x829, 0x82D, ""), + (0x82E, 0x858, "rtl"), + (0x859, 0x85B, ""), + (0x85C, 0x88F, "rtl"), + (0x890, 0x891, ""), + (0x892, 0x896, "rtl"), + (0x897, 0x89F, ""), + (0x8A0, 0x8C9, "rtl"), + (0x8CA, 0x902, ""), + (0x93A, 0x93A, ""), + (0x93C, 0x93C, ""), + (0x941, 0x948, ""), + (0x94D, 0x94D, ""), + (0x951, 0x957, ""), + (0x962, 0x963, ""), + (0x981, 0x981, ""), + (0x9BC, 0x9BC, ""), + (0x9C1, 0x9C4, ""), + (0x9CD, 0x9CD, ""), + (0x9E2, 0x9E3, ""), + (0x9F2, 0x9F3, ""), + (0x9FB, 0x9FB, ""), + (0x9FE, 0x9FE, ""), + (0xA01, 0xA02, ""), + (0xA3C, 0xA3C, ""), + (0xA41, 0xA42, ""), + (0xA47, 0xA48, ""), + (0xA4B, 0xA4D, ""), + (0xA51, 0xA51, ""), + (0xA70, 0xA71, ""), + (0xA75, 0xA75, ""), + (0xA81, 0xA82, ""), + (0xABC, 0xABC, ""), + (0xAC1, 0xAC5, ""), + (0xAC7, 0xAC8, ""), + (0xACD, 0xACD, ""), + (0xAE2, 0xAE3, ""), + (0xAF1, 0xAF1, ""), + (0xAFA, 0xAFF, ""), + (0xB01, 0xB01, ""), + (0xB3C, 0xB3C, ""), + (0xB3F, 0xB3F, ""), + (0xB41, 0xB44, ""), + (0xB4D, 0xB4D, ""), + (0xB55, 0xB56, ""), + (0xB62, 0xB63, ""), + (0xB82, 0xB82, ""), + (0xBC0, 0xBC0, ""), + (0xBCD, 0xBCD, ""), + (0xBF3, 0xBFA, ""), + (0xC00, 0xC00, ""), + (0xC04, 0xC04, ""), + (0xC3C, 0xC3C, ""), + (0xC3E, 0xC40, ""), + (0xC46, 0xC48, ""), + (0xC4A, 0xC4D, ""), + (0xC55, 0xC56, ""), + (0xC62, 0xC63, ""), + (0xC78, 0xC7E, ""), + (0xC81, 0xC81, ""), + (0xCBC, 0xCBC, ""), + (0xCCC, 0xCCD, ""), + (0xCE2, 0xCE3, ""), + (0xD00, 0xD01, ""), + (0xD3B, 0xD3C, ""), + (0xD41, 0xD44, ""), + (0xD4D, 0xD4D, ""), + (0xD62, 0xD63, ""), + (0xD81, 0xD81, ""), + (0xDCA, 0xDCA, ""), + (0xDD2, 0xDD4, ""), + (0xDD6, 0xDD6, ""), + (0xE31, 0xE31, ""), + (0xE34, 0xE3A, ""), + (0xE3F, 0xE3F, ""), + (0xE47, 0xE4E, ""), + (0xEB1, 0xEB1, ""), + (0xEB4, 0xEBC, ""), + (0xEC8, 0xECE, ""), + (0xF18, 0xF19, ""), + (0xF35, 0xF35, ""), + (0xF37, 0xF37, ""), + (0xF39, 0xF3D, ""), + (0xF71, 0xF7E, ""), + (0xF80, 0xF84, ""), + (0xF86, 0xF87, ""), + (0xF8D, 0xF97, ""), + (0xF99, 0xFBC, ""), + (0xFC6, 0xFC6, ""), + (0x102D, 0x1030, ""), + (0x1032, 0x1037, ""), + (0x1039, 0x103A, ""), + (0x103D, 0x103E, ""), + (0x1058, 0x1059, ""), + (0x105E, 0x1060, ""), + (0x1071, 0x1074, ""), + (0x1082, 0x1082, ""), + (0x1085, 0x1086, ""), + (0x108D, 0x108D, ""), + (0x109D, 0x109D, ""), + (0x135D, 0x135F, ""), + (0x1390, 0x1399, ""), + (0x1400, 0x1400, ""), + (0x1680, 0x1680, ""), + (0x169B, 0x169C, ""), + (0x1712, 0x1714, ""), + (0x1732, 0x1733, ""), + (0x1752, 0x1753, ""), + (0x1772, 0x1773, ""), + (0x17B4, 0x17B5, ""), + (0x17B7, 0x17BD, ""), + (0x17C6, 0x17C6, ""), + (0x17C9, 0x17D3, ""), + (0x17DB, 0x17DB, ""), + (0x17DD, 0x17DD, ""), + (0x17F0, 0x17F9, ""), + (0x1800, 0x180F, ""), + (0x1885, 0x1886, ""), + (0x18A9, 0x18A9, ""), + (0x1920, 0x1922, ""), + (0x1927, 0x1928, ""), + (0x1932, 0x1932, ""), + (0x1939, 0x193B, ""), + (0x1940, 0x1940, ""), + (0x1944, 0x1945, ""), + (0x19DE, 0x19FF, ""), + (0x1A17, 0x1A18, ""), + (0x1A1B, 0x1A1B, ""), + (0x1A56, 0x1A56, ""), + (0x1A58, 0x1A5E, ""), + (0x1A60, 0x1A60, ""), + (0x1A62, 0x1A62, ""), + (0x1A65, 0x1A6C, ""), + (0x1A73, 0x1A7C, ""), + (0x1A7F, 0x1A7F, ""), + (0x1AB0, 0x1ADD, ""), + (0x1AE0, 0x1AEB, ""), + (0x1B00, 0x1B03, ""), + (0x1B34, 0x1B34, ""), + (0x1B36, 0x1B3A, ""), + (0x1B3C, 0x1B3C, ""), + (0x1B42, 0x1B42, ""), + (0x1B6B, 0x1B73, ""), + (0x1B80, 0x1B81, ""), + (0x1BA2, 0x1BA5, ""), + (0x1BA8, 0x1BA9, ""), + (0x1BAB, 0x1BAD, ""), + (0x1BE6, 0x1BE6, ""), + (0x1BE8, 0x1BE9, ""), + (0x1BED, 0x1BED, ""), + (0x1BEF, 0x1BF1, ""), + (0x1C2C, 0x1C33, ""), + (0x1C36, 0x1C37, ""), + (0x1CD0, 0x1CD2, ""), + (0x1CD4, 0x1CE0, ""), + (0x1CE2, 0x1CE8, ""), + (0x1CED, 0x1CED, ""), + (0x1CF4, 0x1CF4, ""), + (0x1CF8, 0x1CF9, ""), + (0x1DC0, 0x1DFF, ""), + (0x1FBD, 0x1FBD, ""), + (0x1FBF, 0x1FC1, ""), + (0x1FCD, 0x1FCF, ""), + (0x1FDD, 0x1FDF, ""), + (0x1FED, 0x1FEF, ""), + (0x1FFD, 0x1FFE, ""), + (0x2000, 0x200D, ""), + (0x200F, 0x200F, "rtl"), + (0x2010, 0x2070, ""), + (0x2074, 0x207E, ""), + (0x2080, 0x208E, ""), + (0x20A0, 0x20F0, ""), + (0x2100, 0x2101, ""), + (0x2103, 0x2106, ""), + (0x2108, 0x2109, ""), + (0x2114, 0x2114, ""), + (0x2116, 0x2118, ""), + (0x211E, 0x2123, ""), + (0x2125, 0x2125, ""), + (0x2127, 0x2127, ""), + (0x2129, 0x2129, ""), + (0x212E, 0x212E, ""), + (0x213A, 0x213B, ""), + (0x2140, 0x2144, ""), + (0x214A, 0x214D, ""), + (0x2150, 0x215F, ""), + (0x2189, 0x218B, ""), + (0x2190, 0x2335, ""), + (0x237B, 0x2394, ""), + (0x2396, 0x2429, ""), + (0x2440, 0x244A, ""), + (0x2460, 0x249B, ""), + (0x24EA, 0x26AB, ""), + (0x26AD, 0x27FF, ""), + (0x2900, 0x2B73, ""), + (0x2B76, 0x2BFF, ""), + (0x2CE5, 0x2CEA, ""), + (0x2CEF, 0x2CF1, ""), + (0x2CF9, 0x2CFF, ""), + (0x2D7F, 0x2D7F, ""), + (0x2DE0, 0x2E5D, ""), + (0x2E80, 0x2E99, ""), + (0x2E9B, 0x2EF3, ""), + (0x2F00, 0x2FD5, ""), + (0x2FF0, 0x3004, ""), + (0x3008, 0x3020, ""), + (0x302A, 0x302D, ""), + (0x3030, 0x3030, ""), + (0x3036, 0x3037, ""), + (0x303D, 0x303F, ""), + (0x3099, 0x309C, ""), + (0x30A0, 0x30A0, ""), + (0x30FB, 0x30FB, ""), + (0x31C0, 0x31E5, ""), + (0x31EF, 0x31EF, ""), + (0x321D, 0x321E, ""), + (0x3250, 0x325F, ""), + (0x327C, 0x327E, ""), + (0x32B1, 0x32BF, ""), + (0x32CC, 0x32CF, ""), + (0x3377, 0x337A, ""), + (0x33DE, 0x33DF, ""), + (0x33FF, 0x33FF, ""), + (0x4DC0, 0x4DFF, ""), + (0xA490, 0xA4C6, ""), + (0xA60D, 0xA60F, ""), + (0xA66F, 0xA67F, ""), + (0xA69E, 0xA69F, ""), + (0xA6F0, 0xA6F1, ""), + (0xA700, 0xA721, ""), + (0xA788, 0xA788, ""), + (0xA802, 0xA802, ""), + (0xA806, 0xA806, ""), + (0xA80B, 0xA80B, ""), + (0xA825, 0xA826, ""), + (0xA828, 0xA82C, ""), + (0xA838, 0xA839, ""), + (0xA874, 0xA877, ""), + (0xA8C4, 0xA8C5, ""), + (0xA8E0, 0xA8F1, ""), + (0xA8FF, 0xA8FF, ""), + (0xA926, 0xA92D, ""), + (0xA947, 0xA951, ""), + (0xA980, 0xA982, ""), + (0xA9B3, 0xA9B3, ""), + (0xA9B6, 0xA9B9, ""), + (0xA9BC, 0xA9BD, ""), + (0xA9E5, 0xA9E5, ""), + (0xAA29, 0xAA2E, ""), + (0xAA31, 0xAA32, ""), + (0xAA35, 0xAA36, ""), + (0xAA43, 0xAA43, ""), + (0xAA4C, 0xAA4C, ""), + (0xAA7C, 0xAA7C, ""), + (0xAAB0, 0xAAB0, ""), + (0xAAB2, 0xAAB4, ""), + (0xAAB7, 0xAAB8, ""), + (0xAABE, 0xAABF, ""), + (0xAAC1, 0xAAC1, ""), + (0xAAEC, 0xAAED, ""), + (0xAAF6, 0xAAF6, ""), + (0xAB6A, 0xAB6B, ""), + (0xABE5, 0xABE5, ""), + (0xABE8, 0xABE8, ""), + (0xABED, 0xABED, ""), + (0xFB1D, 0xFB1D, "rtl"), + (0xFB1E, 0xFB1E, ""), + (0xFB1F, 0xFB28, "rtl"), + (0xFB29, 0xFB29, ""), + (0xFB2A, 0xFBC2, "rtl"), + (0xFBC3, 0xFBD2, ""), + (0xFBD3, 0xFD3D, "rtl"), + (0xFD3E, 0xFD4F, ""), + (0xFD50, 0xFD8F, "rtl"), + (0xFD90, 0xFD91, ""), + (0xFD92, 0xFDC7, "rtl"), + (0xFDC8, 0xFDEF, ""), + (0xFDF0, 0xFDFC, "rtl"), + (0xFDFD, 0xFE19, ""), + (0xFE20, 0xFE52, ""), + (0xFE54, 0xFE66, ""), + (0xFE68, 0xFE6B, ""), + (0xFE70, 0xFEFE, "rtl"), + (0xFEFF, 0xFEFF, ""), + (0xFF01, 0xFF20, ""), + (0xFF3B, 0xFF40, ""), + (0xFF5B, 0xFF65, ""), + (0xFFE0, 0xFFE6, ""), + (0xFFE8, 0xFFEE, ""), + (0xFFF0, 0xFFFF, ""), + (0x10101, 0x10101, ""), + (0x10140, 0x1018C, ""), + (0x10190, 0x1019C, ""), + (0x101A0, 0x101A0, ""), + (0x101FD, 0x101FD, ""), + (0x102E0, 0x102FB, ""), + (0x10376, 0x1037A, ""), + (0x10800, 0x1091E, "rtl"), + (0x1091F, 0x1091F, ""), + (0x10920, 0x10A00, "rtl"), + (0x10A01, 0x10A03, ""), + (0x10A04, 0x10A04, "rtl"), + (0x10A05, 0x10A06, ""), + (0x10A07, 0x10A0B, "rtl"), + (0x10A0C, 0x10A0F, ""), + (0x10A10, 0x10A37, "rtl"), + (0x10A38, 0x10A3A, ""), + (0x10A3B, 0x10A3E, "rtl"), + (0x10A3F, 0x10A3F, ""), + (0x10A40, 0x10AE4, "rtl"), + (0x10AE5, 0x10AE6, ""), + (0x10AE7, 0x10B38, "rtl"), + (0x10B39, 0x10B3F, ""), + (0x10B40, 0x10D23, "rtl"), + (0x10D24, 0x10D27, ""), + (0x10D28, 0x10D2F, "rtl"), + (0x10D30, 0x10D39, ""), + (0x10D3A, 0x10D3F, "rtl"), + (0x10D40, 0x10D49, ""), + (0x10D4A, 0x10D68, "rtl"), + (0x10D69, 0x10D6E, ""), + (0x10D6F, 0x10E5F, "rtl"), + (0x10E60, 0x10E7E, ""), + (0x10E7F, 0x10EAA, "rtl"), + (0x10EAB, 0x10EAC, ""), + (0x10EAD, 0x10ECF, "rtl"), + (0x10ED0, 0x10ED8, ""), + (0x10ED9, 0x10EF9, "rtl"), + (0x10EFA, 0x10EFF, ""), + (0x10F00, 0x10F45, "rtl"), + (0x10F46, 0x10F50, ""), + (0x10F51, 0x10F81, "rtl"), + (0x10F82, 0x10F85, ""), + (0x10F86, 0x10FFF, "rtl"), + (0x11001, 0x11001, ""), + (0x11038, 0x11046, ""), + (0x11052, 0x11065, ""), + (0x11070, 0x11070, ""), + (0x11073, 0x11074, ""), + (0x1107F, 0x11081, ""), + (0x110B3, 0x110B6, ""), + (0x110B9, 0x110BA, ""), + (0x110C2, 0x110C2, ""), + (0x11100, 0x11102, ""), + (0x11127, 0x1112B, ""), + (0x1112D, 0x11134, ""), + (0x11173, 0x11173, ""), + (0x11180, 0x11181, ""), + (0x111B6, 0x111BE, ""), + (0x111C9, 0x111CC, ""), + (0x111CF, 0x111CF, ""), + (0x1122F, 0x11231, ""), + (0x11234, 0x11234, ""), + (0x11236, 0x11237, ""), + (0x1123E, 0x1123E, ""), + (0x11241, 0x11241, ""), + (0x112DF, 0x112DF, ""), + (0x112E3, 0x112EA, ""), + (0x11300, 0x11301, ""), + (0x1133B, 0x1133C, ""), + (0x11340, 0x11340, ""), + (0x11366, 0x1136C, ""), + (0x11370, 0x11374, ""), + (0x113BB, 0x113C0, ""), + (0x113CE, 0x113CE, ""), + (0x113D0, 0x113D0, ""), + (0x113D2, 0x113D2, ""), + (0x113E1, 0x113E2, ""), + (0x11438, 0x1143F, ""), + (0x11442, 0x11444, ""), + (0x11446, 0x11446, ""), + (0x1145E, 0x1145E, ""), + (0x114B3, 0x114B8, ""), + (0x114BA, 0x114BA, ""), + (0x114BF, 0x114C0, ""), + (0x114C2, 0x114C3, ""), + (0x115B2, 0x115B5, ""), + (0x115BC, 0x115BD, ""), + (0x115BF, 0x115C0, ""), + (0x115DC, 0x115DD, ""), + (0x11633, 0x1163A, ""), + (0x1163D, 0x1163D, ""), + (0x1163F, 0x11640, ""), + (0x11660, 0x1166C, ""), + (0x116AB, 0x116AB, ""), + (0x116AD, 0x116AD, ""), + (0x116B0, 0x116B5, ""), + (0x116B7, 0x116B7, ""), + (0x1171D, 0x1171D, ""), + (0x1171F, 0x1171F, ""), + (0x11722, 0x11725, ""), + (0x11727, 0x1172B, ""), + (0x1182F, 0x11837, ""), + (0x11839, 0x1183A, ""), + (0x1193B, 0x1193C, ""), + (0x1193E, 0x1193E, ""), + (0x11943, 0x11943, ""), + (0x119D4, 0x119D7, ""), + (0x119DA, 0x119DB, ""), + (0x119E0, 0x119E0, ""), + (0x11A01, 0x11A06, ""), + (0x11A09, 0x11A0A, ""), + (0x11A33, 0x11A38, ""), + (0x11A3B, 0x11A3E, ""), + (0x11A47, 0x11A47, ""), + (0x11A51, 0x11A56, ""), + (0x11A59, 0x11A5B, ""), + (0x11A8A, 0x11A96, ""), + (0x11A98, 0x11A99, ""), + (0x11B60, 0x11B60, ""), + (0x11B62, 0x11B64, ""), + (0x11B66, 0x11B66, ""), + (0x11C30, 0x11C36, ""), + (0x11C38, 0x11C3D, ""), + (0x11C92, 0x11CA7, ""), + (0x11CAA, 0x11CB0, ""), + (0x11CB2, 0x11CB3, ""), + (0x11CB5, 0x11CB6, ""), + (0x11D31, 0x11D36, ""), + (0x11D3A, 0x11D3A, ""), + (0x11D3C, 0x11D3D, ""), + (0x11D3F, 0x11D45, ""), + (0x11D47, 0x11D47, ""), + (0x11D90, 0x11D91, ""), + (0x11D95, 0x11D95, ""), + (0x11D97, 0x11D97, ""), + (0x11EF3, 0x11EF4, ""), + (0x11F00, 0x11F01, ""), + (0x11F36, 0x11F3A, ""), + (0x11F40, 0x11F40, ""), + (0x11F42, 0x11F42, ""), + (0x11F5A, 0x11F5A, ""), + (0x11FD5, 0x11FF1, ""), + (0x13440, 0x13440, ""), + (0x13447, 0x13455, ""), + (0x1611E, 0x16129, ""), + (0x1612D, 0x1612F, ""), + (0x16AF0, 0x16AF4, ""), + (0x16B30, 0x16B36, ""), + (0x16F4F, 0x16F4F, ""), + (0x16F8F, 0x16F92, ""), + (0x16FE2, 0x16FE2, ""), + (0x16FE4, 0x16FE4, ""), + (0x1BC9D, 0x1BC9E, ""), + (0x1BCA0, 0x1BCA3, ""), + (0x1CC00, 0x1CCD5, ""), + (0x1CCF0, 0x1CCFC, ""), + (0x1CD00, 0x1CEB3, ""), + (0x1CEBA, 0x1CED0, ""), + (0x1CEE0, 0x1CEF0, ""), + (0x1CF00, 0x1CF2D, ""), + (0x1CF30, 0x1CF46, ""), + (0x1D167, 0x1D169, ""), + (0x1D173, 0x1D182, ""), + (0x1D185, 0x1D18B, ""), + (0x1D1AA, 0x1D1AD, ""), + (0x1D1E9, 0x1D1EA, ""), + (0x1D200, 0x1D245, ""), + (0x1D300, 0x1D356, ""), + (0x1D6C1, 0x1D6C1, ""), + (0x1D6DB, 0x1D6DB, ""), + (0x1D6FB, 0x1D6FB, ""), + (0x1D715, 0x1D715, ""), + (0x1D735, 0x1D735, ""), + (0x1D74F, 0x1D74F, ""), + (0x1D76F, 0x1D76F, ""), + (0x1D789, 0x1D789, ""), + (0x1D7A9, 0x1D7A9, ""), + (0x1D7C3, 0x1D7C3, ""), + (0x1D7CE, 0x1D7FF, ""), + (0x1DA00, 0x1DA36, ""), + (0x1DA3B, 0x1DA6C, ""), + (0x1DA75, 0x1DA75, ""), + (0x1DA84, 0x1DA84, ""), + (0x1DA9B, 0x1DA9F, ""), + (0x1DAA1, 0x1DAAF, ""), + (0x1E000, 0x1E006, ""), + (0x1E008, 0x1E018, ""), + (0x1E01B, 0x1E021, ""), + (0x1E023, 0x1E024, ""), + (0x1E026, 0x1E02A, ""), + (0x1E08F, 0x1E08F, ""), + (0x1E130, 0x1E136, ""), + (0x1E2AE, 0x1E2AE, ""), + (0x1E2EC, 0x1E2EF, ""), + (0x1E2FF, 0x1E2FF, ""), + (0x1E4EC, 0x1E4EF, ""), + (0x1E5EE, 0x1E5EF, ""), + (0x1E6E3, 0x1E6E3, ""), + (0x1E6E6, 0x1E6E6, ""), + (0x1E6EE, 0x1E6EF, ""), + (0x1E6F5, 0x1E6F5, ""), + (0x1E800, 0x1E8CF, "rtl"), + (0x1E8D0, 0x1E8D6, ""), + (0x1E8D7, 0x1E943, "rtl"), + (0x1E944, 0x1E94A, ""), + (0x1E94B, 0x1EEEF, "rtl"), + (0x1EEF0, 0x1EEF1, ""), + (0x1EEF2, 0x1EFFF, "rtl"), + (0x1F000, 0x1F02B, ""), + (0x1F030, 0x1F093, ""), + (0x1F0A0, 0x1F0AE, ""), + (0x1F0B1, 0x1F0BF, ""), + (0x1F0C1, 0x1F0CF, ""), + (0x1F0D1, 0x1F0F5, ""), + (0x1F100, 0x1F10F, ""), + (0x1F12F, 0x1F12F, ""), + (0x1F16A, 0x1F16F, ""), + (0x1F1AD, 0x1F1AD, ""), + (0x1F260, 0x1F265, ""), + (0x1F300, 0x1F6D8, ""), + (0x1F6DC, 0x1F6EC, ""), + (0x1F6F0, 0x1F6FC, ""), + (0x1F700, 0x1F7D9, ""), + (0x1F7E0, 0x1F7EB, ""), + (0x1F7F0, 0x1F7F0, ""), + (0x1F800, 0x1F80B, ""), + (0x1F810, 0x1F847, ""), + (0x1F850, 0x1F859, ""), + (0x1F860, 0x1F887, ""), + (0x1F890, 0x1F8AD, ""), + (0x1F8B0, 0x1F8BB, ""), + (0x1F8C0, 0x1F8C1, ""), + (0x1F8D0, 0x1F8D8, ""), + (0x1F900, 0x1FA57, ""), + (0x1FA60, 0x1FA6D, ""), + (0x1FA70, 0x1FA7C, ""), + (0x1FA80, 0x1FA8A, ""), + (0x1FA8E, 0x1FAC6, ""), + (0x1FAC8, 0x1FAC8, ""), + (0x1FACD, 0x1FADC, ""), + (0x1FADF, 0x1FAEA, ""), + (0x1FAEF, 0x1FAF8, ""), + (0x1FB00, 0x1FB92, ""), + (0x1FB94, 0x1FBFA, ""), + (0x1FFFE, 0x1FFFF, ""), + (0x2FFFE, 0x2FFFF, ""), + (0x3FFFE, 0x3FFFF, ""), + (0x4FFFE, 0x4FFFF, ""), + (0x5FFFE, 0x5FFFF, ""), + (0x6FFFE, 0x6FFFF, ""), + (0x7FFFE, 0x7FFFF, ""), + (0x8FFFE, 0x8FFFF, ""), + (0x9FFFE, 0x9FFFF, ""), + (0xAFFFE, 0xAFFFF, ""), + (0xBFFFE, 0xBFFFF, ""), + (0xCFFFE, 0xCFFFF, ""), + (0xDFFFE, 0xE0FFF, ""), + (0xEFFFE, 0xEFFFF, ""), + (0xFFFFE, 0xFFFFF, ""), + (0x10FFFE, 0x10FFFF, ""), +]; diff --git a/ui/message/Direction.js b/ui/message/Direction.js index f45f1558d..98d95e180 100644 --- a/ui/message/Direction.js +++ b/ui/message/Direction.js @@ -1,4 +1,5 @@ .pragma library +.import "DirectionData.js" as Bidi // Which way a piece of a message runs. // @@ -61,36 +62,6 @@ function isRightToLeft(direction) { return String(direction) === RTL } -// ------------------------------------------------------- strong and neutral -// -// The classification runs on code points rather than on UTF-16 units, because -// the RTL blocks above the BMP — Kharoshthi, Old Hungarian, Adlam, the Arabic -// mathematical alphabets — are written as surrogate pairs, and a scan that -// read the halves separately would see two unassigned BMP characters and call -// a wholly right-to-left message left-to-right. - -// Every right-to-left block Unicode defines, as [first, last] pairs. This list -// is the one thing here that has to be complete: a script missing from it is -// classified strong left-to-right by the fallback below, which is a wrong -// answer rather than an absent one. -var RTL_RANGES = [ - [0x0590, 0x05FF], // Hebrew - [0x0600, 0x07BF], // Arabic, Syriac, Arabic Supplement, Thaana - [0x07C0, 0x085F], // NKo, Samaritan, Mandaic - [0x0860, 0x08FF], // Syriac Supplement, Arabic Extended-A and -B - [0xFB1D, 0xFB4F], // Hebrew presentation forms - [0xFB50, 0xFDFF], // Arabic presentation forms-A - [0xFE70, 0xFEFC], // Arabic presentation forms-B (the last assigned is FEFC) - [0x10800, 0x10CFF], // Cypriot, Phoenician, Kharoshthi, Old Hungarian - [0x10D00, 0x10FFF], // Hanifi Rohingya, Sogdian, Elymaic, Old Sogdian - [0x1E800, 0x1EFFF] // Mende Kikakui, Adlam, Arabic mathematical alphabets -] - -// The marks and the embedding controls, which say a direction outright instead -// of being a character that happens to have one. -var LEFT_TO_RIGHT_MARK = 0x200E -var RIGHT_TO_LEFT_MARK = 0x200F -var ARABIC_LETTER_MARK = 0x061C var LEFT_TO_RIGHT_EMBEDDING = 0x202A var RIGHT_TO_LEFT_EMBEDDING = 0x202B var LEFT_TO_RIGHT_OVERRIDE = 0x202D @@ -100,84 +71,17 @@ var RIGHT_TO_LEFT_ISOLATE = 0x2067 var FIRST_STRONG_ISOLATE = 0x2068 var POP_DIRECTIONAL_ISOLATE = 0x2069 -function isRtlCode(code) { - for (var rangeIndex = 0; rangeIndex < RTL_RANGES.length; rangeIndex++) { - if (code >= RTL_RANGES[rangeIndex][0] && code <= RTL_RANGES[rangeIndex][1]) return true - } - return false -} - -// Neutral rather than "not a letter": the question P2 asks is which characters -// may be skipped over, and digits are the ones that matter. A subject that -// opens with a year — `2024 مرحبا` — is right-to-left, and a scan that treated -// `2` as strong left-to-right would get it backwards. European and Arabic -// digits are both types of their own (EN and AN) and neither is strong. -function isNeutralCode(code) { - // Controls, space, the ASCII digits, and the two runs of ASCII punctuation - // and symbols on either side of the capital letters. - if (code <= 0x0040) return true - if (code >= 0x005B && code <= 0x0060) return true - // The punctuation after the small letters, then Latin-1 punctuation, signs - // and currency, which run to the first accented letter at 0x00C0. - if (code >= 0x007B && code <= 0x00BF) return true - if (code === 0x00D7 || code === 0x00F7) return true // × ÷ - // The Arabic block's own numbers. These sit inside the strong ranges below, - // so they are only reachable because `directionOfCode` asks this question - // first — see the note there. - if (code >= 0x0600 && code <= 0x0605) return true // Arabic number signs (AN) - if (code >= 0x0660 && code <= 0x066C) return true // Arabic-Indic digits and separators - if (code === 0x06DD || code === 0x08E2) return true // end of ayah, disputed end of ayah - if (code >= 0x06F0 && code <= 0x06F9) return true // extended Arabic-Indic digits - if (code >= 0x10E60 && code <= 0x10E7E) return true // Rumi numeral symbols (AN) - if (code >= 0x0300 && code <= 0x036F) return true // combining marks (NSM) - if (code >= 0x2000 && code <= 0x2BFF) return true // punctuation, symbols, arrows - if (code >= 0x2E00 && code <= 0x2E7F) return true // supplemental punctuation - if (code >= 0x3000 && code <= 0x303F) return true // CJK punctuation - if (code >= 0xFE00 && code <= 0xFE0F) return true // variation selectors - // Fullwidth punctuation, in the three runs around the fullwidth letters — - // which are strong left-to-right and are not here. - if (code >= 0xFF01 && code <= 0xFF20) return true - if (code >= 0xFF3B && code <= 0xFF40) return true - if (code >= 0xFF5B && code <= 0xFF65) return true - // U+FEFF is the byte order mark, which says nothing about direction and - // arrives at the front of a great many plain text parts. It sits just past - // the end of Arabic presentation forms-B, so a range that reached the end of - // the block would have read a BOM as a strong Arabic letter — and an English - // message that carried one would have been laid out right to left. - if (code === 0xFEFF) return true - // Emoji and the pictographic symbols beside them. A subject opening with one - // is the house style of most of the mail anybody receives, and every one of - // them is Other Neutral: the emoji says nothing about which way the sentence - // after it runs. - if (code >= 0x1F000 && code <= 0x1F0FF) return true // mahjong, dominoes, cards - if (code >= 0x1F1E6 && code <= 0x1F1FF) return true // regional indicators (flags) - if (code >= 0x1F300 && code <= 0x1FAFF) return true // pictographs and symbols - return false -} - -// The direction a single code point asserts, or UNKNOWN when it asserts none. -// -// The neutral question comes before the range question, and the order is the -// whole of it. A block is a range of code points and a direction class is not: -// the Arabic block holds the Arabic-Indic digits, which are AN and assert -// nothing, so a scan that asked "is this in a right-to-left block?" first -// answered RTL for a digit and never reached the line written to say otherwise. -// That put `١٢٣ hello` on the right and — because `outgoingDirection` reads a -// body by this same rule — grew a `dir="rtl"` HTML twin onto an English message -// whose first character happened to be an Arabic-Indic number. -// -// The marks stay in front of both: an explicit RLM or ALM is the author saying -// outright which way this runs, and U+200F sits inside the neutral punctuation -// range. function directionOfCode(code) { - if (code === RIGHT_TO_LEFT_MARK || code === ARABIC_LETTER_MARK) return RTL - if (code === LEFT_TO_RIGHT_MARK) return LTR - if (isNeutralCode(code)) return UNKNOWN - if (isRtlCode(code)) return RTL - // Everything left is a letter of some script, and every right-to-left script - // was named above. Falling through to left-to-right rather than listing the - // hundred that are keeps a newly encoded script — Latin, Cyrillic, Devanagari, - // Han, or one that does not exist yet — rendering the way it did before. + if (typeof code !== "number" || code !== Math.floor(code) || code < 0 || code > 0x10FFFF + || (code >= 0xD800 && code <= 0xDFFF)) return UNKNOWN + var low = 0 + var high = Bidi.RANGES.length + while (low < high) { + var middle = Math.floor((low + high) / 2) + if (Bidi.RANGES[middle][1] < code) low = middle + 1 + else high = middle + } + if (low < Bidi.RANGES.length && Bidi.RANGES[low][0] <= code) return Bidi.RANGES[low][2] return LTR } diff --git a/ui/message/DirectionData.js b/ui/message/DirectionData.js new file mode 100644 index 000000000..3b748471d --- /dev/null +++ b/ui/message/DirectionData.js @@ -0,0 +1,626 @@ +.pragma library + +// Generated by scripts/generate-direction-data.py; Unicode 17.0.0. +// DerivedBidiClass SHA-256: 4867b4b7f0731ed1bfcd34cc6251211ff1542541fce0734b6fbda139ee80b3a4 +// Unicode data license: data/unicode/LICENSE.txt. +var RANGES = [ + [0x0, 0x40, ""], + [0x5B, 0x60, ""], + [0x7B, 0xA9, ""], + [0xAB, 0xB4, ""], + [0xB6, 0xB9, ""], + [0xBB, 0xBF, ""], + [0xD7, 0xD7, ""], + [0xF7, 0xF7, ""], + [0x2B9, 0x2BA, ""], + [0x2C2, 0x2CF, ""], + [0x2D2, 0x2DF, ""], + [0x2E5, 0x2ED, ""], + [0x2EF, 0x36F, ""], + [0x374, 0x375, ""], + [0x37E, 0x37E, ""], + [0x384, 0x385, ""], + [0x387, 0x387, ""], + [0x3F6, 0x3F6, ""], + [0x483, 0x489, ""], + [0x58A, 0x58A, ""], + [0x58D, 0x58F, ""], + [0x590, 0x590, "rtl"], + [0x591, 0x5BD, ""], + [0x5BE, 0x5BE, "rtl"], + [0x5BF, 0x5BF, ""], + [0x5C0, 0x5C0, "rtl"], + [0x5C1, 0x5C2, ""], + [0x5C3, 0x5C3, "rtl"], + [0x5C4, 0x5C5, ""], + [0x5C6, 0x5C6, "rtl"], + [0x5C7, 0x5C7, ""], + [0x5C8, 0x5FF, "rtl"], + [0x600, 0x607, ""], + [0x608, 0x608, "rtl"], + [0x609, 0x60A, ""], + [0x60B, 0x60B, "rtl"], + [0x60C, 0x60C, ""], + [0x60D, 0x60D, "rtl"], + [0x60E, 0x61A, ""], + [0x61B, 0x64A, "rtl"], + [0x64B, 0x66C, ""], + [0x66D, 0x66F, "rtl"], + [0x670, 0x670, ""], + [0x671, 0x6D5, "rtl"], + [0x6D6, 0x6E4, ""], + [0x6E5, 0x6E6, "rtl"], + [0x6E7, 0x6ED, ""], + [0x6EE, 0x6EF, "rtl"], + [0x6F0, 0x6F9, ""], + [0x6FA, 0x710, "rtl"], + [0x711, 0x711, ""], + [0x712, 0x72F, "rtl"], + [0x730, 0x74A, ""], + [0x74B, 0x7A5, "rtl"], + [0x7A6, 0x7B0, ""], + [0x7B1, 0x7EA, "rtl"], + [0x7EB, 0x7F3, ""], + [0x7F4, 0x7F5, "rtl"], + [0x7F6, 0x7F9, ""], + [0x7FA, 0x7FC, "rtl"], + [0x7FD, 0x7FD, ""], + [0x7FE, 0x815, "rtl"], + [0x816, 0x819, ""], + [0x81A, 0x81A, "rtl"], + [0x81B, 0x823, ""], + [0x824, 0x824, "rtl"], + [0x825, 0x827, ""], + [0x828, 0x828, "rtl"], + [0x829, 0x82D, ""], + [0x82E, 0x858, "rtl"], + [0x859, 0x85B, ""], + [0x85C, 0x88F, "rtl"], + [0x890, 0x891, ""], + [0x892, 0x896, "rtl"], + [0x897, 0x89F, ""], + [0x8A0, 0x8C9, "rtl"], + [0x8CA, 0x902, ""], + [0x93A, 0x93A, ""], + [0x93C, 0x93C, ""], + [0x941, 0x948, ""], + [0x94D, 0x94D, ""], + [0x951, 0x957, ""], + [0x962, 0x963, ""], + [0x981, 0x981, ""], + [0x9BC, 0x9BC, ""], + [0x9C1, 0x9C4, ""], + [0x9CD, 0x9CD, ""], + [0x9E2, 0x9E3, ""], + [0x9F2, 0x9F3, ""], + [0x9FB, 0x9FB, ""], + [0x9FE, 0x9FE, ""], + [0xA01, 0xA02, ""], + [0xA3C, 0xA3C, ""], + [0xA41, 0xA42, ""], + [0xA47, 0xA48, ""], + [0xA4B, 0xA4D, ""], + [0xA51, 0xA51, ""], + [0xA70, 0xA71, ""], + [0xA75, 0xA75, ""], + [0xA81, 0xA82, ""], + [0xABC, 0xABC, ""], + [0xAC1, 0xAC5, ""], + [0xAC7, 0xAC8, ""], + [0xACD, 0xACD, ""], + [0xAE2, 0xAE3, ""], + [0xAF1, 0xAF1, ""], + [0xAFA, 0xAFF, ""], + [0xB01, 0xB01, ""], + [0xB3C, 0xB3C, ""], + [0xB3F, 0xB3F, ""], + [0xB41, 0xB44, ""], + [0xB4D, 0xB4D, ""], + [0xB55, 0xB56, ""], + [0xB62, 0xB63, ""], + [0xB82, 0xB82, ""], + [0xBC0, 0xBC0, ""], + [0xBCD, 0xBCD, ""], + [0xBF3, 0xBFA, ""], + [0xC00, 0xC00, ""], + [0xC04, 0xC04, ""], + [0xC3C, 0xC3C, ""], + [0xC3E, 0xC40, ""], + [0xC46, 0xC48, ""], + [0xC4A, 0xC4D, ""], + [0xC55, 0xC56, ""], + [0xC62, 0xC63, ""], + [0xC78, 0xC7E, ""], + [0xC81, 0xC81, ""], + [0xCBC, 0xCBC, ""], + [0xCCC, 0xCCD, ""], + [0xCE2, 0xCE3, ""], + [0xD00, 0xD01, ""], + [0xD3B, 0xD3C, ""], + [0xD41, 0xD44, ""], + [0xD4D, 0xD4D, ""], + [0xD62, 0xD63, ""], + [0xD81, 0xD81, ""], + [0xDCA, 0xDCA, ""], + [0xDD2, 0xDD4, ""], + [0xDD6, 0xDD6, ""], + [0xE31, 0xE31, ""], + [0xE34, 0xE3A, ""], + [0xE3F, 0xE3F, ""], + [0xE47, 0xE4E, ""], + [0xEB1, 0xEB1, ""], + [0xEB4, 0xEBC, ""], + [0xEC8, 0xECE, ""], + [0xF18, 0xF19, ""], + [0xF35, 0xF35, ""], + [0xF37, 0xF37, ""], + [0xF39, 0xF3D, ""], + [0xF71, 0xF7E, ""], + [0xF80, 0xF84, ""], + [0xF86, 0xF87, ""], + [0xF8D, 0xF97, ""], + [0xF99, 0xFBC, ""], + [0xFC6, 0xFC6, ""], + [0x102D, 0x1030, ""], + [0x1032, 0x1037, ""], + [0x1039, 0x103A, ""], + [0x103D, 0x103E, ""], + [0x1058, 0x1059, ""], + [0x105E, 0x1060, ""], + [0x1071, 0x1074, ""], + [0x1082, 0x1082, ""], + [0x1085, 0x1086, ""], + [0x108D, 0x108D, ""], + [0x109D, 0x109D, ""], + [0x135D, 0x135F, ""], + [0x1390, 0x1399, ""], + [0x1400, 0x1400, ""], + [0x1680, 0x1680, ""], + [0x169B, 0x169C, ""], + [0x1712, 0x1714, ""], + [0x1732, 0x1733, ""], + [0x1752, 0x1753, ""], + [0x1772, 0x1773, ""], + [0x17B4, 0x17B5, ""], + [0x17B7, 0x17BD, ""], + [0x17C6, 0x17C6, ""], + [0x17C9, 0x17D3, ""], + [0x17DB, 0x17DB, ""], + [0x17DD, 0x17DD, ""], + [0x17F0, 0x17F9, ""], + [0x1800, 0x180F, ""], + [0x1885, 0x1886, ""], + [0x18A9, 0x18A9, ""], + [0x1920, 0x1922, ""], + [0x1927, 0x1928, ""], + [0x1932, 0x1932, ""], + [0x1939, 0x193B, ""], + [0x1940, 0x1940, ""], + [0x1944, 0x1945, ""], + [0x19DE, 0x19FF, ""], + [0x1A17, 0x1A18, ""], + [0x1A1B, 0x1A1B, ""], + [0x1A56, 0x1A56, ""], + [0x1A58, 0x1A5E, ""], + [0x1A60, 0x1A60, ""], + [0x1A62, 0x1A62, ""], + [0x1A65, 0x1A6C, ""], + [0x1A73, 0x1A7C, ""], + [0x1A7F, 0x1A7F, ""], + [0x1AB0, 0x1ADD, ""], + [0x1AE0, 0x1AEB, ""], + [0x1B00, 0x1B03, ""], + [0x1B34, 0x1B34, ""], + [0x1B36, 0x1B3A, ""], + [0x1B3C, 0x1B3C, ""], + [0x1B42, 0x1B42, ""], + [0x1B6B, 0x1B73, ""], + [0x1B80, 0x1B81, ""], + [0x1BA2, 0x1BA5, ""], + [0x1BA8, 0x1BA9, ""], + [0x1BAB, 0x1BAD, ""], + [0x1BE6, 0x1BE6, ""], + [0x1BE8, 0x1BE9, ""], + [0x1BED, 0x1BED, ""], + [0x1BEF, 0x1BF1, ""], + [0x1C2C, 0x1C33, ""], + [0x1C36, 0x1C37, ""], + [0x1CD0, 0x1CD2, ""], + [0x1CD4, 0x1CE0, ""], + [0x1CE2, 0x1CE8, ""], + [0x1CED, 0x1CED, ""], + [0x1CF4, 0x1CF4, ""], + [0x1CF8, 0x1CF9, ""], + [0x1DC0, 0x1DFF, ""], + [0x1FBD, 0x1FBD, ""], + [0x1FBF, 0x1FC1, ""], + [0x1FCD, 0x1FCF, ""], + [0x1FDD, 0x1FDF, ""], + [0x1FED, 0x1FEF, ""], + [0x1FFD, 0x1FFE, ""], + [0x2000, 0x200D, ""], + [0x200F, 0x200F, "rtl"], + [0x2010, 0x2070, ""], + [0x2074, 0x207E, ""], + [0x2080, 0x208E, ""], + [0x20A0, 0x20F0, ""], + [0x2100, 0x2101, ""], + [0x2103, 0x2106, ""], + [0x2108, 0x2109, ""], + [0x2114, 0x2114, ""], + [0x2116, 0x2118, ""], + [0x211E, 0x2123, ""], + [0x2125, 0x2125, ""], + [0x2127, 0x2127, ""], + [0x2129, 0x2129, ""], + [0x212E, 0x212E, ""], + [0x213A, 0x213B, ""], + [0x2140, 0x2144, ""], + [0x214A, 0x214D, ""], + [0x2150, 0x215F, ""], + [0x2189, 0x218B, ""], + [0x2190, 0x2335, ""], + [0x237B, 0x2394, ""], + [0x2396, 0x2429, ""], + [0x2440, 0x244A, ""], + [0x2460, 0x249B, ""], + [0x24EA, 0x26AB, ""], + [0x26AD, 0x27FF, ""], + [0x2900, 0x2B73, ""], + [0x2B76, 0x2BFF, ""], + [0x2CE5, 0x2CEA, ""], + [0x2CEF, 0x2CF1, ""], + [0x2CF9, 0x2CFF, ""], + [0x2D7F, 0x2D7F, ""], + [0x2DE0, 0x2E5D, ""], + [0x2E80, 0x2E99, ""], + [0x2E9B, 0x2EF3, ""], + [0x2F00, 0x2FD5, ""], + [0x2FF0, 0x3004, ""], + [0x3008, 0x3020, ""], + [0x302A, 0x302D, ""], + [0x3030, 0x3030, ""], + [0x3036, 0x3037, ""], + [0x303D, 0x303F, ""], + [0x3099, 0x309C, ""], + [0x30A0, 0x30A0, ""], + [0x30FB, 0x30FB, ""], + [0x31C0, 0x31E5, ""], + [0x31EF, 0x31EF, ""], + [0x321D, 0x321E, ""], + [0x3250, 0x325F, ""], + [0x327C, 0x327E, ""], + [0x32B1, 0x32BF, ""], + [0x32CC, 0x32CF, ""], + [0x3377, 0x337A, ""], + [0x33DE, 0x33DF, ""], + [0x33FF, 0x33FF, ""], + [0x4DC0, 0x4DFF, ""], + [0xA490, 0xA4C6, ""], + [0xA60D, 0xA60F, ""], + [0xA66F, 0xA67F, ""], + [0xA69E, 0xA69F, ""], + [0xA6F0, 0xA6F1, ""], + [0xA700, 0xA721, ""], + [0xA788, 0xA788, ""], + [0xA802, 0xA802, ""], + [0xA806, 0xA806, ""], + [0xA80B, 0xA80B, ""], + [0xA825, 0xA826, ""], + [0xA828, 0xA82C, ""], + [0xA838, 0xA839, ""], + [0xA874, 0xA877, ""], + [0xA8C4, 0xA8C5, ""], + [0xA8E0, 0xA8F1, ""], + [0xA8FF, 0xA8FF, ""], + [0xA926, 0xA92D, ""], + [0xA947, 0xA951, ""], + [0xA980, 0xA982, ""], + [0xA9B3, 0xA9B3, ""], + [0xA9B6, 0xA9B9, ""], + [0xA9BC, 0xA9BD, ""], + [0xA9E5, 0xA9E5, ""], + [0xAA29, 0xAA2E, ""], + [0xAA31, 0xAA32, ""], + [0xAA35, 0xAA36, ""], + [0xAA43, 0xAA43, ""], + [0xAA4C, 0xAA4C, ""], + [0xAA7C, 0xAA7C, ""], + [0xAAB0, 0xAAB0, ""], + [0xAAB2, 0xAAB4, ""], + [0xAAB7, 0xAAB8, ""], + [0xAABE, 0xAABF, ""], + [0xAAC1, 0xAAC1, ""], + [0xAAEC, 0xAAED, ""], + [0xAAF6, 0xAAF6, ""], + [0xAB6A, 0xAB6B, ""], + [0xABE5, 0xABE5, ""], + [0xABE8, 0xABE8, ""], + [0xABED, 0xABED, ""], + [0xFB1D, 0xFB1D, "rtl"], + [0xFB1E, 0xFB1E, ""], + [0xFB1F, 0xFB28, "rtl"], + [0xFB29, 0xFB29, ""], + [0xFB2A, 0xFBC2, "rtl"], + [0xFBC3, 0xFBD2, ""], + [0xFBD3, 0xFD3D, "rtl"], + [0xFD3E, 0xFD4F, ""], + [0xFD50, 0xFD8F, "rtl"], + [0xFD90, 0xFD91, ""], + [0xFD92, 0xFDC7, "rtl"], + [0xFDC8, 0xFDEF, ""], + [0xFDF0, 0xFDFC, "rtl"], + [0xFDFD, 0xFE19, ""], + [0xFE20, 0xFE52, ""], + [0xFE54, 0xFE66, ""], + [0xFE68, 0xFE6B, ""], + [0xFE70, 0xFEFE, "rtl"], + [0xFEFF, 0xFEFF, ""], + [0xFF01, 0xFF20, ""], + [0xFF3B, 0xFF40, ""], + [0xFF5B, 0xFF65, ""], + [0xFFE0, 0xFFE6, ""], + [0xFFE8, 0xFFEE, ""], + [0xFFF0, 0xFFFF, ""], + [0x10101, 0x10101, ""], + [0x10140, 0x1018C, ""], + [0x10190, 0x1019C, ""], + [0x101A0, 0x101A0, ""], + [0x101FD, 0x101FD, ""], + [0x102E0, 0x102FB, ""], + [0x10376, 0x1037A, ""], + [0x10800, 0x1091E, "rtl"], + [0x1091F, 0x1091F, ""], + [0x10920, 0x10A00, "rtl"], + [0x10A01, 0x10A03, ""], + [0x10A04, 0x10A04, "rtl"], + [0x10A05, 0x10A06, ""], + [0x10A07, 0x10A0B, "rtl"], + [0x10A0C, 0x10A0F, ""], + [0x10A10, 0x10A37, "rtl"], + [0x10A38, 0x10A3A, ""], + [0x10A3B, 0x10A3E, "rtl"], + [0x10A3F, 0x10A3F, ""], + [0x10A40, 0x10AE4, "rtl"], + [0x10AE5, 0x10AE6, ""], + [0x10AE7, 0x10B38, "rtl"], + [0x10B39, 0x10B3F, ""], + [0x10B40, 0x10D23, "rtl"], + [0x10D24, 0x10D27, ""], + [0x10D28, 0x10D2F, "rtl"], + [0x10D30, 0x10D39, ""], + [0x10D3A, 0x10D3F, "rtl"], + [0x10D40, 0x10D49, ""], + [0x10D4A, 0x10D68, "rtl"], + [0x10D69, 0x10D6E, ""], + [0x10D6F, 0x10E5F, "rtl"], + [0x10E60, 0x10E7E, ""], + [0x10E7F, 0x10EAA, "rtl"], + [0x10EAB, 0x10EAC, ""], + [0x10EAD, 0x10ECF, "rtl"], + [0x10ED0, 0x10ED8, ""], + [0x10ED9, 0x10EF9, "rtl"], + [0x10EFA, 0x10EFF, ""], + [0x10F00, 0x10F45, "rtl"], + [0x10F46, 0x10F50, ""], + [0x10F51, 0x10F81, "rtl"], + [0x10F82, 0x10F85, ""], + [0x10F86, 0x10FFF, "rtl"], + [0x11001, 0x11001, ""], + [0x11038, 0x11046, ""], + [0x11052, 0x11065, ""], + [0x11070, 0x11070, ""], + [0x11073, 0x11074, ""], + [0x1107F, 0x11081, ""], + [0x110B3, 0x110B6, ""], + [0x110B9, 0x110BA, ""], + [0x110C2, 0x110C2, ""], + [0x11100, 0x11102, ""], + [0x11127, 0x1112B, ""], + [0x1112D, 0x11134, ""], + [0x11173, 0x11173, ""], + [0x11180, 0x11181, ""], + [0x111B6, 0x111BE, ""], + [0x111C9, 0x111CC, ""], + [0x111CF, 0x111CF, ""], + [0x1122F, 0x11231, ""], + [0x11234, 0x11234, ""], + [0x11236, 0x11237, ""], + [0x1123E, 0x1123E, ""], + [0x11241, 0x11241, ""], + [0x112DF, 0x112DF, ""], + [0x112E3, 0x112EA, ""], + [0x11300, 0x11301, ""], + [0x1133B, 0x1133C, ""], + [0x11340, 0x11340, ""], + [0x11366, 0x1136C, ""], + [0x11370, 0x11374, ""], + [0x113BB, 0x113C0, ""], + [0x113CE, 0x113CE, ""], + [0x113D0, 0x113D0, ""], + [0x113D2, 0x113D2, ""], + [0x113E1, 0x113E2, ""], + [0x11438, 0x1143F, ""], + [0x11442, 0x11444, ""], + [0x11446, 0x11446, ""], + [0x1145E, 0x1145E, ""], + [0x114B3, 0x114B8, ""], + [0x114BA, 0x114BA, ""], + [0x114BF, 0x114C0, ""], + [0x114C2, 0x114C3, ""], + [0x115B2, 0x115B5, ""], + [0x115BC, 0x115BD, ""], + [0x115BF, 0x115C0, ""], + [0x115DC, 0x115DD, ""], + [0x11633, 0x1163A, ""], + [0x1163D, 0x1163D, ""], + [0x1163F, 0x11640, ""], + [0x11660, 0x1166C, ""], + [0x116AB, 0x116AB, ""], + [0x116AD, 0x116AD, ""], + [0x116B0, 0x116B5, ""], + [0x116B7, 0x116B7, ""], + [0x1171D, 0x1171D, ""], + [0x1171F, 0x1171F, ""], + [0x11722, 0x11725, ""], + [0x11727, 0x1172B, ""], + [0x1182F, 0x11837, ""], + [0x11839, 0x1183A, ""], + [0x1193B, 0x1193C, ""], + [0x1193E, 0x1193E, ""], + [0x11943, 0x11943, ""], + [0x119D4, 0x119D7, ""], + [0x119DA, 0x119DB, ""], + [0x119E0, 0x119E0, ""], + [0x11A01, 0x11A06, ""], + [0x11A09, 0x11A0A, ""], + [0x11A33, 0x11A38, ""], + [0x11A3B, 0x11A3E, ""], + [0x11A47, 0x11A47, ""], + [0x11A51, 0x11A56, ""], + [0x11A59, 0x11A5B, ""], + [0x11A8A, 0x11A96, ""], + [0x11A98, 0x11A99, ""], + [0x11B60, 0x11B60, ""], + [0x11B62, 0x11B64, ""], + [0x11B66, 0x11B66, ""], + [0x11C30, 0x11C36, ""], + [0x11C38, 0x11C3D, ""], + [0x11C92, 0x11CA7, ""], + [0x11CAA, 0x11CB0, ""], + [0x11CB2, 0x11CB3, ""], + [0x11CB5, 0x11CB6, ""], + [0x11D31, 0x11D36, ""], + [0x11D3A, 0x11D3A, ""], + [0x11D3C, 0x11D3D, ""], + [0x11D3F, 0x11D45, ""], + [0x11D47, 0x11D47, ""], + [0x11D90, 0x11D91, ""], + [0x11D95, 0x11D95, ""], + [0x11D97, 0x11D97, ""], + [0x11EF3, 0x11EF4, ""], + [0x11F00, 0x11F01, ""], + [0x11F36, 0x11F3A, ""], + [0x11F40, 0x11F40, ""], + [0x11F42, 0x11F42, ""], + [0x11F5A, 0x11F5A, ""], + [0x11FD5, 0x11FF1, ""], + [0x13440, 0x13440, ""], + [0x13447, 0x13455, ""], + [0x1611E, 0x16129, ""], + [0x1612D, 0x1612F, ""], + [0x16AF0, 0x16AF4, ""], + [0x16B30, 0x16B36, ""], + [0x16F4F, 0x16F4F, ""], + [0x16F8F, 0x16F92, ""], + [0x16FE2, 0x16FE2, ""], + [0x16FE4, 0x16FE4, ""], + [0x1BC9D, 0x1BC9E, ""], + [0x1BCA0, 0x1BCA3, ""], + [0x1CC00, 0x1CCD5, ""], + [0x1CCF0, 0x1CCFC, ""], + [0x1CD00, 0x1CEB3, ""], + [0x1CEBA, 0x1CED0, ""], + [0x1CEE0, 0x1CEF0, ""], + [0x1CF00, 0x1CF2D, ""], + [0x1CF30, 0x1CF46, ""], + [0x1D167, 0x1D169, ""], + [0x1D173, 0x1D182, ""], + [0x1D185, 0x1D18B, ""], + [0x1D1AA, 0x1D1AD, ""], + [0x1D1E9, 0x1D1EA, ""], + [0x1D200, 0x1D245, ""], + [0x1D300, 0x1D356, ""], + [0x1D6C1, 0x1D6C1, ""], + [0x1D6DB, 0x1D6DB, ""], + [0x1D6FB, 0x1D6FB, ""], + [0x1D715, 0x1D715, ""], + [0x1D735, 0x1D735, ""], + [0x1D74F, 0x1D74F, ""], + [0x1D76F, 0x1D76F, ""], + [0x1D789, 0x1D789, ""], + [0x1D7A9, 0x1D7A9, ""], + [0x1D7C3, 0x1D7C3, ""], + [0x1D7CE, 0x1D7FF, ""], + [0x1DA00, 0x1DA36, ""], + [0x1DA3B, 0x1DA6C, ""], + [0x1DA75, 0x1DA75, ""], + [0x1DA84, 0x1DA84, ""], + [0x1DA9B, 0x1DA9F, ""], + [0x1DAA1, 0x1DAAF, ""], + [0x1E000, 0x1E006, ""], + [0x1E008, 0x1E018, ""], + [0x1E01B, 0x1E021, ""], + [0x1E023, 0x1E024, ""], + [0x1E026, 0x1E02A, ""], + [0x1E08F, 0x1E08F, ""], + [0x1E130, 0x1E136, ""], + [0x1E2AE, 0x1E2AE, ""], + [0x1E2EC, 0x1E2EF, ""], + [0x1E2FF, 0x1E2FF, ""], + [0x1E4EC, 0x1E4EF, ""], + [0x1E5EE, 0x1E5EF, ""], + [0x1E6E3, 0x1E6E3, ""], + [0x1E6E6, 0x1E6E6, ""], + [0x1E6EE, 0x1E6EF, ""], + [0x1E6F5, 0x1E6F5, ""], + [0x1E800, 0x1E8CF, "rtl"], + [0x1E8D0, 0x1E8D6, ""], + [0x1E8D7, 0x1E943, "rtl"], + [0x1E944, 0x1E94A, ""], + [0x1E94B, 0x1EEEF, "rtl"], + [0x1EEF0, 0x1EEF1, ""], + [0x1EEF2, 0x1EFFF, "rtl"], + [0x1F000, 0x1F02B, ""], + [0x1F030, 0x1F093, ""], + [0x1F0A0, 0x1F0AE, ""], + [0x1F0B1, 0x1F0BF, ""], + [0x1F0C1, 0x1F0CF, ""], + [0x1F0D1, 0x1F0F5, ""], + [0x1F100, 0x1F10F, ""], + [0x1F12F, 0x1F12F, ""], + [0x1F16A, 0x1F16F, ""], + [0x1F1AD, 0x1F1AD, ""], + [0x1F260, 0x1F265, ""], + [0x1F300, 0x1F6D8, ""], + [0x1F6DC, 0x1F6EC, ""], + [0x1F6F0, 0x1F6FC, ""], + [0x1F700, 0x1F7D9, ""], + [0x1F7E0, 0x1F7EB, ""], + [0x1F7F0, 0x1F7F0, ""], + [0x1F800, 0x1F80B, ""], + [0x1F810, 0x1F847, ""], + [0x1F850, 0x1F859, ""], + [0x1F860, 0x1F887, ""], + [0x1F890, 0x1F8AD, ""], + [0x1F8B0, 0x1F8BB, ""], + [0x1F8C0, 0x1F8C1, ""], + [0x1F8D0, 0x1F8D8, ""], + [0x1F900, 0x1FA57, ""], + [0x1FA60, 0x1FA6D, ""], + [0x1FA70, 0x1FA7C, ""], + [0x1FA80, 0x1FA8A, ""], + [0x1FA8E, 0x1FAC6, ""], + [0x1FAC8, 0x1FAC8, ""], + [0x1FACD, 0x1FADC, ""], + [0x1FADF, 0x1FAEA, ""], + [0x1FAEF, 0x1FAF8, ""], + [0x1FB00, 0x1FB92, ""], + [0x1FB94, 0x1FBFA, ""], + [0x1FFFE, 0x1FFFF, ""], + [0x2FFFE, 0x2FFFF, ""], + [0x3FFFE, 0x3FFFF, ""], + [0x4FFFE, 0x4FFFF, ""], + [0x5FFFE, 0x5FFFF, ""], + [0x6FFFE, 0x6FFFF, ""], + [0x7FFFE, 0x7FFFF, ""], + [0x8FFFE, 0x8FFFF, ""], + [0x9FFFE, 0x9FFFF, ""], + [0xAFFFE, 0xAFFFF, ""], + [0xBFFFE, 0xBFFFF, ""], + [0xCFFFE, 0xCFFFF, ""], + [0xDFFFE, 0xE0FFF, ""], + [0xEFFFE, 0xEFFFF, ""], + [0xFFFFE, 0xFFFFF, ""], + [0x10FFFE, 0x10FFFF, ""] +] diff --git a/ui/tests/test_direction.js b/ui/tests/test_direction.js index 73bf035d1..da0412126 100644 --- a/ui/tests/test_direction.js +++ b/ui/tests/test_direction.js @@ -3,6 +3,20 @@ const { load } = require("./load") const direction = load("message/Direction.js") +for (const code of [0x05b0, 0x064b, 0x037e, 0x10d40, 0x20c1]) { + const prefix = String.fromCodePoint(code) + assert.strictEqual(direction.directionOfCode(code), "", "non-strong Unicode class " + code.toString(16)) + assert.strictEqual(direction.strongDirectionOf(prefix + "hello"), "ltr") + assert.strictEqual(direction.strongDirectionOf(prefix + "שלום"), "rtl") +} +for (const code of [0x00aa, 0x2102, 0x1f1e6]) { + assert.strictEqual(direction.directionOfCode(code), "ltr", "Unicode L class " + code.toString(16)) + assert.strictEqual(direction.strongDirectionOf(String.fromCodePoint(code) + "שלום"), "ltr") +} +for (const code of [0x0590, 0x086b, 0x10ec0]) { + assert.strictEqual(direction.directionOfCode(code), "rtl", "reserved RTL default " + code.toString(16)) +} + // ------------------------------------------------------------ first strong assert.strictEqual(direction.strongDirectionOf("Hello world"), "ltr") @@ -45,11 +59,10 @@ assert.strictEqual(direction.strongDirectionOf("\uFEFC"), "rtl", "and the last character that really is one still is") // An emoji in front of the subject is how most marketing mail is written, and -// every one of them is Other Neutral: it says nothing about the sentence after -// it. The same goes for the combining marks, the supplemental punctuation and -// the fullwidth punctuation, none of which are letters. +// pictographs are neutral, while regional indicator symbols have class L. +// Combining marks and punctuation also defer to a later strong character. assert.strictEqual(direction.strongDirectionOf("🎉 مرحبا"), "rtl", "an emoji is neutral") -assert.strictEqual(direction.strongDirectionOf("🇸🇦 مرحبا"), "rtl", "so is a flag") +assert.strictEqual(direction.strongDirectionOf("🇸🇦 مرحبا"), "ltr", "regional indicators have Unicode class L") assert.strictEqual(direction.strongDirectionOf("🎉 Hello"), "ltr") assert.strictEqual(direction.strongDirectionOf("\u0301 مرحبا"), "rtl", "a combining mark is neutral") assert.strictEqual(direction.strongDirectionOf("\uFF01 مرحبا"), "rtl", "fullwidth punctuation is neutral") @@ -211,4 +224,20 @@ assert.strictEqual(direction.resolveBody("Hello [image 1] مرحبا", "Auto"), assert.strictEqual(direction.resolveBody("[image 1]Hello", "Right to left"), "rtl") assert.strictEqual(direction.resolveBody("مرحبا", "Left to right"), "ltr") +const { spawnSync } = require("child_process") +const path = require("path") +const generator = path.join(__dirname, "../../scripts/generate-direction-data.py") +const checked = spawnSync("python3", [generator, "--check"], { encoding: "utf8" }) +assert.strictEqual(checked.status, 0, checked.stderr) +const reference = spawnSync("python3", [generator, "--classes"], { maxBuffer: 2 * 1024 * 1024 }) +assert.strictEqual(reference.status, 0, String(reference.stderr)) +assert.strictEqual(reference.stdout.length, 0x110000) +for (var code = 0; code < reference.stdout.length; code++) { + const expected = code >= 0xD800 && code <= 0xDFFF ? "" : ["", "ltr", "rtl"][reference.stdout[code]] + assert.strictEqual(direction.directionOfCode(code), expected, "Unicode class U+" + code.toString(16)) +} +for (const code of [-1, 1.5, 0x110000, NaN, Infinity, "65", null]) { + assert.strictEqual(direction.directionOfCode(code), "", "invalid code point must not assert a direction") +} + console.log("direction tests passed") From fe62179b6535e41a3cc48630f4f07cbcda50ecef Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 145/568] Name Unicode direction policy and scalar lookup --- scripts/generate-direction-data.py | 21 +++-- src/message/direction.rs | 20 +++-- ui/message/Direction.js | 128 +++-------------------------- 3 files changed, 34 insertions(+), 135 deletions(-) diff --git a/scripts/generate-direction-data.py b/scripts/generate-direction-data.py index b3127762b..0e8247204 100644 --- a/scripts/generate-direction-data.py +++ b/scripts/generate-direction-data.py @@ -12,15 +12,18 @@ SOURCE = ROOT / "data/unicode" / f"DerivedBidiClass-{VERSION}.txt.gz" SHA256 = "4867b4b7f0731ed1bfcd34cc6251211ff1542541fce0734b6fbda139ee80b3a4" CODE_POINTS = 0x110000 +NEUTRAL = 0 +LEFT_TO_RIGHT = 1 +RIGHT_TO_LEFT = 2 ENTRY = r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*([A-Za-z_]+)" -def direction(name): +def strong_class(name): if name in ("L", "Left_To_Right"): - return 1 + return LEFT_TO_RIGHT if name in ("R", "AL", "Right_To_Left", "Arabic_Letter"): - return 2 - return 0 + return RIGHT_TO_LEFT + return NEUTRAL def classes(): @@ -28,13 +31,13 @@ def classes(): if hashlib.sha256(source).hexdigest() != SHA256: raise ValueError("Pinned Unicode source hash mismatch") text = source.decode("utf-8") - result = bytearray([1]) * CODE_POINTS + result = bytearray([LEFT_TO_RIGHT]) * CODE_POINTS # Unicode's missing defaults apply before any explicit class assignment. for pattern in (r"^# @missing:\s*" + ENTRY, r"^" + ENTRY): for match in re.finditer(pattern, text, re.MULTILINE): start = int(match[1], 16) end = int(match[2] or match[1], 16) - result[start:end + 1] = bytes([direction(match[3])]) * (end - start + 1) + result[start:end + 1] = bytes([strong_class(match[3])]) * (end - start + 1) return result @@ -44,8 +47,8 @@ def ranges(values): for end in range(1, len(values) + 1): if end < len(values) and values[start] == values[end]: continue - if values[start] != 1: - result.append((start, end - 1, "rtl" if values[start] == 2 else "")) + if values[start] != LEFT_TO_RIGHT: + result.append((start, end - 1, "rtl" if values[start] == RIGHT_TO_LEFT else "")) start = end return result @@ -69,7 +72,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) mode = parser.add_mutually_exclusive_group() mode.add_argument("--check", action="store_true", help="verify checked-in tables without writing") - mode.add_argument("--classes", action="store_true", help="emit one class byte per code point for exhaustive tests") + mode.add_argument("--classes", action="store_true", help="emit one byte per code point:0=non-strong,1=L,2=R/AL") args = parser.parse_args() values = classes() if args.classes: diff --git a/src/message/direction.rs b/src/message/direction.rs index 77d5b8f28..860b2aa57 100644 --- a/src/message/direction.rs +++ b/src/message/direction.rs @@ -53,9 +53,9 @@ pub fn strong_direction(text: &str) -> &'static str { 0x202a | 0x202d => return LTR, _ => (), } - let answer = direction_of_code(code); - if !answer.is_empty() { - return answer; + let direction = direction_of_code(code); + if !direction.is_empty() { + return direction; } } "" @@ -70,7 +70,9 @@ static PREFIX: LazyLock = LazyLock::new(|| { }); pub fn without_reply_prefixes(mut text: &str) -> &str { for _ in 0..12 { - let Some(m) = PREFIX.find(text) else { break }; + let Some(prefix) = PREFIX.find(text) else { + break; + }; let visible = text.trim_start_matches(|c: char| { c.is_whitespace() || matches!(c, '\u{feff}' | '\u{200e}' | '\u{200f}') }); @@ -81,7 +83,7 @@ pub fn without_reply_prefixes(mut text: &str) -> &str { { break; } - text = &text[m.end()..]; + text = &text[prefix.end()..]; } text } @@ -246,9 +248,9 @@ mod tests { let output = child.wait_with_output().unwrap(); assert!(output.status.success()); let expected: Value = serde_json::from_slice(&output.stdout).unwrap(); - for (n, c) in cases.iter().enumerate() { - let text = c["text"].as_str().unwrap(); - let mode = c["mode"].as_str().unwrap(); + for (index, case) in cases.iter().enumerate() { + let text = case["text"].as_str().unwrap(); + let mode = case["mode"].as_str().unwrap(); assert_eq!( json!([ resolve(text, mode), @@ -256,7 +258,7 @@ mod tests { resolve_body(text, mode), without_reply_prefixes(text) ]), - expected[n], + expected[index], "{text:?} {mode}" ) } diff --git a/ui/message/Direction.js b/ui/message/Direction.js index 98d95e180..4708d8e1a 100644 --- a/ui/message/Direction.js +++ b/ui/message/Direction.js @@ -1,54 +1,16 @@ .pragma library .import "DirectionData.js" as Bidi -// Which way a piece of a message runs. -// -// Qt already resolves a paragraph's direction from its first strong character, -// and it does it well: an Arabic body, an Arabic line inside a Latin one, and a -// Hebrew subject in a `Text` all come out right without being told. This module -// exists for the three places that answer is wrong or unavailable. -// -// 1. A reply prefix is Latin. `Re: مرحبا` has a strong `R` in front of it, so -// first-strong says left-to-right and the whole subject aligns against the -// wrong edge for every message in a thread after the first — which is most -// of them. The prefix is not part of what the subject says, so it is not -// part of what decides which way the subject runs. -// 2. Qt's rich text engine honours the `dir` attribute and ignores the CSS -// `direction` property. A sender who writes `style="direction:rtl"` — which -// is what a mail template built for a browser writes — gets a left-to-right -// layout with the text jammed against the wrong margin. Html.js translates -// one spelling into the other, and needs this module to know what it is -// translating to. -// 3. A reader may want the answer overridden. First-strong is a guess about a -// document, and a mailbox that is mostly one direction is better served by -// saying so once than by having the guess re-made per message. -// -// The rules here are the ones from the Unicode bidirectional algorithm (UAX #9) -// that decide a paragraph's direction — P2, "find the first character of type -// L, AL, or R while skipping over any characters between an isolate initiator -// and its matching PDI", and P3, "if a character is found in P2 and it is of -// type AL or R, then set the paragraph level to one; otherwise, set it to -// zero". Not the whole algorithm: the rest of it is Qt's job and Qt does it. - -// ----------------------------------------------------------------- the modes -// -// What the setting stores. Spelled as the words the settings schema shows, -// because the shell hands a plugin the label the user picked rather than a key -// behind it — the same arrangement `heavyMessageRendering` already uses. +// Qt handles paragraph layout; this module excludes client-added subject/body +// prefixes and applies the user's direction preference. Modes match settings labels. var AUTO = "Auto" var LEFT_TO_RIGHT = "Left to right" var RIGHT_TO_LEFT = "Right to left" var MODE_DEFAULT = AUTO -// What a resolved answer is. Lowercase because these are also what goes into -// the `dir` attribute, and a document that carried `dir="Right to left"` would -// be silently ignored rather than loudly wrong. var LTR = "ltr" var RTL = "rtl" -// No strong character at all: a subject that is a number, a body that is a -// row of dashes. The caller decides what to do with it, because "unknown" and -// "left-to-right" are the same rendering but not the same fact — a document -// gets no `dir` at all rather than one asserting a direction nobody chose. +// An absent answer leaves Qt free to resolve each paragraph. var UNKNOWN = "" function normalizeMode(value) { @@ -85,8 +47,8 @@ function directionOfCode(code) { return LTR } -// P2, as far as it goes here: the first strong character wins, an isolate is -// skipped over as a unit, and an embedding or an override answers on its own. +// Skip isolates for first-strong selection. Preserve the app's explicit +// embedding/override policy; Qt handles the remaining bidirectional algorithm. function strongDirectionOf(text) { var source = String(text === undefined || text === null ? "" : text) var depth = 0 @@ -94,8 +56,6 @@ function strongDirectionOf(text) { for (var characterIndex = 0; characterIndex < source.length; characterIndex++) { var code = source.charCodeAt(characterIndex) - // A surrogate pair is one character. Reading its halves as two would put - // an Adlam or Kharoshthi message on the wrong side of the window. if (code >= 0xD800 && code <= 0xDBFF && characterIndex + 1 < source.length) { var low = source.charCodeAt(characterIndex + 1) if (low >= 0xDC00 && low <= 0xDFFF) { @@ -104,8 +64,6 @@ function strongDirectionOf(text) { } } - // Inside an isolate the text is deliberately sealed off from the paragraph - // it sits in, so nothing in it may decide the paragraph's own direction. if (code === LEFT_TO_RIGHT_ISOLATE || code === RIGHT_TO_LEFT_ISOLATE || code === FIRST_STRONG_ISOLATE) { depth++ @@ -117,8 +75,6 @@ function strongDirectionOf(text) { } if (depth > 0) continue - // An embedding or an override is the author saying which way this runs - // rather than leaving it to be worked out. if (code === RIGHT_TO_LEFT_EMBEDDING || code === RIGHT_TO_LEFT_OVERRIDE) return RTL if (code === LEFT_TO_RIGHT_EMBEDDING || code === LEFT_TO_RIGHT_OVERRIDE) return LTR @@ -128,38 +84,20 @@ function strongDirectionOf(text) { return UNKNOWN } -// --------------------------------------------------------------- a subject -// -// What a mail client puts in front of a subject is not part of the subject. -// `Re:` and `Fwd:` are the two that English writes, but a thread crosses -// clients and locales, so a reply from a German Outlook arrives as `AW:` and -// one from a French client as `RE:` or `TR:`. A mailing list adds `[list-name]` -// in front of whatever is already there. -// -// Listed rather than generalised to "any short word before a colon": that rule -// would also eat the `Bug:` off a subject line, and while stripping it happens -// to give the same answer here, a rule that quietly rewrites what it was asked -// about is the wrong shape for something this small. +// Only recognized client prefixes and list tags are skipped; an arbitrary +// word before a colon is part of the subject. var REPLY_PREFIX = new RegExp( "^[\\s\\u200E\\u200F]*(?:" - // Re, Fw, Fwd and their translations, with the optional `[2]` or `(3)` - // count that a client adds when a thread goes round more than once. + "(?:re|aw|sv|vs|vl|antw|antwort|fw|fwd|wg|tr|rv|rif|res|enc|encaminhado" + "|doorst|odp|ynt|ilt|回复|回覆|转发|轉發)" + "\\s*(?:[\\[\\(]\\s*\\d+\\s*[\\]\\)])?\\s*:" - // A mailing list tag, which carries no direction of its own worth having. + "|\\[[^\\]]{0,64}\\]" - // The parenthesised form some clients use instead of a prefix. + "|\\((?:fwd|fw)\\)" + ")[\\s\\u200E\\u200F]*", "i") -// Strips every prefix, not just the first: a thread that has been replied to -// and then forwarded arrives as `Fwd: Re: ...`, and one off a list as -// `[team] Re: ...`. function withoutReplyPrefixes(subject) { var text = String(subject === undefined || subject === null ? "" : subject) - // Bounded rather than `while (true)`: the expression can match empty on a - // pathological subject, and a body of mail is not the place to find out. + // Limit cleanup work for untrusted stacks of client-added prefixes. for (var index = 0; index < 12; index++) { var stripped = text.replace(REPLY_PREFIX, "") if (stripped === text) break @@ -168,22 +106,10 @@ function withoutReplyPrefixes(subject) { return text } -// The direction of what a subject actually says. -// -// A subject that is nothing but prefixes — `Re:`, or `Re: 2024` — answers -// UNKNOWN rather than reading the prefix back as the answer. The prefix is -// strong left-to-right and would give `ltr`, which is also what Qt does with -// the unaltered string, so the two render the same; UNKNOWN is the one that -// does not claim the choice was made on the subject's own account. function subjectDirectionOf(subject) { return strongDirectionOf(withoutReplyPrefixes(subject)) } -// ------------------------------------------------------------ the decision -// -// One entry point for the views: hand it the text and the mode, get back what -// to draw. An explicit mode never looks at the text, which is the point of -// having one. function resolve(text, mode) { var chosen = normalizeMode(mode) if (chosen === RIGHT_TO_LEFT) return RTL @@ -191,14 +117,7 @@ function resolve(text, mode) { return strongDirectionOf(text) } -// The direction the mode names on its own, without reading any text: RTL or -// LTR for a chosen one, UNKNOWN for Auto. -// -// This is what the fields Qt already gets right should be given. A sender's -// name, a recipient list and a one-line snippet all resolve correctly from -// their own first strong character, so on Auto there is nothing to add and the -// view leaves them alone; a chosen direction still has to reach them, because -// choosing one and having half the message ignore it is not a choice. +// Auto leaves native Qt fields to resolve their own content direction. function forced(mode) { var chosen = normalizeMode(mode) if (chosen === RIGHT_TO_LEFT) return RTL @@ -213,18 +132,7 @@ function resolveSubject(subject, mode) { return subjectDirectionOf(subject) } -// ------------------------------------------------------------------ a body - -// The plain reading of a message is not only the sender's words. `Html.js` -// flattens a document by writing `[image 1]` where a picture stood, and a -// remote image is blocked until the reader asks for it — so an HTML newsletter -// that opens with a logo, which is most of them, hands this a string beginning -// with a Latin `i` that omamail wrote itself. -// -// That is the same mistake as reading `Re:` as part of a subject, on the body -// side: a marker this client put there is not the message saying which way it -// runs. It is removed before the question is asked, and only from the front, -// because a marker further in sits after whatever already answered. +// Generated image markers are client text and must not choose body direction. var IMAGE_MARKERS = /^(?:\s*\[image(?:\s+\d+)?\])+/ function withoutImageMarkers(text) { @@ -238,12 +146,6 @@ function resolveBody(text, mode) { return strongDirectionOf(withoutImageMarkers(text)) } -// ---------------------------------------------------------- what QML needs -// -// A `Text` whose `horizontalAlignment` is never set follows the direction of -// its own text, which is the behaviour to keep wherever the answer is UNKNOWN. -// These say which edge to use only when there is an answer; the view leaves the -// property alone otherwise rather than asserting Qt's own default back at it. function alignsRight(direction) { return String(direction) === RTL } @@ -252,20 +154,12 @@ function hasAnswer(direction) { return String(direction) === RTL || String(direction) === LTR } -// ---------------------------------------------------------- what HTML needs -// -// The attribute, ready to be concatenated into a tag. Empty for UNKNOWN, so a -// document with nothing strong in it keeps Qt's per-paragraph resolution rather -// than being pinned to a direction by a wrapper. function attributeFor(direction) { if (!hasAnswer(direction)) return "" return " dir=\"" + String(direction) + "\"" } -// Which physical edge a direction starts and ends on. The document stylesheets -// are written in physical properties because that is all Qt's rich text engine -// reads — it has no `margin-inline-start` — so the side has to be chosen when -// the sheet is built rather than left to the renderer. +// Qt rich text uses physical margin properties, not margin-inline-start/end. function startEdge(direction) { return alignsRight(direction) ? "right" : "left" } From b3166bb2b78a0da5e0b00cb0e92c2d9d6069bb70 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 146/568] Add bundled Unicode license retrieval to the CLI --- src/cli/mod.rs | 13 ++++++++++++- tests/licenses.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 tests/licenses.rs diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 3d23047df..d4fdc685c 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -50,6 +50,8 @@ enum Command { Info, /// Print the executable version Version, + /// Print the bundled Unicode data license notice + Licenses, /// Inspect desktop accounts without exposing credentials Accounts { #[command(subcommand)] @@ -100,6 +102,15 @@ pub fn run() { println!(); return; }; + if matches!(command, Command::Licenses) { + let unicode = include_str!("../../data/unicode/LICENSE.txt"); + if cli.json { + println!("{}", serde_json::json!({"unicode": unicode})); + } else { + print!("{unicode}"); + } + return; + } if matches!(command, Command::Serve) { if cli.json { Cli::command() @@ -187,7 +198,7 @@ pub fn run() { } Command::Call { method } => call::read_params(io::stdin()) .and_then(|params| runtime.block_on(call::dispatch(&session, &method, ¶ms))), - Command::Serve => unreachable!(), + Command::Serve | Command::Licenses => unreachable!(), #[cfg(all(feature = "agent", unix))] Command::AgentWorker { .. } => unreachable!(), #[cfg(all(feature = "agent", unix))] diff --git a/tests/licenses.rs b/tests/licenses.rs new file mode 100644 index 000000000..c5892dd1a --- /dev/null +++ b/tests/licenses.rs @@ -0,0 +1,35 @@ +use serde_json::Value; +use std::{fs, process::Command}; + +#[test] +fn unicode_notice_is_retrievable_without_account_state() { + let home = std::env::temp_dir().join(format!("omamail-license-test-{}", std::process::id())); + fs::create_dir(&home).unwrap(); + let expected = include_str!("../data/unicode/LICENSE.txt"); + for arguments in [vec!["licenses"], vec!["licenses", "--json"]] { + let output = Command::new(env!("CARGO_BIN_EXE_omamail")) + .args(&arguments) + .current_dir(&home) + .env("HOME", &home) + .env("XDG_CONFIG_HOME", &home) + .env("XDG_DATA_HOME", &home) + .env("XDG_CACHE_HOME", &home) + .env("XDG_STATE_HOME", &home) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty()); + let notice = if arguments.len() == 1 { + String::from_utf8(output.stdout).unwrap() + } else { + serde_json::from_slice::(&output.stdout).unwrap()["unicode"] + .as_str() + .unwrap() + .to_owned() + }; + assert_eq!(notice, expected); + assert!(notice.contains("COPYRIGHT AND PERMISSION NOTICE")); + assert!(fs::read_dir(&home).unwrap().next().is_none()); + } + fs::remove_dir(home).unwrap(); +} From 88c7032211e02837296fdd3a827862372f1c6b0a Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 147/568] Fix recipient, calendar and MIME parser boundaries --- ui/message/Calendar.js | 46 +++++++++++------ ui/message/Mailto.js | 2 +- ui/message/Message.js | 98 +++++++++++++++++++----------------- ui/message/Unsubscribe.js | 2 +- ui/tests/test_calendar.js | 32 ++++++++++++ ui/tests/test_mailto.js | 11 +++- ui/tests/test_message.js | 33 ++++++++++++ ui/tests/test_unsubscribe.js | 13 ++++- 8 files changed, 171 insertions(+), 66 deletions(-) diff --git a/ui/message/Calendar.js b/ui/message/Calendar.js index 582562d4a..7f4da4224 100644 --- a/ui/message/Calendar.js +++ b/ui/message/Calendar.js @@ -149,7 +149,7 @@ function parse(text) { var open = stack.length > 0 ? stack[stack.length - 1] : null if (property.name === "BEGIN") { - if (stack.length >= MAX_COMPONENT_DEPTH) continue + if (stack.length >= MAX_COMPONENT_DEPTH) return null var child = { name: String(property.value || "").toUpperCase().trim(), properties: [], @@ -169,6 +169,7 @@ function parse(text) { if (property.name === "END") { if (stack.length === 0) continue + if (open.name !== String(property.value || "").toUpperCase().trim()) return null var closing = stack.pop() var parent = stack.length > 0 ? stack[stack.length - 1] : null // The whole of the child, not the line that closed it. A component's @@ -315,7 +316,7 @@ function parseDateValue(value) { utc: match[7] === "Z", dateOnly: match[4] === undefined } - if (fields.month < 1 || fields.month > 12 || fields.day < 1 || fields.day > 31) return null + if (fields.month < 1 || fields.month > 12 || fields.day < 1 || fields.day > daysInMonth(fields.year, fields.month)) return null if (fields.hour > 23 || fields.minute > 59 || fields.second > 60) return null return fields } @@ -323,8 +324,12 @@ function parseDateValue(value) { function parseOffsetMinutes(value) { var match = String(value || "").trim().match(/^([+-])(\d{2})(\d{2})(\d{2})?$/) if (!match) return null - var minutes = Number(match[2]) * 60 + Number(match[3]) - return match[1] === "-" ? -minutes : minutes + var hours = Number(match[2]) + var minutes = Number(match[3]) + var seconds = Number(match[4] || 0) + if (hours > 23 || minutes > 59 || seconds > 59) return null + var total = hours * 60 + minutes + seconds / 60 + return match[1] === "-" ? -total : total } // The naive local time as a number that sorts: comparing two of these compares @@ -336,7 +341,8 @@ function naiveKey(fields) { } function daysInMonth(year, month) { - return new Date(Date.UTC(year, month, 0)).getUTCDate() + if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28 + return [4, 6, 9, 11].indexOf(month) >= 0 ? 30 : 31 } // "the second Sunday in March", "the last Sunday in October". Ordinal 0 means @@ -1173,19 +1179,29 @@ function normalizedResponse(value) { return PARTSTATS[text] ? text : "" } -// RFC 5545 folds at 75 octets. Folded on characters here, at 72, which is -// short enough that the multi-byte ones this counts as single cannot push a -// line past the limit. function foldIcsLine(line) { var text = String(line || "") - if (text.length <= 72) return text - var out = text.substring(0, 72) - var rest = text.substring(72) - while (rest.length > 71) { - out += "\r\n " + rest.substring(0, 71) - rest = rest.substring(71) + var result = "" + var octets = 0 + for (var i = 0; i < text.length; i++) { + var code = text.charCodeAt(i) + var character = text.charAt(i) + var size = code < 0x80 ? 1 : (code < 0x800 ? 2 : 3) + if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) { + var low = text.charCodeAt(i + 1) + if (low >= 0xdc00 && low <= 0xdfff) { + character += text.charAt(++i) + size = 4 + } + } + if (octets + size > 75) { + result += "\r\n " + octets = 1 + } + result += character + octets += size } - return rest === "" ? out : out + "\r\n " + rest + return result } function icsTimestamp(ms) { diff --git a/ui/message/Mailto.js b/ui/message/Mailto.js index 67084dcc5..dfd30e304 100644 --- a/ui/message/Mailto.js +++ b/ui/message/Mailto.js @@ -11,7 +11,7 @@ // field. The body is allowed them — that is what a body is. function percentDecode(value) { - var text = String(value || "").replace(/\+/g, " ") + var text = String(value || "") try { return decodeURIComponent(text) } catch (e) { diff --git a/ui/message/Message.js b/ui/message/Message.js index c10fddb29..a08a22aed 100644 --- a/ui/message/Message.js +++ b/ui/message/Message.js @@ -299,45 +299,56 @@ function unquote(value) { // "Jane Doe ", "" and a bare address all // have to end up as the same shape. +function addressSyntax(value) { + return String(value || "").replace(/=\?[^?\s]+\?[bq]\?[^?]*\?=/gi, function(word) { + return new Array(word.length + 1).join(" ") + }) +} + function parseAddress(value) { - var raw = decodeHeaderValue(value).trim() + var raw = String(value || "").trim() if (!raw) return { name: "", email: "", display: "" } - var angled = raw.match(/^(.*)<([^>]*)>\s*$/) - var name = "" - var email = "" - if (angled) { - name = unquote(angled[1]) - email = angled[2].trim() - } else { - email = raw.replace(/^\s*<|>\s*$/g, "").trim() - } + var syntax = addressSyntax(raw) + var angled = syntax.match(/^(.*)<([^<>]*)>\s*$/) + var name = angled ? decodeHeaderValue(unquote(raw.substring(0, angled[1].length))) : "" + var email = angled ? angled[2].trim() : syntax.trim() + if (!/^(?:"(?:[^"\\]|\\.)*"|[^\s<>()\[\],;:@"\\]+)@(?:\[[^\r\n\]]+\]|[^\s<>()\[\],;:@"\\]+)$/.test(email)) email = "" + if (!name && email === "") name = decodeHeaderValue(unquote(raw)) if (!name && email.indexOf("@") > 0) name = email.substring(0, email.indexOf("@")) return { name: name, email: email, display: name || email } } function parseAddressList(value) { var raw = String(value || "") + var syntax = addressSyntax(raw) var entries = [] - var current = "" + var start = 0 var inQuotes = false var inAngle = false - for (var i = 0; i < raw.length; i++) { - var character = raw.charAt(i) + for (var i = 0; i < syntax.length; i++) { + var character = syntax.charAt(i) + if (inQuotes && character === "\\") { + i++ + continue + } if (character === "\"") inQuotes = !inQuotes - else if (character === "<") inAngle = true + if (inQuotes) continue + if (character === "<") inAngle = true else if (character === ">") inAngle = false - if (character === "," && !inQuotes && !inAngle) { - entries.push(current) - current = "" + if (inAngle) continue + if (character === ":") { + start = i + 1 continue } - current += character + if (character !== "," && character !== ";") continue + entries.push(raw.substring(start, i)) + start = i + 1 } - entries.push(current) + entries.push(raw.substring(start)) var result = [] for (var j = 0; j < entries.length; j++) { - if (!entries[j].trim()) continue - result.push(parseAddress(entries[j])) + var parsed = parseAddress(entries[j]) + if (parsed.email !== "") result.push(parsed) } return result } @@ -622,10 +633,16 @@ function headerFrom(headers, name) { // (name*0=, name*1=) are not handled: they appear on long filenames, and a // truncated filename is a smaller loss than a parser that guesses. function contentTypeParam(value, name) { - var pattern = new RegExp(name + "\\s*=\\s*(\"([^\"]*)\"|([^;\\s]+))", "i") - var match = String(value || "").match(pattern) - if (!match) return "" - return (match[2] !== undefined ? match[2] : match[3] || "").trim() + var text = String(value || "") + var wanted = String(name || "").toLowerCase() + var parameter = /;\s*([^=;\s]+)\s*=\s*("(?:[^"\\]|\\.)*"|[^;\s]*)/g + var match + while ((match = parameter.exec(text)) !== null) { + if (match[1].toLowerCase() !== wanted) continue + var found = match[2] + return found.charAt(0) === "\"" ? unquote(found) : found.trim() + } + return "" } function mimeTypeOf(contentType) { @@ -641,29 +658,18 @@ function mimeTypeOf(contentType) { // part of the message. function splitMultipart(body, boundary) { var text = String(body || "") - var marker = "--" + String(boundary || "") - if (boundary === "" || boundary === undefined || boundary === null) return [] - + var marker = String(boundary || "") + if (marker === "") return [] + var delimiter = new RegExp("^--" + marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "([^\\r\\n]*)(?:\\r?\\n|$)", "gm") var parts = [] - var index = text.indexOf(marker) - if (index < 0) return [] - - while (index >= 0) { - var afterMarker = index + marker.length - // The closing delimiter is the boundary followed by "--". - if (text.substr(afterMarker, 2) === "--") break - var start = text.indexOf("\n", afterMarker) - if (start < 0) break - start += 1 - var next = text.indexOf(marker, start) - var end = next < 0 ? text.length : next - // The CRLF that precedes the next delimiter belongs to the delimiter, not - // to the part — a body that keeps it gains a trailing blank line, and a - // base64 part gains bytes that were never in the attachment. - var chunk = text.substring(start, end).replace(/\r?\n$/, "") - parts.push(chunk) - index = next + var start = -1 + var match + while ((match = delimiter.exec(text)) !== null) { + if (start >= 0) parts.push(text.substring(start, match.index).replace(/\r?\n$/, "")) + if (match[1].substring(0, 2) === "--") return parts + start = delimiter.lastIndex } + if (start >= 0 && start < text.length) parts.push(text.substring(start).replace(/\r?\n$/, "")) return parts } diff --git a/ui/message/Unsubscribe.js b/ui/message/Unsubscribe.js index 85418e37b..2302b0cd1 100644 --- a/ui/message/Unsubscribe.js +++ b/ui/message/Unsubscribe.js @@ -46,7 +46,7 @@ function entries(value) { // ------------------------------------------------------------------ mailto function percentDecode(value) { - var text = String(value || "").replace(/\+/g, " ") + var text = String(value || "") try { return decodeURIComponent(text) } catch (e) { diff --git a/ui/tests/test_calendar.js b/ui/tests/test_calendar.js index f41bff318..7d5f8eddc 100644 --- a/ui/tests/test_calendar.js +++ b/ui/tests/test_calendar.js @@ -743,4 +743,36 @@ assert.strictEqual(feedEvents[0].summary, "Morning review") assert.strictEqual(feedEvents[1].uid, "second") assert.strictEqual(feedEvents[1].start.allDay, true) + + +{ + for(const value of ['20260231T120000Z','20260229','19000229','20260431']) assert.strictEqual(calendar.parseDateValue(value),null,value) + assert.strictEqual(calendar.parseDateValue('20000229').day,29) + assert.strictEqual(calendar.parseDateValue('20240229').day,29) +} + +{ + const lines=['BEGIN:VCALENDAR','BEGIN:VEVENT','UID:outer'] + for(let i=0;i<8;i++)lines.push('BEGIN:X-NEST') + lines.push('END:X-NEST','ORGANIZER:mailto:promoted@example.test') + assert.strictEqual(calendar.invitationFrom(lines.join('\r\n')),null) + assert.strictEqual(calendar.parse('BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nEND:VTIMEZONE\r\nEND:VCALENDAR'),null) +} + +{ + for(const line of ['SUMMARY:'+ '界'.repeat(80),'SUMMARY:'+ 'a'.repeat(61)+'😀'.repeat(30),'SUMMARY:'+ 'é'.repeat(80)]) { + const folded=calendar.foldIcsLine(line) + assert.strictEqual(folded.replace(/\r\n /g,''),line) + for(const part of folded.split('\r\n')) { + assert.ok(Buffer.byteLength(part)<=75,Buffer.byteLength(part)+' octets') + assert.ok(!/[\uD800-\uDBFF]$/.test(part),'surrogate split') + } + } +} + +{ + for(const offset of ['+2460','-0060','+126199']) assert.strictEqual(calendar.parseOffsetMinutes(offset),null,offset) + assert.strictEqual(calendar.parseOffsetMinutes('+010521'),65.35) +} + console.log("test_calendar.js ok") diff --git a/ui/tests/test_mailto.js b/ui/tests/test_mailto.js index 61e655caa..e48c399fc 100644 --- a/ui/tests/test_mailto.js +++ b/ui/tests/test_mailto.js @@ -28,7 +28,7 @@ deepEqual(mailto.parse("mailto:?bcc=hidden@example.com"), "a bcc-only link still opens a draft") assert.strictEqual(mailto.parse("mailto:jane@example.com?subject=Stop+these").subject, - "Stop these", "+ in a query string is a space") + "Stop+these", "RFC 6068 keeps literal plus signs in mailto queries") assert.strictEqual(mailto.parse("mailto:jane@example.com?subject=%E4%B8%AD%E6%96%87").subject, "中文") assert.strictEqual(mailto.parse("mailto:jane@example.com?body=line%0Abreak").body, @@ -67,4 +67,13 @@ assert.strictEqual(mailto.draftFromPayload({ mailbox: "inbox" }), null) assert.strictEqual(mailto.draftFromPayload({ mailto: "https://example.com" }), null) assert.strictEqual(mailto.draftFromPayload(null), null) + + +{ + const value=mailto.parse('mailto:one+tag@example.test?to=two+tag@example.test&subject=A+B%20C%2BD&body=100%+done') + assert.strictEqual(value.to,'one+tag@example.test, two+tag@example.test') + assert.strictEqual(value.subject,'A+B C+D') + assert.strictEqual(value.body,'100%+done') +} + console.log("test_mailto.js ok") diff --git a/ui/tests/test_message.js b/ui/tests/test_message.js index 8e8d5cc3a..1b74e36be 100644 --- a/ui/tests/test_message.js +++ b/ui/tests/test_message.js @@ -1306,6 +1306,39 @@ assert.strictEqual(message.composeBody("\n Maarten\nmadra.nl \n", "> quoted"), assert.strictEqual(message.composeBody(" \n ", "> quoted"), "\n\n> quoted") assert.strictEqual(message.composeBody("\n\n", ""), "") + + +{ + const recipients = load('compose/Recipients.js') + const encoded = value => '=?UTF-8?B?' + Buffer.from(value).toString('base64') + '?=' + const forged=encoded('Alias ') + const summary=message.summarize({id:'x',payload:{headers:[ + {name:'From',value:'Actual '},{name:'Reply-To',value:forged},{name:'To',value:forged}]}}) + assert.strictEqual(summary.replyTo.email,'') + assert.strictEqual(summary.to.length,0) + assert.strictEqual(recipients.replyFields(summary,'replyAll',[]).to,'actual@example.test') + assert.strictEqual(recipients.replyFields(summary,'replyAll',[]).cc,'') + const named=message.parseAddress(encoded('Alias , Team')+' ') + assert.strictEqual(named.email,'actual@example.test') + assert.strictEqual(named.name,'Alias , Team') +} + +{ + deepEqual(message.parseAddressList('Team: one@example.test, "Two, Example" ;').map(x=>x.email),['one@example.test','two@example.test']) + deepEqual(message.parseAddressList('"A \\"B, C" , two@example.test').map(x=>x.email),['one@example.test','two@example.test']) +} + +{ + const part='Content-Type: text/plain\r\n\r\nKeep prefix --B and the rest\r\nLast line' + deepEqual(message.splitMultipart('--B\r\n'+part+'\r\n--B--\r\nEpilogue','B'),[part]) +} + +{ + assert.strictEqual(message.contentTypeParam('multipart/mixed; notboundary=wrong; boundary=right','boundary'),'right') + assert.strictEqual(message.contentTypeParam('multipart/mixed; note=";boundary=wrong"; boundary="right;still"','boundary'),'right;still') + assert.strictEqual(message.contentTypeParam('attachment; filename="a\\\"b.txt"','filename'),'a"b.txt') +} + console.log("test_message.js ok") // A draft reopened from the server keeps the Reply-To it was saved with. assert.strictEqual(message.draftFields({ replyTo: { email: "team@example.com" }, to: [] }, "x").replyTo, "team@example.com") diff --git a/ui/tests/test_unsubscribe.js b/ui/tests/test_unsubscribe.js index 962511f3b..d519f60ba 100644 --- a/ui/tests/test_unsubscribe.js +++ b/ui/tests/test_unsubscribe.js @@ -32,9 +32,9 @@ deepEqual(unsub.parseMailto("mailto:bye@example.com"), { to: "bye@example.com", subject: "Unsubscribe", body: "Unsubscribe" }) deepEqual(unsub.parseMailto("mailto:bye@example.com?subject=Stop%20these&body=please"), { to: "bye@example.com", subject: "Stop these", body: "please" }) -// "+" is a space in a query string, which is where these live. +// RFC 6068 keeps literal plus signs in mailto queries. assert.strictEqual(unsub.parseMailto("mailto:bye@example.com?subject=Stop+these").subject, - "Stop these") + "Stop+these") // Several recipients: the first is the one that unambiguously belongs here. assert.strictEqual(unsub.parseMailto("mailto:a@example.com,b@example.com").to, "a@example.com") assert.strictEqual(unsub.parseMailto("mailto:not-an-address"), null) @@ -177,4 +177,13 @@ assert.strictEqual(unsub.fromMessage(null).available, false) assert.strictEqual(unsub.postBody(), "List-Unsubscribe=One-Click") assert.strictEqual(unsub.postContentType(), "application/x-www-form-urlencoded") + + +{ + const value=unsub.parseMailto('mailto:list+remove@example.test?subject=A+B%20C%2BD') + assert.ok(value) + assert.strictEqual(value.to,'list+remove@example.test') + assert.strictEqual(value.subject,'A+B C+D') +} + console.log("test_unsubscribe.js ok") From f5f4399a855477f332566113c1de5d74f5d91633 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 148/568] Clarify message parsing stages and private names --- ui/message/Calendar.js | 530 +++++++++++++----------------------- ui/message/Mailto.js | 34 +-- ui/message/Message.js | 558 +++++++++++--------------------------- ui/message/Signature.js | 142 +++++----- ui/message/Unsubscribe.js | 121 ++------- 5 files changed, 455 insertions(+), 930 deletions(-) diff --git a/ui/message/Calendar.js b/ui/message/Calendar.js index 7f4da4224..13b8432a8 100644 --- a/ui/message/Calendar.js +++ b/ui/message/Calendar.js @@ -2,55 +2,37 @@ .import "Message.js" as Mail -// A meeting invitation, out of the message that carried it. -// -// Google Calendar does not send a special kind of mail. It sends an ordinary -// one with a `text/calendar` part beside the HTML, and every calendar that -// speaks RFC 5545 does the same — which is why this reads the part rather than -// the sender, and works for Outlook, Fastmail and a self-hosted CalDAV server -// without knowing that any of them exist. -// -// Answering one is a mail too: an RFC 5546 REPLY, addressed to the organiser, -// carrying the same UID with this account's ATTENDEE line rewritten. That is -// the whole protocol, and it is why RSVP needs no calendar API, no second -// OAuth scope, and works the same on IMAP as on Gmail. +// Docs: Calendar invitations are MIME parts; RSVP uses an RFC 5546 reply addressed to the organiser. var MAX_ICS_BYTES = 512 * 1024 var MAX_COMPONENT_DEPTH = 8 -// --------------------------------------------------------------- unfolding - -// A long property is split across lines with a leading space or tab, and the -// break can fall anywhere — including between the two halves of a UTF-8 -// character or in the middle of an escape. Rejoining before anything else -// looks at the text is what keeps every parse below reading whole values. +// Invariant: unfold content lines before parsing properties so folded escapes remain intact. function unfoldLines(text) { var joined = String(text || "").replace(/\r\n[ \t]|\n[ \t]|\r[ \t]/g, "") var lines = joined.split(/\r\n|\n|\r/) var out = [] - for (var i = 0; i < lines.length; i++) { - if (lines[i] !== "") out.push(lines[i]) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + if (lines[lineIndex] !== "") out.push(lines[lineIndex]) } return out } -// ------------------------------------------------------------------ values - function unescapeText(value) { var input = String(value === undefined || value === null ? "" : value) var out = "" - for (var i = 0; i < input.length; i++) { - var character = input.charAt(i) + for (var index = 0; index < input.length; index++) { + var character = input.charAt(index) if (character !== "\\") { out += character continue } - var next = input.charAt(i + 1) + var next = input.charAt(index + 1) if (next === "n" || next === "N") out += "\n" else if (next === "\\" || next === ";" || next === "," || next === ":") out += next else if (next === "") out += character else out += next - i++ + index++ } return out } @@ -63,20 +45,16 @@ function escapeText(value) { .replace(/\r\n|\n|\r/g, "\\n") } -// ------------------------------------------------------------- one property -// -// The colon that ends the name and its parameters is not the first colon in -// the line: a parameter value may be quoted and hold one, and every value that -// names a person holds "mailto:". So the head is scanned rather than split. +// Invariant: a quoted parameter can contain the colon that otherwise separates the property value. function parseProperty(line) { var text = String(line || "") var quoted = false var cut = -1 - for (var i = 0; i < text.length; i++) { - var character = text.charAt(i) + for (var index = 0; index < text.length; index++) { + var character = text.charAt(index) if (character === "\"") quoted = !quoted - else if (character === ":" && !quoted) { cut = i; break } + else if (character === ":" && !quoted) { cut = index; break } } if (cut < 0) return null @@ -88,11 +66,11 @@ function parseProperty(line) { if (name === "") return null var params = {} - for (var j = 1; j < pieces.length; j++) { - var equals = pieces[j].indexOf("=") + for (var pieceIndex = 1; pieceIndex < pieces.length; pieceIndex++) { + var equals = pieces[pieceIndex].indexOf("=") if (equals < 0) continue - var key = pieces[j].substring(0, equals).toUpperCase().trim() - var raw = pieces[j].substring(equals + 1).trim() + var key = pieces[pieceIndex].substring(0, equals).toUpperCase().trim() + var raw = pieces[pieceIndex].substring(equals + 1).trim() if (key !== "") params[key] = stripQuotes(raw) } @@ -104,8 +82,8 @@ function splitOutsideQuotes(text, separator) { var out = [] var current = "" var quoted = false - for (var i = 0; i < input.length; i++) { - var character = input.charAt(i) + for (var index = 0; index < input.length; index++) { + var character = input.charAt(index) if (character === "\"") { quoted = !quoted current += character @@ -129,12 +107,7 @@ function stripQuotes(value) { return text } -// ------------------------------------------------------------- the document -// -// A component keeps its own source lines as well as its parsed properties. A -// REPLY has to hand the organiser's server back a DTSTART it recognises, and -// the faithful one is the line that arrived rather than one rebuilt out of a -// time this parser may have had to guess at. +// Invariant: replies preserve the organiser's original time and timezone source lines. function parse(text) { var source = String(text || "") @@ -143,8 +116,8 @@ function parse(text) { var root = null var stack = [] - for (var i = 0; i < lines.length; i++) { - var property = parseProperty(lines[i]) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + var property = parseProperty(lines[lineIndex]) if (!property) continue var open = stack.length > 0 ? stack[stack.length - 1] : null @@ -172,10 +145,7 @@ function parse(text) { if (open.name !== String(property.value || "").toUpperCase().trim()) return null var closing = stack.pop() var parent = stack.length > 0 ? stack[stack.length - 1] : null - // The whole of the child, not the line that closed it. A component's - // `lines` has to be its complete source or the VTIMEZONE a reply carries - // back is a header with its rules missing — which is a reply the - // organiser's server cannot place in time. + // Invariant: retain complete nested VTIMEZONE source in replies, including its transition rules. if (parent) { parent.lines = parent.lines .concat(["BEGIN:" + closing.name], closing.lines, ["END:" + closing.name]) @@ -186,17 +156,13 @@ function parse(text) { if (!open) continue open.properties.push(property) - open.lines.push(lines[i]) + open.lines.push(lines[lineIndex]) } return root } -// Replace selected top-level properties in the one VEVENT named by UID while -// leaving every other line alone. CalDAV PUT replaces the whole resource, so -// rebuilding a small event from parsed fields would erase alarms, attendees, -// timezone definitions and server extensions the editor never showed. Nested -// components such as VALARM are deliberately outside the replacement depth. +// Invariant: CalDAV PUT replaces the resource; edit only the selected VEVENT and preserve unmodelled properties and nested components. function rewriteEvent(text, uid, replacementLines, propertyNames) { var lines = unfoldLines(text) var wantedUid = String(uid || "") @@ -204,12 +170,12 @@ function rewriteEvent(text, uid, replacementLines, propertyNames) { var start = -1 var depth = 0 var foundUid = "" - for (var i = 0; i < lines.length; i++) { - var parsed = parseProperty(lines[i]) + for (var scanIndex = 0; scanIndex < lines.length; scanIndex++) { + var parsed = parseProperty(lines[scanIndex]) if (!parsed) continue if (start < 0 && parsed.name === "BEGIN" && String(parsed.value || "").toUpperCase() === "VEVENT") { - start = i + start = scanIndex depth = 1 foundUid = "" continue @@ -218,7 +184,7 @@ function rewriteEvent(text, uid, replacementLines, propertyNames) { if (parsed.name === "BEGIN") { depth++; continue } if (parsed.name === "END") { if (depth === 1 && String(parsed.value || "").toUpperCase() === "VEVENT") { - if (foundUid === wantedUid) matches.push({ start: start, end: i }) + if (foundUid === wantedUid) matches.push({ start: start, end: scanIndex }) start = -1 depth = 0 foundUid = "" @@ -233,7 +199,7 @@ function rewriteEvent(text, uid, replacementLines, propertyNames) { var replace = {} var names = Array.isArray(propertyNames) ? propertyNames : [] - for (var n = 0; n < names.length; n++) replace[String(names[n]).toUpperCase()] = true + for (var nameIndex = 0; nameIndex < names.length; nameIndex++) replace[String(names[nameIndex]).toUpperCase()] = true var target = matches[0] var out = lines.slice(0, target.start + 1) depth = 1 @@ -253,8 +219,8 @@ function rewriteEvent(text, uid, replacementLines, propertyNames) { function childNamed(component, name) { var children = component && Array.isArray(component.children) ? component.children : [] var wanted = String(name || "").toUpperCase() - for (var i = 0; i < children.length; i++) { - if (children[i].name === wanted) return children[i] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + if (children[childIndex].name === wanted) return children[childIndex] } return null } @@ -263,8 +229,8 @@ function childrenNamed(component, name) { var children = component && Array.isArray(component.children) ? component.children : [] var wanted = String(name || "").toUpperCase() var out = [] - for (var i = 0; i < children.length; i++) { - if (children[i].name === wanted) out.push(children[i]) + for (var childIndex = 0; childIndex < children.length; childIndex++) { + if (children[childIndex].name === wanted) out.push(children[childIndex]) } return out } @@ -272,8 +238,8 @@ function childrenNamed(component, name) { function property(component, name) { var list = component && Array.isArray(component.properties) ? component.properties : [] var wanted = String(name || "").toUpperCase() - for (var i = 0; i < list.length; i++) { - if (list[i].name === wanted) return list[i] + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (list[listIndex].name === wanted) return list[listIndex] } return null } @@ -282,8 +248,8 @@ function properties(component, name) { var list = component && Array.isArray(component.properties) ? component.properties : [] var wanted = String(name || "").toUpperCase() var out = [] - for (var i = 0; i < list.length; i++) { - if (list[i].name === wanted) out.push(list[i]) + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (list[listIndex].name === wanted) out.push(list[listIndex]) } return out } @@ -293,15 +259,11 @@ function textOf(component, name) { return found ? unescapeText(found.value).trim() : "" } -// ------------------------------------------------------------------- times - function twoDigits(value) { var number = Math.floor(Number(value) || 0) return (number < 10 ? "0" : "") + number } -// "20260821", "20260821T140000" or "20260821T140000Z". Anything else is not a -// date this can be sure about, and a wrong meeting time is worse than none. function parseDateValue(value) { var text = String(value || "").trim() var match = text.match(/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/) @@ -332,9 +294,7 @@ function parseOffsetMinutes(value) { return match[1] === "-" ? -total : total } -// The naive local time as a number that sorts: comparing two of these compares -// the wall clocks they read, which is the only comparison a timezone rule is -// written in terms of. +// Docs: naiveKey compares wall-clock readings without applying a timezone offset. function naiveKey(fields) { return Date.UTC(fields.year, fields.month - 1, fields.day, fields.hour, fields.minute, fields.second) @@ -345,9 +305,7 @@ function daysInMonth(year, month) { return [4, 6, 9, 11].indexOf(month) >= 0 ? 30 : 31 } -// "the second Sunday in March", "the last Sunday in October". Ordinal 0 means -// the caller had a BYDAY with no number, which for a timezone rule is always -// the first one. +// Docs: ordinal zero selects the first matching weekday for a timezone rule. function nthWeekdayOfMonth(year, month, weekday, ordinal) { var total = daysInMonth(year, month) if (ordinal < 0) { @@ -379,54 +337,38 @@ function weekdayIndex(code) { function parseRuleParts(value) { var parts = {} var pieces = String(value || "").split(";") - for (var i = 0; i < pieces.length; i++) { - var equals = pieces[i].indexOf("=") + for (var pieceIndex = 0; pieceIndex < pieces.length; pieceIndex++) { + var equals = pieces[pieceIndex].indexOf("=") if (equals < 0) continue - parts[pieces[i].substring(0, equals).toUpperCase().trim()] = - pieces[i].substring(equals + 1).trim() + parts[pieces[pieceIndex].substring(0, equals).toUpperCase().trim()] = + pieces[pieceIndex].substring(equals + 1).trim() } return parts } -// A VTIMEZONE's sub-components, read once. Recurrence expansion asks for an -// offset on every day of a series and an invitation can carry thousands of -// RDATEs, so nothing below re-reads a property after this. The plan lives on -// the parsed zone, so a zone timezoneDocument reuses is read only once. -// -// STANDARD first, and that ordering is load-bearing: a zone whose rules this -// cannot place — a lone pair of bare dates outside the years looked at, which -// is what an Exchange zone looks like from here — falls back to rules[0], and -// being an hour behind in winter is a better wrong answer than being an hour -// ahead all year. +// Performance: parsed timezone plans are reused across recurrence lookups. Invariant: STANDARD precedes DAYLIGHT for Exchange fallback. function zonePlan(timezone) { if (timezone.transitionPlan) return timezone.transitionPlan var rules = [] var kinds = ["STANDARD", "DAYLIGHT"] - for (var k = 0; k < kinds.length; k++) { - var found = childrenNamed(timezone, kinds[k]) - for (var i = 0; i < found.length; i++) { - var offset = parseOffsetMinutes(textOf(found[i], "TZOFFSETTO")) + for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) { + var found = childrenNamed(timezone, kinds[kindIndex]) + for (var foundIndex = 0; foundIndex < found.length; foundIndex++) { + var offset = parseOffsetMinutes(textOf(found[foundIndex], "TZOFFSETTO")) if (offset === null) continue - rules.push(zoneRule(found[i], offset)) + rules.push(zoneRule(found[foundIndex], offset)) } } - // A zone that carries its history — retired rules, RDATE lists, more than - // one standard/daylight pair — is also asked about each rule's final year, - // so one that has given up summer time stays where its last transition left - // it. A lone pair of bare dates is the Exchange case above and keeps its - // fallback. + // Invariant: ended timezone rules retain their final transition; a lone Exchange pair keeps its fallback. var history = rules.length > 2 - for (var q = 0; q < rules.length && !history; q++) { - if (rules[q].until || rules[q].listed) history = true + for (var ruleIndex = 0; ruleIndex < rules.length && !history; ruleIndex++) { + if (rules[ruleIndex].until || rules[ruleIndex].listed) history = true } timezone.transitionPlan = { rules: rules, history: history, byYear: {} } return timezone.transitionPlan } -// One STANDARD or DAYLIGHT block. A recurring one keeps its parsed RRULE; one -// without keeps every date it takes effect on — its DTSTART and each RDATE, -// which is how iCloud gathers a zone's one-off transitions, so the last of -// them can sit in an RDATE decades after the DTSTART — grouped by year. +// Invariant: RDATE can carry a later transition than DTSTART, so retain every dated transition by year. function zoneRule(component, offset) { var rule = { offset: offset, @@ -445,30 +387,27 @@ function zoneRule(component, offset) { var dates = [rule.start] var extra = properties(component, "RDATE") rule.listed = extra.length > 0 - for (var i = 0; i < extra.length; i++) { - var values = String(extra[i].value || "").split(",") - for (var j = 0; j < values.length; j++) { - var value = parseDateValue(values[j]) + for (var extraIndex = 0; extraIndex < extra.length; extraIndex++) { + var values = String(extra[extraIndex].value || "").split(",") + for (var valueIndex = 0; valueIndex < values.length; valueIndex++) { + var value = parseDateValue(values[valueIndex]) if (value) dates.push(value) } } - for (var d = 0; d < dates.length; d++) { - var year = dates[d].year + for (var dateIndex = 0; dateIndex < dates.length; dateIndex++) { + var year = dates[dateIndex].year if (!rule.dates[year]) { rule.dates[year] = [] rule.dateYears.push(year) } - rule.dates[year].push(naiveKey(dates[d])) + rule.dates[year].push(naiveKey(dates[dateIndex])) if (rule.lastYear === null || year > rule.lastYear) rule.lastYear = year } - rule.dateYears.sort(function(a, b) { return a - b }) + rule.dateYears.sort(function(left, right) { return left - right }) return rule } -// When one of a VTIMEZONE's rules takes effect, in the year asked about. The -// rules that matter are the ones real zones are written with: a yearly BYMONTH -// with an ordinal BYDAY, a yearly BYMONTH with a BYMONTHDAY, or no rule at all -// — dated transitions, one for a fixed-offset zone, a list for a history. +// Docs: timezone recurrence supports yearly BYMONTH with BYDAY or BYMONTHDAY; fixed histories use dated transitions. function transitionsIn(rule, year) { if (!rule.start) return [] if (!rule.parts) return rule.dates[year] || [] @@ -501,13 +440,7 @@ function recurringTransition(rule, year) { if (day < 1 || day > daysInMonth(year, month)) return null var at = Date.UTC(year, month - 1, day, start.hour, start.minute, start.second) - // A rule stops at its UNTIL. Zones keep their retired rules — iCloud ships - // Vienna's 1981–1995 late-September fall-back to this day — and without - // this one of those wins every autumn. UNTIL is normally UTC while `at` is - // the wall clock the rule left behind, so it is moved to UTC by the offset - // in force before the transition; compared naively, the last transition a - // zone east of UTC made under the rule would fall after its own UNTIL. A - // bare date includes its whole day. + // Invariant: compare UTC UNTIL against the transition using its previous offset; date-only UNTIL includes the entire day. if (until) { var reading = until.utc && rule.from !== null ? at - rule.from * 60000 : at var limit = naiveKey(until) + (until.dateOnly ? 86400000 - 1 : 0) @@ -516,57 +449,58 @@ function recurringTransition(rule, year) { return at } -// The transitions a reading in `year` has to choose between. Every one from -// an earlier year is behind the reading, so of those only the latest is kept; -// the year's own follow it. Listed histories use the nearest occupied past -// year. Recurring rules use the year before and, for a zone with a history, -// their final year and the ones either side — UNTIL -// is UTC, so the last transition can sit in the year before or after the one -// UNTIL names. Later years cannot be behind a reading in this one. +function priorTransitionYears(rule, year, includeHistory) { + var years = [year - 1] + if (includeHistory && !rule.parts) { + var previous = previousListedYear(rule.dateYears, year) + return previous === null ? [] : [previous] + } + var last = includeHistory ? rule.lastYear : null + if (rule.parts && last !== null && last < year - 1) years.push(last - 1, last, last + 1) + return years +} + +// Performance: binary-search occupied years so sparse histories retain their latest past transition without rescanning all dates. +function previousListedYear(years, year) { + var low = 0 + var high = years.length + while (low < high) { + var middle = Math.floor((low + high) / 2) + if (years[middle] < year) low = middle + 1 + else high = middle + } + return low > 0 ? years[low - 1] : null +} + +function latestTransitionIn(rule, years, latest) { + var result = latest + for (var yearIndex = 0; yearIndex < years.length; yearIndex++) { + var transitions = transitionsIn(rule, years[yearIndex]) + for (var transitionIndex = 0; transitionIndex < transitions.length; transitionIndex++) { + var at = transitions[transitionIndex] + if (result === null || at >= result.at) result = { at: at, offset: rule.offset } + } + } + return result +} + +// Invariant: retain the latest past transition and the current year; UTC UNTIL can place the final transition in an adjacent year. function transitionsAround(plan, year) { if (plan.byYear[year]) return plan.byYear[year] var latest = null var within = [] - for (var r = 0; r < plan.rules.length; r++) { - var rule = plan.rules[r] - var years = [year - 1] - // Listed histories can have decades between dates and more dates still - // ahead. Find the latest occupied year before this one, not merely the - // previous year or the final year in the list. The parsed year index is - // sorted once; repeated recurrence lookups need only a binary search. - if (plan.history && !rule.parts) { - var low = 0 - var high = rule.dateYears.length - while (low < high) { - var middle = Math.floor((low + high) / 2) - if (rule.dateYears[middle] < year) low = middle + 1 - else high = middle - } - years = low > 0 ? [rule.dateYears[low - 1]] : [] - } - var last = plan.history ? rule.lastYear : null - if (rule.parts && last !== null && last < year - 1) years.push(last - 1, last, last + 1) - for (var y = 0; y < years.length; y++) { - var earlier = transitionsIn(rule, years[y]) - for (var e = 0; e < earlier.length; e++) { - if (latest === null || earlier[e] >= latest.at) latest = { at: earlier[e], offset: rule.offset } - } - } + for (var ruleIndex = 0; ruleIndex < plan.rules.length; ruleIndex++) { + var rule = plan.rules[ruleIndex] + var years = priorTransitionYears(rule, year, plan.history) + latest = latestTransitionIn(rule, years, latest) var found = transitionsIn(rule, year) - for (var f = 0; f < found.length; f++) within.push({ at: found[f], offset: rule.offset }) + for (var foundIndex = 0; foundIndex < found.length; foundIndex++) within.push({ at: found[foundIndex], offset: rule.offset }) } plan.byYear[year] = latest ? [latest].concat(within) : within return plan.byYear[year] } -// The offset a zone was on at a given wall-clock reading. -// -// This is not a timezone database and does not try to be one. It reads the -// VTIMEZONE the sender shipped in the same file, which is what the standard -// asks a sender to include for exactly this reason, and picks the rule whose -// most recent transition is behind the time being asked about. The hour a -// clock goes back is genuinely ambiguous and is resolved to the later offset; -// no reading of that hour is more correct than another. +// Invariant: inline VTIMEZONE rules determine the offset; an ambiguous repeated hour selects the later transition. function zoneOffsetMinutes(timezone, fields) { if (!timezone) return null var plan = zonePlan(timezone) @@ -577,20 +511,19 @@ function zoneOffsetMinutes(timezone, fields) { var wanted = naiveKey(fields) var best = null var candidates = transitionsAround(plan, fields.year) - for (var c = 0; c < candidates.length; c++) { - if (candidates[c].at > wanted) continue - if (best === null || candidates[c].at >= best.at) best = candidates[c] + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + if (candidates[candidateIndex].at > wanted) continue + if (best === null || candidates[candidateIndex].at >= best.at) best = candidates[candidateIndex] } if (best) return best.offset - // Before every transition this file describes. The offset in force then is - // the one the earliest transition moved away from. + // Invariant: before the first transition, use the offset that transition moved away from. var earliest = null - for (var s = 0; s < rules.length; s++) { - var openings = transitionsIn(rules[s], fields.year - 1) - for (var o = 0; o < openings.length; o++) { - if (earliest === null || openings[o] < earliest.at) { - earliest = { at: openings[o], offset: rules[s].from } + for (var ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) { + var openings = transitionsIn(rules[ruleIndex], fields.year - 1) + for (var openingIndex = 0; openingIndex < openings.length; openingIndex++) { + if (earliest === null || openings[openingIndex] < earliest.at) { + earliest = { at: openings[openingIndex], offset: rules[ruleIndex].from } } } } @@ -601,8 +534,8 @@ function timezoneFor(calendar, tzid) { var wanted = String(tzid || "").trim() if (wanted === "") return null var zones = childrenNamed(calendar, "VTIMEZONE") - for (var i = 0; i < zones.length; i++) { - if (textOf(zones[i], "TZID") === wanted) return zones[i] + for (var zoneIndex = 0; zoneIndex < zones.length; zoneIndex++) { + if (textOf(zones[zoneIndex], "TZID") === wanted) return zones[zoneIndex] } return null } @@ -631,9 +564,7 @@ function dateFieldsFromLine(line) { return found ? parseDateValue(found.value) : null } -// Recurrence expansion walks calendar dates, then asks this function for each -// date's absolute moment. Inline VTIMEZONE rules remain authoritative. A zone -// with no rules uses the same unresolved UTC placeholder on every machine. +// Invariant: recurrence and invitation times use the same inline timezone rules and unresolved UTC placeholder. function timeInZone(fields, tzid, blocks) { var offset = zoneOffsetMinutes(timezoneFor(timezoneDocument(blocks), tzid), fields) if (offset !== null) @@ -641,9 +572,7 @@ function timeInZone(fields, tzid, blocks) { return { ms: naiveKey(fields), resolved: false } } -// A moment, and how sure this is of it. `resolved` false means the wall clock -// is right and the zone is a guess — which the card says out loud rather than -// showing a converted time it cannot stand behind. +// Docs: resolved=false preserves the stated wall clock and exposes the unknown timezone to the view. function resolveTime(found, calendar) { if (!found) return null var fields = parseDateValue(found.value) @@ -666,15 +595,13 @@ function resolveTime(found, calendar) { if (offset !== null) { return { ms: naiveKey(fields) - offset * 60000, allDay: false, tzid: tzid, resolved: true } } - // QML has no IANA timezone database API. Keep the wall fields as a stable - // UTC placeholder and mark them unresolved. Using `new Date(...)` here - // would silently reinterpret them in each machine's local zone. + // Invariant: QML has no IANA timezone database API; an unresolved UTC placeholder must not inherit the machine's local zone. return { ms: naiveKey(fields), allDay: false, tzid: tzid, resolved: false } } - // Floating: the standard says this is local time wherever it is read. + // Invariant: floating iCalendar times use the reader's local clock. return { ms: new Date(fields.year, fields.month - 1, fields.day, fields.hour, fields.minute, fields.second).getTime(), @@ -682,7 +609,7 @@ function resolveTime(found, calendar) { } } -// "PT1H30M", "P2D", "P1W". Returns milliseconds, or 0 for anything unreadable. +// Docs: parseDuration returns milliseconds, or zero for unsupported input. function parseDuration(value) { var text = String(value || "").trim().toUpperCase() var match = text.match(/^([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/) @@ -695,8 +622,6 @@ function parseDuration(value) { return match[1] === "-" ? -total : total } -// -------------------------------------------------------------- recurrence - var WEEKDAY_NAMES = { SU: "Sun", MO: "Mon", TU: "Tue", WE: "Wed", TH: "Thu", FR: "Fri", SA: "Sat" } @@ -708,10 +633,7 @@ var FREQUENCY_NAMES = { YEARLY: ["Yearly", "years"] } -// A sentence for the card, not a full RRULE expansion. It covers what a person -// actually schedules — every week on two days, every other Tuesday, ten times, -// until a date — and says "Repeats" for anything more elaborate rather than -// describing it wrongly. +// Invariant: unsupported recurrence descriptions use "Repeats" rather than inventing a schedule. function describeRecurrence(value) { var text = String(value || "").trim() if (text === "") return "" @@ -726,8 +648,8 @@ function describeRecurrence(value) { if (parts.BYDAY && (frequency === "WEEKLY" || frequency === "MONTHLY")) { var codes = String(parts.BYDAY).split(",") var days = [] - for (var i = 0; i < codes.length; i++) { - var match = codes[i].trim().match(/^([+-]?\d+)?([A-Za-z]{2})$/) + for (var codeIndex = 0; codeIndex < codes.length; codeIndex++) { + var match = codes[codeIndex].trim().match(/^([+-]?\d+)?([A-Za-z]{2})$/) if (!match) continue var name = WEEKDAY_NAMES[match[2].toUpperCase()] if (name) days.push(name) @@ -747,8 +669,6 @@ function describeRecurrence(value) { return sentence } -// -------------------------------------------------------------- addressing - function calendarAddress(found) { if (!found) return null var params = found.params || {} @@ -768,14 +688,11 @@ function sameAddress(left, right) { return String(left || "").trim().toLowerCase() === String(right || "").trim().toLowerCase() } -// Which of the attendee lines is this account, and what it last said. An -// invitation forwarded to an alias has no line naming the reader at all, which -// is a real state and not an error: the card still shows the meeting, and -// answering it speaks for the address the mail is being read from. +// Invariant: a forwarded invitation can be answered by an account absent from its original attendee list. function attendeeFor(invite, address) { var list = invite && Array.isArray(invite.attendees) ? invite.attendees : [] - for (var i = 0; i < list.length; i++) { - if (sameAddress(list[i].email, address)) return list[i] + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (sameAddress(list[listIndex].email, address)) return list[listIndex] } return null } @@ -789,33 +706,26 @@ function responseOf(invite, address) { return "" } -// ------------------------------------------------------------- conferencing - var MEET_URL = /https:\/\/meet\.google\.com\/[a-z0-9-]+/i var CONFERENCE_URL = /https:\/\/(?:[a-z0-9-]+\.)*(?:zoom\.us|teams\.microsoft\.com|teams\.live\.com|meet\.google\.com|whereby\.com|webex\.com|chime\.aws)\/[^\s<>"]+/i -// Google puts the Meet link in a property of its own; everyone else leaves it -// in the location or somewhere in the description. Looked for in that order, -// because the property is the only one of the three that cannot be a sentence -// about a link rather than the link itself. +// Invariant: prefer the declared conference URL, then supported links in location and description. function conferenceLink(event) { var declared = textOf(event, "X-GOOGLE-CONFERENCE") if (MEET_URL.test(declared)) return declared.match(MEET_URL)[0] var fields = [textOf(event, "LOCATION"), textOf(event, "DESCRIPTION")] - for (var i = 0; i < fields.length; i++) { - var meet = fields[i].match(MEET_URL) + for (var meetFieldIndex = 0; meetFieldIndex < fields.length; meetFieldIndex++) { + var meet = fields[meetFieldIndex].match(MEET_URL) if (meet) return meet[0] } - for (var j = 0; j < fields.length; j++) { - var other = fields[j].match(CONFERENCE_URL) + for (var conferenceFieldIndex = 0; conferenceFieldIndex < fields.length; conferenceFieldIndex++) { + var other = fields[conferenceFieldIndex].match(CONFERENCE_URL) if (other) return other[0] } return "" } -// ---------------------------------------------------------- the invitation - var METHODS = ["REQUEST", "REPLY", "CANCEL", "PUBLISH", "COUNTER", "REFRESH", "ADD", "DECLINECOUNTER"] function normalizedMethod(value) { @@ -823,13 +733,7 @@ function normalizedMethod(value) { return METHODS.indexOf(text) >= 0 ? text : "" } -// The MIME part carrying the invitation, if the message has one. -// -// Preferred in the order that gets a usable one: a part that came with its own -// octets first, because the whole invitation is already here. A part that came -// as an id is the fallback, and not a rare one — Gmail withholds the octets of -// every part the sender named, and Google Calendar names both of the two it -// sends, so on Gmail this is how a Google invitation always arrives. +// Invariant: prefer inline calendar bytes over a fetchable attachment, including Gmail's two-part invitation shape. function calendarPart(payload) { var carried = null var promised = null @@ -843,9 +747,7 @@ function calendarPart(payload) { var data = part.body && part.body.data ? String(part.body.data) : "" var attachmentId = part.body && part.body.attachmentId ? String(part.body.attachmentId) : "" - // Measured before it is decoded, not after. This runs on the thread that - // draws the whole desktop, and a part that would be refused for its size - // anyway should not be turned into five megabytes of string first. + // Performance: check encoded-size bounds before decoding a calendar on the drawing thread. var size = Math.max(Math.floor(Number(part.body && part.body.size) || 0), Math.floor(data.length * 3 / 4)) if (isCalendar && size <= MAX_ICS_BYTES) { @@ -854,31 +756,28 @@ function calendarPart(payload) { } else if (attachmentId !== "" && promised === null) promised = part } var children = Array.isArray(part.parts) ? part.parts : [] - for (var i = 0; i < children.length; i++) walk(children[i], depth + 1) + for (var childIndex = 0; childIndex < children.length; childIndex++) walk(children[childIndex], depth + 1) } walk(payload, 0) return carried !== null ? carried : promised } -// The Content-Type of the part states the method too, and it is the one a -// server that rewrote the body may have kept. The property inside the file -// wins, because it is the one the organiser's calendar wrote. +// Invariant: the calendar's METHOD overrides the MIME method parameter. function partMethod(part) { if (!part) return "" var declared = Mail.contentTypeParam(String(part.mimeType || ""), "method") if (declared === "") { var headers = part && Array.isArray(part.headers) ? part.headers : [] - for (var i = 0; i < headers.length; i++) { - if (String(headers[i].name || "").toLowerCase() !== "content-type") continue - declared = Mail.contentTypeParam(headers[i].value, "method") + for (var headerIndex = 0; headerIndex < headers.length; headerIndex++) { + if (String(headers[headerIndex].name || "").toLowerCase() !== "content-type") continue + declared = Mail.contentTypeParam(headers[headerIndex].value, "method") if (declared !== "") break } } return normalizedMethod(declared) } -// Everything the card draws and everything a reply needs, out of one parse. function invitationFrom(text, fallbackMethod) { var calendar = parse(text) if (!calendar || calendar.name !== "VCALENDAR") return null @@ -888,16 +787,14 @@ function invitationFrom(text, fallbackMethod) { return eventFromComponent(calendar, event, fallbackMethod) } -// Calendar feeds may carry more than one VEVENT. Keep their conversion on the -// same path as invitations so a time zone or all-day event cannot mean one -// thing in mail and another thing in the calendar view. +// Invariant: calendar feeds and message invitations share event conversion so timezone and all-day semantics agree. function eventsFrom(text, fallbackMethod) { var calendar = parse(text) if (!calendar || calendar.name !== "VCALENDAR") return [] var components = childrenNamed(calendar, "VEVENT") var events = [] - for (var i = 0; i < components.length; i++) { - var event = eventFromComponent(calendar, components[i], fallbackMethod) + for (var componentIndex = 0; componentIndex < components.length; componentIndex++) { + var event = eventFromComponent(calendar, components[componentIndex], fallbackMethod) if (event) events.push(event) } return events @@ -917,8 +814,8 @@ function eventFromComponent(calendar, event, fallbackMethod) { var attendees = [] var lines = properties(event, "ATTENDEE") - for (var i = 0; i < lines.length; i++) { - var attendee = calendarAddress(lines[i]) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + var attendee = calendarAddress(lines[lineIndex]) if (attendee && attendee.email !== "") attendees.push(attendee) } @@ -954,9 +851,7 @@ function eventFromComponent(calendar, event, fallbackMethod) { recurrenceIdMs: recurrenceId ? recurrenceId.ms : 0, excludedMs: excluded, meetLink: conferenceLink(event), - // Kept verbatim for the reply. A DTSTART rebuilt out of the moment this - // parser settled on would answer a question the organiser did not ask; the - // line that arrived is the one their server matches against. + // Invariant: reply time properties remain verbatim because the organiser matches its original calendar representation. source: { dtstart: rawLine(event, "DTSTART"), dtend: rawLine(event, "DTEND"), @@ -975,15 +870,12 @@ function rawLine(component, name) { function timezoneBlocks(calendar) { var zones = childrenNamed(calendar, "VTIMEZONE") var out = [] - for (var i = 0; i < zones.length; i++) { - out.push(["BEGIN:VTIMEZONE"].concat(zones[i].lines, ["END:VTIMEZONE"]).join("\r\n")) + for (var zoneIndex = 0; zoneIndex < zones.length; zoneIndex++) { + out.push(["BEGIN:VTIMEZONE"].concat(zones[zoneIndex].lines, ["END:VTIMEZONE"]).join("\r\n")) } return out } -// The first call the reader makes. Null when the message carried no -// invitation, which is almost every message — and null too when it carried one -// the server did not send the octets of, which `pendingPart` below is for. function fromPayload(payload) { return fromPart(calendarPart(payload)) } @@ -995,20 +887,13 @@ function fromPart(part) { return invitationFrom(text, partMethod(part)) } -// The part the reader has to ask for before there is anything to draw: a -// calendar part described but not sent. Null when the message either carried -// its invitation or carried none, so the second request is only ever made for -// a message that has an invitation in it. function pendingPart(payload) { var part = calendarPart(payload) if (!part) return null return part.body && part.body.data ? null : part } -// The same part, now that the octets it named have arrived. Read through the -// part rather than on its own so the charset the sender declared still decides -// how the file is read — an invitation whose SUMMARY is not ASCII is the -// ordinary case, not the exotic one. +// Invariant: fetched calendar bytes retain the MIME part's declared charset. function fromAttachment(part, data) { if (!part) return null return fromPart({ @@ -1019,16 +904,14 @@ function fromAttachment(part, data) { }) } -// ------------------------------------------------------------- formatting - -function clockOf(ms, utc) { - var at = new Date(ms) +function clockOf(milliseconds, utc) { + var at = new Date(milliseconds) return twoDigits(utc ? at.getUTCHours() : at.getHours()) + ":" + twoDigits(utc ? at.getUTCMinutes() : at.getMinutes()) } -function dayOf(ms, utc) { - var at = new Date(ms) +function dayOf(milliseconds, utc) { + var at = new Date(milliseconds) var day = utc ? at.getUTCDay() : at.getDay() var month = utc ? at.getUTCMonth() : at.getMonth() var date = utc ? at.getUTCDate() : at.getDate() @@ -1047,10 +930,6 @@ function sameDay(first, second, utc) { === (utc ? right.getUTCDate() : right.getDate()) } -// "Fri, Aug 21, 2026 · 14:00 – 15:00", and the honest variants of it: an -// all-day event has no clock to show, a meeting that runs past midnight names -// the second day, and one whose zone could not be resolved says which zone the -// clock belongs to instead of pretending it is this one. function formatWhen(invite) { var start = invite && invite.start ? invite.start : null if (!start) return "" @@ -1058,8 +937,7 @@ function formatWhen(invite) { var unresolved = !start.resolved && start.tzid !== "" if (start.allDay) { - // An all-day DTEND is the first day *after* the event, so a one-day - // meeting shown from its raw end date reads as two. + // Invariant: all-day DTEND is exclusive, so display the preceding day. if (end && end.ms - start.ms > 86400000) { return dayOf(start.ms) + " – " + dayOf(end.ms - 86400000) } @@ -1076,8 +954,7 @@ function formatWhen(invite) { return text } -// How long it runs, for the line under the date. Left empty rather than shown -// as "0 minutes" when the invitation gave no end and no duration. +// Invariant: an absent duration stays empty rather than claiming a zero-minute event. function formatDuration(invite) { var start = invite && invite.start ? invite.start : null var end = invite && invite.end ? invite.end : null @@ -1095,7 +972,6 @@ function formatDuration(invite) { return rest === 0 ? text : text + " " + rest + " min" } -// Who is coming, as a count rather than a list the card has no room for. function attendeeSummary(invite) { var list = invite && Array.isArray(invite.attendees) ? invite.attendees : [] if (list.length === 0) return "" @@ -1103,10 +979,10 @@ function attendeeSummary(invite) { var no = 0 var maybe = 0 var awaiting = 0 - for (var i = 0; i < list.length; i++) { - if (list[i].partstat === "ACCEPTED") yes++ - else if (list[i].partstat === "DECLINED") no++ - else if (list[i].partstat === "TENTATIVE") maybe++ + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (list[listIndex].partstat === "ACCEPTED") yes++ + else if (list[listIndex].partstat === "DECLINED") no++ + else if (list[listIndex].partstat === "TENTATIVE") maybe++ else awaiting++ } var pieces = [] @@ -1118,9 +994,6 @@ function attendeeSummary(invite) { return count + (pieces.length > 0 ? " · " + pieces.join(", ") : "") } -// What this card is, in the two words above the meeting's name. A cancellation -// and an update are the two the reader most needs to be told apart from a -// first invitation, because both arrive looking exactly like one. function headline(invite) { if (!invite) return "" if (invite.method === "CANCEL" || String(invite.status || "") === "CANCELLED") @@ -1132,9 +1005,6 @@ function headline(invite) { return "Event" } -// One guest's answer, in the same word the buttons use. "Awaiting" rather than -// an empty cell: not having answered is a state, and a blank reads as missing -// data about them. function partstatLabel(partstat) { var value = String(partstat || "").toUpperCase() if (value === "ACCEPTED") return "Yes" @@ -1144,8 +1014,6 @@ function partstatLabel(partstat) { return "Awaiting" } -// ------------------------------------------------------------------- reply - var PARTSTATS = { accepted: "ACCEPTED", declined: "DECLINED", @@ -1158,11 +1026,7 @@ var REPLY_WORDS = { tentative: "Tentative" } -// The account being answered for, given either as its address or as the object -// the panel carries. Written out rather than folded into one expression: the -// obvious "me.email or me" shorthand is correct until me.email is the empty -// string — an account whose profile has not loaded — and then it is the object -// itself, which stringifies into the ATTENDEE line as "[object Object]". +// Invariant: an account with no loaded address must not stringify into an ATTENDEE value. function addressOf(me) { if (!me) return "" if (typeof me === "string") return me.trim() @@ -1183,14 +1047,14 @@ function foldIcsLine(line) { var text = String(line || "") var result = "" var octets = 0 - for (var i = 0; i < text.length; i++) { - var code = text.charCodeAt(i) - var character = text.charAt(i) + for (var characterIndex = 0; characterIndex < text.length; characterIndex++) { + var code = text.charCodeAt(characterIndex) + var character = text.charAt(characterIndex) var size = code < 0x80 ? 1 : (code < 0x800 ? 2 : 3) - if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) { - var low = text.charCodeAt(i + 1) + if (code >= 0xd800 && code <= 0xdbff && characterIndex + 1 < text.length) { + var low = text.charCodeAt(characterIndex + 1) if (low >= 0xdc00 && low <= 0xdfff) { - character += text.charAt(++i) + character += text.charAt(++characterIndex) size = 4 } } @@ -1204,18 +1068,16 @@ function foldIcsLine(line) { return result } -function icsTimestamp(ms) { - var at = new Date(Number(ms) || 0) +function icsTimestamp(milliseconds) { + var at = new Date(Number(milliseconds) || 0) return String(at.getUTCFullYear()) + twoDigits(at.getUTCMonth() + 1) + twoDigits(at.getUTCDate()) + "T" + twoDigits(at.getUTCHours()) + twoDigits(at.getUTCMinutes()) + twoDigits(at.getUTCSeconds()) + "Z" } -// The RFC 5546 answer to an invitation: the same UID and SEQUENCE, one -// ATTENDEE line — this account's — and nobody else's, because a reply speaks -// only for the person sending it. -function buildReply(invite, me, response, nowMs) { +// Invariant: an RSVP preserves UID and SEQUENCE and speaks for exactly one attendee. +function buildReply(invite, me, response, nowMilliseconds) { var answer = normalizedResponse(response) if (!invite || answer === "") return "" var address = addressOf(me) @@ -1225,12 +1087,12 @@ function buildReply(invite, me, response, nowMs) { var lines = ["BEGIN:VCALENDAR", "PRODID:-//Omamail//Omamail//EN", "VERSION:2.0", "METHOD:REPLY"] var zones = invite.source && Array.isArray(invite.source.timezones) ? invite.source.timezones : [] - for (var z = 0; z < zones.length; z++) lines = lines.concat(zones[z].split("\r\n")) + for (var zoneIndex = 0; zoneIndex < zones.length; zoneIndex++) lines = lines.concat(zones[zoneIndex].split("\r\n")) lines.push("BEGIN:VEVENT") lines.push("UID:" + escapeText(invite.uid)) lines.push("SEQUENCE:" + Math.max(0, Math.floor(Number(invite.sequence) || 0))) - lines.push("DTSTAMP:" + icsTimestamp(nowMs === undefined ? Date.now() : nowMs)) + lines.push("DTSTAMP:" + icsTimestamp(nowMilliseconds === undefined ? Date.now() : nowMilliseconds)) if (invite.organizer && invite.organizer.email !== "") lines.push("ORGANIZER:mailto:" + invite.organizer.email) lines.push("ATTENDEE;PARTSTAT=" + PARTSTATS[answer] @@ -1249,21 +1111,18 @@ function buildReply(invite, me, response, nowMs) { lines.push("END:VCALENDAR") var folded = [] - for (var i = 0; i < lines.length; i++) { - if (String(lines[i] || "").trim() !== "") folded.push(foldIcsLine(lines[i])) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + if (String(lines[lineIndex] || "").trim() !== "") folded.push(foldIcsLine(lines[lineIndex])) } return folded.join("\r\n") + "\r\n" } -// A parameter value may not carry a quote, a colon or a semicolon unquoted, -// and there is no escape for a quote inside one — so a display name holding -// one loses it rather than ending the value early. +// Invariant: quoted calendar parameters cannot contain an embedded quote; discard it rather than introduce another parameter. function quoteParam(value) { return "\"" + String(value || "").replace(/["\r\n]/g, "") + "\"" } -// Who the answer goes to. The organiser, and nobody else: a reply copied to -// every attendee is how one accepted meeting becomes forty mails. +// Invariant: an RSVP addresses only the organiser. function replyRecipient(invite) { return invite && invite.organizer ? String(invite.organizer.email || "") : "" } @@ -1275,8 +1134,6 @@ function replySubject(invite, response) { return REPLY_WORDS[answer] + ": " + (summary !== "" ? summary : "(no subject)") } -// The text part beside the calendar one. A calendar reads the attachment; a -// person reading the reply in a client that does not gets a sentence. function replyBody(invite, me, response) { var answer = normalizedResponse(response) if (answer === "") return "" @@ -1286,14 +1143,12 @@ function replyBody(invite, me, response) { return who + " has " + word + " this invitation." } -// Everything `send` needs for one RSVP, or null when this invitation cannot be -// answered — no organiser to answer, or not a request in the first place. -function replyFields(invite, me, response, nowMs) { +function replyFields(invite, me, response, nowMilliseconds) { var answer = normalizedResponse(response) if (!invite || answer === "") return null var to = replyRecipient(invite) if (to === "") return null - var calendar = buildReply(invite, me, answer, nowMs) + var calendar = buildReply(invite, me, answer, nowMilliseconds) if (calendar === "") return null return { to: to, @@ -1303,16 +1158,7 @@ function replyFields(invite, me, response, nowMs) { } } -// The same invitation with this account's answer written into it. -// -// Needed because the answer is not in the file: the `text/calendar` part is -// the organiser's document and an RSVP does not rewrite it, so a message -// reopened tomorrow would show its buttons unanswered — after the answer had -// been sent, and had worked. This is what goes back into the body cache. -// -// An address with no ATTENDEE line of its own gets one. That is the forwarded -// invitation, where a reply is still the right thing to have sent and the file -// is still the wrong place to learn it from. +// Invariant: cache the local RSVP response because the organiser's original attachment does not change after sending. function withResponse(invite, address, response) { var answer = normalizedResponse(response) if (!invite || answer === "") return invite @@ -1322,16 +1168,16 @@ function withResponse(invite, address, response) { var list = Array.isArray(invite.attendees) ? invite.attendees : [] var updated = [] var found = false - for (var i = 0; i < list.length; i++) { - if (!sameAddress(list[i].email, wanted)) { - updated.push(list[i]) + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (!sameAddress(list[listIndex].email, wanted)) { + updated.push(list[listIndex]) continue } found = true updated.push({ - name: list[i].name, email: list[i].email, - partstat: PARTSTATS[answer], role: list[i].role, - optional: list[i].optional, resource: list[i].resource + name: list[listIndex].name, email: list[listIndex].email, + partstat: PARTSTATS[answer], role: list[listIndex].role, + optional: list[listIndex].optional, resource: list[listIndex].resource }) } if (!found) { @@ -1341,18 +1187,14 @@ function withResponse(invite, address, response) { }) } - // A shallow copy with one field replaced. Rebuilt field by field rather than - // mutated, because the object handed in is the one the card is bound to and - // a QML binding does not notice a property of an object changing under it. + // Invariant: replace the invitation object so QML observes the updated attendee state. var copy = {} for (var key in invite) copy[key] = invite[key] copy.attendees = updated return copy } -// Whether the panel may draw the buttons at all. A cancellation and a reply -// somebody else sent are both invitations worth showing and neither is one to -// answer, and an organiser cannot RSVP to their own meeting. +// Invariant: cancelled events, replies, and the organiser's own event cannot be answered. function canRespond(invite, address) { if (!invite || invite.method !== "REQUEST") return false if (String(invite.status || "") === "CANCELLED") return false diff --git a/ui/message/Mailto.js b/ui/message/Mailto.js index dfd30e304..9a7bd09af 100644 --- a/ui/message/Mailto.js +++ b/ui/message/Mailto.js @@ -1,22 +1,13 @@ .pragma library -// A mailto: URL is a draft, not a page. The desktop hands one over when -// something outside this window asks to write a message, and a link in a -// message body can be the same shape. Everything here decides what goes in -// the compose fields; nothing here sends. -// -// RFC 6068: `mailto:` [ to ] [ "?" hfields ]. Headers in the query are not -// trusted: a subject holding a newline is how a stranger writes a Bcc of -// their own, so those values lose their line breaks before they reach a -// field. The body is allowed them — that is what a body is. +// Invariant: mailto opens an editable draft; query headers lose line breaks while the body keeps them. function percentDecode(value) { var text = String(value || "") try { return decodeURIComponent(text) - } catch (e) { - // A stray percent that is not an escape. The raw text is still closer to - // what the sender meant than nothing is. + } catch (parseError) { + // Invariant: a malformed percent escape preserves the original field text. return text } } @@ -31,9 +22,9 @@ function bodyText(value) { function appendAddresses(list, value) { var parts = String(value || "").split(",") - var i - for (i = 0; i < parts.length; i++) { - var address = parts[i].trim() + var partIndex + for (partIndex = 0; partIndex < parts.length; partIndex++) { + var address = parts[partIndex].trim() if (address !== "") list.push(address) } } @@ -58,12 +49,12 @@ function parse(entry) { appendAddresses(to, path) if (mark >= 0) { var pairs = rest.substring(mark + 1).split("&") - var i - for (i = 0; i < pairs.length; i++) { - var equals = pairs[i].indexOf("=") + var pairIndex + for (pairIndex = 0; pairIndex < pairs.length; pairIndex++) { + var equals = pairs[pairIndex].indexOf("=") if (equals < 0) continue - var key = pairs[i].substring(0, equals).toLowerCase() - var raw = percentDecode(pairs[i].substring(equals + 1)) + var key = pairs[pairIndex].substring(0, equals).toLowerCase() + var raw = percentDecode(pairs[pairIndex].substring(equals + 1)) if (key === "to") appendAddresses(to, headerSafe(raw)) else if (key === "cc") appendAddresses(cc, headerSafe(raw)) else if (key === "bcc") appendAddresses(bcc, headerSafe(raw)) @@ -80,9 +71,6 @@ function parse(entry) { } } -// What App.open should put in the compose form. A mailto that is not one -// leaves the window alone rather than opening a blank draft over a listing -// the user already had. function draftFromPayload(payload) { if (!payload || typeof payload !== "object") return null if (payload.mailto) return parse(payload.mailto) diff --git a/ui/message/Message.js b/ui/message/Message.js index a08a22aed..4fac8be60 100644 --- a/ui/message/Message.js +++ b/ui/message/Message.js @@ -2,27 +2,14 @@ .import "Direction.js" as Direction .import "Signature.js" as Signature -// Everything that turns a Gmail API message resource into something a row or a -// reader can show. Two things force real work here rather than a few property -// reads: -// -// - Gmail hands back part bodies as base64url and leaves the transfer -// encoding already undone, but the QML JS engine has no `atob` and -// `Qt.atob` is not available to a plain JS library, so base64 and UTF-8 are -// decoded by hand. -// - Gmail does *not* decode headers. A subject in any non-ASCII language -// arrives as an RFC 2047 encoded word, so "=?UTF-8?B?5L2g5aW9?=" has to -// become "你好" before it reaches a Text element. +// Docs: providers share Gmail-shaped payloads; body data is base64url and headers can contain RFC 2047 words. var B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -// A lookup table rather than indexOf per character. Decoding a 60 KB body -// means 60 000 scans of a 64-character string otherwise, which measured at -// ~9 ms in V8 and several times that in QML's engine — a visible stutter on -// every message, in the process that draws the whole desktop. +// Performance: one lookup per base64 character avoids repeatedly scanning the alphabet on the drawing thread. var B64_LOOKUP = (function() { var table = {} - for (var i = 0; i < B64_ALPHABET.length; i++) table[B64_ALPHABET.charAt(i)] = i + for (var index = 0; index < B64_ALPHABET.length; index++) table[B64_ALPHABET.charAt(index)] = index table["-"] = 62 table["_"] = 63 return table @@ -33,15 +20,13 @@ function b64Index(character) { return value === undefined ? -1 : value } -// Returns an array of byte values. Padding and stray whitespace or newlines — -// both of which Gmail includes — are ignored rather than treated as an error. function base64ToBytes(text) { var input = String(text || "") var bytes = [] var buffer = 0 var bits = 0 - for (var i = 0; i < input.length; i++) { - var value = B64_LOOKUP[input.charAt(i)] + for (var index = 0; index < input.length; index++) { + var value = B64_LOOKUP[input.charAt(index)] if (value === undefined) continue buffer = (buffer << 6) | value bits += 6 @@ -55,29 +40,28 @@ function base64ToBytes(text) { function bytesToUtf8(bytes) { var out = "" - var i = 0 + var byteIndex = 0 var length = bytes.length - while (i < length) { - var byte1 = bytes[i++] + while (byteIndex < length) { + var byte1 = bytes[byteIndex++] if (byte1 < 0x80) { out += String.fromCharCode(byte1) continue } var codePoint = -1 - if (byte1 >= 0xc2 && byte1 <= 0xdf && i < length) { - codePoint = ((byte1 & 0x1f) << 6) | (bytes[i] & 0x3f) - i += 1 - } else if (byte1 >= 0xe0 && byte1 <= 0xef && i + 1 < length) { - codePoint = ((byte1 & 0x0f) << 12) | ((bytes[i] & 0x3f) << 6) | (bytes[i + 1] & 0x3f) - i += 2 - } else if (byte1 >= 0xf0 && byte1 <= 0xf4 && i + 2 < length) { - codePoint = ((byte1 & 0x07) << 18) | ((bytes[i] & 0x3f) << 12) - | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f) - i += 3 + if (byte1 >= 0xc2 && byte1 <= 0xdf && byteIndex < length) { + codePoint = ((byte1 & 0x1f) << 6) | (bytes[byteIndex] & 0x3f) + byteIndex += 1 + } else if (byte1 >= 0xe0 && byte1 <= 0xef && byteIndex + 1 < length) { + codePoint = ((byte1 & 0x0f) << 12) | ((bytes[byteIndex] & 0x3f) << 6) | (bytes[byteIndex + 1] & 0x3f) + byteIndex += 2 + } else if (byte1 >= 0xf0 && byte1 <= 0xf4 && byteIndex + 2 < length) { + codePoint = ((byte1 & 0x07) << 18) | ((bytes[byteIndex] & 0x3f) << 12) + | ((bytes[byteIndex + 1] & 0x3f) << 6) | (bytes[byteIndex + 2] & 0x3f) + byteIndex += 3 } if (codePoint < 0) { - // Not valid UTF-8. Latin-1 is the only other thing this is likely to be, - // and showing the wrong accent beats showing a replacement block. + // Invariant: malformed UTF-8 bytes fall back individually to Latin-1 so message text remains readable. out += String.fromCharCode(byte1) continue } @@ -93,26 +77,19 @@ function bytesToUtf8(bytes) { function bytesToLatin1(bytes) { var out = "" - for (var i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]) + for (var byteIndex = 0; byteIndex < bytes.length; byteIndex++) out += String.fromCharCode(bytes[byteIndex]) return out } -// Qt.atob is native C++ and skips the per-character base64 loop entirely. It -// does not hand back raw bytes: Qt's implementation is QString::fromUtf8 over -// the decoded bytes, so the result is already text. Measured on Qt 6.11 — -// "Alex à l'école" comes back 14 characters with U+00E0 in it, not 16 bytes -// with C3 A0. Decoding that text a second time as UTF-8 bytes is what turned -// every accented calendar title and 8-bit mail body into CJK mojibake. The -// pure JS path stays for the node tests, and as the fallback anywhere Qt is -// absent. +// Invariant: Qt.atob returns decoded QString text; decoding it again as byte values corrupts non-ASCII text. function decodeBase64Url(text) { var input = String(text || "") if (input === "") return "" if (typeof Qt !== "undefined" && typeof Qt.atob === "function") { try { return Qt.atob(input.replace(/-/g, "+").replace(/_/g, "/")) - } catch (e) { - // Fall through to the portable path rather than losing the message. + } catch (parseError) { + } } return bytesToUtf8(base64ToBytes(input)) @@ -121,13 +98,13 @@ function decodeBase64Url(text) { function utf8Bytes(text) { var input = String(text || "") var bytes = [] - for (var i = 0; i < input.length; i++) { - var code = input.charCodeAt(i) - if (code >= 0xd800 && code <= 0xdbff && i + 1 < input.length) { - var low = input.charCodeAt(i + 1) + for (var index = 0; index < input.length; index++) { + var code = input.charCodeAt(index) + if (code >= 0xd800 && code <= 0xdbff && index + 1 < input.length) { + var low = input.charCodeAt(index + 1) if (low >= 0xdc00 && low <= 0xdfff) { code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00) - i++ + index++ } } if (code < 0x80) bytes.push(code) @@ -141,10 +118,10 @@ function utf8Bytes(text) { function bytesToBase64(bytes, urlSafe) { var out = "" - for (var i = 0; i < bytes.length; i += 3) { - var b0 = bytes[i] - var b1 = i + 1 < bytes.length ? bytes[i + 1] : -1 - var b2 = i + 2 < bytes.length ? bytes[i + 2] : -1 + for (var byteIndex = 0; byteIndex < bytes.length; byteIndex += 3) { + var b0 = bytes[byteIndex] + var b1 = byteIndex + 1 < bytes.length ? bytes[byteIndex + 1] : -1 + var b2 = byteIndex + 2 < bytes.length ? bytes[byteIndex + 2] : -1 out += B64_ALPHABET.charAt(b0 >> 2) out += B64_ALPHABET.charAt(((b0 & 0x03) << 4) | (b1 < 0 ? 0 : b1 >> 4)) out += b1 < 0 ? "=" : B64_ALPHABET.charAt(((b1 & 0x0f) << 2) | (b2 < 0 ? 0 : b2 >> 6)) @@ -162,47 +139,30 @@ function encodeBase64(text) { return bytesToBase64(utf8Bytes(text), false) } -// ------------------------------------------------------- RFC 2047 headers - function decodeQuotedPrintableWord(text) { var input = String(text || "").replace(/_/g, " ") var bytes = [] - for (var i = 0; i < input.length; i++) { - if (input.charAt(i) === "=" && i + 2 < input.length) { - var hex = input.substr(i + 1, 2) + for (var index = 0; index < input.length; index++) { + if (input.charAt(index) === "=" && index + 2 < input.length) { + var hex = input.substr(index + 1, 2) if (/^[0-9A-Fa-f]{2}$/.test(hex)) { bytes.push(parseInt(hex, 16)) - i += 2 + index += 2 continue } } - bytes.push(input.charCodeAt(i) & 0xff) + bytes.push(input.charCodeAt(index) & 0xff) } return bytes } -// Whether these bytes are UTF-8 that a single-byte charset could not have -// produced: at least one well-formed multi-byte sequence, and nothing -// malformed anywhere. -// -// A charset header is a claim, and this is the evidence. Mail that declares -// `us-ascii` or `iso-8859-1` while carrying UTF-8 is common enough that every -// other client sniffs for it, and the two readings are never both plausible: -// read as one byte each, the UTF-8 for "ń" is "Å" followed by a control -// character, which is not something anybody wrote. Genuine Latin-1 and -// Latin-2 text does not survive this test — a lone "ł" in ISO 8859-2 is 0xB3, -// a continuation byte with no lead, which is malformed UTF-8 and hands the -// decision back to the declaration. -// -// Strict on purpose. An overlong form, a surrogate or a truncated tail all -// count as malformed, because each is likelier to be single-byte text that -// happens to begin a sequence than UTF-8 worth trusting over the header. +// Invariant: only fully valid multibyte UTF-8 overrides a declared single-byte charset. function looksLikeUtf8(bytes) { var values = bytes || [] var multi = 0 - var i = 0 - while (i < values.length) { - var byte1 = values[i++] + var byteIndex = 0 + while (byteIndex < values.length) { + var byte1 = values[byteIndex++] if (byte1 < 0x80) continue var needed = 0 var codePoint = 0 @@ -216,17 +176,16 @@ function looksLikeUtf8(bytes) { needed = 3 codePoint = byte1 & 0x07 } else { - // 0x80-0xc1 is a continuation with no lead, or an overlong two-byte - // form; 0xf5 and above is past the last code point. + return false } - if (i + needed > values.length) return false - for (var n = 0; n < needed; n++) { - var next = values[i + n] + if (byteIndex + needed > values.length) return false + for (var continuationIndex = 0; continuationIndex < needed; continuationIndex++) { + var next = values[byteIndex + continuationIndex] if (next < 0x80 || next > 0xbf) return false codePoint = (codePoint << 6) | (next & 0x3f) } - i += needed + byteIndex += needed if (needed === 1 && codePoint < 0x80) return false if (needed === 2 && codePoint < 0x800) return false if (needed === 3 && (codePoint < 0x10000 || codePoint > 0x10ffff)) return false @@ -242,15 +201,11 @@ function decodeWordBytes(charset, bytes) { if (name.indexOf("iso-8859") === 0 || name.indexOf("windows-125") === 0 || name.indexOf("us-ascii") === 0 || name === "") return looksLikeUtf8(bytes) ? bytesToUtf8(bytes) : bytesToLatin1(bytes) - // GB18030, Shift_JIS and friends need a table this plugin does not carry. - // UTF-8 decoding degrades to Latin-1 per byte, which at least keeps the - // ASCII parts of the header readable. + // Docs: unsupported multibyte charsets use the UTF-8/Latin-1 fallback because this portable path has no mapping tables. return bytesToUtf8(bytes) } -// Adjacent encoded words are defined to join with the whitespace between them -// dropped, which is what makes multi-word CJK subjects come out unspaced when -// a naive decoder keeps it. +// Invariant: RFC 2047 adjacent encoded words omit separating whitespace. function decodeHeaderValue(value) { var input = String(value === undefined || value === null ? "" : value) if (input.indexOf("=?") < 0) return input @@ -273,15 +228,13 @@ function decodeHeaderValue(value) { return out } -// ---------------------------------------------------------------- headers - function headerValue(message, name) { var payload = message && message.payload ? message.payload : null var headers = payload && Array.isArray(payload.headers) ? payload.headers : [] var wanted = String(name || "").toLowerCase() - for (var i = 0; i < headers.length; i++) { - if (String(headers[i].name || "").toLowerCase() === wanted) - return String(headers[i].value || "") + for (var headerIndex = 0; headerIndex < headers.length; headerIndex++) { + if (String(headers[headerIndex].name || "").toLowerCase() === wanted) + return String(headers[headerIndex].value || "") } return "" } @@ -297,8 +250,7 @@ function unquote(value) { return text.replace(/\\(.)/g, "$1").trim() } -// "Jane Doe ", "" and a bare address all -// have to end up as the same shape. +// Invariant: parse mailbox structure before decoding display words; decoded punctuation must never create a recipient. function addressSyntax(value) { return String(value || "").replace(/=\?[^?\s]+\?[bq]\?[^?]*\?=/gi, function(word) { return new Array(word.length + 1).join(" ") @@ -325,10 +277,10 @@ function parseAddressList(value) { var start = 0 var inQuotes = false var inAngle = false - for (var i = 0; i < syntax.length; i++) { - var character = syntax.charAt(i) + for (var characterIndex = 0; characterIndex < syntax.length; characterIndex++) { + var character = syntax.charAt(characterIndex) if (inQuotes && character === "\\") { - i++ + characterIndex++ continue } if (character === "\"") inQuotes = !inQuotes @@ -337,17 +289,17 @@ function parseAddressList(value) { else if (character === ">") inAngle = false if (inAngle) continue if (character === ":") { - start = i + 1 + start = characterIndex + 1 continue } if (character !== "," && character !== ";") continue - entries.push(raw.substring(start, i)) - start = i + 1 + entries.push(raw.substring(start, characterIndex)) + start = characterIndex + 1 } entries.push(raw.substring(start)) var result = [] - for (var j = 0; j < entries.length; j++) { - var parsed = parseAddress(entries[j]) + for (var entryIndex = 0; entryIndex < entries.length; entryIndex++) { + var parsed = parseAddress(entries[entryIndex]) if (parsed.email !== "") result.push(parsed) } return result @@ -357,21 +309,19 @@ function formatAddressList(addresses, limit) { var list = Array.isArray(addresses) ? addresses : [] var max = Math.max(1, Math.floor(Number(limit) || 3)) var names = [] - for (var i = 0; i < list.length && i < max; i++) names.push(list[i].display) + for (var listIndex = 0; listIndex < list.length && listIndex < max; listIndex++) names.push(list[listIndex].display) if (list.length > max) names.push("+" + (list.length - max)) return names.join(", ") } -// ------------------------------------------------------------------ bodies - function partCharset(part) { var mime = String(part && part.mimeType ? part.mimeType : "") var match = mime.match(/charset="?([^";]+)"?/i) if (match) return match[1] var headers = part && Array.isArray(part.headers) ? part.headers : [] - for (var i = 0; i < headers.length; i++) { - if (String(headers[i].name || "").toLowerCase() !== "content-type") continue - var found = String(headers[i].value || "").match(/charset="?([^";\s]+)"?/i) + for (var headerIndex = 0; headerIndex < headers.length; headerIndex++) { + if (String(headers[headerIndex].name || "").toLowerCase() !== "content-type") continue + var found = String(headers[headerIndex].value || "").match(/charset="?([^";\s]+)"?/i) if (found) return found[1] } return "" @@ -383,11 +333,7 @@ function decodePart(part) { return decodeWordBytes(partCharset(part) || "utf-8", base64ToBytes(data)) } -// Images become a marker rather than nothing at all. Stripped outright — which -// is what removing every tag does — a message built around its pictures reads as -// a long run of unexplained blank space, with no way to tell an empty message -// from one whose contents happen not to be text. The number is what lets the -// reader offer the image itself when the marker is clicked. +// Invariant: preserve image markers when flattening markup so a non-text message does not appear empty. var IMAGE_MARKER = /\[image (\d+)\]/g function htmlToText(html) { @@ -395,10 +341,7 @@ function htmlToText(html) { return String(html || "") .replace(//g, "") .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "") - // The reader does not use this numbering: MailAccount takes the body text - // and the picture list from one walk over Html.js's parse tree, so the two - // cannot disagree. What is left here serves decodeSnippet, where Gmail's - // snippet is escaped prose that never carried an image. + // Invariant: reader text and image IDs come from one Html walk; this fallback serves escaped snippets. .replace(/"']|"[^"]*"|'[^']*')*>/gi, function() { imageCount++ return "[image " + imageCount + "]" @@ -422,9 +365,9 @@ function htmlToText(html) { function partHeader(part, wanted) { var headers = part && Array.isArray(part.headers) ? part.headers : [] - for (var i = 0; i < headers.length; i++) { - if (String(headers[i].name || "").toLowerCase() === wanted) - return String(headers[i].value || "") + for (var headerIndex = 0; headerIndex < headers.length; headerIndex++) { + if (String(headers[headerIndex].name || "").toLowerCase() === wanted) + return String(headers[headerIndex].value || "") } return "" } @@ -447,9 +390,7 @@ function isAttachment(part) { return disposition(part) === "attachment" } -// Walks the MIME tree once and keeps the best text it saw. text/plain wins -// outright; a text/html part is kept only as a fallback because converting it -// always loses something. +// Invariant: prefer text/plain; HTML flattening is a fallback because it loses formatting. function extractBody(payload) { var plain = "" var html = "" @@ -459,7 +400,7 @@ function extractBody(payload) { var mime = String(part.mimeType || "").toLowerCase() var children = Array.isArray(part.parts) ? part.parts : [] if (children.length > 0) { - for (var i = 0; i < children.length; i++) walk(children[i], depth + 1) + for (var childIndex = 0; childIndex < children.length; childIndex++) walk(children[childIndex], depth + 1) return } if (isAttachment(part)) return @@ -473,9 +414,7 @@ function extractBody(payload) { return { text: "", source: "" } } -// The same walk as extractBody, kept separate because the reader wants the -// markup and the list row wants the flattened text, and neither should pay for -// the other's work. +// Performance: plain text and markup extraction stay separate so callers do not pay for both walks. function extractHtml(payload) { var found = "" @@ -484,7 +423,7 @@ function extractHtml(payload) { var mime = String(part.mimeType || "").toLowerCase() var children = Array.isArray(part.parts) ? part.parts : [] if (children.length > 0) { - for (var i = 0; i < children.length; i++) walk(children[i], depth + 1) + for (var childIndex = 0; childIndex < children.length; childIndex++) walk(children[childIndex], depth + 1) return } if (isAttachment(part)) return @@ -509,16 +448,13 @@ function attachments(payload) { attachmentId: String(part.body.attachmentId) }) } - for (var i = 0; i < children.length; i++) walk(children[i], depth + 1) + for (var childIndex = 0; childIndex < children.length; childIndex++) walk(children[childIndex], depth + 1) } walk(payload, 0) return found } -// The part an attachment id names, or null. Gmail describes a part it will not -// send — an id, a type and a size — and this is how the caller gets back to -// what it was told about it once the octets arrive. function partForAttachment(payload, attachmentId) { var wanted = String(attachmentId || "") if (wanted === "") return null @@ -531,7 +467,7 @@ function partForAttachment(payload, attachmentId) { return } var children = Array.isArray(part.parts) ? part.parts : [] - for (var i = 0; i < children.length; i++) walk(children[i], depth + 1) + for (var childIndex = 0; childIndex < children.length; childIndex++) walk(children[childIndex], depth + 1) } walk(payload, 0) @@ -551,52 +487,36 @@ function formatCount(count, singular) { return amount + " " + noun + (amount === 1 ? "" : "s") } -// ------------------------------------------------------ RFC 822 → payload -// -// Gmail hands back a message already taken apart: a headers array, a MIME -// tree, part bodies in base64url. An IMAP server hands back the message. -// -// So this rebuilds Gmail's shape from the wire format, and everything above — -// `extractBody`, `extractHtml`, `attachments`, `summarize`, the whole reader — -// goes on working without learning a second vocabulary. It is the single -// adapter that lets one panel drive two very different services. -// -// The input is a *byte string*: one character per octet, which is what -// `Imap.decodeResponse` produces. Anything else and a Content-Length or a -// literal count would be measured in the wrong unit. +// Docs: MIME input is a byte string, one character per octet; the result uses the shared provider payload shape. var MAX_MIME_DEPTH = 12 function latin1Bytes(text) { var input = String(text || "") var bytes = [] - for (var i = 0; i < input.length; i++) bytes.push(input.charCodeAt(i) & 0xff) + for (var index = 0; index < input.length; index++) bytes.push(input.charCodeAt(index) & 0xff) return bytes } -// The body form of quoted-printable, which differs from the encoded-word form -// above in two ways that matter: "_" is a literal underscore rather than a -// space, and a "=" at the end of a line is a soft break that disappears. +// Invariant: body quoted-printable preserves underscores and removes soft line breaks, unlike encoded-word decoding. function decodeQuotedPrintableBytes(text) { var input = String(text || "").replace(/=\r?\n/g, "") var bytes = [] - for (var i = 0; i < input.length; i++) { - if (input.charAt(i) === "=" && i + 2 < input.length) { - var hex = input.substr(i + 1, 2) + for (var index = 0; index < input.length; index++) { + if (input.charAt(index) === "=" && index + 2 < input.length) { + var hex = input.substr(index + 1, 2) if (/^[0-9A-Fa-f]{2}$/.test(hex)) { bytes.push(parseInt(hex, 16)) - i += 2 + index += 2 continue } } - bytes.push(input.charCodeAt(i) & 0xff) + bytes.push(input.charCodeAt(index) & 0xff) } return bytes } -// A header may be folded across several lines, each continuation beginning -// with a space or a tab. Unfolding has to happen before anything looks for a -// ":", or a long Subject becomes a header called "of the meeting". +// Invariant: unfold header continuations before finding field separators. function unfoldHeaders(text) { return String(text || "").replace(/\r?\n[ \t]+/g, " ") } @@ -604,13 +524,11 @@ function unfoldHeaders(text) { function parseHeaderBlock(text) { var lines = unfoldHeaders(text).split(/\r?\n/) var headers = [] - for (var i = 0; i < lines.length; i++) { - var line = lines[i] + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + var line = lines[lineIndex] if (line === "") continue var colon = line.indexOf(":") - // A line with no colon is not a header. It is what the first line of a - // message looks like when a server included the "From " envelope line, and - // keeping it would give every message a header with an empty name. + if (colon <= 0) continue headers.push({ name: line.substring(0, colon).trim(), @@ -623,15 +541,13 @@ function parseHeaderBlock(text) { function headerFrom(headers, name) { var list = Array.isArray(headers) ? headers : [] var wanted = String(name || "").toLowerCase() - for (var i = 0; i < list.length; i++) { - if (String(list[i].name || "").toLowerCase() === wanted) return String(list[i].value || "") + for (var listIndex = 0; listIndex < list.length; listIndex++) { + if (String(list[listIndex].name || "").toLowerCase() === wanted) return String(list[listIndex].value || "") } return "" } -// A Content-Type parameter, quoted or bare. RFC 2231 continuations -// (name*0=, name*1=) are not handled: they appear on long filenames, and a -// truncated filename is a smaller loss than a parser that guesses. +// Docs: RFC 2231 filename continuations are unsupported; ordinary quoted and bare parameters are parsed structurally. function contentTypeParam(value, name) { var text = String(value || "") var wanted = String(name || "").toLowerCase() @@ -647,15 +563,11 @@ function contentTypeParam(value, name) { function mimeTypeOf(contentType) { var value = String(contentType || "").split(";")[0].trim().toLowerCase() - // No Content-Type at all means text/plain, which is what the RFC says and - // what a message from a script that forgot the header actually is. + // Invariant: absent Content-Type defaults to text/plain. return value === "" ? "text/plain" : value } -// Splits a multipart body on its boundary. Everything before the first -// delimiter is the preamble and everything after the closing one is the -// epilogue; both are for clients that do not understand MIME, and neither is -// part of the message. +// Invariant: multipart delimiters begin a line; preambles and epilogues are outside all parts. function splitMultipart(body, boundary) { var text = String(body || "") var marker = String(boundary || "") @@ -673,10 +585,7 @@ function splitMultipart(body, boundary) { return parts } -// Only ever asked about a body whose own Content-Type has already been shown -// to be wrong, so a guess is the best information there is. Deliberately -// narrow: a plain-text message that happens to mention should stay -// plain text, and only a document that opens like markup is treated as markup. +// Invariant: HTML sniffing is limited to a body whose declared type is already unusable. function looksLikeHtml(body) { return /^\s*( 0) return entity entity.mimeType = looksLikeHtml(body) ? "text/html" : "text/plain" } var bytes = decodeTransfer(body, headerFrom(headers, "Content-Transfer-Encoding")) entity.body.size = bytes.length - // base64url, because that is the shape `decodePart` decodes and the shape - // Gmail would have sent. Encoded from the byte array rather than from the - // string, so a Latin-1 body does not get re-encoded as UTF-8 on the way in. + // Invariant: preserve decoded byte values when converting to the provider payload's base64url representation. entity.body.data = bytesToBase64(bytes, true) - // An attachment needs an id before `attachments()` will list it. The part - // path is the honest one: it is what a later FETCH would ask for. + // Invariant: attachment listing requires a stable part ID even before any separate fetch. if (entity.filename !== "" || /attachment/i.test(disposition)) entity.body.attachmentId = "part:" + entity.partId return entity } -// The whole message. Returns the `payload` half of a Gmail message resource — -// the caller supplies the id, the labels and the internal date, because those -// come from the IMAP response rather than from the message itself. +// Docs: parseMime returns payload only; provider metadata supplies IDs, labels, and receipt time. function parseRfc822(raw) { return parseMimeEntity(raw, "", 0) } -// A list row's preview. Gmail sends one; IMAP has no equivalent, so it is made -// from the body once the body is here. Long enough to be useful, short enough -// that the cache is not storing the message twice. +// Performance: derive a bounded IMAP preview once rather than cache a second full body. function buildSnippet(text) { return String(text || "") .replace(/\s+/g, " ") @@ -768,8 +663,6 @@ function buildSnippet(text) { .substring(0, 200) } -// ------------------------------------------------------------------- dates - var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] @@ -790,8 +683,6 @@ function pad(value) { return (value < 10 ? "0" : "") + value } -// Compact enough for a list row: minutes for the last hour, then the clock -// time for today, a weekday for the last two days, and a date beyond it. function relativeTime(date, now) { if (!date) return "" var reference = now instanceof Date ? now : new Date(Number(now) || Date.now()) @@ -817,8 +708,6 @@ function fullTime(date) { + " " + pad(date.getHours()) + ":" + pad(date.getMinutes()) } -// ------------------------------------------------------------- row summary - function labelIds(message) { return message && Array.isArray(message.labelIds) ? message.labelIds : [] } @@ -828,40 +717,23 @@ function hasLabel(message, label) { } function decodeSnippet(text) { - // Gmail's snippet is HTML-escaped even though it carries no markup. + // Invariant: Gmail snippets are entity-escaped prose even when they contain no markup. return htmlToText(String(text || "")).replace(/\s+/g, " ").trim() } -// The conversation a row stands for: -// -// { id, count, unread, flagged, memberIds } -// -// Every summary carries one, whatever provider it came from, so a row and a -// cached row are the same shape and nothing above has to ask whether the block -// is there. `memberIds` are the counted members oldest first and `count` is -// their length — a count of 0 means the provider does not group its listing, or -// does not know, and the row draws no badge. A conversation is never one -// message: a count of 1 draws nothing either. -// -// `unread` and `flagged` are the whole conversation's, which is why the row's -// own `unread` and `starred` below take them as well as the message's. A -// provider that reports no block reports neither, so nothing changes for it. +// Docs: every summary carries a provider-neutral conversation; memberIds are oldest first and count matches their length. function threadOf(message) { var source = message && message.thread && typeof message.thread === "object" ? message.thread : {} return normalizeThread(source, message ? message.threadId : "") } -// A block in the shape above, whatever shape it arrived in: the ids trimmed -// and emptied of blanks, the count their length, the flags read as booleans, -// and `fallbackId` the thread id when the block names none. This is the one -// normalisation; `Conversation.blockOf` reads a cached row through it too. function normalizeThread(block, fallbackId) { var source = block && typeof block === "object" ? block : {} var list = Array.isArray(source.memberIds) ? source.memberIds : [] var ids = [] - for (var i = 0; i < list.length; i++) { - var id = String(list[i] === undefined || list[i] === null ? "" : list[i]).trim() + for (var listIndex = 0; listIndex < list.length; listIndex++) { + var id = String(list[listIndex] === undefined || list[listIndex] === null ? "" : list[listIndex]).trim() if (id !== "") ids.push(id) } return { @@ -880,7 +752,7 @@ function hasAttachments(message) { budget-- if (isAttachment(part)) return true var parts = Array.isArray(part.parts) ? part.parts : [] - for (var i = 0; i < parts.length; i++) if (walk(parts[i], depth + 1)) return true + for (var partIndex = 0; partIndex < parts.length; partIndex++) if (walk(parts[partIndex], depth + 1)) return true return false } return !!message && (message.hasAttachments === true || walk(message.payload, 0)) @@ -895,9 +767,7 @@ function summarize(message, now) { id: String(message && message.id ? message.id : ""), threadId: String(message && message.threadId ? message.threadId : ""), from: from, - // Reply-To and Message-ID only arrive with the full format, so a list row - // carries empty ones and the reader — which is where replying happens — - // carries the real values. + // Invariant: list metadata can omit Reply-To and Message-ID; full reader metadata supplies reply routing. replyTo: parseAddress(headerValue(message, "Reply-To")), messageId: headerValue(message, "Message-ID"), to: parseAddressList(headerValue(message, "To")), @@ -910,12 +780,7 @@ function summarize(message, now) { time: relativeTime(date, now), fullTime: fullTime(date), thread: thread, - // The conversation's, not only the representative's. A thread whose unread - // reply is not the message the server returned for this view is still an - // unread row, and the representative is a counted member of its own - // conversation in every view that can produce one — so the two readings - // agree wherever both have an answer, and the message's own is what is left - // when the block has none. + // Invariant: conversation unread and flagged state comes from all counted members, not just the representative. unread: hasLabel(message, "UNREAD") || thread.unread, starred: hasLabel(message, "STARRED") || thread.flagged, important: hasLabel(message, "IMPORTANT"), @@ -933,15 +798,13 @@ function summarize(message, now) { function draftAddressText(addresses) { var list = Array.isArray(addresses) ? addresses : [] var out = [] - for (var i = 0; i < list.length; i++) { - var email = String(list[i] && list[i].email ? list[i].email : "").trim() + for (var listIndex = 0; listIndex < list.length; listIndex++) { + var email = String(list[listIndex] && list[listIndex].email ? list[listIndex].email : "").trim() if (email !== "") out.push(email) } return out.join(", ") } -// A full draft read has the same provider-neutral summary and body as any -// message. Compose needs the addresses as editable text rather than row data. function draftFields(summary, body) { var source = summary || ({}) var subject = String(source.subject || "") @@ -951,8 +814,7 @@ function draftFields(summary, body) { to: draftAddressText(source.to), cc: draftAddressText(source.cc), bcc: draftAddressText(source.bcc), - // A Reply-To the draft was saved with comes back into the field it was - // typed in, or the next save would drop it. + // Invariant: preserve a saved draft's Reply-To field across another save. replyTo: String(source.replyTo && source.replyTo.email ? source.replyTo.email : ""), subject: subject === "(no subject)" ? "" : subject, body: String(body || ""), @@ -961,21 +823,12 @@ function draftFields(summary, body) { } } -// ------------------------------------------------------------- composition - -// A header value can never carry a line break. One would end the header and let -// whatever followed be read as the next one, which is how a Bcc gets into a -// message nobody wrote it into. Removed rather than rejected: the values that -// reach here are addresses and subjects, and a stray newline in one of them is -// not worth refusing to send over. +// Invariant: outgoing header values cannot contain line breaks that would introduce another header. function headerSafe(value) { return String(value === undefined || value === null ? "" : value).replace(/[\r\n]+/g, " ") } -// A display name is a phrase, not a header value: an encoded word may not sit -// inside quotes, and an ASCII name carrying a comma or a dot is only legal -// quoted. `foldHeader` cannot do this, because it encodes the whole value as -// one word — `=?UTF-8?B?...?=` wrapped around `"Name" ` is not an address. +// Invariant: encoded display words belong outside quotes; ASCII display punctuation uses a quoted phrase. function encodedPhrase(text) { var value = headerSafe(text).trim() if (value === "") return "" @@ -984,17 +837,7 @@ function encodedPhrase(text) { return '"' + value.replace(/([\\"])/g, "\\$1") + '"' } -// Written by hand rather than through `foldHeader` for the reason above. The -// address still loses its line breaks, so a display name cannot smuggle a -// second header in either. -// One address as a header *value*: `"Name" `, or the bare address when -// there is no name to put in front of it. -// -// Split out from `fromHeader` because a provider composing a message rather -// than parsing one needs the value without a field name — HEY's client builds a -// To line this way, and pasting `fromHeader`'s output into one produced -// `To: From: "Name" `, which `parseAddress` then read as a display -// name of `From: "Name"`. +// Docs: addressHeader returns a mailbox header value, without a field name, so provider adapters can reuse it. function addressHeader(email, displayName) { var address = headerSafe(email).trim() var phrase = encodedPhrase(displayName) @@ -1007,17 +850,12 @@ function fromHeader(email, displayName) { function foldHeader(name, value) { var text = headerSafe(value) - // Any non-ASCII in a header has to go back out as an encoded word, or Gmail - // rejects the raw message. + // Invariant: encode non-ASCII header values as RFC 2047 words for Gmail raw messages. if (/^[\x20-\x7e]*$/.test(text)) return name + ": " + text return name + ": =?UTF-8?B?" + encodeBase64(text) + "?=" } -// In-Reply-To and References carry a Message-ID, and a Message-ID is a string -// off a message a stranger sent — it reaches here having been read out of their -// headers and no further. It goes back out verbatim because a reply has to -// thread, so it is cut down to what a message id can legally be first: -// printable ASCII, on one line, no longer than a header may run. +// Invariant: sender-controlled threading IDs must remain bounded, printable, and on one line. function referenceValue(value) { return headerSafe(value).replace(/[^\x20-\x7e]+/g, "").substring(0, 512).trim() } @@ -1028,22 +866,11 @@ function quoteBody(summary, body) { : "" var lines = String(body || "").split("\n") var quoted = [] - for (var i = 0; i < lines.length; i++) quoted.push("> " + lines[i]) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) quoted.push("> " + lines[lineIndex]) return (header ? header + "\n" : "") + quoted.join("\n") } -// The body a compose window opens with. Two blank lines to type into, then -// whatever the user did not type but must be able to edit. -// -// A signature and a quote are the same kind of thing here — text placed under -// the cursor rather than by it — so they are joined the same way instead of -// being special-cased against each other. That is what keeps the signature -// next to the words it signs: below the reply, above the quoted thread, rather -// than stranded under a screen of somebody else's message. -// -// With no signature set this returns exactly what the caller used to build by -// hand, which is what makes the field optional rather than a new shape of -// draft. +// Invariant: placed signatures precede quoted history and follow the editable reply space. function composeBody(signature, quoted) { var parts = [] var sign = String(signature === undefined || signature === null ? "" : signature).trim() @@ -1060,26 +887,21 @@ function replySubject(subject) { return "Re: " + (text || "(no subject)") } -// A minimal RFC 5322 message. Gmail wants the whole thing base64url encoded in -// a single `raw` field, so this returns the string ready for that. -// Base64 body lines are wrapped at 76 characters as the RFC requires; Gmail -// accepts longer lines but other receiving servers do not. +// Invariant: MIME base64 lines wrap at 76 characters for receiving-server interoperability. function base64Body(text) { var encoded = encodeBase64(String(text || "")) var wrapped = [] - for (var i = 0; i < encoded.length; i += 76) wrapped.push(encoded.substr(i, 76)) + for (var index = 0; index < encoded.length; index += 76) wrapped.push(encoded.substr(index, 76)) return wrapped.join("\r\n") } -// Provider attachment bodies are base64url. MIME uses standard base64, but -// changing alphabets does not require decoding the binary file through a text -// string. Doing that would corrupt every byte sequence that is not UTF-8. +// Invariant: convert base64 alphabets without decoding binary attachments through a text string. function mimeBase64(data) { var encoded = String(data || "").replace(/[\r\n\s]/g, "") .replace(/-/g, "+").replace(/_/g, "/") while (encoded.length % 4 !== 0) encoded += "=" var wrapped = [] - for (var i = 0; i < encoded.length; i += 76) wrapped.push(encoded.substr(i, 76)) + for (var index = 0; index < encoded.length; index += 76) wrapped.push(encoded.substr(index, 76)) return wrapped.join("\r\n") } @@ -1089,10 +911,7 @@ function attachmentType(value) { ? type : "application/octet-stream" } -// The separator only has to be a string the parts do not contain, and every -// part here is base64 — an alphabet with no "_" in it, so a boundary carrying -// one cannot occur inside a body however long it is. The caller may name it, -// which is what lets a test read the message it built. +// Invariant: generated boundaries contain an underscore absent from standard base64 bodies. function mimeBoundary(given) { var stated = String(given || "").replace(/[^A-Za-z0-9'()+_,\-.\/:=?]/g, "") if (stated !== "") return stated.substring(0, 60) @@ -1100,46 +919,35 @@ function mimeBoundary(given) { return "=_Omamail_" + (new Date()).getTime().toString(36) + "_" + random } -// The domain of an address, reduced to the characters a domain may hold, or -// "" when the value carries none. function addressDomain(value) { var address = headerSafe(value).trim() var at = address.lastIndexOf("@") return at < 0 ? "" : address.substring(at + 1).replace(/[^A-Za-z0-9.-]/g, "") } -// The domain half of a Message-ID is the sender's own, so the id agrees with -// the address the message is from — or, when the From line is left for the -// provider to fill in, the address the mailbox is signed in as. Gmail writes -// its own From and the IMAP client puts the account on the envelope rather -// than in the headers, so a compose window sending none is ordinary; a JMAP -// server stores exactly the bytes it was handed, so there the fallback is what -// keeps the id in the account's own domain. +// Invariant: Message-ID uses the explicit sender domain or the signed-in mailbox domain. function messageIdDomain(from, accountAddress) { var domain = addressDomain(from) || addressDomain(accountAddress) - // RFC 2606 reserves .invalid, so a message with no address at all borrows no domain that belongs to somebody else. + // Invariant: RFC 2606 .invalid avoids borrowing a real domain when no sender domain is available. return domain === "" ? "omamail.invalid" : domain } -// Unique by the rule mimeBoundary already uses, and the caller may state one, which is what lets a test read it. -function messageIdValue(given, from, nowMs, accountAddress) { +function messageIdValue(given, from, nowMilliseconds, accountAddress) { var stated = String(given === undefined || given === null ? "" : given) - // A stated id is this client's own choice rather than a stranger's, so one that is not an id is replaced. + // Invariant: replace a malformed caller-supplied Message-ID with a generated valid one. if (stated.length <= 250 && /^<[A-Za-z0-9!#$%&'*+\/=?^_\x60{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_\x60{|}~-]+)*@[A-Za-z0-9!#$%&'*+\/=?^_\x60{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_\x60{|}~-]+)*>$/.test(stated)) return stated - var now = Math.floor(Number(nowMs) || Date.now()) + var now = Math.floor(Number(nowMilliseconds) || Date.now()) var random = Math.floor(Math.random() * 0x100000000).toString(36) return "<" + now.toString(36) + "." + random + ".omamail@" + messageIdDomain(from, accountAddress) + ">" } -// The date a message states, in RFC 5322's own shape: a numeric zone rather than toUTCString's obsolete GMT. -function sentDate(given, nowMs) { +// Invariant: outgoing Date uses RFC 5322 numeric timezone syntax. +function sentDate(given, nowMilliseconds) { var stated = headerSafe(given).trim() - // JavaScript also parses ISO dates and shorthand spellings that are not - // legal header values, so a stated date needs this client's canonical shape - // and RFC 5322's semantic calendar constraints. + // Invariant: JavaScript date parsing accepts non-header syntax; validate canonical header shape and calendar fields first. var canonical = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (0[1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9] [+-][0-9]{2}[0-5][0-9]$/ var parts = stated.match(canonical) if (parts) { @@ -1151,7 +959,7 @@ function sentDate(given, nowMs) { && calendar.getUTCDate() === day && WEEKDAYS[calendar.getUTCDay()] === parts[1]) return stated } - var date = new Date(nowMs === undefined || nowMs === null ? Date.now() : Number(nowMs)) + var date = new Date(nowMilliseconds === undefined || nowMilliseconds === null ? Date.now() : Number(nowMilliseconds)) if (isNaN(date.getTime())) date = new Date() var offset = -date.getTimezoneOffset() var minutes = Math.abs(offset) @@ -1161,32 +969,18 @@ function sentDate(given, nowMs) { + pad(Math.floor(minutes / 60)) + pad(minutes % 60) } -// One method name, and nothing that could end the header early: this string -// arrives from a calendar file somebody else wrote. +// Invariant: an untrusted calendar method cannot introduce another MIME header. function calendarMethod(value) { var text = String(value || "").toUpperCase().replace(/[^A-Z]/g, "") return text === "" ? "REPLY" : text.substring(0, 20) } -// Which way a message being sent runs. -// -// Qt resolves a compose field from the text already in it, so a writer sees -// their own paragraph against the right edge as they type it — but none of -// that travels with the message. A `text/plain` part states no direction at -// all, and a client with nothing to read falls back to left-to-right, which is -// why a Persian mail written here arrives in Gmail against the wrong edge. -// -// Read off the body by the same rule the reader uses, so a message arrives -// looking the way it looked while it was written. +// Invariant: an RTL plain-text message needs an HTML alternative to carry its direction to receiving clients. function outgoingDirection(body) { return Direction.resolve(body, Direction.AUTO) } -// The body again as the least markup that can carry a direction: the text -// escaped, its line breaks kept, and `dir` on the element every client reads -// it from. Not a rendering of the message — a statement about it, which is why -// nothing here styles anything. A recipient who prefers plain text still has -// the plain part, unchanged and listed first. +// Invariant: the HTML direction alternative escapes body text and preserves the plain-text alternative. function directionalHtmlBody(text, direction) { var body = String(text === undefined || text === null ? "" : text) .replace(/&/g, "&") @@ -1197,52 +991,39 @@ function directionalHtmlBody(text, direction) { return "" + body + "" } -// A nested boundary the enclosing one cannot be mistaken for. `splitMultipart` -// finds a delimiter by searching for "--" + boundary anywhere in the body, so -// an inner boundary that began with the outer one would be found by the outer -// scan too and the message would come apart at the wrong line. A prefix cannot -// collide that way; a suffix can. +// Invariant: RFC 2046 forbids a nested boundary beginning with the outer boundary; prefix the inner name instead of suffixing it. function nestedBoundary(outer) { return mimeBoundary("alt_" + String(outer || "")) } -// The body with an HTML signature: the plain text as the plain part, and an -// HTML part that is the same text escaped, paragraph by paragraph, with the -// stored signature markup in place of the plain signature at the end. The -// signature's data: images travel as related parts by cid, because Gmail's -// web client draws no data: image in HTML mail and a related part it does. -// `multipart/related` holds the alternative and the images; `mixed` holds -// that and any attachments, as before. +// Invariant: inline signature images use related CID parts because Gmail does not render data URLs in received HTML. function htmlBodyWithSignature(body, plainSignature, signatureHtml, direction) { var text = String(body === undefined || body === null ? "" : body) var sign = String(plainSignature === undefined || plainSignature === null ? "" : plainSignature).trim() - var dir = Direction.isRightToLeft(direction) ? " dir=\"rtl\"" : "" - // The first occurrence: the writer's own sign-off comes before any quote - // that happens to repeat it. A plain signature the writer took out of the - // body is not put back as markup — the two readings must say the same. + var directionAttribute = Direction.isRightToLeft(direction) ? " dir=\"rtl\"" : "" + // Invariant: replace the first sign-off only; a signature removed from plain text must not reappear in markup. var at = sign === "" ? -1 : text.indexOf(sign) if (sign !== "" && at < 0) - return "" + escapedParagraphs(text) + "" + return "" + escapedParagraphs(text) + "" var before, after if (at >= 0) { before = text.slice(0, at) after = text.slice(at + sign.length) } else { - // A signature that is only a picture has no words to find: it goes - // where the plain one would have, before the quote if there is one. + // Invariant: an image-only signature has no text marker and belongs before quoted history. var quoteAt = text.search(/(^|\n)>/) before = quoteAt >= 0 ? text.slice(0, quoteAt) : text after = quoteAt >= 0 ? text.slice(quoteAt) : "" } - return "" + escapedParagraphs(before) + return "" + escapedParagraphs(before) + String(signatureHtml || "") + escapedParagraphs(after) + "" } function escapedParagraphs(text) { var lines = String(text || "").replace(/\r\n/g, "\n").split("\n") var out = [] - for (var i = 0; i < lines.length; i++) { - out.push(lines[i].replace(/&/g, "&").replace(//g, ">")) + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + out.push(lines[lineIndex].replace(/&/g, "&").replace(//g, ">")) } var joined = out.join("
") return joined === "" ? "" : "
" + joined + "
" @@ -1271,8 +1052,8 @@ function pushSignedBodyPart(lines, values, direction, boundary) { lines.push("") lines.push(base64Body(html)) lines.push("--" + alt + "--") - for (var i = 0; i < swapped.parts.length; i++) { - var part = swapped.parts[i] + for (var index = 0; index < swapped.parts.length; index++) { + var part = swapped.parts[index] lines.push("--" + related) lines.push("Content-Type: " + part.mimeType) lines.push("Content-Transfer-Encoding: base64") @@ -1296,9 +1077,7 @@ function pushBodyPart(lines, body, direction, boundary, values) { lines.push(base64Body(body)) return } - // Least preferred first: a client that shows only one alternative should - // show the last it understands, and the HTML twin is the one that carries - // the direction. + // Invariant: MIME alternatives appear least preferred first so capable clients choose the directional HTML. lines.push("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"") lines.push("") lines.push("--" + boundary) @@ -1316,16 +1095,14 @@ function pushBodyPart(lines, body, direction, boundary, values) { function buildRawMessage(fields) { var values = fields || {} - // One reading of the clock for both headers, so a message cannot be dated a - // millisecond apart from the id that names it. + // Invariant: Date and Message-ID use one clock reading. var now = Date.now() var lines = [] if (values.from) lines.push(fromHeader(values.from, values.fromName)) lines.push(foldHeader("To", values.to || "")) if (values.cc) lines.push(foldHeader("Cc", values.cc)) if (values.bcc) lines.push(foldHeader("Bcc", values.bcc)) - // Where answers should go when that is not the sender: one header, folded - // like the rest, so a line break typed into it cannot start a second one. + // Invariant: Reply-To uses the same header-injection protection as other outgoing fields. if (values.replyTo) lines.push(foldHeader("Reply-To", values.replyTo)) lines.push(foldHeader("Subject", values.subject || "")) var inReplyTo = referenceValue(values.inReplyTo) @@ -1333,12 +1110,9 @@ function buildRawMessage(fields) { lines.push("In-Reply-To: " + inReplyTo) lines.push("References: " + (referenceValue(values.references) || inReplyTo)) } - // Behind the addressing rather than in front of it: RFC 5322 makes header - // order insignificant outside the trace fields, so the raw form still opens - // with the From line everything that reads one here already expects. - // RFC 5322 requires a Date on a message this client originates, and the writer's clock is the one it means. + // Invariant: originated messages include Date while preserving the established From-first header order. lines.push("Date: " + sentDate(values.date, now)) - // RFC 5322 asks every message for an id, and a relay told not to add missing headers relays none. + // Invariant: originate Message-ID because a relay may leave missing headers unchanged. lines.push("Message-ID: " + messageIdValue(values.messageId, values.from, now, values.accountAddress)) lines.push("MIME-Version: 1.0") @@ -1353,8 +1127,7 @@ function buildRawMessage(fields) { included.push(attachment) } - // Resolved once, here, so a message and the draft it was saved as cannot - // disagree about which way the same words run. + // Invariant: sent messages and saved drafts share one direction decision. var direction = outgoingDirection(values.body) if (!calendar && included.length === 0) { @@ -1383,14 +1156,7 @@ function buildRawMessage(fields) { return lines.join("\r\n") + "\r\n" } - // `multipart/alternative`, not `mixed`: the calendar part and the sentence - // beside it are two readings of one answer, and a client that understands - // the first should not also show the second as a file to open. It is also - // the shape every calendar server recognises a reply in — and the reason no - // HTML twin joins it the way one joins an ordinary body. An RSVP's sentence - // is generated rather than composed, so there is no writer's direction to - // carry, and a third alternative is a shape some of those servers do not - // expect. + // Invariant: calendar replies use multipart/alternative for the human sentence and RFC 5546 payload. var boundary = mimeBoundary(values.boundary) lines.push("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"") lines.push("") @@ -1412,17 +1178,13 @@ function buildRawMessage(fields) { function buildSendPayload(fields) { var payload = { raw: encodeBase64Url(buildRawMessage(fields)) } if (fields && fields.threadId) payload.threadId = String(fields.threadId) - // The draft this message replaces, so a provider that can destroy it in the - // same request as the send or the save does not leave the old copy behind. - // Always present and empty when the compose window was not opened from one, - // because a client reading it asks whether there is one to destroy rather - // than whether the field exists. + // Invariant: send and save retain the replaced draft ID so capable providers can remove the previous copy atomically. payload.draftId = String((fields && fields.draftId) || "") var files = Array.isArray(fields && fields.attachments) ? fields.attachments : [] var paths = [] - for (var i = 0; i < files.length; i++) { - if (files[i] && files[i].path) - paths.push({ path: String(files[i].path), filename: String(files[i].filename || "") }) + for (var fileIndex = 0; fileIndex < files.length; fileIndex++) { + if (files[fileIndex] && files[fileIndex].path) + paths.push({ path: String(files[fileIndex].path), filename: String(files[fileIndex].filename || "") }) } if (paths.length > 0) payload.attachments = paths return payload diff --git a/ui/message/Signature.js b/ui/message/Signature.js index 9daa7cd7f..1574c05ae 100644 --- a/ui/message/Signature.js +++ b/ui/message/Signature.js @@ -1,27 +1,13 @@ .pragma library .import "Html.js" as Html -// A signature imported from a file: a picture, or a page of markup somebody -// else's tool wrote. What is stored is never the file. A picture is checked -// to be the raster it claims and wrapped in one ``; markup goes through -// the same gate the reader trusts for a stranger's message — `Html.sanitize`, -// which drops scripts, handlers and every fetch — and is then walked once -// more here against a short list of what can never be in a signature, so -// the argument does not rest on one pass. The formatting the file carries -// — colours, faces, sizes, tables, alignment — is kept: it is what the -// owner imported the file for. Scripts, styles blocks, forms, frames, -// objects, event handlers, remote images and every address that is not a -// public link, a mailto or an inline picture do not survive, and the count -// of what was dropped is reported so the preview can say so. +// Invariant: imported signature HTML passes both the shared sanitizer and a stricter signature policy. var MAX_HTML_BYTES = 256 * 1024 var MAX_IMAGE_BYTES = 512 * 1024 var MAX_DATA_IMAGES = 8 -// What can never be in a signature, whatever the sanitiser kept: elements -// that run, embed, or take input, and attributes that name an address or a -// handler. Everything else — inline style without a url(), class, colour, -// face, size, alignment, table geometry — stays. +// Invariant: signatures forbid executable, embedded, interactive, and remote-loading content while preserving safe formatting. var FORBIDDEN_ELEMENTS = ["script", "style", "iframe", "frame", "frameset", "object", "embed", "applet", "form", "input", "button", "select", "textarea", "option", "svg", "math", "template", "link", "meta", "base", "video", "audio", "source", "track", "canvas", "noscript"] @@ -41,10 +27,10 @@ function base64Prefix(data, count) { var bytes = [] var bits = 0 var value = 0 - for (var i = 0; i < text.length && bytes.length < count; i++) { - var ch = text.charAt(i) - if (ch === "=") break - var index = alphabet.indexOf(ch) + for (var characterIndex = 0; characterIndex < text.length && bytes.length < count; characterIndex++) { + var character = text.charAt(characterIndex) + if (character === "=") break + var index = alphabet.indexOf(character) if (index < 0) return [] value = (value << 6) | index bits += 6 @@ -56,18 +42,16 @@ function base64Prefix(data, count) { return bytes } -// The raster a base64 body is, by its first bytes, or "" for anything else. -// The declared type is not consulted: an SVG named PNG is the case this -// exists to refuse, because SVG is a document with scripts in it. +// Invariant: inspect raster bytes rather than trust a declared image type; SVG must not be admitted as PNG. function rasterKind(base64) { var head = base64Prefix(base64, 16) - for (var r = 0; r < RASTERS.length; r++) { - var raster = RASTERS[r] + for (var rasterIndex = 0; rasterIndex < RASTERS.length; rasterIndex++) { + var raster = RASTERS[rasterIndex] var ok = head.length >= raster.magic.length - for (var i = 0; ok && i < raster.magic.length; i++) if (head[i] !== raster.magic[i]) ok = false + for (var headIndex = 0; ok && headIndex < raster.magic.length; headIndex++) if (head[headIndex] !== raster.magic[headIndex]) ok = false if (ok && raster.at12) { ok = head.length >= 16 - for (var j = 0; ok && j < 4; j++) if (head[8 + j] !== raster.at12[j]) ok = false + for (var signatureIndex = 0; ok && signatureIndex < 4; signatureIndex++) if (head[8 + signatureIndex] !== raster.at12[signatureIndex]) ok = false } if (ok) return raster.mime } @@ -80,7 +64,6 @@ function base64Bytes(base64) { return Math.floor(text.length * 3 / 4) - padding } -// A picture as a signature: one image, its type read from its bytes. function importImage(base64, options) { var settings = options || {} var limit = Math.max(1, Math.floor(Number(settings.maxImageBytes) || MAX_IMAGE_BYTES)) @@ -107,36 +90,61 @@ function hrefOk(value) { return !!match && Html.isPublicHost(match[1]) } -// The second walk: drop what can never be here, count it, keep the rest. -function prune(node, ctx) { +function signatureAttributes(node, name, context) { + var attributes = [] + var list = Array.isArray(node.attrs) ? node.attrs : [] + for (var attributeIndex = 0; attributeIndex < list.length; attributeIndex++) { + var attribute = list[attributeIndex] + var attributeName = String(attribute.name || "").toLowerCase() + var value = String(attribute.value === undefined ? "" : attribute.value) + if (!signatureAttributeAllowed(attributeName, value, name, context)) { + context.dropped++ + continue + } + attributes.push({ name: attributeName, value: value }) + } + return attributes +} + +function signatureAttributeAllowed(attributeName, value, elementName, context) { + if (attributeName.indexOf("on") === 0 || FORBIDDEN_ATTRIBUTES.indexOf(attributeName) >= 0) return false + if (attributeName === "href") return hrefOk(value) + if (attributeName === "src") { + if (elementName !== "img" || !dataImageOk(value, context.imageLimit) || context.images >= MAX_DATA_IMAGES) return false + context.images++ + return true + } + // Invariant: signature styles cannot fetch resources, execute content, or hide words. + if (attributeName === "style") + return !/url\s*\(|expression\s*\(|@import|behavior\s*:|javascript:|display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?![.\d])|font-size\s*:\s*0(?![.\d])|font-size\s*:\s*0?\.\d|text-indent\s*:\s*-/i.test(value) + return true +} + +function prune(node, context) { var kept = [] - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] - if (child.type === "text") { kept.push(child); continue } - if (child.type !== "element") { ctx.dropped++; continue } + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] + if (child.type === "text") { + kept.push(child) + continue + } + if (child.type !== "element") { + context.dropped++ + continue + } var name = String(child.name || "").toLowerCase() - if (FORBIDDEN_ELEMENTS.indexOf(name) >= 0) { ctx.dropped++; continue } - var attrs = [] - var list = Array.isArray(child.attrs) ? child.attrs : [] - for (var a = 0; a < list.length; a++) { - var attr = list[a] - var attrName = String(attr.name || "").toLowerCase() - var value = String(attr.value === undefined ? "" : attr.value) - if (attrName.indexOf("on") === 0 || FORBIDDEN_ATTRIBUTES.indexOf(attrName) >= 0) { ctx.dropped++; continue } - if (attrName === "href" && !hrefOk(value)) { ctx.dropped++; continue } - if (attrName === "src") { - if (name !== "img" || !dataImageOk(value, ctx.imageLimit) || ctx.images >= MAX_DATA_IMAGES) { ctx.dropped++; continue } - ctx.images++ - } - // A style that fetches, runs, or hides text is dropped whole: a - // signature has no business carrying invisible words. - if (attrName === "style" && /url\s*\(|expression\s*\(|@import|behavior\s*:|javascript:|display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?![.\d])|font-size\s*:\s*0(?![.\d])|font-size\s*:\s*0?\.\d|text-indent\s*:\s*-/i.test(value)) { ctx.dropped++; continue } - attrs.push({ name: attrName, value: value }) + if (FORBIDDEN_ELEMENTS.indexOf(name) >= 0) { + context.dropped++ + continue } - child.attrs = attrs + var attributes = signatureAttributes(child, name, context) + child.attrs = attributes child.name = name - if (name === "img" && attrs.filter(function(x) { return x.name === "src" }).length === 0) { ctx.dropped++; continue } - prune(child, ctx) + if (name === "img" && !attributes.some(function(attribute) { return attribute.name === "src" })) { + context.dropped++ + continue + } + prune(child, context) kept.push(child) } node.children = kept @@ -147,38 +155,32 @@ function sourceRemovals(source) { var count = 0 var patterns = [/<\s*(script|style|iframe|object|embed|form|input|svg|template|link|meta)\b/gi, /\son[a-z]+\s*=/gi, /javascript\s*:/gi, /url\s*\(/gi, /\sbackground\s*=/gi] - for (var i = 0; i < patterns.length; i++) { - var found = text.match(patterns[i]) + for (var patternIndex = 0; patternIndex < patterns.length; patternIndex++) { + var found = text.match(patterns[patternIndex]) if (found) count += found.length } return count } -// Markup as a signature. Returns what is stored (`html`), the plain text a -// text-only client sees (`plain`), how many things were dropped, and a -// problem where the file cannot be a signature at all. function importHtml(html, options) { var settings = options || {} var source = String(html === undefined || html === null ? "" : html) if (source.length > Math.max(1, Math.floor(Number(settings.maxHtmlBytes) || MAX_HTML_BYTES))) return { html: "", plain: "", dropped: 0, images: 0, problem: "That file is too large for a signature" } var cleaned = Html.sanitize(source, { allowRemoteImages: false, keepColors: true }) - // What the sanitiser took out is counted from the source, since it reports - // only images: every script, frame, form and handler the file carried is a - // removal the preview should own up to. - var ctx = { dropped: sourceRemovals(source) + cleaned.blockedImages, images: 0, + // Docs: count non-image removals from the source because Html reports only blocked images. + var context = { dropped: sourceRemovals(source) + cleaned.blockedImages, images: 0, imageLimit: Math.max(1, Math.floor(Number(settings.maxImageBytes) || MAX_IMAGE_BYTES)) } var document = Html.parse(cleaned.html) - prune(document, ctx) + prune(document, context) var text = Html.serialize(document) var read = Html.readTree(document) var plain = String(read && read.text !== undefined ? read.text : read || "").replace(/[ \t]+\n/g, "\n").trim() - if (text.trim() === "" || (plain === "" && ctx.images === 0)) - return { html: "", plain: "", dropped: ctx.dropped, images: 0, problem: "Nothing in that file can be a signature" } - return { html: text, plain: plain, dropped: ctx.dropped, images: ctx.images, problem: "" } + if (text.trim() === "" || (plain === "" && context.images === 0)) + return { html: "", plain: "", dropped: context.dropped, images: 0, problem: "Nothing in that file can be a signature" } + return { html: text, plain: plain, dropped: context.dropped, images: context.images, problem: "" } } -// What the preview says about the import. function importNote(result) { if (!result) return "" if (result.problem) return result.problem @@ -188,9 +190,7 @@ function importNote(result) { return parts.length === 0 ? "Imported" : "Imported: " + parts.join(", ") } -// The data: images a stored signature carries, each swapped for a cid: so -// the message can carry them as parts; a client that hides data: images in -// HTML mail still shows a related part. +// Invariant: convert stored data images to CID parts for receiving clients that suppress data URLs. function inlineParts(html, prefix) { var text = String(html || "") var parts = [] diff --git a/ui/message/Unsubscribe.js b/ui/message/Unsubscribe.js index 2302b0cd1..3b6232178 100644 --- a/ui/message/Unsubscribe.js +++ b/ui/message/Unsubscribe.js @@ -1,41 +1,26 @@ .pragma library .import "Html.js" as Html +.import "Mailto.js" as Mailto -// Getting off a mailing list, out of the headers the list already sends. -// -// `List-Unsubscribe` has been in every newsletter since RFC 2369, and RFC 8058 -// added the one line that makes a single click enough: a sender that also sends -// `List-Unsubscribe-Post` has promised that one POST removes the address, with -// no page to visit and no form to fill in. That is the whole of the fast path, -// and it is the same promise Gmail's own "Unsubscribe" button relies on. -// -// Everything here decides; nothing here fetches. Which URL may be posted to is -// the one question worth being careful about, and it is answered in one place. - -// A header long enough to be an attack rather than a list. Real ones are two -// entries. +// Invariant: unsubscribe planning is pure; network dispatch must validate the chosen destination separately. var MAX_HEADER_LENGTH = 2048 var MAX_ENTRIES = 8 -// ------------------------------------------------------------------ header - -// Entries are bracketed rather than separated, because a mailto's query string -// legitimately holds the comma the RFC also uses as the separator. Scanning for -// the brackets is what stops "" being read as two. +// Invariant: List-Unsubscribe uses bracketed entries because commas can occur inside a mailto query. function entries(value) { var text = String(value || "") if (text.length > MAX_HEADER_LENGTH) return [] var found = [] var open = -1 - for (var i = 0; i < text.length && found.length < MAX_ENTRIES; i++) { - var character = text.charAt(i) + for (var index = 0; index < text.length && found.length < MAX_ENTRIES; index++) { + var character = text.charAt(index) if (character === "<") { - open = i + open = index continue } if (character !== ">" || open < 0) continue - var raw = text.substring(open + 1, i) + var raw = text.substring(open + 1, index) var entry = /[\u0000-\u001f\u007f]/.test(raw) ? "" : raw.trim() if (entry !== "") found.push(entry) open = -1 @@ -43,34 +28,13 @@ function entries(value) { return found } -// ------------------------------------------------------------------ mailto - -function percentDecode(value) { - var text = String(value || "") - try { - return decodeURIComponent(text) - } catch (e) { - // A stray percent that is not an escape. The raw text is still closer to - // what the sender meant than nothing is. - return text - } -} - -// Anything that could start a header of its own is removed rather than escaped. -// This value is going into a message this plugin builds, and a subject holding -// a newline is how a list gets to write its own Bcc. -function headerSafe(value) { - return String(value || "").replace(/[\r\n]+/g, " ").trim() -} - function parseMailto(entry) { var text = String(entry || "") if (!/^mailto:/i.test(text)) return null var rest = text.substring(7) var mark = rest.indexOf("?") - var to = headerSafe(percentDecode(mark < 0 ? rest : rest.substring(0, mark))) - // One recipient. A List-Unsubscribe naming several is unusual, and sending to - // the first is the one that unambiguously belongs to this list. + var to = Mailto.headerSafe(Mailto.percentDecode(mark < 0 ? rest : rest.substring(0, mark))) + // Invariant: unsubscribe mail targets one path recipient and never adopts query recipients. to = to.split(",")[0].trim() if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) return null @@ -78,18 +42,16 @@ function parseMailto(entry) { var body = "" if (mark >= 0) { var pairs = rest.substring(mark + 1).split("&") - for (var i = 0; i < pairs.length; i++) { - var equals = pairs[i].indexOf("=") + for (var pairIndex = 0; pairIndex < pairs.length; pairIndex++) { + var equals = pairs[pairIndex].indexOf("=") if (equals < 0) continue - var key = pairs[i].substring(0, equals).toLowerCase() - var raw = percentDecode(pairs[i].substring(equals + 1)) - if (key === "subject") subject = headerSafe(raw) + var key = pairs[pairIndex].substring(0, equals).toLowerCase() + var raw = Mailto.percentDecode(pairs[pairIndex].substring(equals + 1)) + if (key === "subject") subject = Mailto.headerSafe(raw) else if (key === "body") body = String(raw) } } - // A list that asked for nothing still needs a message with something in it: - // `send` refuses an empty body, and an empty subject reads as a mistake in - // the sent folder. + // Invariant: default unsubscribe subject and body keep an otherwise empty request sendable. return { to: to, subject: subject !== "" ? subject : "Unsubscribe", @@ -97,14 +59,7 @@ function parseMailto(entry) { } } -// --------------------------------------------------------------------- URL - -// The sender chose this address and this plugin is about to send a request to -// it, so the question is not whether it parses but where it points. -// `Html.imageSourceKind` is already the one place that separates a host on the -// public internet from loopback, a private range, a link-local address and a -// single-label name — the same judgement that decides whether a message may -// load a picture, for the same reason. +// Invariant: sender-controlled unsubscribe URLs must pass the same public-address policy as remote images. function isPublicWebUrl(value) { if (/[\u0000-\u001f\u007f]/.test(String(value || ""))) return false var text = String(value || "").trim() @@ -112,32 +67,23 @@ function isPublicWebUrl(value) { return Html.imageSourceKind(text) === "remote" } -// A one-click POST is https only. RFC 8058 says so, and the reason is that -// this request carries the fact that this address reads this mail — over -// plain http that is a postcard, sent to a host chosen by the sender. +// Invariant: RFC 8058 one-click POST requires HTTPS. function isPostableUrl(value) { return /^https:\/\//i.test(String(value || "").trim()) && isPublicWebUrl(value) } -// ------------------------------------------------------------------ result - function empty() { return { available: false, oneClick: false, url: "", postUrl: "", mail: null } } -// What this message offers, out of its own two headers. -// -// `oneClick` is not "there is an https URL". It is the sender having said, in -// `List-Unsubscribe-Post`, that posting to it is enough — without that line a -// POST would be a guess at somebody else's API, and the honest thing is to -// open the page and let the user finish there. +// Invariant: an HTTPS URL alone never authorizes POST; List-Unsubscribe-Post must declare one-click support. function from(listHeader, postHeader) { var result = empty() var list = entries(listHeader) if (list.length === 0) return result - for (var i = 0; i < list.length; i++) { - var entry = list[i] + for (var listIndex = 0; listIndex < list.length; listIndex++) { + var entry = list[listIndex] if (/^mailto:/i.test(entry)) { if (!result.mail) result.mail = parseMailto(entry) continue @@ -156,7 +102,6 @@ function from(listHeader, postHeader) { return result } -// The Gmail message resource shape, which is what every provider hands back. function fromMessage(message) { var headers = message && message.payload && Array.isArray(message.payload.headers) ? message.payload.headers @@ -168,23 +113,15 @@ function fromHeaders(headers) { var list = Array.isArray(headers) ? headers : [] var listHeader = "" var postHeader = "" - for (var i = 0; i < list.length; i++) { - var name = String(list[i].name || "").toLowerCase() - if (name === "list-unsubscribe" && listHeader === "") listHeader = String(list[i].value || "") - else if (name === "list-unsubscribe-post" && postHeader === "") postHeader = String(list[i].value || "") + for (var listIndex = 0; listIndex < list.length; listIndex++) { + var name = String(list[listIndex].name || "").toLowerCase() + if (name === "list-unsubscribe" && listHeader === "") listHeader = String(list[listIndex].value || "") + else if (name === "list-unsubscribe-post" && postHeader === "") postHeader = String(list[listIndex].value || "") } return from(listHeader, postHeader) } -// ------------------------------------------------------------------- plan - -// How the button behaves, decided once so no view branches on a header. -// -// The order is how little the user has to do, not how much this plugin would -// enjoy doing it. A declared one-click POST finishes without leaving the -// window; a mailto finishes without leaving it either, on any account that can -// send; a page has to be opened and read, so it goes last and its label says -// so with a trailing "...". +// Invariant: prefer one-click POST, then supported mail, then opening the sender's page. function plan(info, canSend) { var found = info || empty() if (found.oneClick && found.postUrl !== "") return "post" @@ -194,17 +131,13 @@ function plan(info, canSend) { return "" } -// A page is the only one of the three that leaves the window, and the label -// has to say that before it is pressed. +// Invariant: a browser action uses an ellipsis because it leaves the app to finish the workflow. function label(info, canSend) { var how = plan(info, canSend) if (how === "") return "" return how === "browser" ? "Unsubscribe..." : "Unsubscribe" } -// The sentence beside the button. It says what pressing it does, because -// "unsubscribe" means three different amounts of work here and the user is -// entitled to know which one they are agreeing to. function explanation(info, canSend) { var how = plan(info, canSend) if (how === "post") return "This sender accepts a one-click unsubscribe" @@ -213,7 +146,7 @@ function explanation(info, canSend) { return "" } -// The body of an RFC 8058 POST. Fixed by the standard, and the whole of it. +// Invariant: the RFC 8058 request body and content type are fixed protocol values. function postBody() { return "List-Unsubscribe=One-Click" } From 6df43f73c6e0c9ad4ed9beb4ebede74a09d0f2af Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 149/568] Fix UTF-8 scalar and calendar value validation --- ui/message/AttachmentPreview.js | 3 +- ui/message/Calendar.js | 31 ++++++--- ui/message/Message.js | 99 +++++++++++++---------------- ui/tests/test_attachment_preview.js | 6 ++ ui/tests/test_calendar.js | 14 ++++ ui/tests/test_message.js | 14 ++++ 6 files changed, 102 insertions(+), 65 deletions(-) diff --git a/ui/message/AttachmentPreview.js b/ui/message/AttachmentPreview.js index c8f1be68e..a28e95f9c 100644 --- a/ui/message/AttachmentPreview.js +++ b/ui/message/AttachmentPreview.js @@ -4,8 +4,9 @@ function supported(attachment) { var file = attachment || ({}) var mime = String(file.mimeType || "").toLowerCase() + var size = Number(file.size || 0) return String(file.attachmentId || "") !== "" - && Number(file.size || 0) <= 8 * 1024 * 1024 + && isFinite(size) && size >= 0 && size <= 8 * 1024 * 1024 && ["application/pdf", "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"].indexOf(mime) >= 0 } diff --git a/ui/message/Calendar.js b/ui/message/Calendar.js index 13b8432a8..aec8f4a63 100644 --- a/ui/message/Calendar.js +++ b/ui/message/Calendar.js @@ -5,6 +5,7 @@ // Docs: Calendar invitations are MIME parts; RSVP uses an RFC 5546 reply addressed to the organiser. var MAX_ICS_BYTES = 512 * 1024 +var MAX_ICS_CODE_UNITS = 512 * 1024 var MAX_COMPONENT_DEPTH = 8 // Invariant: unfold content lines before parsing properties so folded escapes remain intact. @@ -111,7 +112,7 @@ function stripQuotes(value) { function parse(text) { var source = String(text || "") - if (source.length > MAX_ICS_BYTES) return null + if (source.length > MAX_ICS_CODE_UNITS) return null var lines = unfoldLines(source) var root = null var stack = [] @@ -296,8 +297,21 @@ function parseOffsetMinutes(value) { // Docs: naiveKey compares wall-clock readings without applying a timezone offset. function naiveKey(fields) { - return Date.UTC(fields.year, fields.month - 1, fields.day, - fields.hour, fields.minute, fields.second) + return utcDate(fields).getTime() +} + +function utcDate(fields) { + var date = new Date(0) + date.setUTCFullYear(fields.year, fields.month - 1, fields.day) + date.setUTCHours(fields.hour || 0, fields.minute || 0, fields.second || 0, 0) + return date +} + +function localDate(fields) { + var date = new Date(0) + date.setFullYear(fields.year, fields.month - 1, fields.day) + date.setHours(fields.hour || 0, fields.minute || 0, fields.second || 0, 0) + return date } function daysInMonth(year, month) { @@ -310,7 +324,7 @@ function nthWeekdayOfMonth(year, month, weekday, ordinal) { var total = daysInMonth(year, month) if (ordinal < 0) { for (var back = total; back >= 1; back--) { - if (new Date(Date.UTC(year, month - 1, back)).getUTCDay() === weekday) { + if (utcDate({ year: year, month: month, day: back }).getUTCDay() === weekday) { var skipped = -ordinal - 1 var day = back - skipped * 7 return day >= 1 ? day : 0 @@ -321,7 +335,7 @@ function nthWeekdayOfMonth(year, month, weekday, ordinal) { var wanted = ordinal < 1 ? 1 : ordinal var seen = 0 for (var forward = 1; forward <= total; forward++) { - if (new Date(Date.UTC(year, month - 1, forward)).getUTCDay() !== weekday) continue + if (utcDate({ year: year, month: month, day: forward }).getUTCDay() !== weekday) continue seen++ if (seen === wanted) return forward } @@ -439,7 +453,7 @@ function recurringTransition(rule, year) { } if (day < 1 || day > daysInMonth(year, month)) return null - var at = Date.UTC(year, month - 1, day, start.hour, start.minute, start.second) + var at = naiveKey({ year: year, month: month, day: day, hour: start.hour, minute: start.minute, second: start.second }) // Invariant: compare UTC UNTIL against the transition using its previous offset; date-only UNTIL includes the entire day. if (until) { var reading = until.utc && rule.from !== null ? at - rule.from * 60000 : at @@ -581,7 +595,7 @@ function resolveTime(found, calendar) { if (fields.dateOnly) { return { - ms: new Date(fields.year, fields.month - 1, fields.day).getTime(), + ms: localDate(fields).getTime(), allDay: true, tzid: "", resolved: true } } @@ -603,8 +617,7 @@ function resolveTime(found, calendar) { } // Invariant: floating iCalendar times use the reader's local clock. return { - ms: new Date(fields.year, fields.month - 1, fields.day, - fields.hour, fields.minute, fields.second).getTime(), + ms: localDate(fields).getTime(), allDay: false, tzid: "", resolved: true } } diff --git a/ui/message/Message.js b/ui/message/Message.js index 4fac8be60..80dc5b6eb 100644 --- a/ui/message/Message.js +++ b/ui/message/Message.js @@ -38,41 +38,50 @@ function base64ToBytes(text) { return bytes } +function utf8Scalar(bytes, index) { + var first = bytes[index] + if (first < 0x80) return first + var width = first >= 0xc2 && first <= 0xdf ? 2 + : (first >= 0xe0 && first <= 0xef ? 3 : (first >= 0xf0 && first <= 0xf4 ? 4 : 0)) + if (width === 0 || index + width > bytes.length) return -1 + var codePoint = first & (width === 2 ? 0x1f : (width === 3 ? 0x0f : 0x07)) + for (var offset = 1; offset < width; offset++) { + var continuation = bytes[index + offset] + if (continuation < 0x80 || continuation > 0xbf) return -1 + codePoint = (codePoint << 6) | (continuation & 0x3f) + } + if (width === 3 && codePoint < 0x800) return -1 + if (width === 4 && (codePoint < 0x10000 || codePoint > 0x10ffff)) return -1 + if (codePoint >= 0xd800 && codePoint <= 0xdfff) return -1 + return codePoint +} + function bytesToUtf8(bytes) { - var out = "" + var result = "" var byteIndex = 0 - var length = bytes.length - while (byteIndex < length) { - var byte1 = bytes[byteIndex++] - if (byte1 < 0x80) { - out += String.fromCharCode(byte1) + while (byteIndex < bytes.length) { + var first = bytes[byteIndex] + if (first < 0x80) { + result += String.fromCharCode(first) + byteIndex++ continue } - var codePoint = -1 - if (byte1 >= 0xc2 && byte1 <= 0xdf && byteIndex < length) { - codePoint = ((byte1 & 0x1f) << 6) | (bytes[byteIndex] & 0x3f) - byteIndex += 1 - } else if (byte1 >= 0xe0 && byte1 <= 0xef && byteIndex + 1 < length) { - codePoint = ((byte1 & 0x0f) << 12) | ((bytes[byteIndex] & 0x3f) << 6) | (bytes[byteIndex + 1] & 0x3f) - byteIndex += 2 - } else if (byte1 >= 0xf0 && byte1 <= 0xf4 && byteIndex + 2 < length) { - codePoint = ((byte1 & 0x07) << 18) | ((bytes[byteIndex] & 0x3f) << 12) - | ((bytes[byteIndex + 1] & 0x3f) << 6) | (bytes[byteIndex + 2] & 0x3f) - byteIndex += 3 - } + var codePoint = utf8Scalar(bytes, byteIndex) if (codePoint < 0) { // Invariant: malformed UTF-8 bytes fall back individually to Latin-1 so message text remains readable. - out += String.fromCharCode(byte1) + result += String.fromCharCode(first) + byteIndex++ continue } - if (codePoint > 0xffff) { - codePoint -= 0x10000 - out += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) - } else { - out += String.fromCharCode(codePoint) + byteIndex += codePoint < 0x800 ? 2 : (codePoint < 0x10000 ? 3 : 4) + if (codePoint <= 0xffff) { + result += String.fromCharCode(codePoint) + continue } + codePoint -= 0x10000 + result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) } - return out + return result } function bytesToLatin1(bytes) { @@ -107,6 +116,7 @@ function utf8Bytes(text) { index++ } } + if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd if (code < 0x80) bytes.push(code) else if (code < 0x800) bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)) else if (code < 0x10000) bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f)) @@ -159,40 +169,19 @@ function decodeQuotedPrintableWord(text) { // Invariant: only fully valid multibyte UTF-8 overrides a declared single-byte charset. function looksLikeUtf8(bytes) { var values = bytes || [] - var multi = 0 + var multibyte = false var byteIndex = 0 while (byteIndex < values.length) { - var byte1 = values[byteIndex++] - if (byte1 < 0x80) continue - var needed = 0 - var codePoint = 0 - if (byte1 >= 0xc2 && byte1 <= 0xdf) { - needed = 1 - codePoint = byte1 & 0x1f - } else if (byte1 >= 0xe0 && byte1 <= 0xef) { - needed = 2 - codePoint = byte1 & 0x0f - } else if (byte1 >= 0xf0 && byte1 <= 0xf4) { - needed = 3 - codePoint = byte1 & 0x07 - } else { - - return false - } - if (byteIndex + needed > values.length) return false - for (var continuationIndex = 0; continuationIndex < needed; continuationIndex++) { - var next = values[byteIndex + continuationIndex] - if (next < 0x80 || next > 0xbf) return false - codePoint = (codePoint << 6) | (next & 0x3f) + if (values[byteIndex] < 0x80) { + byteIndex++ + continue } - byteIndex += needed - if (needed === 1 && codePoint < 0x80) return false - if (needed === 2 && codePoint < 0x800) return false - if (needed === 3 && (codePoint < 0x10000 || codePoint > 0x10ffff)) return false - if (codePoint >= 0xd800 && codePoint <= 0xdfff) return false - multi += 1 + var codePoint = utf8Scalar(values, byteIndex) + if (codePoint < 0) return false + byteIndex += codePoint < 0x800 ? 2 : (codePoint < 0x10000 ? 3 : 4) + multibyte = true } - return multi > 0 + return multibyte } function decodeWordBytes(charset, bytes) { diff --git a/ui/tests/test_attachment_preview.js b/ui/tests/test_attachment_preview.js index a961b62b4..a089af9b8 100644 --- a/ui/tests/test_attachment_preview.js +++ b/ui/tests/test_attachment_preview.js @@ -12,4 +12,10 @@ for (const file of [{attachmentId:"1",mimeType:"image/svg+xml"}, {attachmentId:" assert.equal(preview.fileLabel({filename:"report.pdf",mimeType:"application/pdf"}), "PDF") assert.equal(preview.fileLabel({filename:"budget.xlsx"}), "XLSX") assert.equal(preview.fileLabel({filename:''}), "File") + +for (const size of [-1, Infinity, "unknown"]) { + assert.strictEqual(preview.supported({attachmentId: "part", mimeType: "application/pdf", size}), false, + "unusable attachment size metadata cannot authorize a preview fetch") +} + console.log("test_attachment_preview.js ok") diff --git a/ui/tests/test_calendar.js b/ui/tests/test_calendar.js index 7d5f8eddc..f8751d8c4 100644 --- a/ui/tests/test_calendar.js +++ b/ui/tests/test_calendar.js @@ -775,4 +775,18 @@ assert.strictEqual(feedEvents[1].start.allDay, true) assert.strictEqual(calendar.parseOffsetMinutes('+010521'),65.35) } + +{ + const fields = calendar.parseDateValue("00990228T123000Z") + assert.strictEqual(new Date(calendar.naiveKey(fields)).getUTCFullYear(), 99) + assert.strictEqual(new Date(calendar.naiveKey(fields)).getUTCMonth(), 1) + assert.strictEqual(new Date(calendar.naiveKey(fields)).getUTCDate(), 28) + for (const stamp of ["00990228T123000", "00990228"]) { + const resolved = calendar.resolveTime(calendar.parseProperty("DTSTART:" + stamp), null) + assert.strictEqual(new Date(resolved.ms).getFullYear(), 99) + assert.strictEqual(new Date(resolved.ms).getMonth(), 1) + assert.strictEqual(new Date(resolved.ms).getDate(), 28) + } +} + console.log("test_calendar.js ok") diff --git a/ui/tests/test_message.js b/ui/tests/test_message.js index 1b74e36be..441d85f4d 100644 --- a/ui/tests/test_message.js +++ b/ui/tests/test_message.js @@ -1339,6 +1339,20 @@ assert.strictEqual(message.composeBody("\n\n", ""), "") assert.strictEqual(message.contentTypeParam('attachment; filename="a\\\"b.txt"','filename'),'a"b.txt') } + +{ + for (const bytes of [[0xc2, 0x41], [0xe0, 0x80, 0xbc], [0xed, 0xa0, 0x80], [0xf4, 0x90, 0x80, 0x80]]) { + assert.strictEqual(message.bytesToUtf8(bytes), String.fromCharCode(...bytes)) + assert.strictEqual(message.looksLikeUtf8(bytes), false) + } + assert.strictEqual(message.bytesToUtf8([0xe0, 0x80, 0xbc]).includes("<"), false, + "an overlong sequence cannot synthesize a markup delimiter") + for (const value of ["\ud800x", "x\udc00", "\ud800\ud800", "😀"]) { + deepEqual(message.utf8Bytes(value), Array.from(Buffer.from(value)), + "isolated surrogates encode as the Unicode replacement character") + } +} + console.log("test_message.js ok") // A draft reopened from the server keeps the Reply-To it was saved with. assert.strictEqual(message.draftFields({ replyTo: { email: "team@example.com" }, to: [] }, "x").replyTo, "team@example.com") From 213923097ad256e83c85fc9aeae8a8e68d169f88 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 150/568] Remove unused message reference helpers --- ui/message/Message.js | 23 +- ui/message/Outbox.js | 10 - ui/message/Signature.js | 4 +- ui/message/Unsubscribe.js | 9 - ui/tests/qml/tst_message_base64.qml | 30 +++ ui/tests/test_calendar.js | 110 +++------- ui/tests/test_mailto.js | 8 +- ui/tests/test_message.js | 330 +++++++++------------------- ui/tests/test_outbox.js | 17 +- ui/tests/test_signature.js | 8 +- ui/tests/test_unsubscribe.js | 43 +--- 11 files changed, 191 insertions(+), 401 deletions(-) diff --git a/ui/message/Message.js b/ui/message/Message.js index 80dc5b6eb..b09169eec 100644 --- a/ui/message/Message.js +++ b/ui/message/Message.js @@ -15,11 +15,6 @@ var B64_LOOKUP = (function() { return table })() -function b64Index(character) { - var value = B64_LOOKUP[character] - return value === undefined ? -1 : value -} - function base64ToBytes(text) { var input = String(text || "") var bytes = [] @@ -43,16 +38,16 @@ function utf8Scalar(bytes, index) { if (first < 0x80) return first var width = first >= 0xc2 && first <= 0xdf ? 2 : (first >= 0xe0 && first <= 0xef ? 3 : (first >= 0xf0 && first <= 0xf4 ? 4 : 0)) - if (width === 0 || index + width > bytes.length) return -1 + if (width === 0 || index + width > bytes.length) return null var codePoint = first & (width === 2 ? 0x1f : (width === 3 ? 0x0f : 0x07)) for (var offset = 1; offset < width; offset++) { var continuation = bytes[index + offset] - if (continuation < 0x80 || continuation > 0xbf) return -1 + if (continuation < 0x80 || continuation > 0xbf) return null codePoint = (codePoint << 6) | (continuation & 0x3f) } - if (width === 3 && codePoint < 0x800) return -1 - if (width === 4 && (codePoint < 0x10000 || codePoint > 0x10ffff)) return -1 - if (codePoint >= 0xd800 && codePoint <= 0xdfff) return -1 + if (width === 3 && codePoint < 0x800) return null + if (width === 4 && (codePoint < 0x10000 || codePoint > 0x10ffff)) return null + if (codePoint >= 0xd800 && codePoint <= 0xdfff) return null return codePoint } @@ -67,7 +62,7 @@ function bytesToUtf8(bytes) { continue } var codePoint = utf8Scalar(bytes, byteIndex) - if (codePoint < 0) { + if (codePoint === null) { // Invariant: malformed UTF-8 bytes fall back individually to Latin-1 so message text remains readable. result += String.fromCharCode(first) byteIndex++ @@ -97,9 +92,7 @@ function decodeBase64Url(text) { if (typeof Qt !== "undefined" && typeof Qt.atob === "function") { try { return Qt.atob(input.replace(/-/g, "+").replace(/_/g, "/")) - } catch (parseError) { - - } + } catch (parseError) {} } return bytesToUtf8(base64ToBytes(input)) } @@ -177,7 +170,7 @@ function looksLikeUtf8(bytes) { continue } var codePoint = utf8Scalar(values, byteIndex) - if (codePoint < 0) return false + if (codePoint === null) return false byteIndex += codePoint < 0x800 ? 2 : (codePoint < 0x10000 ? 3 : 4) multibyte = true } diff --git a/ui/message/Outbox.js b/ui/message/Outbox.js index 3fc4ea223..7dc8fcc7f 100644 --- a/ui/message/Outbox.js +++ b/ui/message/Outbox.js @@ -10,13 +10,3 @@ function normalizeDelay(value) { if (!isFinite(seconds)) return DEFAULT_DELAY_SECONDS return Math.max(0, Math.min(MAX_DELAY_SECONDS, Math.floor(seconds))) } - -function schedule(payload, now, delaySeconds) { - var delay = normalizeDelay(delaySeconds) - if (delay === 0) return null - return ({ payload: payload, dueAt: Number(now) + delay * 1000 }) -} - -function remainingSeconds(dueAt, now) { - return Math.max(0, Math.ceil((Number(dueAt) - Number(now)) / 1000)) -} diff --git a/ui/message/Signature.js b/ui/message/Signature.js index 1574c05ae..352621521 100644 --- a/ui/message/Signature.js +++ b/ui/message/Signature.js @@ -3,7 +3,7 @@ // Invariant: imported signature HTML passes both the shared sanitizer and a stricter signature policy. -var MAX_HTML_BYTES = 256 * 1024 +var MAX_HTML_CODE_UNITS = 256 * 1024 var MAX_IMAGE_BYTES = 512 * 1024 var MAX_DATA_IMAGES = 8 @@ -165,7 +165,7 @@ function sourceRemovals(source) { function importHtml(html, options) { var settings = options || {} var source = String(html === undefined || html === null ? "" : html) - if (source.length > Math.max(1, Math.floor(Number(settings.maxHtmlBytes) || MAX_HTML_BYTES))) + if (source.length > Math.max(1, Math.floor(Number(settings.maxHtmlBytes) || MAX_HTML_CODE_UNITS))) return { html: "", plain: "", dropped: 0, images: 0, problem: "That file is too large for a signature" } var cleaned = Html.sanitize(source, { allowRemoteImages: false, keepColors: true }) // Docs: count non-image removals from the source because Html reports only blocked images. diff --git a/ui/message/Unsubscribe.js b/ui/message/Unsubscribe.js index 3b6232178..c3525f630 100644 --- a/ui/message/Unsubscribe.js +++ b/ui/message/Unsubscribe.js @@ -145,12 +145,3 @@ function explanation(info, canSend) { if (how === "browser") return "Unsubscribing opens this sender's page in a browser" return "" } - -// Invariant: the RFC 8058 request body and content type are fixed protocol values. -function postBody() { - return "List-Unsubscribe=One-Click" -} - -function postContentType() { - return "application/x-www-form-urlencoded" -} diff --git a/ui/tests/qml/tst_message_base64.qml b/ui/tests/qml/tst_message_base64.qml index 345927e26..4bb2f2e1d 100644 --- a/ui/tests/qml/tst_message_base64.qml +++ b/ui/tests/qml/tst_message_base64.qml @@ -1,6 +1,8 @@ import QtQuick 2.15 import QtTest 1.3 import "../../message/Message.js" as Message +import "../../message/Calendar.js" as Calendar +import "../../compose/Recipients.js" as Recipients Item { TestCase { @@ -9,5 +11,33 @@ Item { function test_qt_atob_result_is_not_decoded_a_second_time() { compare(Message.decodeBase64Url("QWxleCDDoCBsJ8OpY29sZQ=="), "Alex à l'école") } + + function test_encoded_display_text_cannot_route_a_reply() { + var forged = "=?UTF-8?B?" + Message.encodeBase64("Alias ") + "?=" + var summary = Message.summarize({id: "synthetic", payload: {headers: [ + {name: "From", value: "Actual "}, + {name: "Reply-To", value: forged}, + {name: "To", value: forged} + ]}}) + compare(summary.replyTo.email, "") + compare(summary.to.length, 0) + var reply = Recipients.replyFields(summary, "replyAll", []) + compare(reply.to, "actual@example.test") + compare(reply.cc, "") + } + + function test_malformed_utf8_cannot_synthesize_markup() { + compare(Message.bytesToUtf8([0xe0, 0x80, 0xbc]).indexOf("<"), -1) + compare(Message.bytesToUtf8([0xc2, 0x41]), "\u00c2A") + } + + function test_calendar_folds_complete_characters_at_75_octets() { + var original = "SUMMARY:" + new Array(50).join("界😀") + var folded = Calendar.foldIcsLine(original) + compare(folded.replace(/\r\n /g, ""), original) + var lines = folded.split("\r\n") + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) + verify(Message.utf8Bytes(lines[lineIndex]).length <= 75) + } } } diff --git a/ui/tests/test_calendar.js b/ui/tests/test_calendar.js index f8751d8c4..513071b73 100644 --- a/ui/tests/test_calendar.js +++ b/ui/tests/test_calendar.js @@ -8,7 +8,7 @@ function b64url(text) { .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") } -// A real Google Calendar invitation, down to the folded ATTENDEE line and the +// Invariant: A real Google Calendar invitation, down to the folded ATTENDEE line and the // VTIMEZONE it ships so a reader with no timezone database can still place the // meeting. Folded exactly where Google folds: at 75 octets, continued with one // leading space. @@ -60,9 +60,7 @@ const GOOGLE_INVITE = [ "END:VCALENDAR" ].join("\r\n") -// ------------------------------------------------------------- line folding - -// The break *and* the space that continued it both go: RFC 5545 folds between +// Invariant: The break *and* the space that continued it both go: RFC 5545 folds between // any two characters, so a kept space would land in the middle of a word. deepEqual(calendar.unfoldLines("A:one\r\n B:two"), ["A:oneB:two"], "a folded line rejoins with no space left behind") @@ -71,8 +69,6 @@ deepEqual(calendar.unfoldLines("A:one\nB:two\r\n\r\nC:three"), deepEqual(calendar.unfoldLines("A:one\r\n\ttab-folded"), ["A:onetab-folded"], "a tab continues a line too") -// ------------------------------------------------------------- one property - const attendee = calendar.parseProperty( 'ATTENDEE;PARTSTAT=NEEDS-ACTION;CN="Doe, Jane":mailto:jane@example.com') assert.strictEqual(attendee.name, "ATTENDEE") @@ -81,7 +77,7 @@ assert.strictEqual(attendee.params.CN, "Doe, Jane", "a quoted CN keeps its comma assert.strictEqual(attendee.value, "mailto:jane@example.com", "the colon inside the value does not end the parameters") -// A colon inside a quoted parameter must not be mistaken for the one that ends +// Invariant: A colon inside a quoted parameter must not be mistaken for the one that ends // the head, or every property after it reads as the wrong name. const quotedColon = calendar.parseProperty('X-THING;NOTE="a:b":value') assert.strictEqual(quotedColon.name, "X-THING") @@ -90,20 +86,16 @@ assert.strictEqual(quotedColon.value, "value") assert.strictEqual(calendar.parseProperty("no-colon-here"), null) -// --------------------------------------------------------------- escaping - assert.strictEqual(calendar.unescapeText("one\\, two\\; three"), "one, two; three") assert.strictEqual(calendar.unescapeText("line\\nbreak"), "line\nbreak") assert.strictEqual(calendar.unescapeText("back\\\\slash"), "back\\slash") assert.strictEqual(calendar.escapeText("one, two; three"), "one\\, two\\; three") assert.strictEqual(calendar.escapeText("line\nbreak"), "line\\nbreak") -// Round trip, because a summary goes back out in the reply this builds. +// Invariant: Round trip, because a summary goes back out in the reply this builds. const tricky = "Q3 review, part 2; \"the\\one\"\nand a second line" assert.strictEqual(calendar.unescapeText(calendar.escapeText(tricky)), tricky, "escape then unescape is the identity") -// ------------------------------------------------------------ the invitation - const invite = calendar.invitationFrom(GOOGLE_INVITE) assert.ok(invite, "a Google invitation parses") assert.strictEqual(invite.method, "REQUEST") @@ -126,9 +118,7 @@ assert.strictEqual(invite.attendees[0].name, "Jason Lee", assert.strictEqual(invite.attendees[0].partstat, "NEEDS-ACTION") assert.strictEqual(invite.attendees[1].optional, true) -// ------------------------------------------------------------------- times -// -// August is EDT: the second Sunday in March 2026 is the 8th, the first in +// Invariant: August is EDT: the second Sunday in March 2026 is the 8th, the first in // November is the 1st, and the 21st of August is between them. 10:00 -0400 is // 14:00 UTC, and getting this wrong is the difference between joining a // meeting and missing it. @@ -138,7 +128,7 @@ assert.strictEqual(invite.start.resolved, true) assert.strictEqual(invite.start.allDay, false) assert.strictEqual(invite.start.tzid, "America/New_York") -// The same zone in January is EST, which is the rule the *previous* year's +// Invariant: The same zone in January is EST, which is the rule the *previous* year's // November transition put in force — the case a search that only looks inside // the event's own year gets wrong. const winter = calendar.invitationFrom( @@ -147,7 +137,6 @@ const winter = calendar.invitationFrom( assert.strictEqual(winter.start.ms, Date.UTC(2026, 0, 15, 15, 0, 0), "January is EST, not EDT") -// A UTC stamp needs no zone at all. const utcInvite = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", "BEGIN:VEVENT", "UID:u1", "SUMMARY:Standup", @@ -157,7 +146,7 @@ assert.strictEqual(utcInvite.start.ms, Date.UTC(2026, 7, 21, 9, 0, 0)) assert.strictEqual(utcInvite.start.tzid, "") assert.strictEqual(calendar.formatDuration(utcInvite), "15 min") -// A named zone without a VTIMEZONE block stays unresolved. Its placeholder +// Invariant: A named zone without a VTIMEZONE block stays unresolved. Its placeholder // must not change with the machine timezone running the parser. const namedZone = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", "BEGIN:VEVENT", @@ -169,7 +158,7 @@ assert.strictEqual(namedZone.start.tzid, "Europe/Stockholm") assert.strictEqual(namedZone.start.ms, Date.UTC(2026, 7, 21, 9, 0, 0)) assert.ok(calendar.formatWhen(namedZone).indexOf("09:00 (Europe/Stockholm)") > 0) -// A private zone name cannot be converted. Its fallback is UTC rather than +// Invariant: A private zone name cannot be converted. Its fallback is UTC rather than // the parser machine's local zone, so separate machines agree on the instant. const unknownZone = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", "BEGIN:VEVENT", @@ -182,7 +171,6 @@ assert.strictEqual(unknownZone.start.ms, Date.UTC(2026, 7, 21, 9, 0, 0)) assert.ok(calendar.formatWhen(unknownZone).indexOf("(Example/Headquarters)") > 0, "an unresolved time says which clock it is on") -// DURATION stands in for a missing DTEND. const byDuration = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", "BEGIN:VEVENT", "UID:u3", "SUMMARY:Interview", @@ -191,7 +179,7 @@ const byDuration = calendar.invitationFrom([ assert.strictEqual(byDuration.end.ms, Date.UTC(2026, 7, 21, 10, 30, 0)) assert.strictEqual(calendar.formatDuration(byDuration), "1 hour 30 min") -// An all-day DTEND is the day *after* the last one, so a one-day event shown +// Invariant: An all-day DTEND is the day *after* the last one, so a one-day event shown // from its raw end date would read as two. const allDay = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", "BEGIN:VEVENT", @@ -210,7 +198,7 @@ const twoDays = calendar.invitationFrom([ assert.strictEqual(calendar.formatWhen(twoDays), "Fri, Aug 21, 2026 – Sat, Aug 22, 2026") -// A zone whose transitions are listed as dates rather than rules — an Exchange +// Invariant: A zone whose transitions are listed as dates rather than rules — an Exchange // invitation with RDATEs — cannot be placed by reading rules. It falls back to // standard time rather than to whichever sub-component happened to be first. { @@ -232,7 +220,6 @@ assert.strictEqual(calendar.formatWhen(twoDays), "standard time is the fallback, not whichever rule was written first") } -// A zone with exactly one rule is a fixed offset and needs no search at all. { const fixed = calendar.invitationFrom([ "BEGIN:VCALENDAR", "VERSION:2.0", "METHOD:REQUEST", @@ -247,7 +234,7 @@ assert.strictEqual(calendar.formatWhen(twoDays), assert.strictEqual(fixed.start.resolved, true) } -// iCloud ships a zone's whole history, retired rules included. Vienna fell +// Invariant: iCloud ships a zone's whole history, retired rules included. Vienna fell // back in late September from 1981 to 1995; that rule's UNTIL has to end it, // or every autumn reads as standard time a month early and an event made on // an iPhone shows an hour late from late September to the end of October. @@ -285,14 +272,14 @@ assert.strictEqual(calendar.formatWhen(twoDays), "the rule still in force ends summer time on the last Sunday of October") assert.strictEqual(at("20260701T120000").ms, Date.UTC(2026, 6, 1, 10, 0, 0)) assert.strictEqual(at("20260115T120000").ms, Date.UTC(2026, 0, 15, 11, 0, 0)) - // UNTIL=19950924T010000Z is the 03:00 summer-time transition itself. Read - // as a wall clock it would land after its own UNTIL and drop out, leaving - // October 1995 on summer time. + // Invariant: UNTIL=19950924T010000Z is the 03:00 summer-time transition itself. Read +// as a wall clock it would land after its own UNTIL and drop out, leaving +// October 1995 on summer time. assert.strictEqual(at("19951010T120000").ms, Date.UTC(1995, 9, 10, 11, 0, 0), "a rule's last transition is the one its UTC UNTIL names") } -// Once every summer-time rule has ended, the zone stays where the last one +// Invariant: Once every summer-time rule has ended, the zone stays where the last one // left it. Mexico City dropped summer time in 2022; years later it is on // -0600 all year, not on the 1922 entry that heads the list. { @@ -321,7 +308,7 @@ assert.strictEqual(calendar.formatWhen(twoDays), "the final summer under the rules still counts") } -// iCloud gathers a zone's one-off transitions into one sub-component per +// Invariant: iCloud gathers a zone's one-off transitions into one sub-component per // offset pair, so the last change can be an RDATE decades after its DTSTART. // Moscow went to +0400 for good in 2011 and back to +0300 in 2014 — the // second only an RDATE of a component that starts in 1930. @@ -352,7 +339,7 @@ assert.strictEqual(calendar.formatWhen(twoDays), "between the two, +0400 all year") } -// One rule can take effect twice in a year. Casablanca leaves +0100 for +// Invariant: One rule can take effect twice in a year. Casablanca leaves +0100 for // Ramadan, and in 2029 Ramadan starts in January and again in December, so // the January date has to count although the December one is still ahead. { @@ -377,7 +364,7 @@ assert.strictEqual(calendar.formatWhen(twoDays), assert.strictEqual(at("20291231T120000").ms, Date.UTC(2029, 11, 31, 12, 0, 0)) } -// Sparse RDATE histories must keep the nearest past transition even when a +// Invariant: Sparse RDATE histories must keep the nearest past transition even when a // later listed date lies ahead of the reading and the previous year is empty. { const sparse = [ @@ -404,8 +391,6 @@ assert.strictEqual(calendar.formatWhen(twoDays), "the current year's transition still takes effect at its wall-clock boundary") } -// ------------------------------------------------------------- formatting - assert.strictEqual(calendar.formatWhen(invite), new Date(Date.UTC(2026, 7, 21, 14, 0, 0)).getHours() === 14 ? "Fri, Aug 21, 2026 · 14:00 – 15:00" @@ -414,8 +399,6 @@ assert.strictEqual(calendar.formatWhen(invite), assert.strictEqual(calendar.formatDuration(invite), "1 hour") assert.strictEqual(calendar.attendeeSummary(invite), "2 guests · 1 yes, 1 awaiting") -// -------------------------------------------------------------- recurrence - assert.strictEqual(calendar.describeRecurrence("FREQ=WEEKLY;BYDAY=MO,WE"), "Weekly on Mon, Wed") assert.strictEqual(calendar.describeRecurrence("FREQ=WEEKLY;INTERVAL=2;BYDAY=TU"), @@ -428,8 +411,6 @@ assert.strictEqual(calendar.describeRecurrence("FREQ=HOURLY"), "Repeats", "an exotic rule is admitted to rather than described wrongly") assert.strictEqual(calendar.describeRecurrence(""), "") -// ---------------------------------------------------------------- headline - assert.strictEqual(calendar.headline(invite), "Updated invitation", "a sequence above zero means this is not the first one") assert.strictEqual(calendar.headline( @@ -449,8 +430,6 @@ assert.strictEqual(calendar.partstatLabel("NEEDS-ACTION"), "Awaiting") assert.strictEqual(calendar.partstatLabel(""), "Awaiting", "not having answered is a state, not missing data") -// ---------------------------------------------------------------- responses - assert.strictEqual(calendar.responseOf(invite, "jason@example.com"), "") assert.strictEqual(calendar.responseOf(invite, "grace@example.com"), "accepted") assert.strictEqual(calendar.responseOf(invite, "GRACE@EXAMPLE.COM"), "accepted", @@ -471,8 +450,6 @@ assert.strictEqual(reply.method, "REPLY") assert.strictEqual(calendar.canRespond(reply, "jason@example.com"), false, "somebody else's answer is not an invitation") -// ------------------------------------------------- remembering the answer - { const answered = calendar.withResponse(invite, "jason@example.com", "accepted") assert.strictEqual(calendar.responseOf(answered, "jason@example.com"), "accepted") @@ -485,8 +462,8 @@ assert.strictEqual(calendar.canRespond(reply, "jason@example.com"), false, assert.strictEqual(answered.summary, invite.summary) deepEqual(answered.source, invite.source) - // A forwarded invitation names no line for the reader. Answering it is still - // the right thing to have done, so the answer is recorded rather than lost. + // Invariant: A forwarded invitation names no line for the reader. Answering it is still +// the right thing to have done, so the answer is recorded rather than lost. const forwarded = calendar.withResponse(invite, "someone-else@example.com", "declined") assert.strictEqual(forwarded.attendees.length, 3) assert.strictEqual(calendar.responseOf(forwarded, "someone-else@example.com"), "declined") @@ -497,8 +474,6 @@ assert.strictEqual(calendar.canRespond(reply, "jason@example.com"), false, assert.strictEqual(calendar.withResponse(null, "a@b.com", "accepted"), null) } -// -------------------------------------------------------------- the reply - const me = { name: "Jason Lee", email: "jason@example.com" } const answer = calendar.buildReply(invite, me, "accepted", Date.UTC(2026, 7, 20, 8, 30, 0)) const answerLines = answer.split("\r\n") @@ -517,19 +492,17 @@ assert.ok(answer.indexOf("BEGIN:VTIMEZONE") >= 0 && answer.indexOf("RRULE:FREQ=Y assert.ok(answer.indexOf("END:VTIMEZONE") >= 0) assert.ok(answer.indexOf("END:VCALENDAR\r\n") >= 0) -// A reply speaks for one person. Copying the other guests' lines back is how +// Invariant: A reply speaks for one person. Copying the other guests' lines back is how // an organiser's calendar gets told that Grace accepted, by Jason. assert.strictEqual(answer.split("ATTENDEE").length - 1, 1, "exactly one ATTENDEE line, and it is this account's") assert.strictEqual(answer.indexOf("grace@example.com"), -1) -// Nothing may exceed the 75-octet line limit once folded. for (const line of answerLines) { assert.ok(Buffer.byteLength(line, "utf8") <= 75, "line over 75 octets: " + JSON.stringify(line)) } -// The other two answers differ only in the one word they exist to carry. assert.ok(calendar.buildReply(invite, me, "declined", 0).indexOf("PARTSTAT=DECLINED") >= 0) assert.ok(calendar.buildReply(invite, me, "tentative", 0).indexOf("PARTSTAT=TENTATIVE") >= 0) assert.strictEqual(calendar.buildReply(invite, me, "maybe", 0), "", @@ -537,12 +510,12 @@ assert.strictEqual(calendar.buildReply(invite, me, "maybe", 0), "", assert.strictEqual(calendar.buildReply(invite, { email: "" }, "accepted", 0), "", "an account with no address cannot answer") -// A display name may not carry a quote: there is no escape for one inside a +// Invariant: A display name may not carry a quote: there is no escape for one inside a // quoted parameter, so a name holding one would end the value early and the // rest of it would be read as more parameters. const sneaky = calendar.buildReply(invite, { name: 'Jason";X-EVIL=1;CN="x', email: "jason@example.com" }, "accepted", 0) -// Read back through the parser, which unfolds first — the line is long enough +// Invariant: Read back through the parser, which unfolds first — the line is long enough // to be folded, and a test that read the raw first line would be asserting // about half an address. const sneakyEvent = calendar.parse(sneaky).children.filter(function(child) { @@ -557,8 +530,6 @@ assert.strictEqual(sneakyParsed.params["X-EVIL"], undefined, "a quote in a display name cannot open a parameter of its own") assert.strictEqual(sneaky.split("ATTENDEE").length - 1, 1) -// ---------------------------------------------------------- reply as a mail - const fields = calendar.replyFields(invite, me, "accepted", Date.UTC(2026, 7, 20, 8, 30, 0)) assert.strictEqual(fields.to, "ada@example.com", "the answer goes to the organiser alone") assert.strictEqual(fields.subject, "Accepted: Weekly sync") @@ -578,10 +549,6 @@ assert.strictEqual(calendar.replyFields(noOrganizer, me, "accepted", 0), null, "with nobody to answer, there is no reply to build") assert.strictEqual(calendar.canRespond(noOrganizer, "jason@example.com"), false) -// ------------------------------------------------------------ out of a mail - -// The Gmail message resource, which is the shape both providers hand back. -// `fromPayload` takes the MIME root out of it, the way `Mail.attachments` does. const message = { payload: { mimeType: "multipart/mixed", @@ -600,9 +567,9 @@ const message = { { mimeType: "application/ics", filename: "invite.ics", - // Listed by id only, the way Gmail lists an attachment. There is - // nothing here to parse, and reaching for it would be a second round - // trip to learn what the inline part already said. + // Invariant: Listed by id only, the way Gmail lists an attachment. There is +// nothing here to parse, and reaching for it would be a second round +// trip to learn what the inline part already said. body: { size: 2048, attachmentId: "att1" } } ] @@ -614,27 +581,24 @@ assert.ok(fromMail, "the invitation is found in the MIME tree") assert.strictEqual(fromMail.uid, "abc123@google.com") assert.strictEqual(fromMail.method, "REQUEST") -// A calendar part past the ceiling is skipped before it is decoded: this runs +// Invariant: A calendar part past the ceiling is skipped before it is decoded: this runs // on the thread that draws the whole desktop. assert.strictEqual(calendar.fromPayload({ mimeType: "text/calendar; method=REQUEST", body: { size: 4 * 1024 * 1024, data: b64url(GOOGLE_INVITE) } }), null) -// An ordinary message has none, and that is the answer for nearly every one. assert.strictEqual(calendar.fromPayload({ mimeType: "text/plain", body: { data: b64url("hello") } }), null) assert.strictEqual(calendar.fromPayload(null), null) -// An inline part wins over one that would have to be fetched, even when the +// Invariant: An inline part wins over one that would have to be fetched, even when the // fetchable one comes first in the tree: the file is already here. assert.strictEqual(calendar.pendingPart(message.payload), null, "nothing to ask for when the invitation arrived with the message") -// ------------------------------------------------- the invitation as a file -// -// What Gmail actually hands back for a Google Calendar invitation: both +// Invariant: What Gmail actually hands back for a Google Calendar invitation: both // calendar parts named `invite.ics`, and so both listed by id with no octets // on either. Read as it stood, the message has a meeting in it and no way to // see one — which is what this shape is here to keep fixed. @@ -673,12 +637,11 @@ assert.strictEqual(fetched.method, "REQUEST") assert.strictEqual(calendar.canRespond(fetched, "jason@example.com"), true, "and it can be answered like any other") -// A part too big to parse is not worth a round trip either. assert.strictEqual(calendar.pendingPart({ mimeType: "text/calendar", filename: "invite.ics", body: { size: 4 * 1024 * 1024, attachmentId: "att-huge" } }), null) -// Neither is one the server described but gave no way to ask for. + assert.strictEqual(calendar.pendingPart({ mimeType: "text/calendar", filename: "invite.ics", body: { size: 900 } }), null) @@ -686,15 +649,12 @@ assert.strictEqual(calendar.fromAttachment(null, b64url(GOOGLE_INVITE)), null) assert.strictEqual(calendar.fromAttachment(wanted, ""), null) assert.strictEqual(calendar.fromAttachment(wanted, b64url("not a calendar")), null) -// The Content-Type states the method too, for a file that left the property out. const methodFromHeader = calendar.fromPayload({ mimeType: "text/calendar; method=REQUEST", body: { data: b64url(GOOGLE_INVITE.replace("METHOD:REQUEST\r\n", "")) } }) assert.strictEqual(methodFromHeader.method, "REQUEST") -// -------------------------------------------------------------- robustness - assert.strictEqual(calendar.invitationFrom(""), null) assert.strictEqual(calendar.invitationFrom("BEGIN:VCALENDAR\r\nEND:VCALENDAR"), null, "a calendar with no event is not an invitation") @@ -702,22 +662,21 @@ assert.strictEqual(calendar.invitationFrom( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:No id\r\nEND:VEVENT\r\nEND:VCALENDAR"), null, "without a UID there is nothing a reply could name") assert.strictEqual(calendar.invitationFrom("not a calendar at all"), null) -// Truncated mid-component: the parser has to stop rather than loop. +// Invariant: truncated but structurally consistent calendars retain the fields already received. assert.ok(calendar.invitationFrom( "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nBEGIN:VEVENT\r\nUID:u9\r\nSUMMARY:Cut"), "a truncated file still yields what it did carry") -// A file past the ceiling is not parsed at all: this runs on the thread that +// Invariant: A file past the ceiling is not parsed at all: this runs on the thread that // draws the desktop. assert.strictEqual(calendar.parse("BEGIN:VCALENDAR\r\n" + "X-PAD:" + new Array(600000).join("x") + "\r\nEND:VCALENDAR"), null) -// A date this cannot be sure about is refused rather than guessed at. assert.strictEqual(calendar.parseDateValue("2026-08-21"), null) assert.strictEqual(calendar.parseDateValue("20261321T100000"), null, "month 13") assert.strictEqual(calendar.parseDateValue("20260821T250000"), null, "hour 25") assert.ok(calendar.parseDateValue("20260821T100000Z").utc) -// A CalDAV object may carry several events. Calendar views need every event, +// Invariant: A CalDAV object may carry several events. Calendar views need every event, // while the invitation reader intentionally takes only the first one. const feed = [ "BEGIN:VCALENDAR", @@ -743,8 +702,6 @@ assert.strictEqual(feedEvents[0].summary, "Morning review") assert.strictEqual(feedEvents[1].uid, "second") assert.strictEqual(feedEvents[1].start.allDay, true) - - { for(const value of ['20260231T120000Z','20260229','19000229','20260431']) assert.strictEqual(calendar.parseDateValue(value),null,value) assert.strictEqual(calendar.parseDateValue('20000229').day,29) @@ -775,7 +732,6 @@ assert.strictEqual(feedEvents[1].start.allDay, true) assert.strictEqual(calendar.parseOffsetMinutes('+010521'),65.35) } - { const fields = calendar.parseDateValue("00990228T123000Z") assert.strictEqual(new Date(calendar.naiveKey(fields)).getUTCFullYear(), 99) diff --git a/ui/tests/test_mailto.js b/ui/tests/test_mailto.js index e48c399fc..4f0b36be0 100644 --- a/ui/tests/test_mailto.js +++ b/ui/tests/test_mailto.js @@ -7,8 +7,6 @@ function draft(to, cc, bcc, subject, body) { return { to: to, cc: cc, bcc: bcc, subject: subject, body: body } } -// ------------------------------------------------------------------ parse - deepEqual(mailto.parse("mailto:jane@example.com"), draft("jane@example.com", "", "", "", ""), "a bare address is a new message to that person") @@ -51,12 +49,10 @@ deepEqual(mailto.parse("mailto:jane@example.com#ignored"), draft("jane@example.com", "", "", "", ""), "a fragment is not part of the message") -// A stray percent is not an escape. Losing the whole subject over one is worse +// Invariant: A stray percent is not an escape. Losing the whole subject over one is worse // than keeping it as written. assert.strictEqual(mailto.parse("mailto:jane@example.com?subject=100%").subject, "100%") -// --------------------------------------------------------- payload → draft - deepEqual(mailto.draftFromPayload({ mailto: "mailto:jane@example.com?subject=Hi" }), draft("jane@example.com", "", "", "Hi", "")) deepEqual(mailto.draftFromPayload({ compose: true }), @@ -67,8 +63,6 @@ assert.strictEqual(mailto.draftFromPayload({ mailbox: "inbox" }), null) assert.strictEqual(mailto.draftFromPayload({ mailto: "https://example.com" }), null) assert.strictEqual(mailto.draftFromPayload(null), null) - - { const value=mailto.parse('mailto:one+tag@example.test?to=two+tag@example.test&subject=A+B%20C%2BD&body=100%+done') assert.strictEqual(value.to,'one+tag@example.test, two+tag@example.test') diff --git a/ui/tests/test_message.js b/ui/tests/test_message.js index 441d85f4d..02383f91c 100644 --- a/ui/tests/test_message.js +++ b/ui/tests/test_message.js @@ -8,10 +8,7 @@ function b64url(text) { .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") } -// ------------------------------------------------------------- base64 core -// -// The QML JS engine has no atob/btoa, so these are hand-rolled and checked -// against node's Buffer rather than against themselves. +// Invariant: the portable base64 codec is checked against Node Buffer rather than against its own inverse. const samples = [ "", @@ -19,9 +16,9 @@ const samples = [ "ab", "abc", "hello world", - "你好,世界", // three-byte UTF-8 - "Grüße aus München", // two-byte UTF-8 - "emoji 😀 tail", // surrogate pair, four-byte UTF-8 + "你好,世界", + "Grüße aus München", + "emoji 😀 tail", "line\r\nbreak\ttab", "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,./" ] @@ -34,18 +31,15 @@ for (const sample of samples) { "encodeUrl " + JSON.stringify(sample)) assert.strictEqual(message.decodeBase64Url(b64url(sample)), sample, "round trip " + JSON.stringify(sample)) - // Padded standard base64 has to decode too: Gmail pads some part bodies. + // Invariant: Padded standard base64 has to decode too: Gmail pads some part bodies. assert.strictEqual(message.decodeBase64Url(expected), sample) } -// Gmail wraps long part bodies with newlines inside the base64 payload. assert.strictEqual(message.decodeBase64Url("aGVs\nbG8g\r\nd29ybGQ="), "hello world") assert.strictEqual(message.decodeBase64Url(""), "") assert.strictEqual(message.decodeBase64Url(null), "") -// ------------------------------------------------------- RFC 2047 headers -// -// Gmail decodes transfer encodings for part bodies but leaves headers exactly +// Invariant: Gmail decodes transfer encodings for part bodies but leaves headers exactly // as they arrived, so every non-ASCII subject line arrives encoded. assert.strictEqual(message.decodeHeaderValue("Plain subject"), "Plain subject") @@ -61,7 +55,7 @@ assert.strictEqual( message.decodeHeaderValue("Re: =?UTF-8?B?" + Buffer.from("发票", "utf8").toString("base64") + "?= (fwd)"), "Re: 发票 (fwd)") -// Long CJK subjects are split across several encoded words. The whitespace +// Invariant: Long CJK subjects are split across several encoded words. The whitespace // between adjacent words is defined to disappear — keeping it inserts spaces // into the middle of Chinese sentences. const half1 = Buffer.from("这是一封很长的", "utf8").toString("base64") @@ -70,17 +64,12 @@ assert.strictEqual( message.decodeHeaderValue("=?UTF-8?B?" + half1 + "?= =?UTF-8?B?" + half2 + "?="), "这是一封很长的中文邮件标题") -// An unsupported charset must still yield readable ASCII rather than an error. +// Invariant: An unsupported charset must still yield readable ASCII rather than an error. assert.ok(message.decodeHeaderValue("=?GB2312?B?1eLK1w==?=").length > 0) assert.strictEqual(message.decodeHeaderValue(""), "") assert.strictEqual(message.decodeHeaderValue(null), "") -// ------------------------------------------- a charset that is not the truth - -// A charset header is a claim, and a sender that declares one and sends -// another is common. Read as one byte each, the UTF-8 for "ń" is "Å" followed -// by a control character — so the two readings are never both plausible and -// the bytes decide. +// Invariant: valid UTF-8 bytes override a mistaken single-byte charset declaration. const polish = "Dzień dobry, zmieniła się wartość wskaźników" const polishData = b64url(polish) @@ -92,7 +81,7 @@ const polishData = b64url(polish) }), polish, charset + " must not turn UTF-8 into mojibake") }) -// Genuine single-byte text is left to its declaration. "ç" is 0xE7 in +// Invariant: Genuine single-byte text is left to its declaration. "ç" is 0xE7 in // Latin-1, which is a lead byte with no continuation after it — malformed // UTF-8, so the header keeps the decision. assert.strictEqual(message.decodePart({ @@ -102,7 +91,7 @@ assert.strictEqual(message.decodePart({ .toString("base64") } }), "Français") -// The evidence, on its own. Only a well-formed multi-byte sequence counts: +// Invariant: The evidence, on its own. Only a well-formed multi-byte sequence counts: // everything else is likelier to be single-byte text that happens to begin // one than UTF-8 worth trusting over the header. assert.strictEqual(message.looksLikeUtf8([0x68, 0x69]), false, @@ -118,15 +107,11 @@ assert.strictEqual(message.looksLikeUtf8([0xf5, 0x80, 0x80, 0x80]), false, assert.strictEqual(message.looksLikeUtf8([]), false) assert.strictEqual(message.looksLikeUtf8(null), false) -// A subject is decoded through the same door, so a mislabelled encoded word -// comes out right too. assert.strictEqual( message.decodeHeaderValue("=?iso-8859-1?B?" + Buffer.from("wartość", "utf8").toString("base64") + "?="), "wartość") -// ------------------------------------------------------------- addresses - deepEqual(message.parseAddress("Jane Doe "), { name: "Jane Doe", email: "jane@example.com", display: "Jane Doe" }) deepEqual(message.parseAddress(""), @@ -140,7 +125,7 @@ assert.strictEqual( message.parseAddress("=?UTF-8?B?" + Buffer.from("张三", "utf8").toString("base64") + "?= ").display, "张三") -// A comma inside a quoted display name is not a list separator. +// Invariant: A comma inside a quoted display name is not a list separator. const recipients = message.parseAddressList("\"Doe, Jane\" , bob@y.com, Carl ") assert.strictEqual(recipients.length, 3) assert.strictEqual(recipients[0].display, "Doe, Jane") @@ -151,8 +136,6 @@ assert.strictEqual(message.formatAddressList(recipients, 2), "Doe, Jane, bob, +1 assert.strictEqual(message.formatAddressList(recipients, 5), "Doe, Jane, bob, Carl") assert.strictEqual(message.formatAddressList([], 3), "") -// ------------------------------------------------------------------ bodies - const multipart = { mimeType: "multipart/alternative", parts: [ @@ -162,7 +145,6 @@ const multipart = { } deepEqual(message.extractBody(multipart), { text: "plain body 你好", source: "plain" }) -// text/plain wins even when it is nested deeper than the html alternative. const nested = { mimeType: "multipart/mixed", parts: [ @@ -178,7 +160,7 @@ assert.strictEqual(message.extractBody(nested).text, "inner plain") const htmlOnly = { mimeType: "text/html", body: { data: b64url("

Hi
there

") } } deepEqual(message.extractBody(htmlOnly), { text: "Hi\nthere", source: "html" }) -// A text/plain attachment is a file, not the message body. +// Invariant: A text/plain attachment is a file, not the message body. const withAttachment = { mimeType: "multipart/mixed", parts: [ @@ -189,8 +171,7 @@ const withAttachment = { assert.strictEqual(message.extractBody(withAttachment).text, "real body") deepEqual(message.attachments(withAttachment), [{ filename: "notes.txt", mimeType: "text/plain", size: 2048, attachmentId: "att1" }]) -// And the way back: an id names the part it was listed from, which is how a -// caller holding only an id gets at what the server said about it. + assert.strictEqual(message.partForAttachment(withAttachment, "att1"), withAttachment.parts[0]) assert.strictEqual(message.partForAttachment(withAttachment, "nosuch"), null) @@ -235,7 +216,7 @@ assert.strictEqual(message.formatSize(2 * 1024 * 1024), "2.0 MB") assert.strictEqual(message.formatCount(1, "original attachment"), "1 original attachment") assert.strictEqual(message.formatCount(2, "original attachment"), "2 original attachments") -// A forwarded file is a real MIME attachment, not only a label in the draft. +// Invariant: A forwarded file is a real MIME attachment, not only a label in the draft. // Its provider data is already base64url, including arbitrary binary bytes. const forwardRaw = message.buildRawMessage({ from: "me@example.com", @@ -261,9 +242,7 @@ const emptyForward = message.buildRawMessage({ }) assert.ok(emptyForward.includes('filename="empty.txt"'), "a zero-byte attachment is still attached") -// -------------------------------------------------------------------- time - -// Local, not UTC. relativeTime reads local calendar fields to decide whether a +// Invariant: Local, not UTC. relativeTime reads local calendar fields to decide whether a // message arrived today, so a UTC-anchored fixture is only "15:00 on the 19th" // for a reader west of UTC+9. From UTC+9 to UTC+11 it is already past local // midnight, three hours before it falls on the previous local day, and the @@ -275,8 +254,7 @@ function ago(ms) { return new Date(now.getTime() - ms) } assert.strictEqual(message.relativeTime(ago(30 * 1000), now), "now") assert.strictEqual(message.relativeTime(ago(5 * 60000), now), "5m") assert.strictEqual(message.relativeTime(ago(59 * 60000), now), "59m") -// Past an hour a clock time is more useful than "3h", and it matches how -// Gmail's own list reads. + assert.ok(/^\d\d:\d\d$/.test(message.relativeTime(ago(3 * 3600 * 1000), now))) assert.ok(/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)$/.test(message.relativeTime(ago(2 * 86400000), now))) assert.ok(/^[A-Z][a-z]{2} \d+$/.test(message.relativeTime(ago(40 * 86400000), now))) @@ -285,11 +263,9 @@ assert.strictEqual(message.relativeTime(ago(3 * 86400000), now), "Aug 16") assert.strictEqual(message.relativeTime(new Date(2025, 11, 21, 15), now), "Dec 21") assert.strictEqual(message.relativeTime(new Date(2025, 7, 18, 15), now), "Aug 18, 2025") assert.strictEqual(message.relativeTime(null, now), "") -// A message dated in the future must not render as a negative age. +// Invariant: A message dated in the future must not render as a negative age. assert.strictEqual(message.relativeTime(new Date(now.getTime() + 60000), now), "now") -// --------------------------------------------------------------- summarize - const resource = { id: "18f3a", threadId: "18f39", @@ -334,7 +310,6 @@ assert.strictEqual(summary.inTrash, false) assert.strictEqual(message.summarize({ payload: { headers: [] } }, now).subject, "(no subject)") assert.strictEqual(message.summarize({}, now).id, "") -// A message with no internalDate falls back to the Date header. const headerDated = message.summarize({ payload: { headers: [{ name: "Date", value: "Wed, 19 Aug 2026 14:00:00 +0000" }] } }, now) @@ -344,7 +319,7 @@ assert.strictEqual(message.headerValue(resource, "subject"), " Invoice for "header lookup is case-insensitive") assert.strictEqual(message.headerValue(resource, "Reply-To"), "") -// A reply goes to Reply-To when the sender set one, and to From otherwise. +// Invariant: A reply goes to Reply-To when the sender set one, and to From otherwise. // The list rows are fetched with the metadata format and simply have neither. assert.strictEqual(summary.replyTo.email, "") assert.strictEqual(summary.messageId, "") @@ -358,9 +333,7 @@ const withReplyTo = message.summarize({ assert.strictEqual(withReplyTo.replyTo.email, "help@example.com") assert.strictEqual(withReplyTo.messageId, "") -// ------------------------------------------------------------- the thread block -// -// Every summary carries one, whatever provider it came from, so a row and a +// Invariant: Every summary carries one, whatever provider it came from, so a row and a // cached row are the same shape and nothing above has to ask whether it is // there. A provider that does not group its listing reports a count of 0, which // means unknown and draws no badge — which is what this resource, carrying no @@ -370,8 +343,6 @@ deepEqual(summary.thread, deepEqual(message.summarize({}, now).thread, { id: "", count: 0, unread: false, flagged: false, memberIds: [] }) -// A collapsed listing hands one over, and `count` is how many members it -// counted: a block cannot report a number it has no ids for. const collapsed = message.summarize({ id: "maaaaaf", threadId: "d", @@ -384,7 +355,7 @@ deepEqual(collapsed.thread, { id: "d", count: 3, unread: true, flagged: false, memberIds: ["maaaaad", "maaaaae", "maaaaaf"] }) -// The row's own marks are the conversation's as well as the message's. A thread +// Invariant: The row's own marks are the conversation's as well as the message's. A thread // whose unread reply is not the message the server returned for this view is // still an unread row, and one with a flagged member is still a flagged row. const readRepresentative = message.summarize({ @@ -399,8 +370,6 @@ assert.strictEqual(readRepresentative.unread, true, "the conversation has an unread member, so the row is unread") assert.strictEqual(readRepresentative.starred, true) -// And the message's own answer is what is left when the block has none, so -// nothing changes for a provider that reports no block. assert.strictEqual(message.summarize({ labelIds: ["UNREAD", "STARRED"], payload: { headers: [] } }, now).unread, true) @@ -433,8 +402,6 @@ deepEqual(message.draftFields({ }) assert.strictEqual(message.draftFields({ subject: "(no subject)" }, "").subject, "") -// ------------------------------------------------------------ composition - assert.strictEqual(message.replySubject("Invoice"), "Re: Invoice") assert.strictEqual(message.replySubject("Re: Invoice"), "Re: Invoice", "Re: is not stacked") assert.strictEqual(message.replySubject("RE: Invoice"), "RE: Invoice") @@ -450,7 +417,7 @@ const raw = message.buildRawMessage({ assert.ok(raw.indexOf("From: work@example.net\r\n") === 0) -// A display name is a phrase and encodes as one. Quoted when it is ASCII — +// Invariant: A display name is a phrase and encodes as one. Quoted when it is ASCII — // an unquoted comma or dot would split the address list — and an encoded word // when it is not, which may never be wrapped in quotes of its own. assert.ok(message.buildRawMessage({ @@ -484,7 +451,7 @@ assert.ok(message.buildRawMessage({ to: "jane@example.com", body: "x" }).indexOf assert.ok(injected.indexOf("\r\nBcc: attacker@example.net\r\n") < 0, "a line break in the reply-to cannot smuggle a header") } -// An HTML signature makes the message two readings and, with a picture, a +// Invariant: An HTML signature makes the message two readings and, with a picture, a // related part per picture: the text part still carries the plain signature, // the HTML part carries the markup with the picture by cid. { @@ -504,9 +471,9 @@ assert.ok(message.buildRawMessage({ to: "jane@example.com", body: "x" }).indexOf assert.ok(html.indexOf('src="cid:sig1@omamail"') > 0) assert.strictEqual(html.indexOf("data:"), -1) assert.strictEqual((html.match(/Analyst/g) || []).length, 1, "the plain signature is not repeated under the markup") - // The two readings agree: a sign-off the writer removed is not put back - // in the HTML, the writer's own sign-off is the one replaced rather than a - // quoted copy, and a picture-only signature sits before the quote. + // Invariant: The two readings agree: a sign-off the writer removed is not put back +// in the HTML, the writer's own sign-off is the one replaced rather than a +// quoted copy, and a picture-only signature sits before the quote. const removed = message.buildRawMessage({ to: "jane@example.com", body: "Hi Jane, thanks", signature: "Ada", signatureHtml: "

Ada

" }) @@ -537,7 +504,7 @@ assert.ok(message.buildRawMessage({ to: "jane@example.com", body: "x" }).indexOf assert.ok(message.buildRawMessage({ to: "j@e.com", body: "Hi" }).indexOf("text/html") < 0, "no signature markup, no HTML part, as before") } -// A non-ASCII subject has to go back out as an encoded word or Gmail rejects +// Invariant: A non-ASCII subject has to go back out as an encoded word or Gmail rejects // the whole raw message. assert.ok(raw.indexOf("Subject: =?UTF-8?B?" + Buffer.from("你好", "utf8").toString("base64") + "?=") >= 0) assert.ok(raw.indexOf("In-Reply-To: \r\n") >= 0) @@ -556,7 +523,7 @@ assert.strictEqual( Buffer.from(payload.raw, "base64url").toString("utf8").indexOf("To: a@b.com"), 0) assert.strictEqual(message.buildSendPayload({ to: "a@b.com" }).threadId, undefined) -// The draft this message replaces, carried so a provider that can destroy the +// Invariant: The draft this message replaces, carried so a provider that can destroy the // old copy in the same request as the send does not leave one behind. Always // present, because a client reading it asks whether there is a draft to // destroy rather than whether the field exists. @@ -565,14 +532,7 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com" }).draftId, "", "a compose window that was not opened from a draft names none") assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draftId, "7") -// ---------------------------------------- the date and the id it leaves with -// -// The two headers themselves are asserted further down. What is asserted here -// is that every shape the builder builds carries them as the message's own -// headers, and that the address the mailbox is signed in as names the id when -// the From line is left for the provider to fill in — Gmail writes its own and -// the IMAP client puts the account on the envelope, so a compose window can -// legitimately send none, and a JMAP server stores exactly what it was handed. +// Invariant: adding Date and Message-ID preserves every existing MIME envelope shape. { const headersOf = (raw) => { const found = {} @@ -585,8 +545,6 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft const DATE = "Mon, 05 Jan 2026 09:30:00 +0000" const ID = "" - // Every shape the builder builds, and the stated values are what a test - // reads back — the point of being able to state them at all. const shapes = { "a plain message": { to: "a@b.com", body: "hi" }, "a right-to-left message": { to: "a@b.com", body: "سلام دوست من", boundary: "RTLB" }, @@ -607,9 +565,9 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft assert.strictEqual(headers["Message-ID"], ID, name + " is identified") } - // Both are the message's own headers, not a part's: the twin is still the - // second of exactly two alternatives, and the calendar reply still has no - // twin of its own. + // Invariant: Both are the message's own headers, not a part's: the twin is still the +// second of exactly two alternatives, and the calendar reply still has no +// twin of its own. const rtl = message.parseRfc822(message.buildRawMessage({ to: "a@b.com", body: "سلام دوست من", boundary: "RTLB", date: DATE, messageId: ID })) @@ -627,15 +585,11 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft assert.strictEqual(invite.parts[1].mimeType, "text/calendar") assert.strictEqual(message.headerFrom(invite.headers, "Message-ID"), ID) - // The From domain names the id when there is a From, whatever the mailbox - // is signed in as. assert.ok(/^<[^<>@\s]+@example\.net>$/.test(headersOf(message.buildRawMessage({ from: "work@example.net", to: "a@b.com", body: "hi", accountAddress: "me@ignored.example" }))["Message-ID"]), "the From domain names the id when there is a From") - // No From: the signed-in address names it, in whichever form the account - // holds it. assert.ok(/^<[^<>@\s]+@signed-in\.example>$/.test( headersOf(message.buildRawMessage({ to: "a@b.com", body: "hi", accountAddress: "Me " @@ -645,20 +599,14 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft "signed-in.example", "a From with no domain falls through to the account") assert.strictEqual(message.messageIdDomain("", ""), "omamail.invalid") - // The two headers read one clock: the id's timestamp is the Date's second. + // Invariant: The two headers read one clock: the id's timestamp is the Date's second. const sameClock = headersOf(message.buildRawMessage({ to: "a@b.com", body: "hi" })) const idMillis = parseInt(sameClock["Message-ID"].substring(1).split(".")[0], 36) assert.ok(Math.abs(idMillis - new Date(sameClock["Date"]).getTime()) < 1000, "the id is minted at the instant the message is dated") } -// ------------------------------------------- the direction a message states -// -// The compose field is resolved by Qt from the text in it, so the writer sees -// their own paragraph the right way round. None of that leaves with the -// message: a `text/plain` part states no direction, and a client with nothing -// to read assumes left-to-right. An HTML twin beside the plain text is the -// only thing every client honours, so a right-to-left message grows one. +// Invariant: outgoing RTL text carries an HTML direction alternative while retaining plain text. { const persian = "سلام، عرض ادب\n\nبا تشکر" const raw = message.buildRawMessage({ @@ -668,53 +616,47 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft const parsed = message.parseRfc822(raw) assert.strictEqual(parsed.mimeType, "multipart/alternative") assert.strictEqual(parsed.parts.length, 2) - // Least preferred first: a client showing one alternative shows the last it - // understands, and the twin is the part carrying the direction. + // Invariant: Least preferred first: a client showing one alternative shows the last it +// understands, and the twin is the part carrying the direction. assert.strictEqual(parsed.parts[0].mimeType, "text/plain") assert.strictEqual(message.decodePart(parsed.parts[0]), persian, "the plain part is the message as written, unchanged") assert.strictEqual(parsed.parts[1].mimeType, "text/html") assert.ok(message.decodePart(parsed.parts[1]).indexOf('') > 0) - // Line breaks are what a plain body says with, so they have to survive the - // crossing into markup. assert.ok(message.decodePart(parsed.parts[1]).indexOf("
") > 0) - // The body is a person's typing, not markup, and may not become markup on - // the way out. + // Invariant: The body is a person's typing, not markup, and may not become markup on +// the way out. const escaped = message.parseRfc822(message.buildRawMessage({ to: "a@b.com", body: "سلام &x", boundary: "ESCB" })) assert.strictEqual(message.decodePart(escaped.parts[1]), 'سلام <b>&x</b>') - // Left-to-right is what a bare text/plain already means, so saying it would - // make every message ever sent multipart in order to repeat the default. + // Invariant: Left-to-right is what a bare text/plain already means, so saying it would +// make every message ever sent multipart in order to repeat the default. const latin = message.buildRawMessage({ to: "a@b.com", body: "Hi Jane,\n\nThanks!" }) assert.ok(latin.indexOf("Content-Type: text/plain; charset=UTF-8") > 0) assert.ok(latin.indexOf("multipart") < 0, "a left-to-right message keeps the shape it has always had") - // A forced setting is not consulted here: the direction is read off the body - // by the same rule the reader uses, so what arrives matches what was typed. + // Invariant: A forced setting is not consulted here: the direction is read off the body +// by the same rule the reader uses, so what arrives matches what was typed. assert.ok(message.buildRawMessage({ to: "a@b.com", body: "Hello سلام" }).indexOf("multipart") < 0, "first strong character decides, as it does everywhere") - // An Arabic-Indic number is not a strong character, so an English message - // that opens with a price or a date pasted out of one does not become a - // right-to-left message on the way out. It did: the digits sit inside the - // Arabic block, and the scan asked which block before it asked which class. + // Invariant: An Arabic-Indic number is not a strong character, so an English message +// that opens with a price or a date pasted out of one does not become a +// right-to-left message on the way out. It did: the digits sit inside the +// Arabic block, and the scan asked which block before it asked which class. assert.ok(message.buildRawMessage({ to: "a@b.com", body: "١٢٣ Smith Street\nThe report is attached." }).indexOf("multipart") < 0, "an English body opening with an Arabic-Indic number stays plain text") - // With an attachment the pair moves one level in. The inner boundary may not - // begin with the outer one: `splitMultipart` finds a delimiter by searching - // for "--" + boundary anywhere in the body, so a suffixed inner boundary - // would be found by the outer scan too and the message would come apart at - // the wrong line. + // Invariant: a nested MIME boundary must not start with the outer boundary. const attached = message.buildRawMessage({ to: "a@b.com", body: "سلام دوست من", boundary: "OUTER", attachments: [{ filename: "f.txt", mimeType: "text/plain", data: "aGk=" }] @@ -733,9 +675,7 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft "the inner delimiter cannot be read as the outer one") } -// ------------------------------------------------------------- a calendar -// -// An RSVP is an ordinary mail with a `text/calendar` part beside the sentence +// Invariant: An RSVP is an ordinary mail with a `text/calendar` part beside the sentence // a person would read. Checked by parsing the message back with the adapter // the IMAP client uses, because "the shape is right" only means anything if // the readers agree. @@ -764,8 +704,8 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft assert.strictEqual(parsed.parts[1].mimeType, "text/calendar") assert.strictEqual(message.decodePart(parsed.parts[1]), ics) - // The transfer encoding is base64, so no part body can contain the boundary - // however long the calendar file gets. + // Invariant: The transfer encoding is base64, so no part body can contain the boundary +// however long the calendar file gets. const bigRaw = message.buildRawMessage({ to: "a@b.com", body: "x", calendar: { method: "REPLY", text: "BEGIN:VCALENDAR\r\nX-PAD:" + "y".repeat(5000) + "\r\nEND:VCALENDAR\r\n" }, @@ -774,8 +714,8 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft assert.strictEqual(bigRaw.split("--TESTBOUNDARY").length - 1, 3, "two openers and one closer, and nothing that looks like a third opener") - // The method comes out of a file somebody else wrote, so it may not end the - // header early or add one of its own. + // Invariant: The method comes out of a file somebody else wrote, so it may not end the +// header early or add one of its own. const hostile = message.buildRawMessage({ to: "a@b.com", body: "x", calendar: { method: 'REPLY"\r\nBcc: attacker@example.net', text: "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" }, @@ -788,12 +728,9 @@ assert.strictEqual(message.buildSendPayload({ to: "a@b.com", draftId: 7 }).draft assert.ok(/^Content-Type: text\/calendar; charset=UTF-8; method=[A-Z]+$/.test(methodLine), "the method is letters only: " + JSON.stringify(methodLine)) - // No calendar, no change: an ordinary reply is still one flat text/plain. assert.strictEqual(message.parseRfc822( message.buildRawMessage({ to: "a@b.com", body: "hi" })).mimeType, "text/plain") - // A boundary the caller did not name is generated, and is still a boundary - // the message parses against. const generated = message.parseRfc822(message.buildRawMessage({ to: "a@b.com", body: "hi", calendar: { method: "REPLY", text: "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" } })) @@ -805,7 +742,7 @@ const quoted = message.quoteBody(summary, "line one\nline two") assert.ok(quoted.indexOf("> line one\n> line two") > 0) assert.ok(quoted.indexOf("李四 wrote:") > 0) -// The reader wants the markup; the list row wants the flattened text. Both +// Invariant: The reader wants the markup; the list row wants the flattened text. Both // walks must find the same part, and neither may return an attachment. assert.strictEqual(message.extractHtml(multipart), "

html body

") assert.strictEqual(message.extractHtml(nested), "

outer html

") @@ -816,25 +753,18 @@ assert.strictEqual(message.extractHtml({ parts: [{ mimeType: "text/html", filename: "page.html", body: { attachmentId: "a1", data: b64url("

file

") } }] }), "", "an html attachment is a file, not the body") - -// An image becomes a numbered marker, so the reader can offer the picture -// itself when the marker is clicked. { assert.strictEqual( message.htmlToText("
Hello

Bye

"), "Hello\n[image 1]\n[image 2]Bye") assert.strictEqual(message.htmlToText("

none

"), "none", "text without images is unchanged") - // A ">" inside an alt text does not end the tag — Html.imageSources numbers - // the pictures with the same walk, and a disagreement puts every marker after - // it on the wrong one. + // Invariant: a quoted greater-than sign cannot end an image tag and shift image-marker numbering. assert.strictEqual( message.htmlToText("\"ab\" src=\"x.png\">

after

"), "[image 1]after\n[image 2]") } -// -------------------------------------------------------- header injection -// -// In-Reply-To carries a Message-ID, and a Message-ID is whatever the sender +// Invariant: In-Reply-To carries a Message-ID, and a Message-ID is whatever the sender // wrote in theirs. A line break in one would end the header and let the rest be // read as another — a Bcc in a reply the user typed no Bcc into. { @@ -859,21 +789,16 @@ assert.strictEqual(message.extractHtml({ }) assert.ok(headerNames(folded).indexOf("Bcc") < 0) assert.ok(headerNames(folded).indexOf("X-Injected") < 0) - // Every header a message must carry is still there, and the body still - // starts after exactly one blank line. + assert.ok(folded.indexOf("\r\n\r\n") > 0) - // A reference that is nothing but a line break leaves the header out - // altogether rather than emitting an empty one. + // Invariant: A reference that is nothing but a line break leaves the header out +// altogether rather than emitting an empty one. assert.ok(message.buildRawMessage({ to: "a@b.com", inReplyTo: "\r\n", body: "x" }) .indexOf("In-Reply-To") < 0) } -// ------------------------------------------------------------- Message-ID -// -// RFC 5322 asks every message for an id, and a relay told not to add missing -// headers relays none: Postfix logs `message-id=<>` for a message sent without -// one, and a reply to it has nothing to thread on. +// Invariant: originated Message-ID is valid without relying on a relay to add one. { const headerNames = (text) => text.split("\r\n\r\n")[0].split("\r\n") .map((line) => line.split(":")[0]) @@ -897,17 +822,17 @@ assert.strictEqual(message.extractHtml({ }) assert.notStrictEqual(idOf(sent), idOf(again), "every message gets its own id") - // No From leaves no domain to take, and .invalid is reserved by RFC 2606 so - // the id cannot land in a namespace somebody else's uniqueness depends on. + // Invariant: No From leaves no domain to take, and .invalid is reserved by RFC 2606 so +// the id cannot land in a namespace somebody else's uniqueness depends on. assert.ok(/^<[^<>@\s]+@omamail\.invalid>$/.test( idOf(message.buildRawMessage({ to: "a@b.com", body: "x" })))) assert.strictEqual(message.messageIdDomain('"Jane" '), "Example.COM") assert.strictEqual(message.messageIdDomain("nobody"), "omamail.invalid") assert.strictEqual(message.messageIdDomain(""), "omamail.invalid") - // Every label in this domain is legal, and the separator between its first - // two 63-character labels lands at the old arbitrary length ceiling. Cutting - // there would leave the id's domain ending in a dot. + // Invariant: Every label in this domain is legal, and the separator between its first +// two 63-character labels lands at the old arbitrary length ceiling. Cutting +// there would leave the id's domain ending in a dot. const longDomain = "a".repeat(63) + "." + "b".repeat(63) + "." + "c".repeat(63) + ".com" const longDomainId = idOf(message.buildRawMessage({ @@ -916,22 +841,21 @@ assert.strictEqual(message.extractHtml({ assert.ok(longDomainId.endsWith("@" + longDomain + ">"), "a valid sender domain survives whole in the generated id") - // Stated by the caller, which is what lets a test read the message it built. assert.ok(message.buildRawMessage({ from: "work@example.net", to: "a@b.com", body: "x", messageId: "" }).indexOf("Message-ID: \r\n") > 0) - // Dot-atom permits every RFC 5322 `atext` punctuation character on either - // side of the separator. A legal caller-stated id is preserved byte for byte. + // Invariant: Dot-atom permits every RFC 5322 `atext` punctuation character on either +// side of the separator. A legal caller-stated id is preserved byte for byte. const fullAtext = "" assert.ok(message.buildRawMessage({ from: "work@example.net", to: "a@b.com", body: "x", messageId: fullAtext }).indexOf("Message-ID: " + fullAtext + "\r\n") > 0, "every legal atext character survives in a stated id") - // Validation judges the caller's original value. Removing a space first - // would silently turn this into a different, apparently valid id, while an - // empty dot-atom segment is not a legal id at all. + // Invariant: Validation judges the caller's original value. Removing a space first +// would silently turn this into a different, apparently valid id, while an +// empty dot-atom segment is not a legal id at all. const repaired = idOf(message.buildRawMessage({ from: "work@example.net", to: "a@b.com", body: "x", messageId: "" })) @@ -942,8 +866,8 @@ assert.strictEqual(message.extractHtml({ from: "work@example.net", to: "a@b.com", body: "x", messageId: "" })), "", "an empty dot-atom segment is replaced") - // A stated id is this client's own choice rather than a stranger's, so one - // that is not an id is replaced instead of carried through mangled. + // Invariant: A stated id is this client's own choice rather than a stranger's, so one +// that is not an id is replaced instead of carried through mangled. const forged = message.buildRawMessage({ from: "work@example.net", to: "a@b.com", body: "x", messageId: "\r\nBcc: attacker@example.net" @@ -954,12 +878,7 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(headerNames(forged).filter((name) => name === "Message-ID").length, 1) } -// ------------------------------------------------------------------- Date -// -// RFC 5322 requires a Date on a message this client originates. Without one a -// reader falls back to the time the message was delivered or stored, which is -// not the time it was written — this client delays a send behind an undo -// window, so those are not the same moment. +// Invariant: originated Date remains valid without relying on a relay to add it. { const headerNames = (text) => text.split("\r\n\r\n")[0].split("\r\n") .map((line) => line.split(":")[0]) @@ -972,8 +891,8 @@ assert.strictEqual(message.extractHtml({ "one Date, and only one") assert.ok(sent.indexOf("From: work@example.net\r\n") === 0, "From still opens the message") - // The shape RFC 5322 §3.3 states, with a numeric zone rather than the - // obsolete GMT that toUTCString would give. + // Invariant: The shape RFC 5322 §3.3 states, with a numeric zone rather than the +// obsolete GMT that toUTCString would give. const stamped = message.sentDate("", clock) assert.ok(/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} [+-]\d{4}$/.test(stamped), stamped) @@ -983,25 +902,24 @@ assert.strictEqual(message.extractHtml({ message.messageDate({ payload: { headers: [{ name: "Date", value: stamped }] } }).getTime(), clock, "this file's own reader gets the instant back out of it") - // Stated by the caller, the way the id and the boundary already are. assert.ok(message.buildRawMessage({ to: "a@b.com", body: "x", date: "Thu, 03 Sep 2026 12:04:31 +0200" }).indexOf("Date: Thu, 03 Sep 2026 12:04:31 +0200\r\n") > 0) assert.strictEqual(new Date(message.sentDate("Thu, 03 Sep 2026 10:04:31 +0000")).getTime(), clock, "a caller who wants no offset says so through the same field") - // JavaScript parses ISO dates and several shorthand spellings that are not - // RFC 5322 date-time values. A parseable but non-header-shaped override is - // replaced with this client's canonical form. + // Invariant: JavaScript parses ISO dates and several shorthand spellings that are not +// RFC 5322 date-time values. A parseable but non-header-shaped override is +// replaced with this client's canonical form. const nonRfc = message.sentDate("2026-09-03", clock) assert.notStrictEqual(nonRfc, "2026-09-03", "an ISO-only override is not emitted verbatim") assert.ok(/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} [+-]\d{4}$/.test(nonRfc), nonRfc) assert.strictEqual(new Date(nonRfc).getTime(), clock, "the replacement uses the stated build clock") - // JavaScript normalizes an impossible calendar date and ignores a weekday - // that disagrees with the date. Neither can be emitted as the caller stated - // it: RFC 5322 requires the written date to exist and the weekday to agree. + // Invariant: JavaScript normalizes an impossible calendar date and ignores a weekday +// that disagrees with the date. Neither can be emitted as the caller stated +// it: RFC 5322 requires the written date to exist and the weekday to agree. const impossible = "Tue, 31 Feb 2026 10:04:31 +0000" const replacedImpossible = message.sentDate(impossible, clock) assert.notStrictEqual(replacedImpossible, impossible, @@ -1014,8 +932,8 @@ assert.strictEqual(message.extractHtml({ "a weekday that disagrees with its date is replaced") assert.strictEqual(new Date(replacedWeekday).getTime(), clock) - // RFC 5322 permits years from 1900 onward. A numeric zone has two digits - // each for hours and minutes, but only the minute pair is bounded to 00–59. + // Invariant: RFC 5322 permits years from 1900 onward. A numeric zone has two digits +// each for hours and minutes, but only the minute pair is bounded to 00–59. const obsoleteYear = "Mon, 04 Sep 1899 10:04:31 +0000" const replacedObsoleteYear = message.sentDate(obsoleteYear, clock) assert.notStrictEqual(replacedObsoleteYear, obsoleteYear, @@ -1031,8 +949,8 @@ assert.strictEqual(message.extractHtml({ assert.notStrictEqual(message.sentDate("Thu, 03 Sep 2026 10:04:31 +9960", clock), "Thu, 03 Sep 2026 10:04:31 +9960", "a numeric zone minute cannot reach 60") - // A stated value that is not a date is replaced, and a line break in one can - // become neither a second header nor a mangled first one. + // Invariant: A stated value that is not a date is replaced, and a line break in one can +// become neither a second header nor a mangled first one. const forged = message.buildRawMessage({ to: "a@b.com", body: "x", date: "not a date\r\nBcc: attacker@example.net" }) @@ -1040,25 +958,16 @@ assert.strictEqual(message.extractHtml({ assert.ok(forged.indexOf("attacker@example.net") < 0, "nothing of the forged value survives") assert.strictEqual(headerNames(forged).filter((name) => name === "Date").length, 1) - // The header survives a round trip through this file's own parser. assert.strictEqual(message.parseRfc822(message.buildRawMessage({ to: "a@b.com", body: "x", date: stamped })).headers.filter((header) => header.name === "Date").length, 1) } -// ------------------------------------------------------ RFC 822 → payload -// -// The adapter that lets an IMAP message drive the same reader a Gmail message -// does. Everything here is checked through the *existing* readers — -// extractBody, extractHtml, attachments, summarize — because "the shape is -// right" only means anything if those still work on it. { - // A byte string: one character per octet, the shape Imap.decodeResponse - // produces and the only shape these counts are correct in. + // Invariant: A byte string: one character per octet, the shape Imap.decodeResponse +// produces and the only shape these counts are correct in. const bytes = (text) => Buffer.from(text, "utf8").toString("latin1") - // --- the simplest possible message - const plain = message.parseRfc822(bytes( "From: Jane \r\n" + "Subject: Hello\r\n" + @@ -1070,14 +979,12 @@ assert.strictEqual(message.extractHtml({ deepEqual(message.extractBody(plain), { text: "Just a line.\n", source: "plain" }) assert.strictEqual(message.headerValue({ payload: plain }, "Subject"), "Hello") - // Bare LF, which a surprising number of senders emit, has to parse too. + // Invariant: Bare LF, which a surprising number of senders emit, has to parse too. const bareLf = message.parseRfc822("Subject: X\n\nbody text\n") assert.strictEqual(message.extractBody(bareLf).text, "body text\n") - // --- folded headers - // - // Unfolding must happen before anything looks for a ":", or a wrapped - // Subject becomes a header named after its own second line. + // Invariant: Unfolding must happen before anything looks for a ":", or a wrapped +// Subject becomes a header named after its own second line. const foldedHeaders = message.parseRfc822(bytes( "Subject: a very long subject that the sender\r\n" + @@ -1091,8 +998,6 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(message.headerValue({ payload: foldedHeaders }, "From"), "jane@example.org", "the header after a folded one is still found") - // --- transfer encodings - const quotedPrintable = message.parseRfc822(bytes( "Content-Type: text/plain; charset=UTF-8\r\n" + "Content-Transfer-Encoding: quoted-printable\r\n" + @@ -1101,8 +1006,8 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(message.extractBody(quotedPrintable).text, "Café crème and a soft break\n", "=XX decodes, a trailing = is a soft break that disappears, and an underscore is literal") - // The encoded-word form of quoted-printable turns "_" into a space; the body - // form must not, or every snake_case word in a message loses its underscores. + // Invariant: The encoded-word form of quoted-printable turns "_" into a space; the body +// form must not, or every snake_case word in a message loses its underscores. const underscores = message.parseRfc822(bytes( "Content-Transfer-Encoding: quoted-printable\r\n\r\nsnake_case_name\r\n")) assert.strictEqual(message.extractBody(underscores).text, "snake_case_name\n") @@ -1114,15 +1019,12 @@ assert.strictEqual(message.extractHtml({ Buffer.from("你好,世界", "utf8").toString("base64") + "\r\n")) assert.strictEqual(message.extractBody(base64Body).text, "你好,世界") - // A charset that is not UTF-8 still has to come out right. const latin1 = message.parseRfc822( "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n" + Buffer.from("Café", "latin1").toString("latin1")) assert.strictEqual(message.extractBody(latin1).text, "Café", "the declared charset decides, not a guess") - // --- multipart/alternative: plain wins, html is the fallback - const alternative = message.parseRfc822(bytes( "Content-Type: multipart/alternative; boundary=\"XYZ\"\r\n" + "\r\n" + @@ -1142,12 +1044,10 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(alternative.parts.length, 2, "preamble and epilogue are not parts") deepEqual(message.extractBody(alternative), { text: "the plain one", source: "plain" }) assert.strictEqual(message.extractHtml(alternative), "

the html one

") - // The CRLF before a delimiter belongs to the delimiter. A part that keeps it - // gains a trailing blank line — and a base64 part gains bytes. + // Invariant: The CRLF before a delimiter belongs to the delimiter. A part that keeps it +// gains a trailing blank line — and a base64 part gains bytes. assert.ok(!/\n$/.test(message.extractHtml(alternative))) - // --- nested multipart/mixed → alternative, which is the everyday newsletter - const nested = message.parseRfc822(bytes( "Content-Type: multipart/mixed; boundary=OUTER\r\n\r\n" + "--OUTER\r\n" + @@ -1177,11 +1077,9 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(found[0].attachmentId, "part:2", "the id is the IMAP part path, which is what a later FETCH would ask for") - // An attachment must never be mistaken for the body. + // Invariant: An attachment must never be mistaken for the body. assert.ok(message.extractBody(nested).text.indexOf("PDF") < 0) - // --- an encoded filename - const encodedName = message.parseRfc822(bytes( "Content-Type: multipart/mixed; boundary=B\r\n\r\n" + "--B\r\n" + @@ -1190,18 +1088,15 @@ assert.strictEqual(message.extractHtml({ "--B--\r\n")) assert.strictEqual(message.attachments(encodedName)[0].filename, "报告.pdf") - // --- a multipart whose boundary never appears - // - // Broken, and sent every day. Falling through to the body keeps the message - // readable instead of showing an empty reader. + // Invariant: a broken multipart with no delimiter remains readable as a leaf body. const brokenBoundary = message.parseRfc822(bytes( "Content-Type: multipart/alternative; boundary=NOPE\r\n\r\nthe body anyway\r\n")) assert.strictEqual(message.extractBody(brokenBoundary).text, "the body anyway\n") - // The same repair has to reach the reader, not just the text: a broken - // multipart carrying markup is relabelled html so the reader still renders - // it, while one carrying prose stays plain and keeps its angle brackets. + // Invariant: The same repair has to reach the reader, not just the text: a broken +// multipart carrying markup is relabelled html so the reader still renders +// it, while one carrying prose stays plain and keeps its angle brackets. const brokenHtml = message.parseRfc822(bytes( "Content-Type: multipart/alternative; boundary=NOPE\r\n\r\n" + "

markup anyway

\r\n")) @@ -1212,10 +1107,7 @@ assert.strictEqual(message.extractHtml({ "a < b and c > d\r\n"))), "", "prose that merely contains brackets is not promoted to markup") - // --- depth is bounded - // - // Everything downstream walks this tree by recursion, in the process that - // draws the whole desktop. + // Invariant: MIME tree depth stays bounded on the drawing thread. let deep = "deep body" for (let i = 0; i < 40; i++) { @@ -1231,8 +1123,6 @@ assert.strictEqual(message.extractHtml({ } assert.ok(depth <= 12, "a deeply nested message is not an unbounded recursion (was " + depth + ")") - // --- the whole round trip, as summarize sees it - const summary = message.summarize({ id: "42", labelIds: ["UNREAD", "INBOX"], @@ -1254,20 +1144,16 @@ assert.strictEqual(message.extractHtml({ assert.strictEqual(summary.inInbox, true) assert.strictEqual(summary.time, "5m") - // --- snippets, which IMAP does not send and this has to make - assert.strictEqual(message.buildSnippet(" lots of\n\nwhitespace "), "lots of whitespace") assert.strictEqual(message.buildSnippet("x".repeat(400)).length, 200) assert.strictEqual(message.buildSnippet(""), "") assert.strictEqual(message.buildSnippet(null), "") - // --- nothing at all - deepEqual(message.extractBody(message.parseRfc822("")), { text: "", source: "" }) deepEqual(message.attachments(message.parseRfc822("")), []) } -// A header value is not a header line. `fromHeader` writes the whole `From:` +// Invariant: A header value is not a header line. `fromHeader` writes the whole `From:` // field; a provider composing a `To:` needs the address on its own, and pasting // one into the other produced `To: From: "Name" ` — which parses back // as a display name of `From: "Name"`. @@ -1279,35 +1165,28 @@ assert.strictEqual(message.fromHeader("jane@example.com", "Jane Roe"), assert.strictEqual(message.parseAddress(message.addressHeader("jane@example.com", "Jane Roe")).name, "Jane Roe", "what is written comes back") -// ---------------------------------------------------------------- compose - -// With nothing to place, the body a compose window opens with is what it was -// before signatures existed: empty for a new message, two blank lines above -// the quote for a reply. That equivalence is what makes the field optional. assert.strictEqual(message.composeBody("", ""), "") assert.strictEqual(message.composeBody("", "> quoted"), "\n\n> quoted") assert.strictEqual(message.composeBody(null, undefined), "") -// The signature goes under the cursor and above the quote, so a reply reads as +// Invariant: The signature goes under the cursor and above the quote, so a reply reads as // the reply, the sign-off, then the thread being answered. assert.strictEqual(message.composeBody("Maarten", ""), "\n\nMaarten") assert.strictEqual(message.composeBody("Maarten", "> quoted"), "\n\nMaarten\n\n> quoted") -// A multi-line signature is placed as written. Only the ends are trimmed: +// Invariant: A multi-line signature is placed as written. Only the ends are trimmed: // blank lines around it are this function's to decide, and the ones inside it // are the user's. assert.strictEqual(message.composeBody("\n Maarten\nmadra.nl \n", "> quoted"), "\n\nMaarten\nmadra.nl\n\n> quoted") -// Whitespace is not a signature. A field holding only spaces or newlines must +// Invariant: Whitespace is not a signature. A field holding only spaces or newlines must // produce the same body as an empty one, or every reply gains a blank gap the // user cannot see the cause of. assert.strictEqual(message.composeBody(" \n ", "> quoted"), "\n\n> quoted") assert.strictEqual(message.composeBody("\n\n", ""), "") - - { const recipients = load('compose/Recipients.js') const encoded = value => '=?UTF-8?B?' + Buffer.from(value).toString('base64') + '?=' @@ -1339,7 +1218,6 @@ assert.strictEqual(message.composeBody("\n\n", ""), "") assert.strictEqual(message.contentTypeParam('attachment; filename="a\\\"b.txt"','filename'),'a"b.txt') } - { for (const bytes of [[0xc2, 0x41], [0xe0, 0x80, 0xbc], [0xed, 0xa0, 0x80], [0xf4, 0x90, 0x80, 0x80]]) { assert.strictEqual(message.bytesToUtf8(bytes), String.fromCharCode(...bytes)) @@ -1354,6 +1232,6 @@ assert.strictEqual(message.composeBody("\n\n", ""), "") } console.log("test_message.js ok") -// A draft reopened from the server keeps the Reply-To it was saved with. + assert.strictEqual(message.draftFields({ replyTo: { email: "team@example.com" }, to: [] }, "x").replyTo, "team@example.com") assert.strictEqual(message.draftFields({ replyTo: { email: "" }, to: [] }, "x").replyTo, "") diff --git a/ui/tests/test_outbox.js b/ui/tests/test_outbox.js index 3a5d07c3c..2f3869441 100644 --- a/ui/tests/test_outbox.js +++ b/ui/tests/test_outbox.js @@ -1,5 +1,5 @@ const assert = require("assert") -const { load, deepEqual } = require("./load") +const { load } = require("./load") const outbox = load("message/Outbox.js") @@ -14,19 +14,4 @@ assert.strictEqual(outbox.normalizeDelay(-4), 0) assert.strictEqual(outbox.normalizeDelay(90), 60, "the setting cannot leave mail queued for more than one minute") -deepEqual(outbox.schedule({ subject: "Hello" }, 1000, 10), { - payload: { subject: "Hello" }, - dueAt: 11000 -}) -assert.strictEqual(outbox.schedule({}, 1000, 0), null, - "an immediate send does not create a pending item") - -assert.strictEqual(outbox.remainingSeconds(11000, 1000), 10) -assert.strictEqual(outbox.remainingSeconds(11000, 1001), 10, - "the countdown must not show nine immediately") -assert.strictEqual(outbox.remainingSeconds(11000, 10000), 1) -assert.strictEqual(outbox.remainingSeconds(11000, 10999), 1) -assert.strictEqual(outbox.remainingSeconds(11000, 11000), 0) -assert.strictEqual(outbox.remainingSeconds(11000, 12000), 0) - console.log("test_outbox.js ok") diff --git a/ui/tests/test_signature.js b/ui/tests/test_signature.js index 41f2687f6..65fcc2739 100644 --- a/ui/tests/test_signature.js +++ b/ui/tests/test_signature.js @@ -3,12 +3,10 @@ const { load, deepEqual } = require("./load") const signature = load("message/Signature.js") -// One-pixel rasters, as base64. const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" const GIF = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" const SVG = Buffer.from('').toString("base64") -// A picture: only a real raster, by its bytes, within the cap. assert.strictEqual(signature.rasterKind(PNG), "image/png") assert.strictEqual(signature.rasterKind(GIF), "image/gif") assert.strictEqual(signature.rasterKind(SVG), "", "an SVG is a document, whatever it is named") @@ -21,7 +19,6 @@ assert.strictEqual(signature.rasterKind(""), "") assert.ok(signature.importImage(PNG, { maxImageBytes: 10 }).problem.indexOf("larger") >= 0) } -// Markup: everything that could run, fetch or hide is gone; the words stay. { const hostile = '' + '

Ada Lovelace

' @@ -55,7 +52,6 @@ assert.strictEqual(signature.rasterKind(""), "") assert.strictEqual(html.indexOf("<"), 0, "what is stored is markup rebuilt from the tree") } -// Formatting is what the file was imported for: colours, a face, a table. { const styled = signature.importHtml('
Ada
Analyst
') assert.strictEqual(styled.problem, "") @@ -65,12 +61,11 @@ assert.strictEqual(signature.rasterKind(""), "") assert.strictEqual(styled.dropped, 0, "nothing needed removing") } -// Nothing usable, and too big, are refused rather than stored empty. assert.ok(signature.importHtml("").problem.indexOf("Nothing") >= 0) assert.ok(signature.importHtml("x".repeat(300 * 1024)).problem.indexOf("too large") >= 0) assert.ok(signature.importHtml("").problem !== "") -// Text with a break in it stays two lines, and a stored signature round-trips +// Invariant: Text with a break in it stays two lines, and a stored signature round-trips // through the importer unchanged in what it says. { const first = signature.importHtml("

Ada Lovelace
Analyst

") @@ -80,7 +75,6 @@ assert.ok(signature.importHtml("").problem !== "") assert.strictEqual(again.plain, first.plain) } -// Sending: each data image becomes a cid part. { const swapped = signature.inlineParts('

and

', "sig") assert.strictEqual(swapped.parts.length, 2) diff --git a/ui/tests/test_unsubscribe.js b/ui/tests/test_unsubscribe.js index d519f60ba..abde20135 100644 --- a/ui/tests/test_unsubscribe.js +++ b/ui/tests/test_unsubscribe.js @@ -9,8 +9,6 @@ function headers(pairs) { }) } -// ----------------------------------------------------------- header entries - deepEqual(unsub.entries(", "), ["https://example.com/u/1", "mailto:bye@example.com"]) deepEqual(unsub.entries(" "), ["https://example.com/u/1"]) @@ -18,29 +16,26 @@ deepEqual(unsub.entries(""), []) deepEqual(unsub.entries("https://example.com/u/1"), [], "an entry outside brackets is not one the RFC defines") -// The brackets delimit, not the comma: a mailto body may hold one, and reading +// Invariant: The brackets delimit, not the comma: a mailto body may hold one, and reading // it as a separator turns one address into two broken ones. deepEqual(unsub.entries(""), ["mailto:bye@example.com?body=one,two"]) -// A header long enough to be an attack rather than a list is not walked at all. deepEqual(unsub.entries(""), []) -// ------------------------------------------------------------------ mailto - deepEqual(unsub.parseMailto("mailto:bye@example.com"), { to: "bye@example.com", subject: "Unsubscribe", body: "Unsubscribe" }) deepEqual(unsub.parseMailto("mailto:bye@example.com?subject=Stop%20these&body=please"), { to: "bye@example.com", subject: "Stop these", body: "please" }) -// RFC 6068 keeps literal plus signs in mailto queries. +// Invariant: RFC 6068 keeps literal plus signs in mailto queries. assert.strictEqual(unsub.parseMailto("mailto:bye@example.com?subject=Stop+these").subject, "Stop+these") -// Several recipients: the first is the one that unambiguously belongs here. + assert.strictEqual(unsub.parseMailto("mailto:a@example.com,b@example.com").to, "a@example.com") assert.strictEqual(unsub.parseMailto("mailto:not-an-address"), null) assert.strictEqual(unsub.parseMailto("https://example.com"), null) -// This value goes into a message this plugin builds. A newline in it is how a +// Invariant: This value goes into a message this plugin builds. A newline in it is how a // list gets to write its own Bcc, so it never survives. const injected = unsub.parseMailto( "mailto:bye@example.com?subject=Stop%0D%0ABcc:%20victim@example.com") @@ -49,12 +44,10 @@ assert.strictEqual(injected.subject.indexOf("\r"), -1) assert.strictEqual(injected.subject, "Stop Bcc: victim@example.com") assert.strictEqual(unsub.parseMailto("mailto:bye@example.com?subject=%E4%B8%AD%E6%96%87").subject, "中文", "a percent-encoded subject decodes as UTF-8") -// A stray percent is not an escape, and losing the whole subject over one is +// Invariant: A stray percent is not an escape, and losing the whole subject over one is // worse than keeping it as written. assert.strictEqual(unsub.parseMailto("mailto:bye@example.com?subject=100%").subject, "100%") -// --------------------------------------------------------------------- URLs - for (const control of ["\r", "\n", "\r\n", "\t", "\u0000", "\u007f"]) { const url = "https://list.example.com/u" + control + "next" assert.strictEqual(unsub.isPostableUrl(url), false, "reject raw URL controls") @@ -80,14 +73,12 @@ assert.strictEqual(unsub.isPublicWebUrl("https://router.local/u/1"), false) assert.strictEqual(unsub.isPublicWebUrl("javascript:alert(1)"), false) assert.strictEqual(unsub.isPublicWebUrl("file:///etc/passwd"), false) -// A POST carries the fact that this address reads this mail. Over plain http +// Invariant: A POST carries the fact that this address reads this mail. Over plain http // that is a postcard to a host the sender chose. assert.strictEqual(unsub.isPostableUrl("https://list.example.com/u/1"), true) assert.strictEqual(unsub.isPostableUrl("http://list.example.com/u/1"), false) assert.strictEqual(unsub.isPostableUrl("https://10.0.0.5/u/1"), false) -// ------------------------------------------------------------- the decision - const oneClick = unsub.from( ", ", "List-Unsubscribe=One-Click") @@ -100,7 +91,7 @@ assert.strictEqual(unsub.plan(oneClick, false), "post", "a one-click POST needs nothing from the provider") assert.strictEqual(unsub.label(oneClick, true), "Unsubscribe") -// Without the header there is no promise that a POST is enough, and posting +// Invariant: Without the header there is no promise that a POST is enough, and posting // anyway would be a guess at somebody else's API. const linkOnly = unsub.from("", "") assert.strictEqual(linkOnly.oneClick, false) @@ -110,12 +101,12 @@ assert.strictEqual(unsub.plan(linkOnly, true), "browser") assert.strictEqual(unsub.label(linkOnly, true), "Unsubscribe...", "a label that opens a browser says so before it is pressed") -// The header claims one-click over plain http, which RFC 8058 does not allow. +// Invariant: The header claims one-click over plain http, which RFC 8058 does not allow. const insecure = unsub.from("", "List-Unsubscribe=One-Click") assert.strictEqual(insecure.oneClick, false) assert.strictEqual(unsub.plan(insecure, true), "browser") -// A URL nobody should be asked to fetch leaves only the mailto standing. +// Invariant: A URL nobody should be asked to fetch leaves only the mailto standing. const privateHost = unsub.from( ", ", "List-Unsubscribe=One-Click") assert.strictEqual(privateHost.url, "") @@ -124,7 +115,7 @@ assert.strictEqual(unsub.plan(privateHost, true), "mail") const mailOnly = unsub.from("", "") assert.strictEqual(unsub.plan(mailOnly, true), "mail") -// A mailbox that cannot send still has something to offer, and it is the last +// Invariant: A mailbox that cannot send still has something to offer, and it is the last // resort rather than a button that fails after it is pressed. assert.strictEqual(unsub.plan(unsub.from(", ", ""), false), "browser") @@ -137,8 +128,6 @@ assert.strictEqual(unsub.plan(nothing, true), "") assert.strictEqual(unsub.label(nothing, true), "") assert.strictEqual(unsub.explanation(nothing, true), "") -// The sentence beside the button says which of the three amounts of work the -// user is agreeing to. assert.strictEqual(unsub.explanation(oneClick, true), "This sender accepts a one-click unsubscribe") assert.strictEqual(unsub.explanation(mailOnly, true), @@ -146,8 +135,6 @@ assert.strictEqual(unsub.explanation(mailOnly, true), assert.strictEqual(unsub.explanation(linkOnly, true), "Unsubscribing opens this sender's page in a browser") -// ---------------------------------------------------------- out of a mail - const found = unsub.fromHeaders(headers({ "From": "News ", "List-Unsubscribe": "", @@ -156,7 +143,7 @@ const found = unsub.fromHeaders(headers({ assert.strictEqual(found.oneClick, true) assert.strictEqual(found.postUrl, "https://list.example.com/u/9") -// Header names are case-insensitive on the wire and both providers pass them +// Invariant: Header names are case-insensitive on the wire and both providers pass them // through as the server wrote them. assert.strictEqual(unsub.fromHeaders(headers({ "list-unsubscribe": "" @@ -166,19 +153,11 @@ assert.strictEqual(unsub.fromHeaders(headers({ "From": "a@b.com" })).available, assert.strictEqual(unsub.fromHeaders([]).available, false) assert.strictEqual(unsub.fromHeaders(null).available, false) -// The whole message resource, which is what the reader holds. assert.strictEqual(unsub.fromMessage({ payload: { headers: headers({ "List-Unsubscribe": "" }) } }).mail.to, "bye@example.com") assert.strictEqual(unsub.fromMessage(null).available, false) -// ------------------------------------------------------------------- POST - -assert.strictEqual(unsub.postBody(), "List-Unsubscribe=One-Click") -assert.strictEqual(unsub.postContentType(), "application/x-www-form-urlencoded") - - - { const value=unsub.parseMailto('mailto:list+remove@example.test?subject=A+B%20C%2BD') assert.ok(value) From ad26e06b45cdbb8554797cc5a9fb4013e80442aa Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:22:04 +0100 Subject: [PATCH 151/568] chore: Use valid PNG bytes in reader success fixtures --- ui/tests/qml/tst_image_popover.qml | 2 +- ui/tests/qml/tst_signature_import_lifecycle.qml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/tests/qml/tst_image_popover.qml b/ui/tests/qml/tst_image_popover.qml index 8e4705588..995e16399 100644 --- a/ui/tests/qml/tst_image_popover.qml +++ b/ui/tests/qml/tst_image_popover.qml @@ -36,7 +36,7 @@ Item { function test_prepared_raster_bytes_are_shown() { var sheet = popover() - var data = "data:image/png;base64,iVBORw0KGgo=" + var data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" sheet.showPrepared("https://cdn.example.com/a.png", data) compare(sheet.source, data) compare(sheet.refused, false) diff --git a/ui/tests/qml/tst_signature_import_lifecycle.qml b/ui/tests/qml/tst_signature_import_lifecycle.qml index a73c1255d..68183b330 100644 --- a/ui/tests/qml/tst_signature_import_lifecycle.qml +++ b/ui/tests/qml/tst_signature_import_lifecycle.qml @@ -95,7 +95,7 @@ Item { fakeBackend.callback = null } function picked() { fakeService.pickerCallback({ok: true, paths: ["/synthetic/signature.png"]}) } - function read() { fakeBackend.callback({ok: true, mimeType: "image/png", data: "iVBORw0KGgoAAA=="}, null) } + function read() { fakeBackend.callback({ok: true, mimeType: "image/png", data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"}, null) } function imported() { fakeBackend.callback({html: "

signature

", plain: "", images: 1, dropped: 0, problem: ""}, null) } function test_import_button_starts_the_owned_request() { var trigger = findChild(page, "settings-signature-import") From 4826a66a564ddec5469d4a2d964e759841d12838 Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:24:53 +0100 Subject: [PATCH 152/568] website: Fix stale copy feedback after a second request --- docs/index.html | 5 ++++- tests/test_website.js | 30 ++++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/docs/index.html b/docs/index.html index 1d29fab11..10baf47ad 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1128,6 +1128,7 @@

Run from source

} var copy = document.querySelector(".copy"); + var copyResetTimer; function selectCommand() { var range = document.createRange(); range.selectNodeContents(document.querySelector(".command .cmd")); @@ -1140,6 +1141,8 @@

Run from source

copy.disabled = false; } function copyCommand() { + clearTimeout(copyResetTimer); + copy.removeAttribute("data-state"); if (!navigator.clipboard || typeof navigator.clipboard.writeText !== "function") { selectCommand(); return; @@ -1151,7 +1154,7 @@

Run from source

copy.textContent = copyLabels[lang]; copy.setAttribute("data-state", "done"); copy.disabled = false; - setTimeout(function () { + copyResetTimer = setTimeout(function () { copy.innerHTML = copy.getAttribute("data-" + lang); copy.removeAttribute("data-state"); }, 1600); diff --git a/tests/test_website.js b/tests/test_website.js index 3194c0087..4df0118cd 100644 --- a/tests/test_website.js +++ b/tests/test_website.js @@ -8,8 +8,11 @@ const html = fs.readFileSync(path.join(__dirname, "../docs/index.html"), "utf8") const script = [...html.matchAll(/ok").html, "ok") - assert.strictEqual(html.sanitize("

secret

real

").html, "

real

") - assert.strictEqual(html.sanitize("
t").html, "t") + '
x
') + assert.strictEqual(sanitize("ok").html, "ok") + assert.strictEqual(sanitize("

secret

real

").html, "

real

") + assert.strictEqual(sanitize("t").html, "t") // A "<" that starts no tag is a "<" the sender typed, and it goes back out // escaped rather than raw. It draws the same either way, and leaving it raw @@ -73,21 +88,21 @@ const html = load("message/Html.js") // A raw-text element ends at its own closing tag and at nothing else, so a // stylesheet cannot hide markup from the walk that follows it. - assert.strictEqual(html.sanitize("ok").html, "ok") - assert.strictEqual(html.sanitize("ok").html, "ok") + assert.strictEqual(sanitize("ok").html, "ok") + assert.strictEqual(sanitize("ok").html, "ok") // ...and per the spec the first "a{}

after

").html.indexOf("

after

") >= 0) + assert.ok(sanitize("

after

").html.indexOf("

after

") >= 0) // A tag that never closes takes the rest of the document with it, which is // what Qt does with it too — and is the reading that cannot leave a fetch // behind. - assert.strictEqual(html.sanitize("

kept

kept

") + assert.strictEqual(sanitize("

kept

kept

") // A doctype is not text: Qt would lay it out as a line above the message. - assert.strictEqual(html.sanitize("

hi

").html, "

hi

") + assert.strictEqual(sanitize("

hi

").html, "

hi

") // A title is not body text either, and nearly every marketing mail ships one. - assert.strictEqual(html.sanitize("Newsletter

real

").html, + assert.strictEqual(sanitize("Newsletter

real

").html, "

real

") } @@ -110,11 +125,11 @@ const html = load("message/Html.js") // just stops adding a level to hold it. { const deepest = "
".repeat(20000) + "text" - const out = html.sanitize(deepest, { allowRemoteImages: true }) + const out = sanitize(deepest, { allowRemoteImages: true }) assert.ok(out.html.indexOf("127.0.0.1") < 0, "the ceiling is not a way past the image policy") assert.ok(out.html.indexOf("text") > 0, "the content is still there") const tables = "
".repeat(4000) + "cell" - assert.ok(html.sanitize(tables).html.indexOf("cell") > 0) + assert.ok(sanitize(tables).html.indexOf("cell") > 0) assert.ok(html.tooHeavyForRichText(tables), "and it is still refused as too heavy") } @@ -122,10 +137,10 @@ const html = load("message/Html.js") // asking separately would mean parsing the whole body again to count what was // just counted. { - const light = html.sanitize("

hi

") + const light = sanitize("

hi

") assert.strictEqual(light.tooHeavy, false) assert.strictEqual(light.complexity.tags, 1) - const heavy = html.sanitize("
".repeat(html.MAX_ELEMENTS + 1)) + const heavy = sanitize("
".repeat(html.MAX_ELEMENTS + 1)) assert.strictEqual(heavy.tooHeavy, true) assert.strictEqual(heavy.tooHeavy, html.tooHeavyForRichText(heavy.html), "and it agrees with asking the long way round") @@ -137,7 +152,7 @@ const html = load("message/Html.js") const body = "" + "

copy

" + "" - const asked = html.sanitize(body, { withPlainText: true }) + const asked = sanitize(body, { withPlainText: true }) // Numbered off the sender's own tree, before the image policy is applied: a // message's second picture is its second picture whether or not the first was // a request to the machine itself. A beacon is the one thing not counted — @@ -151,7 +166,7 @@ const html = load("message/Html.js") // The same answer the long way round, so the shortcut cannot drift from it. deepEqual(asked.plainText, html.readPlainText(body)) // And nothing is paid for it unless it is asked for. - assert.strictEqual(html.sanitize(body).plainText, null) + assert.strictEqual(sanitize(body).plainText, null) } // ------------------------------------------------------------ scaffolding @@ -162,44 +177,44 @@ const html = load("message/Html.js") // the two shapes that provably render the same. { // A stack of empty wrappers is the innermost thing in it. - assert.strictEqual(html.sanitize("

hi

").html, "

hi

") + assert.strictEqual(sanitize("

hi

").html, "

hi

") const table = "
ab
cd
" - assert.strictEqual(html.sanitize("
" + table + "
").html, table) + assert.strictEqual(sanitize("
" + table + "
").html, table) // An inline element carrying nothing is nothing. - assert.strictEqual(html.sanitize("

abc

").html, "

abc

") + assert.strictEqual(sanitize("

abc

").html, "

abc

") // Anything the wrapper carries is a reason it is there. - assert.strictEqual(html.sanitize("

hi

").html, + assert.strictEqual(sanitize("

hi

").html, "

hi

") // Centring is not one of those reasons. The sender centres a 600px card in // the middle of a wide window; the reader is a panel of left-aligned text // beside a left-aligned list, and a newsletter kept centred there comes out // as a column of short lines adrift in it. - assert.strictEqual(html.sanitize("

hi

").html, "

hi

") - assert.strictEqual(html.sanitize("

hi

").html, "

hi

") - assert.strictEqual(html.sanitize("

hi

").html, + assert.strictEqual(sanitize("

hi

").html, "

hi

") + assert.strictEqual(sanitize("

hi

").html, "

hi

") + assert.strictEqual(sanitize("

hi

").html, "

hi

") // Every other alignment is the sender saying something the panel can honour: // a column of numbers reads right, and Arabic reads from the other end. - assert.ok(html.sanitize("

9.00

").html + assert.ok(sanitize("

9.00

").html .indexOf("text-align:right") > 0) // And a cell keeps even centring: a column lining up is the one thing a grid // is kept for. - assert.ok(html.sanitize("" + assert.ok(sanitize("
ab
" + "
ab
cd
").html .indexOf("text-align:center") > 0) // is not : it says something with no attributes at all. - assert.strictEqual(html.sanitize("

bold

").html, "

bold

") + assert.strictEqual(sanitize("

bold

").html, "

bold

") // Two boxes are two boxes, and a box holding text as well as a box is not // holding only that box. - assert.strictEqual(html.sanitize("

a

b

").html, "

a

b

") - assert.strictEqual(html.sanitize("
text

b

").html, "
text

b

") + assert.strictEqual(sanitize("

a

b

").html, "

a

b

") + assert.strictEqual(sanitize("
text

b

").html, "
text

b

") // Whitespace between blocks is not text: a template's newlines do not pin a // wrapper in place. - assert.strictEqual(html.sanitize("
\n

a

\n
").html, "

a

") + assert.strictEqual(sanitize("
\n

a

\n
").html, "

a

") // An inline child means the wrapper is what puts it on its own line. - assert.strictEqual(html.sanitize("
a
").html, + assert.strictEqual(sanitize("
a
").html, "
a
") // On mail shaped like the real thing this is most of the document. Nine @@ -210,10 +225,10 @@ const html = load("message/Html.js") close = "
" + close } card += "

copy

" + close - const carded = html.sanitize(card, { allowRemoteImages: true }) + const carded = sanitize(card, { allowRemoteImages: true }) assert.ok(carded.complexity.tags < 12, "nine levels of scaffolding come out as a handful of elements, not thirty") - assert.ok(carded.html.indexOf("copy") > 0 && carded.html.indexOf("h.png") > 0, + assert.ok(carded.html.indexOf("copy") > 0 && carded.html.indexOf(tinyPng) > 0, "and everything that was in them is still there") } @@ -270,13 +285,13 @@ const html = load("message/Html.js") // of a

hi

").html, "

hi

") -assert.strictEqual(html.sanitize("text").html, "text") -assert.strictEqual(html.sanitize("text").html, "text") -assert.strictEqual(html.sanitize("

hi

").html, "

hi

") -assert.strictEqual(html.sanitize("hi").html, "hi") -assert.strictEqual(html.sanitize("kept").html, "kept") -assert.strictEqual(html.sanitize("body").html, "body") +assert.strictEqual(sanitize("

hi

").html, "

hi

") +assert.strictEqual(sanitize("text").html, "text") +assert.strictEqual(sanitize("text").html, "text") +assert.strictEqual(sanitize("

hi

").html, "

hi

") +assert.strictEqual(sanitize("hi").html, "hi") +assert.strictEqual(sanitize("kept").html, "kept") +assert.strictEqual(sanitize("body").html, "body") // The tags that carry an email's actual layout must survive untouched. Real // mail is still table-and-inline-style HTML written for Outlook, which is @@ -284,10 +299,10 @@ assert.strictEqual(html.sanitize("body").html, "body") // Layout survives; the sender's palette does not (see the theming block). const table = "" + "
ItemTotal
Tea2.00
" -assert.strictEqual(html.sanitize(table).html, table) -assert.strictEqual(html.sanitize("link").html, +assert.strictEqual(sanitize(table).html, table) +assert.strictEqual(sanitize("link").html, "link") -assert.strictEqual(html.sanitize("mail").html, +assert.strictEqual(sanitize("mail").html, "mail") // -------------------------------------------------------- remote images @@ -296,51 +311,51 @@ assert.strictEqual(html.sanitize("mail").html, // pixel in the message fires the moment the reader opens it. const tracked = "

Hi

" -const blocked = html.sanitize(tracked) +const blocked = sanitize(tracked) assert.strictEqual(blocked.blockedImages, 1) assert.ok(blocked.html.indexOf("track.example") < 0, "the URL must not reach the renderer") assert.ok(blocked.html.indexOf("

Hi

") === 0, "the rest of the message is untouched") // A 1x1 image is a beacon, never something to look at, so it goes even when // images are welcome. Every real message in a live mailbox carries one. -const allowedPixel = html.sanitize(tracked, { allowRemoteImages: true }) +const allowedPixel = sanitize(tracked, { allowRemoteImages: true }) assert.strictEqual(allowedPixel.images, 0) assert.strictEqual(allowedPixel.blockedImages, 1) -assert.strictEqual(html.sanitize("", +assert.strictEqual(sanitize("", { allowRemoteImages: true }).images, 0) -assert.strictEqual(html.sanitize("", +assert.strictEqual(sanitize("", { allowRemoteImages: true }).images, 0) // A real picture is kept. const real = "" -assert.strictEqual(html.sanitize(real, { allowRemoteImages: true }).images, 1) -assert.ok(html.sanitize(real, { allowRemoteImages: true }).html.indexOf("photo.png") > 0) -assert.strictEqual(html.sanitize(real).images, 0, "still off unless asked for") +assert.strictEqual(sanitize(real, { allowRemoteImages: true }).images, 1) +assert.ok(sanitize(real, { allowRemoteImages: true }).html.indexOf(tinyPng) > 0) +assert.strictEqual(sanitize(real).images, 0, "still off unless asked for") // Every image is a fetch Qt performs during layout, and every completed fetch // triggers another layout pass, so the count is capped. let many = "" for (let i = 0; i < html.MAX_IMAGES + 8; i++) many += "" -const capped = html.sanitize(many, { allowRemoteImages: true }) +const capped = sanitize(many, { allowRemoteImages: true }) assert.strictEqual(capped.images, html.MAX_IMAGES) assert.strictEqual(capped.blockedImages, 8) -assert.strictEqual(html.sanitize(many, { allowRemoteImages: true, maxImages: 3 }).images, 3) +assert.strictEqual(sanitize(many, { allowRemoteImages: true, maxImages: 3 }).images, 3) // A caller may defer remote resources until it has fetched and validated the // bytes itself. Qt then sees no loading URL (and draws no broken placeholder), // only a data URI once that exact source is ready. { const source = "

" - const waiting = html.sanitize(source, { + const waiting = sanitize(source, { allowRemoteImages: true, remoteImageData: ({}), withReader: true }) assert.strictEqual(waiting.html.indexOf("cdn.example.com"), -1) assert.strictEqual(waiting.reader.html.indexOf("cdn.example.com"), -1) deepEqual(waiting.remoteImageSources, ["https://cdn.example.com/photo.png"]) - deepEqual(html.sanitize("
") + deepEqual(sanitize("
") .remoteImageSources, [], "a hidden picture is not prefetched") - const ready = html.sanitize(source, { + const ready = sanitize(source, { allowRemoteImages: true, remoteImageData: ({ "https://cdn.example.com/photo.png": "data:image/png;base64,iVBORw0KGgo=" }), withReader: true @@ -370,13 +385,13 @@ assert.strictEqual(html.complexity(null).length, 0) // cid: images point at attachments this plugin does not fetch, and data: URIs // are already local. Neither is a network request, and neither is counted. -assert.strictEqual(html.sanitize("").blockedImages, 0) -assert.strictEqual(html.sanitize("").blockedImages, 0) -assert.strictEqual(html.sanitize("").blockedImages, 2) -assert.strictEqual(html.sanitize("", +assert.strictEqual(sanitize("").blockedImages, 0) +assert.strictEqual(sanitize("").blockedImages, 0) +assert.strictEqual(sanitize("").blockedImages, 2) +assert.strictEqual(sanitize("", { allowRemoteImages: true }).images, 2, "images with no stated size are real pictures") // Protocol-relative sources are still network fetches. -assert.strictEqual(html.sanitize("").blockedImages, 1) +assert.strictEqual(sanitize("").blockedImages, 1) // ------------------------------------------------- where an image may point // @@ -402,7 +417,7 @@ const localSources = [ "http://cdn.example.com@127.0.0.1/x.png" ] for (const source of localSources) { - const asked = html.sanitize("", + const asked = sanitize("", { allowRemoteImages: true }) assert.strictEqual(asked.images, 0, source + " must never be fetched") assert.ok(asked.html.indexOf("img") < 0, source + " must not reach the renderer") @@ -416,33 +431,33 @@ assert.strictEqual(html.externallyOpenableHttpUrl("javascript:alert(1)"), "") assert.strictEqual(html.externallyOpenableHttpUrl("file:///etc/passwd"), "") // A public address in a URL is fine, however it is written. -assert.strictEqual(html.sanitize("", +assert.strictEqual(sanitize("", { allowRemoteImages: true }).images, 1) // Qt resolves the character references in an attribute before it fetches, so a // source that does not look like a URL to a reader can still be one to it. assert.strictEqual( - html.sanitize("").blockedImages, 1) + sanitize("").blockedImages, 1) assert.strictEqual( - html.sanitize("", + sanitize("", { allowRemoteImages: true }).images, 0) // A relative source has no base but the plugin's own directory, so Qt would // read whatever sits next to the QML. -assert.ok(html.sanitize("").html.indexOf("img") < 0) -assert.ok(html.sanitize("").html.indexOf("img") < 0) +assert.ok(sanitize("").html.indexOf("img") < 0) +assert.ok(sanitize("").html.indexOf("img") < 0) // The count the reader offers to load is the count it can actually load. const mixed = "" + "" + "" -assert.strictEqual(html.sanitize(mixed).remoteImages, 1) -assert.strictEqual(html.sanitize(mixed, { allowRemoteImages: true }).images, 1) +assert.strictEqual(sanitize(mixed).remoteImages, 1) +assert.strictEqual(sanitize(mixed, { allowRemoteImages: true }).images, 1) // A url() in an inline style is a fetch too, wherever the engine honours one. -assert.ok(html.sanitize("
x
") +assert.ok(sanitize("
x
") .html.indexOf("track.example.com") < 0) -assert.ok(html.sanitize("
x
") +assert.ok(sanitize("
x
") .html.indexOf("padding:4px") > 0, "the rest of the style survives") // ---------------------------------------------------------- tag boundaries @@ -453,22 +468,22 @@ assert.ok(html.sanitize("
" in an alt text was enough to walk an image past the block. { const hidden = "\"ab\" src=\"https://tracker.example.com/p.gif\" width=\"90\">" - assert.strictEqual(html.sanitize(hidden).blockedImages, 1) - assert.ok(html.sanitize(hidden).html.indexOf("tracker.example.com") < 0) - assert.strictEqual(html.sanitize(hidden, { allowRemoteImages: true }).images, 1) + assert.strictEqual(sanitize(hidden).blockedImages, 1) + assert.ok(sanitize(hidden).html.indexOf("tracker.example.com") < 0) + assert.strictEqual(sanitize(hidden, { allowRemoteImages: true }).images, 1) const hiddenLocal = "a>b" - assert.ok(html.sanitize(hiddenLocal, { allowRemoteImages: true }).html.indexOf("127.0.0.1") < 0) + assert.ok(sanitize(hiddenLocal, { allowRemoteImages: true }).html.indexOf("127.0.0.1") < 0) // A quote that never closes takes the rest of the document with it: Qt would // swallow the remainder into the tag anyway, and dropping it is the reading // that cannot leave a fetch behind. - assert.ok(html.sanitize("

hi

\"oops")hi

\"oops")hi

\"x\"

bye

").html, + sanitize("

hi

\"x\"

bye

").html, "

hi

bye

") } @@ -486,7 +501,6 @@ assert.ok(html.sanitize("
none

"), false) -assert.strictEqual(html.sanitize("").html, "") -assert.strictEqual(html.sanitize(null).html, "") -assert.strictEqual(html.sanitize(null).blockedImages, 0) +assert.strictEqual(sanitize("").html, "") +assert.strictEqual(sanitize(null).html, "") +assert.strictEqual(sanitize(null).blockedImages, 0) // ----------------------------------------------------------- theming // @@ -541,8 +555,8 @@ assert.strictEqual(html.stripColors(null), "") // sanitize does it by default, so nothing renders in the sender's palette // unless a caller explicitly asks to keep it. -assert.ok(html.sanitize("x").html.indexOf("#") < 0) -assert.ok(html.sanitize("x", { keepColors: true }).html.indexOf("#fff") > 0) +assert.ok(sanitize("x").html.indexOf("#") < 0) +assert.ok(sanitize("x", { keepColors: true }).html.indexOf("#fff") > 0) // An HTML `background` is not one of them. It is an image URL, Qt fetches it, // and it rode in the colour list because senders write it beside `bgcolor` — @@ -553,28 +567,28 @@ const painted = "" + "
ab
cd
" for (const options of [{}, { keepColors: true }, { keepColors: true, allowRemoteImages: true }]) { - const formatted = html.sanitize(painted, options).html + const formatted = sanitize(painted, options).html assert.ok(formatted.indexOf("background=") < 0, "background survived " + JSON.stringify(options)) assert.ok(formatted.indexOf("static.example.net") < 0) } // The colours themselves are still an appearance question, still answered by // the option rather than by the resource rule. -assert.ok(html.sanitize(painted, { keepColors: true }).html.indexOf("#ffffff") > 0) +assert.ok(sanitize(painted, { keepColors: true }).html.indexOf("#ffffff") > 0) assert.strictEqual(html.stripColors("t"), "t") // The rest of the attributes whose value is an address rather than a value. for (const attribute of ["srcset", "lowsrc", "dynsrc", "poster", "usemap", "ping", "formaction", "longdesc"]) { - assert.ok(html.sanitize("

t

", + assert.ok(sanitize("

t

", { keepColors: true }).html.indexOf("x.example.com") < 0, attribute + " kept an address") } // And a url() in a style is a fetch wherever the engine honours one, whatever // the appearance setting says. for (const options of [{}, { keepColors: true }]) { - assert.ok(html.sanitize("
t
", + assert.ok(sanitize("
t
", options).html.indexOf("url(") < 0) } @@ -585,7 +599,7 @@ for (const options of [{}, { keepColors: true }]) { // So the references come out before anything is split. for (const hidden of ["url", "url", "&#117;rl", "url"]) { for (const options of [{}, { keepColors: true }]) { - const out = html.sanitize("", options).html assert.ok(out.indexOf("x.example.com") < 0, hidden + " reached the renderer " + JSON.stringify(options) + ": " + out) @@ -593,24 +607,24 @@ for (const hidden of ["url", "url", "&#117;rl", "url"]) { } // The same reference used to smuggle a whole second declaration past the split. assert.strictEqual( - html.sanitize("
t
", + sanitize("
t
", { keepColors: true }).html, "
t
") // ...and to hide the thing that says it is hidden. -assert.strictEqual(html.sanitize("

secret

real

").html, +assert.strictEqual(sanitize("

secret

real

").html, "

real

") // CSS escapes and comments are the same smuggle after entities are gone. // A hex escape is at most six digits; the space form is the other spelling. for (const hidden of ["\\000075rl", "\\75 rl", "url/**/", "\\\\75rl", "url/\\*\\*/", "url/\\2a\\2a/"]) { for (const options of [{}, { keepColors: true }]) { - const out = html.sanitize("", options).html assert.ok(out.indexOf("x.example.com") < 0, hidden + " reached the renderer " + JSON.stringify(options) + ": " + out) } } // Duplicate src: only the first is judged, so the second must not survive. -assert.ok(html.sanitize( +assert.ok(sanitize( "" ).html.indexOf("x.example.com") < 0) @@ -618,24 +632,24 @@ assert.ok(html.sanitize( // the same address with none of that checking behind it. for (const source of ["", ""]) { - assert.ok(html.sanitize(source, { allowRemoteImages: true }).html.indexOf("x.example.com") < 0, + assert.ok(sanitize(source, { allowRemoteImages: true }).html.indexOf("x.example.com") < 0, "a src survived on " + source) } // A data: URL is the message's own bytes only when it is a raster picture. // SVG is a document with references of its own; the fetch worker refuses it // and so does the sanitiser, even with remote images off. -assert.ok(html.sanitize("").html.indexOf("data:image/png") > 0) -assert.strictEqual(html.sanitize("").html, "", +assert.ok(sanitize("").html.indexOf("data:image/png") > 0) +assert.strictEqual(sanitize("").html, "", "a disguised document must be removed before rendering") -assert.strictEqual(html.sanitize("x\">").html, "") -assert.strictEqual(html.sanitize("").html, "") +assert.strictEqual(sanitize("x\">").html, "") +assert.strictEqual(sanitize("").html, "") assert.strictEqual(html.imageSourceKind("data:image/svg+xml;base64,AAA"), "unsafe") // The host is the one question where reading an address twice is not the safe // direction: a second decoding can turn up a "@" and hand the authority to a // later label. So it has to be public to both readings. -assert.ok(html.sanitize("", +assert.ok(sanitize("", { allowRemoteImages: true }).html.indexOf("127.0.0.1") < 0) assert.strictEqual( reading("

t

").html, "

t

") @@ -664,7 +678,7 @@ const smuggled = [ "

<\u200bstyle>body{background-image:url(https://x.example.com/x.png)}

" ] for (const source of smuggled) { - const ready = html.sanitize(source, { withReader: true }) + const ready = sanitize(source, { withReader: true }) for (const [view, out] of [["formatted", ready.html], ["reading", ready.reader.html]]) { assert.ok(!/<(img|a|style)\b/i.test(out.replace(/<\/?(p|span|pre|b|strong|em|br)\b[^>]*>/gi, "")), view + " parsed a tag out of text: " + out) @@ -725,8 +739,8 @@ assert.strictEqual(html.tableDepth(grids), 3) assert.strictEqual(html.tableDepth(html.flattenTables(grids, 2)), 2, "nothing survives past the limit") // sanitize flattens by default; a caller can ask for the original. -assert.strictEqual(html.complexity(html.sanitize(deep).html).tableDepth, 0) -assert.strictEqual(html.complexity(html.sanitize(deep, { keepTables: true }).html).tableDepth, 3) +assert.strictEqual(html.complexity(sanitize(deep).html).tableDepth, 0) +assert.strictEqual(html.complexity(sanitize(deep, { keepTables: true }).html).tableDepth, 3) // The backstop still catches anything flattening cannot tame. let wide = "" @@ -756,7 +770,7 @@ assert.ok(bare.indexOf("x") > 0) // the sender's outer content width instead, so a 600px message does not stretch // across a wide monitor. { - const card = html.sanitize("
" + const card = sanitize("
" + "

copy

") assert.strictEqual(html.preferredContentWidth(card.document, 1800), 600) assert.strictEqual(html.preferredContentWidth(card.document, 480), 480, @@ -820,14 +834,14 @@ assert.ok(bare.indexOf("x") > 0) // honoured in pixels but a percentage collapses the image, and an explicit // height survives the clamp and smears the picture. { - var cssSizedLogo = html.sanitize( + var cssSizedLogo = sanitize( '', { allowRemoteImages: true }) var logoDoc = html.documentFor(cssSizedLogo.document, { maxImageWidth: 1200 }) assert.ok(logoDoc.indexOf('height="34"') > 0, "a CSS-only logo height becomes the HTML attribute Qt supports") - var logoRow = html.sanitize('
' + var logoRow = sanitize('
' + '
' + '

Title below

', { allowRemoteImages: true }).html assert.ok(logoRow.indexOf("line-height:0") < 0, @@ -884,7 +898,7 @@ assert.ok(bare.indexOf("x") > 0) // The document itself is accepted in place of the string written from it, and // has to fit to exactly the same thing. - var built = html.sanitize(fitted, { allowRemoteImages: true }) + var built = sanitize(fitted, { allowRemoteImages: true }) assert.strictEqual(html.documentFor(built.document, { maxImageWidth: 380, compact: true }), html.documentFor(built.html, { maxImageWidth: 380, compact: true })) assert.strictEqual(html.documentFor(built.document, { maxImageWidth: 800, compact: true }) @@ -946,7 +960,7 @@ assert.ok(bare.indexOf("x") > 0) // A void element has no subtree to eat, so it must not swallow what follows. assert.ok(html.dropHidden('

real

').indexOf("

real

") >= 0) - assert.ok(html.sanitize('
SECRET

real

').html.indexOf("SECRET") < 0, + assert.ok(sanitize('
SECRET

real

').html.indexOf("SECRET") < 0, "and the sanitizer applies it") } @@ -979,7 +993,7 @@ function attributesOf(node, out) { function reading(source, options) { const settings = Object.assign({ withReader: true }, options || {}) - const ready = html.sanitize(source, settings) + const ready = sanitize(source, settings) const kinds = {} for (const pair of attributesOf(ready.reader.document, [])) kinds[pair] = true for (const pair of Object.keys(kinds)) { @@ -1126,7 +1140,7 @@ function activityMail() { // Reading mode is lighter than the formatted view of the same message, which // is what lets it draw messages the formatted view refuses. - const formatted = html.sanitize(newsletter) + const formatted = sanitize(newsletter) assert.ok(read.complexity.tags < formatted.complexity.tags) assert.strictEqual(read.tooHeavy, false) } @@ -1316,8 +1330,8 @@ function activityMail() { + "" + "

", { allowRemoteImages: true }) assert.strictEqual(shown.html, - "

" - + "" + "

" + + "" + "" + "

") assert.strictEqual(shown.images, 2) @@ -1415,7 +1429,7 @@ function activityMail() { return out + "" } - const heavy = html.sanitize(outlookMail(240), { withReader: true }) + const heavy = sanitize(outlookMail(240), { withReader: true }) assert.strictEqual(heavy.tooHeavy, true, "the formatted view refuses this one") assert.strictEqual(heavy.reader.tooHeavy, false, "and reading mode still draws it") assert.ok(heavy.reader.complexity.tags < heavy.complexity.tags / 2) @@ -1428,7 +1442,7 @@ function activityMail() { // message that ended there. let long = "" for (let i = 0; i < 3000; i++) long += "

Paragraph number " + i + " of a long message.

" - const enormous = html.sanitize(long + "", { withReader: true }).reader + const enormous = sanitize(long + "", { withReader: true }).reader assert.strictEqual(enormous.tooHeavy, true) assert.ok(enormous.html.indexOf("number 2999") > 0, "and the whole message is in what was refused") @@ -1440,7 +1454,7 @@ function activityMail() { // is still there. let held = "".repeat(126) for (let i = 0; i < 400; i++) held += "
x
" - const stacked = html.sanitize(held, { withReader: true }).reader + const stacked = sanitize(held, { withReader: true }).reader assert.ok(stacked.complexity.tags < 400 * (html.MAX_READER_CHAIN + 2), "a held-open chain multiplied the message: " + stacked.complexity.tags) assert.ok(stacked.html.indexOf("x") > 0, "and the message is still in it") @@ -1496,22 +1510,22 @@ function activityMail() { + "" + "", { allowRemoteImages: true }).html assert.strictEqual(icons, - "

" - + "

") + "

" + + "

") // A standalone logo is not inline artwork, but its declared size still // prevents Qt from expanding the source bitmap to its natural pixel width. // It keeps the bounded dimension without becoming an avatar or icon strip. assert.strictEqual(reading("

", { allowRemoteImages: true }).html, - "

") + "

") // The reading column may clamp a large picture's width. Its explicit height // must not survive that clamp or Qt stretches the image instead of deriving // the matching height from its intrinsic aspect ratio. assert.strictEqual(reading("

", { allowRemoteImages: true }).html, - "

") + "

") // An avatar at the start of a line is interface-like identity content, not // a picture sitting on the text baseline. Qt ignores image alignment in the @@ -1522,17 +1536,17 @@ function activityMail() { assert.strictEqual(avatar, "" + "" + + "" + "" + "
" - + "Alice left a comment
") // One parse answers for all three readings, which is what makes changing mode // free: the reader is built from the tree the sanitiser is about to clean, // and reading that tree does not change it. - const both = html.sanitize(activityMail(), { withReader: true, withPlainText: true }) - assert.strictEqual(both.html, html.sanitize(activityMail()).html) + const both = sanitize(activityMail(), { withReader: true, withPlainText: true }) + assert.strictEqual(both.html, sanitize(activityMail()).html) deepEqual(both.plainText, html.readPlainText(activityMail())) - assert.strictEqual(html.sanitize(activityMail()).reader, null, + assert.strictEqual(sanitize(activityMail()).reader, null, "and nobody pays for a reading no caller asked for") } @@ -1663,23 +1677,23 @@ function activityMail() { // `direction` property, so a template written for a browser states its // direction in the one spelling that will be thrown away. { - const rtl = html.sanitize('
مرحبا
', {}) + const rtl = sanitize('
مرحبا
', {}) assert.ok(/dir="rtl"/.test(rtl.html), "a CSS direction is promoted to the attribute Qt reads") assert.ok(/direction:\s*rtl/.test(rtl.html), "and the sender's own declaration is left where it was") - const ltr = html.sanitize('
hello
', {}) + const ltr = sanitize('
hello
', {}) assert.ok(/dir="ltr"/.test(ltr.html)) // The sender's own attribute is the more specific statement of the two. - const both = html.sanitize('
x
', {}) + const both = sanitize('
x
', {}) assert.ok(/dir="ltr"/.test(both.html), "an existing attribute is not overwritten") assert.ok(!/dir="rtl"/.test(both.html)) // Only the two values mean anything. `inherit` and friends are not directions // a renderer can be handed. - const junk = html.sanitize('
x
', {}) + const junk = sanitize('
x
', {}) assert.ok(!/ dir=/.test(junk.html), "an unusable value promotes nothing") } @@ -1717,9 +1731,85 @@ function activityMail() { // A base direction is a default. A sender who states one of their own keeps // it, which is why supplying one is safe. - const sender = html.sanitize('
hello
', {}) + const sender = sanitize('
hello
', {}) assert.ok(/dir="ltr"/.test(sender.html), "the sender's own direction survives into the document it is wrapped in") } + +{ + const source = '' + for (const remoteImageData of [undefined, null, {}]) { + const ready = html.sanitize(source, { allowRemoteImages: true, remoteImageData, withReader: true }) + for (const result of [ready, ready.reader]) { + assert.ok(!/src=["']https?:/i.test(result.html), "an unprepared source must never reach Qt") + assert.strictEqual(result.images, 0) + } + } +} + +{ + const source = '' + + '' + const ready = html.sanitize(source, { maxImages: 2, allowRemoteImages: true, + remoteImageData: { 'https://cdn.example.com/ready': tinyPng }, withReader: true }) + for (const result of [ready, ready.reader]) { + assert.strictEqual(result.complexity.images, 2, "inline, CID and remote images share a document budget") + assert.strictEqual(result.blockedImages, 2) + assert.ok(!result.html.includes('https://cdn.example.com/ready')) + } + const empty = html.sanitize(source, { maxImages: 0, withReader: true }) + assert.ok(!empty.html.includes('Body

' + ''.repeat(4), + { allowRemoteImages: true, remoteImageData: { 'https://cdn.example.com/large': data }, withReader: true }) + for (const result of [ready, ready.reader]) { + assert.strictEqual(result.complexity.images, 3, "data URI bytes have a separate 16 MiB document budget") + assert.strictEqual(result.blockedImages, 1) + assert.strictEqual(result.tooHeavy, false, "embedded picture bytes are not layout markup") + assert.ok(result.html.length < 16 * 1024 * 1024) + } + const encoded = data.replace(/^data/, "data") + const embedded = html.sanitize('

Body

' + ('').repeat(4), { withReader: true }) + for (const result of [embedded, embedded.reader]) { + assert.strictEqual(result.complexity.images, 3, "encoded data schemes cannot bypass the byte budget") + assert.strictEqual(result.blockedImages, 1) + assert.strictEqual(result.tooHeavy, false) + } +} + +{ + for (const attributes of ['style="display:none"', 'style="visibility:hidden"', 'hidden']) { + const ready = html.sanitize('', + { allowRemoteImages: true, remoteImageData: { 'https://cdn.example.com/hidden': tinyPng }, withReader: true }) + deepEqual(ready.remoteImageSources, [], "hidden images must not become fetch candidates") + assert.ok(!ready.html.includes('', { withReader: true }) + assert.ok(!inlineTracker.html.includes('Visible').html, '

Visible

', + "an inherited Object member is not an allowed reader element") + assert.strictEqual(html.readPlainText('

&constructor; 😀 🙂

').text, + '&constructor; 😀 🙂', "references preserve unknown names and supplementary Unicode characters") + assert.strictEqual(reading('🙂').html, + '

🙂

') +} + +{ + const source = '
Body
' + + '' + const ready = html.sanitize(source, { keepColors: true, withReader: true }) + assert.ok(!ready.html.includes('https://cdn.example.com/'), + "malformed attribute names and non-anchor references must not reach Qt") + assert.ok(ready.html.includes('Body')) +} + console.log("test_html.js ok") From 53a0caf96ef1277a7fbac3df021164bdf09ed0ad Mon Sep 17 00:00:00 2001 From: David Reinecke <6206278+dreinecke@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:28:22 +0100 Subject: [PATCH 166/568] Name HTML parsing and rendering values explicitly --- ui/message/Html.js | 548 +++++++++++++++++++++--------------------- ui/tests/test_html.js | 286 +++++++++++----------- 2 files changed, 417 insertions(+), 417 deletions(-) diff --git a/ui/message/Html.js b/ui/message/Html.js index f7a506cd8..81737fdcf 100644 --- a/ui/message/Html.js +++ b/ui/message/Html.js @@ -388,13 +388,13 @@ function parse(html) { // turn "&" into "&amp;" on every round trip — so only the quote that // delimits them has to go. -function serializeAttributes(attrs) { +function serializeAttributes(attributes) { var out = "" - for (var i = 0; i < attrs.length; i++) { - var attr = attrs[i] - out += " " + attr.name - if (attr.value === null || attr.value === undefined) continue - out += "=\"" + String(attr.value).replace(/"/g, """) + "\"" + for (var attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { + var attribute = attributes[attributeIndex] + out += " " + attribute.name + if (attribute.value === null || attribute.value === undefined) continue + out += "=\"" + String(attribute.value).replace(/"/g, """) + "\"" } return out } @@ -436,7 +436,7 @@ function serializeInto(node, out, fit) { } out.push(">") } - for (var i = 0; i < node.children.length; i++) serializeInto(node.children[i], out, fit) + for (var childIndex = 0; childIndex < node.children.length; childIndex++) serializeInto(node.children[childIndex], out, fit) if (node.type !== "root") out.push("") } @@ -453,8 +453,8 @@ function serialize(node, fit) { // children and drops the element around them. function transform(node, visit) { var kept = [] - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") { kept.push(child) continue @@ -463,7 +463,7 @@ function transform(node, visit) { if (verdict === null) continue transform(child, visit) if (verdict === "unwrap") { - for (var j = 0; j < child.children.length; j++) kept.push(child.children[j]) + for (var grandchildIndex = 0; grandchildIndex < child.children.length; grandchildIndex++) kept.push(child.children[grandchildIndex]) continue } kept.push(child) @@ -473,39 +473,39 @@ function transform(node, visit) { } function attributeOf(node, name) { - for (var i = 0; i < node.attrs.length; i++) { - if (node.attrs[i].name === name) return node.attrs[i] + for (var attributeIndex = 0; attributeIndex < node.attrs.length; attributeIndex++) { + if (node.attrs[attributeIndex].name === name) return node.attrs[attributeIndex] } return null } function attributeValue(node, name) { - var attr = attributeOf(node, name) - return attr && attr.value !== null && attr.value !== undefined ? String(attr.value) : "" + var attribute = attributeOf(node, name) + return attribute && attribute.value !== null && attribute.value !== undefined ? String(attribute.value) : "" } function removeAttribute(node, name) { var kept = [] - for (var i = 0; i < node.attrs.length; i++) { - if (node.attrs[i].name !== name) kept.push(node.attrs[i]) + for (var attributeIndex = 0; attributeIndex < node.attrs.length; attributeIndex++) { + if (node.attrs[attributeIndex].name !== name) kept.push(node.attrs[attributeIndex]) } node.attrs = kept } function setAttribute(node, name, value) { - var attr = attributeOf(node, name) - if (attr) attr.value = String(value) + var attribute = attributeOf(node, name) + if (attribute) attribute.value = String(value) else node.attrs.push({ name: name, value: String(value) }) } function setStyle(node, declarations) { - var attr = attributeOf(node, "style") + var attribute = attributeOf(node, "style") var style = joinDeclarations(declarations) if (style === "") { - if (attr) removeAttribute(node, "style") + if (attribute) removeAttribute(node, "style") return } - if (attr) attr.value = style + if (attribute) attribute.value = style else node.attrs.push({ name: "style", value: style }) } @@ -570,8 +570,8 @@ function hostsOf(value) { function isPublicUrl(value) { var hosts = hostsOf(value) - for (var i = 0; i < hosts.length; i++) { - if (!isPublicHost(hosts[i])) return false + for (var hostIndex = 0; hostIndex < hosts.length; hostIndex++) { + if (!isPublicHost(hosts[hostIndex])) return false } return true } @@ -612,24 +612,24 @@ function isPublicIpv4(host) { var parts = String(host).match(DOTTED_QUAD) if (!parts) return false var octets = [] - for (var i = 1; i <= 4; i++) { + for (var octetIndex = 1; octetIndex <= 4; octetIndex++) { // A leading zero reads as octal to some resolvers and as decimal to // others, so "0177.0.0.1" is 127.0.0.1 to one of them. Neither reading is // worth the risk of picking the wrong one. - if (parts[i].length > 1 && parts[i].charAt(0) === "0") return false - var value = Number(parts[i]) + if (parts[octetIndex].length > 1 && parts[octetIndex].charAt(0) === "0") return false + var value = Number(parts[octetIndex]) if (value > 255) return false octets.push(value) } - var a = octets[0] - var b = octets[1] - if (a === 0 || a === 10 || a === 127) return false - if (a === 169 && b === 254) return false - if (a === 172 && b >= 16 && b <= 31) return false - if (a === 192 && (b === 168 || b === 0)) return false - if (a === 198 && (b === 18 || b === 19)) return false - if (a === 100 && b >= 64 && b <= 127) return false - if (a >= 224) return false + var firstOctet = octets[0] + var secondOctet = octets[1] + if (firstOctet === 0 || firstOctet === 10 || firstOctet === 127) return false + if (firstOctet === 169 && secondOctet === 254) return false + if (firstOctet === 172 && secondOctet >= 16 && secondOctet <= 31) return false + if (firstOctet === 192 && (secondOctet === 168 || secondOctet === 0)) return false + if (firstOctet === 198 && (secondOctet === 18 || secondOctet === 19)) return false + if (firstOctet === 100 && secondOctet >= 64 && secondOctet <= 127) return false + if (firstOctet >= 224) return false return true } @@ -696,25 +696,25 @@ function base64Prefix(payload, byteLimit) { if (padding === 1 && BASE64_ALPHABET.indexOf(text.charAt(text.length - 2)) % 4 !== 0) return [] var out = [] - for (var i = 0; i < text.length && out.length < byteLimit; i += 4) { - var a = BASE64_ALPHABET.indexOf(text.charAt(i)) - var b = BASE64_ALPHABET.indexOf(text.charAt(i + 1)) - var c = text.charAt(i + 2) === "=" ? 0 : BASE64_ALPHABET.indexOf(text.charAt(i + 2)) - var d = text.charAt(i + 3) === "=" ? 0 : BASE64_ALPHABET.indexOf(text.charAt(i + 3)) - if (a < 0 || b < 0 || c < 0 || d < 0) return [] - out.push((a << 2) | (b >> 4)) - if (text.charAt(i + 2) !== "=" && out.length < byteLimit) - out.push(((b & 15) << 4) | (c >> 2)) - if (text.charAt(i + 3) !== "=" && out.length < byteLimit) - out.push(((c & 3) << 6) | d) + for (var offset = 0; offset < text.length && out.length < byteLimit; offset += 4) { + var firstDigit = BASE64_ALPHABET.indexOf(text.charAt(offset)) + var secondDigit = BASE64_ALPHABET.indexOf(text.charAt(offset + 1)) + var thirdDigit = text.charAt(offset + 2) === "=" ? 0 : BASE64_ALPHABET.indexOf(text.charAt(offset + 2)) + var fourthDigit = text.charAt(offset + 3) === "=" ? 0 : BASE64_ALPHABET.indexOf(text.charAt(offset + 3)) + if (firstDigit < 0 || secondDigit < 0 || thirdDigit < 0 || fourthDigit < 0) return [] + out.push((firstDigit << 2) | (secondDigit >> 4)) + if (text.charAt(offset + 2) !== "=" && out.length < byteLimit) + out.push(((secondDigit & 15) << 4) | (thirdDigit >> 2)) + if (text.charAt(offset + 3) !== "=" && out.length < byteLimit) + out.push(((thirdDigit & 3) << 6) | fourthDigit) } return out } function bytesStartWith(bytes, expected) { if (bytes.length < expected.length) return false - for (var i = 0; i < expected.length; i++) { - if (bytes[i] !== expected[i]) return false + for (var byteIndex = 0; byteIndex < expected.length; byteIndex++) { + if (bytes[byteIndex] !== expected[byteIndex]) return false } return true } @@ -776,16 +776,16 @@ function safeHref(value) { function stripCssComments(text) { var input = String(text || "") var out = "" - var i = 0 - while (i < input.length) { - if (input.charAt(i) === "/" && input.charAt(i + 1) === "*") { - var end = input.indexOf("*/", i + 2) + var position = 0 + while (position < input.length) { + if (input.charAt(position) === "/" && input.charAt(position + 1) === "*") { + var end = input.indexOf("*/", position + 2) if (end < 0) break - i = end + 2 + position = end + 2 continue } - out += input.charAt(i) - i++ + out += input.charAt(position) + position++ } return out } @@ -793,26 +793,26 @@ function stripCssComments(text) { function cssUnescape(text) { var input = String(text || "") var out = "" - for (var i = 0; i < input.length; i++) { - if (input.charAt(i) !== "\\") { - out += input.charAt(i) + for (var position = 0; position < input.length; position++) { + if (input.charAt(position) !== "\\") { + out += input.charAt(position) continue } - if (i + 1 >= input.length) break + if (position + 1 >= input.length) break var hex = "" - var j = i + 1 - while (j < input.length && hex.length < 6 && /[0-9a-fA-F]/.test(input.charAt(j))) { - hex += input.charAt(j) - j++ + var escapeEnd = position + 1 + while (escapeEnd < input.length && hex.length < 6 && /[0-9a-fA-F]/.test(input.charAt(escapeEnd))) { + hex += input.charAt(escapeEnd) + escapeEnd++ } if (hex !== "") { out += String.fromCharCode(parseInt(hex, 16)) - if (/[\t\n\r\f ]/.test(input.charAt(j))) j++ - i = j - 1 + if (/[\t\n\r\f ]/.test(input.charAt(escapeEnd))) escapeEnd++ + position = escapeEnd - 1 continue } - out += input.charAt(i + 1) - i++ + out += input.charAt(position + 1) + position++ } return out } @@ -820,11 +820,11 @@ function cssUnescape(text) { function resolvedStyle(style) { var current = String(style === undefined || style === null ? "" : style) var previous = "" - var n = 0 - while (current !== previous && n < 8) { + var iteration = 0 + while (current !== previous && iteration < 8) { previous = current current = cssUnescape(stripCssComments(current)) - n++ + iteration++ } return current } @@ -837,8 +837,8 @@ function splitDeclarations(style) { var current = "" var quote = "" var depth = 0 - for (var i = 0; i < text.length; i++) { - var character = text.charAt(i) + for (var characterIndex = 0; characterIndex < text.length; characterIndex++) { + var character = text.charAt(characterIndex) if (quote !== "") { current += character if (character === quote) quote = "" @@ -861,8 +861,8 @@ function splitDeclarations(style) { out.push(current) var declarations = [] - for (var j = 0; j < out.length; j++) { - var piece = out[j] + for (var declarationIndex = 0; declarationIndex < out.length; declarationIndex++) { + var piece = out[declarationIndex] if (piece.replace(/\s+/g, "") === "") continue var colon = piece.indexOf(":") if (colon < 0) continue @@ -890,9 +890,9 @@ function sourceDeclarations(node) { function joinDeclarations(declarations) { var parts = [] - for (var i = 0; i < declarations.length; i++) { - if (declarations[i].value === "") continue - parts.push(declarations[i].name + ":" + declarations[i].value) + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].value === "") continue + parts.push(declarations[declarationIndex].name + ":" + declarations[declarationIndex].value) } return parts.join(";") } @@ -900,12 +900,12 @@ function joinDeclarations(declarations) { // Rewrites an element's style attribute through `decide`, which is handed each // declaration and returns it, a replacement, or null to drop it. function rewriteStyle(node, decide) { - var attr = attributeOf(node, "style") - if (!attr || attr.value === null || attr.value === undefined) return - var declarations = splitDeclarations(attr.value) + var attribute = attributeOf(node, "style") + if (!attribute || attribute.value === null || attribute.value === undefined) return + var declarations = splitDeclarations(attribute.value) var kept = [] - for (var i = 0; i < declarations.length; i++) { - var verdict = decide(declarations[i]) + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var verdict = decide(declarations[declarationIndex]) if (verdict) kept.push(verdict) } setStyle(node, kept) @@ -983,8 +983,8 @@ function stripStyleUrlsFrom(node) { // two-pixel smudge of unreadable characters above the message. Elements the // sender marked hidden are therefore removed rather than styled away. function isHiddenBy(declarations) { - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i] + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var declaration = declarations[declarationIndex] if (declaration.name === "display" && /^none\b/i.test(declaration.value)) return true if (declaration.name === "visibility" && /^hidden\b/i.test(declaration.value)) return true } @@ -1006,9 +1006,9 @@ function isTrackingPixel(node) { if (isFinite(width) && attributeValue(node, "width") !== "" && width <= 2) return true if (isFinite(height) && attributeValue(node, "height") !== "" && height <= 2) return true var declarations = sourceDeclarations(node) || [] - for (var i = 0; i < declarations.length; i++) { - if (declarations[i].name !== "width" && declarations[i].name !== "height") continue - if (/^[012](\.\d+)?px/i.test(declarations[i].value)) return true + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].name !== "width" && declarations[declarationIndex].name !== "height") continue + if (/^[012](\.\d+)?px/i.test(declarations[declarationIndex].value)) return true } return false } @@ -1035,8 +1035,8 @@ var TABLE_PARTS = { // is a logo beside a nav, one cell is a box, and neither loses anything by // becoming what it already was. function rowsOf(node, out) { - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue // A nested table's rows are its own. They answer this question for it. if (child.name === "table") continue @@ -1049,10 +1049,10 @@ function rowsOf(node, out) { function isGrid(node) { var rows = rowsOf(node, []) var lines = 0 - for (var i = 0; i < rows.length; i++) { + for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = 0 - for (var j = 0; j < rows[i].children.length; j++) { - var cell = rows[i].children[j] + for (var childIndex = 0; childIndex < rows[rowIndex].children.length; childIndex++) { + var cell = rows[rowIndex].children[childIndex] if (cell.type === "text") continue if (cell.name === "td" || cell.name === "th") cells++ } @@ -1072,8 +1072,8 @@ function asBlock(node) { // The parts belonging to this table, which stops at a nested one: that table // has been asked its own question already, and those rows and cells are its. function flattenPartsOf(node) { - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text" || child.name === "table") continue flattenPartsOf(child) if (TABLE_PARTS[child.name] === true) asBlock(child) @@ -1085,8 +1085,8 @@ function flattenPartsOf(node) { // budget meant for competing column widths is what put the budget on the // wrong two levels in the first place. function flattenTablesIn(node, limit, depth) { - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue if (child.name !== "table") { flattenTablesIn(child, limit, depth) @@ -1132,13 +1132,13 @@ var ALIGNED_BY_COLUMN = { td: true, th: true } function cleanAttributes(node, keepColors, declarations) { var uncentre = ALIGNED_BY_COLUMN[node.name] !== true - var attrs = node.attrs - var kept = attrs + var attributes = node.attrs + var kept = attributes var dropped = false - for (var i = 0; i < attrs.length; i++) { - var attr = attrs[i] - var name = attr.name + for (var attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { + var attribute = attributes[attributeIndex] + var name = attribute.name var drop = false // Unconditionally, and before the colour question is asked: `keepColors` // is an appearance setting, and no appearance setting may hand the @@ -1155,14 +1155,14 @@ function cleanAttributes(node, keepColors, declarations) { // Event handlers, which Qt ignores but which have no business surviving a // trip through a mail client. else if (name.charCodeAt(0) === 111 && HANDLER_ATTRIBUTE.test(name)) drop = true - else if (name === "href" && !safeHref(attr.value)) drop = true - else if (uncentre && name === "align" && CENTRED.test(String(attr.value))) drop = true + else if (name === "href" && !safeHref(attribute.value)) drop = true + else if (uncentre && name === "align" && CENTRED.test(String(attribute.value))) drop = true if (drop && !dropped) { dropped = true - kept = attrs.slice(0, i) + kept = attributes.slice(0, attributeIndex) } else if (!drop && dropped) { - kept.push(attr) + kept.push(attribute) } } if (dropped) node.attrs = kept @@ -1170,8 +1170,8 @@ function cleanAttributes(node, keepColors, declarations) { if (declarations === null) return var survivors = [] - for (var j = 0; j < declarations.length; j++) { - var declaration = declarations[j] + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var declaration = declarations[declarationIndex] if (!keepColors && COLOUR_DECLARATIONS[declaration.name] === true) continue if (uncentre && declaration.name === "text-align" && CENTRED.test(declaration.value)) continue // No test for a reference here: `splitDeclarations` has already taken them @@ -1185,12 +1185,12 @@ function cleanAttributes(node, keepColors, declarations) { function collapseAttributes(node) { var seen = {} var kept = [] - var attrs = node.attrs - for (var i = 0; i < attrs.length; i++) { - var name = attrs[i].name + var attributes = node.attrs + for (var attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { + var name = attributes[attributeIndex].name if (seen[name] === true) continue seen[name] = true - kept.push(attrs[i]) + kept.push(attributes[attributeIndex]) } node.attrs = kept } @@ -1201,8 +1201,8 @@ function collapseAttributes(node) { // Qt understands while leaving the original declaration for other consumers. function promoteImageDimensions(node, declarations) { if (node.name !== "img" || declarations === null) return - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i] + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var declaration = declarations[declarationIndex] if (declaration.name !== "width" && declaration.name !== "height") continue if (attributeOf(node, declaration.name) !== null) continue var pixels = String(declaration.value).match(/^(\d+(?:\.\d+)?)px$/i) @@ -1230,9 +1230,9 @@ function promoteDirection(node, declarations) { // The sender's own attribute wins. It is the more specific statement of the // two, and it is the one they wrote for a client that reads it. if (attributeOf(node, "dir") !== null) return - for (var i = 0; i < declarations.length; i++) { - if (declarations[i].name !== "direction") continue - var value = String(declarations[i].value).trim().toLowerCase() + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].name !== "direction") continue + var value = String(declarations[declarationIndex].value).trim().toLowerCase() if (DIRECTION_VALUES[value] !== true) continue setAttribute(node, "dir", value) return @@ -1240,8 +1240,8 @@ function promoteDirection(node, declarations) { } function hasDirectImage(node) { - for (var i = 0; i < node.children.length; i++) { - if (node.children[i].type !== "text" && node.children[i].name === "img") return true + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + if (node.children[childIndex].type !== "text" && node.children[childIndex].name === "img") return true } return false } @@ -1286,8 +1286,8 @@ var PLAIN_CONTAINER = { // Whitespace between blocks is not content and does not count against it. function soleBlockChild(node) { var found = null - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") { if (child.text.replace(/[\s\u00a0]+/g, "") !== "") return null continue @@ -1302,8 +1302,8 @@ function soleBlockChild(node) { // Bottom up, so a stack of seven collapses to one rather than to six. function collapse(node) { var kept = [] - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") { kept.push(child) continue @@ -1311,7 +1311,7 @@ function collapse(node) { collapse(child) if (child.attrs.length === 0) { if (TRANSPARENT_INLINE[child.name] === true) { - for (var j = 0; j < child.children.length; j++) kept.push(child.children[j]) + for (var grandchildIndex = 0; grandchildIndex < child.children.length; grandchildIndex++) kept.push(child.children[grandchildIndex]) continue } if (PLAIN_CONTAINER[child.name] === true) { @@ -1414,8 +1414,8 @@ function sanitize(html, options) { function clean(node) { var survivors = [] - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") { survivors.push(child) continue @@ -1562,8 +1562,8 @@ function stripElement(html, name) { function measure(node, depth, size) { var deepest = depth - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue size.tags++ if (child.name === "img") size.images++ @@ -1683,46 +1683,46 @@ var FITTABLE_DECLARATION = /width|nowrap/i // is the reader fitting a message to the window it happens to be, and the same // message is fitted again at the next width. function fitAttributes(node, fit) { - var attrs = node.attrs - if (attrs.length === 0) return attrs + var attributes = node.attrs + if (attributes.length === 0) return attributes var isImage = fit.heights && node.name === "img" var isSized = fit.widths && SIZED_ELEMENTS[node.name] === true var imageWidth = Number(attributeValue(node, "width")) var dropImageHeight = isImage && (!fit.clampedHeightsOnly || (isFinite(imageWidth) && imageWidth > fit.limit)) if (!isImage && !isSized && !fit.sides) { - if (!fit.widths) return attrs + if (!fit.widths) return attributes // Anything can carry white-space:nowrap, so the fast path out of here has // to ask every element about it — and asks with a substring test, because // splitting the declarations of a document that has none is the whole cost // of a relayout for nothing. var carried = attributeOf(node, "style") - if (carried === null || String(carried.value).indexOf("nowrap") < 0) return attrs + if (carried === null || String(carried.value).indexOf("nowrap") < 0) return attributes } var out = null - for (var i = 0; i < attrs.length; i++) { - var attr = attrs[i] - var replacement = attr + for (var attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { + var attribute = attributes[attributeIndex] + var replacement = attribute // An explicit height survives the max-width clamp, so a banner scaled from // 1600 to 380 keeps its original height and renders as a smear. Measured // against the engine rather than assumed: strip the heights and Qt derives // the height from the aspect ratio on its own. - if (dropImageHeight && attr.name === "height") replacement = null - else if (isSized && attr.name === "width" - && intrinsicContentWidth(node, attr.value)) replacement = null - else if (isSized && attr.name === "width" && /^\d+$/.test(String(attr.value)) - && Number(attr.value) > fit.limit) replacement = null - else if (attr.name === "style" && attr.value !== null && attr.value !== undefined - && (fit.sides || FITTABLE_DECLARATION.test(String(attr.value)) + if (dropImageHeight && attribute.name === "height") replacement = null + else if (isSized && attribute.name === "width" + && intrinsicContentWidth(node, attribute.value)) replacement = null + else if (isSized && attribute.name === "width" && /^\d+$/.test(String(attribute.value)) + && Number(attribute.value) > fit.limit) replacement = null + else if (attribute.name === "style" && attribute.value !== null && attribute.value !== undefined + && (fit.sides || FITTABLE_DECLARATION.test(String(attribute.value)) || dropImageHeight)) { - var declarations = splitDeclarations(attr.value) + var declarations = splitDeclarations(attribute.value) var kept = [] var changed = false - for (var j = 0; j < declarations.length; j++) { - var fitted = fitDeclaration(declarations[j], node, fit, dropImageHeight) - if (fitted !== declarations[j]) changed = true + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var fitted = fitDeclaration(declarations[declarationIndex], node, fit, dropImageHeight) + if (fitted !== declarations[declarationIndex]) changed = true if (fitted) kept.push(fitted) } if (changed) { @@ -1731,14 +1731,14 @@ function fitAttributes(node, fit) { } } - if (replacement === attr) { - if (out !== null) out.push(attr) + if (replacement === attribute) { + if (out !== null) out.push(attribute) continue } - if (out === null) out = attrs.slice(0, i) + if (out === null) out = attributes.slice(0, attributeIndex) if (replacement !== null) out.push(replacement) } - return out === null ? attrs : out + return out === null ? attributes : out } // The reader rebuilds its document whenever the window width or the zoom @@ -1764,16 +1764,16 @@ function fixedPixelWidth(value) { function widestDeclaredContent(node, current) { var widest = current - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue if (CONTENT_WIDTH_ELEMENTS[child.name] === true) { var width = fixedPixelWidth(attributeValue(child, "width")) var declarations = splitDeclarations(attributeValue(child, "style")) - for (var j = 0; j < declarations.length; j++) { - if (declarations[j].name !== "max-width" - && declarations[j].name !== "width") continue - width = Math.max(width, fixedPixelWidth(declarations[j].value)) + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].name !== "max-width" + && declarations[declarationIndex].name !== "width") continue + width = Math.max(width, fixedPixelWidth(declarations[declarationIndex].value)) } // Tiny fixed boxes are icons, bullets, and badges, not the message card. if (width >= 240) widest = Math.max(widest, width) @@ -1833,8 +1833,8 @@ function documentFor(bodyHtml, colors) { var quote = String(palette.quote || foreground) // Margin on body is ignored by Qt's rich text engine, so the padding lives // on a wrapper the sender's markup sits inside. - var pad = Math.max(0, Math.floor(Number(palette.padding) || 0)) - var maxImage = Math.floor(Number(palette.maxImageWidth) || 0) + var paddingPixels = Math.max(0, Math.floor(Number(palette.padding) || 0)) + var maxImageWidthPixels = Math.floor(Number(palette.maxImageWidth) || 0) // Which way the message runs — see `baseDirectionAttribute` below. var direction = String(palette.direction || "") var quoteEdge = Direction.startEdge(direction) @@ -1847,7 +1847,7 @@ function documentFor(bodyHtml, colors) { // cannot hold goes at every width: there is no horizontal scroll here, so // what overflows is not read at all. var fit = fitting(true, palette.compact === true, - maxImage >= MIN_IMAGE_WIDTH, maxImage, true) + maxImageWidthPixels >= MIN_IMAGE_WIDTH, maxImageWidthPixels, true) return "" - + (pad > 0 ? "
" : "") + + (paddingPixels > 0 ? "
" : "") + serialize(root, fit) - + (pad > 0 ? "
" : "") + + (paddingPixels > 0 ? "
" : "") + "" } @@ -2041,8 +2041,8 @@ function readerAppendBreak(state) { // block the reader does not draw, which is most of what a layout table is made // of. function readerMeaningful(nodes) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i] + for (var nodeIndex = 0; nodeIndex < nodes.length; nodeIndex++) { + var node = nodes[nodeIndex] if (node.type === "text") { if (decodeReferences(node.text).replace(/[\s\u00a0]+/g, "") !== "") return true continue @@ -2071,8 +2071,8 @@ function readerTrimmed(nodes) { // asked of anything about to become a heading. function readerLength(nodes) { var total = 0 - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i] + for (var nodeIndex = 0; nodeIndex < nodes.length; nodeIndex++) { + var node = nodes[nodeIndex] if (node.type === "text") total += decodeReferences(node.text).length // A picture is a word or two of the line it sits on, which is all this has // to be right about: the question is only whether a run is short. @@ -2091,11 +2091,11 @@ function readerFlush(state, name) { state.filled = false var reopened = [] - for (var i = 0; i < state.chain.length; i++) { - var fresh = readerElement(state.chain[i].name) + for (var chainIndex = 0; chainIndex < state.chain.length; chainIndex++) { + var fresh = readerElement(state.chain[chainIndex].name) // Shared rather than copied: nothing mutates a reader element's attributes // once it is built, and a link wrapped around forty boxes is forty of these. - fresh.attrs = state.chain[i].attrs + fresh.attrs = state.chain[chainIndex].attrs if (reopened.length > 0) reopened[reopened.length - 1].children.push(fresh) else state.inline.push(fresh) reopened.push(fresh) @@ -2122,8 +2122,8 @@ function readerHiddenBy(declarations, leaf) { if (isHiddenBy(declarations)) return true var clipped = false var hidden = false - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i] + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + var declaration = declarations[declarationIndex] var name = declaration.name // Only where the text is. A container full of boxes writes "font-size:0" to // take out the space between them and every box inside sets a size of its @@ -2147,8 +2147,8 @@ function readerHidden(node) { var style = attributeValue(node, "style") if (style === "") return false var leaf = true - for (var i = 0; i < node.children.length; i++) { - if (node.children[i].type !== "text") { leaf = false; break } + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + if (node.children[childIndex].type !== "text") { leaf = false; break } } return readerHiddenBy(sourceDeclarations(node) || [], leaf) } @@ -2175,9 +2175,9 @@ function readerHref(node) { // than passed through: an attribute value is not markup, and alt="a 0)) { var declarations = sourceDeclarations(node) || [] - for (var i = 0; i < declarations.length; i++) { - if (declarations[i].name !== name) continue - var match = String(declarations[i].value).match(/^\s*(\d+(?:\.\d+)?)px\s*$/i) + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].name !== name) continue + var match = String(declarations[declarationIndex].value).match(/^\s*(\d+(?:\.\d+)?)px\s*$/i) if (match) value = Number(match[1]) } } @@ -2203,18 +2203,18 @@ function readerImageDimension(node, name) { return Math.max(3, Math.round(value)) } -function readerAppendImage(state, node, ctx) { +function readerAppendImage(state, node, reading) { // A beacon is not a picture, and a reader that left a placeholder where one // had been would be announcing the tracker rather than removing it. if (isTrackingPixel(node)) return - var attr = attributeOf(node, "src") - var source = attr && attr.value !== null && attr.value !== undefined ? String(attr.value) : "" - var kind = attr === null ? "none" : imageSourceKind(source) - - var renderedSource = kind === "remote" ? preparedImage(ctx, source) : source - var eligible = kind === "inline" || (kind === "remote" && ctx.allowImages && renderedSource !== "") - if (eligible && admitImage(ctx, renderedSource)) { - if (kind === "remote") ctx.kept++ + var attribute = attributeOf(node, "src") + var source = attribute && attribute.value !== null && attribute.value !== undefined ? String(attribute.value) : "" + var kind = attribute === null ? "none" : imageSourceKind(source) + + var renderedSource = kind === "remote" ? preparedImage(reading, source) : source + var eligible = kind === "inline" || (kind === "remote" && reading.allowImages && renderedSource !== "") + if (eligible && admitImage(reading, renderedSource)) { + if (kind === "remote") reading.kept++ readerSpace(state) var image = readerElement("img") image.attrs = [{ name: "src", value: renderedSource }] @@ -2233,7 +2233,7 @@ function readerAppendImage(state, node, ctx) { state.pending = false return } - if (!eligible && kind === "remote") ctx.blocked++ + if (!eligible && kind === "remote") reading.blocked++ var alt = readerAltText(node) if (alt !== "") { @@ -2243,7 +2243,7 @@ function readerAppendImage(state, node, ctx) { // An alt the sender wrote and left empty is the sender saying this one is // decoration. One they never wrote at all is a picture with something in it, // and a reader that drew nothing there would leave unexplained blank space. - if (kind === "remote" && attr !== null && attributeOf(node, "alt") === null) + if (kind === "remote" && attribute !== null && attributeOf(node, "alt") === null) readerAppendText(state, "[image]") } @@ -2287,9 +2287,9 @@ function readerHeadingOf(node) { if (style.toLowerCase().indexOf("font-size") < 0) return "" var declarations = sourceDeclarations(node) || [] var level = "" - for (var i = 0; i < declarations.length; i++) { - if (declarations[i].name !== "font-size") continue - level = readerHeadingLevel(declarations[i].value) + for (var declarationIndex = 0; declarationIndex < declarations.length; declarationIndex++) { + if (declarations[declarationIndex].name !== "font-size") continue + level = readerHeadingLevel(declarations[declarationIndex].value) } return level } @@ -2298,24 +2298,24 @@ function readerHeadingOf(node) { //

holding two paragraphs is still the sender saying heading, so those are // joined into one; a box holding two paragraphs is a card whatever type the // sender set on it, and inferring a heading from that would swallow the card. -function readerHeading(node, state, ctx, tag, single) { +function readerHeading(node, state, reading, tag, single) { readerFlush(state, "p") - var blocks = readerBuild(node, ctx) + var blocks = readerBuild(node, reading) var content = single === true && blocks.length > 1 ? null : [] - for (var i = 0; i < blocks.length && content !== null; i++) { - if (blocks[i].name !== "p") { + for (var blockIndex = 0; blockIndex < blocks.length && content !== null; blockIndex++) { + if (blocks[blockIndex].name !== "p") { content = null break } if (content.length > 0) content.push(readerText(" ")) - for (var j = 0; j < blocks[i].children.length; j++) content.push(blocks[i].children[j]) + for (var childIndex = 0; childIndex < blocks[blockIndex].children.length; childIndex++) content.push(blocks[blockIndex].children[childIndex]) } // A sender who wrapped a whole card in an

, or set a font size on the box // around one, did not write a heading. What is inside it is what the message // says, so it comes through as itself. if (content === null || content.length === 0 || readerLength(content) > MAX_HEADING_CHARS) { - for (var k = 0; k < blocks.length; k++) state.blocks.push(blocks[k]) + for (var remainingIndex = 0; remainingIndex < blocks.length; remainingIndex++) state.blocks.push(blocks[remainingIndex]) return } var heading = readerElement(tag) @@ -2342,8 +2342,8 @@ function readerHeading(node, state, ctx, tag, single) { var READER_SEPARATOR = /^[\s\u00a0]*[|\u00b7\u2022\u2013\u2014\/-]?[\s\u00a0]*$/ function readerFurniture(node) { - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue // A picture is content whatever it weighs in characters. if (child.name === "img") return false @@ -2354,24 +2354,24 @@ function readerFurniture(node) { function readerTextOf(node) { var text = "" - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] text += child.type === "text" ? child.text : readerTextOf(child) } return text } -function readerDataTable(node, ctx) { +function readerDataTable(node, reading) { var rows = rowsOf(node, []) if (rows.length === 0 || rows.length > MAX_READER_TABLE_ROWS) return null // The whole shape is settled before a single cell is built, so refusing the // table costs no walk that the blocks it becomes instead would have to repeat. var grid = [] - for (var i = 0; i < rows.length; i++) { + for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = [] - for (var j = 0; j < rows[i].children.length; j++) { - var cell = rows[i].children[j] + for (var childIndex = 0; childIndex < rows[rowIndex].children.length; childIndex++) { + var cell = rows[rowIndex].children[childIndex] if (cell.type === "text") continue if (cell.name === "td" || cell.name === "th") cells.push(cell) } @@ -2381,20 +2381,20 @@ function readerDataTable(node, ctx) { if (grid.length === 0) return null var columns = 0 - for (var g = 0; g < grid.length; g++) { - if (grid[g].length > columns) columns = grid[g].length + for (var gridIndex = 0; gridIndex < grid.length; gridIndex++) { + if (grid[gridIndex].length > columns) columns = grid[gridIndex].length } for (var column = columns - 1; column >= 0; column--) { var furniture = true - for (var r = 0; r < grid.length && furniture; r++) { - if (column >= grid[r].length || !readerFurniture(grid[r][column])) furniture = false + for (var candidateRow = 0; candidateRow < grid.length && furniture; candidateRow++) { + if (column >= grid[candidateRow].length || !readerFurniture(grid[candidateRow][column])) furniture = false } if (!furniture) continue - for (var w = 0; w < grid.length; w++) grid[w].splice(column, 1) + for (var trimmedRow = 0; trimmedRow < grid.length; trimmedRow++) grid[trimmedRow].splice(column, 1) } var widest = 0 - for (var h = 0; h < grid.length; h++) { - if (grid[h].length > widest) widest = grid[h].length + for (var widthIndex = 0; widthIndex < grid.length; widthIndex++) { + if (grid[widthIndex].length > widest) widest = grid[widthIndex].length } // What is left of a grid once the furniture is out may not be one. if (widest < 2) return null @@ -2402,17 +2402,17 @@ function readerDataTable(node, ctx) { var table = readerElement("table") // Nested grids inside a kept one are the scaffolding again. One level of // table is all the reader draws. - ctx.tables = false + reading.tables = false for (var row = 0; row < grid.length; row++) { var line = readerElement("tr") - for (var k = 0; k < grid[row].length; k++) { - var out = readerElement(grid[row][k].name === "th" ? "th" : "td") - out.children = readerInlineOrBlocks(readerBuild(grid[row][k], ctx)) + for (var columnIndex = 0; columnIndex < grid[row].length; columnIndex++) { + var out = readerElement(grid[row][columnIndex].name === "th" ? "th" : "td") + out.children = readerInlineOrBlocks(readerBuild(grid[row][columnIndex], reading)) line.children.push(out) } table.children.push(line) } - ctx.tables = true + reading.tables = true return table } @@ -2437,8 +2437,8 @@ var MAX_ROW_CHARS = 160 // three cells reading "label / value" came out as "Kundennummer", then // "1210617221 Rechnung Nr.", then "M26056185488 Rechnungsdatum". function readerBroken(children) { - for (var i = 0; i < children.length; i++) { - var child = children[i] + for (var childIndex = 0; childIndex < children.length; childIndex++) { + var child = children[childIndex] if (child.type === "text") continue if (child.name === "br") return true if (readerBroken(child.children)) return true @@ -2446,11 +2446,11 @@ function readerBroken(children) { return false } -function readerRow(node, state, ctx) { +function readerRow(node, state, reading) { // Everything that can refuse a row is asked before anything is built. var cells = [] - for (var i = 0; i < node.children.length; i++) { - var cell = node.children[i] + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var cell = node.children[childIndex] if (cell.type === "text") continue if (cell.name !== "td" && cell.name !== "th") return false // A cell the sender set heading type on is a heading, and joining the row @@ -2463,18 +2463,18 @@ function readerRow(node, state, ctx) { } var built = [] - for (var j = 0; j < cells.length; j++) built.push(readerBuild(cells[j], ctx)) + for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) built.push(readerBuild(cells[cellIndex], reading)) var line = [] - for (var k = 0; k < built.length && line !== null; k++) { - var blocks = built[k] + for (var lineIndex = 0; lineIndex < built.length && line !== null; lineIndex++) { + var blocks = built[lineIndex] if (blocks.length === 0) continue if (blocks.length > 1 || blocks[0].name !== "p" || readerBroken(blocks[0].children)) { line = null break } if (line.length > 0) line.push(readerText(" ")) - for (var m = 0; m < blocks[0].children.length; m++) line.push(blocks[0].children[m]) + for (var wordIndex = 0; wordIndex < blocks[0].children.length; wordIndex++) line.push(blocks[0].children[wordIndex]) } readerFlush(state, "p") @@ -2486,8 +2486,8 @@ function readerRow(node, state, ctx) { } return true } - for (var n = 0; n < built.length; n++) { - for (var b = 0; b < built[n].length; b++) state.blocks.push(built[n][b]) + for (var cellIndex = 0; cellIndex < built.length; cellIndex++) { + for (var blockIndex = 0; blockIndex < built[cellIndex].length; blockIndex++) state.blocks.push(built[cellIndex][blockIndex]) } return true } @@ -2499,17 +2499,17 @@ function readerInlineOrBlocks(blocks) { return blocks } -function readerListItems(node, list, ctx) { - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i] +function readerListItems(node, list, reading) { + for (var childIndex = 0; childIndex < node.children.length; childIndex++) { + var child = node.children[childIndex] if (child.type === "text") continue if (READER_DROPPED[child.name] === true) continue if (child.name !== "li") { - readerListItems(child, list, ctx) + readerListItems(child, list, reading) continue } var item = readerElement("li") - item.children = readerInlineOrBlocks(readerBuild(child, ctx)) + item.children = readerInlineOrBlocks(readerBuild(child, reading)) if (item.children.length === 0) continue list.children.push(item) } @@ -2517,7 +2517,7 @@ function readerListItems(node, list, ctx) { // ------------------------------------------------------------------ the walk -function readerNode(child, state, ctx) { +function readerNode(child, state, reading) { if (child.type === "text") { // Raw text is a stylesheet or a script, whose element is dropped anyway. if (!child.raw) readerAppendText(state, child.text) @@ -2532,7 +2532,7 @@ function readerNode(child, state, ctx) { return } if (name === "img") { - readerAppendImage(state, child, ctx) + readerAppendImage(state, child, reading) return } if (name === "hr") { @@ -2545,13 +2545,13 @@ function readerNode(child, state, ctx) { var href = readerHref(child) // A link the reader will not follow is still a label the reader draws. if (href === "") { - readerWalk(child, state, ctx) + readerWalk(child, state, reading) return } var link = readerElement("a") link.attrs = [{ name: "href", value: href }] var linked = readerOpen(state, link) - readerWalk(child, state, ctx) + readerWalk(child, state, reading) if (linked) state.chain.pop() return } @@ -2559,13 +2559,13 @@ function readerNode(child, state, ctx) { var inline = READER_INLINE[name] if (typeof inline === "string") { var opened = readerOpen(state, readerElement(inline)) - readerWalk(child, state, ctx) + readerWalk(child, state, reading) if (opened) state.chain.pop() return } if (READER_HEADINGS[name] === true) { - readerHeading(child, state, ctx, name) + readerHeading(child, state, reading, name) return } @@ -2583,20 +2583,20 @@ function readerNode(child, state, ctx) { if (name === "ul" || name === "ol") { readerFlush(state, "p") var list = readerElement(name) - readerListItems(child, list, ctx) + readerListItems(child, list, reading) if (list.children.length > 0) { state.blocks.push(list) return } // A list with no items is a box somebody spelled