From 09b2a9b244861cabb72d0abe552b2ae032a0b558 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 25 Nov 2026 07:30:43 +0900 Subject: [PATCH] feat(hosts): add web, iOS, and Android hosts with local storage bridges --- .../apps/android/App/app/build.gradle | 3 +- .../apps/ios/App/xc-universal-binary.sh | 12 +- packages/frontend/hosts/android/AGENTS.md | 53 + .../hosts/android/AndroidManifest.xml | 54 + packages/frontend/hosts/android/CLAUDE.md | 1 + packages/frontend/hosts/android/Cargo.toml | 42 + .../pro/host/AndroidBootstrapCoordinator.kt | 250 + .../app/affine/pro/host/AuthDataStore.kt | 800 +++ .../pro/host/LegacyLocalStorageProbe.kt | 272 + .../app/affine/pro/host/MainActivity.kt | 4237 +++++++++++++ .../app/affine/pro/host/ShareIntentBridge.kt | 1408 +++++ .../affine/pro/host/ShareReceiverActivity.kt | 170 + .../android/scripts/package-debug-apk.sh | 122 + .../hosts/android/src/android_window.rs | 498 ++ .../frontend/hosts/android/src/autofill.rs | 463 ++ .../frontend/hosts/android/src/datastore.rs | 1118 ++++ .../hosts/android/src/editor_fallback.rs | 459 ++ .../hosts/android/src/editor_platform.rs | 819 +++ .../hosts/android/src/editor_runtime/ime.rs | 411 ++ .../hosts/android/src/editor_runtime/mod.rs | 687 +++ .../hosts/android/src/editor_selection.rs | 255 + packages/frontend/hosts/android/src/ime.rs | 405 ++ .../frontend/hosts/android/src/jni_bridge.rs | 783 +++ .../frontend/hosts/android/src/jni_editor.rs | 801 +++ .../hosts/android/src/jni_interaction.rs | 950 +++ .../frontend/hosts/android/src/jni_islands.rs | 527 ++ .../frontend/hosts/android/src/jni_shell.rs | 152 + .../frontend/hosts/android/src/jni_storage.rs | 688 +++ packages/frontend/hosts/android/src/lib.rs | 1400 +++++ .../hosts/android/src/native_islands.rs | 250 + packages/frontend/hosts/android/src/pdf.rs | 243 + .../hosts/android/src/runtime_root.rs | 92 + .../frontend/hosts/android/src/selection.rs | 868 +++ .../hosts/android/src/shell_runtime.rs | 637 ++ .../hosts/android/src/shell_workspace.rs | 223 + .../frontend/hosts/android/src/storage.rs | 828 +++ .../frontend/hosts/android/src/surface.rs | 459 ++ .../frontend/hosts/android/src/text_layout.rs | 395 ++ .../hosts/android/tests/ImeHostParityCheck.kt | 3764 ++++++++++++ packages/frontend/hosts/ios/AGENTS.md | 35 + packages/frontend/hosts/ios/CLAUDE.md | 1 + packages/frontend/hosts/ios/Cargo.toml | 39 + packages/frontend/hosts/ios/Info.plist | 58 + .../ios/Sources/AffinePaywallBridge.swift | 283 + .../hosts/ios/Sources/AppDelegate.swift | 56 + .../hosts/ios/Sources/HapticsBridge.swift | 134 + .../Sources/HostBootstrapCoordinator.swift | 214 + .../KeyboardAvoidanceCoordinator.swift | 161 + .../hosts/ios/Sources/LegacyAuthBridge.swift | 588 ++ .../ios/Sources/LegacyLocalStorageProbe.swift | 466 ++ .../ios/Sources/MetalHostViewController.swift | 2732 +++++++++ .../ios/Sources/OnboardingSignInBridge.swift | 65 + .../hosts/ios/Sources/PdfRendererBridge.swift | 327 + .../ios/Sources/ShareExtensionBridge.swift | 619 ++ .../ios/Sources/TextRenderingBridge.swift | 939 +++ .../ios/Sources/WorkspaceStorageBridge.swift | 230 + .../hosts/ios/include/affine_mobile_host.h | 902 +++ .../hosts/ios/scripts/build-rust-ios.sh | 33 + .../hosts/ios/scripts/check-sim-host.sh | 75 + .../hosts/ios/scripts/package-sim-app.sh | 71 + packages/frontend/hosts/ios/src/auth.rs | 538 ++ packages/frontend/hosts/ios/src/clipboard.rs | 182 + .../hosts/ios/src/editor_doc_positions.rs | 598 ++ .../frontend/hosts/ios/src/editor_fallback.rs | 274 + .../frontend/hosts/ios/src/editor_platform.rs | 821 +++ .../frontend/hosts/ios/src/editor_runtime.rs | 1092 ++++ packages/frontend/hosts/ios/src/ffi.rs | 950 +++ .../hosts/ios/src/ffi_doc_positions.rs | 278 + packages/frontend/hosts/ios/src/ffi_editor.rs | 792 +++ .../frontend/hosts/ios/src/ffi_islands.rs | 322 + packages/frontend/hosts/ios/src/ffi_s3.rs | 893 +++ .../frontend/hosts/ios/src/ffi_selection.rs | 618 ++ packages/frontend/hosts/ios/src/ffi_text.rs | 439 ++ packages/frontend/hosts/ios/src/haptics.rs | 90 + .../frontend/hosts/ios/src/keyboard_insets.rs | 374 ++ .../frontend/hosts/ios/src/legacy_storage.rs | 449 ++ packages/frontend/hosts/ios/src/lib.rs | 636 ++ .../frontend/hosts/ios/src/native_islands.rs | 437 ++ packages/frontend/hosts/ios/src/pdf.rs | 221 + .../frontend/hosts/ios/src/runtime_root.rs | 92 + packages/frontend/hosts/ios/src/selection.rs | 1252 ++++ .../frontend/hosts/ios/src/share_ingest.rs | 435 ++ .../frontend/hosts/ios/src/shell_runtime.rs | 694 +++ .../frontend/hosts/ios/src/shell_workspace.rs | 223 + .../frontend/hosts/ios/src/text_layout.rs | 587 ++ .../frontend/hosts/ios/src/workspace_store.rs | 563 ++ .../hosts/ios/tests/IosHostS2SmokeTest.swift | 817 +++ .../hosts/ios/tests/IosHostS3SmokeTest.swift | 2038 +++++++ packages/frontend/hosts/web/AGENTS.md | 50 + packages/frontend/hosts/web/CLAUDE.md | 1 + packages/frontend/hosts/web/desktop/boot.js | 42 + .../frontend/hosts/web/desktop/index.html | 39 + packages/frontend/hosts/web/desktop/start.js | 555 ++ packages/frontend/hosts/web/index.html | 183 + .../hosts/web/scripts/chromium-harness.mjs | 685 +++ .../scripts/legacy-workspace-readiness.mjs | 882 +++ .../web/scripts/stage-canary-dual-shell.mjs | 1597 +++++ .../web/scripts/stage-preview-workers.mjs | 79 + .../verify-canary-dual-shell-browser.mjs | 744 +++ .../scripts/verify-canary-dual-shell-e2e.mjs | 2167 +++++++ .../scripts/verify-desktop-persistence.mjs | 1003 +++ .../web/scripts/verify-idb-real-browser.mjs | 353 ++ .../scripts/verify-preview-workers-e2e.mjs | 657 ++ .../scripts/verify-s3-web-real-browser.mjs | 740 +++ .../web/scripts/verify-workerd-bundle-e2e.mjs | 647 ++ .../scripts/verify-zero-third-party-js.mjs | 376 ++ .../hosts/web/scripts/yjs-v1-inspect.mjs | 293 + packages/frontend/hosts/web/sign-in.html | 528 ++ packages/frontend/hosts/web/src/a11y.js | 404 ++ .../hosts/web/src/default-app-entry.js | 884 +++ packages/frontend/hosts/web/src/host.js | 2280 +++++++ .../frontend/hosts/web/src/idb-storage.js | 2557 ++++++++ packages/frontend/hosts/web/src/pdf-client.js | 760 +++ .../hosts/web/src/selection-overlay.js | 1181 ++++ packages/frontend/hosts/web/src/sign-in.js | 2407 ++++++++ .../frontend/hosts/web/src/wasm-scalar-rpc.js | 143 + .../frontend/hosts/web/src/worker-loader.js | 370 ++ .../hosts/web/src/workers/math-worker.js | 4 + .../hosts/web/src/workers/mermaid-worker.js | 4 + .../hosts/web/src/workers/pdf-worker.js | 4 + .../web/src/workers/preview-worker-core.js | 323 + .../hosts/web/src/workers/typst-worker.js | 4 + .../tests/check-snapshot-prefixes.test.mjs | 376 ++ .../hosts/web/tests/chromium-harness.test.mjs | 665 ++ .../tests/desktop-wheel-diagnostics.test.mjs | 118 + .../frontend/hosts/web/tests/desktop.test.mjs | 1742 ++++++ .../web/tests/dual-shell-save.browser.mjs | 201 + .../tests/dual-shell-verifiers.browser.mjs | 337 + .../web/tests/dual-shell-wasm-fixture.mjs | 89 + .../web/tests/extract-tokens-shadow.test.mjs | 145 + .../hosts/web/tests/idb-storage.test.mjs | 2680 ++++++++ .../legacy-workspace-readiness.browser.mjs | 779 +++ .../frontend/hosts/web/tests/memory-idb.mjs | 563 ++ .../hosts/web/tests/preview-workers.test.mjs | 948 +++ .../hosts/web/tests/sign-in-and-a11y.test.mjs | 1687 +++++ .../hosts/web/tests/web-host.test.mjs | 5422 +++++++++++++++++ .../web/tests/yjs-v1-inspect.browser.mjs | 173 + .../hosts/web/tests/yjs-v1-inspect.test.mjs | 45 + 138 files changed, 89242 insertions(+), 6 deletions(-) create mode 100644 packages/frontend/hosts/android/AGENTS.md create mode 100644 packages/frontend/hosts/android/AndroidManifest.xml create mode 100644 packages/frontend/hosts/android/CLAUDE.md create mode 100644 packages/frontend/hosts/android/Cargo.toml create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt create mode 100644 packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt create mode 100755 packages/frontend/hosts/android/scripts/package-debug-apk.sh create mode 100644 packages/frontend/hosts/android/src/android_window.rs create mode 100644 packages/frontend/hosts/android/src/autofill.rs create mode 100644 packages/frontend/hosts/android/src/datastore.rs create mode 100644 packages/frontend/hosts/android/src/editor_fallback.rs create mode 100644 packages/frontend/hosts/android/src/editor_platform.rs create mode 100644 packages/frontend/hosts/android/src/editor_runtime/ime.rs create mode 100644 packages/frontend/hosts/android/src/editor_runtime/mod.rs create mode 100644 packages/frontend/hosts/android/src/editor_selection.rs create mode 100644 packages/frontend/hosts/android/src/ime.rs create mode 100644 packages/frontend/hosts/android/src/jni_bridge.rs create mode 100644 packages/frontend/hosts/android/src/jni_editor.rs create mode 100644 packages/frontend/hosts/android/src/jni_interaction.rs create mode 100644 packages/frontend/hosts/android/src/jni_islands.rs create mode 100644 packages/frontend/hosts/android/src/jni_shell.rs create mode 100644 packages/frontend/hosts/android/src/jni_storage.rs create mode 100644 packages/frontend/hosts/android/src/lib.rs create mode 100644 packages/frontend/hosts/android/src/native_islands.rs create mode 100644 packages/frontend/hosts/android/src/pdf.rs create mode 100644 packages/frontend/hosts/android/src/runtime_root.rs create mode 100644 packages/frontend/hosts/android/src/selection.rs create mode 100644 packages/frontend/hosts/android/src/shell_runtime.rs create mode 100644 packages/frontend/hosts/android/src/shell_workspace.rs create mode 100644 packages/frontend/hosts/android/src/storage.rs create mode 100644 packages/frontend/hosts/android/src/surface.rs create mode 100644 packages/frontend/hosts/android/src/text_layout.rs create mode 100644 packages/frontend/hosts/android/tests/ImeHostParityCheck.kt create mode 100644 packages/frontend/hosts/ios/AGENTS.md create mode 100644 packages/frontend/hosts/ios/CLAUDE.md create mode 100644 packages/frontend/hosts/ios/Cargo.toml create mode 100644 packages/frontend/hosts/ios/Info.plist create mode 100644 packages/frontend/hosts/ios/Sources/AffinePaywallBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/AppDelegate.swift create mode 100644 packages/frontend/hosts/ios/Sources/HapticsBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/HostBootstrapCoordinator.swift create mode 100644 packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift create mode 100644 packages/frontend/hosts/ios/Sources/LegacyAuthBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift create mode 100644 packages/frontend/hosts/ios/Sources/MetalHostViewController.swift create mode 100644 packages/frontend/hosts/ios/Sources/OnboardingSignInBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/ShareExtensionBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift create mode 100644 packages/frontend/hosts/ios/Sources/WorkspaceStorageBridge.swift create mode 100644 packages/frontend/hosts/ios/include/affine_mobile_host.h create mode 100755 packages/frontend/hosts/ios/scripts/build-rust-ios.sh create mode 100644 packages/frontend/hosts/ios/scripts/check-sim-host.sh create mode 100755 packages/frontend/hosts/ios/scripts/package-sim-app.sh create mode 100644 packages/frontend/hosts/ios/src/auth.rs create mode 100644 packages/frontend/hosts/ios/src/clipboard.rs create mode 100644 packages/frontend/hosts/ios/src/editor_doc_positions.rs create mode 100644 packages/frontend/hosts/ios/src/editor_fallback.rs create mode 100644 packages/frontend/hosts/ios/src/editor_platform.rs create mode 100644 packages/frontend/hosts/ios/src/editor_runtime.rs create mode 100644 packages/frontend/hosts/ios/src/ffi.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_doc_positions.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_editor.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_islands.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_s3.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_selection.rs create mode 100644 packages/frontend/hosts/ios/src/ffi_text.rs create mode 100644 packages/frontend/hosts/ios/src/haptics.rs create mode 100644 packages/frontend/hosts/ios/src/keyboard_insets.rs create mode 100644 packages/frontend/hosts/ios/src/legacy_storage.rs create mode 100644 packages/frontend/hosts/ios/src/lib.rs create mode 100644 packages/frontend/hosts/ios/src/native_islands.rs create mode 100644 packages/frontend/hosts/ios/src/pdf.rs create mode 100644 packages/frontend/hosts/ios/src/runtime_root.rs create mode 100644 packages/frontend/hosts/ios/src/selection.rs create mode 100644 packages/frontend/hosts/ios/src/share_ingest.rs create mode 100644 packages/frontend/hosts/ios/src/shell_runtime.rs create mode 100644 packages/frontend/hosts/ios/src/shell_workspace.rs create mode 100644 packages/frontend/hosts/ios/src/text_layout.rs create mode 100644 packages/frontend/hosts/ios/src/workspace_store.rs create mode 100644 packages/frontend/hosts/ios/tests/IosHostS2SmokeTest.swift create mode 100644 packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift create mode 100644 packages/frontend/hosts/web/AGENTS.md create mode 100644 packages/frontend/hosts/web/CLAUDE.md create mode 100644 packages/frontend/hosts/web/desktop/boot.js create mode 100644 packages/frontend/hosts/web/desktop/index.html create mode 100644 packages/frontend/hosts/web/desktop/start.js create mode 100644 packages/frontend/hosts/web/index.html create mode 100644 packages/frontend/hosts/web/scripts/chromium-harness.mjs create mode 100644 packages/frontend/hosts/web/scripts/legacy-workspace-readiness.mjs create mode 100644 packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs create mode 100644 packages/frontend/hosts/web/scripts/stage-preview-workers.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-desktop-persistence.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-preview-workers-e2e.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-s3-web-real-browser.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-workerd-bundle-e2e.mjs create mode 100644 packages/frontend/hosts/web/scripts/verify-zero-third-party-js.mjs create mode 100644 packages/frontend/hosts/web/scripts/yjs-v1-inspect.mjs create mode 100644 packages/frontend/hosts/web/sign-in.html create mode 100644 packages/frontend/hosts/web/src/a11y.js create mode 100644 packages/frontend/hosts/web/src/default-app-entry.js create mode 100644 packages/frontend/hosts/web/src/host.js create mode 100644 packages/frontend/hosts/web/src/idb-storage.js create mode 100644 packages/frontend/hosts/web/src/pdf-client.js create mode 100644 packages/frontend/hosts/web/src/selection-overlay.js create mode 100644 packages/frontend/hosts/web/src/sign-in.js create mode 100644 packages/frontend/hosts/web/src/wasm-scalar-rpc.js create mode 100644 packages/frontend/hosts/web/src/worker-loader.js create mode 100644 packages/frontend/hosts/web/src/workers/math-worker.js create mode 100644 packages/frontend/hosts/web/src/workers/mermaid-worker.js create mode 100644 packages/frontend/hosts/web/src/workers/pdf-worker.js create mode 100644 packages/frontend/hosts/web/src/workers/preview-worker-core.js create mode 100644 packages/frontend/hosts/web/src/workers/typst-worker.js create mode 100644 packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs create mode 100644 packages/frontend/hosts/web/tests/chromium-harness.test.mjs create mode 100644 packages/frontend/hosts/web/tests/desktop-wheel-diagnostics.test.mjs create mode 100644 packages/frontend/hosts/web/tests/desktop.test.mjs create mode 100644 packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs create mode 100644 packages/frontend/hosts/web/tests/dual-shell-verifiers.browser.mjs create mode 100644 packages/frontend/hosts/web/tests/dual-shell-wasm-fixture.mjs create mode 100644 packages/frontend/hosts/web/tests/extract-tokens-shadow.test.mjs create mode 100644 packages/frontend/hosts/web/tests/idb-storage.test.mjs create mode 100644 packages/frontend/hosts/web/tests/legacy-workspace-readiness.browser.mjs create mode 100644 packages/frontend/hosts/web/tests/memory-idb.mjs create mode 100644 packages/frontend/hosts/web/tests/preview-workers.test.mjs create mode 100644 packages/frontend/hosts/web/tests/sign-in-and-a11y.test.mjs create mode 100644 packages/frontend/hosts/web/tests/web-host.test.mjs create mode 100644 packages/frontend/hosts/web/tests/yjs-v1-inspect.browser.mjs create mode 100644 packages/frontend/hosts/web/tests/yjs-v1-inspect.test.mjs diff --git a/packages/frontend/apps/android/App/app/build.gradle b/packages/frontend/apps/android/App/app/build.gradle index ee15fb58b2..f1d671bfed 100644 --- a/packages/frontend/apps/android/App/app/build.gradle +++ b/packages/frontend/apps/android/App/app/build.gradle @@ -199,8 +199,9 @@ android.applicationVariants.configureEach { variant -> def variantName = "${variant.name.substring(0,1).toUpperCase()}${variant.name.substring(1)}" def t = tasks.register("generate${variantName}UniFFIBindings", Exec) { workingDir "${project.projectDir}" + def rootManifest = file("${project.projectDir}/../../../../../../Cargo.toml").canonicalPath // Runs the bindings generation, note that you must have uniffi-bindgen installed and in your PATH environment variable - commandLine "${cargoPath}", 'run', '--bin', 'uniffi-bindgen', 'generate', '--library', "${buildDir}/rustJniLibs/android/${nativeAbi}/libaffine_mobile_native.so", '--language', 'kotlin', '--out-dir', "${project.projectDir}/src/main/java" + commandLine "${cargoPath}", 'run', '--manifest-path', "${rootManifest}", '--bin', 'uniffi-bindgen', 'generate', '--library', "${buildDir}/rustJniLibs/android/${nativeAbi}/libaffine_mobile_native.so", '--language', 'kotlin', '--out-dir', "${project.projectDir}/src/main/java" dependsOn(nativeLibraries) } tasks.named("compile${variantName}Kotlin").configure { dependsOn(t) } diff --git a/packages/frontend/apps/ios/App/xc-universal-binary.sh b/packages/frontend/apps/ios/App/xc-universal-binary.sh index 045faae8f9..454283a732 100644 --- a/packages/frontend/apps/ios/App/xc-universal-binary.sh +++ b/packages/frontend/apps/ios/App/xc-universal-binary.sh @@ -43,7 +43,9 @@ FFI_TARGET=${1} SRC_ROOT=${2} # Keep Cargo artifacts in a stable repo-local location so Xcode does not inherit # a sandbox-specific CARGO_TARGET_DIR from the parent shell. -export CARGO_TARGET_DIR="$SRC_ROOT/../../../target" +REPO_ROOT="$(cd "$SRC_ROOT/../../.." && pwd)" +MANIFEST_PATH="$REPO_ROOT/Cargo.toml" +export CARGO_TARGET_DIR="$REPO_ROOT/target" # buildvariant from our xcconfigs BUILDVARIANT=$(echo "${3}" | tr '[:upper:]' '[:lower:]') @@ -76,18 +78,18 @@ for arch in $ARCHS; do # Intel iOS simulator export CFLAGS_x86_64_apple_ios="-target x86_64-apple-ios" - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target x86_64-apple-ios --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target x86_64-apple-ios --features use-as-lib SIM_X86_64_LIB="$CARGO_TARGET_DIR/x86_64-apple-ios/${RELFLAG}/lib${FFI_TARGET}.a" ;; arm64) if [ $IS_SIMULATOR -eq 0 ]; then # Hardware iOS targets - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios --features use-as-lib DEVICE_ARM64_LIB="$CARGO_TARGET_DIR/aarch64-apple-ios/${RELFLAG}/lib${FFI_TARGET}.a" else # Apple Silicon iOS simulator - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios-sim --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios-sim --features use-as-lib SIM_ARM64_LIB="$CARGO_TARGET_DIR/aarch64-apple-ios-sim/${RELFLAG}/lib${FFI_TARGET}.a" fi ;; @@ -106,7 +108,7 @@ else exit 1 fi -$CARGO run -p affine_mobile_native --features use-as-lib --bin uniffi-bindgen generate --no-format --library "$BINDGEN_LIB" --language swift --out-dir "$SRCROOT/../../ios/App/App/uniffi" +$CARGO run --manifest-path "$MANIFEST_PATH" -p affine_mobile_native --features use-as-lib --bin uniffi-bindgen generate --no-format --library "$BINDGEN_LIB" --language swift --out-dir "$SRCROOT/../../ios/App/App/uniffi" if [ $IS_SIMULATOR -eq 0 ]; then cp "$DEVICE_ARM64_LIB" "$OUTPUT_LIB" diff --git a/packages/frontend/hosts/android/AGENTS.md b/packages/frontend/hosts/android/AGENTS.md new file mode 100644 index 0000000000..703c67e34a --- /dev/null +++ b/packages/frontend/hosts/android/AGENTS.md @@ -0,0 +1,53 @@ +# Working in `packages/frontend/hosts/android/` (for agents) + +This directory holds the thin Android host for AFFiNE (`affine-android-host`). +It combines a hand-written JNI Rust crate with a minimal Kotlin `SurfaceView` activity. + +## Hard boundaries + +- Keep zero JNA and zero UniFFI bindings. + Export hand-written `extern "C"` JNI symbols under `#[cfg(any(target_os = "android", test, feature = "host-jni"))]` across `src/jni_bridge.rs`, `src/jni_editor.rs`, `src/jni_interaction.rs`, `src/jni_shell.rs`, and `src/jni_storage.rs`. +- `MainActivity` creates its host with `nativeCreateShellHost`, which mounts the `affine-mobile` `MobileShellView`; `nativeCreateHost` keeps one bare `PlaygroundView` for editor-only parity sequences. `src/runtime_root.rs` resolves the editor that owns the `InputConnection` and selection handles: the root editor, or the shell's embedded `page_editor()` while the `Page` route shows with no sheet or drawer above it. The shell's focused `EntityInputHandler` takes `InputConnection` text on the Search route with no sheet above it and in the drawer once its filter holds `search_focus`; while any other sheet, or the drawer without a focused filter, covers the shell, the runtime drops text and composition edits. `nativeHandleBack` lets the page editor close its overlay first, then runs `MobileBackCoordinator`, and returns `false` at the root route. Every bootstrap result (first start, retried start, and `retryFailedWorkspaces`) goes through `MainActivity.applyBootstrapOutcome`, which mounts the first allowlisted workspace that bootstrap opened (`AndroidBootstrapCoordinator.shellWorkspaceId`) with `nativeShellMountWorkspace` (`src/shell_workspace.rs`): the mount loads only the root document and `db$*` tables, each page loads when the shell opens it (a failed load retries the next time the page shows), a scheduler task commits edits every second (zero SQLite access without pending changes), and `nativeShellFlushWorkspace` commits them in `onStop`. `onConfigurationChanged` and `onResume` pass the system dark mode to `nativeShellSetSystemDark`. `AffineSurfaceView` publishes the shell's `AccessibilityTree` (`nativeShellAccessibilityJson`, parsed by `ShellAccessibilityNode`) as virtual views through `AccessibilityNodeProvider` with stable virtual view IDs per node ID and accessibility focus (`ShellAccessibilityViews`), and an accessibility click sends a tap at the node center. `ShellAccessibilityViews` sends accessibility events only while `AccessibilityManager.isEnabled` is true, so the system can clear the focus after the last service stops. A retried bootstrap reads the allowlist again while no shell workspace is mounted (`AndroidBootstrapCoordinator.retryPlan`). `ShellBootstrapState` keeps the bootstrap state of the activity: `onResume` and `onNewIntent` retry as `retryPlan` plans while no shell workspace is mounted (an incomplete outcome, an allowlist without a workspace yet, or a failed mount), at most three times in a row, and drain shares otherwise. +- Keep the main app shell free of any persistent `WebView` and free of `SurfaceHolder.lockCanvas` calls. +- Mount the live pure-Rust `PlaygroundView` (`src/editor_platform.rs`, `src/editor_runtime/mod.rs`, `src/editor_selection.rs`, `src/jni_editor.rs`, with `native_selection_ui = true`) inside `MainActivity` (`AffineSurfaceView` + `DocumentSelectionHandleView`, with `HostTextPreviewView` and the custom `Copy | Cut` capsule removed from `MainActivity`). Drive GPU document-level teardrop handles, system `android.widget.Magnifier` (API 28+), system `ActionMode.TYPE_FLOATING` (`ActionMode.Callback2.onGetContentRect` + `onPrepareActionMode` gated by Rust `action_mask`), and multi-MIME `ClipboardManager` (`ClipData.newHtmlText` carrying embedded `data-blocksuite-snapshot` + plain text) from Rust `PlaygroundView`, hiding handles/Magnifier/ActionMode whenever `documentBufferController.isAutofillFocused()` is true. Forward `MotionEvent` touch pointers (`nativeOnTouchEvent`), `InputConnection.sendKeyEvent` (`nativeOnKeyEvent`), and `FormFactor::from_android_smallest_width_dp` (`< 600` -> `Phone`, `>= 600` -> `Tablet`, Stage-1 `edgeless_readonly = true`, `database_readonly = true`). +- Enforce zero host text copy (`AffineInputConnection` reads straight from `PlatformInputHandler`), push editor mutations to `InputMethodManager.updateSelection` / `restartInput` / `updateCursorAnchorInfo`, and preserve exact `[start, end)` ranges in `setComposingRegion` via `replace_and_mark_text_in_range`. +- Use `scripts/package-debug-apk.sh` to build and sign `AffineAndroidHost-debug.apk` directly with Android SDK CLI tools (`aapt2`, `kotlinc`, `d8`, `zipalign`, `apksigner`) without Gradle daemons. + Compute teardrop handle geometry, line-midpoint grab-offset drag, UTF-16 anchor-authoritative handle ownership (`nativeApplyTextDragEndpoints`), continuous zero-length crossover inversion, off-screen hiding, line-midpoint magnifier focus, and Copy/Cut/Paste/SelectAll actions wired to `ClipboardManager` (`HostClipboard` / `AndroidClipboardAdapter`, checking `primaryClipDescription` metadata without reading `primaryClip` during draw, and writing before deleting on `Cut`) and `InputConnection.performContextMenuAction` in `src/selection.rs`, `src/ime.rs`, and `MainActivity.kt`. + `AndroidSelectionOverlayView` fills a pre-allocated 24-float JNI buffer (`nativeFillSelectionOverlayGeometry`) and draws teardrop `Path` handles, `getSelectionPath` loupe highlights with centered focus carets, and `Copy | Cut | Paste` pills with dividers using zero per-frame allocations, zero Binder IPC in `onDraw`, and zero `SurfaceHolder.lockCanvas` calls. +- Clear the default surface canvas to light `#FAFAFC` (`DEFAULT_CLEAR_COLOR_ARGB = 0xFFFA_FAFC`) and adapt `HostTextPreviewView` text and selection colors to surface luminance. + Preserve viewport size, display density, scroll offset, IME state, and texture generation across `surfaceDestroyed -> surfaceCreated -> surfaceChanged` recreation while gating `is_ready()` on per-generation `surfaceChanged` configuration (`configured_for_generation`). + `SurfaceLifecycleState` models `Vulkan -> Gles3 -> CpuFallback` downgrade on device loss; the current `android_window` runtime probe returns `(false, true)` and starts on EGL/GLES3 with CPU fallback. +- Gate `AutofillManager` virtual view structure and per-field isolated value write-back at API 26 (`should_expose_autofill(sdk_int)` returns `sdk_int >= 26`, `IMPORTANT_FOR_AUTOFILL_YES` on `AffineSurfaceView`, implemented in `src/autofill.rs` and `AndroidAutofillController`). + Never emit synthetic placeholder asterisks or spaces in `ViewStructure`, update IME only when `autofillId == focusedFieldId`, sync manual `InputConnection` edits back to the focused Autofill field via `onFocusedTextEdited`, isolate form credentials from `HostDocumentStore` and `HostTextPreviewView` via `HostDocumentBufferController`, redact sensitive values in `Debug`, and zero cached plaintext on `commit`, `cancel`, and `clear_fields`. +- Dispatch four-phase predictive back (`Start`, `Progress`, `Cancel`, `Commit`) on API 34+ (`OnBackAnimationCallback`, including standalone button/key `onBackInvoked` calls) and single-step atomic commit on API 24-33 (`OnBackInvokedCallback` / `onBackPressed`) against a real destination route stack (`BackNavigationState`) and `HostDocumentStore` driven by `MainActivity.navigateTo` and `MainActivity.openDocument`, blocking re-entrant commits and returning `false` at the root route. +- Render PDF pages in place through `android.graphics.pdf.PdfRenderer` (`AndroidPdfPageRenderer`) with pre-validated Rust bounds, OOM cap (`4096x4096`), clamped `dpi_bucket >= 72` cache keys, and zero-Rust-heap chunked streaming `ARGB_8888 -> RGBA8` conversion with per-call JNI `ExceptionCheck` in `src/pdf.rs` and `src/jni_interaction.rs`. +- Open in-place SQLite WAL databases only from the ordered `affine-local-workspace` allowlist. + Never scan disk `*.db` files to discover local workspaces. +- Store auth sessions in `/datastore/auth-sessions.preferences_pb` using `v1::` AES-GCM envelopes, 1970 Unix millisecond `i64` timestamps, and the persisted `auth-installation-id` key. +- Parse legacy `https://localhost` `localStorage` probe and rollback write-back payloads through `parse_legacy_local_storage_probe` using an explicit key allowlist only. + Block `window.indexedDB.open` and `window.indexedDB.deleteDatabase` in every probe script. +- Keep every `.rs` file at or below 800 non-test lines, free of non-test `super::super::`, and free of wall-clock calls. + +## Verification + +Always clear inherited root rustflags: + +```sh +CARGO_ENCODED_RUSTFLAGS="" cargo test --locked -p affine-android-host --all-features +CARGO_ENCODED_RUSTFLAGS="" cargo build --locked -p affine-android-host --features host-jni +CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-android-host --target aarch64-linux-android +``` + +To run the 33-sequence Kotlin-to-JNI parity harness on a host with `kotlinc` and `ANDROID_HOME`: + +```sh +kotlinc -classpath "$ANDROID_JAR" -d /tmp/affine-android-kotlin \ + hosts/android/kotlin/app/affine/pro/host/MainActivity.kt \ + hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt \ + hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt \ + hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt \ + hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt \ + hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt \ + hosts/android/tests/ImeHostParityCheck.kt +kotlin -J-Djava.library.path="$PWD/target/debug" -cp "/tmp/affine-android-kotlin:$ANDROID_JAR" ImeHostParityCheckKt +``` diff --git a/packages/frontend/hosts/android/AndroidManifest.xml b/packages/frontend/hosts/android/AndroidManifest.xml new file mode 100644 index 0000000000..1706237782 --- /dev/null +++ b/packages/frontend/hosts/android/AndroidManifest.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/frontend/hosts/android/CLAUDE.md b/packages/frontend/hosts/android/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/frontend/hosts/android/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/frontend/hosts/android/Cargo.toml b/packages/frontend/hosts/android/Cargo.toml new file mode 100644 index 0000000000..2b4a6e8925 --- /dev/null +++ b/packages/frontend/hosts/android/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "affine-android-host" +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true +workspace = "../.." + +[lib] +crate-type = ["rlib", "cdylib"] + +[features] +default = ["preview-typst"] +host-jni = [] +preview-typst = ["playground/preview-typst"] + +[dependencies] +affine-client = { path = "../../client" } +affine-legacy-import = { path = "../../legacy-import" } +affine-mobile = { path = "../../mobile" } +affine-store = { path = "../../../common/store" } +anyhow.workspace = true +base64.workspace = true +blocksuite-playground-doc = { path = "../../../../blocksuite/crates/doc", default-features = false } +chrono.workspace = true +futures.workspace = true +playground = { path = "../../../../blocksuite/crates/playground", default-features = false } +raw-window-handle.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +smallvec.workspace = true +sqlx.workspace = true +tokio.workspace = true +ui = { path = "../../../ui/ui" } +ui-tokens = { path = "../../../ui/tokens" } +url.workspace = true +uuid.workspace = true +y-octo.workspace = true + +[lints] +workspace = true diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt new file mode 100644 index 0000000000..0c04ec6a3b --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt @@ -0,0 +1,250 @@ +package app.affine.pro.host + +/** + * Outcome of the one-shot legacy Android bootstrap sequence. + */ +data class BootstrapOutcome( + val imported: Boolean, + val canCreateDefaultWorkspace: Boolean, + val connectedWorkspaceKeys: List, + val failedWorkspaceIds: List = emptyList(), + val preservedLocalWorkspaceRaw: String?, +) { + val isComplete: Boolean + get() = imported && failedWorkspaceIds.isEmpty() +} + +/** + * Coordinates the Android startup migration path: + * `LegacyLocalStorageProbe` -> `nativeImportLegacyLocalStorageProbe` -> + * mounting allowlisted legacy local workspaces in place via `nativeConnectWorkspace` + * (zero mounts on empty/corrupt/failed probes so deleted `.db` files never resurrect). + */ +class AndroidBootstrapCoordinator( + private val handleProvider: () -> Long, + private val filesDirProvider: () -> String, +) { + fun start( + probe: LegacyLocalStorageProbe, + onComplete: (BootstrapOutcome) -> Unit = {}, + ) { + probe.capture { raw -> + onComplete(completeWithProbePayload(raw)) + } + } + + fun completeWithProbePayload( + payloadJson: String?, + allowedKeysCsv: String = "", + ): BootstrapOutcome { + val handle = handleProvider() + if (handle == 0L || payloadJson.isNullOrBlank()) { + return BootstrapOutcome( + imported = false, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + } + val imported = NativeBridge.nativeImportLegacyLocalStorageProbe( + handle, + payloadJson, + allowedKeysCsv, + ) + if (!imported) { + return BootstrapOutcome( + imported = false, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + } + + val canCreateDefault = NativeBridge.nativeCanCreateDefaultWorkspace(handle) + val preservedRaw = NativeBridge.nativeGetPreservedLocalWorkspaceRaw(handle) + val allowlistedIds = parseJsonStringArray( + NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(handle), + ) + val filesDir = filesDirProvider() + val connected = mutableListOf() + val failed = mutableListOf() + for (workspaceId in allowlistedIds) { + val key = NativeBridge.nativeConnectWorkspace(handle, filesDir, "local", workspaceId) + if (key != null) { + connected.add(key) + } else { + failed.add(workspaceId) + } + } + return BootstrapOutcome( + imported = true, + canCreateDefaultWorkspace = canCreateDefault, + connectedWorkspaceKeys = connected, + failedWorkspaceIds = failed, + preservedLocalWorkspaceRaw = preservedRaw, + ) + } + + /** + * Re-evaluates local workspace mounts against the current allowlist in Rust, + * dropping obsolete failed IDs removed from the allowlist while preserving + * already connected healthy workspace handles without reconnecting them. + */ + fun retryFailedWorkspaces(previous: BootstrapOutcome): BootstrapOutcome { + if (previous.isComplete || !previous.imported) { + return previous + } + val handle = handleProvider() + if (handle == 0L) { + return previous + } + val currentAllowlistedIds = parseJsonStringArray( + NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(handle), + ) + val filesDir = filesDirProvider() + val connected = mutableListOf() + val remainingFailed = mutableListOf() + for (workspaceId in currentAllowlistedIds) { + val key = NativeBridge.nativeConnectWorkspace(handle, filesDir, "local", workspaceId) + if (key != null) { + if (!connected.contains(key)) { + connected.add(key) + } + } else { + remainingFailed.add(workspaceId) + } + } + return previous.copy( + connectedWorkspaceKeys = connected, + failedWorkspaceIds = remainingFailed, + preservedLocalWorkspaceRaw = NativeBridge.nativeGetPreservedLocalWorkspaceRaw(handle), + ) + } + + /** + * First allowlisted local workspace that `outcome` mounted, which the shell shows in place of + * the showcase. Returns null before an import or when no allowlisted workspace mounted. + */ + fun shellWorkspaceId(outcome: BootstrapOutcome): String? { + val handle = handleProvider() + if (handle == 0L || !outcome.imported) return null + return parseJsonStringArray(NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(handle)) + .firstOrNull { it.isNotEmpty() && it !in outcome.failedWorkspaceIds } + } + + /** What a bootstrap retry runs. */ + enum class Retry { + /** The workspace is mounted: report the current outcome. */ + NONE, + /** Read the legacy storage and the allowlist again, then mount. */ + RESTART, + /** Mount the allowlisted workspaces that failed before. */ + FAILED_WORKSPACES, + } + + companion object { + /** + * Retry for `current`. A complete outcome without a mounted shell workspace (for example an + * empty allowlist) reads the allowlist again, so a workspace that appears later mounts in + * the same activity. + */ + fun retryPlan(current: BootstrapOutcome?, shellWorkspaceMounted: Boolean): Retry = when { + current == null || !current.imported -> Retry.RESTART + current.isComplete && shellWorkspaceMounted -> Retry.NONE + current.isComplete -> Retry.RESTART + else -> Retry.FAILED_WORKSPACES + } + + internal fun parseJsonStringArray(rawJson: String): List { + val len = NativeBridge.nativeJsonStringArrayLen(rawJson) + if (len <= 0) return emptyList() + return List(len) { idx -> + NativeBridge.nativeJsonStringArrayGet(rawJson, idx) ?: "" + } + } + } +} + +/** + * Bootstrap state of one activity: the last outcome, the shell workspace mount, and the + * automatic retries that the lifecycle entries (`onResume`, `onNewIntent`) start. + * + * A run is numbered when it begins, and only the newest run records its outcome. The lifecycle + * entries retry as [AndroidBootstrapCoordinator.retryPlan] plans while no shell workspace is + * mounted (an incomplete outcome, an allowlist without a workspace yet, or a mount that + * failed), at most [maxAutoRetries] times in a row. A manual retry and a mounted workspace + * reset that count. + */ +internal class ShellBootstrapState(private val maxAutoRetries: Int) { + @Volatile + var outcome: BootstrapOutcome? = null + private set + + /** A bootstrap run recorded its outcome. */ + @Volatile + var completed: Boolean = false + private set + + var workspaceMounted: Boolean = false + private set + + private var inFlight = false + private var generation = 0L + private var autoRetries = 0 + + val retryPlan: AndroidBootstrapCoordinator.Retry + get() = AndroidBootstrapCoordinator.retryPlan(outcome, workspaceMounted) + + /** The lifecycle entries retry while a recorded outcome leaves no shell workspace mounted. */ + val wantsAutoRetry: Boolean + get() = completed && retryPlan != AndroidBootstrapCoordinator.Retry.NONE + + /** + * `onResume` and `onNewIntent`: run [retry] while the bootstrap is not done and automatic + * retries remain, else [drainShares]. + */ + fun onLifecycleEntry(retry: () -> Unit, drainShares: () -> Unit) { + if (wantsAutoRetry && autoRetries < maxAutoRetries) retry() else drainShares() + } + + /** + * Begin a run and return its number, or `null` while a run is in flight or after + * [maxAutoRetries] automatic retries. + */ + fun begin(manual: Boolean): Long? { + if (inFlight) return null + if (manual) { + autoRetries = 0 + } else { + if (autoRetries >= maxAutoRetries) return null + autoRetries += 1 + } + inFlight = true + generation += 1 + return generation + } + + /** The run [run] ended without an outcome. */ + fun abandon(run: Long) { + if (run == generation) inFlight = false + } + + /** + * Record the outcome of run [run]. [mount] mounts the shell workspace of the outcome and + * returns `null` when the outcome opened none. Returns `false` for a run that a newer run + * replaced. + */ + fun finish(run: Long, result: BootstrapOutcome, mount: (BootstrapOutcome) -> Boolean?): Boolean { + if (run != generation) return false + inFlight = false + outcome = result + completed = true + if (!workspaceMounted) { + workspaceMounted = mount(result) == true + } + if (!wantsAutoRetry) autoRetries = 0 + return true + } +} diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt new file mode 100644 index 0000000000..fe77eac7fe --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt @@ -0,0 +1,800 @@ +package app.affine.pro.host + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.webkit.CookieManager +import java.io.File +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL +import java.nio.charset.StandardCharsets +import java.security.KeyStore +import java.security.SecureRandom +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CountDownLatch +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * Pure-Kotlin RFC 4648 Base64 (`NO_WRAP`, standard alphabet with `=` padding). + * + * Works identically on Android API 24+ (where `java.util.Base64` does not exist) + * and desktop JVM parity tests (where `android.util.Base64` is a stub). + */ +object Rfc4648Base64 { + private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + + private val DECODE_TABLE = IntArray(128) { -1 }.apply { + for (i in ALPHABET.indices) { + this[ALPHABET[i].code] = i + } + } + + fun encode(bytes: ByteArray): String { + if (bytes.isEmpty()) return "" + val out = StringBuilder(((bytes.size + 2) / 3) * 4) + var i = 0 + while (i < bytes.size) { + val b0 = bytes[i].toInt() and 0xFF + val has1 = i + 1 < bytes.size + val has2 = i + 2 < bytes.size + val b1 = if (has1) bytes[i + 1].toInt() and 0xFF else 0 + val b2 = if (has2) bytes[i + 2].toInt() and 0xFF else 0 + val triple = (b0 shl 16) or (b1 shl 8) or b2 + out.append(ALPHABET[(triple ushr 18) and 0x3F]) + out.append(ALPHABET[(triple ushr 12) and 0x3F]) + out.append(if (has1) ALPHABET[(triple ushr 6) and 0x3F] else '=') + out.append(if (has2) ALPHABET[triple and 0x3F] else '=') + i += 3 + } + return out.toString() + } + + fun decode(input: String): ByteArray { + if (input.isEmpty()) return ByteArray(0) + require(input.length % 4 == 0) { "invalid base64 length: ${input.length}" } + val pad = when { + input.endsWith("==") -> 2 + input.endsWith("=") -> 1 + else -> 0 + } + val out = ByteArray((input.length / 4) * 3 - pad) + var outIdx = 0 + var i = 0 + while (i < input.length) { + val c0 = decodeChar(input[i]) + val c1 = decodeChar(input[i + 1]) + val ch2 = input[i + 2] + val ch3 = input[i + 3] + val c2 = if (ch2 == '=') 0 else decodeChar(ch2) + val c3 = if (ch3 == '=') 0 else decodeChar(ch3) + val triple = (c0 shl 18) or (c1 shl 12) or (c2 shl 6) or c3 + out[outIdx++] = ((triple ushr 16) and 0xFF).toByte() + if (ch2 != '=' && outIdx < out.size) { + out[outIdx++] = ((triple ushr 8) and 0xFF).toByte() + } + if (ch3 != '=' && outIdx < out.size) { + out[outIdx++] = (triple and 0xFF).toByte() + } + i += 4 + } + return out + } + + private fun decodeChar(ch: Char): Int { + val code = ch.code + val v = if (code < DECODE_TABLE.size) DECODE_TABLE[code] else -1 + require(v >= 0) { "invalid base64 character: $ch" } + return v + } +} + +/** + * Clears ONLY the three `0.27.5` auth cookies (`affine_session`, + * `affine_user_id`, `affine_csrf_token`) for a canonical endpoint origin on + * sign-out or terminal 401, leaving unrelated same-origin preference cookies + * untouched. + */ +interface CookieCleaner { + fun clearAuthCookies(canonicalEndpoint: String) +} + +/** + * Production Android `CookieManager` cleaner matching `OkHttp.kt:70-72,92-100`. + */ +class AndroidCookieCleaner : CookieCleaner { + override fun clearAuthCookies(canonicalEndpoint: String) { + runCatching { + val manager = CookieManager.getInstance() + val headers = filterClearedCookieHeaders(manager.getCookie(canonicalEndpoint)) + if (headers.isEmpty()) return@runCatching + for (header in headers) { + manager.setCookie(canonicalEndpoint, header) + } + manager.flush() + } + } + + companion object { + val AUTH_COOKIE_NAMES: Set = setOf( + "affine_session", + "affine_user_id", + "affine_csrf_token", + ) + + /** + * Returns `Set-Cookie` expiration headers ONLY for `0.27.5` auth cookies + * present in [rawCookieHeader]. Non-auth cookies are ignored untouched. + */ + fun filterClearedCookieHeaders(rawCookieHeader: String?): List { + if (rawCookieHeader.isNullOrBlank()) return emptyList() + val matched = LinkedHashSet() + for (part in rawCookieHeader.split(";")) { + val name = part.substringBefore("=").trim() + if (name in AUTH_COOKIE_NAMES) { + matched.add(name) + } + } + return matched.map { name -> + "$name=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT" + } + } + } +} + +object NoOpCookieCleaner : CookieCleaner { + override fun clearAuthCookies(canonicalEndpoint: String) = Unit +} + +/** + * Result of a `/api/auth/session/refresh` transport call. + */ +sealed class RefreshResult { + data class Success(val serverResponseJson: String, val nowMs: Long) : RefreshResult() + data class Failure(val errorCode: String?) : RefreshResult() +} + +fun interface RefreshTransport { + fun refresh(canonicalEndpoint: String, refreshToken: String, attemptId: String): RefreshResult +} + +fun interface SessionPersistence { + fun writeEncryptedSession(filesDir: String, key: String, encrypted: String): Boolean +} + +/** + * Production `HttpURLConnection` transport for `POST /api/auth/session/refresh` + * aligned with `0.27.5` `AuthPlugin.kt:191-195` (sends `refreshToken` ONLY in + * the JSON body, never as an `Authorization: Bearer` header). + */ +class HttpUrlConnectionRefreshTransport( + private val appVersion: String = AuthSessionStore.CLIENT_VERSION_VALUE, + private val connectTimeoutMs: Int = 10_000, + private val readTimeoutMs: Int = 15_000, +) : RefreshTransport { + override fun refresh( + canonicalEndpoint: String, + refreshToken: String, + attemptId: String, + ): RefreshResult { + var conn: HttpURLConnection? = null + return try { + val url = URL("$canonicalEndpoint/api/auth/session/refresh") + conn = (url.openConnection() as HttpURLConnection).apply { + requestMethod = "POST" + connectTimeout = connectTimeoutMs + readTimeout = readTimeoutMs + doOutput = true + setRequestProperty("Content-Type", "application/json") + setRequestProperty("Accept", "application/json") + setRequestProperty(AuthSessionStore.CLIENT_KIND_HEADER, AuthSessionStore.CLIENT_KIND_VALUE) + setRequestProperty(AuthSessionStore.CLIENT_VERSION_HEADER, appVersion) + setRequestProperty(AuthSessionStore.REFRESH_ATTEMPT_HEADER, attemptId) + } + val payload = """{"refreshToken":${quoteJsonString(refreshToken)}}""" + conn.outputStream.use { out -> + out.write(payload.toByteArray(StandardCharsets.UTF_8)) + } + val status = conn.responseCode + val stream = if (status in 200..299) conn.inputStream else conn.errorStream + val body = stream?.bufferedReader(StandardCharsets.UTF_8)?.use { it.readText() } ?: "" + if (status in 200..299) { + RefreshResult.Success(body, System.currentTimeMillis()) + } else { + val code = NativeBridge.nativeExtractJsonStringField(body, "code") + ?.takeIf { it.isNotEmpty() } + ?: NativeBridge.nativeExtractJsonStringField(body, "name") + ?.takeIf { it.isNotEmpty() } + RefreshResult.Failure(code) + } + } catch (_: Exception) { + RefreshResult.Failure(null) + } finally { + conn?.disconnect() + } + } + + private fun quoteJsonString(value: String): String { + val sb = StringBuilder(value.length + 2) + sb.append('"') + for (ch in value) { + when (ch) { + '"' -> sb.append("\\\"") + '\\' -> sb.append("\\\\") + '\b' -> sb.append("\\b") + '\u000C' -> sb.append("\\f") + '\n' -> sb.append("\\n") + '\r' -> sb.append("\\r") + '\t' -> sb.append("\\t") + else -> if (ch.code < 0x20) { + sb.append("\\u%04x".format(ch.code)) + } else { + sb.append(ch) + } + } + } + sb.append('"') + return sb.toString() + } +} + +/** + * Key provider backing `AuthTokenCipher`. + * + * Production Android builds use [AndroidKeyStoreKeyProvider]; desktop JVM + * parity checks use [InMemoryAesKeyProvider]. + */ +interface SecretKeyProvider { + fun getOrCreateKey(alias: String): SecretKey + fun deleteKey(alias: String) +} + +/** + * Production Android Keystore AES-256-GCM provider aligned with `AuthPlugin.kt`. + */ +class AndroidKeyStoreKeyProvider : SecretKeyProvider { + override fun getOrCreateKey(alias: String): SecretKey { + val store = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } + (store.getEntry(alias, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) + generator.init( + KeyGenParameterSpec.Builder( + alias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setRandomizedEncryptionRequired(true) + .build(), + ) + return generator.generateKey() + } + + override fun deleteKey(alias: String) { + val store = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } + if (store.containsAlias(alias)) { + store.deleteEntry(alias) + } + } + + companion object { + private const val ANDROID_KEYSTORE = "AndroidKeyStore" + } +} + +/** + * Deterministic-test-friendly in-memory AES-256 key provider for JVM parity runs. + */ +class InMemoryAesKeyProvider( + private val random: SecureRandom = SecureRandom(), +) : SecretKeyProvider { + private val keys = ConcurrentHashMap() + + override fun getOrCreateKey(alias: String): SecretKey = + keys.computeIfAbsent(alias) { + val raw = ByteArray(32) + random.nextBytes(raw) + SecretKeySpec(raw, "AES") + } + + override fun deleteKey(alias: String) { + keys.remove(alias) + } +} + +/** + * AES/GCM/NoPadding (12-byte IV, 128-bit GCM tag) session cipher producing the + * exact `0.27.5` `v1::` format. + */ +class AuthTokenCipher( + private val keyProvider: SecretKeyProvider = AndroidKeyStoreKeyProvider(), + private val explicitIvForJvm: Boolean = false, + private val random: SecureRandom = SecureRandom(), +) { + fun encrypt(endpoint: String, plaintext: String): String { + val alias = NativeBridge.nativeKeystoreAlias(endpoint) + return runCatching { encryptWithAlias(alias, plaintext) }.getOrElse { + keyProvider.deleteKey(alias) + encryptWithAlias(alias, plaintext) + } + } + + private fun encryptWithAlias(alias: String, plaintext: String): String { + val cipher = Cipher.getInstance(TRANSFORMATION) + val key = keyProvider.getOrCreateKey(alias) + if (explicitIvForJvm) { + val iv = ByteArray(GCM_IV_LEN) + random.nextBytes(iv) + cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv)) + } else { + cipher.init(Cipher.ENCRYPT_MODE, key) + } + val ciphertext = cipher.doFinal(plaintext.toByteArray(StandardCharsets.UTF_8)) + val ivB64 = Rfc4648Base64.encode(cipher.iv) + val ctB64 = Rfc4648Base64.encode(ciphertext) + return "$VERSION_PREFIX:$ivB64:$ctB64" + } + + fun decrypt(endpoint: String, encoded: String): String? = runCatching { + if (!NativeBridge.nativeValidateV1Ciphertext(encoded)) return null + val parts = encoded.split(":") + val iv = Rfc4648Base64.decode(parts[1]) + val ciphertext = Rfc4648Base64.decode(parts[2]) + val alias = NativeBridge.nativeKeystoreAlias(endpoint) + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, keyProvider.getOrCreateKey(alias), GCMParameterSpec(GCM_TAG_BITS, iv)) + String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8) + }.getOrNull() + + fun reset(endpoint: String) { + keyProvider.deleteKey(NativeBridge.nativeKeystoreAlias(endpoint)) + } + + companion object { + const val TRANSFORMATION = "AES/GCM/NoPadding" + const val VERSION_PREFIX = "v1" + const val GCM_IV_LEN = 12 + const val GCM_TAG_BITS = 128 + } +} + +private class InFlightRefresh { + val latch = CountDownLatch(1) + @Volatile + var succeeded: Boolean = false +} + +private data class PendingRotatedSession( + val epoch: Long, + val serverResponseJson: String, + val nowMs: Long, +) + +private class EndpointCoordination { + val lock = Any() + var epoch: Long = 0L + var inFlight: InFlightRefresh? = null + var pendingAttemptToken: String? = null + var pendingAttemptId: String? = null + var pendingRotated: PendingRotatedSession? = null + + fun clearPendingRotation() { + pendingAttemptToken = null + pendingAttemptId = null + pendingRotated = null + } +} + +private object AuthSessionCoordinator { + private val coords = ConcurrentHashMap() + + fun forEndpoint(filesDir: String, canonicalEndpoint: String): EndpointCoordination { + val canonicalFile = runCatching { + File(filesDir, "datastore/auth-sessions.preferences_pb").canonicalPath + }.getOrElse { File(filesDir, "datastore/auth-sessions.preferences_pb").absolutePath } + return coords.computeIfAbsent("$canonicalFile|$canonicalEndpoint") { EndpointCoordination() } + } +} + +/** + * In-place reader/writer for `0.27.5` Jetpack Preferences DataStore + * (`/datastore/auth-sessions.preferences_pb`) with process-wide + * per-endpoint single-flight refresh coordination and `CookieCleaner` support. + */ +class AuthSessionStore( + private val filesDir: String, + private val cipher: AuthTokenCipher = AuthTokenCipher(), + private val cookieCleaner: CookieCleaner = AndroidCookieCleaner(), + private val defaultTransport: RefreshTransport = HttpUrlConnectionRefreshTransport(), + private val persistence: SessionPersistence = SessionPersistence { dir, key, enc -> + NativeBridge.nativeDataStoreSetString(dir, key, enc) + }, +) { + constructor( + context: Context, + cipher: AuthTokenCipher = AuthTokenCipher(), + cookieCleaner: CookieCleaner = AndroidCookieCleaner(), + defaultTransport: RefreshTransport = HttpUrlConnectionRefreshTransport( + appVersion = resolveAppVersion(context), + ), + persistence: SessionPersistence = SessionPersistence { dir, key, enc -> + NativeBridge.nativeDataStoreSetString(dir, key, enc) + }, + ) : this( + filesDir = context.filesDir.absolutePath, + cipher = cipher, + cookieCleaner = cookieCleaner, + defaultTransport = defaultTransport, + persistence = persistence, + ) + private fun coord(canonicalEndpoint: String): EndpointCoordination = + AuthSessionCoordinator.forEndpoint(filesDir, canonicalEndpoint) + + fun currentEpoch(endpoint: String): Long { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val c = coord(canonical) + return synchronized(c.lock) { c.epoch } + } + + /** + * Atomically reads `auth-installation-id` or persists [fallbackUuid] inside a + * single Rust per-file lock critical section. Throws [IllegalStateException] + * on `"ERROR:..."` so a corrupt DataStore never silently overwrites disk. + */ + fun getOrCreateInstallationId(fallbackUuid: String = UUID.randomUUID().toString()): String { + val result = NativeBridge.nativeDataStoreGetOrCreateString( + filesDir, + INSTALLATION_ID_KEY, + fallbackUuid, + ) + if (result.startsWith("OK:")) { + val persisted = result.substring(3) + if (persisted.isNotEmpty()) return persisted + } + throw IllegalStateException("Refusing to overwrite installationId on DataStore error: $result") + } + + fun storeServerResponse(endpoint: String, serverResponseJson: String, nowMs: Long): Boolean { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val storedJson = NativeBridge.nativePrepareAuthSessionJson(serverResponseJson, nowMs) + ?: return false + val encrypted = cipher.encrypt(canonical, storedJson) + if (!NativeBridge.nativeValidateV1Ciphertext(encrypted)) return false + val c = coord(canonical) + return synchronized(c.lock) { + c.epoch += 1L + c.clearPendingRotation() + val written = persistence.writeEncryptedSession(filesDir, NativeBridge.nativeAuthTokenKey(canonical), encrypted) + if (written) { + clearPersistedRefreshAttemptUnlocked(canonical) + } + written + } + } + + fun storeRefreshedSessionIfEpochMatches( + endpoint: String, + startEpoch: Long, + serverResponseJson: String, + nowMs: Long, + ): Boolean { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val storedJson = NativeBridge.nativePrepareAuthSessionJson(serverResponseJson, nowMs) + ?: return false + val encrypted = cipher.encrypt(canonical, storedJson) + if (!NativeBridge.nativeValidateV1Ciphertext(encrypted)) return false + val c = coord(canonical) + return synchronized(c.lock) { + if (c.epoch != startEpoch) { + return@synchronized false + } + val written = persistence.writeEncryptedSession(filesDir, NativeBridge.nativeAuthTokenKey(canonical), encrypted) + if (written) { + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + } + written + } + } + + /** + * Two-argument convenience overload for callers that do not inspect `attemptId`. + */ + fun refreshSession( + endpoint: String, + transport: (canonicalEndpoint: String, refreshToken: String) -> RefreshResult, + ): Boolean = refreshSession( + endpoint = endpoint, + transport = RefreshTransport { canonical, token, _ -> transport(canonical, token) }, + ) + + /** + * Process-wide single-flight refresh per `(datastoreFile, canonicalEndpoint)`. + * + * - Concurrent callers share one in-flight transport call. + * - Retries for the same logical `refreshToken` reuse the same lowercase UUID + * `x-affine-refresh-attempt` header so the server can recover idempotently. + * - If a `200 OK` rotated session fails to persist to disk, it is retained in + * memory for the current `epoch` and flushed on the next `refreshSession` + * call with zero network requests. + */ + fun refreshSession( + endpoint: String, + transport: RefreshTransport = defaultTransport, + ): Boolean { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val c = coord(canonical) + var waiter: InFlightRefresh? = null + var owned: InFlightRefresh? = null + var startEpoch = 0L + var refreshToken: String? = null + var attemptId: String? = null + var pendingToFlush: PendingRotatedSession? = null + + synchronized(c.lock) { + val existing = c.inFlight + if (existing != null) { + waiter = existing + } else { + val cached = c.pendingRotated + if (cached != null && cached.epoch == c.epoch) { + startEpoch = c.epoch + pendingToFlush = cached + } else { + if (cached != null) { + c.pendingRotated = null + } + val currentJson = readSessionJsonUnlocked(canonical) ?: return false + val token = NativeBridge.nativeExtractJsonStringField(currentJson, "refreshToken") + ?.takeIf { it.isNotEmpty() } + ?: return false + val reusedAttempt = if (c.pendingAttemptToken == token && c.pendingAttemptId != null) { + c.pendingAttemptId!! + } else { + readPersistedRefreshAttemptUnlocked(canonical, token) ?: run { + val fresh = UUID.randomUUID().toString().lowercase() + persistRefreshAttemptUnlocked(canonical, token, fresh) + fresh + } + } + c.pendingAttemptToken = token + c.pendingAttemptId = reusedAttempt + startEpoch = c.epoch + refreshToken = token + attemptId = reusedAttempt + } + val flight = InFlightRefresh() + c.inFlight = flight + owned = flight + } + } + + if (waiter != null) { + waiter!!.latch.await() + return waiter!!.succeeded + } + + val flight = owned!! + var ok = false + try { + val flush = pendingToFlush + if (flush != null) { + val storedJson = NativeBridge.nativePrepareAuthSessionJson(flush.serverResponseJson, flush.nowMs) + val encrypted = storedJson?.let { cipher.encrypt(canonical, it) } + synchronized(c.lock) { + if (c.epoch == startEpoch && encrypted != null && NativeBridge.nativeValidateV1Ciphertext(encrypted)) { + val written = persistence.writeEncryptedSession(filesDir, NativeBridge.nativeAuthTokenKey(canonical), encrypted) + if (written) { + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + ok = true + } + } + } + } else { + when (val res = transport.refresh(canonical, refreshToken!!, attemptId!!)) { + is RefreshResult.Success -> { + val storedJson = NativeBridge.nativePrepareAuthSessionJson(res.serverResponseJson, res.nowMs) + val encrypted = storedJson?.let { cipher.encrypt(canonical, it) } + synchronized(c.lock) { + if (c.epoch == startEpoch && encrypted != null && NativeBridge.nativeValidateV1Ciphertext(encrypted)) { + c.pendingRotated = PendingRotatedSession(startEpoch, res.serverResponseJson, res.nowMs) + val written = persistence.writeEncryptedSession(filesDir, NativeBridge.nativeAuthTokenKey(canonical), encrypted) + if (written) { + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + ok = true + } + } + } + } + is RefreshResult.Failure -> { + if (!res.errorCode.isNullOrEmpty() && NativeBridge.nativeIsPermanentAuthErrorCode(res.errorCode)) { + var shouldCleanCookies = false + synchronized(c.lock) { + if (c.epoch == startEpoch) { + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + NativeBridge.nativeDataStoreDeleteKey(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + clearLegacyCookieKeysUnlocked(canonical) + shouldCleanCookies = true + } + } + if (shouldCleanCookies) { + cookieCleaner.clearAuthCookies(canonical) + } + } + } + } + } + } finally { + synchronized(c.lock) { + if (c.inFlight === flight) { + c.inFlight = null + } + } + flight.succeeded = ok + flight.latch.countDown() + } + return ok + } + + fun readSessionJson(endpoint: String): String? { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val c = coord(canonical) + return synchronized(c.lock) { readSessionJsonUnlocked(canonical) } + } + + private fun readSessionJsonUnlocked(canonical: String): String? { + val result = NativeBridge.nativeDataStoreReadResult(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + if (!result.startsWith("OK:")) { + return null + } + val encoded = result.substring(3).takeIf { it.isNotEmpty() } ?: return null + val plaintext = cipher.decrypt(canonical, encoded) ?: run { + cipher.reset(canonical) + NativeBridge.nativeDataStoreDeleteKey(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + return null + } + if (!NativeBridge.nativeValidateAuthSessionJson(plaintext)) { + NativeBridge.nativeDataStoreDeleteKey(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + return null + } + return plaintext + } + + fun clearSession(endpoint: String): Boolean = deleteSession(endpoint) + + fun deleteSession(endpoint: String): Boolean { + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val c = coord(canonical) + val deleted = synchronized(c.lock) { + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + val removed = NativeBridge.nativeDataStoreDeleteKey(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + val legacyCleared = clearLegacyCookieKeysUnlocked(canonical) + removed && legacyCleared + } + cookieCleaner.clearAuthCookies(canonical) + return deleted + } + + fun handleRefreshFailure(endpoint: String, errorCode: String?): Boolean { + if (errorCode.isNullOrEmpty() || !NativeBridge.nativeIsPermanentAuthErrorCode(errorCode)) { + return false + } + return deleteSession(endpoint) + } + + fun handleRefreshFailureIfEpochMatches( + endpoint: String, + startEpoch: Long, + errorCode: String?, + ): Boolean { + if (errorCode.isNullOrEmpty() || !NativeBridge.nativeIsPermanentAuthErrorCode(errorCode)) { + return false + } + val canonical = NativeBridge.nativeCanonicalEndpoint(endpoint) + val c = coord(canonical) + val deleted = synchronized(c.lock) { + if (c.epoch != startEpoch) { + return@synchronized false + } + c.epoch += 1L + c.clearPendingRotation() + clearPersistedRefreshAttemptUnlocked(canonical) + val removed = NativeBridge.nativeDataStoreDeleteKey(filesDir, NativeBridge.nativeAuthTokenKey(canonical)) + val legacyCleared = clearLegacyCookieKeysUnlocked(canonical) + removed && legacyCleared + } + if (deleted) { + cookieCleaner.clearAuthCookies(canonical) + } + return deleted + } + + private fun clearLegacyCookieKeysUnlocked(canonicalEndpoint: String): Boolean { + val host = runCatching { URI(canonicalEndpoint).host }.getOrNull()?.takeIf { it.isNotEmpty() } + ?: return true + val appUser = NativeBridge.nativeLegacyAppDataStoreDeleteKey(filesDir, "${host}affine_user_id") + val appCsrf = NativeBridge.nativeLegacyAppDataStoreDeleteKey(filesDir, "${host}affine_csrf_token") + val authUser = NativeBridge.nativeDataStoreDeleteKey(filesDir, "${host}affine_user_id") + val authCsrf = NativeBridge.nativeDataStoreDeleteKey(filesDir, "${host}affine_csrf_token") + return appUser && appCsrf && authUser && authCsrf + } + + private fun attemptKey(canonicalEndpoint: String): String = "$REFRESH_ATTEMPT_KEY_PREFIX$canonicalEndpoint" + + private fun hashTokenDigest(token: String): String { + val digest = java.security.MessageDigest.getInstance("SHA-256") + .digest(token.toByteArray(StandardCharsets.UTF_8)) + val sb = StringBuilder(digest.size * 2) + for (b in digest) { + sb.append(String.format("%02x", b)) + } + return sb.toString() + } + + private fun readPersistedRefreshAttemptUnlocked( + canonicalEndpoint: String, + token: String, + ): String? { + val raw = NativeBridge.nativeDataStoreGetString(filesDir, attemptKey(canonicalEndpoint)) + ?: return null + val sep = raw.indexOf('|') + if (sep <= 0 || sep >= raw.length - 1) { + return null + } + val storedDigest = raw.substring(0, sep) + val storedAttempt = raw.substring(sep + 1) + return if (storedDigest == hashTokenDigest(token) && storedAttempt.isNotEmpty()) { + storedAttempt + } else { + null + } + } + + private fun persistRefreshAttemptUnlocked( + canonicalEndpoint: String, + token: String, + attemptId: String, + ) { + NativeBridge.nativeDataStoreSetString( + filesDir, + attemptKey(canonicalEndpoint), + "${hashTokenDigest(token)}|$attemptId", + ) + } + + private fun clearPersistedRefreshAttemptUnlocked(canonicalEndpoint: String) { + NativeBridge.nativeDataStoreDeleteKey(filesDir, attemptKey(canonicalEndpoint)) + } + + companion object { + const val INSTALLATION_ID_KEY = "auth-installation-id" + const val REFRESH_ATTEMPT_KEY_PREFIX = "auth-refresh-attempt:" + const val CLIENT_KIND_HEADER = "x-affine-client-kind" + const val CLIENT_KIND_VALUE = "native" + const val CLIENT_VERSION_HEADER = "x-affine-version" + const val CLIENT_VERSION_VALUE = "0.27.5" + const val REFRESH_ATTEMPT_HEADER = "x-affine-refresh-attempt" + + @Suppress("DEPRECATION") + fun resolveAppVersion(context: Context): String = runCatching { + context.packageManager + .getPackageInfo(context.packageName, 0) + .versionName + ?.takeIf { it.isNotBlank() } + }.getOrNull() ?: CLIENT_VERSION_VALUE + } +} diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt new file mode 100644 index 0000000000..31ed157ea6 --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt @@ -0,0 +1,272 @@ +package app.affine.pro.host + +import android.annotation.SuppressLint +import android.content.Context +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.webkit.RenderProcessGoneDetail +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import java.io.ByteArrayInputStream +import java.util.concurrent.atomic.AtomicBoolean + +/** + * One-shot upgrade/rollback probe that reads or writes whitelisted `localStorage` + * keys on the legacy Capacitor Android origin (`https://localhost`) with active + * `window.indexedDB.open` / `deleteDatabase` interception, timeout/error/crash + * WebView cleanup, and zero network traffic. Never instantiated by the main app shell. + */ +class LegacyLocalStorageProbe(private val context: Context) { + companion object { + const val LEGACY_ORIGIN = "https://localhost" + const val PROBE_URL = "https://localhost/__affine_probe__" + const val LOCAL_WORKSPACE_KEY = "affine-local-workspace" + const val DEFAULT_TIMEOUT_MS = 5_000L + + /** Delegates allowlist membership directly to `affine-legacy-import` via JNI. */ + fun isAllowedKey(key: String): Boolean = NativeBridge.nativeIsAllowedLegacyLocalStorageKey(key) + + private const val IDB_GUARD_PRELUDE = """ + let idbTouchCount = 0; + const idbBlocked = true; + if (typeof window !== 'undefined' && window.indexedDB) { + const blockIdb = (name) => () => { + idbTouchCount += 1; + throw new Error('AFFINE_IDB_FORBIDDEN:' + name); + }; + try { + Object.defineProperty(window.indexedDB, 'open', { + configurable: true, + value: blockIdb('open'), + }); + Object.defineProperty(window.indexedDB, 'deleteDatabase', { + configurable: true, + value: blockIdb('deleteDatabase'), + }); + } catch (_) { + window.indexedDB.open = blockIdb('open'); + window.indexedDB.deleteDatabase = blockIdb('deleteDatabase'); + } + } + """ + + private fun jsString(raw: String): String { + val escaped = raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + return "\"$escaped\"" + } + + /** + * Filters raw `evaluateJavascript` snapshot JSON in Rust via `affine-legacy-import`'s + * single allowlist, avoiding Android `org.json` stubs and keeping zero allowlist rules + * in Kotlin. + */ + fun filterSnapshotEntries(rawJson: String?): String? { + if (rawJson.isNullOrBlank() || rawJson.trim() == "null") return null + return NativeBridge.nativeFilterLegacyLocalStorageProbe(rawJson) + } + + fun buildCaptureScript(): String { + return """ + (() => { + $IDB_GUARD_PRELUDE + const keys = []; + const entries = {}; + const total = window.localStorage.length; + for (let i = 0; i < total; i += 1) { + const k = window.localStorage.key(i); + if (k !== null) { + keys.push(k); + const v = window.localStorage.getItem(k); + if (v !== null) entries[k] = v; + } + } + keys.sort(); + return { + origin: window.location.origin, + length: total, + keys, + entries, + idbBlocked, + idbTouchCount + }; + })() + """.trimIndent() + } + + fun buildWriteBackScript( + setEntries: Map, + removeKeys: List = emptyList(), + ): String { + require(LOCAL_WORKSPACE_KEY !in removeKeys) { + "affine-local-workspace must be written as \"[]\" in setEntries, never removed" + } + for (k in setEntries.keys) { + require(isAllowedKey(k)) { "non-allowlisted setEntries key: $k" } + } + for (k in removeKeys) { + require(isAllowedKey(k)) { "non-allowlisted removeKeys key: $k" } + } + val setPairs = setEntries.entries + .sortedBy { it.key } + .joinToString(",") { (k, v) -> "[${jsString(k)},${jsString(v)}]" } + val remList = removeKeys.distinct().sorted().joinToString(",") { jsString(it) } + return """ + (() => { + $IDB_GUARD_PRELUDE + const targetSet = [$setPairs]; + const targetRemove = [$remList]; + for (const k of targetRemove) { + if (k === "affine-local-workspace") { + throw new Error('AFFINE_WRITEBACK_REMOVE_FORBIDDEN:' + k); + } + } + for (const [k, v] of targetSet) { + window.localStorage.setItem(k, v); + } + for (const k of targetRemove) { + window.localStorage.removeItem(k); + } + const keys = []; + const entries = {}; + const total = window.localStorage.length; + for (let i = 0; i < total; i += 1) { + const k = window.localStorage.key(i); + if (k !== null) { + keys.push(k); + const v = window.localStorage.getItem(k); + if (v !== null) entries[k] = v; + } + } + let verified = true; + for (const [k, v] of targetSet) { + if (entries[k] !== v) verified = false; + } + const removedKeys = []; + for (const k of targetRemove) { + if (window.localStorage.getItem(k) === null) { + removedKeys.push(k); + } else { + verified = false; + } + } + keys.sort(); + removedKeys.sort(); + return { + origin: window.location.origin, + length: total, + keys, + entries, + removedKeys, + verified, + idbBlocked, + idbTouchCount + }; + })() + """.trimIndent() + } + } + + fun capture( + timeoutMs: Long = DEFAULT_TIMEOUT_MS, + onResult: (String?) -> Unit, + ) { + runIsolatedScript(buildCaptureScript(), timeoutMs) { raw -> + onResult(filterSnapshotEntries(raw)) + } + } + + fun writeBackLegacyLocalStorage( + setEntries: Map, + removeKeys: List = emptyList(), + timeoutMs: Long = DEFAULT_TIMEOUT_MS, + onResult: (String?) -> Unit, + ) { + runIsolatedScript(buildWriteBackScript(setEntries, removeKeys), timeoutMs) { raw -> + onResult(filterSnapshotEntries(raw)) + } + } + + @SuppressLint("SetJavaScriptEnabled") + private fun runIsolatedScript( + script: String, + timeoutMs: Long, + onResult: (String?) -> Unit, + ) { + val webView = WebView(context) + webView.settings.javaScriptEnabled = true + webView.settings.domStorageEnabled = true + val completed = AtomicBoolean(false) + val mainHandler = Handler(Looper.getMainLooper()) + + lateinit var timeoutRunnable: Runnable + fun finish(result: String?) { + if (!completed.compareAndSet(false, true)) return + mainHandler.removeCallbacks(timeoutRunnable) + runCatching { webView.stopLoading() } + runCatching { webView.destroy() } + onResult(result) + } + + timeoutRunnable = Runnable { finish(null) } + mainHandler.postDelayed(timeoutRunnable, timeoutMs.coerceAtLeast(1L)) + + webView.webViewClient = object : WebViewClient() { + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest?, + ): WebResourceResponse? { + if (request?.url?.toString() == PROBE_URL) { + return WebResourceResponse( + "text/html", + "utf-8", + ByteArrayInputStream("".toByteArray()), + ) + } + return WebResourceResponse( + "text/plain", + "utf-8", + 204, + "No Content", + emptyMap(), + ByteArrayInputStream(ByteArray(0)), + ) + } + + override fun onPageFinished(view: WebView?, url: String?) { + if (completed.get()) return + webView.evaluateJavascript(script) { raw -> finish(raw) } + } + + override fun onReceivedError( + view: WebView?, + request: WebResourceRequest?, + error: WebResourceError?, + ) { + if (request?.isForMainFrame == true) { + finish(null) + } + } + + override fun onRenderProcessGone( + view: WebView?, + detail: RenderProcessGoneDetail?, + ): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + finish(null) + return true + } + return false + } + } + + webView.loadUrl(PROBE_URL) + } +} diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt new file mode 100644 index 0000000000..76d653ed12 --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt @@ -0,0 +1,4237 @@ +package app.affine.pro.host + +import android.annotation.TargetApi +import android.app.Activity +import android.content.ClipData +import android.content.ClipDescription +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect +import android.graphics.RectF +import android.graphics.pdf.PdfRenderer +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.ParcelFileDescriptor +import android.text.InputType +import android.text.Layout +import android.text.StaticLayout +import android.text.TextDirectionHeuristics +import android.text.TextPaint +import java.text.BreakIterator +import android.util.SparseArray +import android.view.ActionMode +import android.view.Choreographer +import android.view.KeyEvent +import android.view.Menu +import android.view.MenuItem +import android.view.MotionEvent +import android.view.Surface +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.View +import android.view.ViewStructure +import android.view.WindowInsets +import android.view.WindowInsetsAnimation +import android.view.WindowInsetsController +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityNodeProvider +import android.view.autofill.AutofillManager +import android.view.autofill.AutofillValue +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.CompletionInfo +import android.view.inputmethod.CorrectionInfo +import android.view.inputmethod.CursorAnchorInfo +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.ExtractedText +import android.view.inputmethod.ExtractedTextRequest +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputContentInfo +import android.view.inputmethod.InputMethodManager +import android.view.inputmethod.TextAttribute +import android.widget.FrameLayout +import android.widget.Magnifier +import android.window.BackEvent +import android.window.OnBackAnimationCallback +import android.window.OnBackInvokedCallback +import android.window.OnBackInvokedDispatcher + +object NativeBridge { + init { + System.loadLibrary("affine_android_host") + } + + private val wakeupListeners = java.util.concurrent.ConcurrentHashMap Unit>() + + fun registerWakeupListener(handle: Long, listener: () -> Unit) { + if (handle != 0L) { + wakeupListeners[handle] = listener + } + } + + fun unregisterWakeupListener(handle: Long) { + if (handle != 0L) { + wakeupListeners.remove(handle) + } + } + + @JvmStatic + fun onNativeWakeup(handle: Long) { + wakeupListeners[handle]?.invoke() + } + + external fun nativeShouldExposeAutofill(sdkInt: Int): Boolean + external fun nativeCreateHost(): Long + external fun nativeDestroyHost(handle: Long) + external fun nativeSetHasBackDestination(handle: Long, hasDestination: Boolean) + external fun nativeOnSurfaceCreated(handle: Long, surface: Surface) + external fun nativeOnSurfaceChanged(handle: Long, format: Int, widthPx: Int, heightPx: Int) + external fun nativeOnSurfaceDestroyed(handle: Long) + external fun nativeRequestFrame(handle: Long) + external fun nativeGetSurfaceGeneration(handle: Long): Long + external fun nativeIsSurfaceReady(handle: Long): Boolean + external fun nativeHasPendingFrame(handle: Long): Boolean + external fun nativeGetFrameCount(handle: Long): Long + external fun nativeGetRenderBackend(handle: Long): Int + external fun nativeOnSurfaceInsetsPx( + handle: Long, + safeTopPx: Int, + safeRightPx: Int, + safeBottomPx: Int, + safeLeftPx: Int, + imeBottomPx: Int, + density: Float, + ) + external fun nativeOnFrameTick(handle: Long, frameTimeNanos: Long): Int + external fun nativeOnBackGesturePhase( + handle: Long, + phaseCode: Int, + progress: Float, + ): Boolean + external fun nativeOnCommitText(handle: Long, text: String, newCursorPosition: Int) + external fun nativeOnSetComposingText(handle: Long, text: String, newCursorPosition: Int) + external fun nativeOnSetComposingRegion(handle: Long, start: Int, end: Int) + external fun nativeOnFinishComposingText(handle: Long) + external fun nativeOnSetSelection(handle: Long, start: Int, end: Int) + external fun nativeOnDeleteSurroundingText(handle: Long, beforeLen: Int, afterLen: Int) + external fun nativeOnDeleteSurroundingTextInCodePoints( + handle: Long, + beforeLen: Int, + afterLen: Int, + ): Boolean + external fun nativeOnReplaceText( + handle: Long, + start: Int, + end: Int, + text: String, + newCursorPosition: Int, + ): Boolean + external fun nativeGetUtf16Length(handle: Long): Int + external fun nativeGetUtf16Text(handle: Long): String + external fun nativeHasPendingTimer(handle: Long): Boolean + external fun nativeNextTimerDelayMs(handle: Long): Long + external fun nativeIsDarkTheme(handle: Long): Boolean + external fun nativeGetUtf16Unit(handle: Long, index: Int): Int + external fun nativeGetSelectionStart(handle: Long): Int + external fun nativeGetSelectionEnd(handle: Long): Int + external fun nativeGetComposingStart(handle: Long): Int + external fun nativeGetComposingEnd(handle: Long): Int + + // Legacy localStorage upgrade import & rollback write-back (zero IndexedDB). + external fun nativeIsAllowedLegacyLocalStorageKey(key: String): Boolean + external fun nativeFilterLegacyLocalStorageProbe(rawJson: String): String? + external fun nativeImportLegacyLocalStorageProbe( + handle: Long, + payloadJson: String, + allowedKeysCsv: String, + ): Boolean + external fun nativeCanCreateDefaultWorkspace(handle: Long): Boolean + external fun nativeGetAllowlistedWorkspaceIdsJson(handle: Long): String + external fun nativeGetPreservedLocalWorkspaceRaw(handle: Long): String? + external fun nativePlanLegacyLocalStorageWriteBack(handle: Long): String? + external fun nativeVerifyLegacyWriteBack( + expectedSetJson: String, + expectedRemoveJson: String, + readbackJson: String, + ): Boolean + + // In-place SQLite WAL co-storage (allowlist-only, never scans disk *.db). + external fun nativeConnectWorkspace( + handle: Long, + filesDir: String, + peer: String, + spaceId: String, + ): String? + external fun nativeOpenUserspace( + handle: Long, + filesDir: String, + peer: String, + userId: String, + ): String? + external fun nativeStoragePushUpdateB64( + handle: Long, + connectionKey: String, + docId: String, + updateB64: String, + nowMs: Long, + ): Long + external fun nativeStorageGetDocB64( + handle: Long, + connectionKey: String, + docId: String, + ): String? + external fun nativeStorageGetBlobB64( + handle: Long, + connectionKey: String, + blobKey: String, + ): String? + external fun nativeStorageCheckpoint(handle: Long, connectionKey: String): Boolean + external fun nativeStorageCheckpointAllPassive(handle: Long): Int + external fun nativeStorageClose(handle: Long, connectionKey: String): Boolean + + // Jetpack Preferences DataStore (`auth-sessions`) & `v1:` AES-GCM auth contract. + external fun nativeCanonicalEndpoint(endpoint: String): String + external fun nativeAuthTokenKey(endpoint: String): String + external fun nativeKeystoreAlias(endpoint: String): String + external fun nativeDataStoreGetString(filesDir: String, key: String): String? + external fun nativeDataStoreReadResult(filesDir: String, key: String): String + external fun nativeDataStoreGetOrCreateString( + filesDir: String, + key: String, + candidateValue: String, + ): String + external fun nativeDataStoreSetString(filesDir: String, key: String, value: String): Boolean + external fun nativeDataStoreDeleteKey(filesDir: String, key: String): Boolean + external fun nativeLegacyAppDataStoreDeleteKey(filesDir: String, key: String): Boolean + external fun nativePrepareAuthSessionJson(responseJson: String, nowMs: Long): String? + external fun nativeValidateAuthSessionJson(storedJson: String): Boolean + external fun nativeValidateV1Ciphertext(encoded: String): Boolean + external fun nativeIsPermanentAuthErrorCode(code: String): Boolean + external fun nativeExtractJsonStringField(json: String, field: String): String? + external fun nativeJsonStringArrayLen(json: String): Int + external fun nativeJsonStringArrayGet(json: String, index: Int): String? + + // Native selection teardrop handles, magnifier loupe, and context action menu. + external fun nativeSetSelectionViewport( + handle: Long, + width: Float, + height: Float, + density: Float, + ) + external fun nativeUpdateSelectionOverlay( + handle: Long, + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + directionCode: Int, + hasSelection: Boolean, + ) + external fun nativeApplyTextDragEndpoints( + handle: Long, + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + directionCode: Int, + activeHandleCode: Int, + ) + external fun nativeSelectionBeginDrag(handle: Long, touchX: Float, touchY: Float): Int + external fun nativeSelectionEndDrag(handle: Long): Boolean + external fun nativeSelectionCancelDrag(handle: Long) + external fun nativeClearSelectionOverlay(handle: Long) + external fun nativeGetSelectionOverlayJson(handle: Long): String + external fun nativeGetSelectionOverlayGeometry(handle: Long): FloatArray? + external fun nativeFillSelectionOverlayGeometry(handle: Long, outBuffer: FloatArray): Boolean + + // Surface recreation state preservation, effective IME insets, and Vulkan -> GLES3 recovery. + external fun nativeSetSurfaceScrollOffset(handle: Long, scrollX: Float, scrollY: Float) + external fun nativeGetSurfaceScrollY(handle: Long): Float + external fun nativeGetSurfaceDensity(handle: Long): Float + external fun nativeGetTextureGeneration(handle: Long): Long + external fun nativeGetEffectiveImeBottomDp(handle: Long): Float + external fun nativeSelectRenderBackend( + handle: Long, + vulkanAvailable: Boolean, + gles3Available: Boolean, + ): Int + external fun nativeReportVulkanDeviceLost(handle: Long): Int + + // API 26+ AutofillManager virtual view structure and value write-back. + external fun nativeConfigureAutofillSdk(handle: Long, sdkInt: Int): Boolean + external fun nativeUpsertAutofillField( + handle: Long, + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int, + ): Boolean + external fun nativeFocusAutofillField(handle: Long, autofillId: Int): Int + external fun nativeGetFocusedAutofillFieldId(handle: Long): Int + external fun nativeSetAutofillFieldText(handle: Long, autofillId: Int, text: String): Boolean + external fun nativeApplyAutofillValue(handle: Long, autofillId: Int, value: String): Boolean + external fun nativeGetAutofillValue(handle: Long, autofillId: Int): String? + external fun nativeGetAutofillValueByKind(handle: Long, kindCode: Int): String? + external fun nativeCommitAutofill(handle: Long): Boolean + external fun nativeCancelAutofill(handle: Long): Boolean + external fun nativeClearAutofillFields(handle: Long) + external fun nativeGetAutofillStructureJson(handle: Long): String + + // Predictive back API-level dispatch and destination navigation stack. + external fun nativeBackDispatchMode(sdkInt: Int): Int + external fun nativePushDestination(handle: Long, route: String): Boolean + external fun nativeGetCurrentDestination(handle: Long): String? + external fun nativeSetBackStackDepth(handle: Long, depth: Int) + external fun nativeGetBackStackDepth(handle: Long): Int + + // Native PdfRenderer page validation, cache key, and ARGB_8888 -> RGBA8 conversion. + external fun nativeValidatePdfPageRequest( + pageIndex: Int, + pageCount: Int, + widthPx: Int, + heightPx: Int, + ): Boolean + external fun nativePdfPageCacheKey( + docId: String, + pageIndex: Int, + widthPx: Int, + heightPx: Int, + dpiBucket: Int, + ): String + external fun nativePdfConvertArgbToRgba( + argbPixels: IntArray, + widthPx: Int, + heightPx: Int, + ): ByteArray? + + // Live pure-Rust GPU BlockSuite editor mount, touch/key dispatch, and H-S2 IME sync. + external fun nativeLoadShowcaseDocument(handle: Long) + external fun nativeResetEmptyDocument(handle: Long) + external fun nativeSetFormFactor(handle: Long, smallestWidthDp: Int) + external fun nativeIsEdgelessReadonly(handle: Long): Boolean + external fun nativeIsDatabaseReadonly(handle: Long): Boolean + external fun nativeIsPageReadonly(handle: Long): Boolean + external fun nativeSetEditorMode(handle: Long, modeCode: Int) + external fun nativeOnTouchEvent( + handle: Long, + pointerId: Long, + phase: Int, + xDp: Float, + yDp: Float, + ) + external fun nativeOnScrollWheel( + handle: Long, + xDp: Float, + yDp: Float, + deltaX: Float, + deltaY: Float, + ) + + external fun nativeHandleBack(handle: Long): Boolean + external fun nativeCreateShellHost( + languageTag: String, + nowMs: Long, + utcOffsetMinutes: Int, + dark: Boolean, + ): Long + external fun nativeShellRoute(handle: Long): Int + external fun nativeShellAccessibilityJson(handle: Long): String? + external fun nativeShellMountWorkspace( + handle: Long, + filesDir: String, + spaceType: String, + peer: String, + spaceId: String, + name: String, + nowMs: Long, + ): Boolean + external fun nativeShellFlushWorkspace(handle: Long): Long + external fun nativeShellSetSystemDark(handle: Long, dark: Boolean): Boolean + external fun nativeTakePendingOpenUrl(handle: Long): String? + external fun nativeOnKeyEvent( + handle: Long, + keyCode: Int, + shift: Boolean, + ctrl: Boolean, + alt: Boolean, + ): Boolean + external fun nativeGetTextInputChangeSeq(handle: Long): Long + external fun nativeGetFocusedBlockHash(handle: Long): Long + external fun nativeWantsSoftwareKeyboard(handle: Long): Boolean + external fun nativeTakeSoftwareKeyboardRequest(handle: Long): Boolean + external fun nativeWantsCodeInput(handle: Long): Boolean + external fun nativeGetCaretRectDpX(handle: Long): Float + external fun nativeGetCaretRectDpY(handle: Long): Float + external fun nativeGetCaretRectDpHeight(handle: Long): Float + + // Document-level selection geometry, cross-block drag, authoritative actions, and multi-MIME clipboard. + external fun nativeFillDocumentSelectionGeometry(handle: Long, outBuffer: FloatArray): Boolean + external fun nativeGetSelectionMenuRequestSeq(handle: Long): Long + external fun nativeDocSelectionBeginDrag(handle: Long, handleKind: Int): Boolean + external fun nativeDocSelectionUpdateDrag(handle: Long, xDp: Float, yDp: Float): Boolean + external fun nativeDocSelectionEndDrag(handle: Long) + external fun nativeDocSelectionCancelDrag(handle: Long) + external fun nativeSelectionActionCopy(handle: Long) + external fun nativeSelectionActionCut(handle: Long) + external fun nativeSelectionActionPaste( + handle: Long, + plain: String?, + html: String?, + markdown: String?, + snapshot: String?, + ) + external fun nativeSelectionActionSelectAll(handle: Long) + external fun nativeTakePendingClipboardJson(handle: Long): String? + external fun nativeSetPageReadonly(handle: Long, readonly: Boolean) + external fun nativeShareEnqueue( + handle: Long, + id: String, + kind: Int, + title: String, + content: String, + mimeType: String, + ): Boolean + external fun nativeShareEnqueueBytes( + handle: Long, + id: String, + kind: Int, + title: String, + content: String, + mimeType: String, + attachmentBytes: ByteArray?, + ): Boolean + external fun nativeSharePendingCount(handle: Long): Int + external fun nativeShareIsConsumed(handle: Long, id: String): Boolean + external fun nativeShareIsDurablyCommitted( + handle: Long, + workspaceStorageKey: String, + shareId: String, + ): Boolean + external fun nativeShareDrainJson(handle: Long): String? + external fun nativeGetActivePageSnapshotJson(handle: Long): String? + external fun nativeIngestSharedItems( + handle: Long, + targetWorkspaceKey: String = "", + targetDocId: String = "", + nowMs: Long = 0L, + ): Int +} + +private fun drainPendingOpenUrl(context: Context, handle: Long) { + if (handle == 0L) return + while (true) { + val pendingUrl = NativeBridge.nativeTakePendingOpenUrl(handle)?.trim() + if (pendingUrl.isNullOrEmpty()) break + if (pendingUrl.startsWith("https://") || pendingUrl.startsWith("http://")) { + runCatching { + context.startActivity( + android.content.Intent( + android.content.Intent.ACTION_VIEW, + android.net.Uri.parse(pendingUrl), + ).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), + ) + } + } + } +} + +/** + * Testable clipboard bridge wrapping Android `ClipboardManager` so `Copy`, `Cut`, + * and `Paste` interact with the system clipboard without losing text on `Cut`. + */ +interface HostClipboard { + fun setPlainText(label: String, text: String): Boolean + fun getPlainText(): String? + fun hasPlainText(): Boolean = !getPlainText().isNullOrEmpty() + fun setRichClip(label: String, plain: String, html: String?): Boolean = + setPlainText(label, plain) + fun getRichClip(): Pair = Pair(getPlainText(), null) +} + +class AndroidClipboardAdapter( + private val manager: ClipboardManager?, +) : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean { + val cm = manager ?: return false + return try { + cm.setPrimaryClip(ClipData.newPlainText(label, text)) + true + } catch (_: Throwable) { + false + } + } + + override fun setRichClip(label: String, plain: String, html: String?): Boolean { + val cm = manager ?: return false + if (!html.isNullOrEmpty()) { + try { + cm.setPrimaryClip(ClipData.newHtmlText(label, plain, html)) + return true + } catch (_: Throwable) { + // Fall back to plain text if oversized HTML exceeds Binder transaction limits. + } + } + return setPlainText(label, plain) + } + + override fun getPlainText(): String? { + val cm = manager ?: return null + return try { + val clip = cm.primaryClip ?: return null + if (clip.itemCount <= 0) return null + clip.getItemAt(0)?.text?.toString() + } catch (_: Throwable) { + null + } + } + + override fun getRichClip(): Pair { + val cm = manager ?: return Pair(null, null) + return try { + val clip = cm.primaryClip ?: return Pair(null, null) + if (clip.itemCount <= 0) return Pair(null, null) + val item = clip.getItemAt(0) ?: return Pair(null, null) + Pair(item.text?.toString(), item.htmlText) + } catch (_: Throwable) { + Pair(null, null) + } + } + + override fun hasPlainText(): Boolean { + val cm = manager ?: return false + return try { + if (!cm.hasPrimaryClip()) return false + val desc = cm.primaryClipDescription ?: return false + desc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) || + desc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML) + } catch (_: Throwable) { + false + } + } +} + +/** + * Pure Kotlin IME controller backed directly by `AndroidHostState` over JNI as + * the single source of truth for text, selection, and composing spans. + */ +class AffineImeController( + private val handleProvider: () -> Long, + private val onMutated: () -> Unit, + private val onTextEdited: (String) -> Unit, +) { + constructor(handleProvider: () -> Long) : this(handleProvider, {}, {}) + constructor(handleProvider: () -> Long, onMutated: () -> Unit) : this(handleProvider, onMutated, {}) + + fun currentText(): String = readText() + + fun commitText(text: String, newCursorPosition: Int): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + NativeBridge.nativeOnCommitText(handle, text, newCursorPosition) + onMutated() + onTextEdited(currentText()) + return true + } + + fun setComposingText(text: String, newCursorPosition: Int): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + NativeBridge.nativeOnSetComposingText(handle, text, newCursorPosition) + onMutated() + onTextEdited(currentText()) + return true + } + + fun setComposingRegion(start: Int, end: Int): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + NativeBridge.nativeOnSetComposingRegion(handle, start, end) + onMutated() + return true + } + + fun finishComposingText(): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val hadComposing = NativeBridge.nativeGetComposingStart(handle) >= 0 + NativeBridge.nativeOnFinishComposingText(handle) + if (hadComposing) { + onMutated() + onTextEdited(currentText()) + } + return true + } + + fun setSelection(start: Int, end: Int): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + if ( + start == NativeBridge.nativeGetSelectionStart(handle) && + end == NativeBridge.nativeGetSelectionEnd(handle) + ) { + return true + } + NativeBridge.nativeOnSetSelection(handle, start, end) + onMutated() + return true + } + + fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + val handle = handleProvider() + if (handle == 0L || beforeLength < 0 || afterLength < 0) return false + NativeBridge.nativeOnDeleteSurroundingText(handle, beforeLength, afterLength) + onMutated() + onTextEdited(currentText()) + return true + } + + fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean { + val handle = handleProvider() + if (handle == 0L || beforeLength < 0 || afterLength < 0) return false + val ok = NativeBridge.nativeOnDeleteSurroundingTextInCodePoints(handle, beforeLength, afterLength) + if (ok) { + onMutated() + onTextEdited(currentText()) + } + return ok + } + + fun replaceText(start: Int, end: Int, text: String, newCursorPosition: Int): Boolean { + val handle = handleProvider() + if (handle == 0L || start < 0 || end < 0) return false + val ok = NativeBridge.nativeOnReplaceText(handle, start, end, text, newCursorPosition) + if (ok) { + onMutated() + onTextEdited(currentText()) + } + return ok + } + + fun readText(): String { + val handle = handleProvider() + if (handle == 0L) return "" + return NativeBridge.nativeGetUtf16Text(handle) + } + + fun selectionStart(): Int { + val handle = handleProvider() + return if (handle == 0L) 0 else NativeBridge.nativeGetSelectionStart(handle) + } + + fun selectionEnd(): Int { + val handle = handleProvider() + return if (handle == 0L) 0 else NativeBridge.nativeGetSelectionEnd(handle) + } + + fun composingStart(): Int { + val handle = handleProvider() + return if (handle == 0L) -1 else NativeBridge.nativeGetComposingStart(handle) + } + + fun composingEnd(): Int { + val handle = handleProvider() + return if (handle == 0L) -1 else NativeBridge.nativeGetComposingEnd(handle) + } + + fun getTextBeforeCursor(length: Int): String { + if (length <= 0) return "" + val text = readText() + val selStart = selectionStart().coerceIn(0, text.length) + val take = length.coerceAtMost(selStart) + return text.substring(selStart - take, selStart) + } + + fun getTextAfterCursor(length: Int): String { + if (length <= 0) return "" + val text = readText() + val selEnd = selectionEnd().coerceIn(0, text.length) + val take = length.coerceAtMost(text.length - selEnd) + return text.substring(selEnd, selEnd + take) + } + + fun getSelectedText(): String? { + val text = readText() + val selStart = selectionStart().coerceIn(0, text.length) + val selEnd = selectionEnd().coerceIn(selStart, text.length) + return if (selStart == selEnd) null else text.substring(selStart, selEnd) + } + + fun sendKeyEvent(keyCode: Int, shift: Boolean, ctrl: Boolean, alt: Boolean): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val handled = NativeBridge.nativeOnKeyEvent(handle, keyCode, shift, ctrl, alt) + if (handled) { + onMutated() + onTextEdited(currentText()) + } + return handled + } + + fun textInputChangeSeq(): Long { + val handle = handleProvider() + return if (handle == 0L) 0L else NativeBridge.nativeGetTextInputChangeSeq(handle) + } + + fun focusedBlockHash(): Long { + val handle = handleProvider() + return if (handle == 0L) 0L else NativeBridge.nativeGetFocusedBlockHash(handle) + } +} + +/** + * Direct `InputConnection` implementation backed solely by `AffineImeController` + * and Rust `AndroidHostState` with zero Kotlin `Editable` mirror buffer. + */ +class AffineInputConnection( + private val ime: AffineImeController, + private val onContextMenuAction: (Int) -> Boolean = { false }, + private val onCursorUpdatesRequested: (Int) -> Unit = {}, + private val isActiveSession: () -> Boolean = { true }, +) : InputConnection { + private var batchEditDepth: Int = 0 + private var cursorUpdateMonitor: Boolean = false + + override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ime.getTextBeforeCursor(n) + + override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ime.getTextAfterCursor(n) + + override fun getSelectedText(flags: Int): CharSequence? = ime.getSelectedText() + + override fun getCursorCapsMode(reqModes: Int): Int = 0 + + override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText { + val text = ime.readText() + return ExtractedText().apply { + this.text = text + startOffset = 0 + selectionStart = ime.selectionStart().coerceIn(0, text.length) + selectionEnd = ime.selectionEnd().coerceIn(selectionStart, text.length) + } + } + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean = + if (isActiveSession()) ime.deleteSurroundingText(beforeLength, afterLength) else false + + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean = + if (isActiveSession()) ime.deleteSurroundingTextInCodePoints(beforeLength, afterLength) else false + + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = + if (isActiveSession()) ime.setComposingText(text?.toString() ?: "", newCursorPosition) else false + + override fun setComposingText( + text: CharSequence, + newCursorPosition: Int, + textAttribute: TextAttribute?, + ): Boolean = if (isActiveSession()) ime.setComposingText(text.toString(), newCursorPosition) else false + + override fun setComposingRegion(start: Int, end: Int): Boolean = + if (isActiveSession()) ime.setComposingRegion(start, end) else false + + override fun setComposingRegion(start: Int, end: Int, textAttribute: TextAttribute?): Boolean = + if (isActiveSession()) ime.setComposingRegion(start, end) else false + + override fun finishComposingText(): Boolean = + if (isActiveSession()) ime.finishComposingText() else false + + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean = + if (isActiveSession()) ime.commitText(text?.toString() ?: "", newCursorPosition) else false + + override fun commitText( + text: CharSequence, + newCursorPosition: Int, + textAttribute: TextAttribute?, + ): Boolean = if (isActiveSession()) ime.commitText(text.toString(), newCursorPosition) else false + + override fun replaceText( + start: Int, + end: Int, + text: CharSequence, + newCursorPosition: Int, + textAttribute: TextAttribute?, + ): Boolean = if (isActiveSession()) ime.replaceText(start, end, text.toString(), newCursorPosition) else false + + override fun setSelection(start: Int, end: Int): Boolean = + if (isActiveSession()) ime.setSelection(start, end) else false + + override fun beginBatchEdit(): Boolean { + batchEditDepth += 1 + return true + } + + override fun endBatchEdit(): Boolean { + if (batchEditDepth > 0) { + batchEditDepth -= 1 + } + return batchEditDepth > 0 + } + + override fun closeConnection() { + finishComposingText() + batchEditDepth = 0 + } + + override fun getHandler(): Handler? = null + + override fun commitCompletion(text: CompletionInfo?): Boolean = false + + override fun commitCorrection(correctionInfo: CorrectionInfo?): Boolean = false + + override fun commitContent( + inputContentInfo: InputContentInfo, + flags: Int, + opts: Bundle?, + ): Boolean = false + + override fun performEditorAction(editorAction: Int): Boolean = false + + override fun performContextMenuAction(id: Int): Boolean { + if (!isActiveSession()) return false + return when (id) { + android.R.id.copy, + android.R.id.cut, + android.R.id.paste, + android.R.id.selectAll -> onContextMenuAction(id) + else -> false + } + } + + override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = false + + override fun sendKeyEvent(event: KeyEvent?): Boolean { + if (!isActiveSession()) return false + if (event == null || event.action != KeyEvent.ACTION_DOWN) return false + if (ime.composingStart() >= 0) return false + val handled = ime.sendKeyEvent( + keyCode = event.keyCode, + shift = event.isShiftPressed, + ctrl = event.isCtrlPressed, + alt = event.isAltPressed, + ) + if (handled) return true + val ch = event.unicodeChar + if (ch > 0 && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed) { + return ime.commitText(String(Character.toChars(ch)), 1) + } + return false + } + + override fun clearMetaKeyStates(states: Int): Boolean = false + + override fun reportFullscreenMode(enabled: Boolean): Boolean = false + + override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean { + cursorUpdateMonitor = (cursorUpdateMode and InputConnection.CURSOR_UPDATE_MONITOR) != 0 + if ((cursorUpdateMode and InputConnection.CURSOR_UPDATE_IMMEDIATE) != 0 || cursorUpdateMonitor) { + onCursorUpdatesRequested(cursorUpdateMode) + } + return true + } +} + +/** + * Selection teardrop handle and magnifier coordinator backed by Rust + * `SelectionOverlayState` without touching `SurfaceHolder.lockCanvas`. + */ +class AndroidSelectionCoordinator( + private val handleProvider: () -> Long, + private val onMutated: () -> Unit = {}, +) { + fun setViewport(width: Float, height: Float, density: Float) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeSetSelectionViewport(handle, width, height, density) + onMutated() + } + + fun updateSelection( + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + rtl: Boolean = false, + hasSelection: Boolean = true, + ) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeUpdateSelectionOverlay( + handle, + startX, + startY, + endX, + endY, + lineHeight, + if (rtl) 1 else 0, + hasSelection, + ) + onMutated() + } + + fun applyTextDragEndpoints( + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + rtl: Boolean = false, + activeHandleCode: Int, + ) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeApplyTextDragEndpoints( + handle, + startX, + startY, + endX, + endY, + lineHeight, + if (rtl) 1 else 0, + activeHandleCode, + ) + onMutated() + } + + fun beginDrag(touchX: Float, touchY: Float): Int { + val handle = handleProvider() + if (handle == 0L) return 0 + val hit = NativeBridge.nativeSelectionBeginDrag(handle, touchX, touchY) + if (hit != 0) onMutated() + return hit + } + + fun endDrag(): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val hasMenu = NativeBridge.nativeSelectionEndDrag(handle) + onMutated() + return hasMenu + } + + fun cancelDrag() { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeSelectionCancelDrag(handle) + onMutated() + } + + fun clear() { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeClearSelectionOverlay(handle) + onMutated() + } + + fun snapshotJson(): String { + val handle = handleProvider() + return if (handle == 0L) "{}" else NativeBridge.nativeGetSelectionOverlayJson(handle) + } + + fun overlayGeometry(): FloatArray? { + val handle = handleProvider() + return if (handle == 0L) null else NativeBridge.nativeGetSelectionOverlayGeometry(handle) + } + + fun fillOverlayGeometry(outBuffer: FloatArray): Boolean { + val handle = handleProvider() + if (handle == 0L || outBuffer.size < 24) return false + return NativeBridge.nativeFillSelectionOverlayGeometry(handle, outBuffer) + } + + fun performCopy(ime: AffineImeController, clipboard: HostClipboard): String? { + val selected = ime.getSelectedText() ?: return null + if (!clipboard.setPlainText("AFFiNE", selected)) { + return null + } + return selected + } + + fun performCut(ime: AffineImeController, clipboard: HostClipboard): String? { + val selected = ime.getSelectedText() ?: return null + // Always persist to the system clipboard BEFORE deleting text so Cut never loses content. + if (!clipboard.setPlainText("AFFiNE", selected)) { + return null + } + val start = ime.selectionStart() + val end = ime.selectionEnd() + if (start < end) { + ime.replaceText(start, end, "", 1) + onMutated() + } + return selected + } + + fun performPaste(ime: AffineImeController, clipboard: HostClipboard): String? { + val text = clipboard.getPlainText() ?: return null + val start = ime.selectionStart() + val end = ime.selectionEnd() + if (!ime.replaceText(start, end, text, 1)) { + return null + } + onMutated() + return text + } + + fun performSelectAll(ime: AffineImeController): Boolean { + val len = ime.currentText().length + if (len <= 0) return false + val ok = ime.setSelection(0, len) + if (ok) onMutated() + return ok + } + + fun handleContextMenuAction( + id: Int, + ime: AffineImeController, + clipboard: HostClipboard, + ): Boolean = when (id) { + android.R.id.copy -> performCopy(ime, clipboard) != null + android.R.id.cut -> performCut(ime, clipboard) != null + android.R.id.paste -> performPaste(ime, clipboard) != null + android.R.id.selectAll -> performSelectAll(ime) + else -> false + } +} + +/** + * Caret visual geometry in viewport pixels computed by Android `StaticLayout`. + */ +data class CaretBounds( + val x: Float, + val top: Float, + val bottom: Float, + val lineIndex: Int, + val isRtlParagraph: Boolean, +) { + val lineHeight: Float + get() = (bottom - top).coerceAtLeast(1f) + val midY: Float + get() = (top + bottom) * 0.5f +} + +/** + * Single authoritative text layout contract implemented by Android `ShapedTextLayout` + * (`StaticLayout`) on devices and deterministic proportional harnesses in JVM parity tests. + */ +interface TextLayoutAuthority { + val cachedText: String + fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean + fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean = false, + selStart: Int = utf16Offset, + selEnd: Int = utf16Offset, + ): CaretBounds? + fun selectionEndCarets(selStart: Int, selEnd: Int): Pair? + fun fillSelectionEndCarets(selStart: Int, selEnd: Int, out: FloatArray): Boolean { + val pair = selectionEndCarets(selStart, selEnd) ?: return false + val (startCaret, endCaret) = pair + out[0] = startCaret.x + out[1] = startCaret.bottom + out[2] = endCaret.x + out[3] = endCaret.bottom + out[4] = startCaret.lineHeight + out[5] = if (startCaret.isRtlParagraph) 1f else 0f + return true + } + fun closestOffset(x: Float, y: Float): Int + fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int = closestOffset(x, y) +} + +/** + * Pure Kotlin handle-drag gesture controller that keeps `TextLayoutAuthority` + * (`ShapedTextLayout`) as the single source of truth across `ACTION_DOWN`, + * `ACTION_MOVE` (line-midpoint vertical probe + cross-anchor `active_drag` flip), + * `ACTION_UP`, and `ACTION_CANCEL` (never reverting to Rust fallback glyph widths). + */ +class SelectionGestureController( + private val coordinator: AndroidSelectionCoordinator, + private val layoutAuthority: TextLayoutAuthority, + private val selectionStartProvider: () -> Int, + private val selectionEndProvider: () -> Int, + private val onSelectionChanged: (Int, Int) -> Unit, + private val onOverlaySynced: () -> Unit = {}, +) { + private val geomBuf = FloatArray(24) + private val dragCaretsBuf = FloatArray(8) + var draggingHandle: Boolean = false + private set + private var dragAnchorOffset: Int = -1 + private var dragMovingOffset: Int = -1 + private var dragInitialHandle: Int = 0 + private var dragGrabDx: Float = 0f + private var dragGrabDy: Float = 0f + + fun syncSelectionFromLayout( + text: String, + selStart: Int, + selEnd: Int, + viewportWidthPx: Int, + density: Float, + ) { + val hasLayout = layoutAuthority.ensureLayoutReady(text, viewportWidthPx, density) + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + if (lo < hi && hasLayout) { + if (layoutAuthority.fillSelectionEndCarets(lo, hi, dragCaretsBuf)) { + coordinator.updateSelection( + startX = dragCaretsBuf[0], + startY = dragCaretsBuf[1], + endX = dragCaretsBuf[2], + endY = dragCaretsBuf[3], + lineHeight = dragCaretsBuf[4], + rtl = dragCaretsBuf[5] >= 0.5f, + hasSelection = true, + ) + } + } else if (!draggingHandle) { + coordinator.clear() + } + onOverlaySynced() + } + + fun onDown(x: Float, y: Float, density: Float): Int { + val hit = coordinator.beginDrag(x, y) + if (hit == 0) return 0 + draggingHandle = true + dragInitialHandle = hit + val selStart = selectionStartProvider() + val selEnd = selectionEndProvider() + dragAnchorOffset = if (hit == 1) selEnd else selStart + val grabbedOffset = if (hit == 1) selStart else selEnd + dragMovingOffset = grabbedOffset + val caret = layoutAuthority.caretBounds( + utf16Offset = grabbedOffset, + isSelectionEnd = hit == 2, + selStart = selStart, + selEnd = selEnd, + ) + if (caret != null) { + // Anchor vertical grab offset to the visual line's vertical midpoint (never getLineBottom), + // so multi-line line-0 handles never jump into line 1 on stationary or horizontal drags. + dragGrabDx = caret.x - x + dragGrabDy = caret.midY - y + } else if (coordinator.fillOverlayGeometry(geomBuf)) { + val ax = if (hit == 1) geomBuf[3] else geomBuf[9] + val tipY = if (hit == 1) geomBuf[4] else geomBuf[10] + val midY = tipY - 12f * density.coerceAtLeast(1f) + dragGrabDx = ax - x + dragGrabDy = midY - y + } + return hit + } + + fun onMove(x: Float, y: Float): Boolean { + if (!draggingHandle) return false + if (dragAnchorOffset >= 0 && layoutAuthority.cachedText.isNotEmpty()) { + val probeX = x + dragGrabDx + val probeY = y + dragGrabDy + val targetOff = layoutAuthority.closestOffset(probeX, probeY, dragMovingOffset) + dragMovingOffset = targetOff + val lo = minOf(dragAnchorOffset, targetOff) + val hi = maxOf(dragAnchorOffset, targetOff) + val activeHandleCode = when { + targetOff < dragAnchorOffset -> 1 + targetOff > dragAnchorOffset -> 2 + else -> dragInitialHandle + } + onSelectionChanged(lo, hi) + if (layoutAuthority.fillSelectionEndCarets(lo, hi, dragCaretsBuf)) { + coordinator.applyTextDragEndpoints( + startX = dragCaretsBuf[0], + startY = dragCaretsBuf[1], + endX = dragCaretsBuf[2], + endY = dragCaretsBuf[3], + lineHeight = dragCaretsBuf[4], + rtl = dragCaretsBuf[5] >= 0.5f, + activeHandleCode = activeHandleCode, + ) + return true + } + } + return false + } + + fun onUp(viewportWidthPx: Int, density: Float): Boolean { + if (!draggingHandle) return false + draggingHandle = false + dragAnchorOffset = -1 + dragMovingOffset = -1 + dragInitialHandle = 0 + val hasMenu = coordinator.endDrag() + // Re-apply authoritative layout coordinates so Rust end_drag fallback never overwrites them. + syncSelectionFromLayout( + layoutAuthority.cachedText, + selectionStartProvider(), + selectionEndProvider(), + viewportWidthPx, + density, + ) + return hasMenu + } + + fun onCancel(viewportWidthPx: Int, density: Float): Boolean { + if (!draggingHandle) return false + draggingHandle = false + dragAnchorOffset = -1 + dragMovingOffset = -1 + dragInitialHandle = 0 + coordinator.cancelDrag() + syncSelectionFromLayout( + layoutAuthority.cachedText, + selectionStartProvider(), + selectionEndProvider(), + viewportWidthPx, + density, + ) + return true + } +} + +/** + * Coordinates strict isolation between Autofill form fields and the authoritative + * GPU BlockSuite editor (`H-S1`: never writes route text or Autofill credentials + * into `AffineImeController` and never keeps a shadow copy of editor text). + */ +class HostDocumentBufferController( + val documentStore: HostDocumentStore, + private val imeProvider: () -> AffineImeController, + private val autofillProvider: () -> AndroidAutofillController?, + private val onDocumentPreviewUpdated: (String) -> Unit = {}, +) { + var lastPreviewText: String = "" + private set + + fun isAutofillFocused(): Boolean = autofillProvider()?.focusedFieldId() != null + + fun isFocusedAutofillFieldMasked(): Boolean = + autofillProvider()?.isFocusedFieldMasked() == true + + fun currentDocumentText(): String = imeProvider().currentText() + + fun onImeTextEdited(text: String) { + if (isAutofillFocused()) { + autofillProvider()?.onFocusedTextEdited(text) + } + } + + fun restoreDocumentBufferToIme() { + // H-S1: Editor CRDT text is never overwritten by Autofill or host buffers. + val liveText = imeProvider().currentText() + lastPreviewText = liveText + onDocumentPreviewUpdated(liveText) + } + + fun onAutofillFocusChanged(nextFieldId: Int?) { + autofillProvider()?.onFieldFocusChanged(nextFieldId) + } + + fun commitAutofillSession(): Boolean = autofillProvider()?.commit() ?: false + + fun cancelAutofillSession(): Boolean = autofillProvider()?.cancel() ?: false + + fun clearAutofillFields() { + autofillProvider()?.clearFields() + } + + fun onRouteChanged(nextRoute: String) { + if (documentStore.activeDocumentId == nextRoute) return + if (isAutofillFocused()) { + autofillProvider()?.onFieldFocusChanged(null) + } + documentStore.switchTo(nextRoute, "") + } +} + +/** + * Single authoritative Android `StaticLayout` engine cached by `(text, viewportWidthPx, density)` + * and shared by `HostTextPreviewView` and `AndroidSelectionOverlayView` so body text, + * selection highlights, teardrop handle tips, hit-testing, and the magnified loupe are + * 100% pixel-aligned with zero per-frame allocations during handle drags. + */ +class ShapedTextLayout(density: Float) : TextLayoutAuthority { + val textPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply { + color = Color.rgb(0x14, 0x16, 0x1C) + textSize = 18f * density.coerceAtLeast(1f) + } + var paddingLeftPx: Float = 24f * density.coerceAtLeast(1f) + private set + var paddingTopPx: Float = 80f * density.coerceAtLeast(1f) + private set + override var cachedText: String = "" + private set + var cachedViewportWidthPx: Int = -1 + private set + var cachedDensity: Float = density.coerceAtLeast(1f) + private set + var cachedLayout: StaticLayout? = null + private set + private val tmpPath = Path() + private val tmpBounds = RectF() + private val breakIterator: BreakIterator = BreakIterator.getCharacterInstance() + + fun applyClearColor(clearColorArgb: Int) { + textPaint.color = if (isLightClearColor(clearColorArgb)) { + Color.rgb(0x14, 0x16, 0x1C) + } else { + Color.rgb(0xF4, 0xF4, 0xF5) + } + } + + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean = + ensureLayout(text, viewportWidthPx, density) != null + + fun ensureLayout(text: String, viewportWidthPx: Int, density: Float): StaticLayout? { + val safeDensity = if (density.isFinite() && density > 0f) density else 1f + val padH = 24f * safeDensity + val contentW = (viewportWidthPx - (padH * 2f).toInt()).coerceAtLeast(120) + if (cachedLayout != null && + cachedText == text && + cachedViewportWidthPx == viewportWidthPx && + cachedDensity == safeDensity + ) { + return cachedLayout + } + paddingLeftPx = padH + paddingTopPx = 80f * safeDensity + textPaint.textSize = 18f * safeDensity + if (cachedText != text) { + breakIterator.setText(text) + } + cachedText = text + cachedViewportWidthPx = viewportWidthPx + cachedDensity = safeDensity + cachedLayout = StaticLayout.Builder.obtain(text, 0, text.length, textPaint, contentW) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR) + .setIncludePad(false) + .build() + return cachedLayout + } + + private fun visualLineForOffset(layout: StaticLayout, text: String, off: Int): Int { + var line = layout.getLineForOffset(off) + // Soft-wrap boundary offsets belong to the start of the next visual line. + if (off > 0 && + line + 1 < layout.lineCount && + layout.getLineStart(line + 1) == off && + text[off - 1] != '\n' + ) { + line += 1 + } + return line + } + + private fun caretHorizontalPx( + layout: StaticLayout, + text: String, + off: Int, + paraRtl: Boolean, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): Float { + var localX = layout.getPrimaryHorizontal(off) + if (selStart < selEnd) { + val charIdx = if (isSelectionEnd) { + (off - 1).coerceIn(selStart, text.length - 1) + } else { + off.coerceIn(0, (selEnd - 1).coerceAtLeast(0)) + } + val charRtl = layout.isRtlCharAt(charIdx) + if (charRtl != paraRtl) { + localX = layout.getSecondaryHorizontal(off) + } + } + return paddingLeftPx + localX + } + + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds? { + val layout = cachedLayout ?: return null + val text = cachedText + val off = utf16Offset.coerceIn(0, text.length) + val line = visualLineForOffset(layout, text, off) + val top = paddingTopPx + layout.getLineTop(line).toFloat() + val bottom = paddingTopPx + layout.getLineBottom(line).toFloat() + val paraRtl = layout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT + val x = caretHorizontalPx(layout, text, off, paraRtl, isSelectionEnd, selStart, selEnd) + return CaretBounds( + x = x, + top = top, + bottom = bottom, + lineIndex = line, + isRtlParagraph = paraRtl, + ) + } + + override fun fillSelectionEndCarets(selStart: Int, selEnd: Int, out: FloatArray): Boolean { + val layout = cachedLayout ?: return false + val text = cachedText + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + val startLine = visualLineForOffset(layout, text, lo) + val endLine = visualLineForOffset(layout, text, hi) + val startTop = paddingTopPx + layout.getLineTop(startLine).toFloat() + val startBottom = paddingTopPx + layout.getLineBottom(startLine).toFloat() + val endBottom = paddingTopPx + layout.getLineBottom(endLine).toFloat() + var startRtl = layout.getParagraphDirection(startLine) == Layout.DIR_RIGHT_TO_LEFT + val endRtl = layout.getParagraphDirection(endLine) == Layout.DIR_RIGHT_TO_LEFT + var startX = caretHorizontalPx(layout, text, lo, startRtl, false, lo, hi) + var endX = caretHorizontalPx(layout, text, hi, endRtl, true, lo, hi) + + // Guard mixed BiDi single-line spans against degenerate identical X coordinates. + if (lo < hi && startLine == endLine && kotlin.math.abs(startX - endX) < 0.5f) { + tmpPath.reset() + layout.getSelectionPath(lo, hi, tmpPath) + tmpPath.computeBounds(tmpBounds, true) + if (!tmpBounds.isEmpty) { + val leftX = paddingLeftPx + tmpBounds.left + val rightX = paddingLeftPx + tmpBounds.right + val charRtl = layout.isRtlCharAt(lo.coerceIn(0, (text.length - 1).coerceAtLeast(0))) + if (charRtl) { + startX = rightX + endX = leftX + startRtl = true + } else { + startX = leftX + endX = rightX + startRtl = false + } + } + } + out[0] = startX + out[1] = startBottom + out[2] = endX + out[3] = endBottom + out[4] = (startBottom - startTop).coerceAtLeast(1f) + out[5] = if (startRtl) 1f else 0f + return true + } + + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair? { + val lo = selStart.coerceIn(0, cachedText.length) + val hi = selEnd.coerceIn(lo, cachedText.length) + var start = caretBounds(lo, isSelectionEnd = false, selStart = lo, selEnd = hi) ?: return null + var end = caretBounds(hi, isSelectionEnd = true, selStart = lo, selEnd = hi) ?: return null + // Guard mixed BiDi single-line spans against degenerate identical X coordinates. + if (lo < hi && start.lineIndex == end.lineIndex && kotlin.math.abs(start.x - end.x) < 0.5f) { + val layout = cachedLayout + if (layout != null) { + tmpPath.reset() + layout.getSelectionPath(lo, hi, tmpPath) + tmpPath.computeBounds(tmpBounds, true) + if (!tmpBounds.isEmpty) { + val leftX = paddingLeftPx + tmpBounds.left + val rightX = paddingLeftPx + tmpBounds.right + val charRtl = layout.isRtlCharAt(lo.coerceIn(0, (cachedText.length - 1).coerceAtLeast(0))) + if (charRtl) { + start = start.copy(x = rightX, isRtlParagraph = true) + end = end.copy(x = leftX, isRtlParagraph = true) + } else { + start = start.copy(x = leftX, isRtlParagraph = false) + end = end.copy(x = rightX, isRtlParagraph = false) + } + } + } + } + return start to end + } + + private fun snapToGraphemeStart(text: String, raw: Int): Int { + if (raw <= 0 || raw >= text.length) return raw + if (Character.isLowSurrogate(text[raw])) { + return (raw - 1).coerceAtLeast(0) + } + if (breakIterator.isBoundary(raw)) return raw + val prev = breakIterator.preceding(raw) + return if (prev != BreakIterator.DONE) prev else raw + } + + override fun closestOffset(x: Float, y: Float): Int = closestOffset(x, y, -1) + + override fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int { + val layout = cachedLayout ?: return 0 + val text = cachedText + if (text.isEmpty()) return 0 + val localX = (x - paddingLeftPx).coerceAtLeast(0f) + val localY = (y - paddingTopPx).toInt().coerceAtLeast(0) + val line = layout.getLineForVertical(localY) + // Preserve the active endpoint at mixed-direction run boundaries where two logical offsets + // share the same visual X coordinate until the drag moves past the local glyph snap tolerance. + if (preferredOffset in 0..text.length && visualLineForOffset(layout, text, preferredOffset) == line) { + val primX = layout.getPrimaryHorizontal(preferredOffset) + val secX = layout.getSecondaryHorizontal(preferredOffset) + val lineStart = layout.getLineStart(line) + val lineEnd = layout.getLineEnd(line) + var adjAdvance = Float.MAX_VALUE + if (preferredOffset > lineStart) { + val prevX = layout.getPrimaryHorizontal(preferredOffset - 1) + val d1 = kotlin.math.abs(primX - prevX) + val d2 = kotlin.math.abs(secX - prevX) + if (d1 > 0.5f && d1 < adjAdvance) adjAdvance = d1 + if (d2 > 0.5f && d2 < adjAdvance) adjAdvance = d2 + } + if (preferredOffset < lineEnd) { + val nextX = layout.getPrimaryHorizontal(preferredOffset + 1) + val d1 = kotlin.math.abs(nextX - primX) + val d2 = kotlin.math.abs(nextX - secX) + if (d1 > 0.5f && d1 < adjAdvance) adjAdvance = d1 + if (d2 > 0.5f && d2 < adjAdvance) adjAdvance = d2 + } + if (adjAdvance == Float.MAX_VALUE) adjAdvance = 4f + val snapTol = minOf(2.0f * cachedDensity, adjAdvance * 0.35f) + if (kotlin.math.abs(localX - primX) <= snapTol || + kotlin.math.abs(localX - secX) <= snapTol + ) { + return snapToGraphemeStart(text, preferredOffset) + } + } + val raw = layout.getOffsetForHorizontal(line, localX).coerceIn(0, text.length) + return snapToGraphemeStart(text, raw) + } + + fun fillSelectionPath(selStart: Int, selEnd: Int, outPath: Path): Boolean { + outPath.reset() + val layout = cachedLayout ?: return false + val lo = selStart.coerceIn(0, cachedText.length) + val hi = selEnd.coerceIn(lo, cachedText.length) + if (lo >= hi) return false + layout.getSelectionPath(lo, hi, outPath) + return true + } +} + +/** + * In-memory host document store backed by the active destination route stack so + * `openDocument`, `navigateTo`, and predictive back `Cancel`/`Commit` preserve + * and restore real per-document text content. + */ +class HostDocumentStore( + initialRoute: String = "workspace/home", + initialText: String = "", +) { + private val documents = linkedMapOf(initialRoute to initialText) + var activeDocumentId: String = initialRoute + private set + + fun saveCurrent(text: String) { + documents[activeDocumentId] = text + } + + fun switchTo(nextRoute: String, outgoingText: String): String { + documents[activeDocumentId] = outgoingText + activeDocumentId = nextRoute + return documents.getOrPut(nextRoute) { "" } + } + + fun readDocument(route: String): String = documents[route] ?: "" +} + +internal const val DEFAULT_SURFACE_CLEAR_COLOR_ARGB: Int = 0xFFFA_FAFC.toInt() + +internal fun isLightClearColor(argb: Int): Boolean { + val r = ((argb ushr 16) and 0xFF) / 255.0 + val g = ((argb ushr 8) and 0xFF) / 255.0 + val b = (argb and 0xFF) / 255.0 + val luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b + return luminance >= 0.5 +} + +/** + * Pure Android `View` overlay layered above `AffineSurfaceView` in a `FrameLayout` + * to render teardrop handles, single-authority `ShapedTextLayout` magnified loupe + * (with `getSelectionPath` highlight and vertically centered focus), and clickable + * `Copy | Cut | Paste` action menu pills with zero per-frame allocations and + * without ever calling `SurfaceHolder.lockCanvas`. + */ +class AndroidSelectionOverlayView( + context: Context, + private val coordinator: AndroidSelectionCoordinator, + private val shapedLayout: ShapedTextLayout, + private val selectionStartProvider: () -> Int = { 0 }, + private val selectionEndProvider: () -> Int = { 0 }, + private val onSelectionChanged: (Int, Int) -> Unit = { _, _ -> }, + private val canPaste: () -> Boolean = { false }, + private val onActionCopy: () -> Unit = {}, + private val onActionCut: () -> Unit = {}, + private val onActionPaste: () -> Unit = {}, + private val isOverlaySuppressed: () -> Boolean = { false }, +) : View(context) { + private val handlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(235, 30, 150, 235) + style = Paint.Style.FILL + } + private val selectionHighlightPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(56, 30, 150, 235) + style = Paint.Style.FILL + } + private val loupeBgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.rgb(0xFA, 0xFB, 0xFD) + style = Paint.Style.FILL + } + private val loupeBorderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(235, 30, 150, 235) + style = Paint.Style.STROKE + strokeWidth = 3f + } + private val menuPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(225, 28, 28, 32) + style = Paint.Style.FILL + } + private val menuDividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(60, 255, 255, 255) + style = Paint.Style.FILL + } + private val menuTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textSize = 36f + textAlign = Paint.Align.CENTER + } + private val geometryBuffer = FloatArray(24) + private val handlePath = Path() + private val loupeClipPath = Path() + private val reusableSelectionPath = Path() + private val loupeRect = RectF() + private val menuRect = RectF() + private val gestureController = SelectionGestureController( + coordinator = coordinator, + layoutAuthority = shapedLayout, + selectionStartProvider = selectionStartProvider, + selectionEndProvider = selectionEndProvider, + onSelectionChanged = onSelectionChanged, + onOverlaySynced = { invalidate() }, + ) + private var hasVisibleMenu: Boolean = false + private var menuHasPaste: Boolean = false + + init { + setWillNotDraw(false) + isClickable = false + isFocusable = false + } + + fun refreshPasteState() { + menuHasPaste = canPaste() + } + + override fun onWindowFocusChanged(hasWindowFocus: Boolean) { + super.onWindowFocusChanged(hasWindowFocus) + if (hasWindowFocus) { + refreshPasteState() + invalidate() + } + } + + fun syncFromShapedLayout( + text: String, + selStart: Int, + selEnd: Int, + viewportWidthPx: Int, + density: Float, + ) { + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + menuHasPaste = if (lo < hi) canPaste() else false + gestureController.syncSelectionFromLayout(text, lo, hi, viewportWidthPx, density) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (isOverlaySuppressed()) return false + val viewportW = if (width > 0) width else resources.displayMetrics.widthPixels + val density = resources.displayMetrics.density + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + val hit = gestureController.onDown(event.x, event.y, density) + if (hit != 0) { + invalidate() + return true + } + if (hasVisibleMenu && menuRect.contains(event.x, event.y)) { + return true + } + return false + } + MotionEvent.ACTION_MOVE -> { + if (!gestureController.draggingHandle) return false + gestureController.onMove(event.x, event.y) + invalidate() + return true + } + MotionEvent.ACTION_UP -> { + if (gestureController.draggingHandle) { + refreshPasteState() + gestureController.onUp(viewportW, density) + invalidate() + return true + } + if (hasVisibleMenu && menuRect.contains(event.x, event.y)) { + if (menuHasPaste) { + val third = menuRect.width() / 3f + when { + event.x < menuRect.left + third -> onActionCopy() + event.x < menuRect.left + third * 2f -> onActionCut() + else -> onActionPaste() + } + } else { + if (event.x < menuRect.centerX()) { + onActionCopy() + } else { + onActionCut() + } + } + refreshPasteState() + invalidate() + return true + } + return false + } + MotionEvent.ACTION_CANCEL -> { + if (!gestureController.draggingHandle) return false + refreshPasteState() + gestureController.onCancel(viewportW, density) + invalidate() + return true + } + else -> return false + } + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (isOverlaySuppressed()) { + hasVisibleMenu = false + return + } + val g = geometryBuffer + if (!coordinator.fillOverlayGeometry(g) || g[0] < 0.5f) { + hasVisibleMenu = false + return + } + if (g[2] >= 0.5f) { + drawTeardropHandle(canvas, g[3], g[4], g[5], g[6], g[7], leanLeft = g[5] < g[3]) + } + if (g[8] >= 0.5f) { + drawTeardropHandle(canvas, g[9], g[10], g[11], g[12], g[13], leanLeft = g[11] < g[9]) + } + if (g[14] >= 0.5f) { + val ax = g[15] + val ay = g[16] + val lx = g[17] + val ly = g[18] + val density = resources.displayMetrics.density + val loupeW = 100f * density + val loupeH = 48f * density + loupeRect.set(lx - loupeW * 0.5f, ly - loupeH * 0.5f, lx + loupeW * 0.5f, ly + loupeH * 0.5f) + loupeClipPath.reset() + loupeClipPath.addRoundRect(loupeRect, loupeH * 0.5f, loupeH * 0.5f, Path.Direction.CW) + val layout = shapedLayout.cachedLayout + canvas.save() + canvas.clipPath(loupeClipPath) + canvas.drawRect(loupeRect, loupeBgPaint) + if (layout != null && shapedLayout.cachedText.isNotEmpty()) { + val selStart = selectionStartProvider() + val selEnd = selectionEndProvider() + val halfCaretH = (shapedLayout.textPaint.textSize * 0.65f).coerceAtLeast(12f) + canvas.scale(1.5f, 1.5f, lx, ly) + canvas.save() + canvas.translate(lx - ax + shapedLayout.paddingLeftPx, ly - ay + shapedLayout.paddingTopPx) + if (shapedLayout.fillSelectionPath(selStart, selEnd, reusableSelectionPath)) { + canvas.drawPath(reusableSelectionPath, selectionHighlightPaint) + } + layout.draw(canvas) + canvas.restore() + // Focus caret bar vertically centered on the dragged line midpoint (lx, ly). + canvas.drawRect(lx - 1.5f, ly - halfCaretH, lx + 1.5f, ly + halfCaretH, handlePaint) + } + canvas.restore() + canvas.drawPath(loupeClipPath, loupeBorderPaint) + } + if (g[19] >= 0.5f) { + val mx = g[20] + val my = g[21] + val mw = g[22] + val mh = g[23] + val density = resources.displayMetrics.density + val marginX = 12f * density + val actualW = if (menuHasPaste) mw * 1.38f else mw + val maxLeft = (width - marginX - actualW).coerceAtLeast(0f) + val minLeft = marginX.coerceAtMost(maxLeft) + val actualX = (mx + (mw - actualW) * 0.5f).coerceIn(minLeft, maxLeft) + menuRect.set(actualX, my, actualX + actualW, my + mh) + hasVisibleMenu = true + canvas.drawRoundRect(menuRect, mh * 0.5f, mh * 0.5f, menuPaint) + val baselineY = menuRect.centerY() + menuTextPaint.textSize * 0.35f + if (menuHasPaste) { + val third = actualW / 3f + val d1 = actualX + third + val d2 = actualX + third * 2f + canvas.drawRect(d1 - 1f, my + mh * 0.22f, d1 + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawRect(d2 - 1f, my + mh * 0.22f, d2 + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawText("Copy", actualX + third * 0.5f, baselineY, menuTextPaint) + canvas.drawText("Cut", actualX + third * 1.5f, baselineY, menuTextPaint) + canvas.drawText("Paste", actualX + third * 2.5f, baselineY, menuTextPaint) + } else { + val dividerX = actualX + actualW * 0.5f + canvas.drawRect(dividerX - 1f, my + mh * 0.22f, dividerX + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawText("Copy", actualX + actualW * 0.25f, baselineY, menuTextPaint) + canvas.drawText("Cut", actualX + actualW * 0.75f, baselineY, menuTextPaint) + } + } else { + hasVisibleMenu = false + } + } + + private fun drawTeardropHandle( + canvas: Canvas, + tipX: Float, + tipY: Float, + centerX: Float, + centerY: Float, + radius: Float, + leanLeft: Boolean, + ) { + // Draw vertical selection stem above the tip + teardrop bulb curving into tip. + val stemHeight = radius * 1.4f + canvas.drawRect(tipX - 2f, tipY - stemHeight, tipX + 2f, tipY, handlePaint) + handlePath.reset() + handlePath.moveTo(tipX, tipY) + if (leanLeft) { + handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX + radius, centerY) + } else { + handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX - radius, centerY) + } + handlePath.addCircle(centerX, centerY, radius, Path.Direction.CW) + canvas.drawPath(handlePath, handlePaint) + } +} + +/** + * GPU-document-level selection teardrop handle overlay with system `android.widget.Magnifier` + * (API 28+). Draws zero custom action pills (system `ActionMode.TYPE_FLOATING` owns the menu) + * and reads 100% of its endpoint coordinates from Rust `DocumentSelectionGeometry`. + */ +internal class DocumentSelectionHandleView( + context: Context, + private val targetSurfaceView: View, + private val handleProvider: () -> Long, + private val isSuppressed: () -> Boolean, + private val onSelectionMutated: () -> Unit, + private val onDragStateChanged: (Boolean) -> Unit, +) : View(context) { + private val handlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(240, 30, 150, 235) + style = Paint.Style.FILL + } + private val handlePath = Path() + private var hasSelection: Boolean = false + private var isCollapsed: Boolean = true + private var startVisible: Boolean = false + private var startTipX: Float = 0f + private var startTipY: Float = 0f + private var startHeight: Float = 0f + private var startCenterX: Float = 0f + private var startCenterY: Float = 0f + private var startLeanLeft: Boolean = true + private var endVisible: Boolean = false + private var endTipX: Float = 0f + private var endTipY: Float = 0f + private var endHeight: Float = 0f + private var endCenterX: Float = 0f + private var endCenterY: Float = 0f + private var endLeanLeft: Boolean = false + private var draggingHandle: Int = 0 + private var grabDx: Float = 0f + private var grabDy: Float = 0f + private var magnifier: Magnifier? = null + + init { + setWillNotDraw(false) + isClickable = false + isFocusable = false + } + + fun updateFromDocumentBuffer(buf: FloatArray, density: Float) { + if (isSuppressed() || buf.size < 24 || buf[0] < 0.5f || buf[1] >= 0.5f) { + if (hasSelection || startVisible || endVisible) { + hasSelection = false + isCollapsed = true + startVisible = false + endVisible = false + dismissMagnifier() + invalidate() + } + return + } + val d = density.coerceAtLeast(1f) + val radius = 11f * d + val nextStartVis = buf[3] >= 0.5f + val nextStartX = buf[4] * d + val nextStartH = (buf[6] * d).coerceAtLeast(14f * d) + val nextStartTipY = buf[5] * d + nextStartH + val nextStartRtl = buf[7] >= 0.5f + val nextStartLeanLeft = !nextStartRtl + val nextStartCx = if (nextStartLeanLeft) nextStartX - radius else nextStartX + radius + val nextStartCy = nextStartTipY + radius + + val nextEndVis = buf[8] >= 0.5f + val nextEndX = buf[9] * d + val nextEndH = (buf[11] * d).coerceAtLeast(14f * d) + val nextEndTipY = buf[10] * d + nextEndH + val nextEndRtl = buf[12] >= 0.5f + val nextEndLeanLeft = nextEndRtl + val nextEndCx = if (nextEndLeanLeft) nextEndX - radius else nextEndX + radius + val nextEndCy = nextEndTipY + radius + + val changed = !hasSelection || + isCollapsed || + startVisible != nextStartVis || + endVisible != nextEndVis || + kotlin.math.abs(startTipX - nextStartX) > 0.5f || + kotlin.math.abs(startTipY - nextStartTipY) > 0.5f || + kotlin.math.abs(endTipX - nextEndX) > 0.5f || + kotlin.math.abs(endTipY - nextEndTipY) > 0.5f || + startLeanLeft != nextStartLeanLeft || + endLeanLeft != nextEndLeanLeft + + hasSelection = true + isCollapsed = false + startVisible = nextStartVis + startTipX = nextStartX + startTipY = nextStartTipY + startHeight = nextStartH + startCenterX = nextStartCx + startCenterY = nextStartCy + startLeanLeft = nextStartLeanLeft + endVisible = nextEndVis + endTipX = nextEndX + endTipY = nextEndTipY + endHeight = nextEndH + endCenterX = nextEndCx + endCenterY = nextEndCy + endLeanLeft = nextEndLeanLeft + + if (changed) { + invalidate() + } + } + + fun dismissMagnifier() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + magnifier?.dismiss() + } + } + + @Suppress("DEPRECATION") + private fun showMagnifier(xPx: Float, yPx: Float) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val mag = magnifier ?: Magnifier.Builder(targetSurfaceView).build().also { magnifier = it } + mag.show(xPx, yPx) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + val mag = magnifier ?: Magnifier(targetSurfaceView).also { magnifier = it } + mag.show(xPx, yPx) + } + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (isSuppressed()) { + dismissMagnifier() + return false + } + val handle = handleProvider() + if (handle == 0L) return false + val d = resources.displayMetrics.density.coerceAtLeast(1f) + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + if (!hasSelection || isCollapsed) return false + val hitR = 28f * d + val maxSq = hitR * hitR + val dStart = if (startVisible) { + val dx = event.x - startCenterX + val dy = event.y - startCenterY + dx * dx + dy * dy + } else Float.POSITIVE_INFINITY + val dEnd = if (endVisible) { + val dx = event.x - endCenterX + val dy = event.y - endCenterY + dx * dx + dy * dy + } else Float.POSITIVE_INFINITY + val hit = when { + dStart <= maxSq && dStart <= dEnd -> 1 + dEnd <= maxSq -> 2 + else -> 0 + } + if (hit == 0) return false + if (!NativeBridge.nativeDocSelectionBeginDrag(handle, hit)) return false + draggingHandle = hit + if (hit == 1) { + grabDx = startTipX - event.x + grabDy = (startTipY - startHeight * 0.5f) - event.y + showMagnifier(startTipX, startTipY - startHeight * 0.5f) + } else { + grabDx = endTipX - event.x + grabDy = (endTipY - endHeight * 0.5f) - event.y + showMagnifier(endTipX, endTipY - endHeight * 0.5f) + } + onDragStateChanged(true) + onSelectionMutated() + return true + } + MotionEvent.ACTION_MOVE -> { + if (draggingHandle == 0) return false + val probeX = (event.x + grabDx).coerceIn(0f, width.toFloat().coerceAtLeast(1f)) + val probeY = (event.y + grabDy).coerceIn(0f, height.toFloat().coerceAtLeast(1f)) + NativeBridge.nativeDocSelectionUpdateDrag(handle, probeX / d, probeY / d) + showMagnifier(probeX, probeY) + onSelectionMutated() + return true + } + MotionEvent.ACTION_UP -> { + if (draggingHandle == 0) return false + draggingHandle = 0 + dismissMagnifier() + NativeBridge.nativeDocSelectionEndDrag(handle) + onDragStateChanged(false) + onSelectionMutated() + return true + } + MotionEvent.ACTION_CANCEL -> { + if (draggingHandle == 0) return false + draggingHandle = 0 + dismissMagnifier() + NativeBridge.nativeDocSelectionCancelDrag(handle) + onDragStateChanged(false) + onSelectionMutated() + return true + } + else -> return false + } + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (isSuppressed() || !hasSelection || isCollapsed) return + val radius = 11f * resources.displayMetrics.density.coerceAtLeast(1f) + if (startVisible) { + drawTeardrop(canvas, startTipX, startTipY, startCenterX, startCenterY, radius, startLeanLeft) + } + if (endVisible) { + drawTeardrop(canvas, endTipX, endTipY, endCenterX, endCenterY, radius, endLeanLeft) + } + } + + private fun drawTeardrop( + canvas: Canvas, + tipX: Float, + tipY: Float, + centerX: Float, + centerY: Float, + radius: Float, + leanLeft: Boolean, + ) { + handlePath.reset() + handlePath.moveTo(tipX, tipY) + if (leanLeft) { + handlePath.lineTo(centerX, tipY) + handlePath.lineTo(tipX, centerY) + } else { + handlePath.lineTo(tipX, centerY) + handlePath.lineTo(centerX, tipY) + } + handlePath.close() + handlePath.addCircle(centerX, centerY, radius, Path.Direction.CCW) + canvas.drawPath(handlePath, handlePaint) + } +} + +data class VirtualAutofillNode( + val autofillId: Int, + val kindCode: Int, + val hint: String, + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, + val masked: Boolean, + val valueLen: Int, +) + +interface AutofillPlatformBackend { + fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) + fun notifyViewExited(autofillId: Int) + fun notifyValueChanged(autofillId: Int, text: String) + fun commit() + fun cancel() +} + +@TargetApi(Build.VERSION_CODES.O) +class SystemAutofillPlatformBackend( + private val hostView: View, + private val manager: AutofillManager, +) : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + manager.notifyViewEntered(hostView, autofillId, Rect(left, top, right, bottom)) + } + + override fun notifyViewExited(autofillId: Int) { + manager.notifyViewExited(hostView, autofillId) + } + + override fun notifyValueChanged(autofillId: Int, text: String) { + manager.notifyValueChanged(hostView, autofillId, AutofillValue.forText(text)) + } + + override fun commit() { + manager.commit() + } + + override fun cancel() { + manager.cancel() + } +} + +/** + * API 26+ `AutofillManager` virtual view structure controller. + * Safely degrades to a no-op on API 24 and 25 without touching API 26 classes. + */ +class AndroidAutofillController( + private val sdkInt: Int, + private val handleProvider: () -> Long, + private val backend: AutofillPlatformBackend? = null, + private val onMutated: () -> Unit = {}, + private val onValueCommitted: (Int, String) -> Unit = { _, _ -> }, + private val onFocusedFieldTextSync: (Int, String) -> Unit = { _, _ -> }, +) { + private val nodes = linkedMapOf() + private var focusedId: Int? = null + + val isEnabled: Boolean + get() = sdkInt >= Build.VERSION_CODES.O && NativeBridge.nativeShouldExposeAutofill(sdkInt) + + fun focusedFieldId(): Int? = if (isEnabled) focusedId else null + + fun isFocusedFieldMasked(): Boolean { + val id = focusedFieldId() ?: return false + return nodes[id]?.masked == true + } + + fun readFormValues(): Map { + if (!isEnabled) return emptyMap() + val handle = handleProvider() + if (handle == 0L) return emptyMap() + val out = linkedMapOf() + NativeBridge.nativeGetAutofillValueByKind(handle, 0)?.let { out["username"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 1)?.let { out["email"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 2)?.let { out["password"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 3)?.let { out["otp"] = it } + return out + } + + private var inputFocusGeneration: Long = 0L + var onFocusGenerationChanged: () -> Unit = {} + + fun currentFocusGeneration(): Long = inputFocusGeneration + + private fun bumpFocusGeneration() { + inputFocusGeneration += 1L + onFocusGenerationChanged() + } + + fun onFocusedTextEdited(text: String): Boolean { + val active = focusedId ?: return false + return updateFieldText(active, text) + } + + init { + val handle = handleProvider() + if (handle != 0L) { + NativeBridge.nativeConfigureAutofillSdk(handle, sdkInt) + } + } + + fun registerField( + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int = 0, + ): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeUpsertAutofillField( + handle, + autofillId, + kindCode, + left, + top, + right, + bottom, + masked, + valueLen, + ) + if (ok) { + val hint = when (kindCode) { + 0 -> View.AUTOFILL_HINT_USERNAME + 1 -> View.AUTOFILL_HINT_EMAIL_ADDRESS + 2 -> View.AUTOFILL_HINT_PASSWORD + else -> "smsOTPCode" + } + nodes[autofillId] = VirtualAutofillNode( + autofillId = autofillId, + kindCode = kindCode, + hint = hint, + left = minOf(left, right), + top = minOf(top, bottom), + right = maxOf(left, right), + bottom = maxOf(top, bottom), + masked = masked, + valueLen = valueLen.coerceAtLeast(0), + ) + } + return ok + } + + fun updateFieldText(autofillId: Int, text: String): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeSetAutofillFieldText(handle, autofillId, text) + if (ok) { + val existing = nodes[autofillId] + if (existing != null) { + nodes[autofillId] = existing.copy(valueLen = text.length) + } + backend?.notifyValueChanged(autofillId, text) + } + return ok + } + + fun resolveVirtualFieldValueForStructure(autofillId: Int): String? { + if (!isEnabled) return null + val handle = handleProvider() + if (handle == 0L) return null + return NativeBridge.nativeGetAutofillValue(handle, autofillId)?.takeIf { it.isNotEmpty() } + } + + fun onFieldFocusChanged(nextAutofillId: Int?) { + if (!isEnabled) return + val handle = handleProvider() + if (handle == 0L) return + val validNext = if (nextAutofillId != null && nodes.containsKey(nextAutofillId)) { + nextAutofillId + } else { + null + } + if (focusedId == validNext) return + val prev = focusedId + focusedId = validNext + bumpFocusGeneration() + NativeBridge.nativeFocusAutofillField(handle, validNext ?: 0) + if (prev != null) { + backend?.notifyViewExited(prev) + } + if (validNext != null) { + val node = nodes[validNext] + if (node != null) { + backend?.notifyViewEntered(node.autofillId, node.left, node.top, node.right, node.bottom) + } + onFocusedFieldTextSync(validNext, resolveVirtualFieldValueForStructure(validNext) ?: "") + } + } + + fun virtualNodesSnapshot(): List = + if (!isEnabled) emptyList() else nodes.values.toList() + + @TargetApi(Build.VERSION_CODES.O) + fun populateVirtualStructure(structure: ViewStructure) { + if (!isEnabled || nodes.isEmpty()) return + val parentId = structure.autofillId ?: return + val ordered = nodes.values.toList() + val baseIndex = structure.addChildCount(ordered.size) + ordered.forEachIndexed { offset, node -> + val child = structure.newChild(baseIndex + offset) + child.setAutofillId(parentId, node.autofillId) + child.setAutofillType(View.AUTOFILL_TYPE_TEXT) + child.setAutofillHints(arrayOf(node.hint)) + child.setInputType( + when (node.kindCode) { + 1 -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + 2 -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + 3 -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL + else -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL + }, + ) + child.setDimens( + node.left, + node.top, + 0, + 0, + (node.right - node.left).coerceAtLeast(0), + (node.bottom - node.top).coerceAtLeast(0), + ) + val realText = resolveVirtualFieldValueForStructure(node.autofillId) + if (!realText.isNullOrEmpty()) { + child.setAutofillValue(AutofillValue.forText(realText)) + } + } + } + + fun onAutofillValues(values: Map): Int { + if (!isEnabled) return 0 + val handle = handleProvider() + if (handle == 0L) return 0 + var applied = 0 + val activeFocus = focusedId + for ((id, text) in values) { + if (NativeBridge.nativeApplyAutofillValue(handle, id, text)) { + applied += 1 + val existing = nodes[id] + if (existing != null) { + nodes[id] = existing.copy(valueLen = text.length) + } + if (activeFocus != null && id == activeFocus) { + onValueCommitted(id, text) + } + backend?.notifyValueChanged(id, text) + } + } + if (applied > 0) onMutated() + return applied + } + + @TargetApi(Build.VERSION_CODES.O) + fun onAutofillSparseArray(values: SparseArray): Int { + if (!isEnabled) return 0 + val map = linkedMapOf() + for (idx in 0 until values.size()) { + val id = values.keyAt(idx) + val value = values.valueAt(idx) + if (value != null && value.isText) { + map[id] = value.textValue.toString() + } + } + return onAutofillValues(map) + } + + fun commit(): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + focusedId = null + bumpFocusGeneration() + val ok = NativeBridge.nativeCommitAutofill(handle) + if (ok) backend?.commit() + return ok + } + + fun cancel(): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + focusedId = null + bumpFocusGeneration() + val ok = NativeBridge.nativeCancelAutofill(handle) + if (ok) backend?.cancel() + return ok + } + + fun clearFields() { + nodes.clear() + focusedId = null + bumpFocusGeneration() + val handle = handleProvider() + if (handle != 0L) { + NativeBridge.nativeClearAutofillFields(handle) + } + } + + fun virtualStructureJson(): String { + val handle = handleProvider() + return if (handle == 0L) "{}" else NativeBridge.nativeGetAutofillStructureJson(handle) + } +} + +/** + * Four-phase predictive back (API 34+) and legacy single-commit (API 24-33) + * dispatcher backed by Rust `back_stack_depth`, with re-entrancy protection + * and full support for standalone API 34+ button/key `onBackInvoked()` calls. + */ +class AndroidBackDispatcher( + private val sdkInt: Int, + private val handleProvider: () -> Long, + private val onMutated: () -> Unit = {}, + private val onDestinationChanged: (String?) -> Unit = {}, + private val onSystemExit: () -> Unit = {}, +) { + val dispatchMode: Int = NativeBridge.nativeBackDispatchMode(sdkInt) + private var gestureActive: Boolean = false + private var inDispatch: Boolean = false + + fun pushDestination(route: String): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativePushDestination(handle, route) + if (ok) { + onDestinationChanged(currentDestination()) + onMutated() + } + return ok + } + + fun navigateTo(destination: String): Boolean = pushDestination(destination) + + fun openDocument(docId: String): Boolean { + val clean = docId.trim().removePrefix("/") + if (clean.isEmpty()) return false + val route = if (clean.startsWith("doc/")) clean else "doc/$clean" + return pushDestination(route) + } + + fun currentDestination(): String? { + val handle = handleProvider() + return if (handle == 0L) null else NativeBridge.nativeGetCurrentDestination(handle) + } + + fun onBackStarted(progress: Float = 0f): Boolean { + if (dispatchMode < 2) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 0, progress) + if (ok) { + gestureActive = true + onMutated() + } + return ok + } + + fun onBackProgressed(progress: Float): Boolean { + if (dispatchMode < 2 || !gestureActive) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 1, progress) + if (ok) onMutated() + return ok + } + + fun onBackCancelled(): Boolean { + if (dispatchMode < 2 || !gestureActive) return false + val handle = handleProvider() + if (handle == 0L) return false + gestureActive = false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 2, 0f) + if (ok) onMutated() + return ok + } + + fun onBackInvoked(): Boolean { + if (inDispatch) return false + inDispatch = true + try { + gestureActive = false + val handle = handleProvider() + val consumed = handle != 0L && NativeBridge.nativeOnBackGesturePhase(handle, 3, 1f) + if (consumed) { + onDestinationChanged(currentDestination()) + onMutated() + } else { + onSystemExit() + } + return consumed + } finally { + inDispatch = false + } + } + + fun onLegacyBackPressed(invokeSystemExit: Boolean = true): Boolean { + if (inDispatch) return false + inDispatch = true + try { + gestureActive = false + val handle = handleProvider() + val consumed = handle != 0L && NativeBridge.nativeOnBackGesturePhase(handle, 3, 1f) + if (consumed) { + onDestinationChanged(currentDestination()) + onMutated() + } else if (invokeSystemExit) { + onSystemExit() + } + return consumed + } finally { + inDispatch = false + } + } +} + +interface PdfPageBackend : AutoCloseable { + fun pageCount(): Int + fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray +} + +data class RenderedPdfPage( + val cacheKey: String, + val pageIndex: Int, + val widthPx: Int, + val heightPx: Int, + val rgbaBytes: ByteArray, +) + +class SystemPdfRendererBackend( + private val descriptor: ParcelFileDescriptor, +) : PdfPageBackend { + private val renderer = PdfRenderer(descriptor) + + override fun pageCount(): Int = renderer.pageCount + + override fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray { + renderer.openPage(pageIndex).use { page -> + val bitmap = Bitmap.createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888) + try { + Canvas(bitmap).drawColor(Color.WHITE) + page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) + val pixels = IntArray(widthPx * heightPx) + bitmap.getPixels(pixels, 0, widthPx, 0, 0, widthPx, heightPx) + return pixels + } finally { + bitmap.recycle() + } + } + } + + override fun close() { + renderer.close() + descriptor.close() + } +} + +/** + * In-place Android `PdfRenderer` page renderer with Rust OOM/bounds validation + * and deterministic `ARGB_8888 -> RGBA8` conversion. + */ +class AndroidPdfPageRenderer( + private val docId: String, + private val backend: PdfPageBackend, +) : AutoCloseable { + fun renderPageRgba( + pageIndex: Int, + widthPx: Int, + heightPx: Int, + dpiBucket: Int = 160, + ): RenderedPdfPage? { + if (!NativeBridge.nativeValidatePdfPageRequest(pageIndex, backend.pageCount(), widthPx, heightPx)) { + return null + } + val argb = backend.renderPageArgb(pageIndex, widthPx, heightPx) + val rgba = NativeBridge.nativePdfConvertArgbToRgba(argb, widthPx, heightPx) ?: return null + val safeDpi = dpiBucket.coerceAtLeast(72) + val key = NativeBridge.nativePdfPageCacheKey(docId, pageIndex, widthPx, heightPx, safeDpi) + return RenderedPdfPage( + cacheKey = key, + pageIndex = pageIndex, + widthPx = widthPx, + heightPx = heightPx, + rgbaBytes = rgba, + ) + } + + override fun close() { + backend.close() + } +} + +internal class AffineSurfaceView( + context: Context, + private val handleProvider: () -> Long, + private val onMutated: () -> Unit = {}, + private val onTextEdited: (String) -> Unit = {}, + private val onContextMenuAction: (Int) -> Boolean = { false }, + private val autofillProvider: () -> AndroidAutofillController? = { null }, + private val onTouchDispatched: () -> Unit = {}, + private val onCursorUpdatesRequested: (Int) -> Unit = {}, +) : SurfaceView(context) { + init { + isFocusable = true + isFocusableInTouchMode = true + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + markImportantForAutofillApi26() + } + } + + @TargetApi(Build.VERSION_CODES.O) + private fun markImportantForAutofillApi26() { + importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES + } + + private var touchDownX = 0f + private var touchDownY = 0f + private var touchMovedBeyondSlop = false + + /** + * Shell controls, published to TalkBack and UI Automator as virtual views. Events go out only + * while an accessibility service runs: `requestSendAccessibilityEvent` throws once the last + * service stops, which is when the system clears the accessibility focus. + */ + private val accessibilityViews = ShellAccessibilityViews( + accessibilityEnabled = { + context.getSystemService(AccessibilityManager::class.java)?.isEnabled == true + }, + sendEvent = ::sendVirtualViewEvent, + ) + + private val shellAccessibilityProvider = object : AccessibilityNodeProvider() { + override fun createAccessibilityNodeInfo(virtualViewId: Int): AccessibilityNodeInfo? { + val host = this@AffineSurfaceView + if (virtualViewId == HOST_VIEW_ID) { + val info = AccessibilityNodeInfo.obtain(host) + onInitializeAccessibilityNodeInfo(info) + val handle = handleProvider() + val json = if (handle == 0L) null else NativeBridge.nativeShellAccessibilityJson(handle) + accessibilityViews.update(json?.let(ShellAccessibilityNode::parse).orEmpty()) + accessibilityViews.virtualIds().forEach { info.addChild(host, it) } + return info + } + val node = accessibilityViews.node(virtualViewId) ?: return null + val info = AccessibilityNodeInfo.obtain(host, virtualViewId) + val density = resources.displayMetrics.density.coerceAtLeast(1f) + val local = Rect( + (node.x * density).toInt(), + (node.y * density).toInt(), + ((node.x + node.width) * density).toInt(), + ((node.y + node.height) * density).toInt(), + ) + val origin = IntArray(2) + getLocationOnScreen(origin) + @Suppress("DEPRECATION") + info.setBoundsInParent(local) + info.setBoundsInScreen(Rect(local).apply { offset(origin[0], origin[1]) }) + info.setParent(host) + info.packageName = context.packageName + info.className = node.className + info.text = node.name + info.contentDescription = node.name + info.isEnabled = true + info.isVisibleToUser = true + val focused = accessibilityViews.focusedVirtualId == virtualViewId + info.isAccessibilityFocused = focused + info.addAction( + if (focused) { + AccessibilityNodeInfo.AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS + } else { + AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS + }, + ) + if (node.clickable) { + info.isClickable = true + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK) + } + return info + } + + override fun findFocus(focus: Int): AccessibilityNodeInfo? { + val focused = accessibilityViews.focusedVirtualId + if (focus != AccessibilityNodeInfo.FOCUS_ACCESSIBILITY || focused == View.NO_ID) return null + return createAccessibilityNodeInfo(focused) + } + + override fun performAction(virtualViewId: Int, action: Int, arguments: Bundle?): Boolean { + if (virtualViewId == HOST_VIEW_ID) { + return performAccessibilityAction(action, arguments) + } + when (action) { + AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, + AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS -> { + if (!accessibilityViews.performFocusAction(virtualViewId, action)) return false + invalidate() + return true + } + } + val node = accessibilityViews.node(virtualViewId) ?: return false + val handle = handleProvider() + if (handle == 0L || action != AccessibilityNodeInfo.ACTION_CLICK || !node.clickable) { + return false + } + val x = node.x + node.width / 2f + val y = node.y + node.height / 2f + NativeBridge.nativeOnTouchEvent(handle, ACCESSIBILITY_POINTER_ID, 0, x, y) + NativeBridge.nativeOnTouchEvent(handle, ACCESSIBILITY_POINTER_ID, 2, x, y) + onTouchDispatched() + accessibilityViews.announce(virtualViewId, AccessibilityEvent.TYPE_VIEW_CLICKED) + sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) + return true + } + } + + private fun sendVirtualViewEvent(virtualViewId: Int, eventType: Int) { + val parentView = parent ?: return + @Suppress("DEPRECATION") + val event = AccessibilityEvent.obtain(eventType) + event.packageName = context.packageName + event.setSource(this, virtualViewId) + parentView.requestSendAccessibilityEvent(this, event) + } + + override fun getAccessibilityNodeProvider(): AccessibilityNodeProvider = shellAccessibilityProvider + + override fun onCheckIsTextEditor(): Boolean { + if (autofillProvider()?.focusedFieldId() != null) return true + val handle = handleProvider() + return handle != 0L && NativeBridge.nativeWantsSoftwareKeyboard(handle) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + val handle = handleProvider() + if (handle == 0L) return super.onTouchEvent(event) + val density = resources.displayMetrics.density.coerceAtLeast(1f) + val slopPx = 10f * density + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { + val idx = event.actionIndex + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + touchDownX = event.getX(idx) + touchDownY = event.getY(idx) + touchMovedBeyondSlop = false + } + NativeBridge.nativeOnTouchEvent( + handle, + event.getPointerId(idx).toLong(), + 0, + event.getX(idx) / density, + event.getY(idx) / density, + ) + } + MotionEvent.ACTION_MOVE -> { + if (event.pointerCount > 0) { + val dx = event.getX(0) - touchDownX + val dy = event.getY(0) - touchDownY + if (dx * dx + dy * dy > slopPx * slopPx) { + touchMovedBeyondSlop = true + } + } + // Forward historical touch samples before the current sample so inertial + // fling velocity stays smooth on 60/120 Hz Android displays. + for (h in 0 until event.historySize) { + for (idx in 0 until event.pointerCount) { + NativeBridge.nativeOnTouchEvent( + handle, + event.getPointerId(idx).toLong(), + 1, + event.getHistoricalX(idx, h) / density, + event.getHistoricalY(idx, h) / density, + ) + } + } + for (idx in 0 until event.pointerCount) { + NativeBridge.nativeOnTouchEvent( + handle, + event.getPointerId(idx).toLong(), + 1, + event.getX(idx) / density, + event.getY(idx) / density, + ) + } + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { + val idx = event.actionIndex + NativeBridge.nativeOnTouchEvent( + handle, + event.getPointerId(idx).toLong(), + 2, + event.getX(idx) / density, + event.getY(idx) / density, + ) + if (event.actionMasked == MotionEvent.ACTION_UP) { + drainPendingOpenUrl(context, handle) + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + val requestedKb = NativeBridge.nativeTakeSoftwareKeyboardRequest(handle) + if (NativeBridge.nativeWantsSoftwareKeyboard(handle)) { + if (requestedKb && !touchMovedBeyondSlop) { + requestFocus() + imm?.restartInput(this) + imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) + } + } else { + imm?.hideSoftInputFromWindow(windowToken, 0) + imm?.restartInput(this) + } + } + } + MotionEvent.ACTION_CANCEL -> { + for (idx in 0 until event.pointerCount) { + NativeBridge.nativeOnTouchEvent( + handle, + event.getPointerId(idx).toLong(), + 3, + event.getX(idx) / density, + event.getY(idx) / density, + ) + } + } + } + onTouchDispatched() + return true + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + val handle = handleProvider() + if (handle == 0L) return super.onKeyDown(keyCode, event) + val ime = AffineImeController(handleProvider, onMutated, onTextEdited) + // Yield hardware keyboard navigation/edit keys while IME composition is active. + if (ime.composingStart() >= 0) { + return super.onKeyDown(keyCode, event) + } + val handled = ime.sendKeyEvent( + keyCode = keyCode, + shift = event.isShiftPressed, + ctrl = event.isCtrlPressed, + alt = event.isAltPressed, + ) + drainPendingOpenUrl(context, handle) + if (handled) { + onTouchDispatched() + return true + } + val ch = event.unicodeChar + if (ch > 0 && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed) { + if (ime.commitText(String(Character.toChars(ch)), 1)) { + onTouchDispatched() + return true + } + } + return super.onKeyDown(keyCode, event) + } + + override fun onGenericMotionEvent(event: MotionEvent): Boolean { + val handle = handleProvider() + if (handle != 0L && event.actionMasked == MotionEvent.ACTION_SCROLL) { + val vScroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL) + val hScroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL) + val density = resources.displayMetrics.density.coerceAtLeast(1f) + if (vScroll != 0f || hScroll != 0f) { + val xDp = event.x / density + val yDp = event.y / density + NativeBridge.nativeOnScrollWheel(handle, xDp, yDp, -hScroll * 48f, vScroll * 48f) + onTouchDispatched() + return true + } + } + return super.onGenericMotionEvent(event) + } + + override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { + val af = autofillProvider() + if (af != null && af.focusedFieldId() != null) { + outAttrs.inputType = if (af.isFocusedFieldMasked()) { + InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + } else { + InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + } + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI + val current = af.focusedFieldId()?.let { af.resolveVirtualFieldValueForStructure(it) } ?: "" + outAttrs.initialSelStart = current.length + outAttrs.initialSelEnd = current.length + return AutofillVirtualInputConnection(af, onMutated) + } + val handle = handleProvider() + if (handle == 0L || !NativeBridge.nativeWantsSoftwareKeyboard(handle)) { + outAttrs.inputType = InputType.TYPE_NULL + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI + return null + } + val boundGen = af?.currentFocusGeneration() ?: 0L + return createInputConnection( + handleProvider, + outAttrs, + onMutated, + onTextEdited, + onContextMenuAction, + onCursorUpdatesRequested, + isActiveSession = { + val currentAf = autofillProvider() + currentAf == null || (currentAf.focusedFieldId() == null && currentAf.currentFocusGeneration() == boundGen) + }, + ) + } + + @TargetApi(Build.VERSION_CODES.O) + override fun onProvideAutofillVirtualStructure(structure: ViewStructure, flags: Int) { + super.onProvideAutofillVirtualStructure(structure, flags) + autofillProvider()?.populateVirtualStructure(structure) + } + + @TargetApi(Build.VERSION_CODES.O) + override fun autofill(values: SparseArray) { + autofillProvider()?.onAutofillSparseArray(values) + } + + companion object { + /** Pointer ID for touches that accessibility clicks send; it never collides with a finger. */ + private const val ACCESSIBILITY_POINTER_ID = 1_099_511_627_776L + + internal fun dispatchAutofillBatch( + controller: AndroidAutofillController, + values: Map, + ): Int = controller.onAutofillValues(values) + + internal fun resolveDocumentInputType(wantsCodeInput: Boolean): Int = + if (wantsCodeInput) { + InputType.TYPE_CLASS_TEXT or + InputType.TYPE_TEXT_FLAG_MULTI_LINE or + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + } else { + InputType.TYPE_CLASS_TEXT or + InputType.TYPE_TEXT_FLAG_MULTI_LINE or + InputType.TYPE_TEXT_FLAG_AUTO_CORRECT or + InputType.TYPE_TEXT_FLAG_CAP_SENTENCES + } + + internal fun createInputConnection( + handleProvider: () -> Long, + outAttrs: EditorInfo? = null, + onMutated: () -> Unit = {}, + onTextEdited: (String) -> Unit = {}, + onContextMenuAction: (Int) -> Boolean = { false }, + onCursorUpdatesRequested: (Int) -> Unit = {}, + isActiveSession: () -> Boolean = { true }, + ): InputConnection { + val ime = AffineImeController(handleProvider, onMutated, onTextEdited) + if (outAttrs != null) { + val handle = handleProvider() + val codeMode = handle != 0L && NativeBridge.nativeWantsCodeInput(handle) + outAttrs.inputType = resolveDocumentInputType(codeMode) + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI + outAttrs.initialSelStart = ime.selectionStart() + outAttrs.initialSelEnd = ime.selectionEnd() + } + return AffineInputConnection(ime, onContextMenuAction, onCursorUpdatesRequested, isActiveSession) + } + } +} + +/** + * Isolated virtual-form `InputConnection` used while an Autofill credential field holds focus. + * Reads and writes solely through `AndroidAutofillController` and never invokes + * `NativeBridge.nativeOnCommitText` or mutates the BlockSuite document buffer. + */ +class AutofillVirtualInputConnection( + private val autofillController: AndroidAutofillController, + private val onMutated: () -> Unit = {}, +) : InputConnection { + private val boundFieldId: Int = autofillController.focusedFieldId() ?: 0 + private val boundGeneration: Long = autofillController.currentFocusGeneration() + private var composingRange: IntRange? = null + + private fun isBoundActive(): Boolean = + boundFieldId != 0 && + autofillController.focusedFieldId() == boundFieldId && + autofillController.currentFocusGeneration() == boundGeneration + + private fun currentValue(): String = + if (isBoundActive()) autofillController.resolveVirtualFieldValueForStructure(boundFieldId) ?: "" else "" + + private fun writeValue(next: String): Boolean { + if (!isBoundActive()) { + composingRange = null + return false + } + val ok = autofillController.onFocusedTextEdited(next) + if (ok) onMutated() + return ok + } + + private fun replaceComposingOrAppend(incoming: String, keepComposing: Boolean): Boolean { + if (!isBoundActive()) { + composingRange = null + return false + } + val cur = currentValue() + val range = composingRange + val start: Int + val next = if (range != null && range.first >= 0 && range.last + 1 <= cur.length && range.first <= range.last + 1) { + start = range.first + cur.substring(0, range.first) + incoming + cur.substring(range.last + 1) + } else { + start = cur.length + cur + incoming + } + composingRange = if (keepComposing && incoming.isNotEmpty()) { + start until (start + incoming.length) + } else { + null + } + return writeValue(next) + } + + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean = + replaceComposingOrAppend(text?.toString() ?: "", keepComposing = false) + + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = + replaceComposingOrAppend(text?.toString() ?: "", keepComposing = true) + + override fun finishComposingText(): Boolean { + composingRange = null + return isBoundActive() + } + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + composingRange = null + if (!isBoundActive()) return false + val cur = currentValue() + val keep = (cur.length - beforeLength.coerceAtLeast(0)).coerceAtLeast(0) + return writeValue(cur.substring(0, keep)) + } + + override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence { + val cur = currentValue() + val start = (cur.length - n.coerceAtLeast(0)).coerceAtLeast(0) + return cur.substring(start) + } + + override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = "" + + override fun getSelectedText(flags: Int): CharSequence? = null + + override fun getCursorCapsMode(reqModes: Int): Int = 0 + + override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText? = null + + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean = + deleteSurroundingText(beforeLength, afterLength) + + override fun setComposingRegion(start: Int, end: Int): Boolean { + if (!isBoundActive()) { + composingRange = null + return false + } + val cur = currentValue() + val lo = start.coerceIn(0, cur.length) + val hi = end.coerceIn(lo, cur.length) + composingRange = if (hi > lo) lo until hi else null + return true + } + + override fun commitCompletion(text: CompletionInfo?): Boolean = false + + override fun commitCorrection(correctionInfo: CorrectionInfo?): Boolean = false + + override fun setSelection(start: Int, end: Int): Boolean { + composingRange = null + return isBoundActive() + } + + override fun performEditorAction(editorAction: Int): Boolean = false + + override fun performContextMenuAction(id: Int): Boolean = false + + override fun beginBatchEdit(): Boolean = true + + override fun endBatchEdit(): Boolean = true + + override fun sendKeyEvent(event: KeyEvent?): Boolean = false + + override fun clearMetaKeyStates(states: Int): Boolean = true + + override fun reportFullscreenMode(enabled: Boolean): Boolean = false + + override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = false + + override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean = false + + override fun getHandler(): Handler? = null + + override fun closeConnection() { + composingRange = null + } + + override fun commitContent( + inputContentInfo: InputContentInfo, + flags: Int, + opts: Bundle?, + ): Boolean = false +} + +class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCallback { + companion object { + private val bootstrapRetryExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "affine-bootstrap-retry").apply { isDaemon = true } + } + } + private var nativeHandle: Long = 0L + private lateinit var rootContainer: FrameLayout + private lateinit var surfaceView: AffineSurfaceView + private lateinit var documentHandleView: DocumentSelectionHandleView + private lateinit var bootstrapCoordinator: AndroidBootstrapCoordinator + private lateinit var shareIntentBridge: ShareIntentBridge + private lateinit var backDispatcher: AndroidBackDispatcher + private lateinit var imeController: AffineImeController + private lateinit var clipboardAdapter: HostClipboard + private val documentStore = HostDocumentStore() + private lateinit var documentBufferController: HostDocumentBufferController + private var autofillController: AndroidAutofillController? = null + private var lastImeChangeSeq: Long = 0L + private var lastFocusedBlockHash: Long = 0L + private var clearColorArgb: Int = DEFAULT_SURFACE_CLEAR_COLOR_ARGB + private val docSelectionBuf = FloatArray(24) + private var floatingActionMode: ActionMode? = null + private var lastMenuRequestSeq: Long = 0L + private var pendingActionModeSeq: Long = 0L + private var actionModeRetryScheduled: Boolean = false + private var lastMenuWasCollapsed: Boolean = false + private var lastCollapsedMenuOffset: Int = -1 + private var lastCollapsedMenuBlockHash: Long = 0L + private var lastActionMask: Int = 0 + private var lastMenuLeftPx: Int = 0 + private var lastMenuTopPx: Int = 0 + private var lastMenuRightPx: Int = 0 + private var lastMenuBottomPx: Int = 0 + private var actionModeHiddenForMotion: Boolean = false + private val bootstrap = ShellBootstrapState(maxAutoRetries = 3) + val lastBootstrapOutcome: BootstrapOutcome? + get() = bootstrap.outcome + @Volatile + var currentDestination: String = "workspace/home" + private set + private var frameLoopActive: Boolean = false + private var frameCallbackPosted: Boolean = false + private var surfaceReady: Boolean = false + private var lastObservedPageReadonly: Boolean = false + private var backCallback: OnBackInvokedCallback? = null + private val mainHandler = Handler(Looper.getMainLooper()) + private var lastWantsKeyboard: Boolean = false + private var lastWantsCodeInput: Boolean = false + private var lastDarkTheme: Boolean? = null + private val timerWakeRunnable: Runnable = Runnable { + if (!frameLoopActive || !surfaceReady || nativeHandle == 0L) return@Runnable + val nextDelayMs = NativeBridge.nativeNextTimerDelayMs(nativeHandle) + if (NativeBridge.nativeHasPendingFrame(nativeHandle)) { + scheduleFrameIfNeeded() + } else if (nextDelayMs >= 0L) { + mainHandler.postDelayed(timerWakeRunnable, nextDelayMs.coerceAtLeast(16L)) + } + } + + private val floatingActionCallback: ActionMode.Callback2 = object : ActionMode.Callback2() { + override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { + populateSelectionMenu(menu) + return menu.size() > 0 + } + + override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { + populateSelectionMenu(menu) + return true + } + + override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { + val handled = dispatchEditorSelectionAction(item.itemId) + if (item.itemId != android.R.id.selectAll) { + pendingActionModeSeq = 0L + mode.finish() + } + return handled + } + + override fun onDestroyActionMode(mode: ActionMode) { + if (floatingActionMode === mode) { + floatingActionMode = null + actionModeHiddenForMotion = false + } + } + + override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) { + outRect.set(lastMenuLeftPx, lastMenuTopPx, lastMenuRightPx, lastMenuBottomPx) + } + } + + private fun populateSelectionMenu(menu: Menu) { + menu.clear() + val mask = lastActionMask + if ((mask and 1) != 0) { + menu.add(Menu.NONE, android.R.id.copy, 0, android.R.string.copy) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) + } + if ((mask and 2) != 0) { + menu.add(Menu.NONE, android.R.id.cut, 1, android.R.string.cut) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) + } + if ((mask and 4) != 0 && clipboardAdapter.hasPlainText()) { + menu.add(Menu.NONE, android.R.id.paste, 2, android.R.string.paste) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) + } + if ((mask and 8) != 0) { + menu.add(Menu.NONE, android.R.id.selectAll, 3, android.R.string.selectAll) + .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM) + } + } + + private fun dispatchEditorSelectionAction(actionId: Int): Boolean { + if (nativeHandle == 0L || documentBufferController.isAutofillFocused()) return false + when (actionId) { + android.R.id.copy -> { + NativeBridge.nativeSelectionActionCopy(nativeHandle) + flushPendingClipboardToSystem() + } + android.R.id.cut -> { + NativeBridge.nativeSelectionActionCut(nativeHandle) + flushPendingClipboardToSystem() + } + android.R.id.paste -> { + val (plain, html) = clipboardAdapter.getRichClip() + NativeBridge.nativeSelectionActionPaste(nativeHandle, plain, html, null, null) + } + android.R.id.selectAll -> { + NativeBridge.nativeSelectionActionSelectAll(nativeHandle) + } + else -> return false + } + syncSystemImeFromEditor() + syncDocumentSelectionFromEditor() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + floatingActionMode?.invalidateContentRect() + } + requestFrameAndSchedule() + return true + } + + private fun flushPendingClipboardToSystem() { + if (nativeHandle == 0L) return + val json = NativeBridge.nativeTakePendingClipboardJson(nativeHandle) ?: return + val plain = NativeBridge.nativeExtractJsonStringField(json, "text/plain") ?: "" + val html = NativeBridge.nativeExtractJsonStringField(json, "text/html") + if (plain.isNotEmpty() || !html.isNullOrEmpty()) { + clipboardAdapter.setRichClip("AFFiNE", plain, html) + } + } + + private val reshowActionModeRunnable: Runnable = Runnable { + actionModeRetryScheduled = false + presentFloatingActionModeIfCurrent(pendingActionModeSeq) + } + + private fun dismissFloatingActionMode(clearPending: Boolean = true) { + mainHandler.removeCallbacks(reshowActionModeRunnable) + actionModeRetryScheduled = false + if (clearPending) { + pendingActionModeSeq = 0L + } + floatingActionMode?.finish() + floatingActionMode = null + actionModeHiddenForMotion = false + } + + override fun onCreate(savedInstanceState: Bundle?) { + requestWindowFeature(android.view.Window.FEATURE_NO_TITLE) + super.onCreate(savedInstanceState) + actionBar?.hide() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + window.setDecorFitsSystemWindows(false) + } + + val nowMs = System.currentTimeMillis() + nativeHandle = NativeBridge.nativeCreateShellHost( + java.util.Locale.getDefault().toLanguageTag(), + nowMs, + java.util.TimeZone.getDefault().getOffset(nowMs) / 60_000, + isSystemDark(resources.configuration), + ) + NativeBridge.registerWakeupListener(nativeHandle) { + mainHandler.post { + if (!frameLoopActive || !surfaceReady || nativeHandle == 0L) return@post + val nextDelayMs = NativeBridge.nativeNextTimerDelayMs(nativeHandle) + if (NativeBridge.nativeHasPendingFrame(nativeHandle)) { + scheduleFrameIfNeeded() + } else if (nextDelayMs >= 0L) { + mainHandler.removeCallbacks(timerWakeRunnable) + mainHandler.postDelayed(timerWakeRunnable, nextDelayMs.coerceAtLeast(16L)) + } + } + } + NativeBridge.nativeSetFormFactor( + nativeHandle, + resources.configuration.smallestScreenWidthDp, + ) + NativeBridge.nativeLoadShowcaseDocument(nativeHandle) + lastImeChangeSeq = NativeBridge.nativeGetTextInputChangeSeq(nativeHandle) + lastFocusedBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle) + clipboardAdapter = AndroidClipboardAdapter( + getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager, + ) + documentBufferController = HostDocumentBufferController( + documentStore = documentStore, + imeProvider = { imeController }, + autofillProvider = { autofillController }, + onDocumentPreviewUpdated = { _ -> + syncDocumentSelectionFromEditor() + }, + ) + val onImeMutated: () -> Unit = { + syncSystemImeFromEditor() + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + } + val onImeTextEdited: (String) -> Unit = { text -> + if (imeController.selectionStart() == imeController.selectionEnd()) { + dismissFloatingActionMode() + } + documentBufferController.onImeTextEdited(text) + } + imeController = AffineImeController( + handleProvider = { nativeHandle }, + onMutated = onImeMutated, + onTextEdited = onImeTextEdited, + ) + val onContextMenuAction: (Int) -> Boolean = { actionId -> + dispatchEditorSelectionAction(actionId) + } + backDispatcher = AndroidBackDispatcher( + sdkInt = Build.VERSION.SDK_INT, + handleProvider = { nativeHandle }, + onMutated = { requestFrameAndSchedule() }, + onDestinationChanged = { dest -> + dismissFloatingActionMode() + if (dest != null) { + currentDestination = dest + documentBufferController.onRouteChanged(dest) + } + requestFrameAndSchedule() + }, + onSystemExit = { finish() }, + ) + surfaceView = AffineSurfaceView( + context = this, + handleProvider = { nativeHandle }, + onMutated = onImeMutated, + onTextEdited = onImeTextEdited, + onContextMenuAction = onContextMenuAction, + autofillProvider = { autofillController }, + onTouchDispatched = { + syncSystemImeFromEditor() + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + }, + onCursorUpdatesRequested = { + pushCursorAnchorInfo() + }, + ).apply { + holder.addCallback(this@MainActivity) + } + documentHandleView = DocumentSelectionHandleView( + context = this, + targetSurfaceView = surfaceView, + handleProvider = { nativeHandle }, + isSuppressed = { documentBufferController.isAutofillFocused() }, + onSelectionMutated = { + syncSystemImeFromEditor() + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + }, + onDragStateChanged = { dragging -> + if (dragging) { + dismissFloatingActionMode(clearPending = false) + } else { + syncDocumentSelectionFromEditor() + } + }, + ) + rootContainer = FrameLayout(this).apply { + setBackgroundColor(clearColorArgb) + addView( + surfaceView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + addView( + documentHandleView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + } + setContentView(rootContainer) + + installInsetsBridge(rootContainer) + syncStatusBarAppearance() + installPredictiveBackBridge() + configureAutofillIfSupported() + + bootstrapCoordinator = AndroidBootstrapCoordinator( + handleProvider = { nativeHandle }, + filesDirProvider = { filesDir.absolutePath }, + ) + shareIntentBridge = ShareIntentBridge(handleProvider = { nativeHandle }) + bootstrap.begin(manual = true)?.let { run -> + bootstrapCoordinator.start(LegacyLocalStorageProbe(this)) { outcome -> + applyBootstrapOutcome(run, outcome) + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + bootstrap.onLifecycleEntry( + retry = { retryBootstrapIfNeeded(manual = false) }, + drainShares = ::drainPendingShareIntentIfReady, + ) + } + + override fun onResume() { + super.onResume() + syncSystemDark(resources.configuration) + bootstrap.onLifecycleEntry( + retry = { retryBootstrapIfNeeded(manual = false) }, + drainShares = ::drainPendingShareIntentIfReady, + ) + } + + private fun drainPendingShareIntentIfReady() { + if (nativeHandle == 0L || !::shareIntentBridge.isInitialized || !bootstrap.completed) { + return + } + val drainTargetProvider: () -> ShareIntentBridge.ShareDrainTarget = { + ShareIntentBridge.resolveDrainTarget(bootstrap.completed, bootstrap.outcome) + } + val ingestNow: () -> Int = { + val targetWsKey = when (val target = drainTargetProvider()) { + is ShareIntentBridge.ShareDrainTarget.DurableWorkspace -> target.storageKey + else -> "" + } + val ingested = NativeBridge.nativeIngestSharedItems( + nativeHandle, + targetWsKey, + "", + System.currentTimeMillis(), + ) + if (ingested > 0) { + requestFrameAndSchedule() + } + ingested + } + val inbox = ShareDiskInbox(java.io.File(filesDir, ShareDiskInbox.DEFAULT_DIR_NAME)) + shareIntentBridge.triggerDiskInboxDrainAsync( + inbox = inbox, + drainTargetProvider = drainTargetProvider, + isReady = { nativeHandle != 0L && bootstrap.completed }, + ingestNative = ingestNow, + runNative = { block -> + val latch = java.util.concurrent.CountDownLatch(1) + mainHandler.post { + try { + block() + } finally { + latch.countDown() + } + } + latch.await(5L, java.util.concurrent.TimeUnit.SECONDS) + }, + onBatchQuarantined = { + mainHandler.post { + android.widget.Toast.makeText( + applicationContext, + "Skipped a corrupted shared item batch", + android.widget.Toast.LENGTH_SHORT, + ).show() + } + }, + ) + } + + fun retryBootstrapIfNeeded( + manual: Boolean = true, + onComplete: (BootstrapOutcome) -> Unit = {}, + ) { + if (nativeHandle == 0L) return + val current = bootstrap.outcome + val plan = bootstrap.retryPlan + if (plan == AndroidBootstrapCoordinator.Retry.NONE && current != null) { + onComplete(current) + return + } + val run = bootstrap.begin(manual) ?: return + if (current == null || plan == AndroidBootstrapCoordinator.Retry.RESTART) { + try { + bootstrapCoordinator.start(LegacyLocalStorageProbe(this)) { outcome -> + applyBootstrapOutcome(run, outcome) + onComplete(outcome) + } + } catch (_: Throwable) { + bootstrap.abandon(run) + val fallback = current ?: BootstrapOutcome( + imported = false, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + onComplete(fallback) + } + return + } + bootstrapRetryExecutor.execute { + var updated: BootstrapOutcome = current + try { + updated = bootstrapCoordinator.retryFailedWorkspaces(current) + } catch (_: Throwable) { + updated = current + } finally { + mainHandler.post { + applyBootstrapOutcome(run, updated) + onComplete(updated) + } + } + } + } + + override fun onStart() { + super.onStart() + frameLoopActive = true + scheduleFrameIfNeeded() + } + + override fun onStop() { + frameLoopActive = false + mainHandler.removeCallbacks(timerWakeRunnable) + dismissFloatingActionMode() + if (::documentHandleView.isInitialized) { + documentHandleView.dismissMagnifier() + } + if (frameCallbackPosted) { + Choreographer.getInstance().removeFrameCallback(this) + frameCallbackPosted = false + } + if (nativeHandle != 0L) { + if (bootstrap.workspaceMounted) { + NativeBridge.nativeShellFlushWorkspace(nativeHandle) + } + NativeBridge.nativeStorageCheckpointAllPassive(nativeHandle) + } + super.onStop() + } + + /** + * Records the outcome of bootstrap run [run] (first start, retried start, or + * `retryFailedWorkspaces`), shows its mounted local workspace in the shell in place of the + * showcase, and resumes pending share intents. An outcome of a replaced run is dropped. + */ + private fun applyBootstrapOutcome(run: Long, outcome: BootstrapOutcome) { + if (!bootstrap.finish(run, outcome, ::mountShellWorkspace)) return + drainPendingShareIntentIfReady() + requestFrameAndSchedule() + } + + /** Mounts the shell workspace of [outcome]; `null` when the outcome opened none. */ + private fun mountShellWorkspace(outcome: BootstrapOutcome): Boolean? { + if (nativeHandle == 0L) return null + val workspaceId = bootstrapCoordinator.shellWorkspaceId(outcome) ?: return null + return NativeBridge.nativeShellMountWorkspace( + nativeHandle, + filesDir.absolutePath, + "workspace", + "local", + workspaceId, + workspaceId, + System.currentTimeMillis(), + ) + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + syncSystemDark(newConfig) + } + + /** Lets the shell follow the system dark mode while the activity runs. */ + private fun syncSystemDark(config: Configuration) { + if (nativeHandle != 0L && NativeBridge.nativeShellSetSystemDark(nativeHandle, isSystemDark(config))) { + requestFrameAndSchedule() + } + } + + private fun isSystemDark(config: Configuration): Boolean = + (config.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + + override fun onDestroy() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + backCallback?.let { onBackInvokedDispatcher.unregisterOnBackInvokedCallback(it) } + backCallback = null + } + if (nativeHandle != 0L) { + NativeBridge.unregisterWakeupListener(nativeHandle) + NativeBridge.nativeDestroyHost(nativeHandle) + nativeHandle = 0L + } + super.onDestroy() + } + + override fun doFrame(frameTimeNanos: Long) { + frameCallbackPosted = false + if (!frameLoopActive || !surfaceReady || nativeHandle == 0L) return + NativeBridge.nativeOnFrameTick(nativeHandle, frameTimeNanos) + val pageReadonlyNow = NativeBridge.nativeIsPageReadonly(nativeHandle) + if (lastObservedPageReadonly && !pageReadonlyNow) { + if (ShareDiskInbox(java.io.File(filesDir, ShareDiskInbox.DEFAULT_DIR_NAME)).hasPendingManifests()) { + drainPendingShareIntentIfReady() + } + } + lastObservedPageReadonly = pageReadonlyNow + drainPendingOpenUrl(this, nativeHandle) + syncStatusBarAppearance() + syncSystemImeFromEditor() + syncDocumentSelectionFromEditor() + scheduleFrameIfNeeded() + } + + override fun surfaceCreated(holder: SurfaceHolder) { + surfaceReady = true + if (nativeHandle != 0L) { + NativeBridge.nativeOnSurfaceCreated(nativeHandle, holder.surface) + requestFrameAndSchedule() + } + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { + if (nativeHandle != 0L) { + NativeBridge.nativeOnSurfaceChanged(nativeHandle, format, width, height) + syncDocumentSelectionFromEditor() + if (surfaceReady && width > 0 && height > 0) { + requestFrameAndSchedule() + } + } + } + + private fun presentFloatingActionModeIfCurrent(reqSeq: Long) { + if ( + !frameLoopActive || + nativeHandle == 0L || + !::surfaceView.isInitialized || + reqSeq <= 0L || + reqSeq != pendingActionModeSeq + ) { + return + } + if (documentBufferController.isAutofillFocused()) { + return + } + if (!NativeBridge.nativeFillDocumentSelectionGeometry(nativeHandle, docSelectionBuf)) { + return + } + val hasSelection = docSelectionBuf[0] >= 0.5f + val menuVisible = docSelectionBuf[13] >= 0.5f + val actionMask = docSelectionBuf[18].toInt() + if (!hasSelection || !menuVisible || actionMask == 0) { + return + } + val density = resources.displayMetrics.density.coerceAtLeast(1f) + lastMenuLeftPx = (docSelectionBuf[14] * density).toInt().coerceAtLeast(0) + lastMenuTopPx = (docSelectionBuf[15] * density).toInt().coerceAtLeast(0) + lastMenuRightPx = ((docSelectionBuf[14] + docSelectionBuf[16]) * density).toInt().coerceAtLeast(lastMenuLeftPx + 2) + lastMenuBottomPx = ((docSelectionBuf[15] + docSelectionBuf[17]) * density).toInt().coerceAtLeast(lastMenuTopPx + 2) + lastActionMask = actionMask + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!surfaceView.hasFocus()) { + surfaceView.requestFocus() + } + floatingActionMode?.finish() + floatingActionMode = null + actionModeHiddenForMotion = false + floatingActionMode = surfaceView.startActionMode( + floatingActionCallback, + ActionMode.TYPE_FLOATING, + ) + } + } + + private fun syncDocumentSelectionFromEditor() { + if (nativeHandle == 0L || !::surfaceView.isInitialized || !::documentHandleView.isInitialized) { + return + } + flushPendingClipboardToSystem() + if (documentBufferController.isAutofillFocused()) { + documentHandleView.updateFromDocumentBuffer(FloatArray(0), resources.displayMetrics.density) + pendingActionModeSeq = 0L + dismissFloatingActionMode() + return + } + val density = resources.displayMetrics.density.coerceAtLeast(1f) + if (!NativeBridge.nativeFillDocumentSelectionGeometry(nativeHandle, docSelectionBuf)) { + return + } + documentHandleView.updateFromDocumentBuffer(docSelectionBuf, density) + val hasSelection = docSelectionBuf[0] >= 0.5f + val isCollapsed = docSelectionBuf[1] >= 0.5f + val menuVisible = docSelectionBuf[13] >= 0.5f + val actionMask = docSelectionBuf[18].toInt() + val suppressedForMotion = docSelectionBuf[19] >= 0.5f + val menuReqSeq = NativeBridge.nativeGetSelectionMenuRequestSeq(nativeHandle) + val seqAdvanced = menuReqSeq != lastMenuRequestSeq && menuReqSeq > 0L + + if (!hasSelection || actionMask == 0 || !menuVisible || suppressedForMotion) { + dismissFloatingActionMode(clearPending = !hasSelection || actionMask == 0) + return + } + + val curCaretOffset = imeController.selectionStart() + val curBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle) + if ( + !seqAdvanced && + isCollapsed && + (!lastMenuWasCollapsed || curCaretOffset != lastCollapsedMenuOffset || curBlockHash != lastCollapsedMenuBlockHash) + ) { + dismissFloatingActionMode() + return + } + + val leftPx = (docSelectionBuf[14] * density).toInt().coerceAtLeast(0) + val topPx = (docSelectionBuf[15] * density).toInt().coerceAtLeast(0) + val rightPx = ((docSelectionBuf[14] + docSelectionBuf[16]) * density).toInt().coerceAtLeast(leftPx + 2) + val bottomPx = ((docSelectionBuf[15] + docSelectionBuf[17]) * density).toInt().coerceAtLeast(topPx + 2) + val rectChanged = leftPx != lastMenuLeftPx || topPx != lastMenuTopPx || + rightPx != lastMenuRightPx || bottomPx != lastMenuBottomPx + val maskChanged = actionMask != lastActionMask + lastMenuLeftPx = leftPx + lastMenuTopPx = topPx + lastMenuRightPx = rightPx + lastMenuBottomPx = bottomPx + lastActionMask = actionMask + + if (seqAdvanced) { + lastMenuRequestSeq = menuReqSeq + pendingActionModeSeq = menuReqSeq + lastMenuWasCollapsed = isCollapsed + lastCollapsedMenuOffset = curCaretOffset + lastCollapsedMenuBlockHash = curBlockHash + dismissFloatingActionMode(clearPending = false) + surfaceView.post { presentFloatingActionModeIfCurrent(menuReqSeq) } + } else if (floatingActionMode != null) { + if (maskChanged) { + floatingActionMode?.invalidate() + } + if (rectChanged && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + floatingActionMode?.invalidateContentRect() + } + } else if (pendingActionModeSeq > 0L && pendingActionModeSeq == menuReqSeq && !actionModeRetryScheduled) { + // State-driven re-present whenever soft-keyboard launch (e.g. cold Gboard ~675ms) + // or transient scroll/drag motion finished tearing down the floating ActionMode. + actionModeRetryScheduled = true + mainHandler.postDelayed(reshowActionModeRunnable, 80L) + } + } + + /** + * H-S2: Push editor-initiated selection, block-focus, and caret-anchor changes to Android + * `InputMethodManager` so Gboard/IME candidates stay aligned after Markdown transforms, + * touch caret placement, or block splits/merges. + */ + private fun syncSystemImeFromEditor() { + if (nativeHandle == 0L || !::surfaceView.isInitialized) return + val nextSeq = NativeBridge.nativeGetTextInputChangeSeq(nativeHandle) + val nextBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle) + val wantsKeyboard = NativeBridge.nativeWantsSoftwareKeyboard(nativeHandle) + val wantsCodeInput = NativeBridge.nativeWantsCodeInput(nativeHandle) + val wantsKeyboardChanged = wantsKeyboard != lastWantsKeyboard + val codeModeChanged = wantsCodeInput != lastWantsCodeInput + if (nextSeq == lastImeChangeSeq && nextBlockHash == lastFocusedBlockHash && !wantsKeyboardChanged && !codeModeChanged) { + return + } + val blockChanged = nextBlockHash != lastFocusedBlockHash + lastImeChangeSeq = nextSeq + lastFocusedBlockHash = nextBlockHash + lastWantsKeyboard = wantsKeyboard + lastWantsCodeInput = wantsCodeInput + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return + if (!wantsKeyboard) { + imm.hideSoftInputFromWindow(surfaceView.windowToken, 0) + } + if (blockChanged || wantsKeyboardChanged || codeModeChanged) { + imm.restartInput(surfaceView) + } else if (wantsKeyboard) { + imm.updateSelection( + surfaceView, + imeController.selectionStart(), + imeController.selectionEnd(), + imeController.composingStart(), + imeController.composingEnd(), + ) + } + if (wantsKeyboard) { + pushCursorAnchorInfo(imm) + } + } + + private fun pushCursorAnchorInfo(existingImm: InputMethodManager? = null) { + if (nativeHandle == 0L || !::surfaceView.isInitialized) return + val imm = existingImm + ?: (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager) + ?: return + val density = resources.displayMetrics.density.coerceAtLeast(1f) + val cx = NativeBridge.nativeGetCaretRectDpX(nativeHandle) * density + val cy = NativeBridge.nativeGetCaretRectDpY(nativeHandle) * density + val ch = NativeBridge.nativeGetCaretRectDpHeight(nativeHandle) * density + val loc = IntArray(2) + surfaceView.getLocationOnScreen(loc) + val matrix = android.graphics.Matrix(surfaceView.matrix).apply { + postTranslate(loc[0].toFloat(), loc[1].toFloat()) + } + val anchor = CursorAnchorInfo.Builder() + .setMatrix(matrix) + .setSelectionRange(imeController.selectionStart(), imeController.selectionEnd()) + .setInsertionMarkerLocation(cx, cy, cy + ch * 0.8f, cy + ch, CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION) + .build() + imm.updateCursorAnchorInfo(surfaceView, anchor) + } + + override fun surfaceDestroyed(holder: SurfaceHolder) { + surfaceReady = false + mainHandler.removeCallbacks(timerWakeRunnable) + if (frameCallbackPosted) { + Choreographer.getInstance().removeFrameCallback(this) + frameCallbackPosted = false + } + if (nativeHandle != 0L) { + NativeBridge.nativeOnSurfaceDestroyed(nativeHandle) + } + } + + private fun requestFrameAndSchedule() { + if (nativeHandle == 0L) return + NativeBridge.nativeRequestFrame(nativeHandle) + scheduleFrameIfNeeded() + } + + private fun scheduleFrameIfNeeded() { + if (!frameLoopActive || !surfaceReady || frameCallbackPosted || nativeHandle == 0L) return + mainHandler.removeCallbacks(timerWakeRunnable) + if (NativeBridge.nativeHasPendingFrame(nativeHandle)) { + frameCallbackPosted = true + Choreographer.getInstance().postFrameCallback(this) + return + } + val nextDelayMs = NativeBridge.nativeNextTimerDelayMs(nativeHandle) + if (NativeBridge.nativeHasPendingFrame(nativeHandle)) { + frameCallbackPosted = true + Choreographer.getInstance().postFrameCallback(this) + } else if (nextDelayMs >= 0L) { + mainHandler.postDelayed(timerWakeRunnable, nextDelayMs.coerceAtLeast(16L)) + } + } + + @Suppress("DEPRECATION") + private fun syncStatusBarAppearance() { + if (nativeHandle == 0L) return + val isDark = NativeBridge.nativeIsDarkTheme(nativeHandle) + if (lastDarkTheme == isDark) return + lastDarkTheme = isDark + val isLight = !isDark + val bg = if (isDark) 0xFF141414.toInt() else 0xFFFFFFFF.toInt() + clearColorArgb = bg + if (::rootContainer.isInitialized) { + rootContainer.setBackgroundColor(bg) + } + window.decorView.setBackgroundColor(bg) + window.statusBarColor = Color.TRANSPARENT + window.navigationBarColor = Color.TRANSPARENT + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + window.isNavigationBarContrastEnforced = false + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or + WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS + val appearance = if (isLight) mask else 0 + window.insetsController?.setSystemBarsAppearance(appearance, mask) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + val decor = window.decorView + var flags = decor.systemUiVisibility + flags = if (isLight) { + flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR + } else { + flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + flags = if (isLight) { + flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + } else { + flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() + } + } + decor.systemUiVisibility = flags + } + } + + @Suppress("DEPRECATION") + override fun onBackPressed() { + if (floatingActionMode != null) { + dismissFloatingActionMode() + return + } + if (nativeHandle != 0L && NativeBridge.nativeHandleBack(nativeHandle)) { + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + return + } + val consumed = backDispatcher.onLegacyBackPressed(invokeSystemExit = false) + if (!consumed) { + super.onBackPressed() + } + } + + private fun installInsetsBridge(root: View) { + root.setOnApplyWindowInsetsListener { v, insets -> + forwardInsets(v, insets) + insets + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + root.setWindowInsetsAnimationCallback( + object : WindowInsetsAnimation.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) { + override fun onProgress( + insets: WindowInsets, + runningAnimations: MutableList, + ): WindowInsets { + forwardInsets(root, insets) + return insets + } + }, + ) + } + } + + @Suppress("DEPRECATION") + private fun forwardInsets(root: View, insets: WindowInsets) { + if (nativeHandle == 0L) return + val density = resources.displayMetrics.density + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val bars = insets.getInsets( + WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout(), + ) + val ime = insets.getInsets(WindowInsets.Type.ime()) + // Inset the SurfaceView container to systemBars() so the editor top bar and + // bottom toolbar stay clear of the status bar and navigation gesture bar. + if (root.paddingLeft != bars.left || root.paddingTop != bars.top || + root.paddingRight != bars.right || root.paddingBottom != bars.bottom + ) { + root.setPadding(bars.left, bars.top, bars.right, bars.bottom) + } + val imeAboveBars = maxOf(0, ime.bottom - bars.bottom) + NativeBridge.nativeOnSurfaceInsetsPx( + nativeHandle, + 0, + 0, + 0, + 0, + imeAboveBars, + density, + ) + } else { + val left = insets.systemWindowInsetLeft + val top = insets.systemWindowInsetTop + val right = insets.systemWindowInsetRight + val bottom = insets.systemWindowInsetBottom + if (root.paddingLeft != left || root.paddingTop != top || + root.paddingRight != right || root.paddingBottom != bottom + ) { + root.setPadding(left, top, right, bottom) + } + NativeBridge.nativeOnSurfaceInsetsPx( + nativeHandle, + 0, + 0, + 0, + 0, + 0, + density, + ) + } + syncDocumentSelectionFromEditor() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + floatingActionMode?.invalidateContentRect() + } + requestFrameAndSchedule() + } + + private fun installPredictiveBackBridge() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + val callback = object : OnBackAnimationCallback { + override fun onBackStarted(backEvent: BackEvent) { + backDispatcher.onBackStarted(backEvent.progress) + } + + override fun onBackProgressed(backEvent: BackEvent) { + backDispatcher.onBackProgressed(backEvent.progress) + } + + override fun onBackCancelled() { + backDispatcher.onBackCancelled() + } + + override fun onBackInvoked() { + if (floatingActionMode != null) { + dismissFloatingActionMode() + return + } + if (nativeHandle != 0L && NativeBridge.nativeHandleBack(nativeHandle)) { + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + return + } + backDispatcher.onBackInvoked() + } + } + backCallback = callback + onBackInvokedDispatcher.registerOnBackInvokedCallback( + OnBackInvokedDispatcher.PRIORITY_DEFAULT, + callback, + ) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val callback = OnBackInvokedCallback { + if (floatingActionMode != null) { + dismissFloatingActionMode() + return@OnBackInvokedCallback + } + if (nativeHandle != 0L && NativeBridge.nativeHandleBack(nativeHandle)) { + syncDocumentSelectionFromEditor() + requestFrameAndSchedule() + return@OnBackInvokedCallback + } + backDispatcher.onLegacyBackPressed() + } + backCallback = callback + onBackInvokedDispatcher.registerOnBackInvokedCallback( + OnBackInvokedDispatcher.PRIORITY_DEFAULT, + callback, + ) + } + } + + private fun configureAutofillIfSupported() { + val platformBackend = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + NativeBridge.nativeShouldExposeAutofill(Build.VERSION.SDK_INT) + ) { + getSystemService(AutofillManager::class.java)?.let { manager -> + SystemAutofillPlatformBackend(surfaceView, manager) + } + } else { + null + } + autofillController = AndroidAutofillController( + sdkInt = Build.VERSION.SDK_INT, + handleProvider = { nativeHandle }, + backend = platformBackend, + onMutated = { requestFrameAndSchedule() }, + ).apply { + onFocusGenerationChanged = { + if (::surfaceView.isInitialized) { + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.restartInput(surfaceView) + } + } + } + } + + fun navigateTo(destination: String): Boolean = backDispatcher.navigateTo(destination) + + fun openDocument(docId: String): Boolean = backDispatcher.openDocument(docId) + + fun readAutofillFormValues(): Map = + autofillController?.readFormValues() ?: emptyMap() + + fun registerAutofillField( + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int = 0, + ): Boolean = autofillController?.registerField( + autofillId, + kindCode, + left, + top, + right, + bottom, + masked, + valueLen, + ) ?: false + + fun focusAutofillField(autofillId: Int?) { + documentBufferController.onAutofillFocusChanged(autofillId) + } + + fun commitAutofillSession(): Boolean = documentBufferController.commitAutofillSession() + + fun cancelAutofillSession(): Boolean = documentBufferController.cancelAutofillSession() + + fun clearAutofillFields() { + documentBufferController.clearAutofillFields() + } +} + +/** + * Virtual view IDs and the accessibility focus of the shell's accessibility nodes. Each node ID + * keeps one positive virtual view ID for the life of the view, so IDs stay the same when other + * nodes come and go; IDs count up and never take `HOST_VIEW_ID` or `View.NO_ID`. + */ +internal class ShellAccessibilityViews( + private val accessibilityEnabled: () -> Boolean = { true }, + private val sendEvent: (virtualViewId: Int, eventType: Int) -> Unit = { _, _ -> }, +) { + private val virtualIdsByNodeId = HashMap() + private var nextVirtualId = 1 + private var nodes: Map = emptyMap() + + /** Virtual view ID that holds accessibility focus, or `View.NO_ID`. */ + var focusedVirtualId: Int = View.NO_ID + private set + + /** Replace the published nodes; focus on a node that left clears. */ + fun update(published: List) { + val next = LinkedHashMap() + for (node in published) { + next[virtualIdsByNodeId.getOrPut(node.id) { nextVirtualId++ }] = node + } + nodes = next + if (focusedVirtualId !in nodes) { + focusedVirtualId = View.NO_ID + } + } + + fun virtualIds(): Collection = nodes.keys + + fun virtualId(nodeId: String): Int? = virtualIdsByNodeId[nodeId]?.takeIf { it in nodes } + + fun node(virtualViewId: Int): ShellAccessibilityNode? = nodes[virtualViewId] + + /** Returns `true` when focus moved to `virtualViewId`. */ + fun focus(virtualViewId: Int): Boolean { + if (virtualViewId !in nodes || focusedVirtualId == virtualViewId) return false + focusedVirtualId = virtualViewId + return true + } + + /** Returns `true` when `virtualViewId` held focus and lost it. */ + fun clearFocus(virtualViewId: Int): Boolean { + if (focusedVirtualId != virtualViewId) return false + focusedVirtualId = View.NO_ID + return true + } + + /** + * Apply `ACTION_ACCESSIBILITY_FOCUS` or `ACTION_CLEAR_ACCESSIBILITY_FOCUS` to + * `virtualViewId` and announce the change. Returns `true` when the focus changed. + */ + fun performFocusAction(virtualViewId: Int, action: Int): Boolean { + val event = when (action) { + AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS -> + if (focus(virtualViewId)) AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED else return false + AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS -> + if (clearFocus(virtualViewId)) AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED else return false + else -> return false + } + announce(virtualViewId, event) + return true + } + + /** Send `eventType` for `virtualViewId` while an accessibility service runs. */ + fun announce(virtualViewId: Int, eventType: Int) { + if (accessibilityEnabled()) sendEvent(virtualViewId, eventType) + } +} + +/** One shell accessibility node that `AffineSurfaceView` publishes as a virtual view, in dp. */ +internal data class ShellAccessibilityNode( + val id: String, + val role: String, + val name: String, + val x: Float, + val y: Float, + val width: Float, + val height: Float, +) { + val clickable: Boolean + get() = role in CLICKABLE_ROLES + + val className: String + get() = when (role) { + "button", "tab" -> "android.widget.Button" + "textField" -> "android.widget.EditText" + "heading", "status" -> "android.widget.TextView" + else -> "android.view.View" + } + + companion object { + private val CLICKABLE_ROLES = setOf("button", "link", "listItem", "tab", "textField") + private const val STRING = "\"((?:[^\"\\\\]|\\\\.)*)\"" + private const val NUMBER = "(-?[0-9.eE+-]+)" + private val NODE = Regex( + "\"id\":$STRING,\"role\":\"(\\w+)\",\"name\":$STRING.*?" + + "\"bounds\":\\{\"x\":$NUMBER,\"y\":$NUMBER,\"width\":$NUMBER,\"height\":$NUMBER\\}", + ) + + /** Visible nodes of the shell's `AccessibilityTree` JSON, top to bottom. */ + fun parse(json: String): List = + NODE.findAll(json) + .map { m -> + val v = m.groupValues + ShellAccessibilityNode( + unescape(v[1]), + v[2], + unescape(v[3]), + v[4].toFloat(), + v[5].toFloat(), + v[6].toFloat(), + v[7].toFloat(), + ) + } + .filter { it.width > 0f && it.height > 0f && it.name.isNotEmpty() } + .sortedWith(compareBy({ it.y }, { it.x })) + .toList() + + private fun unescape(text: String): String { + if (!text.contains('\\')) return text + val out = StringBuilder(text.length) + var i = 0 + while (i < text.length) { + val c = text[i] + if (c == '\\' && i + 1 < text.length) { + val next = text[i + 1] + when (next) { + 'n' -> out.append('\n') + 't' -> out.append('\t') + 'u' -> if (i + 5 < text.length) { + out.append(text.substring(i + 2, i + 6).toInt(16).toChar()) + i += 4 + } + else -> out.append(next) + } + i += 2 + } else { + out.append(c) + i += 1 + } + } + return out.toString() + } + } +} diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt new file mode 100644 index 0000000000..139e4ccc0b --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt @@ -0,0 +1,1408 @@ +package app.affine.pro.host + +import android.content.ContentResolver +import android.content.Intent +import android.net.Uri +import java.io.ByteArrayOutputStream +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.util.UUID + +/** + * Durable `/share-inbox/` queue written by [ShareReceiverActivity] and drained by + * [MainActivity] after `AndroidBootstrapCoordinator` mounts local SQLite workspaces. + * + * Uses pure `java.io` length-prefixed binary manifests (`AFSH` v1) so both Android ART and + * standalone JVM parity tests (`kotlin -cp ...:android.jar`) execute identical persistence, + * quarantine, and SQLite-receipt-gated deletion logic without stubbed `android.*` / `org.json.*` classes. + */ +class ShareDiskInbox( + private val inboxDir: File, +) { + companion object { + const val DEFAULT_DIR_NAME: String = "share-inbox" + const val INVALID_DIR_NAME: String = "invalid" + const val MAX_INGEST_ATTEMPTS: Int = 3 + const val MAX_BATCH_ITEMS: Int = 256 + const val MAX_PENDING_BATCHES: Int = 64 + const val MAX_TOTAL_INBOX_BYTES: Long = 128L * 1024L * 1024L + const val MAX_INVALID_QUARANTINE_BYTES: Long = 80L * 1024L * 1024L + const val ORPHAN_SWEEP_AGE_MS: Long = 60_000L + private const val MAX_MANIFEST_STRING_BYTES: Int = 16 * 1024 * 1024 + private const val MANIFEST_MAGIC: Int = 0x41465348 // "AFSH" + private const val MANIFEST_VERSION_LEGACY: Int = 1 + private const val MANIFEST_VERSION: Int = 2 + private val inboxLocks = java.util.concurrent.ConcurrentHashMap() + + private fun lockFor(dir: File): Any { + val key = runCatching { dir.canonicalPath }.getOrElse { dir.absolutePath } + return inboxLocks.computeIfAbsent(key) { Any() } + } + } + + data class PersistedShareItem( + val id: String, + val kind: Int, + val title: String, + val content: String, + val mimeType: String, + val attachmentFileName: String?, + ) + + data class PersistedShareBatch( + val batchId: String, + val createdAtMs: Long, + val items: List, + ) + + enum class ShareRejectReason { + NONE, + UNSUPPORTED_PAYLOAD, + STREAM_UNREADABLE, + OVERSIZE_ITEM, + BATCH_LIMIT_EXCEEDED, + QUOTA_EXCEEDED, + STORAGE_UNAVAILABLE, + } + + data class WriteBatchResult( + val batch: PersistedShareBatch?, + val skippedCount: Int, + val rejectReason: ShareRejectReason = ShareRejectReason.NONE, + ) + + val invalidDir: File + get() = File(inboxDir, INVALID_DIR_NAME) + + private fun sanitizeId(raw: String): String { + val sb = StringBuilder(raw.length) + for (ch in raw) { + if (ch.isLetterOrDigit() || ch == '-' || ch == '_') { + sb.append(ch) + } else { + sb.append('_') + } + } + return if (sb.isEmpty()) UUID.randomUUID().toString() else sb.toString() + } + + private fun safeChildFile(fileName: String): File? { + val trimmed = fileName.trim() + if (trimmed.isEmpty() || trimmed.contains('/') || trimmed.contains('\\') || trimmed == "." || trimmed == "..") { + return null + } + val candidate = File(inboxDir, trimmed) + val baseCanon = runCatching { inboxDir.canonicalPath }.getOrNull() ?: return null + val candCanon = runCatching { candidate.canonicalPath }.getOrNull() ?: return null + return if (candCanon.startsWith("$baseCanon${File.separator}")) candidate else null + } + + private fun moveFileIntoDir(src: File, destDir: File) { + if (!src.isFile) return + if (!destDir.exists() && !destDir.mkdirs()) return + val dest = File(destDir, src.name) + if (!src.renameTo(dest)) { + runCatching { + src.copyTo(dest, overwrite = true) + src.delete() + } + } + } + + private fun writeLengthPrefixedUtf8(out: DataOutputStream, value: String) { + val utf8 = value.toByteArray(Charsets.UTF_8) + if (utf8.size > MAX_MANIFEST_STRING_BYTES) { + throw IllegalArgumentException("manifest string exceeds $MAX_MANIFEST_STRING_BYTES bytes") + } + out.writeInt(utf8.size) + out.write(utf8) + } + + private fun readLengthPrefixedUtf8(input: DataInputStream): String { + val len = input.readInt() + if (len < 0 || len > MAX_MANIFEST_STRING_BYTES) { + throw IllegalArgumentException("invalid manifest string length: $len") + } + val buf = ByteArray(len) + input.readFully(buf) + return String(buf, Charsets.UTF_8) + } + + private fun quarantineGroupKey(fileName: String): String = when { + fileName.endsWith(".manifest") -> fileName.removeSuffix(".manifest") + fileName.contains("-att-") -> fileName.substringBeforeLast("-att-") + else -> fileName + } + + private fun sortedQuarantineGroupsLocked(): List, Long>> { + val dir = invalidDir + if (!dir.isDirectory) return emptyList() + val files = dir.listFiles { f -> f.isFile } ?: return emptyList() + return files.groupBy { quarantineGroupKey(it.name) } + .entries + .sortedWith( + compareBy>> { entry -> + entry.value.minOf { it.lastModified() } + }.thenBy { it.key }, + ) + .map { entry -> entry.value to entry.value.sumOf { it.length() } } + } + + private fun pruneInvalidDirIfNeeded() { + val groups = sortedQuarantineGroupsLocked().toMutableList() + var total = groups.sumOf { it.second } + while (total > MAX_INVALID_QUARANTINE_BYTES && groups.isNotEmpty()) { + val (oldestGroup, _) = groups.removeAt(0) + for (member in oldestGroup) { + val len = member.length() + if (runCatching { member.delete() }.getOrDefault(false)) { + total = (total - len).coerceAtLeast(0L) + } + } + } + } + + /** + * Reclaims the oldest complete quarantined groups inside `invalid/` when quota pressure comes + * from historical quarantine files. Deletes nothing unless evicting quarantine groups can free + * at least [neededBytes], and never touches valid pending batches in `inboxDir`. + * Caller must hold `lockFor(inboxDir)`. + */ + private fun reclaimQuarantineForIncomingLocked(neededBytes: Long) { + if (neededBytes <= 0L) return + val groups = sortedQuarantineGroupsLocked() + if (groups.isEmpty()) return + val toEvict = mutableListOf>() + var plannedBytes = 0L + for ((members, groupBytes) in groups) { + toEvict.add(members) + plannedBytes += groupBytes + if (plannedBytes >= neededBytes) break + } + if (plannedBytes < neededBytes) { + return + } + for (members in toEvict) { + for (member in members) { + runCatching { member.delete() } + } + } + } + + private fun totalInboxBytesRecursive(): Long { + if (!inboxDir.isDirectory) return 0L + return inboxDir.walkTopDown().filter { it.isFile }.sumOf { it.length() } + } + + private fun quarantineCorruptManifest(manifestFile: File, batchPrefix: String) { + val targetDir = invalidDir + val attPrefix = "$batchPrefix-att-" + inboxDir.listFiles()?.forEach { child -> + if (child.isFile && child.name.startsWith(attPrefix)) { + moveFileIntoDir(child, targetDir) + } else if (child.isFile && child.name == "$batchPrefix.attempts") { + runCatching { child.delete() } + } + } + moveFileIntoDir(manifestFile, targetDir) + pruneInvalidDirIfNeeded() + } + + /** + * Sweeps top-level unmanifested crash leftovers (`*-att-*.bin`, `*.tmp`, `*.attempts` without a + * matching `.manifest`). Under normal writes, leaves files younger than + * [ORPHAN_SWEEP_AGE_MS] untouched; when `aggressive == true` (quota pressure), reclaims all + * unmanifested leftovers immediately. Concurrent in-process writes are serialized by + * `lockFor(inboxDir)`, which the caller must hold. + */ + private fun collectManifestAttachmentNames(manifestFile: File): Set { + return runCatching { + DataInputStream(FileInputStream(manifestFile)).use { input -> + val magic = input.readInt() + val version = input.readInt() + if (magic != MANIFEST_MAGIC || (version != MANIFEST_VERSION && version != MANIFEST_VERSION_LEGACY)) { + return@use emptySet() + } + val readStr: () -> String = if (version == MANIFEST_VERSION) { + { readLengthPrefixedUtf8(input) } + } else { + { input.readUTF() } + } + readStr() // batchId + input.readLong() // createdAtMs + val count = input.readInt() + if (count <= 0 || count > MAX_BATCH_ITEMS) return@use emptySet() + val names = HashSet(count) + repeat(count) { + readStr() // id + input.readInt() // kind + readStr() // title + readStr() // content + readStr() // mimeType + if (input.readBoolean()) { + names.add(readStr()) + } + } + names + } + }.getOrDefault(emptySet()) + } + + private fun sweepUnmanifestedOrphansLocked(nowMs: Long, aggressive: Boolean = false) { + if (!inboxDir.isDirectory) return + val topFiles = inboxDir.listFiles { f -> f.isFile } ?: return + val manifestPrefixes = HashSet() + val referencedAttachments = HashSet() + for (file in topFiles) { + if (file.name.endsWith(".manifest")) { + manifestPrefixes.add(file.name.removeSuffix(".manifest")) + referencedAttachments.addAll(collectManifestAttachmentNames(file)) + } + } + for (file in topFiles) { + val name = file.name + if (name.endsWith(".manifest") || referencedAttachments.contains(name)) continue + val ageMs = nowMs - file.lastModified() + if (!aggressive && ageMs < ORPHAN_SWEEP_AGE_MS) continue + val orphanPrefix: String? = when { + name.endsWith(".manifest.tmp") -> name.removeSuffix(".manifest.tmp") + name.contains("-att-") && name.endsWith(".bin.tmp") -> name.substringBeforeLast("-att-") + name.endsWith(".tmp") -> name.removeSuffix(".tmp") + name.endsWith(".attempts") -> { + val prefix = name.removeSuffix(".attempts") + if (!manifestPrefixes.contains(prefix)) prefix else null + } + name.contains("-att-") && name.endsWith(".bin") -> { + val prefix = name.substringBeforeLast("-att-") + if (!manifestPrefixes.contains(prefix)) prefix else null + } + else -> null + } + if (orphanPrefix != null) { + runCatching { file.delete() } + } + } + } + + /** Fast lock-free check for whether any `.manifest` file is waiting in `/share-inbox/`. */ + fun hasPendingManifests(): Boolean { + if (!inboxDir.isDirectory) return false + val names = inboxDir.list() ?: return false + return names.any { it.endsWith(".manifest") } + } + + /** + * Validates and atomically persists one incoming share intent to `/share-inbox/`, + * returning both the persisted batch (or `null`), the count of skipped/rejected items, and + * the specific [ShareRejectReason] when `batch == null`. + * + * Single counting contract: `preOversizeCount`, `preUnavailableCount`, and `preCappedCount` + * strictly count URIs filtered out before `streamUris` (and therefore absent from `streamUris`). + */ + fun writeBatchWithStats( + action: String, + mimeType: String, + subject: String, + text: String?, + streamUris: List, + streamBytes: Map, + streamMimeTypes: Map = emptyMap(), + preOversizeCount: Int = 0, + preUnavailableCount: Int = 0, + preCappedCount: Int = 0, + batchId: String = UUID.randomUUID().toString(), + createdAtMs: Long = System.currentTimeMillis(), + ): WriteBatchResult { + val safeBatchId = sanitizeId(batchId) + val parsedResult = ShareIntentBridge.buildParsedItemsWithStats( + action = action, + mimeType = mimeType, + subject = subject, + text = text, + streamUris = streamUris, + streamBytes = streamBytes, + streamMimeTypes = streamMimeTypes, + idPrefix = safeBatchId, + ) + val parsed = parsedResult.items + val totalSkippedBeforeWrite = + parsedResult.skippedCount + + preOversizeCount.coerceAtLeast(0) + + preUnavailableCount.coerceAtLeast(0) + + preCappedCount.coerceAtLeast(0) + if (parsed.isEmpty()) { + val reason = when { + parsedResult.oversizeCount + preOversizeCount > 0 -> ShareRejectReason.OVERSIZE_ITEM + parsedResult.unreadableCount + preUnavailableCount > 0 -> ShareRejectReason.STREAM_UNREADABLE + parsedResult.cappedCount + preCappedCount > 0 -> ShareRejectReason.BATCH_LIMIT_EXCEEDED + else -> ShareRejectReason.UNSUPPORTED_PAYLOAD + } + return WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite, + rejectReason = reason, + ) + } + + val persistedItems = parsed.mapIndexed { idx, candidate -> + PersistedShareItem( + id = candidate.id, + kind = candidate.kind, + title = candidate.title, + content = candidate.content, + mimeType = candidate.mimeType, + attachmentFileName = if (candidate.bytes != null) "$safeBatchId-att-$idx.bin" else null, + ) + } + val manifestBytes = try { + val baos = ByteArrayOutputStream() + DataOutputStream(baos).use { out -> + out.writeInt(MANIFEST_MAGIC) + out.writeInt(MANIFEST_VERSION) + writeLengthPrefixedUtf8(out, safeBatchId) + out.writeLong(createdAtMs) + out.writeInt(persistedItems.size) + for (item in persistedItems) { + writeLengthPrefixedUtf8(out, item.id) + out.writeInt(item.kind) + writeLengthPrefixedUtf8(out, item.title) + writeLengthPrefixedUtf8(out, item.content) + writeLengthPrefixedUtf8(out, item.mimeType) + out.writeBoolean(item.attachmentFileName != null) + if (item.attachmentFileName != null) { + writeLengthPrefixedUtf8(out, item.attachmentFileName) + } + } + out.flush() + } + baos.toByteArray() + } catch (_: Throwable) { + return WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.OVERSIZE_ITEM, + ) + } + val attachmentBytes = parsed.sumOf { (it.bytes?.size ?: 0).toLong() } + + return synchronized(lockFor(inboxDir)) { + if (!inboxDir.exists() && !inboxDir.mkdirs()) { + return@synchronized WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.STORAGE_UNAVAILABLE, + ) + } + pruneInvalidDirIfNeeded() + sweepUnmanifestedOrphansLocked(createdAtMs) + val topFiles = inboxDir.listFiles { f -> f.isFile } ?: emptyArray() + val pendingManifestCount = topFiles.count { it.name.endsWith(".manifest") } + if (pendingManifestCount >= MAX_PENDING_BATCHES) { + return@synchronized WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.QUOTA_EXCEEDED, + ) + } + if (safeChildFile("$safeBatchId.manifest")?.exists() == true) { + return@synchronized WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.STORAGE_UNAVAILABLE, + ) + } + + val incomingBytes = attachmentBytes + manifestBytes.size.toLong() + var existingBytes = totalInboxBytesRecursive() + if (existingBytes + incomingBytes > MAX_TOTAL_INBOX_BYTES) { + sweepUnmanifestedOrphansLocked(createdAtMs, aggressive = true) + existingBytes = totalInboxBytesRecursive() + if (existingBytes + incomingBytes > MAX_TOTAL_INBOX_BYTES) { + reclaimQuarantineForIncomingLocked(existingBytes + incomingBytes - MAX_TOTAL_INBOX_BYTES) + existingBytes = totalInboxBytesRecursive() + if (existingBytes + incomingBytes > MAX_TOTAL_INBOX_BYTES) { + return@synchronized WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.QUOTA_EXCEEDED, + ) + } + } + } + + val writtenAttachments = mutableListOf() + try { + parsed.forEachIndexed { idx, candidate -> + if (candidate.bytes != null) { + val name = "$safeBatchId-att-$idx.bin" + val dest = safeChildFile(name) ?: throw IllegalStateException("unsafe attachment path") + val tmp = safeChildFile("$name.tmp") ?: throw IllegalStateException("unsafe temp path") + FileOutputStream(tmp).use { out -> + out.write(candidate.bytes) + out.fd.sync() + } + if (!tmp.renameTo(dest)) { + tmp.copyTo(dest, overwrite = true) + tmp.delete() + } + writtenAttachments.add(dest) + } + } + + val manifestTmp = safeChildFile("$safeBatchId.manifest.tmp") + ?: throw IllegalStateException("unsafe manifest tmp") + val manifestDest = safeChildFile("$safeBatchId.manifest") + ?: throw IllegalStateException("unsafe manifest dest") + FileOutputStream(manifestTmp).use { fos -> + fos.write(manifestBytes) + fos.flush() + fos.fd.sync() + } + if (!manifestTmp.renameTo(manifestDest)) { + manifestTmp.copyTo(manifestDest, overwrite = true) + manifestTmp.delete() + } + WriteBatchResult( + batch = PersistedShareBatch( + batchId = safeBatchId, + createdAtMs = createdAtMs, + items = persistedItems, + ), + skippedCount = totalSkippedBeforeWrite, + rejectReason = ShareRejectReason.NONE, + ) + } catch (_: Throwable) { + writtenAttachments.forEach { runCatching { it.delete() } } + safeChildFile("$safeBatchId.manifest.tmp")?.delete() + safeChildFile("$safeBatchId.manifest")?.delete() + WriteBatchResult( + batch = null, + skippedCount = totalSkippedBeforeWrite + parsed.size, + rejectReason = ShareRejectReason.STORAGE_UNAVAILABLE, + ) + } + } + } + + /** + * Validates and atomically persists one incoming share intent to `/share-inbox/`. + * Returns `null` without leaving orphan files if zero valid items could be accepted. + */ + fun writeBatch( + action: String, + mimeType: String, + subject: String, + text: String?, + streamUris: List, + streamBytes: Map, + streamMimeTypes: Map = emptyMap(), + batchId: String = UUID.randomUUID().toString(), + createdAtMs: Long = System.currentTimeMillis(), + ): PersistedShareBatch? = writeBatchWithStats( + action = action, + mimeType = mimeType, + subject = subject, + text = text, + streamUris = streamUris, + streamBytes = streamBytes, + streamMimeTypes = streamMimeTypes, + batchId = batchId, + createdAtMs = createdAtMs, + ).batch + + /** Lists pending persisted batches in deterministic `(createdAtMs, batchId)` FIFO order. */ + fun listPendingBatches( + nowMs: Long = System.currentTimeMillis(), + ): List = synchronized(lockFor(inboxDir)) { + sweepUnmanifestedOrphansLocked(nowMs) + val files = inboxDir.listFiles { f -> f.isFile && f.name.endsWith(".manifest") } ?: return@synchronized emptyList() + val batches = mutableListOf() + for (file in files) { + val decoded = runCatching { + DataInputStream(FileInputStream(file)).use { input -> + val magic = input.readInt() + val version = input.readInt() + if (magic != MANIFEST_MAGIC || (version != MANIFEST_VERSION && version != MANIFEST_VERSION_LEGACY)) { + return@use null + } + val readStr: () -> String = if (version == MANIFEST_VERSION) { + { readLengthPrefixedUtf8(input) } + } else { + { input.readUTF() } + } + val batchId = readStr() + val createdAtMs = input.readLong() + val count = input.readInt() + if (count <= 0 || count > MAX_BATCH_ITEMS) { + return@use null + } + val items = ArrayList(count) + repeat(count) { + val id = readStr() + val kind = input.readInt() + val title = readStr() + val content = readStr() + val mimeType = readStr() + val hasAtt = input.readBoolean() + val attName = if (hasAtt) readStr() else null + items.add( + PersistedShareItem( + id = id, + kind = kind, + title = title, + content = content, + mimeType = mimeType, + attachmentFileName = attName, + ), + ) + } + PersistedShareBatch(batchId = batchId, createdAtMs = createdAtMs, items = items) + } + }.getOrNull() + if (decoded == null) { + val batchPrefix = file.name.removeSuffix(".manifest") + quarantineCorruptManifest(file, batchPrefix) + } else { + batches.add(decoded) + } + } + batches.sortWith(compareBy { it.createdAtMs }.thenBy { it.batchId }) + batches + } + + fun readAttachmentBytes(item: PersistedShareItem): ByteArray? = synchronized(lockFor(inboxDir)) { + val name = item.attachmentFileName ?: return@synchronized null + val file = safeChildFile(name) ?: return@synchronized null + if (!file.isFile) return@synchronized null + val len = file.length() + if (len <= 0L || len > ShareIntentBridge.MAX_ATTACHMENT_BYTES.toLong()) return@synchronized null + runCatching { file.readBytes() }.getOrNull() + } + + fun incrementAttempts(batchId: String): Int = synchronized(lockFor(inboxDir)) { + val file = safeChildFile("$batchId.attempts") ?: return@synchronized MAX_INGEST_ATTEMPTS + val prev = runCatching { + if (file.isFile) file.readText().trim().toIntOrNull() ?: 0 else 0 + }.getOrDefault(0) + val next = prev + 1 + runCatching { file.writeText(next.toString()) } + next + } + + fun clearAttempts(batchId: String): Unit = synchronized(lockFor(inboxDir)) { + safeChildFile("$batchId.attempts")?.delete() + } + + fun quarantineBatch(batch: PersistedShareBatch): Unit = synchronized(lockFor(inboxDir)) { + val targetDir = invalidDir + for (item in batch.items) { + val name = item.attachmentFileName ?: continue + safeChildFile(name)?.let { moveFileIntoDir(it, targetDir) } + } + safeChildFile("${batch.batchId}.manifest")?.let { moveFileIntoDir(it, targetDir) } + clearAttempts(batch.batchId) + pruneInvalidDirIfNeeded() + } + + fun removeCommittedBatch(batch: PersistedShareBatch): Unit = synchronized(lockFor(inboxDir)) { + for (item in batch.items) { + val name = item.attachmentFileName ?: continue + safeChildFile(name)?.delete() + } + safeChildFile("${batch.batchId}.manifest")?.delete() + clearAttempts(batch.batchId) + } +} + +/** + * Zero-JNA / zero-UniFFI Android `ACTION_SEND` / `ACTION_SEND_MULTIPLE` narrow bridge. + * Extracts shared URLs, plain text, images, or PDFs (`<= 64 MiB` bounded `content://` streams), + * drains durable `/share-inbox/` batches in strict FIFO order with single-flight + * re-drain coalescing, quarantines permanently corrupt or repeatedly failing batches into + * `invalid/`, and deletes persisted manifests ONLY after SQLite confirms durable receipt + * (`nativeShareIsDurablyCommitted`). + */ +class ShareIntentBridge( + private val handleProvider: () -> Long, +) { + companion object { + const val KIND_URL: Int = 0 + const val KIND_TEXT: Int = 1 + const val KIND_IMAGE: Int = 2 + const val KIND_PDF: Int = 3 + const val MAX_ATTACHMENT_BYTES: Int = 64 * 1024 * 1024 + const val MAX_BATCH_ITEMS: Int = ShareDiskInbox.MAX_BATCH_ITEMS + const val EXTRA_FROM_SHARE_RECEIVER: String = "app.affine.pro.host.EXTRA_FROM_SHARE_RECEIVER" + private const val HISTORY_LAUNCH_FLAG: Int = 0x00100000 // Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY + + fun isHistoryLaunch(flags: Int): Boolean = (flags and HISTORY_LAUNCH_FLAG) != 0 + + fun isShareActionIntent(candidate: Intent?): Boolean { + val action = candidate?.action ?: return false + return action == Intent.ACTION_SEND || action == Intent.ACTION_SEND_MULTIPLE + } + + /** + * Classifies a shared stream attachment into `KIND_IMAGE` or `KIND_PDF`, failing closed (`null`) + * on unsupported binary MIME types. + */ + fun classifyAttachmentKind(mimeType: String?, uriString: String): Int? { + val cleanMime = mimeType?.trim()?.lowercase() ?: "" + val cleanUri = uriString.trim().lowercase() + if ( + cleanMime == "application/pdf" || + ((cleanMime.isEmpty() || cleanMime == "*/*" || cleanMime == "application/octet-stream") && + cleanUri.endsWith(".pdf")) + ) { + return KIND_PDF + } + if ( + cleanMime.startsWith("image/") || + ((cleanMime.isEmpty() || cleanMime == "*/*") && + (cleanUri.endsWith(".png") || + cleanUri.endsWith(".jpg") || + cleanUri.endsWith(".jpeg") || + cleanUri.endsWith(".webp") || + cleanUri.endsWith(".gif"))) + ) { + return KIND_IMAGE + } + return null + } + + data class ParsedShareCandidate( + val id: String, + val kind: Int, + val title: String, + val content: String, + val mimeType: String, + val bytes: ByteArray?, + ) + + data class ParseShareResult( + val items: List, + val skippedCount: Int, + val oversizeCount: Int = 0, + val unreadableCount: Int = 0, + val cappedCount: Int = 0, + ) + + data class ResolvedStreamsResult( + val bytesByUri: Map, + val oversizeCount: Int, + val unavailableCount: Int = 0, + val cappedCount: Int = 0, + ) + + /** + * Pure-Kotlin validator building canonical share candidates and skipped item count for + * both `ShareDiskInbox` and direct `enqueueParsedPayloads`. + */ + fun buildParsedItemsWithStats( + action: String, + mimeType: String, + subject: String, + text: String?, + streamUris: List, + streamBytes: Map, + streamMimeTypes: Map = emptyMap(), + idPrefix: String, + ): ParseShareResult { + val out = mutableListOf() + var skipped = 0 + var oversize = 0 + var unreadable = 0 + var capped = 0 + var remainingBudget = MAX_ATTACHMENT_BYTES + if (action == "android.intent.action.SEND") { + if (!text.isNullOrBlank()) { + val trimmed = text.trim() + val kind = if (trimmed.startsWith("https://") || trimmed.startsWith("http://")) { + KIND_URL + } else { + KIND_TEXT + } + out.add( + ParsedShareCandidate( + id = "$idPrefix-0", + kind = kind, + title = subject, + content = trimmed, + mimeType = "text/plain", + bytes = null, + ), + ) + } + streamUris.forEachIndexed { idx, uriString -> + if (out.size >= MAX_BATCH_ITEMS) { + capped += 1 + skipped += 1 + return@forEachIndexed + } + val trimmedUri = uriString.trim() + if ( + !(trimmedUri.startsWith("content://") || + trimmedUri.startsWith("https://") || + trimmedUri.startsWith("http://")) + ) { + skipped += 1 + return@forEachIndexed + } + val bytes = streamBytes[uriString] + if (bytes == null || bytes.isEmpty() || bytes.size > remainingBudget) { + if (bytes != null && bytes.size > remainingBudget) { + oversize += 1 + } else { + unreadable += 1 + } + skipped += 1 + return@forEachIndexed + } + val effectiveMime = streamMimeTypes[uriString]?.takeIf { it.isNotBlank() } ?: mimeType + val attKind = classifyAttachmentKind(effectiveMime, trimmedUri) + if (attKind == null) { + skipped += 1 + return@forEachIndexed + } + val itemSuffix = if (attKind == KIND_PDF) "pdf" else "img" + remainingBudget -= bytes.size + out.add( + ParsedShareCandidate( + id = "$idPrefix-$itemSuffix-$idx", + kind = attKind, + title = subject, + content = trimmedUri, + mimeType = if (attKind == KIND_PDF && !effectiveMime.lowercase().contains("pdf")) { + "application/pdf" + } else { + effectiveMime + }, + bytes = bytes, + ), + ) + } + } else if (action == "android.intent.action.SEND_MULTIPLE") { + streamUris.forEachIndexed { idx, uriString -> + if (out.size >= MAX_BATCH_ITEMS) { + capped += 1 + skipped += 1 + return@forEachIndexed + } + val trimmedUri = uriString.trim() + if ( + !(trimmedUri.startsWith("content://") || + trimmedUri.startsWith("https://") || + trimmedUri.startsWith("http://")) + ) { + skipped += 1 + return@forEachIndexed + } + val bytes = streamBytes[uriString] + if (bytes == null || bytes.isEmpty() || bytes.size > remainingBudget) { + if (bytes != null && bytes.size > remainingBudget) { + oversize += 1 + } else { + unreadable += 1 + } + skipped += 1 + return@forEachIndexed + } + val effectiveMime = streamMimeTypes[uriString]?.takeIf { it.isNotBlank() } ?: mimeType + val attKind = classifyAttachmentKind(effectiveMime, trimmedUri) + if (attKind == null) { + skipped += 1 + return@forEachIndexed + } + remainingBudget -= bytes.size + out.add( + ParsedShareCandidate( + id = "$idPrefix-multi-$idx", + kind = attKind, + title = subject, + content = trimmedUri, + mimeType = if (attKind == KIND_PDF && !effectiveMime.lowercase().contains("pdf")) { + "application/pdf" + } else { + effectiveMime + }, + bytes = bytes, + ), + ) + } + } + return ParseShareResult( + items = out, + skippedCount = skipped, + oversizeCount = oversize, + unreadableCount = unreadable, + cappedCount = capped, + ) + } + + fun buildParsedItems( + action: String, + mimeType: String, + subject: String, + text: String?, + streamUris: List, + streamBytes: Map, + streamMimeTypes: Map = emptyMap(), + idPrefix: String, + ): List = buildParsedItemsWithStats( + action = action, + mimeType = mimeType, + subject = subject, + text = text, + streamUris = streamUris, + streamBytes = streamBytes, + streamMimeTypes = streamMimeTypes, + idPrefix = idPrefix, + ).items + + private sealed interface BoundedUriRead { + data class Ok(val bytes: ByteArray) : BoundedUriRead + data object Oversize : BoundedUriRead + data object Unavailable : BoundedUriRead + } + + private fun readContentUriBoundedDetailed( + resolver: ContentResolver, + uri: Uri, + remainingBudgetBytes: Int = MAX_ATTACHMENT_BYTES, + ): BoundedUriRead { + val scheme = uri.scheme?.lowercase() ?: return BoundedUriRead.Unavailable + if (scheme != "content") return BoundedUriRead.Unavailable + val cap = remainingBudgetBytes.coerceIn(0, MAX_ATTACHMENT_BYTES) + if (cap <= 0) return BoundedUriRead.Oversize + return runCatching { + resolver.openInputStream(uri)?.use { input -> + val out = ByteArrayOutputStream() + val buf = ByteArray(64 * 1024) + var total = 0 + while (true) { + val n = input.read(buf) + if (n < 0) break + if (n == 0) continue + if (total + n > cap) { + return BoundedUriRead.Oversize + } + out.write(buf, 0, n) + total += n + } + if (total <= 0) BoundedUriRead.Unavailable else BoundedUriRead.Ok(out.toByteArray()) + } ?: BoundedUriRead.Unavailable + }.getOrElse { BoundedUriRead.Unavailable } + } + + /** + * Reads up to `MAX_ATTACHMENT_BYTES` from a `content://` URI via `ContentResolver`. + * Rejects `file://` or other schemes, unreadable/empty streams, and payloads exceeding 64 MiB. + */ + fun readContentUriBounded( + resolver: ContentResolver, + uri: Uri, + remainingBudgetBytes: Int = MAX_ATTACHMENT_BYTES, + ): ByteArray? = (readContentUriBoundedDetailed(resolver, uri, remainingBudgetBytes) as? BoundedUriRead.Ok)?.bytes + + fun extractStreamUrisStatic(intent: Intent?): List { + if (intent == null) return emptyList() + val out = mutableListOf() + if (intent.action == Intent.ACTION_SEND) { + @Suppress("DEPRECATION") + val single = intent.getParcelableExtra(Intent.EXTRA_STREAM) + if (single != null) out.add(single) + } else if (intent.action == Intent.ACTION_SEND_MULTIPLE) { + @Suppress("DEPRECATION") + val multi = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) ?: emptyList() + out.addAll(multi) + } + return out + } + + fun resolveStreamsWithStatsStatic( + resolver: ContentResolver, + uris: List, + ): ResolvedStreamsResult { + if (uris.isEmpty()) return ResolvedStreamsResult(emptyMap(), 0, 0, 0) + val resolved = LinkedHashMap() + var oversizeCount = 0 + var unavailableCount = 0 + var cappedCount = 0 + var remaining = MAX_ATTACHMENT_BYTES + for (uri in uris) { + val key = uri.toString() + if (resolved.containsKey(key)) continue + if (resolved.size >= MAX_BATCH_ITEMS) { + cappedCount += 1 + continue + } + if (remaining <= 0) { + oversizeCount += 1 + continue + } + when (val read = readContentUriBoundedDetailed(resolver, uri, remaining)) { + is BoundedUriRead.Ok -> { + resolved[key] = read.bytes + remaining -= read.bytes.size + } + BoundedUriRead.Oversize -> oversizeCount += 1 + BoundedUriRead.Unavailable -> unavailableCount += 1 + } + } + return ResolvedStreamsResult( + bytesByUri = resolved, + oversizeCount = oversizeCount, + unavailableCount = unavailableCount, + cappedCount = cappedCount, + ) + } + + fun resolveStreamBytesStatic(resolver: ContentResolver, uris: List): Map = + resolveStreamsWithStatsStatic(resolver, uris).bytesByUri + + /** + * Maps `(bootstrapCompleted, outcome)` onto the canonical [ShareDrainTarget] contract: + * - Pre-bootstrap, failed probe (`!outcome.imported`), or any failed local workspace mount + * (`outcome.failedWorkspaceIds.isNotEmpty()`) -> [ShareDrainTarget.PendingBootstrap] + * (retains manifests & attachments on disk until workspace recovery succeeds); + * - Healthy bootstrap with a mounted local workspace -> [ShareDrainTarget.DurableWorkspace]; + * - Healthy bootstrap with zero local workspaces -> [ShareDrainTarget.EphemeralStandalone]. + */ + fun resolveDrainTarget( + bootstrapCompleted: Boolean, + outcome: BootstrapOutcome?, + ): ShareDrainTarget { + if (!bootstrapCompleted || outcome == null || !outcome.isComplete) { + return ShareDrainTarget.PendingBootstrap + } + val wsKey = outcome.connectedWorkspaceKeys.firstOrNull()?.trim().orEmpty() + return when { + wsKey.isNotEmpty() -> ShareDrainTarget.DurableWorkspace(wsKey) + outcome.canCreateDefaultWorkspace -> ShareDrainTarget.EphemeralStandalone + else -> ShareDrainTarget.PendingBootstrap + } + } + } + + /** + * Explicit 3-state target contract for `/share-inbox/` draining so pre-bootstrap + * retention, ephemeral standalone delivery, and SQLite receipt-gated workspace persistence + * never conflate an empty string. + */ + sealed interface ShareDrainTarget { + /** Bootstrap has not yet settled; keep disk batches intact without delivering into demo doc. */ + data object PendingBootstrap : ShareDrainTarget + + /** Bootstrap settled with no mounted SQLite workspace (standalone in-memory mode); + * delete each disk batch once all items are consumed into the live session so cold starts + * never replay already-delivered shares. */ + data object EphemeralStandalone : ShareDrainTarget + + /** Bootstrap settled with a mounted SQLite workspace (`storageKey`); + * delete each disk batch ONLY after `nativeShareIsDurablyCommitted` confirms SQLite receipt. */ + data class DurableWorkspace(val storageKey: String) : ShareDrainTarget + } + + /** Immutable snapshot of one incoming system share intent staged in the FIFO queue. */ + data class PendingShareDescriptor( + val action: String, + val mimeType: String, + val subject: String, + val text: String?, + val streamUris: List, + val rawUris: List, + val idPrefix: String? = null, + val streamMimeTypes: Map = emptyMap(), + ) + + private var autoBatchSeq: Long = 0L + private val pendingQueue: ArrayDeque = ArrayDeque() + private var resolveInFlight: Boolean = false + + private val drainLock = Any() + private var diskDrainInFlight: Boolean = false + private var diskDrainPending: Boolean = false + + private fun nextDefaultPrefix(): String { + autoBatchSeq += 1L + return "share-${System.nanoTime()}-$autoBatchSeq" + } + + fun stageDescriptor(descriptor: PendingShareDescriptor) { + pendingQueue.addLast(descriptor) + } + + fun stagedIntentCount(): Int = pendingQueue.size + + fun isResolveInFlight(): Boolean = resolveInFlight + + fun isItemConsumed(id: String): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + return NativeBridge.nativeShareIsConsumed(handle, id) + } + + /** + * Single authoritative disk-inbox drainer shared by [MainActivity] (via [triggerDiskInboxDrainAsync]) + * and JVM parity tests (directly via [drainDiskInbox]). + */ + private fun drainDiskInboxPass( + inbox: ShareDiskInbox, + drainTargetProvider: () -> ShareDrainTarget, + isReady: () -> Boolean, + ingestNative: () -> Int, + onBatchQuarantined: (String) -> Unit, + runNative: (() -> Unit) -> Unit, + ): Int { + var totalCommitted = 0 + val batches = inbox.listPendingBatches() + for (batch in batches) { + val bytesByItemId = LinkedHashMap() + var missingAttachment = false + for (item in batch.items) { + if (item.attachmentFileName != null) { + val bytes = inbox.readAttachmentBytes(item) + if (bytes == null) { + missingAttachment = true + break + } + bytesByItemId[item.id] = bytes + } + } + if (missingAttachment) { + inbox.quarantineBatch(batch) + onBatchQuarantined(batch.batchId) + continue + } + + var shouldRemoveBatch = false + var mountedWorkspaceAttempted = false + var batchCommittedCount = 0 + var readyForBatch = false + var nativeBlockCompleted = false + + runNative { + val handle = handleProvider() + if (handle == 0L || !isReady() || NativeBridge.nativeIsPageReadonly(handle)) { + return@runNative + } + val target = drainTargetProvider() + if (target is ShareDrainTarget.PendingBootstrap) { + return@runNative + } + val durableWsKey = (target as? ShareDrainTarget.DurableWorkspace)?.storageKey?.trim().orEmpty() + if (target is ShareDrainTarget.DurableWorkspace && durableWsKey.isEmpty()) { + return@runNative + } + readyForBatch = true + val isDurableWorkspace = target is ShareDrainTarget.DurableWorkspace + mountedWorkspaceAttempted = isDurableWorkspace + var needsIngest = false + + for (item in batch.items) { + if (isDurableWorkspace && NativeBridge.nativeShareIsDurablyCommitted(handle, durableWsKey, item.id)) { + continue + } + if (!isDurableWorkspace && NativeBridge.nativeShareIsConsumed(handle, item.id)) { + continue + } + val ok = if (item.attachmentFileName != null) { + val bytes = bytesByItemId[item.id] ?: continue + NativeBridge.nativeShareEnqueueBytes( + handle, + item.id, + item.kind, + item.title, + item.content, + item.mimeType, + bytes, + ) + } else { + NativeBridge.nativeShareEnqueue( + handle, + item.id, + item.kind, + item.title, + item.content, + item.mimeType, + ) + } + if (ok || NativeBridge.nativeSharePendingCount(handle) > 0) { + needsIngest = true + } + } + + if (needsIngest || NativeBridge.nativeSharePendingCount(handle) > 0) { + batchCommittedCount = ingestNative() + } + + shouldRemoveBatch = if (isDurableWorkspace) { + batch.items.all { item -> + NativeBridge.nativeShareIsDurablyCommitted(handle, durableWsKey, item.id) + } + } else { + batch.items.all { item -> + NativeBridge.nativeShareIsConsumed(handle, item.id) + } + } + nativeBlockCompleted = true + } + + totalCommitted += batchCommittedCount + if (!readyForBatch || !nativeBlockCompleted) { + break + } + if (shouldRemoveBatch) { + inbox.removeCommittedBatch(batch) + } else if (mountedWorkspaceAttempted) { + val attempts = inbox.incrementAttempts(batch.batchId) + if (attempts >= ShareDiskInbox.MAX_INGEST_ATTEMPTS) { + inbox.quarantineBatch(batch) + onBatchQuarantined(batch.batchId) + } + } + } + return totalCommitted + } + + /** + * Synchronously drains `/share-inbox/` using single-flight coalescing under [ShareDrainTarget]. + */ + fun drainDiskInbox( + inbox: ShareDiskInbox, + drainTargetProvider: () -> ShareDrainTarget = { ShareDrainTarget.EphemeralStandalone }, + isReady: () -> Boolean, + ingestNative: () -> Int, + onBatchQuarantined: (String) -> Unit = {}, + runNative: (() -> Unit) -> Unit = { it() }, + ): Int { + if (!inbox.hasPendingManifests() || !isReady() || handleProvider() == 0L) { + return 0 + } + synchronized(drainLock) { + if (diskDrainInFlight) { + diskDrainPending = true + return 0 + } + diskDrainInFlight = true + diskDrainPending = false + } + var total = 0 + try { + while (true) { + total += drainDiskInboxPass( + inbox = inbox, + drainTargetProvider = drainTargetProvider, + isReady = isReady, + ingestNative = ingestNative, + onBatchQuarantined = onBatchQuarantined, + runNative = runNative, + ) + val shouldRepeat = synchronized(drainLock) { + if (diskDrainPending && inbox.hasPendingManifests()) { + diskDrainPending = false + true + } else { + diskDrainPending = false + diskDrainInFlight = false + false + } + } + if (!shouldRepeat) break + } + return total + } catch (t: Throwable) { + synchronized(drainLock) { + diskDrainPending = false + diskDrainInFlight = false + } + throw t + } + } + + /** + * Asynchronous single-flight disk-inbox trigger used by [MainActivity]. + * Performs a fast non-blocking manifest check before spawning any worker thread and coalesces + * concurrent `onNewIntent` / `onResume` triggers via `diskDrainPending`. + */ + fun triggerDiskInboxDrainAsync( + inbox: ShareDiskInbox, + drainTargetProvider: () -> ShareDrainTarget, + isReady: () -> Boolean, + ingestNative: () -> Int, + runNative: (() -> Unit) -> Unit, + onBatchQuarantined: (String) -> Unit = {}, + ) { + if (!inbox.hasPendingManifests() || !isReady() || handleProvider() == 0L) { + return + } + synchronized(drainLock) { + if (diskDrainInFlight) { + diskDrainPending = true + return + } + diskDrainInFlight = true + diskDrainPending = false + } + Thread { + try { + while (true) { + drainDiskInboxPass( + inbox = inbox, + drainTargetProvider = drainTargetProvider, + isReady = isReady, + ingestNative = ingestNative, + onBatchQuarantined = onBatchQuarantined, + runNative = runNative, + ) + val shouldRepeat = synchronized(drainLock) { + if (diskDrainPending && inbox.hasPendingManifests()) { + diskDrainPending = false + true + } else { + diskDrainPending = false + diskDrainInFlight = false + false + } + } + if (!shouldRepeat) break + } + } catch (_: Throwable) { + synchronized(drainLock) { + diskDrainPending = false + diskDrainInFlight = false + } + } + }.start() + } + + fun drainStagedQueue( + isReady: () -> Boolean, + resolveStreamAsync: (PendingShareDescriptor, (Map) -> Unit) -> Unit, + ingestNative: () -> Int, + ) { + if (!isReady() || resolveInFlight || handleProvider() == 0L) { + return + } + while (true) { + val next = pendingQueue.removeFirstOrNull() + if (next == null) { + if (pendingCount() > 0) { + ingestNative() + } + return + } + if (next.streamUris.isEmpty()) { + enqueueParsedPayloads( + action = next.action, + mimeType = next.mimeType, + subject = next.subject, + text = next.text, + streamUris = emptyList(), + streamBytes = emptyMap(), + streamMimeTypes = next.streamMimeTypes, + idPrefix = next.idPrefix, + ) + ingestNative() + continue + } + resolveInFlight = true + resolveStreamAsync(next) { resolvedBytes -> + resolveInFlight = false + if (handleProvider() != 0L) { + enqueueParsedPayloads( + action = next.action, + mimeType = next.mimeType, + subject = next.subject, + text = next.text, + streamUris = next.streamUris, + streamBytes = resolvedBytes, + streamMimeTypes = next.streamMimeTypes, + idPrefix = next.idPrefix, + ) + if (isReady()) { + ingestNative() + } + drainStagedQueue( + isReady = isReady, + resolveStreamAsync = resolveStreamAsync, + ingestNative = ingestNative, + ) + } + } + return + } + } + + fun extractStreamUris(intent: Intent?): List = extractStreamUrisStatic(intent) + + fun resolveStreamBytes(resolver: ContentResolver, uris: List): Map = + resolveStreamBytesStatic(resolver, uris) + + fun enqueueParsedPayloads( + action: String, + mimeType: String, + subject: String, + text: String?, + streamUris: List, + streamBytes: Map = emptyMap(), + streamMimeTypes: Map = emptyMap(), + idPrefix: String? = null, + ): Int { + val handle = handleProvider() + if (handle == 0L) return 0 + val effectivePrefix = idPrefix ?: nextDefaultPrefix() + val candidates = buildParsedItems( + action = action, + mimeType = mimeType, + subject = subject, + text = text, + streamUris = streamUris, + streamBytes = streamBytes, + streamMimeTypes = streamMimeTypes, + idPrefix = effectivePrefix, + ) + var accepted = 0 + for (item in candidates) { + val ok = if (item.bytes != null) { + NativeBridge.nativeShareEnqueueBytes( + handle, + item.id, + item.kind, + item.title, + item.content, + item.mimeType, + item.bytes, + ) + } else { + NativeBridge.nativeShareEnqueue( + handle, + item.id, + item.kind, + item.title, + item.content, + item.mimeType, + ) + } + if (ok) { + accepted += 1 + } + } + return accepted + } + + fun pendingCount(): Int { + val handle = handleProvider() + if (handle == 0L) return 0 + return NativeBridge.nativeSharePendingCount(handle) + } + + fun drainJson(): String { + val handle = handleProvider() + if (handle == 0L) return "[]" + return NativeBridge.nativeShareDrainJson(handle) ?: "[]" + } +} diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt new file mode 100644 index 0000000000..187bef9e47 --- /dev/null +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt @@ -0,0 +1,170 @@ +package app.affine.pro.host + +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import java.io.File +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +/** + * Dedicated zero-UI share-sheet trampoline (`@android:style/Theme.Translucent.NoTitleBar`, + * `excludeFromRecents="true"`, `noHistory="true"`, `taskAffinity=""`). + * + * Keeps the temporary `ClipData` / `FLAG_GRANT_READ_URI_PERMISSION` grant alive while copying + * bounded (`<= 64 MiB`) `content://` stream bytes into `/share-inbox/`, surfaces a + * visible `Toast` when an incoming share fails completely or partially, routes into the + * single `MainActivity` task (`singleTask`), and finishes once all queued intents complete + * so Recents never retains or replays a duplicate AFFiNE task. + */ +class ShareReceiverActivity : Activity() { + companion object { + private val sharedWorkerExecutor: ExecutorService = + Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "affine-share-receiver").apply { isDaemon = true } + } + + fun toastMessageForFailure( + reason: ShareDiskInbox.ShareRejectReason, + hasPendingManifests: Boolean = true, + ): String = when (reason) { + ShareDiskInbox.ShareRejectReason.QUOTA_EXCEEDED -> + if (hasPendingManifests) { + "AFFiNE share inbox is full (open AFFiNE to finish importing pending shares)" + } else { + "AFFiNE share inbox is temporarily full; please try again" + } + ShareDiskInbox.ShareRejectReason.OVERSIZE_ITEM -> + "Shared item exceeds the 64 MB attachment limit" + ShareDiskInbox.ShareRejectReason.BATCH_LIMIT_EXCEEDED -> + "Shared items exceed the 256-item batch limit" + ShareDiskInbox.ShareRejectReason.STREAM_UNREADABLE -> + "Unable to read shared content" + ShareDiskInbox.ShareRejectReason.STORAGE_UNAVAILABLE -> + "Unable to save shared content to local storage" + ShareDiskInbox.ShareRejectReason.UNSUPPORTED_PAYLOAD, + ShareDiskInbox.ShareRejectReason.NONE, + -> "Unsupported shared content format" + } + } + + private val mainHandler = Handler(Looper.getMainLooper()) + private var inFlightTasks = 0 + + @Suppress("DEPRECATION") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + overridePendingTransition(0, 0) + if (savedInstanceState != null) { + finishSilently() + return + } + handleShareIntent(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleShareIntent(intent) + } + + private fun handleShareIntent(incoming: Intent?) { + if ( + incoming == null || + ShareIntentBridge.isHistoryLaunch(incoming.flags) || + !ShareIntentBridge.isShareActionIntent(incoming) + ) { + if (inFlightTasks == 0) { + finishSilently() + } + return + } + + val action = incoming.action ?: run { + if (inFlightTasks == 0) { + finishSilently() + } + return + } + val mimeType = incoming.type ?: "text/plain" + val subject = incoming.getStringExtra(Intent.EXTRA_SUBJECT) ?: "" + val text = incoming.getStringExtra(Intent.EXTRA_TEXT) + val uris = ShareIntentBridge.extractStreamUrisStatic(incoming) + incoming.action = null + + inFlightTasks += 1 + val appCtx = applicationContext + val inboxDir = File(filesDir, ShareDiskInbox.DEFAULT_DIR_NAME) + val resolver = appCtx.contentResolver + sharedWorkerExecutor.execute { + val resolvedStreams = ShareIntentBridge.resolveStreamsWithStatsStatic(resolver, uris) + val streamBytes = resolvedStreams.bytesByUri + val streamMimes = LinkedHashMap() + for (uri in uris) { + val resolvedType = runCatching { resolver.getType(uri) }.getOrNull() + if (!resolvedType.isNullOrBlank()) { + streamMimes[uri.toString()] = resolvedType + } + } + val inbox = ShareDiskInbox(inboxDir) + val writeResult = inbox.writeBatchWithStats( + action = action, + mimeType = mimeType, + subject = subject, + text = text, + streamUris = resolvedStreams.bytesByUri.keys.toList(), + streamBytes = streamBytes, + streamMimeTypes = streamMimes, + preOversizeCount = resolvedStreams.oversizeCount, + preUnavailableCount = resolvedStreams.unavailableCount, + preCappedCount = resolvedStreams.cappedCount, + ) + val hasPendingAfterWrite = if (writeResult.batch == null) inbox.hasPendingManifests() else true + mainHandler.post { + inFlightTasks = (inFlightTasks - 1).coerceAtLeast(0) + val batch = writeResult.batch + if (batch == null) { + Toast.makeText( + appCtx, + toastMessageForFailure(writeResult.rejectReason, hasPendingAfterWrite), + Toast.LENGTH_SHORT, + ).show() + if (inFlightTasks == 0) { + finishSilently() + } + return@post + } + if (writeResult.skippedCount > 0) { + Toast.makeText( + appCtx, + "Imported ${batch.items.size} shared item(s); skipped ${writeResult.skippedCount} unsupported or oversized item(s)", + Toast.LENGTH_SHORT, + ).show() + } + val forward = Intent(appCtx, MainActivity::class.java).apply { + addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_SINGLE_TOP or + Intent.FLAG_ACTIVITY_CLEAR_TOP, + ) + putExtra(ShareIntentBridge.EXTRA_FROM_SHARE_RECEIVER, batch.batchId) + } + appCtx.startActivity(forward) + if (inFlightTasks == 0) { + finishSilently() + } + } + } + } + + @Suppress("DEPRECATION") + private fun finishSilently() { + if (!isFinishing) { + finish() + } + overridePendingTransition(0, 0) + } +} diff --git a/packages/frontend/hosts/android/scripts/package-debug-apk.sh b/packages/frontend/hosts/android/scripts/package-debug-apk.sh new file mode 100755 index 0000000000..53e42fc915 --- /dev/null +++ b/packages/frontend/hosts/android/scripts/package-debug-apk.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build and sign `AffineAndroidHost-debug.apk` directly with Android SDK CLI tools +# (`aapt2`, `kotlinc`, `d8`, `zipalign`, `apksigner`) and NDK Clang — zero Gradle daemon. +# +# Usage: +# ./packages/frontend/hosts/android/scripts/package-debug-apk.sh [out_dir] + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ANDROID_HOST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +REPO_ROOT="$(cd "$ANDROID_HOST_DIR/../../../.." && pwd)" +MANIFEST="$REPO_ROOT/packages/frontend/Cargo.toml" +OUT_DIR="${1:-$REPO_ROOT/packages/frontend/target/android-apk}" + +ANDROID_SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/android-sdk}}" +if [ ! -d "$ANDROID_SDK" ]; then + echo "ERROR: Android SDK not found at $ANDROID_SDK" >&2 + exit 1 +fi + +BUILD_TOOLS_DIR="$(ls -1d "$ANDROID_SDK"/build-tools/* | sort -V | tail -n 1)" +PLATFORM_DIR="$(ls -1d "$ANDROID_SDK"/platforms/android-* | sort -V | tail -n 1)" +ANDROID_JAR="$PLATFORM_DIR/android.jar" +NDK_DIR="${ANDROID_NDK_LATEST_HOME:-$(ls -1d "$ANDROID_SDK"/ndk/* | sort -V | tail -n 1)}" +NDK_BIN="$(ls -1d "$NDK_DIR"/toolchains/llvm/prebuilt/*/bin | head -n 1)" + +echo "==> Using SDK=$ANDROID_SDK build-tools=$(basename "$BUILD_TOOLS_DIR") platform=$(basename "$PLATFORM_DIR") ndk=$(basename "$NDK_DIR")" + +export CARGO_ENCODED_RUSTFLAGS="" +export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$NDK_BIN/aarch64-linux-android24-clang" +export CC_aarch64_linux_android="$NDK_BIN/aarch64-linux-android24-clang" +export AR_aarch64_linux_android="$NDK_BIN/llvm-ar" + +echo "==> Building Android NDK libaffine_android_host.so (arm64-v8a)" +if command -v rustup >/dev/null 2>&1 && rustup toolchain list 2>/dev/null | grep -q '^1\.98\.1'; then + rustup run 1.98.1 cargo build --locked --manifest-path "$MANIFEST" -p affine-android-host --target aarch64-linux-android +else + cargo build --locked --manifest-path "$MANIFEST" -p affine-android-host --target aarch64-linux-android +fi + +ARM64_SO="$REPO_ROOT/packages/frontend/target/aarch64-linux-android/debug/libaffine_android_host.so" +test -s "$ARM64_SO" + +WORK_DIR="$OUT_DIR/work" +rm -rf "$WORK_DIR" +mkdir -p "$WORK_DIR/classes" "$WORK_DIR/dex" "$WORK_DIR/apk_root/lib/arm64-v8a" + +echo "==> Compiling Kotlin host sources with kotlinc" +kotlinc -classpath "$ANDROID_JAR" \ + -include-runtime \ + -d "$WORK_DIR/host-classes.jar" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/MainActivity.kt" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AuthDataStore.kt" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/ShareIntentBridge.kt" \ + "$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/ShareReceiverActivity.kt" + +echo "==> Converting bytecode to DEX with d8" +"$BUILD_TOOLS_DIR/d8" \ + --min-api 24 \ + --lib "$ANDROID_JAR" \ + --output "$WORK_DIR/dex" \ + "$WORK_DIR/host-classes.jar" +test -s "$WORK_DIR/dex/classes.dex" + +echo "==> Linking AndroidManifest.xml with aapt2" +"$BUILD_TOOLS_DIR/aapt2" link \ + -I "$ANDROID_JAR" \ + --manifest "$ANDROID_HOST_DIR/AndroidManifest.xml" \ + --min-sdk-version 24 \ + --target-sdk-version 35 \ + -o "$WORK_DIR/unaligned.apk" + +LLVM_STRIP="$NDK_BIN/llvm-strip" +if [ ! -x "$LLVM_STRIP" ]; then + echo "ERROR: NDK llvm-strip not found at $LLVM_STRIP" >&2 + exit 1 +fi + +STAGED_SO="$WORK_DIR/apk_root/lib/arm64-v8a/libaffine_android_host.so" +cp "$ARM64_SO" "$STAGED_SO" +"$LLVM_STRIP" --strip-unneeded "$STAGED_SO" +test -s "$STAGED_SO" +cp "$WORK_DIR/dex/classes.dex" "$WORK_DIR/apk_root/classes.dex" +for extra_dex in "$WORK_DIR"/dex/classes*.dex; do + cp "$extra_dex" "$WORK_DIR/apk_root/" +done + +( + cd "$WORK_DIR/apk_root" + zip -u -r -0 "$WORK_DIR/unaligned.apk" lib + zip -u -r "$WORK_DIR/unaligned.apk" classes*.dex +) + +ALIGNED_APK="$WORK_DIR/aligned.apk" +"$BUILD_TOOLS_DIR/zipalign" -f -p 4 "$WORK_DIR/unaligned.apk" "$ALIGNED_APK" + +KEYSTORE="$WORK_DIR/debug.keystore" +keytool -genkeypair -noprompt \ + -keystore "$KEYSTORE" \ + -storepass android \ + -keypass android \ + -alias androiddebugkey \ + -keyalg RSA \ + -keysize 2048 \ + -validity 10000 \ + -dname "CN=Android Debug,O=AFFiNE,C=US" + +FINAL_APK="$OUT_DIR/AffineAndroidHost-debug.apk" +"$BUILD_TOOLS_DIR/apksigner" sign \ + --ks "$KEYSTORE" \ + --ks-pass pass:android \ + --key-pass pass:android \ + --ks-key-alias androiddebugkey \ + --out "$FINAL_APK" \ + "$ALIGNED_APK" + +"$BUILD_TOOLS_DIR/apksigner" verify --verbose "$FINAL_APK" +test -s "$FINAL_APK" +echo "==> Packaged and signed Android debug APK: $FINAL_APK" diff --git a/packages/frontend/hosts/android/src/android_window.rs b/packages/frontend/hosts/android/src/android_window.rs new file mode 100644 index 0000000000..ee3f90511b --- /dev/null +++ b/packages/frontend/hosts/android/src/android_window.rs @@ -0,0 +1,498 @@ +#![allow(unsafe_code)] + +//! Android NDK `ANativeWindow` binding, real EGL/GLES3 surface presentation, +//! and CPU fallback with producer handoff safety. + +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::NonNull; +use std::collections::BTreeMap; +use std::sync::{Mutex, OnceLock}; + +use raw_window_handle::{ + AndroidDisplayHandle, AndroidNdkWindowHandle, DisplayHandle, HandleError, HasDisplayHandle, + HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle, +}; +use ui::{DevicePixels, GpuContext, WgpuRenderer, WgpuSurfaceConfig, size}; + +use crate::jni_bridge::{JLong, JObject, JniEnvPtr}; +use crate::{AndroidRenderBackend, SurfacePresentError}; + +#[repr(C)] +struct ANativeWindow { + _private: [u8; 0], +} + +#[repr(C)] +struct ANativeWindowBuffer { + width: i32, + height: i32, + stride: i32, + format: i32, + bits: *mut c_void, + reserved: [u32; 6], +} + +#[repr(C)] +struct ARect { + left: i32, + top: i32, + right: i32, + bottom: i32, +} + +type EglDisplay = *mut c_void; +type EglConfig = *mut c_void; +type EglContext = *mut c_void; +type EglSurface = *mut c_void; +type EglBoolean = u32; +type EglInt = i32; +type GlInt = i32; +type GlSizei = i32; +type GlFloat = f32; +type GlBitfield = u32; + +const WINDOW_FORMAT_RGBA_8888: i32 = 1; +const RTLD_LAZY: c_int = 1; + +const EGL_TRUE: EglBoolean = 1; +const EGL_NONE: EglInt = 0x3038; +const EGL_RED_SIZE: EglInt = 0x3024; +const EGL_GREEN_SIZE: EglInt = 0x3023; +const EGL_BLUE_SIZE: EglInt = 0x3022; +const EGL_ALPHA_SIZE: EglInt = 0x3021; +const EGL_SURFACE_TYPE: EglInt = 0x3033; +const EGL_WINDOW_BIT: EglInt = 0x0004; +const EGL_RENDERABLE_TYPE: EglInt = 0x3040; +const EGL_OPENGL_ES2_BIT: EglInt = 0x0004; +const EGL_OPENGL_ES3_BIT: EglInt = 0x0040; +const EGL_CONTEXT_CLIENT_VERSION: EglInt = 0x3098; +const GL_COLOR_BUFFER_BIT: GlBitfield = 0x0000_4000; + +#[link(name = "android")] +unsafe extern "C" { + fn ANativeWindow_fromSurface(env: JniEnvPtr, surface: JObject) -> *mut ANativeWindow; + fn ANativeWindow_setBuffersGeometry( + window: *mut ANativeWindow, + width: i32, + height: i32, + format: i32, + ) -> i32; + fn ANativeWindow_lock( + window: *mut ANativeWindow, + out_buffer: *mut ANativeWindowBuffer, + in_out_dirty_bounds: *mut ARect, + ) -> i32; + fn ANativeWindow_unlockAndPost(window: *mut ANativeWindow) -> i32; + fn ANativeWindow_release(window: *mut ANativeWindow); +} + +#[link(name = "EGL")] +unsafe extern "C" { + fn eglGetDisplay(display_id: *mut c_void) -> EglDisplay; + fn eglInitialize(dpy: EglDisplay, major: *mut EglInt, minor: *mut EglInt) -> EglBoolean; + fn eglChooseConfig( + dpy: EglDisplay, + attrib_list: *const EglInt, + configs: *mut EglConfig, + config_size: EglInt, + num_config: *mut EglInt, + ) -> EglBoolean; + fn eglCreateContext( + dpy: EglDisplay, + config: EglConfig, + share_context: EglContext, + attrib_list: *const EglInt, + ) -> EglContext; + fn eglCreateWindowSurface( + dpy: EglDisplay, + config: EglConfig, + win: *mut ANativeWindow, + attrib_list: *const EglInt, + ) -> EglSurface; + fn eglMakeCurrent( + dpy: EglDisplay, + draw: EglSurface, + read: EglSurface, + ctx: EglContext, + ) -> EglBoolean; + fn eglSwapBuffers(dpy: EglDisplay, surface: EglSurface) -> EglBoolean; + fn eglDestroySurface(dpy: EglDisplay, surface: EglSurface) -> EglBoolean; + fn eglDestroyContext(dpy: EglDisplay, ctx: EglContext) -> EglBoolean; +} + +#[link(name = "GLESv2")] +unsafe extern "C" { + fn glViewport(x: GlInt, y: GlInt, width: GlSizei, height: GlSizei); + fn glClearColor(red: GlFloat, green: GlFloat, blue: GlFloat, alpha: GlFloat); + fn glClear(mask: GlBitfield); +} + +unsafe extern "C" { + fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> c_int; +} + +fn probe_shared_lib(name: &core::ffi::CStr) -> bool { + let handle = unsafe { dlopen(name.as_ptr(), RTLD_LAZY) }; + if handle.is_null() { + return false; + } + unsafe { + let _ = dlclose(handle); + } + true +} + +/// Probes available presentation backends. +/// +/// Vulkan swapchain creation lands in the next stage with `wgpu`, so `vulkan` +/// reports `false` here and presentation starts at real EGL/GLES3 -> CPU fallback. +pub(crate) fn probe_backends() -> (bool, bool) { + let egl_ok = probe_shared_lib(c"libEGL.so") + && (probe_shared_lib(c"libGLESv3.so") || probe_shared_lib(c"libGLESv2.so")); + (false, egl_ok) +} + +#[derive(Clone, Copy)] +struct EglWindowState { + display: usize, + context: usize, + surface: usize, +} + +impl EglWindowState { + fn create(win: *mut ANativeWindow) -> Option { + let display = unsafe { eglGetDisplay(core::ptr::null_mut()) }; + if display.is_null() { + return None; + } + let mut major = 0; + let mut minor = 0; + if unsafe { eglInitialize(display, &mut major, &mut minor) } != EGL_TRUE { + return None; + } + + let (config, client_version) = choose_egl_config(display, EGL_OPENGL_ES3_BIT, 3) + .or_else(|| choose_egl_config(display, EGL_OPENGL_ES2_BIT, 2))?; + + let ctx_attribs = [EGL_CONTEXT_CLIENT_VERSION, client_version, EGL_NONE]; + let context = unsafe { + eglCreateContext(display, config, core::ptr::null_mut(), ctx_attribs.as_ptr()) + }; + if context.is_null() { + return None; + } + + let surface = unsafe { eglCreateWindowSurface(display, config, win, core::ptr::null()) }; + if surface.is_null() { + unsafe { + let _ = eglDestroyContext(display, context); + } + return None; + } + + Some(Self { + display: display as usize, + context: context as usize, + surface: surface as usize, + }) + } + + fn present_clear(&self, width: i32, height: i32, argb: u32) -> bool { + let display = self.display as EglDisplay; + let context = self.context as EglContext; + let surface = self.surface as EglSurface; + if unsafe { eglMakeCurrent(display, surface, surface, context) } != EGL_TRUE { + return false; + } + let a = ((argb >> 24) & 0xFF) as f32 / 255.0; + let r = ((argb >> 16) & 0xFF) as f32 / 255.0; + let g = ((argb >> 8) & 0xFF) as f32 / 255.0; + let b = (argb & 0xFF) as f32 / 255.0; + unsafe { + glViewport(0, 0, width, height); + glClearColor(r, g, b, a); + glClear(GL_COLOR_BUFFER_BIT); + } + let swapped = unsafe { eglSwapBuffers(display, surface) } == EGL_TRUE; + unsafe { + let _ = eglMakeCurrent( + display, + core::ptr::null_mut(), + core::ptr::null_mut(), + core::ptr::null_mut(), + ); + } + swapped + } + + fn destroy(self) { + let display = self.display as EglDisplay; + let context = self.context as EglContext; + let surface = self.surface as EglSurface; + unsafe { + let _ = eglMakeCurrent( + display, + core::ptr::null_mut(), + core::ptr::null_mut(), + core::ptr::null_mut(), + ); + let _ = eglDestroySurface(display, surface); + let _ = eglDestroyContext(display, context); + } + } +} + +fn choose_egl_config( + display: EglDisplay, + renderable_bit: EglInt, + client_version: EglInt, +) -> Option<(EglConfig, EglInt)> { + let attribs = [ + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, + renderable_bit, + EGL_RED_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_BLUE_SIZE, + 8, + EGL_ALPHA_SIZE, + 8, + EGL_NONE, + ]; + let mut config: EglConfig = core::ptr::null_mut(); + let mut num_configs: EglInt = 0; + let ok = + unsafe { eglChooseConfig(display, attribs.as_ptr(), &mut config, 1, &mut num_configs) } + == EGL_TRUE; + if ok && num_configs > 0 && !config.is_null() { + Some((config, client_version)) + } else { + None + } +} + +struct WindowEntry { + addr: usize, + width: i32, + height: i32, + cpu_geometry_ok: bool, + egl: Option, +} + +static WINDOWS: OnceLock>> = OnceLock::new(); + +fn windows() -> &'static Mutex> { + WINDOWS.get_or_init(|| Mutex::new(BTreeMap::new())) +} + +pub(crate) unsafe fn attach(env: JniEnvPtr, handle: JLong, surface: JObject) -> bool { + release(handle); + if env.is_null() || surface.is_null() { + return false; + } + let win = unsafe { ANativeWindow_fromSurface(env, surface) }; + if win.is_null() { + return false; + } + let mut map = windows().lock().unwrap_or_else(|p| p.into_inner()); + map.insert( + handle, + WindowEntry { + addr: win as usize, + width: 0, + height: 0, + cpu_geometry_ok: false, + egl: None, + }, + ); + true +} + +pub(crate) fn set_geometry(handle: JLong, width: i32, height: i32) { + if width <= 0 || height <= 0 { + return; + } + let mut map = windows().lock().unwrap_or_else(|p| p.into_inner()); + if let Some(entry) = map.get_mut(&handle) { + entry.width = width; + entry.height = height; + entry.cpu_geometry_ok = false; + } +} + +/// Presents a real pixel frame via EGL/GLES3 (`glClear` + `eglSwapBuffers`) or +/// `CpuFallback` (`ANativeWindow_lock` + `unlockAndPost`). +/// +/// Never returns `Ok(())` without submitting pixels; tears down any active +/// `EGLSurface` before falling back to CPU `ANativeWindow_lock`. +pub(crate) fn present_frame( + handle: JLong, + backend: AndroidRenderBackend, + argb: u32, +) -> Result<(), SurfacePresentError> { + let mut map = windows().lock().unwrap_or_else(|p| p.into_inner()); + let Some(entry) = map.get_mut(&handle) else { + return Err(SurfacePresentError::SurfaceLost); + }; + if entry.width <= 0 || entry.height <= 0 { + return Err(SurfacePresentError::NotReady); + } + let win = entry.addr as *mut ANativeWindow; + + match backend { + AndroidRenderBackend::Unselected | AndroidRenderBackend::Vulkan => { + Err(SurfacePresentError::BackendUnavailable) + } + AndroidRenderBackend::Gles3 => { + if entry.egl.is_none() { + entry.egl = EglWindowState::create(win); + } + let Some(egl) = entry.egl else { + return Err(SurfacePresentError::BackendUnavailable); + }; + if egl.present_clear(entry.width, entry.height, argb) { + Ok(()) + } else { + if let Some(stale) = entry.egl.take() { + stale.destroy(); + } + Err(SurfacePresentError::BackendUnavailable) + } + } + AndroidRenderBackend::CpuFallback => { + if let Some(egl) = entry.egl.take() { + egl.destroy(); + } + if !entry.cpu_geometry_ok { + let rc = unsafe { + ANativeWindow_setBuffersGeometry( + win, + entry.width, + entry.height, + WINDOW_FORMAT_RGBA_8888, + ) + }; + entry.cpu_geometry_ok = rc == 0; + if !entry.cpu_geometry_ok { + return Err(SurfacePresentError::NotReady); + } + } + let mut buffer = ANativeWindowBuffer { + width: 0, + height: 0, + stride: 0, + format: 0, + bits: core::ptr::null_mut(), + reserved: [0; 6], + }; + if unsafe { ANativeWindow_lock(win, &mut buffer, core::ptr::null_mut()) } != 0 { + return Err(SurfacePresentError::LockOrPostFailed); + } + let format_ok = buffer.format == WINDOW_FORMAT_RGBA_8888 + && !buffer.bits.is_null() + && buffer.width > 0 + && buffer.height > 0 + && buffer.stride >= buffer.width; + if format_ok { + let a = ((argb >> 24) & 0xFF) as u8; + let r = ((argb >> 16) & 0xFF) as u8; + let g = ((argb >> 8) & 0xFF) as u8; + let b = (argb & 0xFF) as u8; + let rgba_le = u32::from_le_bytes([r, g, b, a]); + let (width, height, stride) = ( + buffer.width as usize, + buffer.height as usize, + buffer.stride as usize, + ); + let pixels = buffer.bits as *mut u32; + for row in 0..height { + let slice = + unsafe { core::slice::from_raw_parts_mut(pixels.add(row * stride), width) }; + slice.fill(rgba_le); + } + } + let post_ok = unsafe { ANativeWindow_unlockAndPost(win) == 0 }; + if format_ok && post_ok { + Ok(()) + } else { + Err(SurfacePresentError::LockOrPostFailed) + } + } + } +} + +pub(crate) fn native_window_ptr(handle: JLong) -> Option<*mut c_void> { + let map = windows().lock().unwrap_or_else(|p| p.into_inner()); + let entry = map.get(&handle)?; + if entry.addr == 0 { + None + } else { + Some(entry.addr as *mut c_void) + } +} + +#[derive(Clone, Debug)] +struct AndroidRawWindow(NonNull); + +// SAFETY: `ANativeWindow` pointers are ref-counted NDK handles whose lifetime is +// strictly bounded by `surfaceDestroyed`, where `WgpuRenderer` is dropped before +// `ANativeWindow_release`. +unsafe impl Send for AndroidRawWindow {} +unsafe impl Sync for AndroidRawWindow {} + +impl HasWindowHandle for AndroidRawWindow { + fn window_handle(&self) -> Result, HandleError> { + let handle = AndroidNdkWindowHandle::new(self.0); + // SAFETY: `self.0` is a live `ANativeWindow*` owned by `WINDOWS` for the + // duration of the returned `WgpuRenderer`. + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::AndroidNdk(handle)) }) + } +} + +impl HasDisplayHandle for AndroidRawWindow { + fn display_handle(&self) -> Result, HandleError> { + let handle = AndroidDisplayHandle::new(); + // SAFETY: Android's display handle is a zero-sized marker with no borrowed pointers. + Ok(unsafe { DisplayHandle::borrow_raw(RawDisplayHandle::Android(handle)) }) + } +} + +/// Creates a live `ui::WgpuRenderer` bound to the `ANativeWindow*` for `handle`. +pub(crate) fn create_wgpu_renderer( + gpu_context: GpuContext, + native_window: *mut c_void, + width_px: u32, + height_px: u32, +) -> anyhow::Result { + let ptr = + NonNull::new(native_window).ok_or_else(|| anyhow::anyhow!("null ANativeWindow pointer"))?; + let raw_win = AndroidRawWindow(ptr); + let config = WgpuSurfaceConfig { + size: size( + DevicePixels(width_px.max(1) as i32), + DevicePixels(height_px.max(1) as i32), + ), + transparent: false, + preferred_present_mode: None, + }; + WgpuRenderer::new(gpu_context, &raw_win, config, None) +} + +pub(crate) fn release(handle: JLong) { + let prev = { + let mut map = windows().lock().unwrap_or_else(|p| p.into_inner()); + map.remove(&handle) + }; + if let Some(mut entry) = prev { + if let Some(egl) = entry.egl.take() { + egl.destroy(); + } + unsafe { + ANativeWindow_release(entry.addr as *mut ANativeWindow); + } + } +} diff --git a/packages/frontend/hosts/android/src/autofill.rs b/packages/frontend/hosts/android/src/autofill.rs new file mode 100644 index 0000000000..4f70650eda --- /dev/null +++ b/packages/frontend/hosts/android/src/autofill.rs @@ -0,0 +1,463 @@ +//! API 26+ Android `AutofillManager` virtual view structure and value write-back +//! state machine, with deterministic API 24/25 degradation. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::atomic::{Ordering, compiler_fence}; + +use serde::Serialize; + +use crate::should_expose_autofill; + +/// Sensitive string buffer that zeroes its backing bytes on drop without unsafe code. +#[derive(Clone, PartialEq, Eq)] +struct ZeroizingString { + bytes: Vec, +} + +impl ZeroizingString { + fn from_str(text: &str) -> Self { + Self { + bytes: text.as_bytes().to_vec(), + } + } + + fn as_str(&self) -> &str { + std::str::from_utf8(&self.bytes).unwrap_or("") + } +} + +impl Drop for ZeroizingString { + fn drop(&mut self) { + for b in &mut self.bytes { + *b = 0; + } + compiler_fence(Ordering::SeqCst); + } +} + +/// Semantic autofill field category exposed as virtual nodes on API 26+. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum AutofillFieldKind { + Username = 0, + Email = 1, + Password = 2, + OneTimeCode = 3, +} + +impl AutofillFieldKind { + /// Converts a raw JNI integer code into an [`AutofillFieldKind`]. + pub const fn from_code(code: i32) -> Option { + match code { + 0 => Some(Self::Username), + 1 => Some(Self::Email), + 2 => Some(Self::Password), + 3 => Some(Self::OneTimeCode), + _ => None, + } + } + + /// Returns the Android `View.AUTOFILL_HINT_*` constant string for this field. + pub const fn android_hint(self) -> &'static str { + match self { + Self::Username => "username", + Self::Email => "emailAddress", + Self::Password => "password", + Self::OneTimeCode => "smsOTPCode", + } + } +} + +/// Screen pixel rectangle for an autofill virtual node. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct AutofillRect { + pub left: i32, + pub top: i32, + pub right: i32, + pub bottom: i32, +} + +impl AutofillRect { + /// Normalizes bounds so `right >= left` and `bottom >= top`. + pub const fn normalized(left: i32, top: i32, right: i32, bottom: i32) -> Self { + let (l, r) = if left <= right { + (left, right) + } else { + (right, left) + }; + let (t, b) = if top <= bottom { + (top, bottom) + } else { + (bottom, top) + }; + Self { + left: l, + top: t, + right: r, + bottom: b, + } + } +} + +/// Virtual autofill node registered by the host UI. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AutofillFieldNode { + pub autofill_id: i32, + pub kind: AutofillFieldKind, + pub hint: &'static str, + pub bounds: AutofillRect, + pub masked: bool, + pub value_len: usize, + pub focused: bool, +} + +/// Notification emitted for the platform `AutofillManager` adapter. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum AutofillEvent { + ViewEntered { autofill_id: i32 }, + ViewExited { autofill_id: i32 }, + ValueChanged { autofill_id: i32, value_len: usize }, + Commit, + Cancel, +} + +#[derive(Serialize)] +struct VirtualStructurePayload<'a> { + enabled: bool, + sdk_int: u32, + focused_id: Option, + commit_count: u64, + fields: Vec<&'a AutofillFieldNode>, +} + +/// Host-side autofill state gated strictly at `sdk_int >= 26`. +#[derive(Clone, PartialEq, Eq)] +pub struct AutofillState { + sdk_int: u32, + fields: BTreeMap, + filled_values: BTreeMap, + focused_id: Option, + commit_count: u64, +} + +impl fmt::Debug for AutofillState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AutofillState") + .field("sdk_int", &self.sdk_int) + .field("fields", &self.fields) + .field("filled_value_count", &self.filled_values.len()) + .field("focused_id", &self.focused_id) + .field("commit_count", &self.commit_count) + .finish() + } +} + +impl Default for AutofillState { + fn default() -> Self { + Self::new(0) + } +} + +impl AutofillState { + /// Creates an autofill state machine configured for `sdk_int`. + pub fn new(sdk_int: u32) -> Self { + Self { + sdk_int, + fields: BTreeMap::new(), + filled_values: BTreeMap::new(), + focused_id: None, + commit_count: 0, + } + } + + /// Updates the device API level. Clears virtual state when below API 26. + pub fn set_sdk_int(&mut self, sdk_int: u32) -> bool { + self.sdk_int = sdk_int; + if !self.is_enabled() { + self.fields.clear(); + self.filled_values.clear(); + self.focused_id = None; + return false; + } + true + } + + /// Returns `true` when Android `AutofillManager` is supported (`sdk_int >= 26`). + pub const fn is_enabled(&self) -> bool { + should_expose_autofill(self.sdk_int) + } + + /// Returns the currently focused virtual field ID, if any. + pub const fn focused_id(&self) -> Option { + self.focused_id + } + + /// Returns the number of committed autofill sessions. + pub const fn commit_count(&self) -> u64 { + self.commit_count + } + + /// Registers or updates a virtual login field. Returns `false` on API < 26. + pub fn upsert_field( + &mut self, + autofill_id: i32, + kind: AutofillFieldKind, + bounds: AutofillRect, + masked: bool, + value_len: usize, + ) -> bool { + if !self.is_enabled() || autofill_id <= 0 { + return false; + } + let focused = self.focused_id == Some(autofill_id); + self.fields.insert( + autofill_id, + AutofillFieldNode { + autofill_id, + kind, + hint: kind.android_hint(), + bounds, + masked, + value_len, + focused, + }, + ); + true + } + + /// Removes a virtual field and clears focus if it was focused. + pub fn remove_field(&mut self, autofill_id: i32) -> bool { + if !self.is_enabled() { + return false; + } + if self.focused_id == Some(autofill_id) { + self.focused_id = None; + } + self.filled_values.remove(&autofill_id); + self.fields.remove(&autofill_id).is_some() + } + + /// Moves autofill focus to `next_id`, returning `ViewExited`/`ViewEntered` events. + pub fn focus_field(&mut self, next_id: Option) -> Vec { + if !self.is_enabled() { + return Vec::new(); + } + let valid_next = next_id.filter(|id| self.fields.contains_key(id)); + if self.focused_id == valid_next { + return Vec::new(); + } + let mut events = Vec::with_capacity(2); + if let Some(prev_id) = self.focused_id.take() { + if let Some(node) = self.fields.get_mut(&prev_id) { + node.focused = false; + } + events.push(AutofillEvent::ViewExited { + autofill_id: prev_id, + }); + } + if let Some(id) = valid_next { + if let Some(node) = self.fields.get_mut(&id) { + node.focused = true; + } + self.focused_id = Some(id); + events.push(AutofillEvent::ViewEntered { autofill_id: id }); + } + events + } + + /// Synchronizes the field's real current text without exposing plaintext in + /// `virtual_structure_json()`. Clearing to empty removes the cached value so + /// `ViewStructure` never emits synthetic placeholders. + pub fn set_field_text(&mut self, autofill_id: i32, text: &str) -> bool { + if !self.is_enabled() { + return false; + } + let Some(node) = self.fields.get_mut(&autofill_id) else { + return false; + }; + node.value_len = text.encode_utf16().count(); + if text.is_empty() { + self.filled_values.remove(&autofill_id); + } else { + self.filled_values + .insert(autofill_id, ZeroizingString::from_str(text)); + } + true + } + + /// Applies an autofill value delivered by Android `autofill(SparseArray)`. + pub fn apply_autofill_value(&mut self, autofill_id: i32, value: &str) -> bool { + self.set_field_text(autofill_id, value) + } + + /// Reads the latest autofilled text for `autofill_id`, if present. + pub fn filled_value(&self, autofill_id: i32) -> Option<&str> { + if !self.is_enabled() { + return None; + } + self.filled_values + .get(&autofill_id) + .map(ZeroizingString::as_str) + } + + /// Reads the latest value for the first registered field matching `kind`. + pub fn filled_value_by_kind(&self, kind: AutofillFieldKind) -> Option<&str> { + if !self.is_enabled() { + return None; + } + self.fields + .values() + .find(|node| node.kind == kind) + .and_then(|node| self.filled_value(node.autofill_id)) + } + + /// Marks the active autofill context as committed, clears field focus, and + /// wipes cached plaintext values. + pub fn commit(&mut self) -> bool { + if !self.is_enabled() { + return false; + } + if let Some(prev_id) = self.focused_id.take() + && let Some(node) = self.fields.get_mut(&prev_id) + { + node.focused = false; + } + self.filled_values.clear(); + self.commit_count = self.commit_count.saturating_add(1); + true + } + + /// Cancels the active autofill session, clears focus, and wipes cached plaintext values. + pub fn cancel(&mut self) -> bool { + if !self.is_enabled() { + return false; + } + if let Some(prev_id) = self.focused_id.take() + && let Some(node) = self.fields.get_mut(&prev_id) + { + node.focused = false; + } + self.filled_values.clear(); + true + } + + /// Clears all registered virtual fields, focus, and cached plaintext values + /// (called on page navigation or form unmount). + pub fn clear_fields(&mut self) { + self.fields.clear(); + self.filled_values.clear(); + self.focused_id = None; + } + + /// Serializes the virtual view structure to JSON for Kotlin `ViewStructure` population. + pub fn virtual_structure_json(&self) -> String { + let payload = VirtualStructurePayload { + enabled: self.is_enabled(), + sdk_int: self.sdk_int, + focused_id: if self.is_enabled() { + self.focused_id + } else { + None + }, + commit_count: self.commit_count, + fields: if self.is_enabled() { + self.fields.values().collect() + } else { + Vec::new() + }, + }; + serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn autofill_degrades_safely_below_api_26_and_roundtrips_at_api_26_plus() { + for sdk in [24_u32, 25] { + let mut state = AutofillState::new(sdk); + assert!(!state.is_enabled()); + assert!(!state.upsert_field( + 1, + AutofillFieldKind::Username, + AutofillRect::normalized(10, 20, 300, 80), + false, + 0, + )); + assert!(state.focus_field(Some(1)).is_empty()); + assert!(!state.apply_autofill_value(1, "alice@affine.pro")); + assert_eq!(state.filled_value(1), None); + assert!(!state.commit()); + assert!(state.virtual_structure_json().contains("\"enabled\":false")); + } + + for sdk in [26_u32, 33, 35] { + let mut state = AutofillState::new(sdk); + assert!(state.is_enabled()); + assert!(state.upsert_field( + 101, + AutofillFieldKind::Email, + AutofillRect::normalized(20, 100, 900, 180), + false, + 0, + )); + assert!(state.upsert_field( + 102, + AutofillFieldKind::Password, + AutofillRect::normalized(20, 200, 900, 280), + true, + 0, + )); + assert!(state.upsert_field( + 103, + AutofillFieldKind::OneTimeCode, + AutofillRect::normalized(20, 300, 900, 380), + false, + 0, + )); + + assert_eq!( + state.focus_field(Some(101)), + vec![AutofillEvent::ViewEntered { autofill_id: 101 }] + ); + assert_eq!( + state.focus_field(Some(102)), + vec![ + AutofillEvent::ViewExited { autofill_id: 101 }, + AutofillEvent::ViewEntered { autofill_id: 102 }, + ] + ); + assert!(state.apply_autofill_value(101, "user@affine.pro")); + assert!(state.apply_autofill_value(102, "s3cr3t!")); + assert_eq!(state.filled_value(101), Some("user@affine.pro")); + assert_eq!(state.filled_value(102), Some("s3cr3t!")); + + let debug_repr = format!("{state:?}"); + assert!(!debug_repr.contains("s3cr3t!")); + assert!(!debug_repr.contains("user@affine.pro")); + + let json = state.virtual_structure_json(); + assert!(json.contains("\"enabled\":true")); + assert!(json.contains("\"emailAddress\"")); + assert!(json.contains("\"password\"")); + assert!(json.contains("\"smsOTPCode\"")); + assert!(!json.contains("s3cr3t!")); + + assert!(state.commit()); + assert_eq!(state.commit_count(), 1); + assert_eq!(state.focused_id(), None); + assert_eq!(state.filled_value(101), None); + assert_eq!(state.filled_value(102), None); + + assert!(state.set_field_text(102, "temp-pass")); + assert_eq!(state.filled_value(102), Some("temp-pass")); + assert!(state.cancel()); + assert_eq!(state.filled_value(102), None); + state.clear_fields(); + assert!(state.virtual_structure_json().contains("\"fields\":[]")); + } + } +} diff --git a/packages/frontend/hosts/android/src/datastore.rs b/packages/frontend/hosts/android/src/datastore.rs new file mode 100644 index 0000000000..9899de4b28 --- /dev/null +++ b/packages/frontend/hosts/android/src/datastore.rs @@ -0,0 +1,1118 @@ +//! Jetpack Preferences DataStore wire codec and `0.27.5` `auth-sessions` +//! credential contract (`v1::` AES-GCM envelope, Unix ms `i64` +//! `accessExpiresAt`, and `auth-installation-id` reuse). +//! +//! Aligns byte-for-byte with: +//! - `packages/frontend/apps/android/App/app/src/main/java/app/affine/pro/utils/DataStore.kt` +//! - `packages/frontend/apps/android/App/app/src/main/java/app/affine/pro/plugin/AuthPlugin.kt` + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +pub use affine_store::auth::{ + PERMANENT_AUTH_ERROR_CODES, canonical_endpoint, is_permanent_auth_error_code, + legacy_storage_endpoint_key, +}; +use affine_store::{ + api_client::{ + ApiClientKind, ApiHttpRequest, ApiRequestContext, AuthSessionExchangeRequest, + HEADER_AFFINE_VERSION, HEADER_CLIENT_KIND, build_auth_session_exchange_request, + build_auth_session_refresh_request, build_auth_session_revoke_request, + }, + auth::{ + MAX_EXPIRES_IN_SECS as STORE_MAX_EXPIRES_IN_SECS, + MIN_EXPIRES_IN_SECS as STORE_MIN_EXPIRES_IN_SECS, STORED_TOKEN_PAIR_VERSION, + is_bearer_token_type, is_valid_rfc3339, normalize_rfc3339_utc_z, + }, + sync::DEFAULT_CLIENT_VERSION, +}; +use base64::Engine; +use base64::engine::general_purpose::{STANDARD, URL_SAFE}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Jetpack Preferences DataStore name for Android auth credentials. +pub const AUTH_DATASTORE_NAME: &str = "auth-sessions"; + +/// On-disk filename inside `/datastore/`. +pub const AUTH_DATASTORE_FILE: &str = "auth-sessions.preferences_pb"; + +/// Plaintext preference key holding the persistent installation UUID. +pub const AUTH_INSTALLATION_ID_KEY: &str = "auth-installation-id"; + +/// Prefix for per-endpoint encrypted session keys (`auth-token:`). +pub const AUTH_TOKEN_KEY_PREFIX: &str = "auth-token:"; + +/// Prefix for Android Keystore AES-GCM key aliases. +pub const KEYSTORE_ALIAS_PREFIX: &str = "affine-auth-session-"; + +/// Header identifying native mobile auth requests to AFFiNE server endpoints. +pub const AUTH_CLIENT_KIND_HEADER: &str = HEADER_CLIENT_KIND; +pub const AUTH_CLIENT_KIND_VALUE: &str = ApiClientKind::Native.as_str(); + +/// Header identifying the compatible AFFiNE mobile client version (`0.27.5`). +pub const AUTH_CLIENT_VERSION_HEADER: &str = HEADER_AFFINE_VERSION; +pub const AUTH_CLIENT_VERSION_VALUE: &str = DEFAULT_CLIENT_VERSION; + +/// Ciphertext envelope version prefix (`v1::`). +pub const AUTH_CIPHERTEXT_PREFIX: &str = "v1"; + +/// AES-GCM IV size in bytes (96-bit nonce). +pub const AUTH_GCM_IV_LEN: usize = 12; + +/// AES-GCM authentication tag size in bytes (128-bit tag). +pub const AUTH_GCM_TAG_LEN: usize = 16; + +/// Proactive refresh threshold matching `AuthPlugin.kt` (120 seconds). +pub const AUTH_REFRESH_LEAD_MS: i64 = 120_000; + +/// Minimum allowed `expiresIn` in seconds (`1..=86_400`). +pub const MIN_EXPIRES_IN_SECS: i64 = STORE_MIN_EXPIRES_IN_SECS as i64; + +/// Maximum allowed `expiresIn` in seconds (`1..=86_400`). +pub const MAX_EXPIRES_IN_SECS: i64 = STORE_MAX_EXPIRES_IN_SECS as i64; + +/// Errors returned by the DataStore protobuf codec and auth payload validator. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DataStoreError { + MalformedProtobuf(String), + InvalidCiphertext(String), + InvalidSessionPayload(String), + Io(String), +} + +impl std::fmt::Display for DataStoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::MalformedProtobuf(msg) => write!(f, "malformed datastore protobuf: {msg}"), + Self::InvalidCiphertext(msg) => write!(f, "invalid v1 ciphertext: {msg}"), + Self::InvalidSessionPayload(msg) => write!(f, "invalid auth session payload: {msg}"), + Self::Io(msg) => write!(f, "datastore I/O error: {msg}"), + } + } +} + +impl std::error::Error for DataStoreError {} + +/// Returns `/datastore/auth-sessions.preferences_pb`. +pub fn auth_datastore_path(files_dir: &Path) -> PathBuf { + files_dir.join("datastore").join(AUTH_DATASTORE_FILE) +} + +/// Returns the DataStore preference key `auth-token:`. +pub fn auth_token_key(endpoint: &str) -> String { + format!( + "{AUTH_TOKEN_KEY_PREFIX}{}", + legacy_storage_endpoint_key(endpoint) + ) +} + +/// Computes the Android Keystore alias identically to `TokenCipher.alias` in `AuthPlugin.kt`. +/// +/// Format: `affine-auth-session-`. +pub fn keystore_alias(endpoint: &str) -> String { + let storage_key = legacy_storage_endpoint_key(endpoint); + let digest = Sha256::digest(storage_key.as_bytes()); + let encoded = URL_SAFE.encode(digest); + format!("{KEYSTORE_ALIAS_PREFIX}{}", &encoded[..24]) +} + +/// Parsed `v1::` AES-GCM ciphertext envelope. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct V1EncryptedEnvelope { + pub iv: [u8; AUTH_GCM_IV_LEN], + pub ciphertext_and_tag: Vec, +} + +impl V1EncryptedEnvelope { + /// Parses and validates a `v1::` string produced by `TokenCipher.encrypt`. + pub fn parse(encoded: &str) -> Result { + let mut parts = encoded.split(':'); + let version = parts + .next() + .ok_or_else(|| DataStoreError::InvalidCiphertext("missing version".into()))?; + let iv_b64 = parts + .next() + .ok_or_else(|| DataStoreError::InvalidCiphertext("missing iv".into()))?; + let ct_b64 = parts + .next() + .ok_or_else(|| DataStoreError::InvalidCiphertext("missing ciphertext".into()))?; + if parts.next().is_some() { + return Err(DataStoreError::InvalidCiphertext( + "unexpected extra ':' segments".into(), + )); + } + if version != AUTH_CIPHERTEXT_PREFIX { + return Err(DataStoreError::InvalidCiphertext(format!( + "unsupported version prefix {version:?}" + ))); + } + + let iv_bytes = STANDARD + .decode(iv_b64) + .map_err(|e| DataStoreError::InvalidCiphertext(format!("invalid iv base64: {e}")))?; + let iv: [u8; AUTH_GCM_IV_LEN] = iv_bytes.try_into().map_err(|v: Vec| { + DataStoreError::InvalidCiphertext(format!( + "expected {AUTH_GCM_IV_LEN}-byte GCM IV, got {}", + v.len() + )) + })?; + + let ciphertext_and_tag = STANDARD.decode(ct_b64).map_err(|e| { + DataStoreError::InvalidCiphertext(format!("invalid ciphertext base64: {e}")) + })?; + if ciphertext_and_tag.len() < AUTH_GCM_TAG_LEN { + return Err(DataStoreError::InvalidCiphertext(format!( + "ciphertext shorter than {AUTH_GCM_TAG_LEN}-byte GCM tag" + ))); + } + + Ok(Self { + iv, + ciphertext_and_tag, + }) + } + + /// Formats the envelope as `v1::` (`NO_WRAP`). + pub fn format(&self) -> String { + format!( + "{AUTH_CIPHERTEXT_PREFIX}:{}:{}", + STANDARD.encode(self.iv), + STANDARD.encode(&self.ciphertext_and_tag), + ) + } +} + +/// Nested `session` object in an Android stored auth session JSON payload. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionMeta { + pub absolute_expires_at: String, + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// Stored Android `auth-sessions` JSON payload matching `AuthPlugin.kt:215-245`. +/// +/// `access_expires_at` is strictly **1970 Unix epoch milliseconds (`i64`)**, +/// matching Android `System.currentTimeMillis() + expiresIn * 1000`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionRecord { + pub version: u32, + pub token_type: String, + pub access_token: String, + pub access_expires_at: i64, + pub refresh_token: String, + pub refresh_expires_at: String, + pub session: AuthSessionMeta, + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// Validates RFC 3339 timestamps (both `Z` and `±HH:MM` offsets) via `affine-store`. +pub fn is_valid_iso8601_utc(value: &str) -> bool { + is_valid_rfc3339(value) +} + +impl AuthSessionRecord { + /// Converts a server `/api/auth/session/{exchange,refresh}` response into a + /// stored `version = 1` payload with 1970 Unix ms `i64` `accessExpiresAt`. + pub fn from_server_response(response_json: &str, now_ms: i64) -> Result { + let mut obj: serde_json::Map = + serde_json::from_str(response_json) + .map_err(|e| DataStoreError::InvalidSessionPayload(e.to_string()))?; + + let expires_in = obj + .remove("expiresIn") + .and_then(|v| v.as_i64()) + .ok_or_else(|| { + DataStoreError::InvalidSessionPayload("missing integer expiresIn".into()) + })?; + if !(MIN_EXPIRES_IN_SECS..=MAX_EXPIRES_IN_SECS).contains(&expires_in) { + return Err(DataStoreError::InvalidSessionPayload(format!( + "expiresIn out of range 1..=86400: {expires_in}" + ))); + } + + let access_expires_at = now_ms + .checked_add(expires_in.saturating_mul(1_000)) + .ok_or_else(|| { + DataStoreError::InvalidSessionPayload("accessExpiresAt overflow".into()) + })?; + obj.insert("version".into(), serde_json::Value::from(1u32)); + obj.insert( + "accessExpiresAt".into(), + serde_json::Value::from(access_expires_at), + ); + + let mut record: Self = serde_json::from_value(serde_json::Value::Object(obj)) + .map_err(|e| DataStoreError::InvalidSessionPayload(e.to_string()))?; + record.validate()?; + record.normalize_for_storage()?; + Ok(record) + } + + /// Parses and validates a decrypted stored Android auth session JSON string. + pub fn from_stored_json(plaintext: &str) -> Result { + let raw: serde_json::Value = serde_json::from_str(plaintext) + .map_err(|e| DataStoreError::InvalidSessionPayload(e.to_string()))?; + let access_exp_val = raw.get("accessExpiresAt").ok_or_else(|| { + DataStoreError::InvalidSessionPayload("missing accessExpiresAt".into()) + })?; + if !access_exp_val.is_i64() { + return Err(DataStoreError::InvalidSessionPayload( + "accessExpiresAt must be a 1970 Unix millisecond i64".into(), + )); + } + + let record: Self = serde_json::from_value(raw) + .map_err(|e| DataStoreError::InvalidSessionPayload(e.to_string()))?; + record.validate()?; + Ok(record) + } + + /// Validates version, bearer token type, non-empty tokens, Unix ms range, and RFC 3339 fields. + pub fn validate(&self) -> Result<(), DataStoreError> { + if self.version != STORED_TOKEN_PAIR_VERSION { + return Err(DataStoreError::InvalidSessionPayload(format!( + "unsupported version {}", + self.version + ))); + } + if !is_bearer_token_type(&self.token_type) { + return Err(DataStoreError::InvalidSessionPayload(format!( + "unsupported tokenType {:?}", + self.token_type + ))); + } + if self.access_token.is_empty() || self.refresh_token.is_empty() { + return Err(DataStoreError::InvalidSessionPayload( + "accessToken and refreshToken must be non-empty".into(), + )); + } + // Reject seconds-scale or 2001-epoch timestamps masquerading as 1970 Unix ms. + if self.access_expires_at < 1_000_000_000_000 { + return Err(DataStoreError::InvalidSessionPayload(format!( + "accessExpiresAt must be 1970 Unix milliseconds, got {}", + self.access_expires_at + ))); + } + if !is_valid_rfc3339(&self.refresh_expires_at) { + return Err(DataStoreError::InvalidSessionPayload( + "invalid refreshExpiresAt RFC 3339 timestamp".into(), + )); + } + if !is_valid_rfc3339(&self.session.absolute_expires_at) { + return Err(DataStoreError::InvalidSessionPayload( + "invalid session.absoluteExpiresAt RFC 3339 timestamp".into(), + )); + } + Ok(()) + } + + /// Normalizes `tokenType` to exact `"Bearer"` and RFC 3339 timestamps to UTC `Z` format + /// matching `0.27.5` `AuthPlugin.kt:237-240,278-288` for downgrade-safe persistence. + fn normalize_for_storage(&mut self) -> Result<(), DataStoreError> { + self.token_type = "Bearer".to_string(); + self.refresh_expires_at = + normalize_rfc3339_utc_z(&self.refresh_expires_at).ok_or_else(|| { + DataStoreError::InvalidSessionPayload( + "invalid refreshExpiresAt RFC 3339 timestamp".into(), + ) + })?; + self.session.absolute_expires_at = + normalize_rfc3339_utc_z(&self.session.absolute_expires_at).ok_or_else(|| { + DataStoreError::InvalidSessionPayload( + "invalid session.absoluteExpiresAt RFC 3339 timestamp".into(), + ) + })?; + Ok(()) + } + + /// Serializes the validated session payload for encryption and DataStore persistence, + /// normalizing `tokenType` to `"Bearer"` and timestamps to UTC `Z` for `0.27.5` parity. + pub fn to_stored_json(&self) -> Result { + self.validate()?; + let mut normalized = self.clone(); + normalized.normalize_for_storage()?; + serde_json::to_string(&normalized) + .map_err(|e| DataStoreError::InvalidSessionPayload(e.to_string())) + } + + /// Returns `true` when the access token has more than 120s remaining before expiry. + pub const fn is_access_token_fresh(&self, now_ms: i64) -> bool { + self.access_expires_at.saturating_sub(now_ms) > AUTH_REFRESH_LEAD_MS + } +} + +/// Outbound auth HTTP request specification with `x-affine-client-kind: native`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthHttpRequestSpec { + pub url: String, + pub headers: Vec<(String, String)>, + pub body_json: String, +} + +fn to_android_http_spec(endpoint: &str, req: ApiHttpRequest) -> AuthHttpRequestSpec { + let body_json = String::from_utf8(req.body.unwrap_or_default()).unwrap_or_default(); + AuthHttpRequestSpec { + url: format!("{}{}", canonical_endpoint(endpoint), req.path), + headers: vec![ + ( + AUTH_CLIENT_KIND_HEADER.to_string(), + AUTH_CLIENT_KIND_VALUE.to_string(), + ), + ( + AUTH_CLIENT_VERSION_HEADER.to_string(), + AUTH_CLIENT_VERSION_VALUE.to_string(), + ), + ], + body_json, + } +} + +/// Builds a `/api/auth/session/exchange` request reusing `installation_id`. +pub fn build_exchange_request( + endpoint: &str, + code: &str, + installation_id: &str, + device_name: &str, +) -> AuthHttpRequestSpec { + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_exchange_request( + &ctx, + &AuthSessionExchangeRequest { + code: code.to_string(), + installation_id: installation_id.to_string(), + platform: "android".to_string(), + device_name: Some(device_name.to_string()), + }, + ) + .expect("native exchange request serialization cannot fail"); + to_android_http_spec(endpoint, req) +} + +/// Builds a `/api/auth/session/refresh` request with native client headers. +pub fn build_refresh_request(endpoint: &str, refresh_token: &str) -> AuthHttpRequestSpec { + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_refresh_request(&ctx, refresh_token, None) + .expect("native refresh request serialization cannot fail"); + to_android_http_spec(endpoint, req) +} + +/// Builds a `/api/auth/session/revoke` request with native client headers. +pub fn build_revoke_request(endpoint: &str, refresh_token: &str) -> AuthHttpRequestSpec { + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_revoke_request(&ctx, refresh_token) + .expect("native revoke request serialization cannot fail"); + to_android_http_spec(endpoint, req) +} + +/// Value stored inside Jetpack Preferences DataStore `PreferenceMap`. +#[derive(Debug, Clone, PartialEq, Eq)] +enum PreferenceValue { + String(String), + /// Preserves non-string preference `Value` wire bytes verbatim on round-trip. + RawValueBytes(Vec), +} + +/// Lightweight hand-written protobuf codec for Jetpack `PreferencesProto.PreferenceMap`. +/// +/// Wire schema (`androidx.datastore.preferences.PreferencesProto`): +/// - `PreferenceMap`: field 1 (`map preferences`), length-delimited entries +/// - Map entry: field 1 (`string key`), field 2 (`Value value`) +/// - `Value`: field 5 (`string string`), wire type 2 (tag `0x2A`) +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PreferencesDataStore { + entries: BTreeMap, +} + +impl PreferencesDataStore { + /// Creates an empty preferences map. + pub fn new() -> Self { + Self::default() + } + + /// Reads a string preference by key. + pub fn get_string(&self, key: &str) -> Option<&str> { + match self.entries.get(key) { + Some(PreferenceValue::String(s)) => Some(s.as_str()), + _ => None, + } + } + + /// Sets a string preference by key. + pub fn set_string(&mut self, key: impl Into, value: impl Into) { + self.entries + .insert(key.into(), PreferenceValue::String(value.into())); + } + + /// Removes a preference key, returning `true` if it existed. + pub fn remove(&mut self, key: &str) -> bool { + self.entries.remove(key).is_some() + } + + /// Returns the number of stored preference entries. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Returns `true` when the preferences map has no entries. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Decodes a Jetpack Preferences DataStore `.preferences_pb` binary payload. + pub fn decode(bytes: &[u8]) -> Result { + let mut store = Self::new(); + let mut cursor = 0usize; + while cursor < bytes.len() { + let tag = read_varint(bytes, &mut cursor)?; + let field_number = tag >> 3; + let wire_type = (tag & 0x07) as u8; + match (field_number, wire_type) { + (1, 2) => { + let entry_bytes = read_length_delimited(bytes, &mut cursor)?; + let (key, val) = decode_map_entry(entry_bytes)?; + store.entries.insert(key, val); + } + _ => skip_unknown_field(bytes, &mut cursor, wire_type)?, + } + } + Ok(store) + } + + /// Encodes the preferences map into Jetpack Preferences DataStore `.preferences_pb` format. + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + for (key, value) in &self.entries { + let val_bytes = match value { + PreferenceValue::String(s) => encode_string_value(s), + PreferenceValue::RawValueBytes(raw) => raw.clone(), + }; + let mut entry = Vec::with_capacity(key.len() + val_bytes.len() + 8); + write_tag(&mut entry, 1, 2); + write_length_delimited(&mut entry, key.as_bytes()); + write_tag(&mut entry, 2, 2); + write_length_delimited(&mut entry, &val_bytes); + + write_tag(&mut out, 1, 2); + write_length_delimited(&mut out, &entry); + } + out + } + + /// Loads a `.preferences_pb` file from disk, returning an empty store ONLY if missing. + /// + /// Existing files that fail I/O or protobuf decoding return an error so callers + /// never silently overwrite or wipe intact entries on disk. + pub fn load_from_file(path: &Path) -> Result { + match std::fs::read(path) { + Ok(bytes) => Self::decode(&bytes), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::new()), + Err(err) => Err(DataStoreError::Io(err.to_string())), + } + } + + /// Atomically writes the `.preferences_pb` file to disk using a unique + /// same-directory temporary file, `sync_all()`, and `fs::rename`. + pub fn save_to_file(&self, path: &Path) -> Result<(), DataStoreError> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| DataStoreError::Io(e.to_string()))?; + } + static TMP_SEQ: AtomicU64 = AtomicU64::new(1); + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + let encoded = self.encode(); + let tmp_name = format!( + "{}.{}.{seq}.tmp", + path.file_name() + .and_then(|n| n.to_str()) + .unwrap_or(AUTH_DATASTORE_FILE), + std::process::id(), + ); + let tmp_path = path.with_file_name(tmp_name); + let write_result = (|| -> std::io::Result<()> { + let mut file = std::fs::File::create(&tmp_path)?; + file.write_all(&encoded)?; + file.sync_all()?; + drop(file); + std::fs::rename(&tmp_path, path)?; + Ok(()) + })(); + if let Err(err) = write_result { + let _ = std::fs::remove_file(&tmp_path); + return Err(DataStoreError::Io(err.to_string())); + } + Ok(()) + } +} + +static DATASTORE_FILE_LOCKS: OnceLock>>>> = OnceLock::new(); + +fn canonical_lock_key(path: &Path) -> PathBuf { + if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) + && let Ok(canon_parent) = std::fs::canonicalize(parent) + { + return canon_parent.join(name); + } + path.to_path_buf() +} + +/// Runs `f` while holding a process-wide mutex keyed by the canonical file path, +/// serializing `load -> mutate -> atomic save` across concurrent threads/keys. +pub fn with_datastore_file_lock(path: &Path, f: impl FnOnce() -> R) -> R { + let key = canonical_lock_key(path); + let file_lock = { + let registry = DATASTORE_FILE_LOCKS.get_or_init(|| Mutex::new(BTreeMap::new())); + let mut map = registry.lock().unwrap_or_else(|poison| poison.into_inner()); + map.entry(key) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() + }; + let _guard = file_lock + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + f() +} + +/// Reads a string preference under the per-file lock. +pub fn read_file_string(path: &Path, key: &str) -> Result, DataStoreError> { + with_datastore_file_lock(path, || { + let store = PreferencesDataStore::load_from_file(path)?; + Ok(store.get_string(key).map(str::to_string)) + }) +} + +/// Atomically updates a string preference under the per-file lock. +/// +/// Fails without modifying disk if the existing file is unreadable or corrupt. +pub fn update_file_string(path: &Path, key: &str, value: &str) -> Result<(), DataStoreError> { + with_datastore_file_lock(path, || { + let mut store = PreferencesDataStore::load_from_file(path)?; + store.set_string(key, value); + store.save_to_file(path) + }) +} + +/// Atomically reads a non-empty string preference or persists `candidate_value` +/// inside a single per-file lock critical section. +/// +/// Fails without modifying disk if the existing file is unreadable or corrupt. +pub fn get_or_create_file_string( + path: &Path, + key: &str, + candidate_value: &str, +) -> Result { + with_datastore_file_lock(path, || { + let mut store = PreferencesDataStore::load_from_file(path)?; + if let Some(existing) = store.get_string(key) + && !existing.is_empty() + { + return Ok(existing.to_string()); + } + store.set_string(key, candidate_value); + store.save_to_file(path)?; + Ok(candidate_value.to_string()) + }) +} + +/// Atomically deletes a preference key under the per-file lock. +/// +/// Fails without modifying disk if the existing file is unreadable or corrupt. +pub fn delete_file_key(path: &Path, key: &str) -> Result { + with_datastore_file_lock(path, || { + let mut store = PreferencesDataStore::load_from_file(path)?; + let removed = store.remove(key); + if removed { + store.save_to_file(path)?; + } + Ok(removed) + }) +} + +fn encode_string_value(value: &str) -> Vec { + let mut buf = Vec::with_capacity(value.len() + 4); + write_tag(&mut buf, 5, 2); + write_length_delimited(&mut buf, value.as_bytes()); + buf +} + +fn decode_map_entry(entry: &[u8]) -> Result<(String, PreferenceValue), DataStoreError> { + let mut cursor = 0usize; + let mut key: Option = None; + let mut value_bytes: Option<&[u8]> = None; + + while cursor < entry.len() { + let tag = read_varint(entry, &mut cursor)?; + let field_number = tag >> 3; + let wire_type = (tag & 0x07) as u8; + match (field_number, wire_type) { + (1, 2) => { + let raw = read_length_delimited(entry, &mut cursor)?; + let k = std::str::from_utf8(raw).map_err(|e| { + DataStoreError::MalformedProtobuf(format!("invalid key utf8: {e}")) + })?; + key = Some(k.to_string()); + } + (2, 2) => { + value_bytes = Some(read_length_delimited(entry, &mut cursor)?); + } + _ => skip_unknown_field(entry, &mut cursor, wire_type)?, + } + } + + let key = key.unwrap_or_default(); + let val_raw = value_bytes.unwrap_or(&[]); + let parsed_val = decode_preference_value(val_raw)?; + Ok((key, parsed_val)) +} + +fn decode_preference_value(raw: &[u8]) -> Result { + let mut cursor = 0usize; + while cursor < raw.len() { + let tag = read_varint(raw, &mut cursor)?; + let field_number = tag >> 3; + let wire_type = (tag & 0x07) as u8; + if field_number == 5 && wire_type == 2 { + let bytes = read_length_delimited(raw, &mut cursor)?; + let text = std::str::from_utf8(bytes).map_err(|e| { + DataStoreError::MalformedProtobuf(format!("invalid string value utf8: {e}")) + })?; + return Ok(PreferenceValue::String(text.to_string())); + } + skip_unknown_field(raw, &mut cursor, wire_type)?; + } + Ok(PreferenceValue::RawValueBytes(raw.to_vec())) +} + +fn write_tag(out: &mut Vec, field_number: u64, wire_type: u8) { + write_varint(out, (field_number << 3) | u64::from(wire_type)); +} + +fn write_length_delimited(out: &mut Vec, bytes: &[u8]) { + write_varint(out, bytes.len() as u64); + out.extend_from_slice(bytes); +} + +fn write_varint(out: &mut Vec, mut value: u64) { + loop { + let byte = (value & 0x7F) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + break; + } + out.push(byte | 0x80); + } +} + +fn read_varint(buf: &[u8], cursor: &mut usize) -> Result { + let mut result = 0u64; + let mut shift = 0u32; + loop { + if *cursor >= buf.len() { + return Err(DataStoreError::MalformedProtobuf("truncated varint".into())); + } + let byte = buf[*cursor]; + *cursor += 1; + if shift >= 64 { + return Err(DataStoreError::MalformedProtobuf("varint overflow".into())); + } + result |= u64::from(byte & 0x7F) << shift; + if (byte & 0x80) == 0 { + return Ok(result); + } + shift += 7; + } +} + +fn read_length_delimited<'a>( + buf: &'a [u8], + cursor: &mut usize, +) -> Result<&'a [u8], DataStoreError> { + let len = read_varint(buf, cursor)? as usize; + let end = cursor + .checked_add(len) + .ok_or_else(|| DataStoreError::MalformedProtobuf("length overflow".into()))?; + if end > buf.len() { + return Err(DataStoreError::MalformedProtobuf( + "truncated length-delimited field".into(), + )); + } + let slice = &buf[*cursor..end]; + *cursor = end; + Ok(slice) +} + +fn skip_unknown_field(buf: &[u8], cursor: &mut usize, wire_type: u8) -> Result<(), DataStoreError> { + match wire_type { + 0 => { + let _ = read_varint(buf, cursor)?; + Ok(()) + } + 1 => { + if cursor.checked_add(8).is_none_or(|end| end > buf.len()) { + return Err(DataStoreError::MalformedProtobuf( + "truncated 64-bit field".into(), + )); + } + *cursor += 8; + Ok(()) + } + 2 => { + let _ = read_length_delimited(buf, cursor)?; + Ok(()) + } + 5 => { + if cursor.checked_add(4).is_none_or(|end| end > buf.len()) { + return Err(DataStoreError::MalformedProtobuf( + "truncated 32-bit field".into(), + )); + } + *cursor += 4; + Ok(()) + } + _ => Err(DataStoreError::MalformedProtobuf(format!( + "unsupported wire type {wire_type}" + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_endpoint_and_keystore_alias_match_auth_plugin_kt() { + let cases = [ + ( + "https://app.affine.pro:443/graphql", + "https://app.affine.pro", + ), + ( + "HTTPS://APP.AFFINE.PRO:443/Docs?a=1", + "https://app.affine.pro", + ), + ("https://app.affine.pro/", "https://app.affine.pro"), + ("https://[::1]:443/graphql", "https://[::1]"), + ("https://[::1]:8443/graphql", "https://[::1]:8443"), + ("http://localhost:80/api", "http://localhost"), + ("http://localhost:3010/api/auth", "http://localhost:3010"), + ("not-a-url", "not-a-url"), + ]; + for (raw, expected) in cases { + assert_eq!(canonical_endpoint(raw), expected, "endpoint={raw}"); + } + + assert_eq!( + auth_token_key("https://app.affine.pro:443/docs"), + "auth-token:https://app.affine.pro" + ); + assert_eq!( + auth_token_key("https://[::1]:443/graphql"), + "auth-token:https://::1" + ); + assert_eq!( + auth_token_key("https://[::1]:8443/graphql"), + "auth-token:https://::1:8443" + ); + let alias = keystore_alias("https://app.affine.pro:443"); + assert!(alias.starts_with(KEYSTORE_ALIAS_PREFIX)); + assert_eq!(alias.len(), KEYSTORE_ALIAS_PREFIX.len() + 24); + assert_eq!(alias, keystore_alias("https://app.affine.pro")); + } + + #[test] + fn preferences_protobuf_roundtrip_preserves_strings_and_non_string_values() { + let mut store = PreferencesDataStore::new(); + store.set_string(AUTH_INSTALLATION_ID_KEY, "inst-uuid-0275"); + store.set_string( + auth_token_key("https://app.affine.pro"), + "v1:AAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBB==", + ); + + let mut encoded = store.encode(); + // Append a raw boolean preference entry (field 1 in Value, varint 1) to ensure preservation. + let bool_value = vec![0x08, 0x01]; + let mut extra_entry = Vec::new(); + write_tag(&mut extra_entry, 1, 2); + write_length_delimited(&mut extra_entry, b"legacy-flag"); + write_tag(&mut extra_entry, 2, 2); + write_length_delimited(&mut extra_entry, &bool_value); + write_tag(&mut encoded, 1, 2); + write_length_delimited(&mut encoded, &extra_entry); + + let decoded = PreferencesDataStore::decode(&encoded).unwrap(); + assert_eq!( + decoded.get_string(AUTH_INSTALLATION_ID_KEY), + Some("inst-uuid-0275") + ); + assert_eq!( + decoded.get_string(&auth_token_key("https://app.affine.pro")), + Some("v1:AAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBB==") + ); + assert_eq!(decoded.len(), 3); + + // Re-encode and decode again: non-string entry remains intact. + let reencoded = decoded.encode(); + let decoded2 = PreferencesDataStore::decode(&reencoded).unwrap(); + assert_eq!(decoded2, decoded); + } + + #[test] + fn v1_ciphertext_envelope_and_unix_ms_session_payload_validation() { + let envelope = V1EncryptedEnvelope { + iv: [7u8; AUTH_GCM_IV_LEN], + ciphertext_and_tag: vec![0xAA; 32], + }; + let encoded = envelope.format(); + assert!(encoded.starts_with("v1:")); + assert_eq!(V1EncryptedEnvelope::parse(&encoded).unwrap(), envelope); + + // Reject wrong prefix, wrong IV length, and truncated tag. + assert!( + V1EncryptedEnvelope::parse("v2:AAAAAAAAAAAAAAAA:AAAAAAAAAAAAAAAAAAAAAA==").is_err() + ); + assert!(V1EncryptedEnvelope::parse("v1:AAAA:AAAAAAAAAAAAAAAAAAAAAA==").is_err()); + assert!(V1EncryptedEnvelope::parse("v1:AAAAAAAAAAAAAAAA:AAAA").is_err()); + + let server_json = r#"{ + "tokenType": "Bearer", + "accessToken": "acc-1", + "refreshToken": "ref-1", + "expiresIn": 3600, + "refreshExpiresAt": "2027-01-01T00:00:00.000Z", + "session": { + "id": "sess-1", + "absoluteExpiresAt": "2027-06-01T00:00:00Z" + } + }"#; + let now_ms = 1_795_597_759_000_i64; + let record = AuthSessionRecord::from_server_response(server_json, now_ms).unwrap(); + assert_eq!(record.version, 1); + assert_eq!(record.access_expires_at, now_ms + 3_600_000); + assert!(record.is_access_token_fresh(now_ms)); + assert!(!record.is_access_token_fresh(now_ms + 3_500_000)); + + let stored = record.to_stored_json().unwrap(); + assert!(!stored.contains("expiresIn")); + let reparsed = AuthSessionRecord::from_stored_json(&stored).unwrap(); + assert_eq!(reparsed, record); + + // Reject iOS 2001-epoch float or seconds-scale accessExpiresAt. + let ios_epoch_json = stored.replace(&record.access_expires_at.to_string(), "785754559.5"); + assert!(AuthSessionRecord::from_stored_json(&ios_epoch_json).is_err()); + let seconds_scale_json = + stored.replace(&record.access_expires_at.to_string(), "1795597759"); + assert!(AuthSessionRecord::from_stored_json(&seconds_scale_json).is_err()); + + // Verify native auth headers (`x-affine-client-kind`, `x-affine-version`) and installationId reuse. + let expected_headers = vec![ + ("x-affine-client-kind".into(), "native".into()), + ("x-affine-version".into(), "0.27.5".into()), + ]; + let ex = build_exchange_request( + "https://app.affine.pro:443", + "code-1", + "inst-uuid-0275", + "Pixel 9", + ); + assert_eq!(ex.url, "https://app.affine.pro/api/auth/session/exchange"); + assert_eq!(ex.headers, expected_headers); + assert!( + ex.body_json + .contains("\"installationId\":\"inst-uuid-0275\"") + ); + assert!(ex.body_json.contains("\"platform\":\"android\"")); + + let rf = build_refresh_request("https://app.affine.pro", "ref-1"); + assert_eq!(rf.url, "https://app.affine.pro/api/auth/session/refresh"); + assert_eq!(rf.headers, expected_headers); + let rv = build_revoke_request("https://app.affine.pro", "ref-1"); + assert_eq!(rv.url, "https://app.affine.pro/api/auth/session/revoke"); + assert_eq!(rv.headers, expected_headers); + + for code in PERMANENT_AUTH_ERROR_CODES { + assert!(is_permanent_auth_error_code(code), "code={code}"); + } + assert!(!is_permanent_auth_error_code( + "AUTH_SESSION_TEMPORARILY_UNAVAILABLE" + )); + assert!(!is_permanent_auth_error_code("TOO_MANY_REQUESTS")); + + // Table-driven cross-platform parity: case-insensitive Bearer and RFC3339 timezone offsets. + let parity_cases = [ + ("Bearer", "2027-01-01T00:00:00Z", "2027-06-01T00:00:00Z"), + ( + "bearer", + "2027-01-01T08:00:00+08:00", + "2027-06-01T00:00:00-05:00", + ), + ( + "BEARER", + "2027-01-01T08:00:00.125+08:00", + "2027-06-01T00:00:00.5Z", + ), + ]; + for (token_type, refresh_ts, abs_ts) in parity_cases { + let payload = format!( + r#"{{"tokenType":"{token_type}","accessToken":"a","refreshToken":"r","expiresIn":600,"refreshExpiresAt":"{refresh_ts}","session":{{"id":"s","absoluteExpiresAt":"{abs_ts}"}}}}"# + ); + let rec = AuthSessionRecord::from_server_response(&payload, now_ms).unwrap(); + assert!(AuthSessionRecord::from_stored_json(&rec.to_stored_json().unwrap()).is_ok()); + } + } + + #[test] + fn datastore_concurrent_writes_preserve_all_keys_and_corrupt_file_is_never_wiped() { + let dir = std::env::temp_dir().join(format!( + "affine-android-datastore-conc-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let path = auth_datastore_path(&dir); + + // 4 writer threads x 50 rounds + 1 concurrent reader thread on the same .preferences_pb file. + let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let reader_path = path.clone(); + let reader_done = done.clone(); + let reader = std::thread::spawn(move || { + let mut reads = 0usize; + while !reader_done.load(std::sync::atomic::Ordering::Acquire) { + let _ = read_file_string(&reader_path, AUTH_INSTALLATION_ID_KEY).unwrap(); + reads += 1; + } + reads + }); + + let mut handles = Vec::new(); + for idx in 0..4usize { + let p = path.clone(); + handles.push(std::thread::spawn(move || { + let key = format!("auth-token:https://server-{idx}.example"); + for round in 0..50usize { + let val = format!("v1:AAAAAAAAAAAAAAAA:val-{idx}-{round}"); + update_file_string(&p, &key, &val).unwrap(); + } + })); + } + for h in handles { + h.join().unwrap(); + } + done.store(true, std::sync::atomic::Ordering::Release); + let _ = reader.join().unwrap(); + update_file_string(&path, AUTH_INSTALLATION_ID_KEY, "inst-concurrent").unwrap(); + + assert_eq!( + read_file_string(&path, AUTH_INSTALLATION_ID_KEY) + .unwrap() + .as_deref(), + Some("inst-concurrent") + ); + for idx in 0..4usize { + let key = format!("auth-token:https://server-{idx}.example"); + assert_eq!( + read_file_string(&path, &key).unwrap().as_deref(), + Some(format!("v1:AAAAAAAAAAAAAAAA:val-{idx}-49").as_str()) + ); + } + + // Corrupt file must fail reads/writes WITHOUT overwriting original bytes on disk. + let corrupt_bytes = vec![ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + ]; + std::fs::write(&path, &corrupt_bytes).unwrap(); + assert!(read_file_string(&path, AUTH_INSTALLATION_ID_KEY).is_err()); + assert!(get_or_create_file_string(&path, AUTH_INSTALLATION_ID_KEY, "new-uuid").is_err()); + assert!(update_file_string(&path, "new-key", "new-val").is_err()); + assert!(delete_file_key(&path, AUTH_INSTALLATION_ID_KEY).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), corrupt_bytes); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn get_or_create_file_string_is_atomic_under_cold_start_race() { + let dir = std::env::temp_dir().join(format!( + "affine-android-datastore-race-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let path = auth_datastore_path(&dir); + + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); + let p1 = path.clone(); + let b1 = barrier.clone(); + let t1 = std::thread::spawn(move || { + b1.wait(); + get_or_create_file_string(&p1, AUTH_INSTALLATION_ID_KEY, "uuid-a").unwrap() + }); + let p2 = path.clone(); + let b2 = barrier; + let t2 = std::thread::spawn(move || { + b2.wait(); + get_or_create_file_string(&p2, AUTH_INSTALLATION_ID_KEY, "uuid-b").unwrap() + }); + let r1 = t1.join().unwrap(); + let r2 = t2.join().unwrap(); + assert_eq!(r1, r2); + assert!(r1 == "uuid-a" || r1 == "uuid-b"); + assert_eq!( + read_file_string(&path, AUTH_INSTALLATION_ID_KEY) + .unwrap() + .as_deref(), + Some(r1.as_str()) + ); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn idna_endpoint_and_0275_downgrade_normalization_roundtrip() { + // IDNA endpoint key must match 0.27.5 punycode canonical form. + assert_eq!( + auth_token_key("https://bücher.example"), + "auth-token:https://xn--bcher-kva.example" + ); + assert_eq!( + auth_token_key("https://bücher.example:443/api"), + auth_token_key("https://xn--bcher-kva.example") + ); + + // Lowercase "bearer" and +08:00 cross-day timestamp normalize to exact "Bearer" + UTC Z. + let response = r#"{ + "tokenType": "bearer", + "accessToken": "acc-idna", + "expiresIn": 3600, + "refreshToken": "ref-idna", + "refreshExpiresAt": "2026-12-01T01:30:00+08:00", + "session": { + "id": "sess-idna", + "absoluteExpiresAt": "2026-12-31T23:30:00.5-02:00" + } + }"#; + let record = AuthSessionRecord::from_server_response(response, 1_760_000_000_000) + .expect("lowercase bearer and offset RFC3339 must parse"); + let persisted_json = record.to_stored_json().expect("to_stored_json"); + let parsed: serde_json::Value = serde_json::from_str(&persisted_json).unwrap(); + assert_eq!(parsed["tokenType"], "Bearer"); + assert_eq!(parsed["refreshExpiresAt"], "2026-11-30T17:30:00Z"); + assert_eq!( + parsed["session"]["absoluteExpiresAt"], + "2027-01-01T01:30:00.500Z" + ); + + // Persisted JSON must roundtrip cleanly and pass exact 0.27.5 AuthPlugin.kt rules. + let reloaded = AuthSessionRecord::from_stored_json(&persisted_json).unwrap(); + assert_eq!(reloaded.token_type, "Bearer"); + assert_eq!(reloaded.refresh_expires_at, "2026-11-30T17:30:00Z"); + assert_eq!( + reloaded.session.absolute_expires_at, + "2027-01-01T01:30:00.500Z" + ); + } +} diff --git a/packages/frontend/hosts/android/src/editor_fallback.rs b/packages/frontend/hosts/android/src/editor_fallback.rs new file mode 100644 index 0000000000..bac843214a --- /dev/null +++ b/packages/frontend/hosts/android/src/editor_fallback.rs @@ -0,0 +1,459 @@ +//! Fallback atlas and text system for `affine-android-host`. +//! +//! `FallbackAtlas` backs `SwappableAtlas` before an Android `SurfaceView` attaches +//! (or after `surfaceDestroyed`), and `FallbackTextSystem` runs on non-Android +//! JVM/Linux/macOS test hosts where `CosmicTextSystem` is not required. + +use std::borrow::Cow; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::thread::{self, ThreadId}; +use std::time::Duration; + +use anyhow::Result; +use ui::{ + AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas, + PlatformDispatcher, Priority, RunnableVariant, Size, TileId, point, size, +}; +#[cfg(not(target_os = "android"))] +use ui::{ + BaseDirection, Font, FontId, FontMetrics, FontRun, GlyphId, LineLayout, Pixels, + PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, TextRenderingMode, px, +}; + +struct ScheduledTimer { + due: ui::scheduler::Instant, + runnable: RunnableVariant, +} + +/// Foreground/background dispatcher for the Android thin host. +/// +/// Background tasks (`dispatch`) execute on a dedicated worker thread pool while +/// main-thread tasks (`dispatch_on_main_thread`) and delayed timers (`dispatch_after`, +/// stamped against [`ui::clock_now()`]) are drained on the UI thread by `drain_ready()`. +pub(crate) struct AndroidDispatcher { + main_thread_id: ThreadId, + main_queue: Mutex>, + timers: Mutex>, + bg_tx: Mutex>>, + waker: Mutex>>, + wake_notified: AtomicBool, + #[cfg(test)] + test_clock_offset: Mutex, +} + +impl AndroidDispatcher { + pub(crate) fn new() -> Self { + let (tx, rx) = mpsc::channel::(); + let rx = Arc::new(Mutex::new(rx)); + for idx in 0..2 { + let rx_worker = Arc::clone(&rx); + let _ = thread::Builder::new() + .name(format!("affine-android-bg-{idx}")) + .spawn(move || { + loop { + let next = { + let guard = rx_worker.lock().unwrap_or_else(|e| e.into_inner()); + guard.recv() + }; + match next { + Ok(runnable) => { + let _ = runnable.run(); + } + Err(_) => break, + } + } + }); + } + Self { + main_thread_id: thread::current().id(), + main_queue: Mutex::new(VecDeque::new()), + timers: Mutex::new(Vec::new()), + bg_tx: Mutex::new(Some(tx)), + waker: Mutex::new(None), + wake_notified: AtomicBool::new(false), + #[cfg(test)] + test_clock_offset: Mutex::new(Duration::ZERO), + } + } + + pub(crate) fn set_waker(&self, waker: Option>) { + *self.waker.lock().unwrap_or_else(|e| e.into_inner()) = waker; + } + + fn notify_waker(&self) { + if self + .wake_notified + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_ok() + { + let cb = self.waker.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(waker) = cb { + waker(); + } + } + } + + pub(crate) fn has_pending_main_tasks(&self) -> bool { + !self + .main_queue + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() + } + + fn current_instant(&self) -> ui::scheduler::Instant { + #[cfg(test)] + { + let offset = *self + .test_clock_offset + .lock() + .unwrap_or_else(|e| e.into_inner()); + ui::clock_now() + offset + } + #[cfg(not(test))] + { + ui::clock_now() + } + } + + #[cfg(test)] + pub(crate) fn advance_test_clock(&self, delta: Duration) { + let mut offset = self + .test_clock_offset + .lock() + .unwrap_or_else(|e| e.into_inner()); + *offset += delta; + } + + /// Runs all queued tasks and timers due at `current_instant()`, returning the + /// remaining duration until the earliest still-pending timer, if any. + pub(crate) fn drain_ready(&self) -> Option { + self.wake_notified.store(false, Ordering::SeqCst); + let now = self.current_instant(); + loop { + let due_timers: Vec = { + let mut timers = self.timers.lock().unwrap_or_else(|e| e.into_inner()); + let mut ready = Vec::new(); + let mut i = 0; + while i < timers.len() { + if timers[i].due <= now { + ready.push(timers.swap_remove(i).runnable); + } else { + i += 1; + } + } + ready + }; + let queued: Vec = { + let mut q = self.main_queue.lock().unwrap_or_else(|e| e.into_inner()); + q.drain(..).collect() + }; + if due_timers.is_empty() && queued.is_empty() { + break; + } + for runnable in due_timers.into_iter().chain(queued) { + runnable.run(); + } + } + if self.has_pending_main_tasks() { + return Some(Duration::ZERO); + } + let timers = self.timers.lock().unwrap_or_else(|e| e.into_inner()); + timers + .iter() + .map(|t| t.due.saturating_duration_since(now)) + .min() + } +} + +impl PlatformDispatcher for AndroidDispatcher { + fn is_main_thread(&self) -> bool { + thread::current().id() == self.main_thread_id + } + + fn now(&self) -> ui::scheduler::Instant { + self.current_instant() + } + + fn dispatch(&self, runnable: RunnableVariant, _priority: Priority) { + let tx = self.bg_tx.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(sender) = tx + && let Err(mpsc::SendError(fallback)) = sender.send(runnable) + { + self.main_queue + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back(fallback); + self.notify_waker(); + } + } + + fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) { + let became_non_empty = { + let mut q = self.main_queue.lock().unwrap_or_else(|e| e.into_inner()); + let was_empty = q.is_empty(); + q.push_back(runnable); + was_empty + }; + if became_non_empty { + self.notify_waker(); + } + } + + fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) { + let due = self.current_instant() + duration; + let earlier_from_bg = { + let mut timers = self.timers.lock().unwrap_or_else(|e| e.into_inner()); + let prev_min = timers.iter().map(|t| t.due).min(); + timers.push(ScheduledTimer { due, runnable }); + !self.is_main_thread() && prev_min.is_none_or(|m| due < m) + }; + if earlier_from_bg { + self.notify_waker(); + } + } + + fn spawn_realtime(&self, f: Box) { + f(); + } +} + +/// Delegates to `FallbackAtlas` before an `ANativeWindow` attaches, and hot-swaps to +/// `WgpuRenderer::sprite_atlas()` once `surfaceChanged` initializes the GPU surface. +pub(crate) struct SwappableAtlas { + inner: Mutex>, +} + +impl SwappableAtlas { + pub(crate) fn new(initial: Arc) -> Self { + Self { + inner: Mutex::new(initial), + } + } + + #[cfg(target_os = "android")] + pub(crate) fn swap(&self, next: Arc) { + *self.inner.lock().unwrap_or_else(|e| e.into_inner()) = next; + } +} + +impl PlatformAtlas for SwappableAtlas { + fn get_or_insert_with<'a>( + &self, + key: AtlasKey, + build: &mut dyn FnMut() -> Result, Cow<'a, [u8]>)>>, + ) -> Result> { + let atlas = self.inner.lock().unwrap_or_else(|e| e.into_inner()).clone(); + atlas.get_or_insert_with(key, build) + } + + fn remove(&self, key: &AtlasKey) { + let atlas = self.inner.lock().unwrap_or_else(|e| e.into_inner()).clone(); + atlas.remove(key); + } +} + +pub(crate) struct FallbackAtlas; + +impl PlatformAtlas for FallbackAtlas { + fn get_or_insert_with<'a>( + &self, + _key: AtlasKey, + _build: &mut dyn FnMut() -> Result, Cow<'a, [u8]>)>>, + ) -> Result> { + Ok(Some(AtlasTile { + texture_id: AtlasTextureId { + index: 0, + kind: AtlasTextureKind::Monochrome, + }, + tile_id: TileId(0), + padding: 0, + bounds: Bounds::new( + point(DevicePixels(0), DevicePixels(0)), + size(DevicePixels(1), DevicePixels(1)), + ), + })) + } + + fn remove(&self, _key: &AtlasKey) {} +} + +#[cfg(not(target_os = "android"))] +pub(crate) struct FallbackTextSystem; + +#[cfg(not(target_os = "android"))] +impl PlatformTextSystem for FallbackTextSystem { + fn add_fonts(&self, _fonts: Vec>) -> Result<()> { + Ok(()) + } + + fn all_font_names(&self) -> Vec { + vec!["Inter".to_string(), "IBM Plex Mono".to_string()] + } + + fn font_id(&self, _descriptor: &Font) -> Result { + Ok(FontId(0)) + } + + fn font_metrics(&self, _font_id: FontId) -> FontMetrics { + FontMetrics { + units_per_em: 1000, + ascent: 800.0, + descent: -200.0, + line_gap: 0.0, + underline_position: -100.0, + underline_thickness: 50.0, + cap_height: 700.0, + x_height: 500.0, + bounding_box: Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)), + } + } + + fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result> { + Ok(Bounds::new(point(0.0, -200.0), size(600.0, 1000.0))) + } + + fn advance(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result> { + Ok(size(600.0, 0.0)) + } + + fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { + Some(GlyphId(ch as u32)) + } + + fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result> { + Ok(Bounds::new( + point(DevicePixels(0), DevicePixels(0)), + size(DevicePixels(8), DevicePixels(14)), + )) + } + + fn rasterize_glyph( + &self, + _params: &RenderGlyphParams, + raster_bounds: Bounds, + ) -> Result<(Size, Vec)> { + let w = raster_bounds.size.width.0.max(1) as usize; + let h = raster_bounds.size.height.0.max(1) as usize; + Ok((raster_bounds.size, vec![0u8; w * h])) + } + + fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { + let cell = f32::from(font_size) * 0.56; + let mut x = 0.0f32; + let mut shaped_runs = Vec::new(); + let mut offset = 0usize; + for run in runs { + let end = (offset + run.len).min(text.len()); + let slice = &text[offset..end]; + let mut glyphs = Vec::new(); + for (rel_idx, ch) in slice.char_indices() { + let adv = if ch == ' ' { cell * 0.65 } else { cell }; + glyphs.push(ShapedGlyph { + id: GlyphId(ch as u32), + position: point(px(x), px(0.0)), + index: offset + rel_idx, + is_emoji: false, + }); + x += adv; + } + shaped_runs.push(ShapedRun { + font_id: run.font_id, + glyphs, + bidi_level: 0, + }); + offset = end; + } + LineLayout { + font_size, + width: px(x), + ascent: px(f32::from(font_size) * 0.8), + descent: px(f32::from(font_size) * 0.2), + runs: shaped_runs, + len: text.len(), + base_direction: BaseDirection::Ltr, + } + } + + fn recommended_rendering_mode( + &self, + _font_id: FontId, + _font_size: Pixels, + ) -> TextRenderingMode { + TextRenderingMode::Grayscale + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn android_dispatcher_runs_background_tasks_off_main_thread() { + let dispatcher = Arc::new(AndroidDispatcher::new()); + assert!(dispatcher.is_main_thread()); + let main_id = thread::current().id(); + let (tx, rx) = mpsc::channel(); + let executor = ui::BackgroundExecutor::new(dispatcher); + executor + .spawn(async move { + let _ = tx.send(thread::current().id()); + }) + .detach(); + let worker_id = rx + .recv_timeout(Duration::from_secs(2)) + .expect("background task must run on worker thread"); + assert_ne!( + worker_id, main_id, + "AndroidDispatcher::dispatch must execute off the main thread" + ); + } + + #[test] + fn android_dispatcher_wakes_main_looper_from_background_thread() { + use std::sync::atomic::{AtomicUsize, Ordering as AtomOrd}; + + let dispatcher = Arc::new(AndroidDispatcher::new()); + assert_eq!(dispatcher.drain_ready(), None); + + let (wake_tx, wake_rx) = mpsc::channel(); + dispatcher.set_waker(Some(Arc::new(move || { + let _ = wake_tx.send(()); + }))); + + let fg = ui::ForegroundExecutor::new(dispatcher.clone()); + let bg = ui::BackgroundExecutor::new(dispatcher.clone()); + let main_hits = Arc::new(AtomicUsize::new(0)); + let main_hits_clone = Arc::clone(&main_hits); + let (done_tx, done_rx) = futures::channel::oneshot::channel::<()>(); + + // Park a foreground task on a oneshot resolved by a background worker thread; + // resolving the oneshot off-thread wakes the foreground task via `dispatch_on_main_thread`. + fg.spawn(async move { + let _ = done_rx.await; + main_hits_clone.fetch_add(1, AtomOrd::SeqCst); + }) + .detach(); + // Drain the initial poll so the foreground task is parked waiting on `done_rx`, + // and discard any wakeup already emitted by the initial `fg.spawn` on the main thread. + assert_eq!(dispatcher.drain_ready(), None); + assert_eq!(main_hits.load(AtomOrd::SeqCst), 0); + while wake_rx.try_recv().is_ok() {} + + bg.spawn(async move { + let _ = done_tx.send(()); + }) + .detach(); + + wake_rx + .recv_timeout(Duration::from_secs(2)) + .expect("background thread dispatch_on_main_thread must invoke waker without polling"); + assert!(dispatcher.has_pending_main_tasks()); + let next = dispatcher.drain_ready(); + assert_eq!(main_hits.load(AtomOrd::SeqCst), 1); + assert_eq!(next, None); + } +} diff --git a/packages/frontend/hosts/android/src/editor_platform.rs b/packages/frontend/hosts/android/src/editor_platform.rs new file mode 100644 index 0000000000..8deac9e2d3 --- /dev/null +++ b/packages/frontend/hosts/android/src/editor_platform.rs @@ -0,0 +1,819 @@ +//! Embedded GPUI platform and window bridge for the Android thin host. +//! +//! Runs the shipping `PlaygroundView` directly on Android (`ANativeWindow` + +//! `ui::WgpuRenderer` + `ui::CosmicTextSystem`) and on JVM/Linux/macOS parity +//! hosts via `editor_fallback`. + +use std::{ + cell::RefCell, + ffi::OsString, + path::{Path, PathBuf}, + rc::Rc, + sync::Arc, + time::Duration, +}; + +use anyhow::Result; +use futures::channel::oneshot; +use raw_window_handle::{ + DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle, +}; +#[cfg(target_os = "android")] +use ui::DevicePixels; +use ui::{ + Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ClipboardItem, + CursorStyle, DispatchEventResult, DisplayId, DummyKeyboardMapper, ForegroundExecutor, GpuSpecs, + Keymap, Menu, MenuItem, Modifiers, OperatingSystem, PathPromptOptions, Pixels, Platform, + PlatformAtlas, PlatformDispatcher, PlatformDisplay, PlatformInfo, PlatformInput, + PlatformInputHandler, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTarget, + PlatformTextSystem, PlatformWindow, Point, PromptButton, PromptLevel, RequestFrameOptions, + Scene, Size, Task, TextInputConfiguration, TextInputStateChange, ThermalState, + WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, + WindowParams, WindowVisibility, point, px, size, +}; +use uuid::Uuid; + +pub(crate) use crate::editor_fallback::AndroidDispatcher; +#[cfg(not(target_os = "android"))] +use crate::editor_fallback::FallbackTextSystem; +use crate::editor_fallback::{FallbackAtlas, SwappableAtlas}; + +struct AndroidKeyboardLayout; + +impl PlatformKeyboardLayout for AndroidKeyboardLayout { + fn id(&self) -> &str { + "android.editor" + } + + fn name(&self) -> &str { + "Android" + } +} + +#[derive(Debug)] +struct AndroidDisplay { + bounds: Bounds, +} + +impl PlatformDisplay for AndroidDisplay { + fn id(&self) -> DisplayId { + DisplayId::new(0) + } + + fn uuid(&self) -> Result { + Ok(Uuid::nil()) + } + + fn bounds(&self) -> Bounds { + self.bounds + } + + fn refresh_interval(&self) -> Option { + Some(Duration::from_secs(1) / 60) + } +} + +pub(crate) struct AndroidWindowState { + pub(crate) bounds: Bounds, + pub(crate) scale_factor: f32, + pub(crate) insets: WindowInsets, + pub(crate) input_handler: Option, + pub(crate) request_frame: Option>, + pub(crate) input: Option DispatchEventResult>>, + pub(crate) resize: Option, f32)>>, + pub(crate) visual_viewport_changed: Option>, + pub(crate) appearance_changed: Option>, + pub(crate) active_status_change: Option>, + pub(crate) visibility_change: Option>, + pub(crate) close: Option>, + pub(crate) mouse_position: Point, + pub(crate) modifiers: Modifiers, + pub(crate) ime_position: Option>, + pub(crate) dirty: bool, + pub(crate) text_input_change_seq: u64, + pub(crate) last_text_input_change: Option, + pub(crate) last_scene_quads: usize, + pub(crate) soft_keyboard_requested: bool, +} + +#[derive(Clone)] +pub(crate) struct AndroidEditorWindow { + atlas: Arc, + #[cfg(target_os = "android")] + gpu_context: ui::GpuContext, + #[cfg(target_os = "android")] + renderer: Rc>>, + display: Rc, + pub(crate) state: Rc>, +} + +impl AndroidEditorWindow { + fn new( + bounds: Bounds, + scale_factor: f32, + #[cfg(target_os = "android")] gpu_context: ui::GpuContext, + ) -> Self { + let safe_scale = if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + 2.0 + }; + let display: Rc = Rc::new(AndroidDisplay { bounds }); + #[allow(clippy::arc_with_non_send_sync)] + let atlas = Arc::new(SwappableAtlas::new(Arc::new(FallbackAtlas))); + Self { + atlas, + #[cfg(target_os = "android")] + gpu_context, + #[cfg(target_os = "android")] + renderer: Rc::new(RefCell::new(None)), + display, + state: Rc::new(RefCell::new(AndroidWindowState { + bounds, + scale_factor: safe_scale, + insets: WindowInsets::default(), + input_handler: None, + request_frame: None, + input: None, + resize: None, + visual_viewport_changed: None, + appearance_changed: None, + active_status_change: None, + visibility_change: None, + close: None, + mouse_position: Point::default(), + modifiers: Modifiers::default(), + ime_position: None, + dirty: true, + text_input_change_seq: 0, + last_text_input_change: None, + last_scene_quads: 0, + soft_keyboard_requested: false, + })), + } + } + + #[cfg(target_os = "android")] + pub(crate) fn attach_native_window( + &self, + native_window: *mut core::ffi::c_void, + width_px: u32, + height_px: u32, + ) -> bool { + if native_window.is_null() || width_px == 0 || height_px == 0 { + return false; + } + let mut slot = self.renderer.borrow_mut(); + if let Some(renderer) = slot.as_mut() { + renderer.update_drawable_size(size( + DevicePixels(width_px as i32), + DevicePixels(height_px as i32), + )); + self.state.borrow_mut().dirty = true; + return true; + } + match crate::android_window::create_wgpu_renderer( + Rc::clone(&self.gpu_context), + native_window, + width_px, + height_px, + ) { + Ok(renderer) => { + self.atlas.swap(renderer.sprite_atlas().clone()); + *slot = Some(renderer); + self.state.borrow_mut().dirty = true; + true + } + Err(_) => false, + } + } + + #[cfg(target_os = "android")] + pub(crate) fn detach_native_window(&self) { + self.atlas.swap(Arc::new(FallbackAtlas)); + let _ = self.renderer.borrow_mut().take(); + } + + #[cfg(target_os = "android")] + pub(crate) fn has_gpu_renderer(&self) -> bool { + self.renderer.borrow().is_some() + } + + #[cfg(not(target_os = "android"))] + pub(crate) fn has_gpu_renderer(&self) -> bool { + false + } + + pub(crate) fn request_frame_now(&self) { + self.state.borrow_mut().dirty = false; + let cb = self.state.borrow_mut().request_frame.take(); + if let Some(mut f) = cb { + f(RequestFrameOptions { + require_presentation: true, + ..RequestFrameOptions::default() + }); + self.state.borrow_mut().request_frame = Some(f); + } + } + + pub(crate) fn dispatch_input(&self, event: PlatformInput) -> DispatchEventResult { + let cb = { + let mut st = self.state.borrow_mut(); + match &event { + PlatformInput::MouseDown(e) => st.mouse_position = e.position, + PlatformInput::MouseUp(e) => st.mouse_position = e.position, + PlatformInput::MouseMove(e) => st.mouse_position = e.position, + PlatformInput::Touch(e) => st.mouse_position = e.position, + _ => {} + } + st.dirty = true; + st.input.take() + }; + let Some(mut f) = cb else { + return DispatchEventResult::default(); + }; + let res = f(event); + self.state.borrow_mut().input = Some(f); + res + } + + pub(crate) fn set_viewport(&self, width_dp: f32, height_dp: f32, density: f32) { + let w = width_dp.max(1.0); + let h = height_dp.max(1.0); + let scale = if density.is_finite() && density > 0.0 { + density + } else { + self.state.borrow().scale_factor + }; + let cb = { + let mut st = self.state.borrow_mut(); + st.bounds.size = size(px(w), px(h)); + st.scale_factor = scale; + st.dirty = true; + st.resize.take() + }; + if let Some(mut f) = cb { + f(size(px(w), px(h)), scale); + self.state.borrow_mut().resize = Some(f); + } + } + + pub(crate) fn set_insets(&self, insets: WindowInsets) { + let cb = { + let mut st = self.state.borrow_mut(); + if st.insets == insets { + return; + } + st.insets = insets; + st.dirty = true; + st.visual_viewport_changed.take() + }; + if let Some(mut f) = cb { + f(); + self.state.borrow_mut().visual_viewport_changed = Some(f); + } + } + + pub(crate) fn with_input_handler( + &self, + f: impl FnOnce(&mut PlatformInputHandler) -> R, + ) -> Option { + let mut handler = self.state.borrow_mut().input_handler.take()?; + let out = f(&mut handler); + self.state.borrow_mut().input_handler = Some(handler); + Some(out) + } +} + +impl HasWindowHandle for AndroidEditorWindow { + fn window_handle(&self) -> std::result::Result, HandleError> { + Err(HandleError::Unavailable) + } +} + +impl HasDisplayHandle for AndroidEditorWindow { + fn display_handle(&self) -> std::result::Result, HandleError> { + Err(HandleError::Unavailable) + } +} + +impl PlatformWindow for AndroidEditorWindow { + fn bounds(&self) -> Bounds { + self.state.borrow().bounds + } + + fn is_maximized(&self) -> bool { + true + } + + fn window_bounds(&self) -> WindowBounds { + WindowBounds::Windowed(self.state.borrow().bounds) + } + + fn content_size(&self) -> Size { + self.state.borrow().bounds.size + } + + fn resize(&mut self, size: Size) { + let scale = self.state.borrow().scale_factor; + self.set_viewport(f32::from(size.width), f32::from(size.height), scale); + } + + fn scale_factor(&self) -> f32 { + self.state.borrow().scale_factor + } + + fn appearance(&self) -> WindowAppearance { + WindowAppearance::Light + } + + fn display(&self) -> Option> { + Some(Rc::clone(&self.display)) + } + + fn mouse_position(&self) -> Point { + self.state.borrow().mouse_position + } + + fn modifiers(&self) -> Modifiers { + self.state.borrow().modifiers + } + + fn capslock(&self) -> Capslock { + Capslock::default() + } + + fn set_input_handler(&mut self, input_handler: PlatformInputHandler) { + self.state.borrow_mut().input_handler = Some(input_handler); + } + + fn take_input_handler(&mut self) -> Option { + self.state.borrow_mut().input_handler.take() + } + + fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {} + + fn prompt( + &self, + _level: PromptLevel, + _msg: &str, + _detail: Option<&str>, + _answers: &[PromptButton], + ) -> Option> { + None + } + + fn activate(&self) {} + fn is_active(&self) -> bool { + true + } + fn visibility(&self) -> WindowVisibility { + WindowVisibility::Visible + } + fn is_hovered(&self) -> bool { + false + } + fn background_appearance(&self) -> WindowBackgroundAppearance { + WindowBackgroundAppearance::Opaque + } + fn set_title(&mut self, _title: &str) {} + fn set_background_appearance(&self, _background_appearance: WindowBackgroundAppearance) {} + fn minimize(&self) {} + fn zoom(&self) {} + fn toggle_fullscreen(&self) {} + fn is_fullscreen(&self) -> bool { + true + } + + fn frame_waker(&self) -> Option> { + let weak = Rc::downgrade(&self.state); + Some(Rc::new(move || { + if let Some(state) = weak.upgrade() { + state.borrow_mut().dirty = true; + } + })) + } + + fn schedule_frame(&self) { + self.state.borrow_mut().dirty = true; + } + + fn on_request_frame(&self, callback: Box) { + self.state.borrow_mut().request_frame = Some(callback); + } + + fn on_input(&self, callback: Box DispatchEventResult>) { + self.state.borrow_mut().input = Some(callback); + } + + fn on_active_status_change(&self, callback: Box) { + self.state.borrow_mut().active_status_change = Some(callback); + } + + fn on_visibility_change(&self, callback: Box) { + self.state.borrow_mut().visibility_change = Some(callback); + } + + fn on_hover_status_change(&self, _callback: Box) {} + + fn on_resize(&self, callback: Box, f32)>) { + self.state.borrow_mut().resize = Some(callback); + } + + fn on_moved(&self, _callback: Box) {} + fn on_display_changed(&self, _callback: Box) {} + fn on_should_close(&self, _callback: Box bool>) {} + + fn on_close(&self, callback: Box) { + self.state.borrow_mut().close = Some(callback); + } + + fn on_hit_test_window_control(&self, _callback: Box Option>) { + } + + fn on_appearance_changed(&self, callback: Box) { + self.state.borrow_mut().appearance_changed = Some(callback); + } + + fn on_visual_viewport_changed(&self, callback: Box) { + self.state.borrow_mut().visual_viewport_changed = Some(callback); + } + + fn insets(&self) -> WindowInsets { + self.state.borrow().insets.clone() + } + + fn draw(&self, scene: &Scene) { + // Clear dirty at present time so pre-draw `App::flush_effects()` calls (e.g. power_state + // query before `window.draw`) cannot leave `dirty` permanently stuck true, while post-draw + // `schedule_frame()` / `frame_waker()` for active animations still re-arm `dirty = true`. + { + let mut st = self.state.borrow_mut(); + st.dirty = false; + st.last_scene_quads = scene.quads.len(); + } + #[cfg(target_os = "android")] + if let Some(renderer) = self.renderer.borrow_mut().as_mut() { + renderer.draw(scene); + } + } + + fn sprite_atlas(&self) -> Arc { + Arc::clone(&self.atlas) as Arc + } + + fn is_subpixel_rendering_supported(&self) -> bool { + false + } + + fn gpu_specs(&self) -> Option { + #[cfg(target_os = "android")] + if let Some(renderer) = self.renderer.borrow().as_ref() { + return renderer.gpu_specs(); + } + None + } + + fn update_ime_position(&self, bounds: Bounds) { + self.state.borrow_mut().ime_position = Some(bounds); + } + + fn show_soft_keyboard(&self) { + self.state.borrow_mut().soft_keyboard_requested = true; + } + + fn text_input_state_changed(&self, change: TextInputStateChange) { + let mut st = self.state.borrow_mut(); + st.text_input_change_seq = st.text_input_change_seq.saturating_add(1); + st.last_text_input_change = Some(change); + } +} + +pub(crate) use crate::editor_selection::take_pending_open_url_global; + +pub(crate) struct AndroidEditorPlatform { + dispatcher: Arc, + background_executor: BackgroundExecutor, + foreground_executor: ForegroundExecutor, + text_system: Arc, + #[cfg(target_os = "android")] + gpu_context: ui::GpuContext, + initial_bounds: Bounds, + initial_scale: f32, + opened_window: RefCell>, + clipboard: RefCell>, + pending_clipboard_write: RefCell>, +} + +impl AndroidEditorPlatform { + pub(crate) fn new(width_dp: f32, height_dp: f32, density: f32) -> Self { + let bounds = Bounds::new( + point(px(0.0), px(0.0)), + size(px(width_dp.max(1.0)), px(height_dp.max(1.0))), + ); + let dispatcher = Arc::new(AndroidDispatcher::new()); + let dyn_dispatcher: Arc = dispatcher.clone(); + let background_executor = BackgroundExecutor::new(dyn_dispatcher.clone()); + let foreground_executor = ForegroundExecutor::new(dyn_dispatcher); + #[cfg(target_os = "android")] + let text_system: Arc = + Arc::new(ui::CosmicTextSystem::new("Roboto")); + #[cfg(not(target_os = "android"))] + let text_system: Arc = Arc::new(FallbackTextSystem); + Self { + dispatcher, + background_executor, + foreground_executor, + text_system, + #[cfg(target_os = "android")] + gpu_context: Rc::new(RefCell::new(None)), + initial_bounds: bounds, + initial_scale: if density.is_finite() && density > 0.0 { + density + } else { + 2.0 + }, + opened_window: RefCell::new(None), + clipboard: RefCell::new(None), + pending_clipboard_write: RefCell::new(None), + } + } + + pub(crate) fn set_clipboard_from_host( + &self, + plain: Option, + html: Option, + markdown: Option, + snapshot: Option, + ) { + *self.clipboard.borrow_mut() = + crate::editor_selection::clipboard_item_from_host(plain, html, markdown, snapshot); + } + + pub(crate) fn take_pending_clipboard_json(&self) -> Option { + self.pending_clipboard_write.borrow_mut().take() + } + + pub(crate) fn dispatcher(&self) -> Arc { + Arc::clone(&self.dispatcher) + } + + pub(crate) fn opened_window(&self) -> Option { + self.opened_window.borrow().clone() + } +} + +impl Platform for AndroidEditorPlatform { + fn platform_info(&self) -> PlatformInfo { + PlatformInfo { + os: OperatingSystem::Android, + target: PlatformTarget::Native, + } + } + + fn background_executor(&self) -> BackgroundExecutor { + self.background_executor.clone() + } + + fn foreground_executor(&self) -> ForegroundExecutor { + self.foreground_executor.clone() + } + + fn text_system(&self) -> Arc { + self.text_system.clone() + } + + fn run(&self, on_finish_launching: Box) { + on_finish_launching(); + } + + fn quit(&self) {} + fn restart(&self, _binary_path: Option, _arguments: Vec) {} + fn activate(&self, _ignoring_other_apps: bool) {} + fn hide(&self) {} + fn hide_other_apps(&self) {} + fn unhide_other_apps(&self) {} + + fn displays(&self) -> Vec> { + vec![Rc::new(AndroidDisplay { + bounds: self.initial_bounds, + })] + } + + fn primary_display(&self) -> Option> { + self.displays().into_iter().next() + } + + fn on_displays_changed(&self, _callback: Box) {} + fn active_window(&self) -> Option { + None + } + + fn open_window( + &self, + _handle: AnyWindowHandle, + options: WindowParams, + ) -> Result> { + let window = AndroidEditorWindow::new( + options.bounds, + self.initial_scale, + #[cfg(target_os = "android")] + Rc::clone(&self.gpu_context), + ); + *self.opened_window.borrow_mut() = Some(window.clone()); + Ok(Box::new(window)) + } + + fn window_appearance(&self) -> WindowAppearance { + WindowAppearance::Light + } + + fn open_url(&self, url: &str) { + crate::editor_selection::enqueue_pending_open_url(url); + } + fn on_open_urls(&self, _callback: Box)>) {} + fn register_url_scheme(&self, _url: &str) -> Task> { + Task::ready(Ok(())) + } + + fn prompt_for_paths( + &self, + _options: PathPromptOptions, + ) -> oneshot::Receiver>>> { + let (tx, rx) = oneshot::channel(); + let _ = tx.send(Ok(None)); + rx + } + + fn prompt_for_new_path( + &self, + _directory: &Path, + _suggested_name: Option<&str>, + ) -> oneshot::Receiver>> { + let (tx, rx) = oneshot::channel(); + let _ = tx.send(Ok(None)); + rx + } + + fn can_select_mixed_files_and_dirs(&self) -> bool { + false + } + + fn reveal_path(&self, _path: &Path) {} + fn open_with_system(&self, _path: &Path) {} + fn on_quit(&self, _callback: Box bool>) {} + fn on_reopen(&self, _callback: Box) {} + fn on_system_sleep(&self, _callback: Box) {} + fn on_system_wake(&self, _callback: Box) {} + fn set_menus(&self, _menus: Vec, _keymap: &Keymap) {} + fn set_dock_menu(&self, _menu: Vec, _keymap: &Keymap) {} + fn on_app_menu_action(&self, _callback: Box) {} + fn on_will_open_app_menu(&self, _callback: Box) {} + fn on_validate_app_menu_command(&self, _callback: Box bool>) {} + + fn thermal_state(&self) -> ThermalState { + ThermalState::Nominal + } + + fn on_thermal_state_change(&self, _callback: Box) {} + + fn prevent_idle_sleep(&self, _reason: &str) -> Task> { + Task::ready(Ok(ActivityGuard::noop())) + } + + fn app_path(&self) -> Result { + Ok(PathBuf::from("AffineAndroidHost")) + } + + fn path_for_auxiliary_executable(&self, name: &str) -> Result { + Ok(PathBuf::from(name)) + } + + fn set_cursor_style(&self, _style: CursorStyle) {} + fn hide_cursor_until_mouse_moves(&self) {} + fn is_cursor_visible(&self) -> bool { + false + } + fn should_auto_hide_scrollbars(&self) -> bool { + true + } + + fn read_from_clipboard(&self) -> Option { + self.clipboard.borrow().clone() + } + + fn write_to_clipboard(&self, item: ClipboardItem) { + *self.pending_clipboard_write.borrow_mut() = Some( + crate::editor_selection::serialize_clipboard_item_json(&item), + ); + *self.clipboard.borrow_mut() = Some(item); + } + + #[cfg(target_os = "linux")] + fn read_from_primary(&self) -> Option { + None + } + + #[cfg(target_os = "linux")] + fn write_to_primary(&self, _item: ClipboardItem) {} + + #[cfg(target_os = "macos")] + fn read_from_find_pasteboard(&self) -> Option { + None + } + + #[cfg(target_os = "macos")] + fn write_to_find_pasteboard(&self, _item: ClipboardItem) {} + + fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task> { + Task::ready(Ok(())) + } + + fn read_credentials(&self, _url: &str) -> Task)>>> { + Task::ready(Ok(None)) + } + + fn delete_credentials(&self, _url: &str) -> Task> { + Task::ready(Ok(())) + } + + fn keyboard_layout(&self) -> Box { + Box::new(AndroidKeyboardLayout) + } + + fn keyboard_mapper(&self) -> Rc { + Rc::new(DummyKeyboardMapper) + } + + fn on_keyboard_layout_change(&self, _callback: Box) {} +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + #[test] + fn android_dispatcher_drains_immediate_and_delayed_tasks_deterministically() { + let dispatcher = Arc::new(AndroidDispatcher::new()); + let fg_executor = ForegroundExecutor::new(dispatcher.clone()); + let bg_executor = BackgroundExecutor::new(dispatcher.clone()); + let immediate_hits = Arc::new(AtomicUsize::new(0)); + let delayed_hits = Arc::new(AtomicUsize::new(0)); + + let imm_clone = Arc::clone(&immediate_hits); + let imm_task = fg_executor.spawn(async move { + imm_clone.fetch_add(1, Ordering::SeqCst); + }); + let del_clone = Arc::clone(&delayed_hits); + let del_bg = bg_executor.clone(); + let del_task = fg_executor.spawn(async move { + del_bg.timer(Duration::from_millis(500)).await; + del_clone.fetch_add(1, Ordering::SeqCst); + }); + + let (wake_tx, wake_rx) = std::sync::mpsc::channel(); + dispatcher.set_waker(Some(Arc::new(move || { + let _ = wake_tx.send(()); + }))); + let pending = dispatcher.drain_ready(); + assert_eq!(immediate_hits.load(Ordering::SeqCst), 1); + assert_eq!(delayed_hits.load(Ordering::SeqCst), 0); + assert!(pending.is_some(), "timer must report remaining delay"); + while wake_rx.try_recv().is_ok() {} + + dispatcher.advance_test_clock(Duration::from_millis(501)); + let mut remaining = dispatcher.drain_ready(); + if delayed_hits.load(Ordering::SeqCst) == 0 { + wake_rx + .recv_timeout(Duration::from_secs(2)) + .expect("delayed timer must invoke dispatcher waker without sleep polling"); + remaining = dispatcher.drain_ready(); + } + assert_eq!(delayed_hits.load(Ordering::SeqCst), 1); + assert!(remaining.is_none()); + drop((imm_task, del_task)); + } + + #[test] + fn android_open_url_allows_only_http_and_https_and_queues_for_jni() { + let platform = AndroidEditorPlatform::new(412.0, 915.0, 2.75); + while take_pending_open_url_global().is_some() {} + for bad in [ + "javascript:alert(1)", + "file:///data/local/tmp", + "intent:#Intent;end", + "http://example.com/\r\n", + ] { + platform.open_url(bad); + } + assert_eq!(take_pending_open_url_global(), None); + + platform.open_url(" https://affine.pro/mobile "); + assert_eq!( + take_pending_open_url_global().as_deref(), + Some("https://affine.pro/mobile") + ); + } +} diff --git a/packages/frontend/hosts/android/src/editor_runtime/ime.rs b/packages/frontend/hosts/android/src/editor_runtime/ime.rs new file mode 100644 index 0000000000..e449a8d44e --- /dev/null +++ b/packages/frontend/hosts/android/src/editor_runtime/ime.rs @@ -0,0 +1,411 @@ +//! IME and UTF-16 InputConnection editing methods for [`AndroidEditorRuntime`]. + +use super::{AndroidEditorRuntime, KEYCODE_DEL, KEYCODE_ENTER}; + +impl AndroidEditorRuntime { + pub(crate) fn ensure_input_handler(&mut self) { + if self.window.state.borrow().input_handler.is_none() { + self.window.request_frame_now(); + } + } + + pub(crate) fn utf16_len(&mut self) -> usize { + self.ensure_input_handler(); + self.window + .with_input_handler(|h| { + // Handlers that do not report a length (the shell's Search field) still answer + // `text_for_range`, which clamps the range to their text. + h.text_length_utf16().or_else(|| { + h.text_for_range(0..usize::MAX, &mut None) + .map(|text| text.encode_utf16().count()) + }) + }) + .flatten() + .unwrap_or(0) + } + + pub(crate) fn utf16_text(&mut self) -> Vec { + self.ensure_input_handler(); + let len = self.utf16_len(); + if len == 0 { + return Vec::new(); + } + let mut adjusted = None; + self.window + .with_input_handler(|h| h.text_for_range(0..len, &mut adjusted)) + .flatten() + .unwrap_or_default() + .encode_utf16() + .collect() + } + + pub(crate) fn utf16_unit(&mut self, index: usize) -> Option { + self.utf16_text().get(index).copied() + } + + pub(crate) fn selection_range(&mut self) -> (usize, usize) { + if let Some(preserved) = self.preserved_selection_during_composing_region { + let len = self.utf16_len(); + let s = preserved.0.min(len); + let e = preserved.1.min(len).max(s); + return (s, e); + } + self.ensure_input_handler(); + self.window + .with_input_handler(|h| h.selected_text_range(true)) + .flatten() + .map(|sel| (sel.range.start, sel.range.end)) + .unwrap_or((0, 0)) + } + + pub(crate) fn composing_range(&mut self) -> Option<(usize, usize)> { + self.ensure_input_handler(); + self.window + .with_input_handler(|h| h.marked_text_range()) + .flatten() + .map(|r| (r.start, r.end)) + } + + fn cursor_after_edit( + start: usize, + inserted_len: usize, + new_cursor_pos: i32, + max_len: usize, + ) -> usize { + if new_cursor_pos > 0 { + start + .saturating_add(inserted_len) + .saturating_add((new_cursor_pos - 1) as usize) + .min(max_len) + } else { + let back = new_cursor_pos.unsigned_abs() as usize; + start.saturating_sub(back).min(max_len) + } + } + + pub(crate) fn commit_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + self.preserved_selection_during_composing_region = None; + let text = String::from_utf16_lossy(utf16); + let replace_start = self + .composing_range() + .map(|(s, _)| s) + .unwrap_or_else(|| self.selection_range().0); + if text == "\n" || text == "\r" { + self.dispatch_key_code(KEYCODE_ENTER, false, false, false); + return; + } + let _ = self + .window + .with_input_handler(|h| h.replace_text_in_range(None, &text)); + if new_cursor_pos != 1 { + let max_len = self.utf16_len(); + let pos = Self::cursor_after_edit(replace_start, utf16.len(), new_cursor_pos, max_len); + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(pos..pos)); + } + self.window.request_frame_now(); + } + + pub(crate) fn set_composing_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + self.preserved_selection_during_composing_region = None; + let text = String::from_utf16_lossy(utf16); + let inserted_len = utf16.len(); + let rel_cursor = if new_cursor_pos > 0 { + inserted_len + .saturating_add((new_cursor_pos - 1) as usize) + .min(inserted_len) + } else { + 0 + }; + let _ = self.window.with_input_handler(|h| { + h.replace_and_mark_text_in_range(None, &text, Some(rel_cursor..rel_cursor)) + }); + self.window.request_frame_now(); + } + + /// H-A1: Marks `[start, end)` with the exact authoritative UTF-16 slice so subsequent + /// `setComposingText` replaces `[start, end)` instead of duplicating text. + pub(crate) fn set_composing_region(&mut self, start: usize, end: usize) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let prev_sel = self.selection_range(); + let len = self.utf16_len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + if lo == hi { + self.preserved_selection_during_composing_region = None; + let _ = self.window.with_input_handler(|h| h.unmark_text()); + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(prev_sel.0..prev_sel.1)); + self.window.request_frame_now(); + return; + } + // Commit any previous composing span first so `lo..hi` addresses current document text. + if self.composing_range().is_some() { + let _ = self.window.with_input_handler(|h| h.unmark_text()); + } + // Align interior UTF-16 surrogate-pair indices to full scalar boundaries so + // `text_for_range` and `replace_and_mark_text_in_range` never split an emoji. + let units = self.utf16_text(); + let is_low_surrogate = |u: u16| (0xDC00..=0xDFFF).contains(&u); + let mut lo = lo.min(units.len()); + let mut hi = hi.min(units.len()); + if lo > 0 && lo < units.len() && is_low_surrogate(units[lo]) { + lo -= 1; + } + if hi > 0 && hi < units.len() && is_low_surrogate(units[hi]) { + hi += 1; + } + let mut adjusted = None; + let existing = self + .window + .with_input_handler(|h| h.text_for_range(lo..hi, &mut adjusted)) + .flatten() + .unwrap_or_default(); + let effective = adjusted.unwrap_or(lo..hi); + let sel_in_region = if prev_sel.0 >= effective.start && prev_sel.1 <= effective.end { + self.preserved_selection_during_composing_region = None; + Some((prev_sel.0 - effective.start)..(prev_sel.1 - effective.start)) + } else { + self.preserved_selection_during_composing_region = Some(prev_sel); + Some(existing.encode_utf16().count()..existing.encode_utf16().count()) + }; + let _ = self.window.with_input_handler(|h| { + h.replace_and_mark_text_in_range(Some(effective), &existing, sel_in_region) + }); + let _ = self.dispatcher.drain_ready(); + self.window.request_frame_now(); + } + + pub(crate) fn finish_composing_text(&mut self) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let preserved = self.preserved_selection_during_composing_region.take(); + let _ = self.window.with_input_handler(|h| h.unmark_text()); + if let Some((s, e)) = preserved { + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(s..e)); + } + self.window.request_frame_now(); + } + + pub(crate) fn set_selection(&mut self, start: usize, end: usize) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + self.preserved_selection_during_composing_region = None; + let len = self.utf16_len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(lo..hi)); + self.window.request_frame_now(); + } + + pub(crate) fn replace_text_utf16( + &mut self, + start: usize, + end: usize, + utf16: &[u16], + new_cursor_pos: i32, + ) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + self.preserved_selection_during_composing_region = None; + if self.composing_range().is_some() { + let _ = self.window.with_input_handler(|h| h.unmark_text()); + } + let len = self.utf16_len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + let text = String::from_utf16_lossy(utf16); + let _ = self + .window + .with_input_handler(|h| h.replace_text_in_range(Some(lo..hi), &text)); + let max_len = self.utf16_len(); + let pos = Self::cursor_after_edit(lo, utf16.len(), new_cursor_pos, max_len); + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(pos..pos)); + self.window.request_frame_now(); + } + + fn is_high_surrogate(u: u16) -> bool { + (0xD800..=0xDBFF).contains(&u) + } + + fn is_low_surrogate(u: u16) -> bool { + (0xDC00..=0xDFFF).contains(&u) + } + + pub(crate) fn delete_surrounding_text(&mut self, before_len: usize, after_len: usize) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let units = self.utf16_text(); + let len = units.len(); + let (sel_start, sel_end) = self.selection_range(); + let composing = self.composing_range(); + + // AOSP BaseInputConnection: delete outside composing span when composing is active. + let (anchor_before, anchor_after) = if let Some((cs, ce)) = composing { + (sel_start.min(cs), sel_end.max(ce)) + } else { + (sel_start, sel_end) + }; + + let mut del_before_start = anchor_before.saturating_sub(before_len); + if del_before_start > 0 + && del_before_start < len + && Self::is_low_surrogate(units[del_before_start]) + && Self::is_high_surrogate(units[del_before_start - 1]) + { + del_before_start -= 1; + } + let mut del_after_end = anchor_after.saturating_add(after_len).min(len); + if del_after_end > 0 + && del_after_end < len + && Self::is_high_surrogate(units[del_after_end - 1]) + && Self::is_low_surrogate(units[del_after_end]) + { + del_after_end += 1; + } + + let removed_before = anchor_before - del_before_start; + let removed_after = del_after_end - anchor_after; + if removed_before == 0 && removed_after == 0 { + // When Gboard issues `deleteSurroundingText(1, 0)` at the very start of a block + // (collapsed caret at offset 0 with no active composing span), bridge it to a + // structural Backspace so adjacent non-mergeable block selection and cross-block + // merging behave identically to hardware/software KEYCODE_DEL. + if composing.is_none() + && sel_start == 0 + && sel_end == 0 + && before_len >= 1 + && after_len == 0 + { + let _ = self.dispatch_key_code(KEYCODE_DEL, false, false, false); + } + return; + } + + if let Some((cs, ce)) = composing { + let comp_text = String::from_utf16_lossy(&units[cs..ce]); + let _ = self.window.with_input_handler(|h| h.unmark_text()); + if removed_after > 0 { + let _ = self.window.with_input_handler(|h| { + h.replace_text_in_range(Some(anchor_after..del_after_end), "") + }); + } + if removed_before > 0 { + let _ = self.window.with_input_handler(|h| { + h.replace_text_in_range(Some(del_before_start..anchor_before), "") + }); + } + let new_cs = cs.saturating_sub(removed_before); + let new_ce = ce.saturating_sub(removed_before); + let new_sel_s = sel_start.saturating_sub(removed_before); + let new_sel_e = sel_end.saturating_sub(removed_before); + let rel = if new_sel_s >= new_cs && new_sel_e <= new_ce { + Some((new_sel_s - new_cs)..(new_sel_e - new_cs)) + } else { + Some(comp_text.encode_utf16().count()..comp_text.encode_utf16().count()) + }; + let _ = self.window.with_input_handler(|h| { + h.replace_and_mark_text_in_range(Some(new_cs..new_ce), &comp_text, rel) + }); + } else { + if removed_after > 0 { + let _ = self.window.with_input_handler(|h| { + h.replace_text_in_range(Some(anchor_after..del_after_end), "") + }); + } + if removed_before > 0 { + let _ = self.window.with_input_handler(|h| { + h.replace_text_in_range(Some(del_before_start..anchor_before), "") + }); + } + let new_start = sel_start.saturating_sub(removed_before); + let new_end = sel_end.saturating_sub(removed_before); + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(new_start..new_end)); + } + self.window.request_frame_now(); + } + + pub(crate) fn delete_surrounding_text_in_code_points( + &mut self, + before_code_points: usize, + after_code_points: usize, + ) -> bool { + if self.shell_blocks_text_input() { + return false; + } + self.ensure_input_handler(); + let units = self.utf16_text(); + let (sel_start, sel_end) = self.selection_range(); + let (anchor_before, anchor_after) = if let Some((cs, ce)) = self.composing_range() { + (sel_start.min(cs), sel_end.max(ce)) + } else { + (sel_start, sel_end) + }; + + let mut b_idx = anchor_before; + for _ in 0..before_code_points { + if b_idx == 0 { + break; + } + b_idx -= 1; + if Self::is_low_surrogate(units[b_idx]) { + if b_idx == 0 || !Self::is_high_surrogate(units[b_idx - 1]) { + return false; + } + b_idx -= 1; + } else if Self::is_high_surrogate(units[b_idx]) { + return false; + } + } + let mut a_idx = anchor_after; + for _ in 0..after_code_points { + if a_idx >= units.len() { + break; + } + if Self::is_high_surrogate(units[a_idx]) { + if a_idx + 1 >= units.len() || !Self::is_low_surrogate(units[a_idx + 1]) { + return false; + } + a_idx += 2; + } else if Self::is_low_surrogate(units[a_idx]) { + return false; + } else { + a_idx += 1; + } + } + self.delete_surrounding_text(anchor_before - b_idx, a_idx - anchor_after); + true + } +} diff --git a/packages/frontend/hosts/android/src/editor_runtime/mod.rs b/packages/frontend/hosts/android/src/editor_runtime/mod.rs new file mode 100644 index 0000000000..f432dade0e --- /dev/null +++ b/packages/frontend/hosts/android/src/editor_runtime/mod.rs @@ -0,0 +1,687 @@ +//! Live pure-Rust BlockSuite editor runtime for the Android thin host. + +use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc, time::Duration}; + +use playground::{FormFactor, PlaygroundMode, PlaygroundOptions, PlaygroundView}; +use ui::{ + App, AppContext, Application, ApplicationHandle, Bounds, Edges, Entity, KeyDownEvent, + Keystroke, Modifiers, PlatformInput, Render, ScrollDelta, ScrollEvent, ScrollSource, + TouchEvent, TouchId, TouchPhase, Window, WindowBounds, WindowInsets, WindowOptions, point, px, + size, +}; + +use crate::{ + LogicalWindowInsets, + editor_platform::{AndroidDispatcher, AndroidEditorPlatform, AndroidEditorWindow}, + runtime_root::{EditorView, RuntimeRoot, ShellHost}, +}; + +mod ime; + +pub const KEYCODE_DPAD_UP: i32 = 19; +pub const KEYCODE_DPAD_DOWN: i32 = 20; +pub const KEYCODE_DPAD_LEFT: i32 = 21; +pub const KEYCODE_DPAD_RIGHT: i32 = 22; +pub const KEYCODE_TAB: i32 = 61; +pub const KEYCODE_ENTER: i32 = 66; +pub const KEYCODE_DEL: i32 = 67; +pub const KEYCODE_ESCAPE: i32 = 111; +pub const KEYCODE_FORWARD_DEL: i32 = 112; +pub const KEYCODE_NUMPAD_ENTER: i32 = 160; + +pub(crate) struct AndroidEditorRuntime { + pub(crate) app: ApplicationHandle, + pub(crate) platform: Rc, + pub(crate) dispatcher: Arc, + pub(crate) window: AndroidEditorWindow, + pub(crate) root: RuntimeRoot, + pub(crate) shell: Option, + form_factor: FormFactor, + /// Preserved selection when `setComposingRegion` marks a span outside the current caret + /// (matches AOSP `BaseInputConnection.setComposingRegion`, which must not alter selection). + preserved_selection_during_composing_region: Option<(usize, usize)>, +} + +thread_local! { + static ANDROID_EDITORS: RefCell> = + const { RefCell::new(BTreeMap::new()) }; +} + +pub(crate) fn attach_editor(handle: i64, runtime: Option) { + if let Some(rt) = runtime { + ANDROID_EDITORS.with(|map| { + map.borrow_mut().insert(handle, rt); + }); + } +} + +pub(crate) fn detach_editor(handle: i64) { + ANDROID_EDITORS.with(|map| { + map.borrow_mut().remove(&handle); + }); +} + +pub(crate) fn with_editor_mut( + handle: i64, + f: impl FnOnce(&mut AndroidEditorRuntime) -> R, +) -> Option { + ANDROID_EDITORS.with(|map| map.borrow_mut().get_mut(&handle).map(f)) +} + +impl AndroidEditorRuntime { + pub(crate) fn new( + width_dp: f32, + height_dp: f32, + density: f32, + form_factor: FormFactor, + load_showcase: bool, + ) -> Option { + let mut options = PlaygroundOptions::for_form_factor(form_factor); + options.native_selection_ui = true; + Self::open( + width_dp, + height_dp, + density, + form_factor, + None, + move |window, cx| { + let entity = cx.new(|cx| PlaygroundView::with_options(options, cx)); + entity.update(cx, |view, cx| { + if !load_showcase { + view.load_empty_page_document(window, cx); + } else if !form_factor.is_touch_form_factor() { + view.focus_first_text_block(window, cx); + } + }); + entity + }, + RuntimeRoot::Editor, + ) + } + + /// Open the embedded window with the root view that `build` creates. + pub(crate) fn open( + width_dp: f32, + height_dp: f32, + density: f32, + form_factor: FormFactor, + shell: Option, + build: impl FnOnce(&mut Window, &mut App) -> Entity + 'static, + root: fn(ui::WindowHandle) -> RuntimeRoot, + ) -> Option { + let w = if width_dp.is_finite() && width_dp > 1.0 { + width_dp + } else { + 412.0 + }; + let h = if height_dp.is_finite() && height_dp > 1.0 { + height_dp + } else { + 915.0 + }; + let d = if density.is_finite() && density > 0.0 { + density + } else { + 2.625 + }; + + let platform = Rc::new(AndroidEditorPlatform::new(w, h, d)); + let platform_ref = Rc::clone(&platform); + let root_slot: Rc>> = Rc::new(RefCell::new(None)); + let root_slot_init = Rc::clone(&root_slot); + let bounds = Bounds::new(point(px(0.0), px(0.0)), size(px(w), px(h))); + + let app = Application::with_platform(platform).run_embedded(move |cx| { + let _ = affine_mobile::register_mobile_fonts(cx); + let _ = playground::register_bundled_fonts(cx); + if let Ok(handle) = cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + ..WindowOptions::default() + }, + move |window, cx| { + window.set_touch_gestures_enabled(true); + build(window, cx) + }, + ) { + *root_slot_init.borrow_mut() = Some(root(handle)); + } + }); + + let dispatcher = platform_ref.dispatcher(); + let window = platform_ref.opened_window()?; + let root = root_slot.borrow_mut().take()?; + let rt = Self { + app, + platform: platform_ref, + dispatcher, + window, + root, + shell, + form_factor, + preserved_selection_during_composing_region: None, + }; + let _ = rt.dispatcher.drain_ready(); + rt.window.request_frame_now(); + rt.window.state.borrow_mut().soft_keyboard_requested = false; + Some(rt) + } + + /// The page editor that owns text input right now (see [`RuntimeRoot::editor`]). + pub(crate) fn view(&self) -> EditorView { + EditorView(self.root) + } + + #[cfg(target_os = "android")] + pub(crate) fn attach_surface( + &mut self, + native_window: *mut core::ffi::c_void, + width_px: u32, + height_px: u32, + density: f32, + ) -> bool { + let ok = self + .window + .attach_native_window(native_window, width_px, height_px); + self.resize_px(width_px, height_px, density); + ok + } + + #[cfg(target_os = "android")] + pub(crate) fn detach_surface(&mut self) { + self.window.detach_native_window(); + } + + pub(crate) fn has_gpu_renderer(&self) -> bool { + self.window.has_gpu_renderer() + } + + pub(crate) fn drain_tasks(&self) -> Option { + self.dispatcher.drain_ready() + } + + pub(crate) fn resize_px(&mut self, width_px: u32, height_px: u32, density: f32) { + let d = if density.is_finite() && density > 0.0 { + density + } else { + 1.0 + }; + let w = (width_px as f32 / d).max(1.0); + let h = (height_px as f32 / d).max(1.0); + self.window.set_viewport(w, h, d); + let _ = self.dispatcher.drain_ready(); + self.window.request_frame_now(); + } + + pub(crate) fn set_insets(&mut self, insets: LogicalWindowInsets) { + let ui_insets = WindowInsets { + safe_area: Edges { + top: px(insets.safe_top.max(0.0)), + right: px(insets.safe_right.max(0.0)), + bottom: px(insets.safe_bottom.max(0.0)), + left: px(insets.safe_left.max(0.0)), + }, + ime: Edges { + top: px(0.0), + right: px(0.0), + bottom: px(insets.ime_bottom.max(0.0)), + left: px(0.0), + }, + ..WindowInsets::default() + }; + self.window.set_insets(ui_insets); + } + + pub(crate) fn is_dirty(&self) -> bool { + self.window.state.borrow().dirty + } + + pub(crate) fn mark_dirty(&mut self) { + self.window.state.borrow_mut().dirty = true; + } + + pub(crate) fn set_waker(&self, waker: Option>) { + self.dispatcher.set_waker(waker); + } + + pub(crate) fn has_pending_main_tasks(&self) -> bool { + self.dispatcher.has_pending_main_tasks() + } + + pub(crate) fn is_dark_theme(&self) -> bool { + self.root_theme() == Some(playground::PlaygroundTheme::Dark) + } + + pub(crate) fn render_frame(&mut self) -> bool { + let _ = self.dispatcher.drain_ready(); + if !self.is_dirty() { + return false; + } + self.hydrate_shown_page(); + self.window.request_frame_now(); + true + } + + pub(crate) fn set_form_factor_from_smallest_width_dp(&mut self, smallest_width_dp: i32) { + let ff = FormFactor::from_android_smallest_width_dp(smallest_width_dp); + self.set_form_factor(ff); + } + + pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) { + self.form_factor = form_factor; + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.set_form_factor(form_factor, window, cx); + }); + }); + self.window.request_frame_now(); + } + + fn read_bool(&self, f: impl FnOnce(&PlaygroundView) -> bool, default: bool) -> bool { + self.app + .update(|cx| self.view().read_with(cx, |v, _| f(v))) + .unwrap_or(default) + } + + pub(crate) fn wants_software_keyboard(&self) -> bool { + if self.shell_search_focused() { + return true; + } + self.read_bool(PlaygroundView::wants_software_keyboard, false) + } + + pub(crate) fn take_software_keyboard_request(&self) -> bool { + std::mem::take(&mut self.window.state.borrow_mut().soft_keyboard_requested) + } + + pub(crate) fn wants_code_input(&self) -> bool { + self.read_bool(PlaygroundView::wants_code_input_mode, false) + } + + pub(crate) fn edgeless_readonly(&self) -> bool { + self.read_bool(PlaygroundView::edgeless_readonly, true) + } + + pub(crate) fn database_readonly(&self) -> bool { + self.read_bool(PlaygroundView::database_readonly, true) + } + + pub(crate) fn is_page_readonly(&self) -> bool { + self.read_bool(PlaygroundView::is_page_readonly, false) + } + + pub(crate) fn active_doc_id(&self) -> Option { + self.app.update(|cx| { + self.view() + .read_with(cx, |v, _| v.active_doc_id().map(str::to_string)) + .ok() + .flatten() + }) + } + + pub(crate) fn active_page_snapshot_json(&self) -> Option { + self.app.update(|cx| { + self.view() + .read_with(cx, |v, _| v.active_page_snapshot_json()) + .ok() + .flatten() + }) + } + + pub(crate) fn append_shared_blocks_preserving_selection( + &mut self, + items: &[playground::overlays::SharedNoteBlockItem], + now_ms: u64, + ) -> Vec { + let committed = self.app.update(|cx| { + self.view() + .update(cx, |v, w, cx| { + v.append_shared_blocks_preserving_selection(items, now_ms, w, cx) + }) + .unwrap_or_default() + }); + if !committed.is_empty() { + let _ = self.dispatcher.drain_ready(); + self.window.request_frame_now(); + } + committed + } + + pub(crate) fn set_mode(&mut self, mode: PlaygroundMode) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |v, w, cx| v.set_mode(mode, w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn load_showcase_document(&mut self) { + self.preserved_selection_during_composing_region = None; + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, w, cx| v.load_showcase_document(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn reset_empty_document(&mut self) { + self.preserved_selection_during_composing_region = None; + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, w, cx| v.load_empty_page_document(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn dispatch_touch(&mut self, pointer_id: u64, phase: u8, x_dp: f32, y_dp: f32) { + self.preserved_selection_during_composing_region = None; + if phase == 0 { + self.window.state.borrow_mut().soft_keyboard_requested = false; + } + let touch_phase = match phase { + 0 => TouchPhase::Started, + 1 => TouchPhase::Moved, + 2 => TouchPhase::Ended, + _ => TouchPhase::Cancelled, + }; + let event = TouchEvent { + id: TouchId(pointer_id), + phase: touch_phase, + position: point(px(x_dp), px(y_dp)), + predicted_position: None, + force: None, + }; + let _ = self.window.dispatch_input(PlatformInput::Touch(event)); + self.hydrate_shown_page(); + self.window.request_frame_now(); + if matches!(touch_phase, TouchPhase::Ended) { + self.request_keyboard_for_search_focus(); + } + } + + pub(crate) fn dispatch_scroll_wheel(&mut self, x: f32, y: f32, dx: f32, dy: f32) { + let _ = self + .window + .dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(x), px(y)), + delta: ScrollDelta::Pixels(point(px(dx), px(dy))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: ScrollSource::Pointer, + })); + self.window.request_frame_now(); + } + + /// Platform back action: the page editor closes its own overlay first, then the shell + /// closes a sheet or the drawer, or steps back through its route history. + pub(crate) fn handle_back(&mut self) -> bool { + let handled = self.app.update(|cx| { + self.view() + .update(cx, |v, w, cx| v.handle_back(w, cx)) + .unwrap_or(false) + }) || self.shell_back(); + if handled { + self.window.request_frame_now(); + } + handled + } + + pub(crate) fn dispatch_key_code( + &mut self, + key_code: i32, + shift: bool, + ctrl: bool, + alt: bool, + ) -> bool { + let key_name = match key_code { + KEYCODE_DEL => "backspace", + KEYCODE_FORWARD_DEL => "delete", + KEYCODE_ENTER | KEYCODE_NUMPAD_ENTER => "enter", + KEYCODE_DPAD_LEFT => "left", + KEYCODE_DPAD_RIGHT => "right", + KEYCODE_DPAD_UP => "up", + KEYCODE_DPAD_DOWN => "down", + KEYCODE_ESCAPE => "escape", + KEYCODE_TAB => "tab", + _ => return false, + }; + if key_code != KEYCODE_ESCAPE && self.shell_blocks_text_input() { + return false; + } + self.preserved_selection_during_composing_region = None; + if self.composing_range().is_some() + && matches!(key_code, KEYCODE_ENTER | KEYCODE_NUMPAD_ENTER) + { + self.finish_composing_text(); + } + let event = KeyDownEvent { + keystroke: Keystroke { + modifiers: Modifiers { + control: ctrl, + alt, + shift, + platform: false, + function: false, + }, + key: key_name.to_string(), + key_char: None, + }, + is_held: false, + prefer_character_input: false, + }; + let _ = self.window.dispatch_input(PlatformInput::KeyDown(event)); + self.window.request_frame_now(); + true + } + + pub(crate) fn text_input_change_seq(&self) -> u64 { + self.window.state.borrow().text_input_change_seq + } + + pub(crate) fn focused_block_hash(&self) -> u64 { + self.app + .update(|cx| { + self.view().read_with(cx, |view, _| { + let Some(sel) = view.document_selection() else { + return 0; + }; + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in sel.focus.block_id.as_bytes() { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h + }) + }) + .unwrap_or(0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn android_editor_runtime_gboard_composing_region_and_stage_one_readonly() { + let mut rt = + AndroidEditorRuntime::new(412.0, 915.0, 2.625, FormFactor::Phone, false).expect("rt"); + assert!(rt.edgeless_readonly()); + assert!(rt.database_readonly()); + + // H-A1: Gboard backspace-into-word: " hello" -> setComposingRegion(1, 6) -> setComposingText("hellos") + let hello: Vec = " hello".encode_utf16().collect(); + rt.commit_text_utf16(&hello, 1); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), " hello"); + + rt.set_composing_region(1, 6); + assert_eq!(rt.composing_range(), Some((1, 6))); + + let hellos: Vec = "hellos".encode_utf16().collect(); + rt.set_composing_text_utf16(&hellos, 1); + assert_eq!( + String::from_utf16_lossy(&rt.utf16_text()), + " hellos", + "Gboard composing region replacement must not duplicate 'hello'" + ); + + // KeyEvent ENTER splits block, KEYCODE_DEL at block start merges back. + assert!(rt.dispatch_key_code(KEYCODE_ENTER, false, false, false)); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), ""); + assert!(rt.dispatch_key_code(KEYCODE_DEL, false, false, false)); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), " hellos"); + + // H-A1 surrogate pair alignment: "a😀b" has '😀' at UTF-16 [1..3). + // Passing an interior surrogate index (1..2) must align to the full scalar range [1..3). + rt.reset_empty_document(); + let emoji: Vec = "a😀b".encode_utf16().collect(); + rt.commit_text_utf16(&emoji, 1); + rt.set_composing_region(1, 2); + let replacement: Vec = "🎉".encode_utf16().collect(); + rt.set_composing_text_utf16(&replacement, 1); + assert_eq!( + String::from_utf16_lossy(&rt.utf16_text()), + "a🎉b", + "surrogate-pair composing region must align cleanly without splitting or duplicating" + ); + + // FormFactor Phone/Tablet read-only vs Desktop unlocked. + rt.set_form_factor_from_smallest_width_dp(720); + assert!(rt.edgeless_readonly()); + assert!(rt.database_readonly()); + rt.set_form_factor(FormFactor::Desktop); + assert!(!rt.edgeless_readonly()); + assert!(!rt.database_readonly()); + } + + #[test] + fn android_editor_runtime_frame_dirty_lifecycle_and_block_start_delete_surrounding() { + let mut rt = + AndroidEditorRuntime::new(412.0, 915.0, 2.625, FormFactor::Phone, false).expect("rt"); + // Initial frame clears dirty to false when idle. + let _ = rt.render_frame(); + assert!( + !rt.is_dirty(), + "idle frame must leave is_dirty() == false for 0-fps idle" + ); + assert!( + !rt.render_frame(), + "second idle render_frame() must skip GPU draw" + ); + + // 1. Delayed timer triggering cx.notify() must mark dirty == true and render on next tick. + let (wake_tx, wake_rx) = std::sync::mpsc::channel(); + rt.set_waker(Some(Arc::new(move || { + let _ = wake_tx.send(()); + }))); + let view = rt.view(); + rt.app.update(|cx| { + let bg = cx.background_executor().clone(); + cx.spawn(async move |cx| { + bg.timer(Duration::from_millis(50)).await; + let _ = cx.update(|cx| { + let _ = view.update(cx, |_, _, cx| cx.notify()); + }); + }) + .detach(); + }); + let _ = rt.drain_tasks(); + assert!(!rt.is_dirty()); + while wake_rx.try_recv().is_ok() {} + rt.dispatcher.advance_test_clock(Duration::from_millis(60)); + let _ = rt.drain_tasks(); + while !rt.is_dirty() { + wake_rx + .recv_timeout(Duration::from_secs(1)) + .expect("timer wakeup"); + let _ = rt.drain_tasks(); + } + rt.set_waker(None); + assert!( + rt.is_dirty(), + "timer-driven cx.notify() must set is_dirty() == true via frame_waker" + ); + assert!(rt.render_frame(), "dirty frame must execute render_frame()"); + assert!( + !rt.is_dirty(), + "after idle draw, is_dirty() returns to false" + ); + + // 2. Requesting an animation frame *during* render_frame() must keep is_dirty() == true + // immediately after render_frame() returns (continuous animation liveness). + rt.set_mode(PlaygroundMode::Edgeless); + assert!(rt.is_dirty(), "mode switch must mark dirty"); + assert!( + rt.render_frame(), + "first animation frame after mode switch must execute" + ); + assert!( + rt.is_dirty(), + "request_animation_frame() called inside render_frame() must preserve is_dirty() == true" + ); + rt.set_mode(PlaygroundMode::Page); + let _ = rt.app.update(|cx| { + let _ = rt + .view() + .update(cx, |v, w, cx| v.focus_first_text_block(w, cx)); + }); + let _ = rt.render_frame(); + + // 3. Block-start deleteSurroundingText(1, 0) bridges to structural Backspace (merges blocks). + let first: Vec = "Alpha".encode_utf16().collect(); + rt.commit_text_utf16(&first, 1); + assert!(rt.dispatch_key_code(KEYCODE_ENTER, false, false, false)); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), ""); + rt.delete_surrounding_text(1, 0); + assert_eq!( + String::from_utf16_lossy(&rt.utf16_text()), + "Alpha", + "deleteSurroundingText(1, 0) at block start must bridge to structural Backspace" + ); + } + + #[test] + fn android_touch_cold_start_showcase_checkbox_and_halo_do_not_request_keyboard() { + let mut rt = + AndroidEditorRuntime::new(412.0, 915.0, 2.625, FormFactor::Phone, true).expect("rt"); + let _ = rt.render_frame(); + assert!( + !rt.wants_software_keyboard() && !rt.take_software_keyboard_request(), + "cold-start showcase on Android Phone must not pre-arm software keyboard" + ); + + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |v, _, cx| { + assert!(v.scroll_to_block("showcase-todo-open", cx)); + }); + }); + rt.window.request_frame_now(); + let (inner_x, halo_x, check_y, scroll_before) = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + let layout = v.flow_layout().expect("layout"); + let b = layout.block("showcase-todo-open").expect("todo-open"); + let col_x = ((412.0 - b.rect().w) * 0.5).max(0.0); + let sy = playground::TOPBAR_HEIGHT + b.y - v.scroll_offset() + 12.0; + (col_x + b.x + 12.0, col_x + b.x - 6.0, sy, v.scroll_offset()) + }) + }) + .expect("coords"); + assert!(scroll_before > 50.0); + + rt.dispatch_touch(1, 0, inner_x, check_y); + rt.dispatch_touch(1, 2, inner_x, check_y); + assert!(!rt.take_software_keyboard_request() && !rt.wants_software_keyboard()); + + rt.dispatch_touch(2, 0, halo_x, check_y); + rt.dispatch_touch(2, 2, halo_x, check_y); + assert!(!rt.take_software_keyboard_request() && !rt.wants_software_keyboard()); + + let scroll_after = rt + .app + .update(|cx| rt.view().read_with(cx, |v, _| v.scroll_offset())) + .unwrap_or(0.0); + assert!((scroll_after - scroll_before).abs() < 1.0); + } +} diff --git a/packages/frontend/hosts/android/src/editor_selection.rs b/packages/frontend/hosts/android/src/editor_selection.rs new file mode 100644 index 0000000000..b1a2058e38 --- /dev/null +++ b/packages/frontend/hosts/android/src/editor_selection.rs @@ -0,0 +1,255 @@ +//! Document-level selection geometry, cross-block handle drag, authoritative +//! selection actions, multi-MIME clipboard helpers, and validated external URL +//! queueing for `AndroidEditorRuntime`. + +use std::{cell::RefCell, collections::VecDeque}; + +use ui::ClipboardItem; + +use crate::editor_runtime::AndroidEditorRuntime; + +thread_local! { + static ANDROID_PENDING_OPEN_URLS: RefCell> = + const { RefCell::new(VecDeque::new()) }; +} + +pub(crate) fn enqueue_pending_open_url(url: &str) { + if url.chars().any(char::is_control) { + return; + } + let trimmed = url.trim(); + if !(trimmed.starts_with("https://") || trimmed.starts_with("http://")) { + return; + } + ANDROID_PENDING_OPEN_URLS.with(|q| { + let mut g = q.borrow_mut(); + if g.len() >= 16 { + g.pop_front(); + } + g.push_back(trimmed.to_string()); + }); +} + +pub(crate) fn take_pending_open_url_global() -> Option { + ANDROID_PENDING_OPEN_URLS.with(|q| q.borrow_mut().pop_front()) +} + +pub(crate) fn clipboard_item_from_host( + plain: Option, + html: Option, + markdown: Option, + snapshot: Option, +) -> Option { + let mut meta = serde_json::Map::new(); + if let Some(s) = snapshot.filter(|v| !v.is_empty()) { + meta.insert( + "application/x-blocksuite-snapshot".to_string(), + serde_json::Value::String(s), + ); + } + if let Some(h) = html.filter(|v| !v.is_empty()) { + meta.insert("text/html".to_string(), serde_json::Value::String(h)); + } + if let Some(m) = markdown.filter(|v| !v.is_empty()) { + meta.insert("text/markdown".to_string(), serde_json::Value::String(m)); + } + let plain_str = plain.unwrap_or_default(); + if !meta.is_empty() { + Some(ClipboardItem::new_string_with_json_metadata( + plain_str, + serde_json::Value::Object(meta), + )) + } else if !plain_str.is_empty() { + Some(ClipboardItem::new_string(plain_str)) + } else { + None + } +} + +pub(crate) fn serialize_clipboard_item_json(item: &ClipboardItem) -> String { + let mut map = serde_json::Map::new(); + if let Some(text) = item.text() { + map.insert("text/plain".to_string(), serde_json::Value::String(text)); + } + if let Some(meta_str) = item.metadata() + && let Ok(serde_json::Value::Object(meta)) = + serde_json::from_str::(meta_str) + { + for (k, v) in meta { + if k == "application/x-blocksuite-snapshot" { + let s = match v { + serde_json::Value::String(s) => s, + other => other.to_string(), + }; + map.insert(k, serde_json::Value::String(s)); + } else if let serde_json::Value::String(s) = v { + map.insert(k, serde_json::Value::String(s)); + } + } + } + serde_json::Value::Object(map).to_string() +} + +impl AndroidEditorRuntime { + pub(crate) fn set_page_readonly(&mut self, readonly: bool) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, _, cx| v.set_page_readonly(readonly, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn document_selection_geometry(&mut self) -> playground::DocumentSelectionGeometry { + self.app + .update(|cx| { + self.view() + .update(cx, |v, w, _| v.document_selection_geometry(w)) + }) + .unwrap_or_default() + } + + /// Packs document-level selection geometry into a 24-float buffer (dp coordinates) + /// for zero-allocation per-frame JNI queries from `MainActivity` and `AndroidSelectionOverlayView`. + pub(crate) fn pack_document_selection_floats(&mut self) -> [f32; 24] { + let g = self.document_selection_geometry(); + [ + if g.has_selection { 1.0 } else { 0.0 }, + if g.is_collapsed { 1.0 } else { 0.0 }, + if g.is_reversed { 1.0 } else { 0.0 }, + if g.start_visible { 1.0 } else { 0.0 }, + g.start_caret.x, + g.start_caret.y, + g.start_caret.height, + if g.start_caret.is_rtl { 1.0 } else { 0.0 }, + if g.end_visible { 1.0 } else { 0.0 }, + g.end_caret.x, + g.end_caret.y, + g.end_caret.height, + if g.end_caret.is_rtl { 1.0 } else { 0.0 }, + if g.menu_anchor_visible { 1.0 } else { 0.0 }, + g.menu_anchor_rect.x, + g.menu_anchor_rect.y, + g.menu_anchor_rect.width, + g.menu_anchor_rect.height, + g.action_mask as f32, + if g.menu_suppressed_for_motion { + 1.0 + } else { + 0.0 + }, + g.visible_top, + g.visible_bottom, + g.selection_rects.len() as f32, + 0.0, + ] + } + + pub(crate) fn selection_menu_request_seq(&self) -> u64 { + self.app + .update(|cx| { + self.view() + .read_with(cx, |v, _| v.selection_menu_request_seq()) + }) + .unwrap_or(0) + } + + pub(crate) fn begin_document_selection_drag(&mut self, handle: u8) -> bool { + self.app + .update(|cx| { + self.view() + .update(cx, |v, w, _| v.begin_document_selection_drag(handle, w)) + }) + .unwrap_or(false) + } + + pub(crate) fn update_document_selection_drag(&mut self, x_dp: f32, y_dp: f32) -> bool { + let ok = self + .app + .update(|cx| { + self.view().update(cx, |v, w, cx| { + v.update_document_selection_drag(x_dp, y_dp, w, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn end_document_selection_drag(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, w, cx| v.end_document_selection_drag(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn cancel_document_selection_drag(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, _, _| v.cancel_document_selection_drag()); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_copy(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |v, w, cx| v.selection_copy(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_cut(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |v, w, cx| v.selection_cut(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_paste( + &mut self, + plain: Option, + html: Option, + markdown: Option, + snapshot: Option, + ) { + self.platform + .set_clipboard_from_host(plain, html, markdown, snapshot); + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |v, w, cx| v.selection_paste(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_select_all(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |v, w, cx| v.selection_select_all(w, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn take_pending_clipboard_json(&self) -> Option { + self.platform.take_pending_clipboard_json() + } + + pub(crate) fn caret_rect_dp(&mut self) -> Option<[f32; 4]> { + self.ensure_input_handler(); + let (_, end) = self.selection_range(); + let b = self + .window + .with_input_handler(|h| h.bounds_for_range(end..end)) + .flatten()?; + Some([ + f32::from(b.origin.x), + f32::from(b.origin.y), + f32::from(b.size.width).max(2.0), + f32::from(b.size.height).max(20.0), + ]) + } +} diff --git a/packages/frontend/hosts/android/src/ime.rs b/packages/frontend/hosts/android/src/ime.rs new file mode 100644 index 0000000000..cd8e840949 --- /dev/null +++ b/packages/frontend/hosts/android/src/ime.rs @@ -0,0 +1,405 @@ +use crate::AndroidHostState; +use crate::selection::SelectionHandleKind; +use crate::text_layout::{ + caret_position_for_offset, closest_offset_for_position, detect_direction_at_offset, +}; + +impl AndroidHostState { + /// Synchronizes native selection handles with the current UTF-16 selection. + /// + /// Preserves active drag state when passing through zero-length coincidence points. + pub fn sync_selection_overlay_from_ime(&mut self) { + let (start, end) = self.selection_range(); + let utf16 = self.utf16_text.clone(); + self.sync_selection_overlay_for_snapshot(&utf16, start, end); + } + + /// Synchronizes native selection handles from an authoritative editor UTF-16 snapshot + /// without storing a duplicate host text copy (`H-S1`). + pub fn sync_selection_overlay_for_snapshot(&mut self, utf16: &[u16], start: usize, end: usize) { + if self.selection.active_drag != SelectionHandleKind::None { + return; + } + if start == end { + self.selection.clear(); + return; + } + let (sx, sy) = caret_position_for_offset(utf16, start, &self.text_layout); + let (ex, ey) = caret_position_for_offset(utf16, end, &self.text_layout); + let dir = detect_direction_at_offset(utf16, start, &self.text_layout); + self.selection + .update_selection(sx, sy, ex, ey, self.text_layout.line_height, dir, true); + } + + /// Starts dragging a selection handle and locks the opposite UTF-16 anchor so + /// slow drags across zero-length coincidence points smoothly invert selection. + pub fn begin_selection_handle_drag( + &mut self, + touch_x: f32, + touch_y: f32, + ) -> SelectionHandleKind { + let hit = self.selection.begin_drag(touch_x, touch_y); + let (sel_start, sel_end) = self.selection_range(); + self.selection_drag_initial_handle = hit; + self.selection_drag_anchor_utf16 = match hit { + SelectionHandleKind::Start => Some(sel_end), + SelectionHandleKind::End => Some(sel_start), + SelectionHandleKind::None => None, + }; + hit + } + + /// Continues dragging the active selection handle, using UTF-16 offset comparison + /// against the locked anchor as the single authority for handle ownership and + /// magnifier placement. + pub fn update_selection_handle_drag(&mut self, touch_x: f32, touch_y: f32) -> bool { + if let Some(anchor) = self.selection_drag_anchor_utf16 { + let Some((probe_x, probe_y)) = self.selection.probe_drag_position(touch_x, touch_y) + else { + return false; + }; + let offset = + closest_offset_for_position(&self.utf16_text, probe_x, probe_y, &self.text_layout); + let (lo, hi, active_handle) = if offset < anchor { + (offset, anchor, SelectionHandleKind::Start) + } else if offset > anchor { + (anchor, offset, SelectionHandleKind::End) + } else { + (anchor, anchor, self.selection_drag_initial_handle) + }; + self.selected_start = lo; + self.selected_len = hi - lo; + let (sx, sy) = caret_position_for_offset(&self.utf16_text, lo, &self.text_layout); + let (ex, ey) = caret_position_for_offset(&self.utf16_text, hi, &self.text_layout); + let dir = detect_direction_at_offset(&self.utf16_text, lo, &self.text_layout); + self.selection.apply_text_drag_endpoints( + sx, + sy, + ex, + ey, + self.text_layout.line_height, + dir, + active_handle, + ); + return true; + } + false + } + + /// Finishes dragging a selection handle and snaps handles to the final UTF-16 range. + pub fn end_selection_handle_drag(&mut self) -> bool { + self.selection_drag_anchor_utf16 = None; + self.selection_drag_initial_handle = SelectionHandleKind::None; + let has_menu = self.selection.end_drag().is_some(); + if self.selected_len == 0 && self.selection.has_selection { + // Keep handles only if text selection is non-empty when synced with text. + if !self.utf16_text.is_empty() { + self.selection.clear(); + return false; + } + } else if self.selected_len > 0 { + self.sync_selection_overlay_from_ime(); + } + has_menu + } + + /// Cancels an active handle drag (`ACTION_CANCEL`), hiding the magnifier. + pub fn cancel_selection_handle_drag(&mut self) { + self.selection_drag_anchor_utf16 = None; + self.selection_drag_initial_handle = SelectionHandleKind::None; + let _ = self.selection.end_drag(); + if !self.utf16_text.is_empty() { + self.sync_selection_overlay_from_ime(); + } + } + + pub fn text_string(&self) -> String { + String::from_utf16_lossy(&self.utf16_text) + } + + pub fn utf16_len(&self) -> usize { + self.utf16_text.len() + } + + pub fn utf16_unit(&self, index: usize) -> Option { + self.utf16_text.get(index).copied() + } + + pub fn selection_range(&self) -> (usize, usize) { + let len = self.utf16_text.len(); + let start = self.selected_start.min(len); + let end = start.saturating_add(self.selected_len).min(len); + (start, end) + } + + pub fn composing_range(&self) -> Option<(usize, usize)> { + let len = self.utf16_text.len(); + self.composing_start.map(|cs| { + let start = cs.min(len); + let end = start.saturating_add(self.composing_len).min(len); + (start, end) + }) + } + + /// Clears the active composing span without altering text or selection. + pub fn finish_composing_text(&mut self) { + self.composing_start = None; + self.composing_len = 0; + } + + /// Updates the UTF-16 selection range from `InputConnection.setSelection`. + pub fn set_selection(&mut self, start: usize, end: usize) { + let len = self.utf16_text.len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + self.selected_start = lo; + self.selected_len = hi - lo; + self.sync_selection_overlay_from_ime(); + } + + fn active_replace_span(&self) -> (usize, usize) { + let len = self.utf16_text.len(); + if let Some(comp_start) = self.composing_start { + let start = comp_start.min(len); + let end = start.saturating_add(self.composing_len).min(len); + (start, end) + } else { + let start = self.selected_start.min(len); + let end = start.saturating_add(self.selected_len).min(len); + (start, end) + } + } + + fn cursor_after_edit( + start: usize, + inserted_len: usize, + new_cursor_pos: i32, + max_len: usize, + ) -> usize { + if new_cursor_pos > 0 { + start + .saturating_add(inserted_len) + .saturating_add((new_cursor_pos - 1) as usize) + .min(max_len) + } else { + let back = new_cursor_pos.unsigned_abs() as usize; + start.saturating_sub(back).min(max_len) + } + } + + /// Commits UTF-16 text from `InputConnection.commitText`, replacing the + /// active composing span (or selection) and clearing composing state. + pub fn commit_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) { + let (start, end) = self.active_replace_span(); + self.utf16_text.splice(start..end, utf16.iter().copied()); + self.composing_start = None; + self.composing_len = 0; + self.selected_start = + Self::cursor_after_edit(start, utf16.len(), new_cursor_pos, self.utf16_text.len()); + self.selected_len = 0; + self.sync_selection_overlay_from_ime(); + } + + /// Updates the composing text from `InputConnection.setComposingText`. + pub fn set_composing_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) { + let (start, end) = self.active_replace_span(); + self.utf16_text.splice(start..end, utf16.iter().copied()); + if utf16.is_empty() { + self.composing_start = None; + self.composing_len = 0; + } else { + self.composing_start = Some(start); + self.composing_len = utf16.len(); + } + self.selected_start = + Self::cursor_after_edit(start, utf16.len(), new_cursor_pos, self.utf16_text.len()); + self.selected_len = 0; + self.sync_selection_overlay_from_ime(); + } + + /// Sets or clears the composing span without altering text or selection, + /// matching AOSP `BaseInputConnection.setComposingRegion`. + pub fn set_composing_region(&mut self, start: usize, end: usize) { + let len = self.utf16_text.len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + if lo == hi { + self.composing_start = None; + self.composing_len = 0; + } else { + self.composing_start = Some(lo); + self.composing_len = hi - lo; + } + } + + /// Replaces UTF-16 range `[start, end)` with `utf16`, clears composing + /// state, and collapses selection per AOSP `BaseInputConnection.replaceText`. + pub fn replace_text_utf16( + &mut self, + start: usize, + end: usize, + utf16: &[u16], + new_cursor_pos: i32, + ) { + let len = self.utf16_text.len(); + let a = start.min(len); + let b = end.min(len); + let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; + self.composing_start = None; + self.composing_len = 0; + self.utf16_text.splice(lo..hi, utf16.iter().copied()); + self.selected_start = + Self::cursor_after_edit(lo, utf16.len(), new_cursor_pos, self.utf16_text.len()); + self.selected_len = 0; + self.sync_selection_overlay_from_ime(); + } + + fn is_high_surrogate(u: u16) -> bool { + (0xD800..=0xDBFF).contains(&u) + } + + fn is_low_surrogate(u: u16) -> bool { + (0xDC00..=0xDFFF).contains(&u) + } + + fn find_index_backward_utf16(units: &[u16], from: usize, code_points: usize) -> Option { + let mut idx = from.min(units.len()); + let mut remaining = code_points; + let mut waiting_high = false; + while remaining > 0 { + if idx == 0 { + return if waiting_high { None } else { Some(0) }; + } + idx -= 1; + let u = units[idx]; + if waiting_high { + if Self::is_high_surrogate(u) { + waiting_high = false; + remaining -= 1; + } else { + return None; + } + } else if Self::is_low_surrogate(u) { + waiting_high = true; + } else if Self::is_high_surrogate(u) { + return None; + } else { + remaining -= 1; + } + } + Some(idx) + } + + fn find_index_forward_utf16(units: &[u16], from: usize, code_points: usize) -> Option { + let len = units.len(); + let mut idx = from.min(len); + let mut remaining = code_points; + let mut waiting_low = false; + while remaining > 0 { + if idx >= len { + return if waiting_low { None } else { Some(len) }; + } + let u = units[idx]; + idx += 1; + if waiting_low { + if Self::is_low_surrogate(u) { + waiting_low = false; + remaining -= 1; + } else { + return None; + } + } else if Self::is_high_surrogate(u) { + waiting_low = true; + } else if Self::is_low_surrogate(u) { + return None; + } else { + remaining -= 1; + } + } + Some(idx) + } + + /// Deletes `before_code_points` Unicode code points before `min(sel_start, comp_start)` + /// and `after_code_points` code points after `max(sel_end, comp_end)`, matching AOSP + /// `BaseInputConnection.deleteSurroundingTextInCodePoints`. Returns `false` with zero + /// state mutation if an unpaired surrogate is encountered in either scan range. + pub fn delete_surrounding_text_in_code_points( + &mut self, + before_code_points: usize, + after_code_points: usize, + ) -> bool { + let (mut a, mut b) = self.selection_range(); + if let Some((cs, ce)) = self.composing_range() { + a = a.min(cs); + b = b.max(ce); + } + let Some(start) = Self::find_index_backward_utf16(&self.utf16_text, a, before_code_points) + else { + return false; + }; + let Some(end) = Self::find_index_forward_utf16(&self.utf16_text, b, after_code_points) + else { + return false; + }; + if end > b { + self.utf16_text.drain(b..end); + } + if start < a { + let removed = a - start; + self.utf16_text.drain(start..a); + self.selected_start = self.selected_start.saturating_sub(removed); + if let Some(cs) = self.composing_start { + self.composing_start = Some(cs.saturating_sub(removed)); + } + } + true + } + + /// Deletes `before_len` UTF-16 units before `min(sel_start, comp_start)` and + /// `after_len` units after `max(sel_end, comp_end)` without splitting surrogate + /// pairs, matching AOSP `BaseInputConnection.deleteSurroundingText` ("Ignore + /// the composing text"). Full IME integration on physical Android devices is + /// verified in S2. + pub fn delete_surrounding_text(&mut self, before_len: usize, after_len: usize) { + let (mut a, mut b) = self.selection_range(); + if let Some((cs, ce)) = self.composing_range() { + a = a.min(cs); + b = b.max(ce); + } + + // 1. Delete `after_len` UTF-16 units after `b` (surrogate-pair safe). + // Because `b >= sel_end` and `b >= comp_end`, neither selection nor composing shifts. + if after_len > 0 && b < self.utf16_text.len() { + let mut del_end = b.saturating_add(after_len).min(self.utf16_text.len()); + if del_end > b + && del_end < self.utf16_text.len() + && (0xD800..=0xDBFF).contains(&self.utf16_text[del_end - 1]) + && (0xDC00..=0xDFFF).contains(&self.utf16_text[del_end]) + { + del_end += 1; + } + self.utf16_text.drain(b..del_end); + } + + // 2. Delete `before_len` UTF-16 units before `a` (surrogate-pair safe). + // Both `selected_start` and `composing_start` are >= `a`, so both shift left by `removed`. + if before_len > 0 && a > 0 { + let mut del_start = a.saturating_sub(before_len); + if del_start > 0 + && del_start < a + && (0xD800..=0xDBFF).contains(&self.utf16_text[del_start - 1]) + && (0xDC00..=0xDFFF).contains(&self.utf16_text[del_start]) + { + del_start -= 1; + } + let removed = a - del_start; + self.utf16_text.drain(del_start..a); + self.selected_start = self.selected_start.saturating_sub(removed); + if let Some(cs) = self.composing_start { + self.composing_start = Some(cs.saturating_sub(removed)); + } + } + } +} diff --git a/packages/frontend/hosts/android/src/jni_bridge.rs b/packages/frontend/hosts/android/src/jni_bridge.rs new file mode 100644 index 0000000000..a58ffdc71d --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_bridge.rs @@ -0,0 +1,783 @@ +#![allow(unsafe_code)] + +use core::ffi::c_void; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use crate::{ + AndroidHostState, BackGesturePhase, physical_insets_to_logical_dp, should_expose_autofill, +}; + +pub type JniEnvPtr = *mut c_void; +pub type JClass = *mut c_void; +pub type JObject = *mut c_void; +pub type JString = *mut c_void; +pub type JBoolean = u8; +pub type JInt = i32; +pub type JFloat = f32; +pub type JLong = i64; +pub type JSize = i32; +pub type JChar = u16; + +// Standard JNI `JNINativeInterface` function table indices (JNI 1.1+ spec). +const JNI_NEW_STRING_INDEX: usize = 163; +const JNI_GET_STRING_LENGTH_INDEX: usize = 164; +const JNI_GET_STRING_CHARS_INDEX: usize = 165; +const JNI_RELEASE_STRING_CHARS_INDEX: usize = 166; + +type NewStringFn = unsafe extern "C" fn(JniEnvPtr, *const JChar, JSize) -> JString; +type GetStringLengthFn = unsafe extern "C" fn(JniEnvPtr, JString) -> JSize; +type GetStringCharsFn = unsafe extern "C" fn(JniEnvPtr, JString, *mut JBoolean) -> *const JChar; +type ReleaseStringCharsFn = unsafe extern "C" fn(JniEnvPtr, JString, *const JChar); + +static HOST_REGISTRY: OnceLock>> = OnceLock::new(); +static NEXT_HOST_HANDLE: AtomicI64 = AtomicI64::new(1); + +#[cfg(target_os = "android")] +use crate::android_window; + +pub(crate) fn registry() -> &'static Mutex> { + HOST_REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new())) +} + +pub(crate) fn with_host_mut( + handle: JLong, + f: impl FnOnce(&mut AndroidHostState) -> R, +) -> Option { + if handle == 0 { + return None; + } + let mut map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + map.get_mut(&handle).map(f) +} + +pub(crate) fn with_host_ref(handle: JLong, f: impl FnOnce(&AndroidHostState) -> R) -> Option { + if handle == 0 { + return None; + } + let map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + map.get(&handle).map(f) +} + +fn normalize_jint_range(start: JInt, end: JInt) -> (usize, usize) { + let (lo, hi) = if start <= end { + (start, end) + } else { + (end, start) + }; + (lo.max(0) as usize, hi.max(0) as usize) +} + +/// Reads UTF-16 code units from a JNI `jstring` using `GetStringLength`, +/// `GetStringChars`, and `ReleaseStringChars`. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `jstr` must be null or a valid `jstring`. +pub(crate) unsafe fn read_jstring_utf16(env: JniEnvPtr, jstr: JString) -> Option> { + if env.is_null() || jstr.is_null() { + return None; + } + // SAFETY: `JNIEnv*` points to a pointer to the `JNINativeInterface` vtable. + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return None; + } + // SAFETY: Standard JNI vtable slots 164, 165, 166. + let get_len_ptr = unsafe { *vtable.add(JNI_GET_STRING_LENGTH_INDEX) }; + let get_chars_ptr = unsafe { *vtable.add(JNI_GET_STRING_CHARS_INDEX) }; + let rel_chars_ptr = unsafe { *vtable.add(JNI_RELEASE_STRING_CHARS_INDEX) }; + if get_len_ptr.is_null() || get_chars_ptr.is_null() || rel_chars_ptr.is_null() { + return None; + } + // SAFETY: Function pointer signatures match the JNI specification. + let get_len: GetStringLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let get_chars: GetStringCharsFn = unsafe { core::mem::transmute(get_chars_ptr) }; + let rel_chars: ReleaseStringCharsFn = unsafe { core::mem::transmute(rel_chars_ptr) }; + + let len = unsafe { get_len(env, jstr) }; + if len <= 0 { + return Some(Vec::new()); + } + let chars_ptr = unsafe { get_chars(env, jstr, core::ptr::null_mut()) }; + if chars_ptr.is_null() { + return None; + } + let out = unsafe { core::slice::from_raw_parts(chars_ptr, len as usize) }.to_vec(); + unsafe { rel_chars(env, jstr, chars_ptr) }; + Some(out) +} + +/// Reads a JNI `jstring` as a Rust `String` (lossy UTF-16 decode). +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `jstr` must be null or a valid `jstring`. +pub(crate) unsafe fn read_jstring_utf8(env: JniEnvPtr, jstr: JString) -> Option { + let units = unsafe { read_jstring_utf16(env, jstr) }?; + Some(String::from_utf16_lossy(&units)) +} + +/// Allocates a new JNI `jstring` from a Rust `&str` using `NewString` (vtable slot 163). +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +pub(crate) unsafe fn new_jstring(env: JniEnvPtr, text: &str) -> JString { + if env.is_null() { + return core::ptr::null_mut(); + } + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return core::ptr::null_mut(); + } + let new_str_ptr = unsafe { *vtable.add(JNI_NEW_STRING_INDEX) }; + if new_str_ptr.is_null() { + return core::ptr::null_mut(); + } + let new_str: NewStringFn = unsafe { core::mem::transmute(new_str_ptr) }; + let units: Vec = text.encode_utf16().collect(); + let len = units.len().min(i32::MAX as usize) as JSize; + unsafe { new_str(env, units.as_ptr(), len) } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShouldExposeAutofill( + _env: JniEnvPtr, + _class: JClass, + sdk_int: JInt, +) -> JBoolean { + let sdk = u32::try_from(sdk_int).unwrap_or(0); + u8::from(should_expose_autofill(sdk)) +} + +/// Register a host whose root view is `runtime`. +pub(crate) fn create_host( + env: JniEnvPtr, + class: JClass, + runtime: Option, +) -> JLong { + let mut map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + loop { + let candidate = NEXT_HOST_HANDLE.fetch_add(1, Ordering::Relaxed); + if candidate != 0 && !map.contains_key(&candidate) { + map.insert(candidate, AndroidHostState::new()); + drop(map); + crate::jni_editor::attach_for_host(env, class, candidate, runtime); + return candidate; + } + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDestroyHost( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + if handle == 0 { + return; + } + crate::jni_editor::detach_for_host(env, handle); + #[cfg(target_os = "android")] + android_window::release(handle); + let mut map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + if let Some(mut host) = map.remove(&handle) { + host.sqlite.close_all(); + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetHasBackDestination( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + has_destination: JBoolean, +) { + let _ = with_host_mut(handle, |host| { + host.set_has_back_destination(has_destination != 0); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceCreated( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + surface: JObject, +) { + #[cfg(target_os = "android")] + let (bound, vk_ok, gles3_ok) = { + let b = unsafe { android_window::attach(env, handle, surface) }; + let (vk, gl) = android_window::probe_backends(); + (b, vk, gl) + }; + #[cfg(not(target_os = "android"))] + let (bound, vk_ok, gles3_ok) = { + let _ = env; + (!surface.is_null(), false, true) + }; + let _ = with_host_mut(handle, |host| { + if host.surface.backend == crate::AndroidRenderBackend::Unselected { + host.surface.select_backend(vk_ok, gles3_ok); + } + host.surface.on_created(bound); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceChanged( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + format: JInt, + width_px: JInt, + height_px: JInt, +) { + #[cfg(target_os = "android")] + android_window::set_geometry(handle, width_px, height_px); + let mut density = 1.0f32; + let w = u32::try_from(width_px).unwrap_or(0); + let h = u32::try_from(height_px).unwrap_or(0); + let _ = with_host_mut(handle, |host| { + host.surface.on_changed(format, w, h); + density = host.surface.density; + }); + if w > 0 && h > 0 { + #[cfg(target_os = "android")] + let native_win = android_window::native_window_ptr(handle); + let _ = crate::editor_runtime::with_editor_mut(handle, |ed| { + #[cfg(target_os = "android")] + if let Some(ptr) = native_win { + let _ = ed.attach_surface(ptr, w, h, density); + return; + } + ed.resize_px(w, h, density); + }); + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceDestroyed( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + // Drop `WgpuRenderer` and its `wgpu::Surface` strictly BEFORE `ANativeWindow_release`. + #[cfg(target_os = "android")] + { + let _ = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.detach_surface(); + }); + android_window::release(handle); + } + let _ = with_host_mut(handle, |host| { + host.surface.on_destroyed(); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeRequestFrame( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.mark_dirty(); + }); + let _ = with_host_mut(handle, |host| { + host.surface.request_frame(); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceGeneration( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_host_ref(handle, |host| host.surface.generation as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsSurfaceReady( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_ref(handle, |host| u8::from(host.surface.is_ready())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeHasPendingFrame( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + let surface_pending = with_host_ref(handle, |host| host.surface.pending_frame).unwrap_or(false); + let editor_pending = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.is_dirty() || ed.has_pending_main_tasks() + }) + .unwrap_or(false); + u8::from(surface_pending || editor_pending) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetFrameCount( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_host_ref(handle, |host| host.surface.frame_count as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetRenderBackend( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| host.surface.backend as JInt).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + safe_top_px: JInt, + safe_right_px: JInt, + safe_bottom_px: JInt, + safe_left_px: JInt, + ime_bottom_px: JInt, + density: JFloat, +) { + let mut logical_insets = crate::LogicalWindowInsets::default(); + let _ = with_host_mut(handle, |host| { + host.surface.set_density(density); + host.insets = physical_insets_to_logical_dp( + safe_top_px, + safe_right_px, + safe_bottom_px, + safe_left_px, + ime_bottom_px, + density, + ); + logical_insets = host.insets; + if host.surface.width_px > 0 && host.surface.height_px > 0 { + host.selection.set_viewport( + host.surface.width_px as f32, + host.surface.height_px as f32, + host.surface.density, + ); + } + }); + let _ = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.set_insets(logical_insets); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + frame_time_nanos: JLong, +) -> JInt { + let Some((argb, backend)) = with_host_ref(handle, |host| { + host.surface + .begin_frame() + .map(|c| (c, host.surface.backend)) + }) + .flatten() else { + return 0; + }; + let (has_gpu_renderer, rendered_gpu, still_dirty) = + crate::editor_runtime::with_editor_mut(handle, |ed| { + let has_gpu = ed.has_gpu_renderer(); + let rendered = ed.render_frame(); + let more = ed.is_dirty() || ed.has_pending_main_tasks(); + (has_gpu, rendered, more) + }) + .unwrap_or((false, false, false)); + + #[cfg(target_os = "android")] + let present_result = if has_gpu_renderer { + // `WgpuRenderer::draw(scene)` already presented to `ANativeWindow` when `rendered_gpu` + // is true; when idle (`!rendered_gpu`), skip GPU presentation completely for 0-fps idle. + let _ = (backend, rendered_gpu); + Ok(()) + } else { + android_window::present_frame(handle, backend, argb) + }; + #[cfg(not(target_os = "android"))] + let present_result: Result<(), crate::SurfacePresentError> = { + let _ = (backend, has_gpu_renderer, rendered_gpu); + Ok(()) + }; + + let presented = with_host_mut(handle, |host| { + let ok = host + .surface + .complete_frame(frame_time_nanos, present_result); + if still_dirty { + host.surface.request_frame(); + } + ok + }) + .unwrap_or(false); + if presented { argb as JInt } else { 0 } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnBackGesturePhase( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + phase_code: JInt, + progress: JFloat, +) -> JBoolean { + let Some(phase) = BackGesturePhase::from_code(phase_code) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.handle_back_phase(phase, progress)) + }) + .unwrap_or(0) +} + +pub(crate) fn sync_selection_overlay_from_editor(handle: JLong) { + if let Some((utf16, (start, end))) = crate::editor_runtime::with_editor_mut(handle, |ed| { + let range = ed.selection_range(); + let utf16 = if range.0 == range.1 { + Vec::new() + } else { + ed.utf16_text() + }; + (utf16, range) + }) { + let _ = with_host_mut(handle, |host| { + host.sync_selection_overlay_for_snapshot(&utf16, start, end); + }); + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnCommitText( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + text: JString, + new_cursor_position: JInt, +) { + let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else { + return; + }; + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.commit_text_utf16(&utf16, new_cursor_position); + }) + .is_some() + { + sync_selection_overlay_from_editor(handle); + return; + } + let _ = with_host_mut(handle, |host| { + host.commit_text_utf16(&utf16, new_cursor_position); + }); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetComposingText( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + text: JString, + new_cursor_position: JInt, +) { + let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else { + return; + }; + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.set_composing_text_utf16(&utf16, new_cursor_position); + }) + .is_some() + { + sync_selection_overlay_from_editor(handle); + return; + } + let _ = with_host_mut(handle, |host| { + host.set_composing_text_utf16(&utf16, new_cursor_position); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetComposingRegion( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start: JInt, + end: JInt, +) { + let (a, b) = normalize_jint_range(start, end); + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.set_composing_region(a, b); + }) + .is_some() + { + return; + } + let _ = with_host_mut(handle, |host| { + host.set_composing_region(a, b); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnFinishComposingText( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.finish_composing_text(); + }) + .is_some() + { + return; + } + let _ = with_host_mut(handle, |host| { + host.finish_composing_text(); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetSelection( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start: JInt, + end: JInt, +) { + let (a, b) = normalize_jint_range(start, end); + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.set_selection(a, b); + }) + .is_some() + { + sync_selection_overlay_from_editor(handle); + return; + } + let _ = with_host_mut(handle, |host| { + host.set_selection(a, b); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnDeleteSurroundingText( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + before_len: JInt, + after_len: JInt, +) { + if before_len < 0 || after_len < 0 { + return; + } + let before = before_len as usize; + let after = after_len as usize; + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.delete_surrounding_text(before, after); + }) + .is_some() + { + sync_selection_overlay_from_editor(handle); + return; + } + let _ = with_host_mut(handle, |host| { + host.delete_surrounding_text(before, after); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnDeleteSurroundingTextInCodePoints( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + before_len: JInt, + after_len: JInt, +) -> JBoolean { + if before_len < 0 || after_len < 0 { + return 0; + } + let before = before_len as usize; + let after = after_len as usize; + if let Some(ok) = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.delete_surrounding_text_in_code_points(before, after) + }) { + sync_selection_overlay_from_editor(handle); + return u8::from(ok); + } + with_host_mut(handle, |host| { + u8::from(host.delete_surrounding_text_in_code_points(before, after)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnReplaceText( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + start: JInt, + end: JInt, + text: JString, + new_cursor_position: JInt, +) -> JBoolean { + if start < 0 || end < 0 { + return 0; + } + let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else { + return 0; + }; + if crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.replace_text_utf16(start as usize, end as usize, &utf16, new_cursor_position); + }) + .is_some() + { + sync_selection_overlay_from_editor(handle); + return 1; + } + with_host_mut(handle, |host| { + host.replace_text_utf16(start as usize, end as usize, &utf16, new_cursor_position); + 1 + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Length( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + if let Some(len) = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.utf16_len().min(i32::MAX as usize) as JInt + }) { + return len; + } + with_host_ref(handle, |host| { + host.utf16_len().min(i32::MAX as usize) as JInt + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Unit( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + index: JInt, +) -> JInt { + let Ok(idx) = usize::try_from(index) else { + return 0; + }; + if let Some(unit) = crate::editor_runtime::with_editor_mut(handle, |ed| { + i32::from(ed.utf16_unit(idx).unwrap_or(0)) + }) { + return unit; + } + with_host_ref(handle, |host| i32::from(host.utf16_unit(idx).unwrap_or(0))).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionStart( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + if let Some(start) = + crate::editor_runtime::with_editor_mut(handle, |ed| ed.selection_range().0 as JInt) + { + return start; + } + with_host_ref(handle, |host| host.selection_range().0 as JInt).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionEnd( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + if let Some(end) = + crate::editor_runtime::with_editor_mut(handle, |ed| ed.selection_range().1 as JInt) + { + return end; + } + with_host_ref(handle, |host| host.selection_range().1 as JInt).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetComposingStart( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + if let Some(start) = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.composing_range().map_or(-1, |(s, _)| s as JInt) + }) { + return start; + } + with_host_ref(handle, |host| { + host.composing_range() + .map_or(-1, |(start, _)| start as JInt) + }) + .unwrap_or(-1) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetComposingEnd( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + if let Some(end) = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.composing_range().map_or(-1, |(_, e)| e as JInt) + }) { + return end; + } + with_host_ref(handle, |host| { + host.composing_range().map_or(-1, |(_, end)| end as JInt) + }) + .unwrap_or(-1) +} + +#[cfg(test)] +pub(crate) fn insert_test_host(handle: JLong, state: AndroidHostState) { + let mut map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + map.insert(handle, state); +} + +#[cfg(test)] +pub(crate) fn snapshot_text(handle: JLong) -> Option { + if let Some(units) = crate::editor_runtime::with_editor_mut(handle, |ed| ed.utf16_text()) { + return Some(String::from_utf16_lossy(&units)); + } + let map = registry() + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + map.get(&handle).map(AndroidHostState::text_string) +} diff --git a/packages/frontend/hosts/android/src/jni_editor.rs b/packages/frontend/hosts/android/src/jni_editor.rs new file mode 100644 index 0000000000..89bacb508e --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_editor.rs @@ -0,0 +1,801 @@ +#![allow(unsafe_code)] + +//! Hand-written `extern "C"` JNI exports for the live pure-Rust BlockSuite GPU +//! editor mounted inside `affine-android-host`. + +use playground::PlaygroundMode; + +use crate::{ + editor_runtime::{self, with_editor_mut}, + jni_bridge::{ + JBoolean, JClass, JFloat, JInt, JLong, JObject, JString, JniEnvPtr, new_jstring, + read_jstring_utf8, with_host_mut, with_host_ref, + }, + jni_interaction::{JFloatArray, fill_jfloat_array}, +}; + +/// Pops the next validated `http(s)://` URL queued by the editor, or returns null. +/// +/// # Safety +/// `env` must be a valid JNIEnv pointer passed by the ART runtime. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeTakePendingOpenUrl( + env: JniEnvPtr, + _class: JClass, + _handle: JLong, +) -> JString { + match crate::editor_platform::take_pending_open_url_global() { + Some(url) => unsafe { new_jstring(env, &url) }, + None => std::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeLoadShowcaseDocument( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.load_showcase_document()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeResetEmptyDocument( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.reset_empty_document()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetFormFactor( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + smallest_width_dp: JInt, +) { + let _ = with_editor_mut(handle, |ed| { + ed.set_form_factor_from_smallest_width_dp(smallest_width_dp); + }); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsEdgelessReadonly( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.edgeless_readonly()).unwrap_or(true)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsDatabaseReadonly( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.database_readonly()).unwrap_or(true)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsPageReadonly( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.is_page_readonly()).unwrap_or(true)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeWantsCodeInput( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.wants_code_input()).unwrap_or(false)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetEditorMode( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + mode_code: JInt, +) { + let mode = if mode_code == 1 { + PlaygroundMode::Edgeless + } else { + PlaygroundMode::Page + }; + let _ = with_editor_mut(handle, |ed| ed.set_mode(mode)); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnTouchEvent( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + pointer_id: JLong, + phase: JInt, + x_dp: JFloat, + y_dp: JFloat, +) { + let _ = with_editor_mut(handle, |ed| { + ed.dispatch_touch(pointer_id as u64, phase.clamp(0, 3) as u8, x_dp, y_dp); + }); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnScrollWheel( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + x_dp: JFloat, + y_dp: JFloat, + delta_x: JFloat, + delta_y: JFloat, +) { + let _ = with_editor_mut(handle, |ed| { + ed.dispatch_scroll_wheel(x_dp, y_dp, delta_x, delta_y); + }); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeHandleBack( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + let handled = with_editor_mut(handle, |ed| ed.handle_back()).unwrap_or(false); + if handled { + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + } + u8::from(handled) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnKeyEvent( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + key_code: JInt, + shift: JBoolean, + ctrl: JBoolean, + alt: JBoolean, +) -> JBoolean { + let handled = with_editor_mut(handle, |ed| { + ed.dispatch_key_code(key_code, shift != 0, ctrl != 0, alt != 0) + }) + .unwrap_or(false); + if handled { + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + } + u8::from(handled) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetTextInputChangeSeq( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_editor_mut(handle, |ed| ed.text_input_change_seq() as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetFocusedBlockHash( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_editor_mut(handle, |ed| ed.focused_block_hash() as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeWantsSoftwareKeyboard( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.wants_software_keyboard()).unwrap_or(false)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeTakeSoftwareKeyboardRequest( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.take_software_keyboard_request()).unwrap_or(false)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpX( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_editor_mut(handle, |ed| ed.caret_rect_dp().map(|r| r[0]).unwrap_or(0.0)).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpY( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_editor_mut(handle, |ed| ed.caret_rect_dp().map(|r| r[1]).unwrap_or(0.0)).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpHeight( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_editor_mut(handle, |ed| { + ed.caret_rect_dp().map(|r| r[3]).unwrap_or(20.0) + }) + .unwrap_or(20.0) +} + +/// Bulk UTF-16 read of the focused editor block in a single JNI call (`H-S1`). +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Text( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let text = if let Some(units) = with_editor_mut(handle, |ed| ed.utf16_text()) { + String::from_utf16_lossy(&units) + } else { + with_host_ref(handle, |host| host.text_string()).unwrap_or_default() + }; + unsafe { new_jstring(env, &text) } +} + +/// Returns `true` when the Android editor dispatcher still has pending delayed timers. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeHasPendingTimer( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + let pending = with_editor_mut(handle, |ed| ed.drain_tasks().is_some()).unwrap_or(false); + u8::from(pending) +} + +/// Drains due timers on the UI thread, marks the surface dirty if any due timer invalidated +/// the view, and returns milliseconds until the next pending timer (`-1` when none). +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeNextTimerDelayMs( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + let (next_ms, dirty) = with_editor_mut(handle, |ed| { + let next = ed.drain_tasks(); + let dirty = ed.is_dirty() || ed.has_pending_main_tasks(); + let ms = if ed.has_pending_main_tasks() { + 0 + } else { + next.map(|d| d.as_millis().min(i64::MAX as u128) as i64) + .unwrap_or(-1) + }; + (ms, dirty) + }) + .unwrap_or((-1, false)); + if dirty { + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + } + next_ms +} + +/// Returns `true` when the live editor view is currently in `PlaygroundTheme::Dark`. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsDarkTheme( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + u8::from(with_editor_mut(handle, |ed| ed.is_dark_theme()).unwrap_or(false)) +} + +/// Fills a 24-float JNI buffer with document-level selection geometry (dp), visibility flags, +/// authoritative `SelectionActionMask`, and motion suppression flag. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `out_buffer` must be a `float[>=24]`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFillDocumentSelectionGeometry( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + out_buffer: JFloatArray, +) -> JBoolean { + let Some(packed) = with_editor_mut(handle, |ed| ed.pack_document_selection_floats()) else { + return 0; + }; + u8::from(unsafe { fill_jfloat_array(env, out_buffer, &packed) }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionMenuRequestSeq( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_editor_mut(handle, |ed| ed.selection_menu_request_seq() as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDocSelectionBeginDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + handle_kind: JInt, +) -> JBoolean { + u8::from( + with_editor_mut(handle, |ed| { + ed.begin_document_selection_drag(handle_kind.clamp(0, 2) as u8) + }) + .unwrap_or(false), + ) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDocSelectionUpdateDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + x_dp: JFloat, + y_dp: JFloat, +) -> JBoolean { + let ok = with_editor_mut(handle, |ed| ed.update_document_selection_drag(x_dp, y_dp)) + .unwrap_or(false); + if ok { + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + } + u8::from(ok) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDocSelectionEndDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.end_document_selection_drag()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDocSelectionCancelDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.cancel_document_selection_drag()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionActionCopy( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.selection_copy()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionActionCut( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.selection_cut()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string arguments may be null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionActionPaste( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + plain: JString, + html: JString, + markdown: JString, + snapshot: JString, +) { + let plain_s = unsafe { read_jstring_utf8(env, plain) }; + let html_s = unsafe { read_jstring_utf8(env, html) }; + let md_s = unsafe { read_jstring_utf8(env, markdown) }; + let snap_s = unsafe { read_jstring_utf8(env, snapshot) }; + let _ = with_editor_mut(handle, |ed| { + ed.selection_paste(plain_s, html_s, md_s, snap_s) + }); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionActionSelectAll( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_editor_mut(handle, |ed| ed.selection_select_all()); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +/// Returns and clears any pending multi-MIME JSON clipboard payload written by the editor. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeTakePendingClipboardJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let Some(json) = with_editor_mut(handle, |ed| ed.take_pending_clipboard_json()).flatten() + else { + return core::ptr::null_mut(); + }; + unsafe { new_jstring(env, &json) } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetPageReadonly( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + readonly: JBoolean, +) { + let _ = with_editor_mut(handle, |ed| ed.set_page_readonly(readonly != 0)); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); +} + +// Standard JNI vtable slots used for cross-thread Looper wakeup (`NativeBridge.onNativeWakeup`). +const JNI_FIND_CLASS_INDEX: usize = 6; +const JNI_EXCEPTION_CLEAR_INDEX: usize = 17; +const JNI_NEW_GLOBAL_REF_INDEX: usize = 21; +const JNI_GET_STATIC_METHOD_ID_INDEX: usize = 113; +const JNI_CALL_STATIC_VOID_METHOD_A_INDEX: usize = 143; +const JNI_GET_JAVA_VM_INDEX: usize = 219; +const JNI_INVOKE_ATTACH_INDEX: usize = 4; +const JNI_INVOKE_DETACH_INDEX: usize = 5; +const JNI_INVOKE_GET_ENV_INDEX: usize = 6; +const JNI_VERSION_1_6: JInt = 0x0001_0006; +const JNI_OK: JInt = 0; +const JNI_EDETACHED: JInt = -2; + +type FindClassFn = unsafe extern "C" fn(JniEnvPtr, *const i8) -> JClass; +type ExceptionClearFn = unsafe extern "C" fn(JniEnvPtr); +type NewGlobalRefFn = unsafe extern "C" fn(JniEnvPtr, JObject) -> JObject; +type GetStaticMethodIdFn = + unsafe extern "C" fn(JniEnvPtr, JClass, *const i8, *const i8) -> *mut core::ffi::c_void; +type CallStaticVoidMethodAFn = + unsafe extern "C" fn(JniEnvPtr, JClass, *mut core::ffi::c_void, *const i64); +type GetJavaVmFn = unsafe extern "C" fn(JniEnvPtr, *mut *mut core::ffi::c_void) -> JInt; +type AttachThreadFn = + unsafe extern "C" fn(*mut core::ffi::c_void, *mut JniEnvPtr, *mut core::ffi::c_void) -> JInt; +type DetachThreadFn = unsafe extern "C" fn(*mut core::ffi::c_void) -> JInt; +type GetEnvFn = unsafe extern "C" fn(*mut core::ffi::c_void, *mut JniEnvPtr, JInt) -> JInt; + +/// Process-lifetime cached JNI references for `NativeBridge.onNativeWakeup(long)`. +/// `NativeBridge` lives for the entire process lifetime and is never unloaded, so the +/// single `jclass` global reference is cached once and never deleted on host detach. +#[derive(Clone, Copy)] +struct JniWakeupBridge { + vm: usize, + bridge_class_global: usize, + method_id: usize, +} + +static WAKEUP_BRIDGE: std::sync::OnceLock = std::sync::OnceLock::new(); +static WAKEUP_HANDLES: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + +fn wakeup_handles() -> &'static std::sync::RwLock> { + WAKEUP_HANDLES.get_or_init(|| std::sync::RwLock::new(std::collections::BTreeSet::new())) +} + +unsafe fn build_jni_wakeup(env: JniEnvPtr, class: JClass) -> Option { + if env.is_null() || class.is_null() { + return None; + } + let vtable = unsafe { *(env as *const *const *const core::ffi::c_void) }; + if vtable.is_null() { + return None; + } + let find_class: FindClassFn = + unsafe { core::mem::transmute(*vtable.add(JNI_FIND_CLASS_INDEX)) }; + let get_vm: GetJavaVmFn = unsafe { core::mem::transmute(*vtable.add(JNI_GET_JAVA_VM_INDEX)) }; + let new_gref: NewGlobalRefFn = + unsafe { core::mem::transmute(*vtable.add(JNI_NEW_GLOBAL_REF_INDEX)) }; + let get_mid: GetStaticMethodIdFn = + unsafe { core::mem::transmute(*vtable.add(JNI_GET_STATIC_METHOD_ID_INDEX)) }; + let exc_clear: ExceptionClearFn = + unsafe { core::mem::transmute(*vtable.add(JNI_EXCEPTION_CLEAR_INDEX)) }; + let mut vm: *mut core::ffi::c_void = core::ptr::null_mut(); + if unsafe { get_vm(env, &mut vm) } != JNI_OK || vm.is_null() { + return None; + } + // Kotlin `object NativeBridge` passes `NativeBridge.INSTANCE` (`jobject`, not `jclass`) as the + // 2nd JNI argument to non-`@JvmStatic` external methods; look up the true `jclass` via FindClass. + let bridge_class = + unsafe { find_class(env, c"app/affine/pro/host/NativeBridge".as_ptr().cast()) }; + if bridge_class.is_null() { + unsafe { exc_clear(env) }; + return None; + } + let mid = unsafe { + get_mid( + env, + bridge_class, + c"onNativeWakeup".as_ptr().cast(), + c"(J)V".as_ptr().cast(), + ) + }; + if mid.is_null() { + unsafe { exc_clear(env) }; + return None; + } + let gref = unsafe { new_gref(env, bridge_class) }; + if gref.is_null() { + unsafe { exc_clear(env) }; + return None; + } + Some(JniWakeupBridge { + vm: vm as usize, + bridge_class_global: gref as usize, + method_id: mid as usize, + }) +} + +fn invoke_jni_wakeup(handle: JLong) { + let Some(bridge) = WAKEUP_BRIDGE.get().copied() else { + return; + }; + let handles = wakeup_handles().read().unwrap_or_else(|e| e.into_inner()); + if !handles.contains(&handle) { + return; + } + let vm = bridge.vm as *mut core::ffi::c_void; + let class_addr = bridge.bridge_class_global; + let mid_addr = bridge.method_id; + if vm.is_null() || class_addr == 0 || mid_addr == 0 { + return; + } + unsafe { + let ivtable = *(vm as *const *const *const core::ffi::c_void); + if ivtable.is_null() { + return; + } + let get_env: GetEnvFn = core::mem::transmute(*ivtable.add(JNI_INVOKE_GET_ENV_INDEX)); + let attach: AttachThreadFn = core::mem::transmute(*ivtable.add(JNI_INVOKE_ATTACH_INDEX)); + let detach: DetachThreadFn = core::mem::transmute(*ivtable.add(JNI_INVOKE_DETACH_INDEX)); + let mut env: JniEnvPtr = core::ptr::null_mut(); + let mut attached = false; + let status = get_env(vm, &mut env, JNI_VERSION_1_6); + if status == JNI_EDETACHED { + if attach(vm, &mut env, core::ptr::null_mut()) != JNI_OK || env.is_null() { + return; + } + attached = true; + } else if status != JNI_OK || env.is_null() { + return; + } + let vtable = *(env as *const *const *const core::ffi::c_void); + if !vtable.is_null() { + let call_void: CallStaticVoidMethodAFn = + core::mem::transmute(*vtable.add(JNI_CALL_STATIC_VOID_METHOD_A_INDEX)); + let exc_clear: ExceptionClearFn = + core::mem::transmute(*vtable.add(JNI_EXCEPTION_CLEAR_INDEX)); + let args: [i64; 1] = [handle]; + call_void( + env, + class_addr as JClass, + mid_addr as *mut core::ffi::c_void, + args.as_ptr(), + ); + exc_clear(env); + } + drop(handles); + if attached { + let _ = detach(vm); + } + } +} + +pub(crate) fn attach_for_host( + env: JniEnvPtr, + class: JClass, + handle: JLong, + runtime: Option, +) { + editor_runtime::attach_editor(handle, runtime); + let ready = WAKEUP_BRIDGE.get().is_some() + || unsafe { build_jni_wakeup(env, class) }.is_some_and(|bridge| { + WAKEUP_BRIDGE.set(bridge).is_ok() || WAKEUP_BRIDGE.get().is_some() + }); + if ready { + wakeup_handles() + .write() + .unwrap_or_else(|e| e.into_inner()) + .insert(handle); + let _ = with_editor_mut(handle, |ed| { + ed.set_waker(Some(std::sync::Arc::new(move || { + invoke_jni_wakeup(handle); + }))); + }); + } +} + +pub(crate) fn detach_for_host(_env: JniEnvPtr, handle: JLong) { + let _ = with_editor_mut(handle, |ed| { + ed.set_waker(None); + }); + wakeup_handles() + .write() + .unwrap_or_else(|e| e.into_inner()) + .remove(&handle); + editor_runtime::detach_editor(handle); +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::Duration; + + use super::*; + + #[test] + fn detach_waits_for_inflight_wakeup_read_guard_and_disarms_handle() { + let handle: JLong = 9_900_001; + wakeup_handles() + .write() + .unwrap_or_else(|e| e.into_inner()) + .insert(handle); + + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let inflight_alive = Arc::new(AtomicBool::new(false)); + let inflight_alive_bg = Arc::clone(&inflight_alive); + + let bg = std::thread::spawn(move || { + let guards = wakeup_handles().read().unwrap_or_else(|e| e.into_inner()); + assert!(guards.contains(&handle)); + inflight_alive_bg.store(true, Ordering::SeqCst); + entered_tx.send(()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + inflight_alive_bg.store(false, Ordering::SeqCst); + drop(guards); + }); + + entered_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let detached_observed_inflight = Arc::new(AtomicBool::new(false)); + let detached_flag = Arc::clone(&detached_observed_inflight); + let inflight_check = Arc::clone(&inflight_alive); + let detacher = std::thread::spawn(move || { + detach_for_host(core::ptr::null_mut(), handle); + detached_flag.store(inflight_check.load(Ordering::SeqCst), Ordering::SeqCst); + }); + + std::thread::yield_now(); + release_tx.send(()).unwrap(); + bg.join().unwrap(); + detacher.join().unwrap(); + + assert!( + !detached_observed_inflight.load(Ordering::SeqCst), + "detach_for_host must block on write() until all in-flight wakeup readers exit" + ); + assert!( + !wakeup_handles() + .read() + .unwrap_or_else(|e| e.into_inner()) + .contains(&handle), + "detached handle must be removed so subsequent wakeups become no-ops" + ); + invoke_jni_wakeup(handle); + } + + #[test] + fn android_editor_runtime_wakes_and_renders_after_async_code_preview() { + use std::sync::{Condvar, Mutex}; + + use playground::{FormFactor, overlays::OverlayEvent}; + + let mut ed = editor_runtime::AndroidEditorRuntime::new( + 412.0, + 915.0, + 2.625, + FormFactor::Phone, + false, + ) + .expect("android editor runtime"); + let wake_pair = Arc::new((Mutex::new(0usize), Condvar::new())); + let wake_bg = Arc::clone(&wake_pair); + ed.set_waker(Some(Arc::new(move || { + let (lock, cv) = &*wake_bg; + *lock.lock().unwrap() += 1; + cv.notify_all(); + }))); + + // Convert the empty paragraph into a fenced code block via Markdown ` ``` ` + Space, + // switch its language to `mermaid`, clear caret focus so the host is completely idle, + // and toggle Preview. + let fence: Vec = "``` ".encode_utf16().collect(); + ed.commit_text_utf16(&fence, 1); + let src: Vec = "flowchart LR\n AndroidHostIdle --> AndroidHostWoken" + .encode_utf16() + .collect(); + ed.commit_text_utf16(&src, 1); + let view = ed.view(); + ed.app.update(|cx| { + view.update(cx, |v, win, cx| { + let code_id = v + .document_selection() + .expect("focused code block") + .anchor + .block_id + .clone(); + v.dispatch_overlay( + OverlayEvent::SetCodeLanguage { + block_id: code_id.clone(), + language: "mermaid".into(), + }, + win, + cx, + ); + v.dispatch_overlay(OverlayEvent::SetSelection(None), win, cx); + v.dispatch_overlay(OverlayEvent::ToggleCodePreview(code_id), win, cx); + }) + .unwrap(); + }); + ed.mark_dirty(); + // Render initial Pending frame so the runtime goes idle (`is_dirty == false`). + assert!(ed.render_frame()); + assert!(!ed.is_dirty()); + *wake_pair.0.lock().unwrap() = 0; + + // Wait on real background preview worker wakeup (strictly NO manual flush or mark_dirty). + { + let (lock, cv) = &*wake_pair; + let mut count = lock.lock().unwrap(); + while *count == 0 { + let (next, timeout) = cv.wait_timeout(count, Duration::from_secs(10)).unwrap(); + count = next; + assert!( + !timeout.timed_out(), + "AndroidEditorRuntime must receive waker callback when async Mermaid preview finishes" + ); + } + } + ed.set_waker(None); + assert!( + ed.has_pending_main_tasks() || ed.is_dirty(), + "idle Android host must report pending work after preview wakeup" + ); + assert!( + ed.render_frame(), + "Android render_frame() must drain wakeup task and render Ready preview" + ); + } +} diff --git a/packages/frontend/hosts/android/src/jni_interaction.rs b/packages/frontend/hosts/android/src/jni_interaction.rs new file mode 100644 index 0000000000..694cdc50d8 --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_interaction.rs @@ -0,0 +1,950 @@ +#![allow(unsafe_code)] + +//! Thin hand-written JNI exports for Android selection overlays, surface +//! recreation/fallback recovery, API 26+ autofill, predictive back navigation, +//! and zero-heap streaming `PdfRenderer` pixel conversion with per-call +//! `ExceptionCheck`. + +use core::ffi::c_void; + +use crate::autofill::{AutofillFieldKind, AutofillRect}; +use crate::back_dispatch_mode; +use crate::jni_bridge::{ + JBoolean, JClass, JFloat, JInt, JLong, JObject, JSize, JString, JniEnvPtr, new_jstring, + read_jstring_utf8, with_host_mut, with_host_ref, +}; +use crate::pdf::{ + convert_argb8888_i32_chunk_to_rgba8_slice, pdf_page_cache_key, validate_pdf_dimensions, + validate_pdf_page_request, +}; +use crate::selection::{SelectionHandleKind, TextDirection}; + +pub type JIntArray = JObject; +pub type JByteArray = JObject; +pub type JFloatArray = JObject; + +// Standard JNI 1.2+ `JNINativeInterface` vtable indices. +const JNI_GET_ARRAY_LENGTH_INDEX: usize = 171; +const JNI_NEW_BYTE_ARRAY_INDEX: usize = 176; +const JNI_NEW_FLOAT_ARRAY_INDEX: usize = 181; +const JNI_GET_INT_ARRAY_REGION_INDEX: usize = 203; +const JNI_SET_BYTE_ARRAY_REGION_INDEX: usize = 208; +const JNI_SET_FLOAT_ARRAY_REGION_INDEX: usize = 213; +const JNI_EXCEPTION_CHECK_INDEX: usize = 228; +const PDF_STREAM_CHUNK_PIXELS: usize = 4096; + +type GetArrayLengthFn = unsafe extern "C" fn(JniEnvPtr, JObject) -> JSize; +type NewByteArrayFn = unsafe extern "C" fn(JniEnvPtr, JSize) -> JByteArray; +type NewFloatArrayFn = unsafe extern "C" fn(JniEnvPtr, JSize) -> JFloatArray; +type GetIntArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JIntArray, JSize, JSize, *mut JInt); +type SetByteArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JByteArray, JSize, JSize, *const i8); +type SetFloatArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JFloatArray, JSize, JSize, *const f32); +type ExceptionCheckFn = unsafe extern "C" fn(JniEnvPtr) -> JBoolean; + +unsafe fn new_jfloat_array(env: JniEnvPtr, values: &[f32]) -> JFloatArray { + if env.is_null() { + return core::ptr::null_mut(); + } + let Ok(len) = JSize::try_from(values.len()) else { + return core::ptr::null_mut(); + }; + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return core::ptr::null_mut(); + } + let new_arr_ptr = unsafe { *vtable.add(JNI_NEW_FLOAT_ARRAY_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_FLOAT_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if new_arr_ptr.is_null() || set_region_ptr.is_null() || exc_check_ptr.is_null() { + return core::ptr::null_mut(); + } + let new_arr: NewFloatArrayFn = unsafe { core::mem::transmute(new_arr_ptr) }; + let set_region: SetFloatArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + let arr = unsafe { new_arr(env, len) }; + if arr.is_null() || unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + if len > 0 { + unsafe { set_region(env, arr, 0, len, values.as_ptr()) }; + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + } + arr +} + +pub(crate) unsafe fn fill_jfloat_array(env: JniEnvPtr, arr: JFloatArray, values: &[f32]) -> bool { + if env.is_null() || arr.is_null() { + return false; + } + let Ok(len) = JSize::try_from(values.len()) else { + return false; + }; + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return false; + } + let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_FLOAT_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if get_len_ptr.is_null() || set_region_ptr.is_null() || exc_check_ptr.is_null() { + return false; + } + let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let set_region: SetFloatArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return false; + } + let actual_len = unsafe { get_len(env, arr) }; + if unsafe { exc_check(env) } != 0 || actual_len < len { + return false; + } + if len > 0 { + unsafe { set_region(env, arr, 0, len, values.as_ptr()) }; + if unsafe { exc_check(env) } != 0 { + return false; + } + } + true +} + +// --- Selection Handles & IME-Integrated Drag --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetSelectionViewport( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + width: JFloat, + height: JFloat, + density: JFloat, +) { + let _ = with_host_mut(handle, |host| { + host.text_layout.update_viewport(width, density); + host.selection.set_viewport(width, height, density); + if host.selected_len > 0 { + host.sync_selection_overlay_from_ime(); + } + }); + crate::jni_bridge::sync_selection_overlay_from_editor(handle); +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeUpdateSelectionOverlay( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start_x: JFloat, + start_y: JFloat, + end_x: JFloat, + end_y: JFloat, + line_height: JFloat, + direction_code: JInt, + has_selection: JBoolean, +) { + let direction = TextDirection::from_code(direction_code); + let _ = with_host_mut(handle, |host| { + host.selection.update_selection( + start_x, + start_y, + end_x, + end_y, + line_height, + direction, + has_selection != 0, + ); + }); +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeApplyTextDragEndpoints( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start_x: JFloat, + start_y: JFloat, + end_x: JFloat, + end_y: JFloat, + line_height: JFloat, + direction_code: JInt, + active_handle_code: JInt, +) { + let direction = TextDirection::from_code(direction_code); + let active_handle = SelectionHandleKind::from_code(active_handle_code); + let _ = with_host_mut(handle, |host| { + host.selection.apply_text_drag_endpoints( + start_x, + start_y, + end_x, + end_y, + line_height, + direction, + active_handle, + ); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionBeginDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + touch_x: JFloat, + touch_y: JFloat, +) -> JInt { + with_host_mut(handle, |host| { + host.begin_selection_handle_drag(touch_x, touch_y) as JInt + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionEndDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + let has_menu = + with_host_mut(handle, |host| u8::from(host.end_selection_handle_drag())).unwrap_or(0); + crate::jni_bridge::sync_selection_overlay_from_editor(handle); + has_menu +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionCancelDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.cancel_selection_handle_drag(); + }); + crate::jni_bridge::sync_selection_overlay_from_editor(handle); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeClearSelectionOverlay( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.selection_drag_anchor_utf16 = None; + host.selection_drag_initial_handle = SelectionHandleKind::None; + host.selection.clear(); + }); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionOverlayJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = with_host_ref(handle, |host| host.selection.to_json()).unwrap_or_default(); + unsafe { new_jstring(env, &json) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionOverlayGeometry( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloatArray { + let packed = + with_host_ref(handle, |host| host.selection.pack_overlay_floats()).unwrap_or([0.0; 24]); + unsafe { new_jfloat_array(env, &packed) } +} + +/// Fills a caller-owned `FloatArray` (length >= 24) with packed overlay geometry +/// without per-frame JNI array allocation. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `out` must be null or a valid `jfloatArray`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFillSelectionOverlayGeometry( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + out: JFloatArray, +) -> JBoolean { + let Some(packed) = with_host_ref(handle, |host| host.selection.pack_overlay_floats()) else { + return 0; + }; + u8::from(unsafe { fill_jfloat_array(env, out, &packed) }) +} + +// --- Surface Recreation, Scroll/DPI State Preservation & Vulkan -> GLES3 Recovery --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetSurfaceScrollOffset( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + scroll_x: JFloat, + scroll_y: JFloat, +) { + let _ = with_host_mut(handle, |host| { + host.surface.set_scroll_offset(scroll_x, scroll_y); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceScrollY( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.surface.scroll_offset_y).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceDensity( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.surface.density).unwrap_or(1.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetTextureGeneration( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_host_ref(handle, |host| host.surface.texture_generation as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetEffectiveImeBottomDp( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.insets.effective_ime_above_nav_bar()).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectRenderBackend( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + vulkan_available: JBoolean, + gles3_available: JBoolean, +) -> JInt { + with_host_mut(handle, |host| { + host.surface + .select_backend(vulkan_available != 0, gles3_available != 0) as JInt + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeReportVulkanDeviceLost( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_mut(handle, |host| { + host.surface.report_vulkan_device_lost() as JInt + }) + .unwrap_or(0) +} + +// --- API 26+ AutofillManager Virtual Structure Bridge --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeConfigureAutofillSdk( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + sdk_int: JInt, +) -> JBoolean { + let sdk = u32::try_from(sdk_int).unwrap_or(0); + with_host_mut(handle, |host| u8::from(host.autofill.set_sdk_int(sdk))).unwrap_or(0) +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeUpsertAutofillField( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + kind_code: JInt, + left: JInt, + top: JInt, + right: JInt, + bottom: JInt, + masked: JBoolean, + value_len: JInt, +) -> JBoolean { + let Some(kind) = AutofillFieldKind::from_code(kind_code) else { + return 0; + }; + let len = usize::try_from(value_len).unwrap_or(0); + let bounds = AutofillRect::normalized(left, top, right, bottom); + with_host_mut(handle, |host| { + u8::from( + host.autofill + .upsert_field(autofill_id, kind, bounds, masked != 0, len), + ) + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFocusAutofillField( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, +) -> JInt { + let next = if autofill_id > 0 { + Some(autofill_id) + } else { + None + }; + with_host_mut(handle, |host| host.autofill.focus_field(next).len() as JInt).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetFocusedAutofillFieldId( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| host.autofill.focused_id().unwrap_or(0)).unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetAutofillFieldText( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + text: JString, +) -> JBoolean { + let Some(val) = (unsafe { read_jstring_utf8(env, text) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.autofill.set_field_text(autofill_id, &val)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `value` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeApplyAutofillValue( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + value: JString, +) -> JBoolean { + let Some(text) = (unsafe { read_jstring_utf8(env, value) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.autofill.apply_autofill_value(autofill_id, &text)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillValue( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, +) -> JString { + let value = with_host_ref(handle, |host| { + host.autofill.filled_value(autofill_id).map(str::to_string) + }) + .flatten(); + match value { + Some(v) => unsafe { new_jstring(env, &v) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillValueByKind( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + kind_code: JInt, +) -> JString { + let Some(kind) = AutofillFieldKind::from_code(kind_code) else { + return core::ptr::null_mut(); + }; + let value = with_host_ref(handle, |host| { + host.autofill.filled_value_by_kind(kind).map(str::to_string) + }) + .flatten(); + match value { + Some(v) => unsafe { new_jstring(env, &v) }, + None => core::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCommitAutofill( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_mut(handle, |host| u8::from(host.autofill.commit())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCancelAutofill( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_mut(handle, |host| u8::from(host.autofill.cancel())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeClearAutofillFields( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.autofill.clear_fields(); + }); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillStructureJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = + with_host_ref(handle, |host| host.autofill.virtual_structure_json()).unwrap_or_default(); + unsafe { new_jstring(env, &json) } +} + +// --- Predictive Back API-Level Dispatch & Destination Navigation Stack --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeBackDispatchMode( + _env: JniEnvPtr, + _class: JClass, + sdk_int: JInt, +) -> JInt { + let sdk = u32::try_from(sdk_int).unwrap_or(0); + back_dispatch_mode(sdk) as JInt +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `route` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePushDestination( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + route: JString, +) -> JBoolean { + let Some(route_str) = (unsafe { read_jstring_utf8(env, route) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.push_back_destination(route_str)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCurrentDestination( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let dest = with_host_ref(handle, |host| { + host.current_back_destination().map(str::to_string) + }) + .flatten(); + match dest { + Some(route) => unsafe { new_jstring(env, &route) }, + None => core::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetBackStackDepth( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + depth: JInt, +) { + let safe_depth = u32::try_from(depth).unwrap_or(0); + let _ = with_host_mut(handle, |host| { + host.set_back_stack_depth(safe_depth); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetBackStackDepth( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| { + host.back_stack_depth().min(i32::MAX as u32) as JInt + }) + .unwrap_or(0) +} + +// --- Native PdfRenderer Validation, Cache Key & Zero-Heap Streaming ARGB_8888 -> RGBA8 --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeValidatePdfPageRequest( + _env: JniEnvPtr, + _class: JClass, + page_index: JInt, + page_count: JInt, + width_px: JInt, + height_px: JInt, +) -> JBoolean { + let (Ok(idx), Ok(count), Ok(w), Ok(h)) = ( + u32::try_from(page_index), + u32::try_from(page_count), + u32::try_from(width_px), + u32::try_from(height_px), + ) else { + return 0; + }; + u8::from(validate_pdf_page_request(idx, count, w, h).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `doc_id` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePdfPageCacheKey( + env: JniEnvPtr, + _class: JClass, + doc_id: JString, + page_index: JInt, + width_px: JInt, + height_px: JInt, + dpi_bucket: JInt, +) -> JString { + let doc = unsafe { read_jstring_utf8(env, doc_id) }.unwrap_or_default(); + let idx = page_index.max(0) as u32; + let w = width_px.max(0) as u32; + let h = height_px.max(0) as u32; + let dpi = dpi_bucket.max(72) as u32; + let key = pdf_page_cache_key(&doc, idx, w, h, dpi); + unsafe { new_jstring(env, &key) } +} + +/// Converts a JNI `jintArray` (`ARGB_8888`) directly into a freshly allocated +/// Java `jbyteArray` (`RGBA8`) using stack-only 4096-pixel chunk buffers (0 B +/// Rust heap allocation) and checking `ExceptionCheck` after every JNI call. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `argb_pixels` must be null or a valid `jintArray`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + env: JniEnvPtr, + _class: JClass, + argb_pixels: JIntArray, + width_px: JInt, + height_px: JInt, +) -> JByteArray { + if env.is_null() || argb_pixels.is_null() { + return core::ptr::null_mut(); + } + let (Ok(w), Ok(h)) = (u32::try_from(width_px), u32::try_from(height_px)) else { + return core::ptr::null_mut(); + }; + let Ok(expected_pixels) = validate_pdf_dimensions(w, h) else { + return core::ptr::null_mut(); + }; + let Ok(expected_jlen) = JSize::try_from(expected_pixels) else { + return core::ptr::null_mut(); + }; + let Some(total_rgba_bytes_usize) = expected_pixels.checked_mul(4) else { + return core::ptr::null_mut(); + }; + let Ok(total_rgba_bytes) = JSize::try_from(total_rgba_bytes_usize) else { + return core::ptr::null_mut(); + }; + + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return core::ptr::null_mut(); + } + let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) }; + let new_arr_ptr = unsafe { *vtable.add(JNI_NEW_BYTE_ARRAY_INDEX) }; + let get_region_ptr = unsafe { *vtable.add(JNI_GET_INT_ARRAY_REGION_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_BYTE_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if get_len_ptr.is_null() + || new_arr_ptr.is_null() + || get_region_ptr.is_null() + || set_region_ptr.is_null() + || exc_check_ptr.is_null() + { + return core::ptr::null_mut(); + } + let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let new_arr: NewByteArrayFn = unsafe { core::mem::transmute(new_arr_ptr) }; + let get_region: GetIntArrayRegionFn = unsafe { core::mem::transmute(get_region_ptr) }; + let set_region: SetByteArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + let actual_len = unsafe { get_len(env, argb_pixels) }; + if unsafe { exc_check(env) } != 0 || actual_len != expected_jlen { + return core::ptr::null_mut(); + } + + let out_arr = unsafe { new_arr(env, total_rgba_bytes) }; + if out_arr.is_null() || unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + + let mut argb_chunk = [0_i32; PDF_STREAM_CHUNK_PIXELS]; + let mut rgba_chunk = [0_u8; PDF_STREAM_CHUNK_PIXELS * 4]; + let mut offset = 0usize; + while offset < expected_pixels { + let count = (expected_pixels - offset).min(PDF_STREAM_CHUNK_PIXELS); + unsafe { + get_region( + env, + argb_pixels, + offset as JSize, + count as JSize, + argb_chunk.as_mut_ptr(), + ); + } + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + convert_argb8888_i32_chunk_to_rgba8_slice( + &argb_chunk[..count], + &mut rgba_chunk[..count * 4], + ); + unsafe { + set_region( + env, + out_arr, + (offset * 4) as JSize, + (count * 4) as JSize, + rgba_chunk.as_ptr() as *const i8, + ); + } + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + offset += count; + } + out_arr +} + +#[cfg(test)] +mod tests { + use super::*; + + #[repr(C)] + struct MockJniEnv { + vtable: *const *const c_void, + input_pixels: Vec, + output_bytes: Vec, + pending_exception: bool, + fail_get_region_on_call: Option, + fail_set_region_on_call: Option, + get_region_calls: usize, + set_region_calls: usize, + } + + unsafe extern "C" fn mock_get_array_len(env: JniEnvPtr, _arr: JObject) -> JSize { + let state = unsafe { &*(env as *const MockJniEnv) }; + state.input_pixels.len() as JSize + } + + unsafe extern "C" fn mock_new_byte_array(env: JniEnvPtr, len: JSize) -> JByteArray { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + state.output_bytes = vec![0u8; len as usize]; + (&raw mut state.output_bytes) as JByteArray + } + + unsafe extern "C" fn mock_get_int_region( + env: JniEnvPtr, + _arr: JIntArray, + start: JSize, + len: JSize, + buf: *mut JInt, + ) { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + assert!( + !state.pending_exception, + "must never call GetIntArrayRegion with pending exception" + ); + let call_idx = state.get_region_calls; + state.get_region_calls += 1; + if state.fail_get_region_on_call == Some(call_idx) { + state.pending_exception = true; + return; + } + let s = start as usize; + let n = len as usize; + let dst = unsafe { core::slice::from_raw_parts_mut(buf, n) }; + dst.copy_from_slice(&state.input_pixels[s..s + n]); + } + + unsafe extern "C" fn mock_set_byte_region( + env: JniEnvPtr, + _arr: JByteArray, + start: JSize, + len: JSize, + buf: *const i8, + ) { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + assert!( + !state.pending_exception, + "must never call SetByteArrayRegion with pending exception" + ); + let call_idx = state.set_region_calls; + state.set_region_calls += 1; + if state.fail_set_region_on_call == Some(call_idx) { + state.pending_exception = true; + return; + } + let s = start as usize; + let n = len as usize; + let src = unsafe { core::slice::from_raw_parts(buf as *const u8, n) }; + state.output_bytes[s..s + n].copy_from_slice(src); + } + + unsafe extern "C" fn mock_exception_check(env: JniEnvPtr) -> JBoolean { + let state = unsafe { &*(env as *const MockJniEnv) }; + u8::from(state.pending_exception) + } + + fn build_mock_vtable() -> [*const c_void; 232] { + let mut table = [core::ptr::null(); 232]; + table[JNI_GET_ARRAY_LENGTH_INDEX] = mock_get_array_len as *const c_void; + table[JNI_NEW_BYTE_ARRAY_INDEX] = mock_new_byte_array as *const c_void; + table[JNI_GET_INT_ARRAY_REGION_INDEX] = mock_get_int_region as *const c_void; + table[JNI_SET_BYTE_ARRAY_REGION_INDEX] = mock_set_byte_region as *const c_void; + table[JNI_EXCEPTION_CHECK_INDEX] = mock_exception_check as *const c_void; + table + } + + #[test] + fn pdf_jni_streaming_aborts_immediately_on_exception_and_streams_multi_chunk() { + let vtable = build_mock_vtable(); + let fake_arr = 0x1000usize as JIntArray; + + // 1. Multi-chunk success (5000 pixels > 4096 chunk size -> 2 Get + 2 Set calls). + let mut env = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: None, + fail_set_region_on_call: None, + get_region_calls: 0, + set_region_calls: 0, + }; + let out = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(!out.is_null()); + assert_eq!(env.get_region_calls, 2); + assert_eq!(env.set_region_calls, 2); + assert_eq!(&env.output_bytes[0..4], &[0x11, 0x22, 0x33, 0xFF]); + assert_eq!( + &env.output_bytes[4999 * 4..5000 * 4], + &[0x11, 0x22, 0x33, 0xFF] + ); + + // 2. Pending exception raised during chunk 1 GetIntArrayRegion -> aborts before SetByteArrayRegion #1. + let mut env_fail_get = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: Some(1), + fail_set_region_on_call: None, + get_region_calls: 0, + set_region_calls: 0, + }; + let out_fail_get = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env_fail_get) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(out_fail_get.is_null()); + assert_eq!(env_fail_get.get_region_calls, 2); + assert_eq!(env_fail_get.set_region_calls, 1); + + // 3. Pending exception raised during chunk 0 SetByteArrayRegion -> aborts before chunk 1 GetIntArrayRegion. + let mut env_fail_set = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: None, + fail_set_region_on_call: Some(0), + get_region_calls: 0, + set_region_calls: 0, + }; + let out_fail_set = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env_fail_set) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(out_fail_set.is_null()); + assert_eq!(env_fail_set.get_region_calls, 1); + assert_eq!(env_fail_set.set_region_calls, 1); + } +} diff --git a/packages/frontend/hosts/android/src/jni_islands.rs b/packages/frontend/hosts/android/src/jni_islands.rs new file mode 100644 index 0000000000..ea30365941 --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_islands.rs @@ -0,0 +1,527 @@ +#![allow(unsafe_code)] + +//! Hand-written JNI exports for Android native share-intent bridge (`ShareIntentBridge`). +//! Zero JNA, zero UniFFI, zero WebKit, zero IME-channel typing. + +use core::ffi::c_void; + +use affine_store::share_ingest::{ + MAX_SHARE_ATTACHMENT_BYTES, ShareIngestAttachmentSpec, ShareIngestRequest, SharePayloadKind, +}; +use playground::overlays::{SharedNoteBlockItem, SharedNoteBlockKind}; + +use crate::jni_bridge::{ + JBoolean, JClass, JInt, JLong, JObject, JSize, JString, JniEnvPtr, new_jstring, + read_jstring_utf8, with_host_mut, with_host_ref, +}; +use crate::native_islands::{AndroidShareItem, AndroidShareKind}; + +const JNI_GET_ARRAY_LENGTH_INDEX: usize = 171; +const JNI_GET_BYTE_ARRAY_REGION_INDEX: usize = 200; +const JNI_EXCEPTION_CHECK_INDEX: usize = 228; + +type GetArrayLengthFn = unsafe extern "C" fn(JniEnvPtr, JObject) -> JSize; +type GetByteArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JObject, JSize, JSize, *mut i8); +type ExceptionCheckFn = unsafe extern "C" fn(JniEnvPtr) -> JBoolean; + +/// Reads a JNI `jbyteArray` up to `max_len` bytes (`None` if null, negative, oversized, or JNI exception). +/// Rejects arrays exceeding `max_len` with zero heap allocation. +unsafe fn read_jbyte_array_bounded( + env: JniEnvPtr, + arr: JObject, + max_len: usize, +) -> Option> { + if env.is_null() || arr.is_null() { + return None; + } + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return None; + } + let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) }; + let get_region_ptr = unsafe { *vtable.add(JNI_GET_BYTE_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if get_len_ptr.is_null() || get_region_ptr.is_null() || exc_check_ptr.is_null() { + return None; + } + let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let get_region: GetByteArrayRegionFn = unsafe { core::mem::transmute(get_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + let len = unsafe { get_len(env, arr) }; + if len < 0 { + return None; + } + if len == 0 { + return Some(Vec::new()); + } + let usize_len = len as usize; + if usize_len > max_len { + return None; + } + let mut out = vec![0u8; usize_len]; + unsafe { + get_region(env, arr, 0, len, out.as_mut_ptr() as *mut i8); + } + if unsafe { exc_check(env) } != 0 { + return None; + } + Some(out) +} + +fn sanitize_doc_id_component(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for ch in raw.chars() { + if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { + out.push(ch); + } else { + out.push('-'); + } + } + if out.is_empty() { + "item".to_string() + } else { + out + } +} + +fn build_share_ingest_request( + item: &AndroidShareItem, + doc_id: &str, + now_ms: i64, +) -> ShareIngestRequest { + match item.kind { + AndroidShareKind::Url => ShareIngestRequest { + share_id: item.id.clone(), + import_attempt_id: item.id.clone(), + doc_id: doc_id.to_string(), + kind: SharePayloadKind::Url, + title: item.title.clone(), + text_or_url: item.content.trim().to_string(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: Vec::new(), + client_id: 0, + now_ms, + }, + AndroidShareKind::Text => ShareIngestRequest { + share_id: item.id.clone(), + import_attempt_id: item.id.clone(), + doc_id: doc_id.to_string(), + kind: SharePayloadKind::Text, + title: item.title.clone(), + text_or_url: item.content.trim().to_string(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: Vec::new(), + client_id: 0, + now_ms, + }, + AndroidShareKind::Image => ShareIngestRequest { + share_id: item.id.clone(), + import_attempt_id: item.id.clone(), + doc_id: doc_id.to_string(), + kind: SharePayloadKind::Image, + title: item.title.clone(), + text_or_url: String::new(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: vec![ShareIngestAttachmentSpec { + blob_key: String::new(), + file_name: "shared-image".to_string(), + mime_type: item.mime_type.clone(), + byte_offset: 0, + byte_len: item.attachment_bytes.len(), + }], + client_id: 0, + now_ms, + }, + AndroidShareKind::Pdf => ShareIngestRequest { + share_id: item.id.clone(), + import_attempt_id: item.id.clone(), + doc_id: doc_id.to_string(), + kind: SharePayloadKind::Pdf, + title: item.title.clone(), + text_or_url: String::new(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: vec![ShareIngestAttachmentSpec { + blob_key: String::new(), + file_name: if item.title.trim().is_empty() { + "shared-document.pdf".to_string() + } else if item.title.trim().to_ascii_lowercase().ends_with(".pdf") { + item.title.trim().to_string() + } else { + format!("{}.pdf", item.title.trim()) + }, + mime_type: if item.mime_type.trim().is_empty() { + "application/pdf".to_string() + } else { + item.mime_type.trim().to_string() + }, + byte_offset: 0, + byte_len: item.attachment_bytes.len(), + }], + client_id: 0, + now_ms, + }, + } +} + +fn to_live_shared_block(item: &AndroidShareItem) -> SharedNoteBlockItem { + let spec = match item.kind { + AndroidShareKind::Url => SharedNoteBlockKind::Bookmark { + url: item.content.trim().to_string(), + title: item.title.trim().to_string(), + }, + AndroidShareKind::Text => SharedNoteBlockKind::Quote { + text: item.content.trim().to_string(), + }, + AndroidShareKind::Image => SharedNoteBlockKind::Image { + caption: item.title.trim().to_string(), + bytes: item.attachment_bytes.clone(), + }, + AndroidShareKind::Pdf => SharedNoteBlockKind::Pdf { + file_name: if item.title.trim().is_empty() { + "shared-document.pdf".to_string() + } else if item.title.trim().to_ascii_lowercase().ends_with(".pdf") { + item.title.trim().to_string() + } else { + format!("{}.pdf", item.title.trim()) + }, + mime_type: if item.mime_type.trim().is_empty() { + "application/pdf".to_string() + } else { + item.mime_type.trim().to_string() + }, + bytes: item.attachment_bytes.clone(), + }, + }; + SharedNoteBlockItem { + queue_id: item.id.clone(), + share_id: sanitize_doc_id_component(&item.id), + spec, + } +} + +/// Enqueues an incoming Android `ACTION_SEND` payload without attachment bytes (`0 = url`, `1 = text`). +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareEnqueue( + env: JniEnvPtr, + class: JClass, + handle: JLong, + id: JString, + kind: JInt, + title: JString, + content: JString, + mime_type: JString, +) -> JBoolean { + unsafe { + Java_app_affine_pro_host_NativeBridge_nativeShareEnqueueBytes( + env, + class, + handle, + id, + kind, + title, + content, + mime_type, + core::ptr::null_mut(), + ) + } +} + +/// Enqueues an incoming Android `ACTION_SEND` payload with optional attachment bytes (`2 = image`). +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareEnqueueBytes( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + id: JString, + kind: JInt, + title: JString, + content: JString, + mime_type: JString, + attachment_bytes: JObject, +) -> JBoolean { + let Some(id_str) = (unsafe { read_jstring_utf8(env, id) }) else { + return 0; + }; + let Some(content_str) = (unsafe { read_jstring_utf8(env, content) }) else { + return 0; + }; + let title_str = unsafe { read_jstring_utf8(env, title) }.unwrap_or_default(); + let mime_str = + unsafe { read_jstring_utf8(env, mime_type) }.unwrap_or_else(|| "text/plain".to_string()); + let share_kind = match kind { + 0 => AndroidShareKind::Url, + 1 => AndroidShareKind::Text, + 2 => AndroidShareKind::Image, + 3 => AndroidShareKind::Pdf, + _ => return 0, + }; + let bytes = if attachment_bytes.is_null() { + Vec::new() + } else { + match unsafe { read_jbyte_array_bounded(env, attachment_bytes, MAX_SHARE_ATTACHMENT_BYTES) } + { + Some(b) => b, + None => return 0, + } + }; + let ok = with_host_mut(handle, |host| { + let has_sqlite = host.sqlite.has_any_connection(); + host.islands + .share_queue + .enqueue_for_target( + AndroidShareItem { + id: id_str, + kind: share_kind, + title: title_str, + content: content_str, + mime_type: mime_str, + attachment_bytes: bytes, + }, + has_sqlite, + ) + .is_ok() + }) + .unwrap_or(false); + u8::from(ok) +} + +/// Returns the number of queued share items waiting to be ingested. +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSharePendingCount( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| { + host.islands + .share_queue + .pending_count() + .min(i32::MAX as usize) as JInt + }) + .unwrap_or(0) +} + +/// Returns `true` when `id` has already been durably committed and marked consumed. +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareIsConsumed( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + id: JString, +) -> JBoolean { + let Some(id_str) = (unsafe { read_jstring_utf8(env, id) }) else { + return 0; + }; + let consumed = with_host_ref(handle, |host| host.islands.share_queue.is_consumed(&id_str)) + .unwrap_or(false); + u8::from(consumed) +} + +/// Returns `true` only when `share_id` has a durable receipt row in the mounted workspace's +/// SQLite `share_ingest_receipts` table (`false` when no persistent workspace DB is mounted). +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareIsDurablyCommitted( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + workspace_storage_key: JString, + share_id: JString, +) -> JBoolean { + let Some(share_id_str) = (unsafe { read_jstring_utf8(env, share_id) }) else { + return 0; + }; + let explicit_ws_key = unsafe { read_jstring_utf8(env, workspace_storage_key) } + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + let committed = with_host_mut(handle, |host| { + let resolved_ws = match &explicit_ws_key { + Some(key) => host.sqlite.has_connection(key).then(|| key.clone()), + None => host.sqlite.first_connected_local_workspace_key(), + }; + let Some(ws_key) = resolved_ws else { + return false; + }; + host.sqlite + .is_share_durably_committed(&ws_key, &share_id_str) + .unwrap_or(false) + }) + .unwrap_or(false); + u8::from(committed) +} + +/// Atomically drains all queued Android share items as a JSON array. +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareDrainJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = with_host_mut(handle, |host| { + let items = host.islands.share_queue.drain_all(); + serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string()) + }) + .unwrap_or_else(|| "[]".to_string()); + unsafe { new_jstring(env, &json) } +} + +/// Returns the active `PlaygroundView` `PageSnapshot` as JSON for host verification. +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetActivePageSnapshotJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let snap = crate::editor_runtime::with_editor_mut(handle, |ed| ed.active_page_snapshot_json()) + .flatten(); + match snap { + Some(json) => unsafe { new_jstring(env, &json) }, + None => core::ptr::null_mut(), + } +} + +/// Atomically ingests pending Android share items into a single authoritative target: +/// - **Connected SQLite workspace (`resolved_ws == Some(ws_key)`)**: commits structured blocks +/// (`affine_store::share_ingest`) strictly to `target_doc_id` (or newly created `share-doc-` +/// when `target_doc_id` is empty) and never dual-writes into `PlaygroundView`. +/// - **Standalone in-memory editor (`resolved_ws == None` and `target_workspace_key` empty)**: +/// appends structured blocks to the open writable `PlaygroundView` preserving selection and +/// marks ONLY the exact `share_id`s delivered in-session (without durable SQLite receipt). +/// +/// # Safety +/// Called by the JVM/ART runtime with valid JNI pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIngestSharedItems( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + target_workspace_key: JString, + target_doc_id: JString, + now_ms: JLong, +) -> JInt { + let explicit_ws_key = unsafe { read_jstring_utf8(env, target_workspace_key) } + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + let explicit_doc_id = unsafe { read_jstring_utf8(env, target_doc_id) } + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + if now_ms <= 0 { + return 0; + } + let effective_now_ms = now_ms; + + let editor_state = crate::editor_runtime::with_editor_mut(handle, |ed| { + (!ed.is_page_readonly(), ed.active_doc_id()) + }); + let editor_writable = editor_state.as_ref().map(|(w, _)| *w); + let active_doc_id = editor_state.and_then(|(_, d)| d); + let targets_active_editor_doc = explicit_doc_id.is_some() && explicit_doc_id == active_doc_id; + + let Some((sqlite_committed_items, fallback_live_candidates)) = with_host_mut(handle, |host| { + let pending = host.islands.share_queue.peek_pending(); + if pending.is_empty() { + return (Vec::new(), Vec::new()); + } + let resolved_ws = match &explicit_ws_key { + Some(key) => host.sqlite.has_connection(key).then(|| key.clone()), + None => host.sqlite.first_connected_local_workspace_key(), + }; + if explicit_ws_key.is_some() && resolved_ws.is_none() { + return (Vec::new(), Vec::new()); + } + if let Some(ws_key) = resolved_ws { + if targets_active_editor_doc && editor_writable == Some(false) { + return (Vec::new(), Vec::new()); + } + let mut ok_items = Vec::with_capacity(pending.len()); + for item in pending { + let doc_id = explicit_doc_id.clone().unwrap_or_else(|| { + format!("share-doc-{}", sanitize_doc_id_component(&item.id)) + }); + let req = build_share_ingest_request(&item, &doc_id, effective_now_ms); + if host + .sqlite + .ingest_share_item(&ws_key, &req, &item.attachment_bytes) + .is_ok() + { + ok_items.push(item); + } + } + if !ok_items.is_empty() { + let _ = host.sqlite.checkpoint_passive(&ws_key); + } + (ok_items, Vec::new()) + } else if editor_writable == Some(true) + && (explicit_doc_id.is_none() || explicit_doc_id == active_doc_id) + { + (Vec::new(), pending) + } else { + (Vec::new(), Vec::new()) + } + }) else { + return 0; + }; + + let (consumed_ids, durably_committed): (Vec, bool) = + if !sqlite_committed_items.is_empty() { + ( + sqlite_committed_items.into_iter().map(|i| i.id).collect(), + true, + ) + } else if !fallback_live_candidates.is_empty() { + let live_specs: Vec = fallback_live_candidates + .iter() + .map(to_live_shared_block) + .collect(); + let delivered = crate::editor_runtime::with_editor_mut(handle, |ed| { + ed.append_shared_blocks_preserving_selection(&live_specs, effective_now_ms as u64) + }) + .unwrap_or_default(); + (delivered, false) + } else { + (Vec::new(), false) + }; + + if consumed_ids.is_empty() { + return 0; + } + + let count = consumed_ids.len().min(i32::MAX as usize) as JInt; + let _ = with_host_mut(handle, |host| { + if durably_committed { + host.islands.share_queue.mark_consumed(&consumed_ids); + } else { + host.islands.share_queue.mark_live_delivered(&consumed_ids); + } + }); + count +} diff --git a/packages/frontend/hosts/android/src/jni_shell.rs b/packages/frontend/hosts/android/src/jni_shell.rs new file mode 100644 index 0000000000..dea0f3eb33 --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_shell.rs @@ -0,0 +1,152 @@ +#![allow(unsafe_code)] + +//! Hand-written `extern "C"` JNI exports that create a host with its root view (a bare page +//! editor, or the mobile product shell with `Home`, `Explorer`, `Journals`, `Search`, +//! `Settings`, and the `Page` route), and the shell's own exports. +//! +//! `nativeHandleBack`, text input, selection, and frame exports in the sibling modules +//! reach the shell through the same editor runtime. + +use std::path::Path; + +use playground::FormFactor; + +use crate::{ + editor_runtime::{AndroidEditorRuntime, with_editor_mut}, + jni_bridge::{ + JBoolean, JClass, JInt, JLong, JString, JniEnvPtr, create_host, new_jstring, + read_jstring_utf8, with_host_mut, + }, + shell_workspace::ShellLaunch, +}; + +/// Creates a host whose root view is one bare page editor with an empty document. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCreateHost( + env: JniEnvPtr, + class: JClass, +) -> JLong { + let runtime = AndroidEditorRuntime::new(412.0, 915.0, 2.625, FormFactor::Phone, false); + create_host(env, class, runtime) +} + +/// Creates a host whose root view is the mobile shell. It shows the showcase workspaces until +/// `nativeShellMountWorkspace` mounts a local workspace. +/// +/// # Safety +/// `env` must be a valid `JNIEnv*`; `language_tag` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCreateShellHost( + env: JniEnvPtr, + class: JClass, + language_tag: JString, + now_ms: JLong, + utc_offset_minutes: JInt, + dark: JBoolean, +) -> JLong { + let tag = unsafe { read_jstring_utf8(env, language_tag) }.unwrap_or_else(|| "en".into()); + let launch = ShellLaunch::new(&tag, now_ms, utc_offset_minutes, dark != 0); + let runtime = AndroidEditorRuntime::new_shell(412.0, 915.0, 2.625, FormFactor::Phone, &launch); + create_host(env, class, runtime) +} + +/// Returns the shell route: `0` bare editor root, `1` Home, `2` Explorer, `3` Journals, +/// `4` Search, `5` Page, `6` Settings. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShellRoute( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_editor_mut(handle, |ed| JInt::from(ed.shell_route())).unwrap_or(0) +} + +/// Returns the shell's latest accessibility tree as JSON (`rootId`, `nodes` with `bounds` in +/// dp), or null before the first frame. +/// +/// # Safety +/// `env` must be a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShellAccessibilityJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + match with_editor_mut(handle, |ed| ed.shell_accessibility_json()).flatten() { + Some(json) => unsafe { new_jstring(env, &json) }, + None => core::ptr::null_mut(), + } +} + +/// Replaces the showcase with the allowlisted local workspace +/// `/workspaces///.db` (created when absent). +/// +/// # Safety +/// `env` must be a valid `JNIEnv*`; the strings must be null or valid `jstring`s. +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShellMountWorkspace( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + files_dir: JString, + space_type: JString, + peer: JString, + space_id: JString, + name: JString, + now_ms: JLong, +) -> JBoolean { + let (Some(dir), Some(space_type), Some(peer), Some(space_id)) = (unsafe { + ( + read_jstring_utf8(env, files_dir), + read_jstring_utf8(env, space_type), + read_jstring_utf8(env, peer), + read_jstring_utf8(env, space_id), + ) + }) else { + return 0; + }; + let name = unsafe { read_jstring_utf8(env, name) }.unwrap_or_else(|| space_id.clone()); + let mounted = with_editor_mut(handle, |ed| { + ed.mount_shell_workspace( + Path::new(&dir), + &space_type, + &peer, + &space_id, + &name, + now_ms, + ) + }) + .unwrap_or(false); + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + u8::from(mounted) +} + +/// Commits the shell's local changes to the mounted workspace now; the host also commits them +/// every second. Returns the number of written rows (`0` without pending changes), or `-1` when +/// no workspace is mounted or the commit fails. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShellFlushWorkspace( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_editor_mut(handle, AndroidEditorRuntime::flush_shell_workspace).unwrap_or(-1) +} + +/// Follows the system dark mode: the shell resolves its `System` theme preference with it. +/// Returns `false` when the host root is not the shell. +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShellSetSystemDark( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + dark: JBoolean, +) -> JBoolean { + let applied = + with_editor_mut(handle, |ed| ed.set_shell_system_dark(dark != 0)).unwrap_or(false); + if applied { + let _ = with_host_mut(handle, |host| host.surface.request_frame()); + } + u8::from(applied) +} diff --git a/packages/frontend/hosts/android/src/jni_storage.rs b/packages/frontend/hosts/android/src/jni_storage.rs new file mode 100644 index 0000000000..2ab37af837 --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_storage.rs @@ -0,0 +1,688 @@ +#![allow(unsafe_code)] + +//! Thin JNI exports for Android in-place SQLite WAL co-storage, Jetpack +//! Preferences DataStore (`auth-sessions`), and legacy `https://localhost` +//! `localStorage` import / rollback write-back verification. + +use std::collections::BTreeMap; +use std::path::Path; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; + +use crate::datastore::{ + AuthSessionRecord, V1EncryptedEnvelope, auth_datastore_path, auth_token_key, + canonical_endpoint, delete_file_key, get_or_create_file_string, is_permanent_auth_error_code, + keystore_alias, read_file_string, update_file_string, +}; +use crate::jni_bridge::{ + JBoolean, JClass, JInt, JLong, JString, JniEnvPtr, new_jstring, read_jstring_utf8, + with_host_mut, with_host_ref, +}; +use crate::{ + filter_legacy_local_storage_probe_json, is_allowed_legacy_local_storage_key, + verify_legacy_writeback_result, +}; + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `key` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsAllowedLegacyLocalStorageKey( + env: JniEnvPtr, + _class: JClass, + key: JString, +) -> JBoolean { + let Some(raw) = (unsafe { read_jstring_utf8(env, key) }) else { + return 0; + }; + u8::from(is_allowed_legacy_local_storage_key(&raw)) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `raw_json` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFilterLegacyLocalStorageProbe( + env: JniEnvPtr, + _class: JClass, + raw_json: JString, +) -> JString { + let Some(raw) = (unsafe { read_jstring_utf8(env, raw_json) }) else { + return core::ptr::null_mut(); + }; + match filter_legacy_local_storage_probe_json(&raw) { + Some(filtered) => unsafe { new_jstring(env, &filtered) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeImportLegacyLocalStorageProbe( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + payload_json: JString, + allowed_keys_csv: JString, +) -> JBoolean { + let Some(payload) = (unsafe { read_jstring_utf8(env, payload_json) }) else { + return 0; + }; + let custom_keys_owned = unsafe { read_jstring_utf8(env, allowed_keys_csv) }; + let custom_keys: Vec<&str> = custom_keys_owned + .as_deref() + .map(|csv| { + csv.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect() + }) + .unwrap_or_default(); + + with_host_mut(handle, |host| { + u8::from( + host.import_legacy_local_storage_probe(&payload, &custom_keys) + .is_ok(), + ) + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCanCreateDefaultWorkspace( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_ref(handle, |host| { + u8::from(host.upgrade_import.can_create_default_workspace()) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAllowlistedWorkspaceIdsJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = with_host_ref(handle, |host| { + serde_json::to_string(host.workspace_catalog.ids()).unwrap_or_else(|_| "[]".to_string()) + }) + .unwrap_or_else(|| "[]".to_string()); + unsafe { new_jstring(env, &json) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetPreservedLocalWorkspaceRaw( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let raw = with_host_ref(handle, |host| { + host.preserved_local_workspace_raw().map(str::to_string) + }) + .flatten(); + match raw { + Some(value) => unsafe { new_jstring(env, &value) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeVerifyLegacyWriteBack( + env: JniEnvPtr, + _class: JClass, + expected_set_json: JString, + expected_remove_json: JString, + readback_json: JString, +) -> JBoolean { + let Some(expected_set_raw) = (unsafe { read_jstring_utf8(env, expected_set_json) }) else { + return 0; + }; + let expected_remove_raw = + unsafe { read_jstring_utf8(env, expected_remove_json) }.unwrap_or_else(|| "[]".to_string()); + let Some(readback_raw) = (unsafe { read_jstring_utf8(env, readback_json) }) else { + return 0; + }; + let Ok(expected_set) = serde_json::from_str::>(&expected_set_raw) + else { + return 0; + }; + let Ok(expected_remove) = serde_json::from_str::>(&expected_remove_raw) else { + return 0; + }; + u8::from(verify_legacy_writeback_result(&expected_set, &expected_remove, &readback_raw).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeConnectWorkspace( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + files_dir: JString, + peer: JString, + space_id: JString, +) -> JString { + let (Some(dir), Some(peer_s), Some(space_s)) = ( + unsafe { read_jstring_utf8(env, files_dir) }, + unsafe { read_jstring_utf8(env, peer) }, + unsafe { read_jstring_utf8(env, space_id) }, + ) else { + return core::ptr::null_mut(); + }; + let connected = with_host_mut(handle, |host| { + let local_ready = host.is_local_workspace_import_ready(); + let catalog = host.workspace_catalog.clone(); + let res = host.sqlite.connect_workspace( + Path::new(&dir), + &peer_s, + &space_s, + &catalog, + local_ready, + ); + if peer_s == "local" { + host.record_local_workspace_mount_outcome(&space_s, res.is_ok()); + } + res.ok() + }) + .flatten(); + match connected { + Some(key) => unsafe { new_jstring(env, &key) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOpenUserspace( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + files_dir: JString, + peer: JString, + user_id: JString, +) -> JString { + let (Some(dir), Some(peer_s), Some(user_s)) = ( + unsafe { read_jstring_utf8(env, files_dir) }, + unsafe { read_jstring_utf8(env, peer) }, + unsafe { read_jstring_utf8(env, user_id) }, + ) else { + return core::ptr::null_mut(); + }; + let connected = with_host_mut(handle, |host| { + host.sqlite + .open_userspace(Path::new(&dir), &peer_s, &user_s) + .ok() + }) + .flatten(); + match connected { + Some(key) => unsafe { new_jstring(env, &key) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStoragePushUpdateB64( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + connection_key: JString, + doc_id: JString, + update_b64: JString, + now_ms: JLong, +) -> JLong { + let (Some(key), Some(doc), Some(b64)) = ( + unsafe { read_jstring_utf8(env, connection_key) }, + unsafe { read_jstring_utf8(env, doc_id) }, + unsafe { read_jstring_utf8(env, update_b64) }, + ) else { + return -1; + }; + let Ok(bytes) = STANDARD.decode(b64) else { + return -1; + }; + with_host_mut(handle, |host| { + host.sqlite + .push_update(&key, &doc, &bytes, now_ms) + .unwrap_or(-1) + }) + .unwrap_or(-1) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageGetDocB64( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + connection_key: JString, + doc_id: JString, +) -> JString { + let (Some(key), Some(doc)) = (unsafe { read_jstring_utf8(env, connection_key) }, unsafe { + read_jstring_utf8(env, doc_id) + }) else { + return core::ptr::null_mut(); + }; + let data = with_host_mut(handle, |host| { + host.sqlite.get_doc(&key, &doc).ok().flatten() + }) + .flatten(); + match data { + Some(bin) => unsafe { new_jstring(env, &STANDARD.encode(bin)) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageGetBlobB64( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + connection_key: JString, + blob_key: JString, +) -> JString { + let (Some(conn_key), Some(bkey)) = + (unsafe { read_jstring_utf8(env, connection_key) }, unsafe { + read_jstring_utf8(env, blob_key) + }) + else { + return core::ptr::null_mut(); + }; + let data = with_host_mut(handle, |host| { + host.sqlite.get_blob(&conn_key, &bkey).ok().flatten() + }) + .flatten(); + match data { + Some(bin) => unsafe { new_jstring(env, &STANDARD.encode(bin)) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageCheckpoint( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + connection_key: JString, +) -> JBoolean { + let Some(key) = (unsafe { read_jstring_utf8(env, connection_key) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.sqlite.checkpoint(&key).is_ok()) + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageCheckpointAllPassive( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_mut(handle, |host| { + host.sqlite.checkpoint_all_passive().min(i32::MAX as usize) as JInt + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageClose( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + connection_key: JString, +) -> JBoolean { + let Some(key) = (unsafe { read_jstring_utf8(env, connection_key) }) else { + return 0; + }; + with_host_mut(handle, |host| u8::from(host.sqlite.close(&key))).unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `endpoint` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCanonicalEndpoint( + env: JniEnvPtr, + _class: JClass, + endpoint: JString, +) -> JString { + let Some(raw) = (unsafe { read_jstring_utf8(env, endpoint) }) else { + return core::ptr::null_mut(); + }; + unsafe { new_jstring(env, &canonical_endpoint(&raw)) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `endpoint` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeAuthTokenKey( + env: JniEnvPtr, + _class: JClass, + endpoint: JString, +) -> JString { + let Some(raw) = (unsafe { read_jstring_utf8(env, endpoint) }) else { + return core::ptr::null_mut(); + }; + unsafe { new_jstring(env, &auth_token_key(&raw)) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `endpoint` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeKeystoreAlias( + env: JniEnvPtr, + _class: JClass, + endpoint: JString, +) -> JString { + let Some(raw) = (unsafe { read_jstring_utf8(env, endpoint) }) else { + return core::ptr::null_mut(); + }; + unsafe { new_jstring(env, &keystore_alias(&raw)) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +/// +/// Returns tagged status distinguishing missing keys from read/decode errors: +/// - `"OK:"` when key exists +/// - `"MISSING"` when file or key does not exist +/// - `"ERROR:"` when file exists but I/O or protobuf decoding failed +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDataStoreReadResult( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, +) -> JString { + let (Some(dir), Some(k)) = (unsafe { read_jstring_utf8(env, files_dir) }, unsafe { + read_jstring_utf8(env, key) + }) else { + return unsafe { new_jstring(env, "ERROR:null jni argument") }; + }; + let path = auth_datastore_path(Path::new(&dir)); + let tagged = match read_file_string(&path, &k) { + Ok(Some(val)) => format!("OK:{val}"), + Ok(None) => "MISSING".to_string(), + Err(err) => format!("ERROR:{err}"), + }; + unsafe { new_jstring(env, &tagged) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDataStoreGetString( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, +) -> JString { + let (Some(dir), Some(k)) = (unsafe { read_jstring_utf8(env, files_dir) }, unsafe { + read_jstring_utf8(env, key) + }) else { + return core::ptr::null_mut(); + }; + let path = auth_datastore_path(Path::new(&dir)); + match read_file_string(&path, &k) { + Ok(Some(val)) => unsafe { new_jstring(env, &val) }, + _ => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDataStoreSetString( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, + value: JString, +) -> JBoolean { + let (Some(dir), Some(k), Some(v)) = ( + unsafe { read_jstring_utf8(env, files_dir) }, + unsafe { read_jstring_utf8(env, key) }, + unsafe { read_jstring_utf8(env, value) }, + ) else { + return 0; + }; + let path = auth_datastore_path(Path::new(&dir)); + u8::from(update_file_string(&path, &k, &v).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDataStoreDeleteKey( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, +) -> JBoolean { + let (Some(dir), Some(k)) = (unsafe { read_jstring_utf8(env, files_dir) }, unsafe { + read_jstring_utf8(env, key) + }) else { + return 0; + }; + let path = auth_datastore_path(Path::new(&dir)); + u8::from(delete_file_key(&path, &k).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `response_json` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePrepareAuthSessionJson( + env: JniEnvPtr, + _class: JClass, + response_json: JString, + now_ms: JLong, +) -> JString { + let Some(raw) = (unsafe { read_jstring_utf8(env, response_json) }) else { + return core::ptr::null_mut(); + }; + let Ok(record) = AuthSessionRecord::from_server_response(&raw, now_ms) else { + return core::ptr::null_mut(); + }; + let Ok(stored) = record.to_stored_json() else { + return core::ptr::null_mut(); + }; + unsafe { new_jstring(env, &stored) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `stored_json` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeValidateAuthSessionJson( + env: JniEnvPtr, + _class: JClass, + stored_json: JString, +) -> JBoolean { + let Some(raw) = (unsafe { read_jstring_utf8(env, stored_json) }) else { + return 0; + }; + u8::from(AuthSessionRecord::from_stored_json(&raw).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `encoded` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeValidateV1Ciphertext( + env: JniEnvPtr, + _class: JClass, + encoded: JString, +) -> JBoolean { + let Some(raw) = (unsafe { read_jstring_utf8(env, encoded) }) else { + return 0; + }; + u8::from(V1EncryptedEnvelope::parse(&raw).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +/// +/// Atomically reads a non-empty string preference or persists `candidate_value` +/// inside a single per-file lock critical section. +/// Returns `"OK:"` or `"ERROR:"`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDataStoreGetOrCreateString( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, + candidate_value: JString, +) -> JString { + let (Some(dir), Some(k), Some(candidate)) = ( + unsafe { read_jstring_utf8(env, files_dir) }, + unsafe { read_jstring_utf8(env, key) }, + unsafe { read_jstring_utf8(env, candidate_value) }, + ) else { + return unsafe { new_jstring(env, "ERROR:null jni argument") }; + }; + let path = auth_datastore_path(Path::new(&dir)); + let tagged = match get_or_create_file_string(&path, &k, &candidate) { + Ok(persisted) => format!("OK:{persisted}"), + Err(err) => format!("ERROR:{err}"), + }; + unsafe { new_jstring(env, &tagged) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeExtractJsonStringField( + env: JniEnvPtr, + _class: JClass, + json: JString, + field: JString, +) -> JString { + let (Some(raw), Some(key)) = (unsafe { read_jstring_utf8(env, json) }, unsafe { + read_jstring_utf8(env, field) + }) else { + return core::ptr::null_mut(); + }; + let Ok(val) = serde_json::from_str::(&raw) else { + return core::ptr::null_mut(); + }; + match val.get(&key).and_then(serde_json::Value::as_str) { + Some(text) => unsafe { new_jstring(env, text) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `json` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeJsonStringArrayLen( + env: JniEnvPtr, + _class: JClass, + json: JString, +) -> JInt { + let Some(raw) = (unsafe { read_jstring_utf8(env, json) }) else { + return 0; + }; + serde_json::from_str::>(&raw) + .map(|items| items.len().min(i32::MAX as usize) as JInt) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `json` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeJsonStringArrayGet( + env: JniEnvPtr, + _class: JClass, + json: JString, + index: JInt, +) -> JString { + let (Some(raw), Ok(idx)) = ( + unsafe { read_jstring_utf8(env, json) }, + usize::try_from(index), + ) else { + return core::ptr::null_mut(); + }; + let Ok(items) = serde_json::from_str::>(&raw) else { + return core::ptr::null_mut(); + }; + match items.get(idx) { + Some(item) => unsafe { new_jstring(env, item) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +/// +/// Plans a rollback `localStorage` write-back JSON payload. Returns `null` +/// while upgrade import is incomplete or any allowlisted local workspace has +/// an unresolved mount failure. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePlanLegacyLocalStorageWriteBack( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let plan = with_host_ref(handle, |host| host.plan_legacy_local_storage_writeback()).flatten(); + match plan { + Some(json) => unsafe { new_jstring(env, &json) }, + None => core::ptr::null_mut(), + } +} + +fn legacy_app_datastore_path(files_dir: &Path) -> std::path::PathBuf { + files_dir.join("datastore").join("affine.preferences_pb") +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s. +/// +/// Deletes a key from the `0.27.5` general app DataStore (`datastore/affine.preferences_pb`) +/// under its per-file lock. Succeeds without creating an empty file when absent. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeLegacyAppDataStoreDeleteKey( + env: JniEnvPtr, + _class: JClass, + files_dir: JString, + key: JString, +) -> JBoolean { + let (Some(dir), Some(k)) = (unsafe { read_jstring_utf8(env, files_dir) }, unsafe { + read_jstring_utf8(env, key) + }) else { + return 0; + }; + let path = legacy_app_datastore_path(Path::new(&dir)); + u8::from(delete_file_key(&path, &k).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `code` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsPermanentAuthErrorCode( + env: JniEnvPtr, + _class: JClass, + code: JString, +) -> JBoolean { + let Some(raw) = (unsafe { read_jstring_utf8(env, code) }) else { + return 0; + }; + u8::from(is_permanent_auth_error_code(&raw)) +} diff --git a/packages/frontend/hosts/android/src/lib.rs b/packages/frontend/hosts/android/src/lib.rs new file mode 100644 index 0000000000..b495bc5de9 --- /dev/null +++ b/packages/frontend/hosts/android/src/lib.rs @@ -0,0 +1,1400 @@ +#![deny(unsafe_code)] + +//! Thin Android host bridge for AFFiNE (`affine-android-host`): predictive back, +//! API 26+ Autofill, inset conversion, `SurfaceHolder` lifecycle, SQLite WAL, +//! DataStore `v1:` AES-GCM, legacy `localStorage` import/rollback, and JNI exports. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +#[cfg(target_os = "android")] +mod android_window; +pub mod autofill; +pub mod datastore; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +mod editor_fallback; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod editor_platform; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod editor_runtime; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod editor_selection; +mod ime; +pub mod native_islands; +pub mod pdf; +pub mod selection; +pub mod storage; +pub mod surface; +pub mod text_layout; + +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_bridge; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_editor; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_interaction; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_islands; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_shell; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_storage; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod runtime_root; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod shell_runtime; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub(crate) mod shell_workspace; + +pub use autofill::{ + AutofillEvent, AutofillFieldKind, AutofillFieldNode, AutofillRect, AutofillState, +}; +pub use pdf::{ + MAX_PDF_RENDER_DIM_PX, MAX_PDF_RENDER_PIXELS, PdfRenderError, argb8888_i32_to_rgba8, + argb8888_to_rgba8, pdf_page_cache_key, validate_pdf_page_request, +}; +pub use selection::{ + HandleGeometry, MagnifierState, RectF, SelectionHandleKind, SelectionOverlayState, + TeardropOrientation, TextDirection, +}; +pub use storage::{ + AndroidSqliteBridge, AndroidWorkspaceCatalog, LOCAL_WORKSPACE_LOCAL_STORAGE_KEY, +}; +pub use surface::{ + AndroidRenderBackend, DEFAULT_CLEAR_COLOR_ARGB, LogicalWindowInsets, SurfaceLifecycleState, + SurfacePresentError, physical_insets_to_logical_dp, +}; + +/// Legacy Capacitor Android WebView origin used for one-shot `localStorage` probing. +pub const LEGACY_ANDROID_ORIGIN: &str = "https://localhost"; + +/// Returns `true` when `key` matches the single authoritative `affine-legacy-import` +/// `localStorage` allowlist (including cloud/self-hosted workspace caches and bare `*-auth`). +pub fn is_allowed_legacy_local_storage_key(key: &str) -> bool { + affine_legacy_import::is_permitted_sentinel_entry_key(key) +} + +/// Minimum Android API level that provides `android.view.autofill.AutofillManager`. +pub const AUTOFILL_MIN_SDK_INT: u32 = 26; + +/// Returns `true` when Android `AutofillManager` APIs exist (`sdk_int >= 26`). +pub const fn should_expose_autofill(sdk_int: u32) -> bool { + sdk_int >= AUTOFILL_MIN_SDK_INT +} + +/// Android back navigation dispatch strategy by API level. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum BackDispatchMode { + /// API 24-32: legacy `Activity.onBackPressed()` single-step commit. + LegacyOnBackPressed = 0, + /// API 33: `OnBackInvokedCallback` single-step commit. + OnBackInvoked = 1, + /// API 34+: `OnBackAnimationCallback` four-phase predictive back. + OnBackAnimation = 2, +} + +/// Selects the Android back dispatch strategy for `sdk_int`. +pub const fn back_dispatch_mode(sdk_int: u32) -> BackDispatchMode { + if sdk_int >= 34 { + BackDispatchMode::OnBackAnimation + } else if sdk_int >= 33 { + BackDispatchMode::OnBackInvoked + } else { + BackDispatchMode::LegacyOnBackPressed + } +} + +/// Four-phase predictive back gesture protocol (plus legacy single-shot `Commit`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum BackGesturePhase { + Start = 0, + Progress = 1, + Cancel = 2, + Commit = 3, +} + +impl BackGesturePhase { + /// Converts a raw JNI integer code into a [`BackGesturePhase`]. + pub const fn from_code(code: i32) -> Option { + match code { + 0 => Some(Self::Start), + 1 => Some(Self::Progress), + 2 => Some(Self::Cancel), + 3 => Some(Self::Commit), + _ => None, + } + } +} + +/// Lifecycle state emitted by [`BackGestureMachine`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum BackGestureState { + Idle, + Active { progress: f32 }, + Committed, + Cancelled, +} + +/// Error returned when a back transition violates the four-phase contract. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BackGestureError { + AlreadyActive, + NotActive, + InvalidProgress, +} + +/// Deterministic four-phase state machine for Android back navigation. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BackGestureMachine { + state: BackGestureState, +} + +impl Default for BackGestureMachine { + fn default() -> Self { + Self::new() + } +} + +impl BackGestureMachine { + /// Creates a new idle back gesture state machine. + pub const fn new() -> Self { + Self { + state: BackGestureState::Idle, + } + } + + /// Returns the current gesture state. + pub const fn state(&self) -> BackGestureState { + self.state + } + + /// Applies one back event and returns the updated state. + pub fn transition( + &mut self, + phase: BackGesturePhase, + progress: f32, + ) -> Result { + if !progress.is_finite() { + return Err(BackGestureError::InvalidProgress); + } + let clamped = progress.clamp(0.0, 1.0); + match (self.state, phase) { + ( + BackGestureState::Idle | BackGestureState::Committed | BackGestureState::Cancelled, + BackGesturePhase::Start, + ) => { + self.state = BackGestureState::Active { progress: clamped }; + Ok(self.state) + } + (BackGestureState::Active { .. }, BackGesturePhase::Start) => { + Err(BackGestureError::AlreadyActive) + } + (BackGestureState::Active { .. }, BackGesturePhase::Progress) => { + self.state = BackGestureState::Active { progress: clamped }; + Ok(self.state) + } + (BackGestureState::Active { .. }, BackGesturePhase::Cancel) => { + self.state = BackGestureState::Cancelled; + Ok(self.state) + } + (_, BackGesturePhase::Commit) => { + self.state = BackGestureState::Committed; + Ok(self.state) + } + ( + BackGestureState::Idle | BackGestureState::Committed | BackGestureState::Cancelled, + BackGesturePhase::Progress | BackGesturePhase::Cancel, + ) => Err(BackGestureError::NotActive), + } + } +} + +/// Positive sentinel payload parsed from the legacy Android `https://localhost` +/// `localStorage` probe. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LegacyLocalStorageSnapshot { + pub origin: String, + pub length: usize, + pub keys: Vec, + pub entries: BTreeMap, + #[serde(default, rename = "removedKeys")] + pub removed_keys: Vec, + #[serde(default, rename = "idbTouchCount")] + pub idb_touch_count: u32, +} + +/// Error returned while validating a legacy `localStorage` sentinel payload. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LegacyProbeError { + InvalidJson(String), + UnexpectedOrigin(String), + IndexedDbTouched(u32), + InconsistentSentinel(String), +} + +/// Upgrade import gate distinguishing genuine fresh installs from probe failures. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum LegacyUpgradeImportState { + #[default] + Pending, + FreshInstall, + Imported(LegacyLocalStorageSnapshot), + Failed(LegacyProbeError), +} + +impl LegacyUpgradeImportState { + /// Returns `true` only when the probe positively confirmed zero allowlisted + /// AFFiNE keys on `https://localhost` with zero IndexedDB touches. + pub const fn can_create_default_workspace(&self) -> bool { + matches!(self, Self::FreshInstall) + } +} + +pub use storage::filter_legacy_local_storage_probe_json; + +/// Parses and validates a legacy `https://localhost` `localStorage` probe JSON +/// payload matching the cross-slice `WebViewStorageSentinel` contract: +/// 1. `origin == "https://localhost"` +/// 2. `idbTouchCount == 0` (Iron Rule F12) +/// 3. `keys.len() == length` (`keys` holds every key name in `localStorage`) +/// 4. `keys` has no duplicates +/// 5. every key in `entries` is present in `keys` and satisfies the allowlist +/// 6. every key in `keys` that satisfies the allowlist is present in `entries` +/// +/// Pass an empty `allowed_keys` slice to apply the full `0.27.5` allowlist rules +/// (`is_allowed_legacy_local_storage_key`), or a non-empty slice for an explicit subset. +pub fn parse_legacy_local_storage_probe( + payload_json: &str, + allowed_keys: &[&str], +) -> Result { + parse_legacy_local_storage_probe_with_flag(payload_json, allowed_keys).map(|(snap, _)| snap) +} + +fn parse_legacy_local_storage_probe_with_flag( + payload_json: &str, + allowed_keys: &[&str], +) -> Result<(LegacyLocalStorageSnapshot, bool), LegacyProbeError> { + let trimmed = payload_json.trim(); + let unwrapped_owned: String; + let effective_json = if trimmed.starts_with('"') { + unwrapped_owned = serde_json::from_str::(trimmed) + .map_err(|err| LegacyProbeError::InvalidJson(err.to_string()))?; + unwrapped_owned.as_str() + } else { + trimmed + }; + let mut raw: LegacyLocalStorageSnapshot = serde_json::from_str(effective_json) + .map_err(|err| LegacyProbeError::InvalidJson(err.to_string()))?; + + if raw.idb_touch_count > 0 { + return Err(LegacyProbeError::IndexedDbTouched(raw.idb_touch_count)); + } + + if allowed_keys.is_empty() { + use affine_legacy_import::sentinel::{ + SentinelEvaluation, SentinelFailureReason, WebViewStorageSentinel, evaluate_sentinel, + }; + let sentinel = WebViewStorageSentinel { + origin: raw.origin.clone(), + length: raw.length, + keys: raw.keys.clone(), + entries: raw.entries.clone(), + }; + match evaluate_sentinel(&sentinel, &[LEGACY_ANDROID_ORIGIN]) { + eval @ (SentinelEvaluation::ValidEmpty | SentinelEvaluation::ValidPopulated { .. }) => { + let has_allowlisted_keys = matches!( + eval, + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true + } + ); + raw.keys.sort(); + raw.idb_touch_count = 0; + return Ok((raw, has_allowlisted_keys)); + } + SentinelEvaluation::UnreadyOrMismatch(reason) => { + return Err(match reason { + SentinelFailureReason::EmptyOrigin => { + LegacyProbeError::UnexpectedOrigin(raw.origin) + } + SentinelFailureReason::OriginMismatch { actual } => { + LegacyProbeError::UnexpectedOrigin(actual) + } + SentinelFailureReason::LengthMismatch { + reported_length, + observed_keys, + } => LegacyProbeError::InconsistentSentinel(format!( + "keys.len() ({observed_keys}) != localStorage.length ({reported_length})" + )), + SentinelFailureReason::DuplicateKeys => { + LegacyProbeError::InconsistentSentinel("duplicate key in sentinel".into()) + } + SentinelFailureReason::EntryKeyMissingFromKeyList { key } => { + LegacyProbeError::InconsistentSentinel(format!( + "entry key {key:?} missing from sentinel keys" + )) + } + SentinelFailureReason::DisallowedEntryKey { key } => { + LegacyProbeError::InconsistentSentinel(format!( + "non-allowlisted key in sentinel entries: {key:?}" + )) + } + SentinelFailureReason::MissingAllowlistedEntry { key } => { + LegacyProbeError::InconsistentSentinel(format!( + "allowlisted key {key:?} present in keys but missing from entries" + )) + } + }); + } + } + } + + if raw.origin != LEGACY_ANDROID_ORIGIN { + return Err(LegacyProbeError::UnexpectedOrigin(raw.origin)); + } + if raw.keys.len() != raw.length { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "keys.len() ({}) != localStorage.length ({})", + raw.keys.len(), + raw.length + ))); + } + + let custom_allow: BTreeSet<&str> = allowed_keys.iter().copied().collect(); + let mut seen_keys = BTreeSet::new(); + for k in &raw.keys { + if !seen_keys.insert(k.as_str()) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "duplicate key in sentinel: {k:?}" + ))); + } + } + + let mut entries = BTreeMap::new(); + for (k, v) in raw.entries { + if !seen_keys.contains(k.as_str()) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "entry key {k:?} missing from sentinel keys" + ))); + } + if !custom_allow.contains(k.as_str()) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "non-allowlisted key in sentinel entries: {k:?}" + ))); + } + entries.insert(k, v); + } + + for k in &seen_keys { + if custom_allow.contains(*k) && !entries.contains_key(*k) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "allowlisted key {k:?} present in keys but missing from entries" + ))); + } + } + + let mut keys: Vec = seen_keys.into_iter().map(str::to_string).collect(); + keys.sort(); + + let has_allowlisted_keys = !entries.is_empty(); + Ok(( + LegacyLocalStorageSnapshot { + origin: raw.origin, + length: raw.length, + keys, + entries, + removed_keys: raw.removed_keys, + idb_touch_count: 0, + }, + has_allowlisted_keys, + )) +} + +/// Verifies a rollback `writeBackLegacyLocalStorage` read-back sentinel against +/// expected `set_entries` and `remove_keys`, ensuring zero IndexedDB touches. +/// +/// Rejects removing `affine-local-workspace` (per `local.ts:126-129`, empty +/// local workspace lists must be written as `"[]"` rather than removed). +pub fn verify_legacy_writeback_result( + expected_set: &BTreeMap, + expected_remove: &[String], + readback_json: &str, +) -> Result<(), LegacyProbeError> { + if expected_remove + .iter() + .any(|k| k == LOCAL_WORKSPACE_LOCAL_STORAGE_KEY) + { + return Err(LegacyProbeError::InconsistentSentinel( + "affine-local-workspace must be written as \"[]\", never removed".into(), + )); + } + let snapshot = parse_legacy_local_storage_probe(readback_json, &[])?; + for (key, expected_val) in expected_set { + if !is_allowed_legacy_local_storage_key(key) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "expected set key {key:?} is not allowlisted" + ))); + } + if snapshot.entries.get(key) != Some(expected_val) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "write-back readback mismatch for key {key:?}" + ))); + } + } + for key in expected_remove { + if !is_allowed_legacy_local_storage_key(key) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "expected remove key {key:?} is not allowlisted" + ))); + } + if snapshot.entries.contains_key(key) || snapshot.keys.iter().any(|k| k == key) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "removed key {key:?} still present in readback" + ))); + } + if !snapshot.removed_keys.iter().any(|k| k == key) { + return Err(LegacyProbeError::InconsistentSentinel(format!( + "removed key {key:?} not confirmed in removedKeys" + ))); + } + } + Ok(()) +} + +/// Default root destination route for the Android host navigation stack. +pub const DEFAULT_ROOT_DESTINATION: &str = "workspace/home"; + +/// Destination route stack driving Android back navigation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BackNavigationState { + destinations: Vec, +} + +impl Default for BackNavigationState { + fn default() -> Self { + Self::new() + } +} + +impl BackNavigationState { + /// Creates a navigation stack seeded with the root destination (`depth == 0`). + pub fn new() -> Self { + Self { + destinations: vec![DEFAULT_ROOT_DESTINATION.to_string()], + } + } + + /// Returns the currently active destination route. + pub fn current_destination(&self) -> Option<&str> { + self.destinations.last().map(String::as_str) + } + + /// Pushes a non-empty destination route onto the navigation stack. + pub fn push_destination(&mut self, route: impl Into) -> bool { + let route = route.into(); + if route.is_empty() { + return false; + } + if self.destinations.is_empty() { + self.destinations.push(DEFAULT_ROOT_DESTINATION.to_string()); + } + self.destinations.push(route); + true + } + + /// Pops the top non-root destination, returning `None` when already at root. + pub fn pop_destination(&mut self) -> Option { + if self.destinations.len() > 1 { + self.destinations.pop() + } else { + None + } + } + + /// Returns the number of poppable non-root destinations. + pub fn depth(&self) -> u32 { + self.destinations.len().saturating_sub(1) as u32 + } + + /// Rebuilds synthetic stack entries to match an explicit poppable depth. + pub fn set_depth(&mut self, depth: u32) { + self.destinations.clear(); + self.destinations.push(DEFAULT_ROOT_DESTINATION.to_string()); + for level in 1..=depth { + self.destinations.push(format!("route/{level}")); + } + } +} + +/// Pure safe-Rust state held behind an Android JNI host handle. +#[derive(Debug)] +pub struct AndroidHostState { + pub back_gesture: BackGestureMachine, + pub back_navigation: BackNavigationState, + pub insets: LogicalWindowInsets, + pub surface: SurfaceLifecycleState, + pub selection: SelectionOverlayState, + pub text_layout: text_layout::TextLayoutMetrics, + pub selection_drag_anchor_utf16: Option, + pub selection_drag_initial_handle: SelectionHandleKind, + pub autofill: AutofillState, + pub upgrade_import: LegacyUpgradeImportState, + pub workspace_catalog: AndroidWorkspaceCatalog, + /// Parsed `affine-legacy-import` snapshot holding canonical `preserved_raw_entries` + /// (single source of truth for untouched malformed `affine-local-workspace` write-back). + pub legacy_snapshot: Option, + /// Local workspace IDs that failed `connect_workspace` during bootstrap or retry. + pub failed_local_workspace_mounts: BTreeSet, + pub sqlite: AndroidSqliteBridge, + pub utf16_text: Vec, + pub selected_start: usize, + pub selected_len: usize, + pub composing_start: Option, + pub composing_len: usize, + pub islands: native_islands::AndroidNativeIslandsState, +} + +impl Default for AndroidHostState { + fn default() -> Self { + Self { + back_gesture: BackGestureMachine::new(), + back_navigation: BackNavigationState::new(), + insets: LogicalWindowInsets::default(), + surface: SurfaceLifecycleState::new(), + selection: SelectionOverlayState::new(), + text_layout: text_layout::TextLayoutMetrics::default(), + selection_drag_anchor_utf16: None, + selection_drag_initial_handle: SelectionHandleKind::None, + autofill: AutofillState::default(), + upgrade_import: LegacyUpgradeImportState::Pending, + workspace_catalog: AndroidWorkspaceCatalog::default(), + legacy_snapshot: None, + failed_local_workspace_mounts: BTreeSet::new(), + sqlite: AndroidSqliteBridge::new(), + utf16_text: Vec::new(), + selected_start: 0, + selected_len: 0, + composing_start: None, + composing_len: 0, + islands: native_islands::AndroidNativeIslandsState::default(), + } + } +} + +impl AndroidHostState { + pub fn new() -> Self { + Self::default() + } + + /// Returns `true` once the legacy `localStorage` probe has completed + /// (either `Imported` or `FreshInstall`), guarding local workspace opens. + pub const fn is_local_workspace_import_ready(&self) -> bool { + matches!( + self.upgrade_import, + LegacyUpgradeImportState::Imported(_) | LegacyUpgradeImportState::FreshInstall + ) + } + + /// Pushes a destination route onto the host navigation stack. + pub fn push_back_destination(&mut self, route: impl Into) -> bool { + self.back_navigation.push_destination(route) + } + + /// Returns the currently active destination route. + pub fn current_back_destination(&self) -> Option<&str> { + self.back_navigation.current_destination() + } + + /// Sets the number of poppable navigation entries on the back stack. + pub fn set_back_stack_depth(&mut self, depth: u32) { + self.back_navigation.set_depth(depth); + } + + /// Returns the remaining number of poppable navigation entries. + pub fn back_stack_depth(&self) -> u32 { + self.back_navigation.depth() + } + + /// Sets whether at least one back destination exists (`0` or `1` stack depth). + pub fn set_has_back_destination(&mut self, has_destination: bool) { + self.back_navigation.set_depth(u32::from(has_destination)); + } + + /// Returns `true` when at least one back destination can be popped. + pub fn has_back_destination(&self) -> bool { + self.back_navigation.depth() > 0 + } + + /// Handles a back gesture phase; returns `true` only when the host consumed + /// the event. Each `Commit` atomically pops the top destination from + /// `back_navigation` and returns `false` at the root so Android delegates to + /// system exit. `Cancel` leaves the active destination unchanged. + pub fn handle_back_phase(&mut self, phase: BackGesturePhase, progress: f32) -> bool { + if phase == BackGesturePhase::Commit { + let _ = self.back_gesture.transition(phase, progress); + return self.back_navigation.pop_destination().is_some(); + } + self.back_gesture.transition(phase, progress).is_ok() + } + + /// Imports a legacy `https://localhost` `localStorage` probe result, updating + /// the upgrade gate and allowlisted workspace catalog (never scanning disk). + pub fn import_legacy_local_storage_probe( + &mut self, + payload_json: &str, + allowed_keys: &[&str], + ) -> Result<&LegacyLocalStorageSnapshot, LegacyProbeError> { + match parse_legacy_local_storage_probe_with_flag(payload_json, allowed_keys) { + Ok((snapshot, has_allowlisted_keys)) => { + let parsed_legacy = + affine_legacy_import::parse_allowlisted_entries(&snapshot.entries); + self.workspace_catalog = + AndroidWorkspaceCatalog::from_ids(parsed_legacy.local_workspace_ids.clone()); + self.legacy_snapshot = Some(parsed_legacy); + let _ = self + .sqlite + .evict_unlisted_local_workspaces(&self.workspace_catalog); + self.failed_local_workspace_mounts + .retain(|id| self.workspace_catalog.contains(id)); + + if !has_allowlisted_keys { + self.upgrade_import = LegacyUpgradeImportState::FreshInstall; + } else { + self.upgrade_import = LegacyUpgradeImportState::Imported(snapshot); + } + match &self.upgrade_import { + LegacyUpgradeImportState::Imported(snap) => Ok(snap), + LegacyUpgradeImportState::FreshInstall => { + static EMPTY: std::sync::OnceLock = + std::sync::OnceLock::new(); + Ok(EMPTY.get_or_init(|| LegacyLocalStorageSnapshot { + origin: LEGACY_ANDROID_ORIGIN.to_string(), + length: 0, + keys: Vec::new(), + entries: BTreeMap::new(), + removed_keys: Vec::new(), + idb_touch_count: 0, + })) + } + _ => unreachable!(), + } + } + Err(err) => { + self.upgrade_import = LegacyUpgradeImportState::Failed(err.clone()); + Err(err) + } + } + } + + /// Records the mount outcome for an allowlisted local workspace ID. + pub fn record_local_workspace_mount_outcome(&mut self, space_id: &str, connected: bool) { + if connected { + self.failed_local_workspace_mounts.remove(space_id); + } else if self.workspace_catalog.contains(space_id) { + self.failed_local_workspace_mounts + .insert(space_id.to_string()); + } + } + + /// Returns `true` when any allowlisted local workspace failed to mount or has + /// not yet been connected. + pub fn has_unresolved_local_workspace_mounts(&self) -> bool { + if !self.failed_local_workspace_mounts.is_empty() { + return true; + } + if !self.is_local_workspace_import_ready() { + return false; + } + self.workspace_catalog + .ids() + .iter() + .any(|id| !self.sqlite.is_local_workspace_connected(id)) + } + + /// Returns the preserved raw `affine-local-workspace` string (if malformed/non-array) + /// from `affine-legacy-import`'s `preserved_raw_entries`. + pub fn preserved_local_workspace_raw(&self) -> Option<&str> { + self.legacy_snapshot + .as_ref() + .and_then(|s| { + s.preserved_raw_entries + .get(LOCAL_WORKSPACE_LOCAL_STORAGE_KEY) + }) + .map(String::as_str) + } + + /// Plans a rollback `localStorage` write-back JSON payload (`setEntries` + + /// `removeKeys`). Returns `None` while upgrade import is incomplete or any + /// allowlisted local workspace has an unresolved mount failure. + pub fn plan_legacy_local_storage_writeback(&self) -> Option { + if !self.is_local_workspace_import_ready() || self.has_unresolved_local_workspace_mounts() { + return None; + } + let mut set_entries = BTreeMap::new(); + if let Some(snapshot) = &self.legacy_snapshot { + for (k, v) in &snapshot.preserved_raw_entries { + set_entries.insert(k.clone(), v.clone()); + } + } + if !self.workspace_catalog.ids().is_empty() { + set_entries.insert( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string(), + serde_json::to_string(self.workspace_catalog.ids()).ok()?, + ); + } else if let Some(raw) = self.preserved_local_workspace_raw() { + set_entries.insert( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string(), + raw.to_string(), + ); + } else if matches!(self.upgrade_import, LegacyUpgradeImportState::Imported(_)) { + set_entries.insert( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string(), + "[]".to_string(), + ); + } + let plan = serde_json::json!({ + "setEntries": set_entries, + "removeKeys": Vec::::new(), + }); + Some(plan.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn back_dispatch_mode_and_effective_ime_insets_follow_api_and_nav_bar_rules() { + let mode_cases = [ + (24_u32, BackDispatchMode::LegacyOnBackPressed), + (25, BackDispatchMode::LegacyOnBackPressed), + (32, BackDispatchMode::LegacyOnBackPressed), + (33, BackDispatchMode::OnBackInvoked), + (34, BackDispatchMode::OnBackAnimation), + (35, BackDispatchMode::OnBackAnimation), + ]; + for (sdk_int, expected) in mode_cases { + assert_eq!(back_dispatch_mode(sdk_int), expected); + } + + let inset_cases = [ + // Keyboard taller than navigation bar -> deducts safe_bottom to avoid double subtraction. + ((72, 900, 3.0_f32), 276.0_f32), + // Keyboard hidden (ime_bottom == 0) -> clamps to 0. + ((72, 0, 3.0_f32), 0.0_f32), + // Keyboard inset smaller than nav bar -> clamps to 0. + ((72, 48, 3.0_f32), 0.0_f32), + ]; + for ((nav_px, ime_px, density), expected_effective) in inset_cases { + let insets = physical_insets_to_logical_dp(0, 0, nav_px, 0, ime_px, density); + assert_eq!(insets.effective_ime_above_nav_bar(), expected_effective); + } + + // Real destination navigation stack pops route-by-route, preserves route on Cancel, + // and returns false at root destination. + let mut host = AndroidHostState::new(); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + assert!(host.push_back_destination("doc/welcome")); + assert!(host.push_back_destination("doc/settings")); + assert_eq!(host.back_stack_depth(), 2); + assert_eq!(host.current_back_destination(), Some("doc/settings")); + assert!(host.handle_back_phase(BackGesturePhase::Start, 0.0)); + assert!(host.handle_back_phase(BackGesturePhase::Progress, 0.4)); + assert!(host.handle_back_phase(BackGesturePhase::Cancel, 0.0)); + assert_eq!(host.current_back_destination(), Some("doc/settings")); + assert_eq!(host.back_stack_depth(), 2); + assert!(host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!(host.current_back_destination(), Some("doc/welcome")); + assert_eq!(host.back_stack_depth(), 1); + assert!(host.handle_back_phase(BackGesturePhase::Start, 0.0)); + assert!(host.handle_back_phase(BackGesturePhase::Progress, 0.6)); + assert!(host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + assert_eq!(host.back_stack_depth(), 0); + assert!(!host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + } + + #[test] + fn autofill_gate_enforces_api_26_floor() { + let cases = [ + (21, false), + (24, false), + (25, false), + (26, true), + (33, true), + (35, true), + ]; + for (sdk_int, expected) in cases { + assert_eq!(should_expose_autofill(sdk_int), expected); + } + } + + #[test] + fn back_gesture_supports_four_phase_predictive_and_legacy_single_commit() { + let mut machine = BackGestureMachine::new(); + assert_eq!(machine.state(), BackGestureState::Idle); + assert_eq!( + machine.transition(BackGesturePhase::Progress, 0.2), + Err(BackGestureError::NotActive) + ); + assert_eq!( + machine.transition(BackGesturePhase::Cancel, 0.0), + Err(BackGestureError::NotActive) + ); + assert_eq!( + machine.transition(BackGesturePhase::Commit, 1.0), + Ok(BackGestureState::Committed) + ); + assert_eq!( + machine.transition(BackGesturePhase::Start, 0.0), + Ok(BackGestureState::Active { progress: 0.0 }) + ); + assert_eq!( + machine.transition(BackGesturePhase::Start, 0.1), + Err(BackGestureError::AlreadyActive) + ); + assert_eq!( + machine.transition(BackGesturePhase::Progress, 1.5), + Ok(BackGestureState::Active { progress: 1.0 }) + ); + assert_eq!( + machine.transition(BackGesturePhase::Cancel, 0.0), + Ok(BackGestureState::Cancelled) + ); + assert_eq!( + machine.transition(BackGesturePhase::Commit, 1.0), + Ok(BackGestureState::Committed) + ); + } + + #[test] + fn physical_insets_convert_to_logical_dp_including_ldpi_density() { + let cases = [ + ( + (120, 0, 72, 0, 900, 3.0_f32), + LogicalWindowInsets { + safe_top: 40.0, + safe_right: 0.0, + safe_bottom: 24.0, + safe_left: 0.0, + ime_bottom: 300.0, + }, + ), + ( + (18, 0, 12, 0, 162, 0.75_f32), + LogicalWindowInsets { + safe_top: 24.0, + safe_right: 0.0, + safe_bottom: 16.0, + safe_left: 0.0, + ime_bottom: 216.0, + }, + ), + ( + (-10, 0, 20, 40, 10, 0.0_f32), + LogicalWindowInsets { + safe_top: 0.0, + safe_right: 0.0, + safe_bottom: 20.0, + safe_left: 40.0, + ime_bottom: 10.0, + }, + ), + ]; + + for ((top, right, bottom, left, ime, density), expected) in cases { + assert_eq!( + physical_insets_to_logical_dp(top, right, bottom, left, ime, density), + expected + ); + } + } + + #[test] + fn legacy_local_storage_probe_distinguishes_fresh_install_failure_and_idb_violation() { + // Real 0.27.5 allowlist rules (exact + dynamic keys) and rejection of fictional keys. + for allowed in [ + "affine-local-workspace", + "global-state:serverList", + "global-cache:i18n_lng", + "last_workspace_id", + "last_workspace_flavour", + "affine-settings", + "theme", + "global-state:serverConfig:self-host-1", + "global-state:cloud-auth", + "cloud-auth", + "affine-flag:enable_ai", + "global-state:affine-flag:enable_ai", + ] { + assert!( + is_allowed_legacy_local_storage_key(allowed), + "expected allowed key: {allowed}" + ); + } + for rejected in [ + "affine_theme", + "affine_server_url", + "secret_token", + "global-state:serverConfig:", + "global-state:-auth", + "-auth", + "affine-flag:", + "global-state:affine-flag:", + ] { + assert!( + !is_allowed_legacy_local_storage_key(rejected), + "expected rejected key: {rejected}" + ); + } + + let mut host = AndroidHostState::new(); + assert!(!host.upgrade_import.can_create_default_workspace()); + + // Probe failure blocks default workspace creation. + assert!(host.import_legacy_local_storage_probe("null", &[]).is_err()); + assert!(!host.upgrade_import.can_create_default_workspace()); + + // Sentinel consistency failures: keys.len() != length, duplicate keys, non-allowlisted entry, + // entry not in keys, and allowlisted key in keys missing from entries. + let bad_payloads = [ + r#"{"origin":"https://localhost","length":0,"keys":["theme"],"entries":{"theme":"dark"},"idbTouchCount":0}"#, + r#"{"origin":"https://localhost","length":2,"keys":["theme"],"entries":{"theme":"dark"},"idbTouchCount":0}"#, + r#"{"origin":"https://localhost","length":2,"keys":["theme","theme"],"entries":{"theme":"dark"},"idbTouchCount":0}"#, + r#"{"origin":"https://localhost","length":1,"keys":["affine_theme"],"entries":{"affine_theme":"dark"},"idbTouchCount":0}"#, + r#"{"origin":"https://localhost","length":0,"keys":[],"entries":{"theme":"dark"},"idbTouchCount":0}"#, + r#"{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{},"idbTouchCount":0}"#, + ]; + for bad in bad_payloads { + assert!( + matches!( + host.import_legacy_local_storage_probe(bad, &[]), + Err(LegacyProbeError::InconsistentSentinel(_)) + ), + "expected InconsistentSentinel for {bad}" + ); + assert!(!host.upgrade_import.can_create_default_workspace()); + } + + // Any IndexedDB touch is rejected. + let idb_payload = r#"{ + "origin": "https://localhost", + "length": 1, + "keys": ["affine-local-workspace"], + "entries": { "affine-local-workspace": "[\"ws-1\"]" }, + "idbTouchCount": 1 + }"#; + assert_eq!( + host.import_legacy_local_storage_probe(idb_payload, &[]), + Err(LegacyProbeError::IndexedDbTouched(1)) + ); + assert!(!host.upgrade_import.can_create_default_workspace()); + + // Genuine fresh install with an unrelated non-allowlisted third-party key (length == 1, keys == ["__cap_noise__"], entries == {}). + let fresh_with_noise = r#"{ + "origin": "https://localhost", + "length": 1, + "keys": ["__cap_noise__"], + "entries": {}, + "idbTouchCount": 0 + }"#; + host.import_legacy_local_storage_probe(fresh_with_noise, &[]) + .unwrap(); + assert!(host.upgrade_import.can_create_default_workspace()); + + // Existing user who deleted all local workspaces still has "affine-local-workspace": "[]" -> Imported, NOT FreshInstall. + let deleted_all_payload = r#"{ + "origin": "https://localhost", + "length": 1, + "keys": ["affine-local-workspace"], + "entries": { "affine-local-workspace": "[]" }, + "idbTouchCount": 0 + }"#; + host.import_legacy_local_storage_probe(deleted_all_payload, &[]) + .unwrap(); + assert!(!host.upgrade_import.can_create_default_workspace()); + assert!(host.workspace_catalog.ids().is_empty()); + + // Malformed affine-local-workspace JSON ("{broken") mounts zero workspaces + // while losslessly preserving the raw string for untouched rollback write-back. + let corrupt_ws_payload = r#"{ + "origin": "https://localhost", + "length": 1, + "keys": ["affine-local-workspace"], + "entries": { "affine-local-workspace": "{broken" }, + "idbTouchCount": 0 + }"#; + host.import_legacy_local_storage_probe(corrupt_ws_payload, &[]) + .unwrap(); + assert!(!host.upgrade_import.can_create_default_workspace()); + assert!(host.workspace_catalog.ids().is_empty()); + assert_eq!(host.preserved_local_workspace_raw(), Some("{broken")); + let corrupt_plan = host + .plan_legacy_local_storage_writeback() + .expect("corrupt list rollback plan"); + assert!(corrupt_plan.contains(r#""affine-local-workspace":"{broken""#)); + + // Upgrade with allowlisted workspaces + dynamic keys + 1 unrelated noise key (length == 4, keys.len() == 4). + let upgrade_payload = r#"{ + "origin": "https://localhost", + "length": 4, + "keys": ["__cap_noise__", "affine-local-workspace", "global-state:serverConfig:self-host", "theme"], + "entries": { + "affine-local-workspace": "[\"ws-b\",\"ws-a\"]", + "global-state:serverConfig:self-host": "{\"url\":\"https://self.example\"}", + "theme": "dark" + }, + "removedKeys": ["last_workspace_id"], + "idbTouchCount": 0 + }"#; + let snap = host + .import_legacy_local_storage_probe(upgrade_payload, &[]) + .unwrap(); + assert_eq!( + snap.keys, + vec![ + "__cap_noise__", + "affine-local-workspace", + "global-state:serverConfig:self-host", + "theme" + ] + ); + assert!(!snap.entries.contains_key("__cap_noise__")); + assert!(!host.upgrade_import.can_create_default_workspace()); + assert_eq!( + host.workspace_catalog.ids(), + &["ws-b".to_string(), "ws-a".to_string()] + ); + + // Rollback write-back verification checks setEntries + removeKeys and forbids removing affine-local-workspace. + let mut expected_set = BTreeMap::new(); + expected_set.insert( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string(), + r#"["ws-b","ws-a"]"#.to_string(), + ); + expected_set.insert("theme".to_string(), "dark".to_string()); + let expected_remove = vec!["last_workspace_id".to_string()]; + assert!( + verify_legacy_writeback_result(&expected_set, &expected_remove, upgrade_payload) + .is_ok() + ); + assert!( + verify_legacy_writeback_result( + &expected_set, + &[LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string()], + upgrade_payload + ) + .is_err() + ); + assert!( + verify_legacy_writeback_result(&expected_set, &["theme".to_string()], upgrade_payload) + .is_err() + ); + } + + #[test] + #[allow(unsafe_code)] + fn jni_bridge_lifecycle_negative_tbi_handle_and_utf16_ime_contract() { + use core::ffi::c_void; + + const GET_STRING_LENGTH_INDEX: usize = 164; + const GET_STRING_CHARS_INDEX: usize = 165; + const RELEASE_STRING_CHARS_INDEX: usize = 166; + + struct FakeJString { + units: Vec, + } + + unsafe extern "C" fn fake_get_string_length( + _env: jni_bridge::JniEnvPtr, + string: jni_bridge::JString, + ) -> jni_bridge::JInt { + if string.is_null() { + return 0; + } + let s = unsafe { &*(string as *const FakeJString) }; + s.units.len() as jni_bridge::JInt + } + + unsafe extern "C" fn fake_get_string_chars( + _env: jni_bridge::JniEnvPtr, + string: jni_bridge::JString, + is_copy: *mut jni_bridge::JBoolean, + ) -> *const u16 { + if !is_copy.is_null() { + unsafe { *is_copy = 0 }; + } + if string.is_null() { + return core::ptr::null(); + } + let s = unsafe { &*(string as *const FakeJString) }; + s.units.as_ptr() + } + + unsafe extern "C" fn fake_release_string_chars( + _env: jni_bridge::JniEnvPtr, + _string: jni_bridge::JString, + _chars: *const u16, + ) { + } + + let mut vtable = [core::ptr::null::(); 170]; + vtable[GET_STRING_LENGTH_INDEX] = fake_get_string_length as *const () as *const c_void; + vtable[GET_STRING_CHARS_INDEX] = fake_get_string_chars as *const () as *const c_void; + vtable[RELEASE_STRING_CHARS_INDEX] = + fake_release_string_chars as *const () as *const c_void; + let mut env_ptr: *const *const c_void = vtable.as_ptr(); + let env: jni_bridge::JniEnvPtr = (&mut env_ptr as *mut *const *const c_void).cast(); + + let null = core::ptr::null_mut(); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeShouldExposeAutofill( + env, null, 25 + ), + 0 + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeShouldExposeAutofill( + env, null, 26 + ), + 1 + ); + + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick(env, null, 0, 1), + 0 + ); + + let pos_handle = + jni_shell::Java_app_affine_pro_host_NativeBridge_nativeCreateHost(env, null); + assert_ne!(pos_handle, 0); + + let neg_tbi_handle: i64 = -0x4bff_ff85_0000_1000_i64; + assert!(neg_tbi_handle < 0); + jni_bridge::insert_test_host(neg_tbi_handle, AndroidHostState::new()); + + let mut fake_surface_tag: u8 = 1; + let fake_surface = (&mut fake_surface_tag as *mut u8).cast::(); + + for handle in [pos_handle, neg_tbi_handle] { + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceCreated( + env, + null, + handle, + fake_surface, + ); + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceChanged( + env, null, handle, 1, 1080, 2400, + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeIsSurfaceReady( + env, null, handle + ), + 1 + ); + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx( + env, null, handle, 96, 0, 48, 0, 648, 3.0, + ); + let clear_argb = jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick( + env, null, handle, 16_666_667, + ); + assert_eq!(clear_argb as u32, DEFAULT_CLEAR_COLOR_ARGB); + + // Surface destroyed -> ticks return 0 and pending frame stays queued. + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceDestroyed( + env, null, handle, + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick( + env, null, handle, 33_333_334 + ), + 0 + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeHasPendingFrame( + env, null, handle + ), + 1 + ); + + // Recreate surface -> generation increments to 2 and frame resumes. + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceCreated( + env, + null, + handle, + fake_surface, + ); + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceChanged( + env, null, handle, 1, 1080, 2400, + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceGeneration( + env, null, handle + ), + 2 + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick( + env, null, handle, 50_000_000 + ) as u32, + DEFAULT_CLEAR_COLOR_ARGB + ); + + // Back gesture root check. + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnBackGesturePhase( + env, null, handle, 3, 1.0 + ), + 0 + ); + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeSetHasBackDestination( + env, null, handle, 1, + ); + assert_eq!( + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnBackGesturePhase( + env, null, handle, 3, 1.0 + ), + 1 + ); + + // Real UTF-16 JNI string decoding + surrogate-pair safe deletion. + let mut zhong = FakeJString { + units: "中".encode_utf16().collect(), + }; + let mut wen_emoji = FakeJString { + units: "文😀".encode_utf16().collect(), + }; + unsafe { + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnCommitText( + env, + null, + handle, + (&mut zhong as *mut FakeJString).cast(), + 1, + ); + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnCommitText( + env, + null, + handle, + (&mut wen_emoji as *mut FakeJString).cast(), + 1, + ); + assert_eq!(jni_bridge::snapshot_text(handle).as_deref(), Some("中文😀")); + } + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeOnDeleteSurroundingText( + env, null, handle, 1, 0, + ); + assert_eq!(jni_bridge::snapshot_text(handle).as_deref(), Some("中文")); + + jni_bridge::Java_app_affine_pro_host_NativeBridge_nativeDestroyHost(env, null, handle); + assert_eq!(jni_bridge::snapshot_text(handle), None); + } + } + + #[test] + fn single_line_vertical_drag_beyond_half_line_never_flips_handle_or_loupe() { + let mut host = AndroidHostState::new(); + host.text_layout = crate::text_layout::TextLayoutMetrics::for_viewport(1080.0, 3.0); + host.selection.set_viewport(1080.0, 2400.0, 3.0); + let text: Vec = "Hello world".encode_utf16().collect(); + host.commit_text_utf16(&text, 1); + host.set_selection(6, 11); + + let initial_end_x = host.selection.end_handle.tip_x; + let end_cx = host.selection.end_handle.center_x; + let end_cy = host.selection.end_handle.center_y; + assert_eq!( + host.begin_selection_handle_drag(end_cx, end_cy), + SelectionHandleKind::End + ); + + for dy in [-43.0_f32, -60.0, -120.0, 0.0, 43.0, 120.0, 0.0] { + assert!(host.update_selection_handle_drag(end_cx, end_cy + dy)); + assert_eq!( + host.selection_range(), + (6, 11), + "selection must remain [6, 11) at dy={dy}" + ); + assert_eq!( + host.selection.active_drag, + SelectionHandleKind::End, + "active_drag must remain End at dy={dy}" + ); + assert!( + (host.selection.magnifier.anchor_x - initial_end_x).abs() < 0.01, + "magnifier anchor_x ({}) must stay at right end ({initial_end_x}) at dy={dy}", + host.selection.magnifier.anchor_x + ); + } + } + + #[test] + fn delegated_sentinel_handles_filtered_noise_upgrade_rollback_and_fresh_install() { + // 1. Filtered upgrade payload: affine-local-workspace=["ws-a"] + __cap_noise__ stripped from entries. + let upgrade_json = r#"{"origin":"https://localhost","length":2,"keys":["__cap_noise__","affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-a\"]"},"idbTouchCount":0}"#; + let mut host = AndroidHostState::new(); + let snap = host + .import_legacy_local_storage_probe(upgrade_json, &[]) + .expect("filtered mixed upgrade sentinel must succeed"); + assert_eq!(snap.keys, vec!["__cap_noise__", "affine-local-workspace"]); + assert!(!host.upgrade_import.can_create_default_workspace()); + assert!(host.workspace_catalog.contains("ws-a")); + + // Rollback read-back with the same unrelated noise key stripped from entries passes. + let mut expected_set = BTreeMap::new(); + expected_set.insert( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY.to_string(), + r#"["ws-a"]"#.to_string(), + ); + verify_legacy_writeback_result(&expected_set, &[], upgrade_json) + .expect("rollback readback with noise key in keys only must pass"); + + // 2. Fresh install with only __cap_noise__ stripped from entries allows default workspace. + let fresh_json = r#"{"origin":"https://localhost","length":1,"keys":["__cap_noise__"],"entries":{},"idbTouchCount":0}"#; + let mut fresh_host = AndroidHostState::new(); + fresh_host + .import_legacy_local_storage_probe(fresh_json, &[]) + .expect("filtered fresh install with noise key must succeed"); + assert!(fresh_host.upgrade_import.can_create_default_workspace()); + + // 3. Unfiltered noise key still present in entries is rejected by affine-legacy-import sentinel. + let unfiltered_json = r#"{"origin":"https://localhost","length":1,"keys":["__cap_noise__"],"entries":{"__cap_noise__":"junk"},"idbTouchCount":0}"#; + let err = parse_legacy_local_storage_probe(unfiltered_json, &[]).unwrap_err(); + assert!(matches!(err, LegacyProbeError::InconsistentSentinel(_))); + + // 4. Bare legacy `-auth` single key ("local-auth": "\"tok\"") classifies as FreshInstall + // (matching iOS has_allowlisted_keys == false), mounts 0 workspaces, and preserves the raw + // entry verbatim in rollback writeback without deleting it. + let bare_auth_json = r#"{"origin":"https://localhost","length":1,"keys":["local-auth"],"entries":{"local-auth":"\"tok\""},"idbTouchCount":0}"#; + let mut bare_host = AndroidHostState::new(); + bare_host + .import_legacy_local_storage_probe(bare_auth_json, &[]) + .expect("bare local-auth sentinel must succeed"); + assert!(matches!( + bare_host.upgrade_import, + LegacyUpgradeImportState::FreshInstall + )); + assert!(bare_host.upgrade_import.can_create_default_workspace()); + assert!(bare_host.workspace_catalog.ids().is_empty()); + let bare_plan_raw = bare_host + .plan_legacy_local_storage_writeback() + .expect("FreshInstall writeback plan must be available"); + let bare_plan: serde_json::Value = serde_json::from_str(&bare_plan_raw).unwrap(); + assert_eq!(bare_plan["setEntries"]["local-auth"], "\"tok\""); + assert_eq!(bare_plan["removeKeys"], serde_json::json!([])); + } +} diff --git a/packages/frontend/hosts/android/src/native_islands.rs b/packages/frontend/hosts/android/src/native_islands.rs new file mode 100644 index 0000000000..b2151dcb7d --- /dev/null +++ b/packages/frontend/hosts/android/src/native_islands.rs @@ -0,0 +1,250 @@ +//! Zero-JNA / zero-UniFFI Android native-island narrow state machines: +//! `ShareIntent`: Incoming `ACTION_SEND` / `ACTION_SEND_MULTIPLE` queue with scheme allowlists, +//! 64 MiB per-item & cumulative attachment caps, non-destructive `peek_pending`, and +//! commit-gated `mark_consumed` deduplication. + +use std::collections::{BTreeSet, VecDeque}; + +use affine_store::share_ingest::MAX_SHARE_ATTACHMENT_BYTES; +use serde::{Deserialize, Serialize}; + +/// Supported Android `ACTION_SEND` payload kinds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AndroidShareKind { + Url, + Text, + Image, + Pdf, +} + +/// One queued item received from Android `ACTION_SEND` / `ACTION_SEND_MULTIPLE`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AndroidShareItem { + pub id: String, + pub kind: AndroidShareKind, + pub title: String, + pub content: String, + pub mime_type: String, + #[serde(default, skip_serializing)] + pub attachment_bytes: Vec, +} + +/// Pure-Rust incoming share queue with scheme, size, and idempotent duplicate validation. +#[derive(Debug, Default)] +pub struct AndroidShareQueue { + items: VecDeque, + consumed_ids: BTreeSet, + live_delivered_ids: BTreeSet, +} + +impl AndroidShareQueue { + pub fn enqueue(&mut self, item: AndroidShareItem) -> Result<(), &'static str> { + self.enqueue_for_target(item, false) + } + + pub fn enqueue_for_target( + &mut self, + item: AndroidShareItem, + allow_upgrade_from_live_delivery: bool, + ) -> Result<(), &'static str> { + if item.id.trim().is_empty() { + return Err("share id must be non-empty"); + } + let trimmed = item.content.trim(); + if trimmed.is_empty() { + return Err("share content must be non-empty"); + } + match item.kind { + AndroidShareKind::Url => { + if !(trimmed.starts_with("https://") || trimmed.starts_with("http://")) { + return Err("share url must use http(s) scheme"); + } + } + AndroidShareKind::Image | AndroidShareKind::Pdf => { + if !(trimmed.starts_with("content://") + || trimmed.starts_with("https://") + || trimmed.starts_with("http://")) + { + return Err("share attachment uri must use content:// or http(s):// scheme"); + } + if item.attachment_bytes.is_empty() { + return Err("share attachment must carry non-empty attachment bytes"); + } + if item.attachment_bytes.len() > MAX_SHARE_ATTACHMENT_BYTES { + return Err("share attachment exceeds 64 MiB limit"); + } + let queued_bytes: usize = self + .items + .iter() + .map(|existing| existing.attachment_bytes.len()) + .sum(); + if queued_bytes + .checked_add(item.attachment_bytes.len()) + .is_none_or(|sum| sum > MAX_SHARE_ATTACHMENT_BYTES) + { + return Err("cumulative queued share attachments exceed 64 MiB limit"); + } + } + AndroidShareKind::Text => {} + } + let blocked_by_live = + !allow_upgrade_from_live_delivery && self.live_delivered_ids.contains(&item.id); + if self.consumed_ids.contains(&item.id) + || blocked_by_live + || self.items.iter().any(|existing| existing.id == item.id) + { + return Err("duplicate share id"); + } + self.items.push_back(item); + Ok(()) + } + + pub fn pending_count(&self) -> usize { + self.items.len() + } + + /// Non-destructively clones pending items so failed or blocked ingestion attempts + /// never lose queued shares or mark `consumed_ids` prematurely. + pub fn peek_pending(&self) -> Vec { + self.items.iter().cloned().collect() + } + + /// Commits a subset of pending share IDs as durably consumed after SQLite commit. + pub fn mark_consumed(&mut self, ids: &[String]) { + if ids.is_empty() { + return; + } + let done: BTreeSet<&str> = ids.iter().map(String::as_str).collect(); + self.items.retain(|item| !done.contains(item.id.as_str())); + for id in ids { + self.live_delivered_ids.remove(id); + self.consumed_ids.insert(id.clone()); + } + } + + /// Marks share IDs delivered to the in-memory editor (without SQLite persistence yet). + pub fn mark_live_delivered(&mut self, ids: &[String]) { + if ids.is_empty() { + return; + } + let done: BTreeSet<&str> = ids.iter().map(String::as_str).collect(); + self.items.retain(|item| !done.contains(item.id.as_str())); + for id in ids { + if !self.consumed_ids.contains(id) { + self.live_delivered_ids.insert(id.clone()); + } + } + } + + /// Returns `true` when `id` has been durably committed or delivered in this session. + pub fn is_consumed(&self, id: &str) -> bool { + self.consumed_ids.contains(id) || self.live_delivered_ids.contains(id) + } + + pub fn drain_all(&mut self) -> Vec { + let drained: Vec = self.items.drain(..).collect(); + for item in &drained { + self.consumed_ids.insert(item.id.clone()); + } + drained + } +} + +/// Combined narrow-bridge state for Android native islands. +#[derive(Debug, Default)] +pub struct AndroidNativeIslandsState { + pub share_queue: AndroidShareQueue, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn android_native_islands_share_intent_state_machine() { + let mut islands = AndroidNativeIslandsState::default(); + assert!( + islands + .share_queue + .enqueue(AndroidShareItem { + id: "bad-url".into(), + kind: AndroidShareKind::Url, + title: "".into(), + content: "file:///etc/passwd".into(), + mime_type: "text/plain".into(), + attachment_bytes: Vec::new(), + }) + .is_err() + ); + // Image with file:// scheme or empty bytes must fail closed. + assert!( + islands + .share_queue + .enqueue(AndroidShareItem { + id: "bad-img-file".into(), + kind: AndroidShareKind::Image, + title: "".into(), + content: "file:///sdcard/secret.png".into(), + mime_type: "image/png".into(), + attachment_bytes: vec![0x89, b'P', b'N', b'G'], + }) + .is_err() + ); + assert!( + islands + .share_queue + .enqueue(AndroidShareItem { + id: "bad-img-empty".into(), + kind: AndroidShareKind::Image, + title: "".into(), + content: "content://media/external/images/media/1".into(), + mime_type: "image/png".into(), + attachment_bytes: Vec::new(), + }) + .is_err() + ); + islands + .share_queue + .enqueue(AndroidShareItem { + id: "intent-1".into(), + kind: AndroidShareKind::Url, + title: "AFFiNE".into(), + content: "https://affine.pro".into(), + mime_type: "text/plain".into(), + attachment_bytes: Vec::new(), + }) + .expect("enqueue url"); + islands + .share_queue + .enqueue(AndroidShareItem { + id: "intent-img-1".into(), + kind: AndroidShareKind::Image, + title: "Photo".into(), + content: "content://media/external/images/media/1".into(), + mime_type: "image/png".into(), + attachment_bytes: vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], + }) + .expect("enqueue content:// image with bytes"); + assert_eq!(islands.share_queue.pending_count(), 2); + let peeked = islands.share_queue.peek_pending(); + assert_eq!(peeked.len(), 2); + assert_eq!(islands.share_queue.pending_count(), 2); + islands.share_queue.mark_consumed(&["intent-1".into()]); + assert_eq!(islands.share_queue.pending_count(), 1); + // Re-enqueuing an already-consumed ID must fail idempotently. + assert!( + islands + .share_queue + .enqueue(AndroidShareItem { + id: "intent-1".into(), + kind: AndroidShareKind::Url, + title: "AFFiNE".into(), + content: "https://affine.pro".into(), + mime_type: "text/plain".into(), + attachment_bytes: Vec::new(), + }) + .is_err() + ); + } +} diff --git a/packages/frontend/hosts/android/src/pdf.rs b/packages/frontend/hosts/android/src/pdf.rs new file mode 100644 index 0000000000..22002f046d --- /dev/null +++ b/packages/frontend/hosts/android/src/pdf.rs @@ -0,0 +1,243 @@ +//! Native Android `PdfRenderer` page validation, memory ceiling enforcement, +//! deterministic cache key generation, and `ARGB_8888 -> RGBA8` pixel conversion. + +/// Maximum single-axis dimension (pixels) allowed for an in-place PDF page render. +pub const MAX_PDF_RENDER_DIM_PX: u32 = 4096; + +/// Maximum total pixel count per rendered PDF page (4096 * 4096 = 64 MiB RGBA8). +pub const MAX_PDF_RENDER_PIXELS: u64 = 16_777_216; + +/// Validation or conversion error for an Android `PdfRenderer` page request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PdfRenderError { + OutOfBoundsPage { page_index: u32, page_count: u32 }, + InvalidDimensions { width_px: u32, height_px: u32 }, + ExceedsMemoryCap { width_px: u32, height_px: u32 }, + PixelBufferMismatch { expected: usize, actual: usize }, +} + +/// Validates page bounds and OOM dimension limits before invoking `PdfRenderer`. +pub const fn validate_pdf_page_request( + page_index: u32, + page_count: u32, + width_px: u32, + height_px: u32, +) -> Result<(), PdfRenderError> { + if page_count == 0 || page_index >= page_count { + return Err(PdfRenderError::OutOfBoundsPage { + page_index, + page_count, + }); + } + if width_px == 0 || height_px == 0 { + return Err(PdfRenderError::InvalidDimensions { + width_px, + height_px, + }); + } + if width_px > MAX_PDF_RENDER_DIM_PX || height_px > MAX_PDF_RENDER_DIM_PX { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + let pixels = (width_px as u64) * (height_px as u64); + if pixels > MAX_PDF_RENDER_PIXELS { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + Ok(()) +} + +/// Computes a deterministic cache key for a rendered PDF page tile. +pub fn pdf_page_cache_key( + doc_id: &str, + page_index: u32, + width_px: u32, + height_px: u32, + dpi_bucket: u32, +) -> String { + let safe_dpi = dpi_bucket.max(72); + format!("pdf:{doc_id}:p{page_index}:{width_px}x{height_px}@{safe_dpi}dpi") +} + +/// Validates rendered PDF bitmap dimensions against the OOM cap and returns +/// the exact expected pixel count. +pub const fn validate_pdf_dimensions( + width_px: u32, + height_px: u32, +) -> Result { + if width_px == 0 || height_px == 0 { + return Err(PdfRenderError::InvalidDimensions { + width_px, + height_px, + }); + } + if width_px > MAX_PDF_RENDER_DIM_PX || height_px > MAX_PDF_RENDER_DIM_PX { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + let expected_u64 = (width_px as u64) * (height_px as u64); + if expected_u64 > MAX_PDF_RENDER_PIXELS { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + Ok(expected_u64 as usize) +} + +/// Converts Android `Bitmap.Config.ARGB_8888` pixels (`0xAARRGGBB`) into tightly +/// packed `RGBA8` bytes (`[R, G, B, A]`), enforcing the OOM pixel cap. +pub fn argb8888_to_rgba8( + argb_pixels: &[u32], + width_px: u32, + height_px: u32, +) -> Result, PdfRenderError> { + let expected = validate_pdf_dimensions(width_px, height_px)?; + if argb_pixels.len() != expected { + return Err(PdfRenderError::PixelBufferMismatch { + expected, + actual: argb_pixels.len(), + }); + } + + let mut rgba = Vec::with_capacity(expected * 4); + for &argb in argb_pixels { + let a = ((argb >> 24) & 0xFF) as u8; + let r = ((argb >> 16) & 0xFF) as u8; + let g = ((argb >> 8) & 0xFF) as u8; + let b = (argb & 0xFF) as u8; + rgba.extend_from_slice(&[r, g, b, a]); + } + Ok(rgba) +} + +/// Converts one chunk of signed JNI `jint` `ARGB_8888` pixels directly into a +/// pre-allocated stack/slice `RGBA8` buffer (`out_rgba.len() == argb_chunk.len() * 4`) +/// with zero heap allocation. +pub fn convert_argb8888_i32_chunk_to_rgba8_slice(argb_chunk: &[i32], out_rgba: &mut [u8]) { + debug_assert_eq!(out_rgba.len(), argb_chunk.len() * 4); + for (&px, dst) in argb_chunk.iter().zip(out_rgba.chunks_exact_mut(4)) { + let argb = px as u32; + dst[0] = ((argb >> 16) & 0xFF) as u8; + dst[1] = ((argb >> 8) & 0xFF) as u8; + dst[2] = (argb & 0xFF) as u8; + dst[3] = ((argb >> 24) & 0xFF) as u8; + } +} + +/// Appends one chunk of signed JNI `jint` `ARGB_8888` pixels directly into an +/// `RGBA8` byte buffer without intermediate allocations. +pub fn append_argb8888_i32_chunk_to_rgba8(argb_chunk: &[i32], out_rgba: &mut Vec) { + let start = out_rgba.len(); + out_rgba.resize(start + argb_chunk.len() * 4, 0); + convert_argb8888_i32_chunk_to_rgba8_slice(argb_chunk, &mut out_rgba[start..]); +} + +/// Converts signed JNI `jint` `ARGB_8888` pixels directly into tightly packed +/// `RGBA8` bytes with zero intermediate `Vec` copy. +pub fn argb8888_i32_to_rgba8( + argb_pixels: &[i32], + width_px: u32, + height_px: u32, +) -> Result, PdfRenderError> { + let expected = validate_pdf_dimensions(width_px, height_px)?; + if argb_pixels.len() != expected { + return Err(PdfRenderError::PixelBufferMismatch { + expected, + actual: argb_pixels.len(), + }); + } + let mut rgba = Vec::with_capacity(expected * 4); + append_argb8888_i32_chunk_to_rgba8(argb_pixels, &mut rgba); + Ok(rgba) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pdf_request_validation_enforces_bounds_and_oom_cap() { + let cases = [ + ((0, 3, 1080, 1920), Ok(())), + ((2, 3, 4096, 4096), Ok(())), + ( + (0, 0, 100, 100), + Err(PdfRenderError::OutOfBoundsPage { + page_index: 0, + page_count: 0, + }), + ), + ( + (3, 3, 100, 100), + Err(PdfRenderError::OutOfBoundsPage { + page_index: 3, + page_count: 3, + }), + ), + ( + (0, 2, 0, 100), + Err(PdfRenderError::InvalidDimensions { + width_px: 0, + height_px: 100, + }), + ), + ( + (0, 2, 4097, 100), + Err(PdfRenderError::ExceedsMemoryCap { + width_px: 4097, + height_px: 100, + }), + ), + ]; + + for ((page_index, page_count, width_px, height_px), expected) in cases { + assert_eq!( + validate_pdf_page_request(page_index, page_count, width_px, height_px), + expected + ); + } + } + + #[test] + fn pdf_cache_key_and_argb8888_to_rgba8_conversion_are_deterministic() { + assert_eq!( + pdf_page_cache_key("doc-42", 2, 1080, 1440, 320), + "pdf:doc-42:p2:1080x1440@320dpi" + ); + assert_eq!( + pdf_page_cache_key("doc-42", 0, 100, 100, 0), + "pdf:doc-42:p0:100x100@72dpi" + ); + + let argb = [ + 0xFF_11_22_33_u32, // opaque + 0x80_AA_BB_CC_u32, // semi-transparent + 0xFF_FF_FF_FF_u32, // white background + 0x00_01_02_03_u32, // zero alpha + ]; + let rgba = argb8888_to_rgba8(&argb, 2, 2).expect("valid 2x2 conversion"); + assert_eq!( + rgba, + vec![ + 0x11, 0x22, 0x33, 0xFF, // pixel 0 + 0xAA, 0xBB, 0xCC, 0x80, // pixel 1 + 0xFF, 0xFF, 0xFF, 0xFF, // pixel 2 + 0x01, 0x02, 0x03, 0x00, // pixel 3 + ] + ); + assert_eq!( + argb8888_to_rgba8(&argb[..3], 2, 2), + Err(PdfRenderError::PixelBufferMismatch { + expected: 4, + actual: 3, + }) + ); + } +} diff --git a/packages/frontend/hosts/android/src/runtime_root.rs b/packages/frontend/hosts/android/src/runtime_root.rs new file mode 100644 index 0000000000..66ffa8a96a --- /dev/null +++ b/packages/frontend/hosts/android/src/runtime_root.rs @@ -0,0 +1,92 @@ +//! Root view of the embedded window: a bare page editor or the mobile product shell. +//! +//! [`EditorView`] resolves the page editor that owns text input at call time, so +//! `InputConnection`, selection handles, and selection actions reach the root editor, or the +//! shell's embedded editor while the shell shows a `Page` route. + +use std::rc::Rc; + +use affine_mobile::{InMemoryPlatformAccessibility, MobileRoute, MobileSheet, MobileShellView}; +use anyhow::Context as _; +use playground::PlaygroundView; +use ui::{AnyWindowHandle, App, AppContext, Context, Entity, Task, Window, WindowHandle}; + +use super::shell_workspace::ShellWorkspace; + +/// Root view type mounted in the embedded window. +#[derive(Clone, Copy)] +pub(crate) enum RuntimeRoot { + Editor(WindowHandle), + Shell(WindowHandle), +} + +impl RuntimeRoot { + pub(crate) fn window(self) -> AnyWindowHandle { + match self { + Self::Editor(handle) => handle.into(), + Self::Shell(handle) => handle.into(), + } + } + + pub(crate) fn shell(self) -> Option> { + match self { + Self::Editor(_) => None, + Self::Shell(handle) => Some(handle), + } + } + + /// The root editor, or the shell's embedded editor while the `Page` route is shown with + /// no sheet or drawer above it. + pub(crate) fn editor(self, cx: &App) -> Option> { + match self { + Self::Editor(handle) => handle.entity(cx).ok(), + Self::Shell(handle) => { + let shell = handle.read(cx).ok()?; + if !matches!(shell.state.route, MobileRoute::Page(_)) + || shell.state.active_sheet != MobileSheet::None + { + return None; + } + shell.page_editor().cloned() + } + } + } +} + +/// Handle to the page editor that owns text input, with the `WindowHandle` call shape. +#[derive(Clone, Copy)] +pub(crate) struct EditorView(pub(crate) RuntimeRoot); + +impl EditorView { + pub(crate) fn read_with( + self, + cx: &App, + read: impl FnOnce(&PlaygroundView, &App) -> R, + ) -> anyhow::Result { + let entity = self.0.editor(cx).context("no page editor is shown")?; + Ok(read(entity.read(cx), cx)) + } + + pub(crate) fn update( + self, + cx: &mut App, + update: impl FnOnce(&mut PlaygroundView, &mut Window, &mut Context) -> R, + ) -> anyhow::Result { + let entity = self.0.editor(cx).context("no page editor is shown")?; + cx.update_window(self.0.window(), |_, window, cx| { + entity.update(cx, |view, cx| update(view, window, cx)) + }) + } +} + +/// Host-side state of a mounted shell. +pub(crate) struct ShellHost { + pub(crate) a11y: InMemoryPlatformAccessibility, + pub(crate) workspace: Option, +} + +/// Local workspace behind the shell, and the task that commits its edits every second. +pub(crate) struct MountedWorkspace { + pub(crate) store: Rc, + pub(crate) _autosave: Task<()>, +} diff --git a/packages/frontend/hosts/android/src/selection.rs b/packages/frontend/hosts/android/src/selection.rs new file mode 100644 index 0000000000..a8c6632071 --- /dev/null +++ b/packages/frontend/hosts/android/src/selection.rs @@ -0,0 +1,868 @@ +//! Native Android text selection teardrop handles, magnifier loupe anchor, +//! and post-release context action menu geometry. +//! +//! Coordinates are kept in viewport pixel space scaled by `density` so the +//! Kotlin host can position overlay views without calling `SurfaceHolder.lockCanvas`. + +use serde::Serialize; + +/// Text layout direction controlling teardrop handle orientation. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum TextDirection { + #[default] + Ltr = 0, + Rtl = 1, +} + +impl TextDirection { + /// Converts a raw JNI integer code into a [`TextDirection`]. + pub const fn from_code(code: i32) -> Self { + match code { + 1 => Self::Rtl, + _ => Self::Ltr, + } + } +} + +/// Active selection handle identifier. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum SelectionHandleKind { + #[default] + None = 0, + Start = 1, + End = 2, +} + +impl SelectionHandleKind { + /// Converts a raw JNI integer code into a [`SelectionHandleKind`]. + pub const fn from_code(code: i32) -> Self { + match code { + 1 => Self::Start, + 2 => Self::End, + _ => Self::None, + } + } +} + +/// Visual teardrop lean direction for a selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub enum TeardropOrientation { + #[default] + LeftLeaning, + RightLeaning, +} + +/// Axis-aligned rectangle in viewport pixels. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct RectF { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +/// Computed geometry for a single teardrop selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct HandleGeometry { + pub kind: SelectionHandleKind, + pub tip_x: f32, + pub tip_y: f32, + pub center_x: f32, + pub center_y: f32, + pub radius: f32, + pub orientation: TeardropOrientation, + pub bounds: RectF, + pub visible: bool, +} + +/// Magnifier loupe position and visibility while dragging a selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct MagnifierState { + pub visible: bool, + pub anchor_x: f32, + pub anchor_y: f32, + pub loupe_x: f32, + pub loupe_y: f32, + pub zoom: f32, +} + +/// Complete native selection overlay state for the Android host. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SelectionOverlayState { + pub viewport_width: f32, + pub viewport_height: f32, + pub density: f32, + pub direction: TextDirection, + pub has_selection: bool, + pub active_drag: SelectionHandleKind, + pub line_height: f32, + pub start_handle: HandleGeometry, + pub end_handle: HandleGeometry, + pub magnifier: MagnifierState, + pub action_menu_rect: Option, + pub probe_x: f32, + pub probe_y: f32, + #[serde(skip)] + raw_start_x: f32, + #[serde(skip)] + raw_start_y: f32, + #[serde(skip)] + raw_end_x: f32, + #[serde(skip)] + raw_end_y: f32, + #[serde(skip)] + grab_dx: f32, + #[serde(skip)] + grab_dy: f32, +} + +const HANDLE_RADIUS_DP: f32 = 11.0; +const HANDLE_HIT_SLOP_DP: f32 = 24.0; +const LOUPE_WIDTH_DP: f32 = 100.0; +const LOUPE_HEIGHT_DP: f32 = 48.0; +const LOUPE_OFFSET_Y_DP: f32 = 56.0; +const LOUPE_DEFAULT_ZOOM: f32 = 1.25; +const ACTION_MENU_WIDTH_DP: f32 = 220.0; +const ACTION_MENU_HEIGHT_DP: f32 = 44.0; +const ACTION_MENU_GAP_DP: f32 = 12.0; + +impl Default for SelectionOverlayState { + fn default() -> Self { + Self::new() + } +} + +impl SelectionOverlayState { + /// Creates an empty selection overlay state. + pub fn new() -> Self { + Self { + viewport_width: 0.0, + viewport_height: 0.0, + density: 1.0, + direction: TextDirection::Ltr, + has_selection: false, + active_drag: SelectionHandleKind::None, + line_height: 24.0, + start_handle: HandleGeometry { + kind: SelectionHandleKind::Start, + orientation: TeardropOrientation::LeftLeaning, + ..HandleGeometry::default() + }, + end_handle: HandleGeometry { + kind: SelectionHandleKind::End, + orientation: TeardropOrientation::RightLeaning, + ..HandleGeometry::default() + }, + magnifier: MagnifierState { + zoom: LOUPE_DEFAULT_ZOOM, + ..MagnifierState::default() + }, + action_menu_rect: None, + probe_x: 0.0, + probe_y: 0.0, + raw_start_x: 0.0, + raw_start_y: 0.0, + raw_end_x: 0.0, + raw_end_y: 0.0, + grab_dx: 0.0, + grab_dy: 0.0, + } + } + + /// Updates viewport dimensions and display density, reclamping active overlays. + pub fn set_viewport(&mut self, width: f32, height: f32, density: f32) { + self.viewport_width = sanitize_non_negative(width); + self.viewport_height = sanitize_non_negative(height); + self.density = sanitize_positive(density, 1.0); + self.recompute(); + } + + /// Updates the selection endpoints, line height, and text direction. + #[allow(clippy::too_many_arguments)] + pub fn update_selection( + &mut self, + start_x: f32, + start_y: f32, + end_x: f32, + end_y: f32, + line_height: f32, + direction: TextDirection, + has_selection: bool, + ) { + self.direction = direction; + self.line_height = sanitize_positive(line_height, 24.0 * self.density); + self.has_selection = has_selection; + if !has_selection { + self.clear(); + return; + } + self.raw_start_x = sanitize_finite(start_x); + self.raw_start_y = sanitize_finite(start_y); + self.raw_end_x = sanitize_finite(end_x); + self.raw_end_y = sanitize_finite(end_y); + self.recompute(); + } + + /// Hit-tests a finger-down coordinate against the visible start and end teardrop handles, + /// recording the grab offset so a zero-pixel drag keeps the endpoint stationary. + pub fn begin_drag(&mut self, touch_x: f32, touch_y: f32) -> SelectionHandleKind { + if !self.has_selection || !touch_x.is_finite() || !touch_y.is_finite() { + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + return SelectionHandleKind::None; + } + let hit_radius = HANDLE_HIT_SLOP_DP * self.density; + let max_dist_sq = hit_radius * hit_radius; + + let start_dist_sq = if self.start_handle.visible { + dist_sq( + touch_x, + touch_y, + self.start_handle.center_x, + self.start_handle.center_y, + ) + } else { + f32::INFINITY + }; + let end_dist_sq = if self.end_handle.visible { + dist_sq( + touch_x, + touch_y, + self.end_handle.center_x, + self.end_handle.center_y, + ) + } else { + f32::INFINITY + }; + + let hit = match (start_dist_sq <= max_dist_sq, end_dist_sq <= max_dist_sq) { + (true, true) => { + if start_dist_sq <= end_dist_sq { + SelectionHandleKind::Start + } else { + SelectionHandleKind::End + } + } + (true, false) => SelectionHandleKind::Start, + (false, true) => SelectionHandleKind::End, + (false, false) => SelectionHandleKind::None, + }; + + self.active_drag = hit; + if hit != SelectionHandleKind::None { + let (ax, ay) = self.active_anchor(); + self.grab_dx = ax - touch_x; + self.grab_dy = ay - touch_y; + self.action_menu_rect = None; + let focus_y = (ay - 0.5 * self.line_height).max(0.0); + self.update_magnifier(ax, focus_y, true); + } else { + self.grab_dx = 0.0; + self.grab_dy = 0.0; + } + hit + } + + /// Computes and clamps the grab-offset-compensated drag probe without mutating + /// handle ownership, allowing UTF-16 text layout to be the single authority for + /// start/end handle inversion and magnifier anchoring. + pub fn probe_drag_position(&mut self, touch_x: f32, touch_y: f32) -> Option<(f32, f32)> { + if self.active_drag == SelectionHandleKind::None + || !touch_x.is_finite() + || !touch_y.is_finite() + { + return None; + } + let next_x = self.clamp_x(touch_x + self.grab_dx); + let next_y = self.clamp_y(touch_y + self.grab_dy); + self.probe_x = next_x; + self.probe_y = next_y; + Some((next_x, next_y)) + } + + /// Applies authoritative text-layout selection endpoints and active handle kind + /// during a text-driven handle drag without applying a secondary pixel-based swap. + #[allow(clippy::too_many_arguments)] + pub fn apply_text_drag_endpoints( + &mut self, + start_x: f32, + start_y: f32, + end_x: f32, + end_y: f32, + line_height: f32, + direction: TextDirection, + active_handle: SelectionHandleKind, + ) { + self.has_selection = true; + self.direction = direction; + self.line_height = if line_height.is_finite() && line_height > 0.0 { + line_height + } else { + 24.0 * self.density + }; + self.raw_start_x = if start_x.is_finite() { start_x } else { 0.0 }; + self.raw_start_y = if start_y.is_finite() { start_y } else { 0.0 }; + self.raw_end_x = if end_x.is_finite() { end_x } else { 0.0 }; + self.raw_end_y = if end_y.is_finite() { end_y } else { 0.0 }; + self.active_drag = active_handle; + self.recompute(); + } + + /// Packs the overlay geometry into a fixed 24-float array for zero-allocation, + /// zero-JSON per-frame `AndroidSelectionOverlayView.onDraw` rendering. + pub fn pack_overlay_floats(&self) -> [f32; 24] { + let (menu_vis, mx, my, mw, mh) = match self.action_menu_rect { + Some(r) => (1.0, r.x, r.y, r.width, r.height), + None => (0.0, 0.0, 0.0, 0.0, 0.0), + }; + [ + if self.has_selection { 1.0 } else { 0.0 }, + match self.direction { + TextDirection::Ltr => 0.0, + TextDirection::Rtl => 1.0, + }, + if self.start_handle.visible { 1.0 } else { 0.0 }, + self.start_handle.tip_x, + self.start_handle.tip_y, + self.start_handle.center_x, + self.start_handle.center_y, + self.start_handle.radius, + if self.end_handle.visible { 1.0 } else { 0.0 }, + self.end_handle.tip_x, + self.end_handle.tip_y, + self.end_handle.center_x, + self.end_handle.center_y, + self.end_handle.radius, + if self.magnifier.visible { 1.0 } else { 0.0 }, + self.magnifier.anchor_x, + self.magnifier.anchor_y, + self.magnifier.loupe_x, + self.magnifier.loupe_y, + menu_vis, + mx, + my, + mw, + mh, + ] + } + + /// Ends handle dragging, hides the magnifier, and computes the context action menu rect. + pub fn end_drag(&mut self) -> Option { + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + self.magnifier.visible = false; + self.recompute(); + self.action_menu_rect + } + + /// Clears the selection handles, magnifier, and context action menu. + pub fn clear(&mut self) { + self.has_selection = false; + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + self.start_handle.visible = false; + self.end_handle.visible = false; + self.magnifier.visible = false; + self.action_menu_rect = None; + } + + /// Serializes the current selection overlay state to JSON for JNI consumers. + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) + } + + fn is_y_in_viewport(&self, raw_y: f32) -> bool { + if self.viewport_height <= 0.0 { + return raw_y >= 0.0; + } + raw_y >= 0.0 && raw_y <= self.viewport_height + } + + fn recompute(&mut self) { + let same_line = + (self.raw_start_y - self.raw_end_y).abs() < 0.5 * self.line_height.max(16.0); + let (start_orient, end_orient) = + if same_line && (self.raw_start_x - self.raw_end_x).abs() > 0.01 { + if self.raw_start_x < self.raw_end_x { + ( + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ) + } else { + ( + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ) + } + } else { + match self.direction { + TextDirection::Ltr => ( + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ), + TextDirection::Rtl => ( + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ), + } + }; + + let start_visible = self.has_selection && self.is_y_in_viewport(self.raw_start_y); + let end_visible = self.has_selection && self.is_y_in_viewport(self.raw_end_y); + + let start_tip = ( + self.clamp_x(self.raw_start_x), + self.clamp_y(self.raw_start_y), + ); + let end_tip = (self.clamp_x(self.raw_end_x), self.clamp_y(self.raw_end_y)); + + self.start_handle = self.build_handle( + SelectionHandleKind::Start, + start_tip.0, + start_tip.1, + start_orient, + start_visible, + ); + self.end_handle = self.build_handle( + SelectionHandleKind::End, + end_tip.0, + end_tip.1, + end_orient, + end_visible, + ); + + if !self.has_selection { + self.magnifier.visible = false; + self.action_menu_rect = None; + return; + } + + if self.active_drag != SelectionHandleKind::None { + let (ax, ay) = self.active_anchor(); + let focus_y = (ay - 0.5 * self.line_height).max(0.0); + self.update_magnifier(ax, focus_y, true); + self.action_menu_rect = None; + } else if start_visible || end_visible { + self.magnifier.visible = false; + self.action_menu_rect = Some(self.compute_action_menu_rect()); + } else { + self.magnifier.visible = false; + self.action_menu_rect = None; + } + } + + fn build_handle( + &self, + kind: SelectionHandleKind, + tip_x: f32, + tip_y: f32, + orientation: TeardropOrientation, + visible: bool, + ) -> HandleGeometry { + let r = HANDLE_RADIUS_DP * self.density; + let diameter = r * 2.0; + let lean = match orientation { + TeardropOrientation::LeftLeaning => -0.7 * r, + TeardropOrientation::RightLeaning => 0.7 * r, + }; + let raw_cx = tip_x + lean; + let raw_cy = tip_y + r; + + let width = if self.viewport_width > 0.0 { + diameter.min(self.viewport_width) + } else { + diameter + }; + let height = if self.viewport_height > 0.0 { + diameter.min(self.viewport_height) + } else { + diameter + }; + let bounds_x = clamp_rect_origin(raw_cx - width * 0.5, width, self.viewport_width); + let bounds_y = clamp_rect_origin(raw_cy - height * 0.5, height, self.viewport_height); + + HandleGeometry { + kind, + tip_x, + tip_y, + center_x: bounds_x + width * 0.5, + center_y: bounds_y + height * 0.5, + radius: r, + orientation, + bounds: RectF { + x: bounds_x, + y: bounds_y, + width, + height, + }, + visible, + } + } + + fn active_anchor(&self) -> (f32, f32) { + match self.active_drag { + SelectionHandleKind::Start => (self.start_handle.tip_x, self.start_handle.tip_y), + SelectionHandleKind::End => (self.end_handle.tip_x, self.end_handle.tip_y), + SelectionHandleKind::None => (0.0, 0.0), + } + } + + fn update_magnifier(&mut self, anchor_x: f32, anchor_y: f32, visible: bool) { + let half_w = LOUPE_WIDTH_DP * 0.5 * self.density; + let half_h = LOUPE_HEIGHT_DP * 0.5 * self.density; + let offset_y = LOUPE_OFFSET_Y_DP * self.density; + + let loupe_x = clamp_center(anchor_x, half_w, self.viewport_width); + let loupe_y = clamp_center(anchor_y - offset_y, half_h, self.viewport_height); + + self.magnifier = MagnifierState { + visible, + anchor_x, + anchor_y, + loupe_x, + loupe_y, + zoom: LOUPE_DEFAULT_ZOOM, + }; + } + + fn compute_action_menu_rect(&self) -> RectF { + let menu_w = if self.viewport_width > 0.0 { + (ACTION_MENU_WIDTH_DP * self.density).min(self.viewport_width) + } else { + ACTION_MENU_WIDTH_DP * self.density + }; + let menu_h = if self.viewport_height > 0.0 { + (ACTION_MENU_HEIGHT_DP * self.density).min(self.viewport_height) + } else { + ACTION_MENU_HEIGHT_DP * self.density + }; + let gap = ACTION_MENU_GAP_DP * self.density; + + let mid_x = (self.start_handle.tip_x + self.end_handle.tip_x) * 0.5; + let top_y = self.start_handle.tip_y.min(self.end_handle.tip_y); + let bottom_y = self.start_handle.tip_y.max(self.end_handle.tip_y); + + let preferred_y = top_y - self.line_height - menu_h - gap; + let y = if preferred_y >= 0.0 { + preferred_y + } else { + let below_y = bottom_y + HANDLE_RADIUS_DP * 2.0 * self.density + gap; + clamp_rect_origin(below_y, menu_h, self.viewport_height) + }; + let margin_x = 12.0 * self.density; + let x = if self.viewport_width > menu_w + 2.0 * margin_x { + (mid_x - menu_w * 0.5).clamp(margin_x, self.viewport_width - margin_x - menu_w) + } else { + clamp_rect_origin(mid_x - menu_w * 0.5, menu_w, self.viewport_width) + }; + + RectF { + x, + y, + width: menu_w, + height: menu_h, + } + } + + fn clamp_x(&self, value: f32) -> f32 { + let v = if value.is_finite() { value } else { 0.0 }; + if self.viewport_width > 0.0 { + v.clamp(0.0, self.viewport_width) + } else { + v.max(0.0) + } + } + + fn clamp_y(&self, value: f32) -> f32 { + let v = if value.is_finite() { value } else { 0.0 }; + if self.viewport_height > 0.0 { + v.clamp(0.0, self.viewport_height) + } else { + v.max(0.0) + } + } +} + +fn sanitize_finite(value: f32) -> f32 { + if value.is_finite() { value } else { 0.0 } +} + +fn sanitize_non_negative(value: f32) -> f32 { + if value.is_finite() && value > 0.0 { + value + } else { + 0.0 + } +} + +fn sanitize_positive(value: f32, fallback: f32) -> f32 { + if value.is_finite() && value > 0.0 { + value + } else { + fallback + } +} + +fn dist_sq(ax: f32, ay: f32, bx: f32, by: f32) -> f32 { + let dx = ax - bx; + let dy = ay - by; + dx * dx + dy * dy +} + +fn clamp_rect_origin(origin: f32, size: f32, viewport: f32) -> f32 { + if viewport <= 0.0 { + return origin.max(0.0); + } + let max_origin = (viewport - size).max(0.0); + origin.clamp(0.0, max_origin) +} + +fn clamp_center(center: f32, half_size: f32, viewport: f32) -> f32 { + if viewport <= 0.0 { + return center.max(0.0); + } + if viewport <= half_size * 2.0 { + return viewport * 0.5; + } + center.clamp(half_size, viewport - half_size) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selection_handles_flip_for_rtl_and_clamp_to_viewport() { + let cases = [ + ( + TextDirection::Ltr, + 10.0, + 1075.0, + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ), + ( + TextDirection::Rtl, + 1075.0, + 10.0, + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ), + ]; + + for (dir, start_x, end_x, expected_start, expected_end) in cases { + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(start_x, 400.0, end_x, 400.0, 60.0, dir, true); + assert!(state.start_handle.visible); + assert!(state.end_handle.visible); + assert_eq!(state.start_handle.orientation, expected_start); + assert_eq!(state.end_handle.orientation, expected_end); + assert!(state.start_handle.bounds.x >= 0.0); + assert!(state.end_handle.bounds.x + state.end_handle.bounds.width <= 1080.0); + assert!(state.action_menu_rect.is_some()); + } + } + + #[test] + fn drag_shows_clamped_magnifier_and_release_restores_action_menu() { + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + + // Miss outside touch target. + assert_eq!(state.begin_drag(50.0, 50.0), SelectionHandleKind::None); + assert!(!state.magnifier.visible); + + // Hit end handle center -> magnifier appears, action menu hides. + let hit = state.begin_drag(state.end_handle.center_x, state.end_handle.center_y); + assert_eq!(hit, SelectionHandleKind::End); + assert!(state.magnifier.visible); + assert!(state.action_menu_rect.is_none()); + + // Drag end handle right to viewport edge -> loupe clamps cleanly inside viewport. + state.apply_text_drag_endpoints( + 200.0, + 500.0, + 1200.0, + 500.0, + 60.0, + TextDirection::Ltr, + SelectionHandleKind::End, + ); + assert!(state.magnifier.visible); + assert_eq!(state.end_handle.tip_x, 1080.0); + assert_eq!(state.end_handle.tip_y, 500.0); + assert!(state.magnifier.loupe_x <= 1080.0 - 150.0); + assert!(state.magnifier.loupe_y >= 72.0); + assert!(state.action_menu_rect.is_none()); + + // Release -> magnifier hides and action menu flips below near top edge. + let menu = state.end_drag().expect("action menu rect after release"); + assert!(!state.magnifier.visible); + assert!(menu.x >= 0.0 && menu.x + menu.width <= 1080.0); + assert!(menu.y >= 0.0 && menu.y + menu.height <= 2400.0); + } + + #[test] + fn drag_preserves_grab_offset_swaps_on_crossover_and_hides_offscreen_handles() { + // 1. Zero-pixel move after grabbing handle center must not jump the endpoint. + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + let grab_x = state.start_handle.center_x; + let grab_y = state.start_handle.center_y; + assert_eq!(state.begin_drag(grab_x, grab_y), SelectionHandleKind::Start); + let (probe_x, probe_y) = state + .probe_drag_position(grab_x, grab_y) + .expect("probe drag position during active drag"); + assert!((probe_x - 200.0).abs() < 1e-3); + assert!((probe_y - 500.0).abs() < 1e-3); + state.apply_text_drag_endpoints( + 200.0, + 500.0, + 700.0, + 500.0, + 60.0, + TextDirection::Ltr, + SelectionHandleKind::Start, + ); + assert!((state.start_handle.tip_x - 200.0).abs() < 1e-3); + assert!((state.start_handle.tip_y - 500.0).abs() < 1e-3); + + // 2. Same-line LTR crossover via authoritative UTF-16 anchor -> endpoints swap & active_drag flips to End. + state.apply_text_drag_endpoints( + 700.0, + 500.0, + 900.0, + 500.0, + 60.0, + TextDirection::Ltr, + SelectionHandleKind::End, + ); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_x - 700.0).abs() < 1e-3); + assert!((state.end_handle.tip_x - 900.0).abs() < 1e-3); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::RightLeaning + ); + let _ = state.end_drag(); + + // 3. Cross-line crossover via authoritative UTF-16 anchor -> endpoints swap & active_drag flips to End. + state.update_selection(300.0, 400.0, 600.0, 600.0, 60.0, TextDirection::Ltr, true); + let sx = state.start_handle.center_x; + let sy = state.start_handle.center_y; + assert_eq!(state.begin_drag(sx, sy), SelectionHandleKind::Start); + state.apply_text_drag_endpoints( + 600.0, + 600.0, + 300.0, + 800.0, + 60.0, + TextDirection::Ltr, + SelectionHandleKind::End, + ); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_y - 600.0).abs() < 1e-3); + assert!((state.end_handle.tip_y - 800.0).abs() < 1e-3); + let _ = state.end_drag(); + + // 4. Same-line RTL crossover via authoritative UTF-16 anchor -> active_drag flips to End. + state.update_selection(800.0, 500.0, 400.0, 500.0, 60.0, TextDirection::Rtl, true); + let rsx = state.start_handle.center_x; + let rsy = state.start_handle.center_y; + assert_eq!(state.begin_drag(rsx, rsy), SelectionHandleKind::Start); + state.apply_text_drag_endpoints( + 400.0, + 500.0, + 200.0, + 500.0, + 60.0, + TextDirection::Rtl, + SelectionHandleKind::End, + ); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_x - 400.0).abs() < 1e-3); + assert!((state.end_handle.tip_x - 200.0).abs() < 1e-3); + let _ = state.end_drag(); + + // 5. Off-screen scrolled endpoints hide their handles instead of pinning to y=0. + state.update_selection(200.0, -40.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + assert!(!state.start_handle.visible); + assert!(state.end_handle.visible); + state.update_selection(200.0, -40.0, 700.0, 2600.0, 60.0, TextDirection::Ltr, true); + assert!(!state.start_handle.visible); + assert!(!state.end_handle.visible); + assert!(state.action_menu_rect.is_none()); + + // 6. Same-line vertical jitter via authoritative UTF-16 anchor never swaps End to Start. + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + let ex = state.end_handle.center_x; + let ey = state.end_handle.center_y; + assert_eq!(state.begin_drag(ex, ey), SelectionHandleKind::End); + for dy in [-1.0_f32, 1.0, -2.0, 2.0, -15.0, 15.0] { + let _ = state.probe_drag_position(ex - 20.0, ey + dy); + state.apply_text_drag_endpoints( + 200.0, + 500.0, + 680.0, + 500.0, + 60.0, + TextDirection::Ltr, + SelectionHandleKind::End, + ); + assert_eq!( + state.active_drag, + SelectionHandleKind::End, + "vertical jitter {dy}px must not swap End to Start" + ); + assert!(state.end_handle.tip_x > state.start_handle.tip_x); + } + let _ = state.end_drag(); + + // 7. Mixed-BiDi outward teardrop orientation & 12dp menu horizontal margin. + state.update_selection(200.0, 500.0, 240.0, 500.0, 60.0, TextDirection::Rtl, true); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::RightLeaning + ); + assert!( + (state.end_handle.center_x - state.start_handle.center_x).abs() + > state.start_handle.radius * 2.0 + ); + state.update_selection(240.0, 500.0, 200.0, 500.0, 60.0, TextDirection::Ltr, true); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::RightLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert!( + (state.start_handle.center_x - state.end_handle.center_x).abs() + > state.start_handle.radius * 2.0 + ); + state.update_selection(10.0, 500.0, 40.0, 500.0, 60.0, TextDirection::Ltr, true); + let menu = state.action_menu_rect.expect("left-edge action menu"); + assert!( + menu.x >= 36.0 - 0.01, + "action menu x ({}) must keep >= 12dp (36px) left margin", + menu.x + ); + } +} diff --git a/packages/frontend/hosts/android/src/shell_runtime.rs b/packages/frontend/hosts/android/src/shell_runtime.rs new file mode 100644 index 0000000000..216d76e7d1 --- /dev/null +++ b/packages/frontend/hosts/android/src/shell_runtime.rs @@ -0,0 +1,637 @@ +//! Mobile product shell mounted as the root view of [`AndroidEditorRuntime`]. +//! +//! The shell owns routes, sheets, Search input, and the embedded page editor. The runtime +//! routes text input to whichever of them has focus, runs the platform back action through +//! `MobileBackCoordinator`, and keeps one local SQLite workspace in step with the shell: it +//! loads each page when the shell opens it and commits edits every second. + +use std::{ + path::Path, + rc::Rc, + sync::{Arc, Mutex}, + time::Duration, +}; + +use affine_mobile::{ + BackOutcome, MobileBackCoordinator, MobileRoute, MobileSheet, MobileShellView, MobileTab, + NativeSelectionUi, ThemePreference, +}; +use playground::{FormFactor, PlaygroundTheme}; +use ui::AppContext; + +use super::{ + editor_runtime::AndroidEditorRuntime, + runtime_root::{MountedWorkspace, RuntimeRoot, ShellHost}, + shell_workspace::{ShellLaunch, ShellWorkspace}, +}; + +/// Interval between commits of the shell's edits to its SQLite workspace. +const AUTOSAVE_INTERVAL: Duration = Duration::from_secs(1); + +/// Route of the shell as a C-ABI code. +pub(crate) fn route_code(route: &MobileRoute) -> u8 { + match route { + MobileRoute::Home => 1, + MobileRoute::Explorer => 2, + MobileRoute::Journals => 3, + MobileRoute::Search => 4, + MobileRoute::Page(_) => 5, + MobileRoute::Settings => 6, + } +} + +impl AndroidEditorRuntime { + /// Mount the mobile shell with the showcase workspaces until a local workspace is mounted. + pub(crate) fn new_shell( + width_dp: f32, + height_dp: f32, + density: f32, + form_factor: FormFactor, + launch: &ShellLaunch, + ) -> Option { + let state = launch.showcase_state(); + let host = ShellHost { + a11y: affine_mobile::InMemoryPlatformAccessibility::new(), + workspace: None, + }; + let sink = host.a11y.clone(); + Self::open( + width_dp, + height_dp, + density, + form_factor, + Some(host), + move |_, cx| { + cx.new(|cx| { + let mut shell = + MobileShellView::with_a11y_sink(state, Arc::new(Mutex::new(sink)), cx); + // The host draws the handles, the magnifier, and the action mode; the GPU + // keeps the caret and the selection highlight. + shell.set_native_selection_ui(NativeSelectionUi { + native_selection_ui: true, + native_suppresses_gpu_caret_and_selection: false, + }); + shell + }) + }, + RuntimeRoot::Shell, + ) + } + + /// Shell route code (`0` when the root is a bare page editor). + pub(crate) fn shell_route(&self) -> u8 { + let Some(shell) = self.root.shell() else { + return 0; + }; + self.app + .update(|cx| shell.read_with(cx, |s, _| route_code(&s.state.route))) + .unwrap_or(0) + } + + /// Theme of the root view. + pub(crate) fn root_theme(&self) -> Option { + match self.root { + RuntimeRoot::Editor(_) => self + .app + .update(|cx| self.view().read_with(cx, |v, _| v.theme())) + .ok(), + RuntimeRoot::Shell(shell) => self + .app + .update(|cx| { + shell.read_with(cx, |s, _| match s.state.resolved_theme() { + ui_tokens::ThemeMode::Light => PlaygroundTheme::Light, + ui_tokens::ThemeMode::Dark => PlaygroundTheme::Dark, + }) + }) + .ok(), + } + } + + /// Follow the platform appearance: the shell resolves its `System` preference with it. + /// Returns `false` when the root is a bare page editor. + pub(crate) fn set_shell_system_dark(&mut self, dark: bool) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + let _ = self.app.update(|cx| { + shell.update(cx, |s, _, cx| { + if s.state.system_dark != dark { + s.state.system_dark = dark; + if s.state.settings.theme_preference == ThemePreference::System { + cx.notify(); + } + } + }) + }); + self.window.request_frame_now(); + true + } + + /// Close a sheet, the drawer, or the page, or step back through the route history. + /// Returns `false` at the root route, where the platform handles back. + pub(crate) fn shell_back(&mut self) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + let handled = self.app.update(|cx| { + shell.update(cx, |s, _, cx| { + let now_ms = s.clock_ms(cx); + let handled = match MobileBackCoordinator::handle_back(&mut s.state, now_ms) { + // Without history left, another tab steps back to Home before the app exits. + BackOutcome::YieldToHostExit if s.state.route != MobileRoute::Home => { + s.state.switch_tab(MobileTab::Home, now_ms); + true + } + BackOutcome::YieldToHostExit => false, + _ => true, + }; + if handled { + cx.notify(); + } + handled + }) + }); + let handled = matches!(handled, Ok(true)); + if handled { + self.window.request_frame_now(); + } + handled + } + + /// Whether a shell text field holds keyboard focus: Search with no sheet above it, or the + /// drawer filter. + pub(crate) fn shell_search_focused(&self) -> bool { + self.shell_text_focus() == Some(true) + } + + /// Whether a sheet covers the shell while no shell text field has focus. Text and + /// composition edits are then dropped instead of reaching the page editor under the sheet. + pub(crate) fn shell_blocks_text_input(&self) -> bool { + self.shell_text_focus() == Some(false) + } + + /// `Some(true)` when a shell text field has focus, `Some(false)` when a sheet covers the + /// shell without one, and `None` when the shell takes no part in text input. + fn shell_text_focus(&self) -> Option { + let shell = self.root.shell()?; + self.app + .update(|cx| { + shell.update(cx, |s, window, _| { + let focused = s.search_focus.is_focused(window); + match s.state.active_sheet { + MobileSheet::None => { + (s.state.route == MobileRoute::Search && focused).then_some(true) + } + MobileSheet::WorkspaceDrawer => Some(focused), + _ => Some(false), + } + }) + }) + .ok() + .flatten() + } + + /// Ask the platform for the software keyboard when a touch leaves a shell field focused. + pub(crate) fn request_keyboard_for_search_focus(&mut self) { + if self.shell_search_focused() { + self.window.state.borrow_mut().soft_keyboard_requested = true; + } + } + + /// Latest accessibility tree that the shell published, as JSON. + pub(crate) fn shell_accessibility_json(&self) -> Option { + let tree = self.shell.as_ref()?.a11y.latest_tree()?; + serde_json::to_string(&tree).ok() + } + + fn mounted_workspace(&self) -> Option> { + let mounted = self.shell.as_ref()?.workspace.as_ref()?; + Some(Rc::clone(&mounted.store)) + } + + /// Replace the showcase with the local workspace + /// `/workspaces///.db`. Only the root document and + /// `db$*` tables load now; pages load when the shell opens them. + pub(crate) fn mount_shell_workspace( + &mut self, + base_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, + name: &str, + now_ms: i64, + ) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + if self.shell.as_ref().is_none_or(|h| h.workspace.is_some()) { + return false; + } + let now = self.app.update(|cx| cx.background_executor().now()); + let Ok((workspace, bridge)) = + ShellWorkspace::open(base_dir, space_type, peer, space_id, now_ms, now) + else { + return false; + }; + let store = Rc::new(workspace); + let autosave_store = Rc::clone(&store); + let mounted = self.app.update(|cx| { + let attached = shell.update(cx, |s, _, cx| { + let launch = ShellLaunch { + locale: s.state.locale(), + today: s.state.today_date.clone(), + dark: s.state.system_dark, + }; + *s.state_mut() = launch.local_workspace_state(space_id, name); + let attached = s.attach_workspace_bridge(bridge, now_ms).is_ok(); + cx.notify(); + attached + }); + let clock = cx.background_executor().clone(); + let autosave = cx.spawn(async move |cx| { + loop { + clock.timer(AUTOSAVE_INTERVAL).await; + let now_ms = autosave_store.now_ms(clock.now()); + let committed = shell.update(cx, |s, _, _| { + // A failed commit keeps the changes pending for the next tick. + let _ = autosave_store.commit(s, now_ms); + }); + if committed.is_err() { + break; + } + } + }); + (matches!(attached, Ok(true)), autosave) + }); + let (true, autosave) = mounted else { + return false; + }; + if let Some(host) = self.shell.as_mut() { + host.workspace = Some(MountedWorkspace { + store, + _autosave: autosave, + }); + } + self.window.request_frame_now(); + true + } + + /// Load the page that the shell shows from SQLite before it renders. A page loads once; a + /// page whose load failed loads again when the shell shows it the next time. + pub(crate) fn hydrate_shown_page(&mut self) { + let (Some(shell), Some(store)) = (self.root.shell(), self.mounted_workspace()) else { + return; + }; + let _ = self.app.update(|cx| { + let now_ms = store.now_ms(cx.background_executor().now()); + shell.update(cx, |s, _, cx| { + let shown = match &s.state.route { + MobileRoute::Page(doc_id) => Some(doc_id.clone()), + _ => None, + }; + if !store.needs_load(shown.as_deref()) { + return; + } + let Some(doc_id) = shown else { + return; + }; + let Some(Ok(mut bridge)) = s.take_workspace_bridge(now_ms) else { + return; + }; + let loaded = store.hydrate(&mut bridge, &doc_id, now_ms); + if s.attach_workspace_bridge(bridge, now_ms).is_ok() && loaded { + cx.notify(); + } + }) + }); + } + + /// Commit the shell's local changes to the mounted SQLite workspace now. + /// Returns the number of written rows, or `-1` when nothing is mounted or the commit fails. + pub(crate) fn flush_shell_workspace(&mut self) -> i64 { + let (Some(shell), Some(store)) = (self.root.shell(), self.mounted_workspace()) else { + return -1; + }; + self.app + .update(|cx| { + let now_ms = store.now_ms(cx.background_executor().now()); + shell.read_with(cx, |s, _| store.commit(s, now_ms)) + }) + .ok() + .and_then(Result::ok) + .map_or(-1, |n| n.min(i64::MAX as usize) as i64) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn node_center(rt: &AndroidEditorRuntime, prefix: &str) -> Option<(f32, f32)> { + let json = rt.shell_accessibility_json()?; + let tree: affine_client::AccessibilityTree = serde_json::from_str(&json).ok()?; + tree.nodes + .values() + .filter(|n| n.id.starts_with(prefix) && n.bounds.width > 0.0 && n.bounds.height > 0.0) + .min_by(|a, b| a.bounds.y.total_cmp(&b.bounds.y)) + .map(|n| { + ( + n.bounds.x + n.bounds.width * 0.5, + n.bounds.y + n.bounds.height * 0.5, + ) + }) + } + + fn tap(rt: &mut AndroidEditorRuntime, id: u64, prefix: &str) { + let (x, y) = node_center(rt, prefix).unwrap_or_else(|| panic!("node {prefix}")); + rt.dispatch_touch(id, 0, x, y); + rt.dispatch_touch(id, 2, x, y); + let _ = rt.render_frame(); + } + + fn focus_page_text(rt: &mut AndroidEditorRuntime) { + let _ = rt.app.update(|cx| { + rt.view() + .update(cx, |v, w, cx| v.focus_first_text_block(w, cx)) + }); + let _ = rt.render_frame(); + } + + fn units(text: &str) -> Vec { + text.encode_utf16().collect() + } + + fn launch() -> ShellLaunch { + ShellLaunch::new("zh-CN", 1_764_000_000_000, 480, false) + } + + fn open_sheet(rt: &mut AndroidEditorRuntime, sheet: MobileSheet) { + if let Some(shell) = rt.root.shell() { + let _ = rt.app.update(|cx| { + shell.update(cx, |s, _, cx| { + s.state.open_sheet(sheet, 0.0); + cx.notify(); + }) + }); + } + let _ = rt.render_frame(); + } + + fn active_sheet(rt: &AndroidEditorRuntime) -> Option { + let shell = rt.root.shell()?; + rt.app + .update(|cx| shell.read_with(cx, |s, _| s.state.active_sheet)) + .ok() + } + + /// Load page `doc_id` the way `hydrate_shown_page` does, without showing it. + fn load_page(rt: &mut AndroidEditorRuntime, doc_id: &str) -> bool { + let (Some(shell), Some(store)) = (rt.root.shell(), rt.mounted_workspace()) else { + return false; + }; + rt.app + .update(|cx| { + shell.update(cx, |s, _, _| { + let Some(Ok(mut bridge)) = s.take_workspace_bridge(10) else { + return false; + }; + let loaded = store.hydrate(&mut bridge, doc_id, 10); + s.attach_workspace_bridge(bridge, 10).is_ok() && loaded + }) + }) + .unwrap_or(false) + } + + /// Pages that the bridge's session holds in memory. + fn loaded_pages(rt: &AndroidEditorRuntime) -> usize { + let Some(shell) = rt.root.shell() else { + return 0; + }; + rt.app + .update(|cx| { + shell.read_with(cx, |s, _| { + s.workspace_bridge() + .map_or(0, |b| b.session().open_doc_revisions().count()) + }) + }) + .unwrap_or(0) + } + + fn back_to_home(rt: &mut AndroidEditorRuntime) { + for _ in 0..4 { + if rt.shell_route() == 1 { + return; + } + assert!(rt.handle_back()); + let _ = rt.render_frame(); + } + assert_eq!(rt.shell_route(), 1, "back must reach Home"); + } + + #[test] + fn shell_routes_page_ime_search_ime_and_system_back() { + let mut rt = + AndroidEditorRuntime::new_shell(412.0, 915.0, 2.625, FormFactor::Phone, &launch()) + .expect("shell runtime"); + let _ = rt.render_frame(); + assert_eq!(rt.shell_route(), 1, "launch shows Home"); + assert!(!rt.wants_software_keyboard() && rt.utf16_len() == 0); + + // A Home row opens the Page route; the embedded editor owns the InputConnection. + tap(&mut rt, 1, "mobile.home.doc."); + assert_eq!(rt.shell_route(), 5); + focus_page_text(&mut rt); + let before = rt.utf16_len(); + rt.set_composing_text_utf16(&units("ni"), 1); + assert_eq!(rt.composing_range().map(|(s, e)| e - s), Some(2)); + rt.commit_text_utf16(&units("你好 Hi"), 1); + assert_eq!(rt.composing_range(), None); + assert_eq!(rt.utf16_len(), before + 5); + assert!(String::from_utf16_lossy(&rt.utf16_text()).contains("你好 Hi")); + assert!(rt.caret_rect_dp().is_some()); + + // A sheet or the drawer above the page owns touches and back: system back closes it + // before the page editor sees back, and the page editor exposes no caret meanwhile. + let page_text = rt.utf16_text(); + // An overlay sheet takes the focus from the editor, so the keyboard has no text; the + // drawer leaves the focus where it is. `(sheet, the editor keeps the focus)` + for (sheet, editor_focus) in [ + (MobileSheet::DocActions, false), + (MobileSheet::WorkspaceDrawer, true), + ] { + open_sheet(&mut rt, sheet); + // Text and composition edits under the sheet are dropped. + rt.set_composing_text_utf16(&units("ni"), 1); + rt.commit_text_utf16(&units("LEAK"), 1); + let _ = rt.render_frame(); + let shown = if editor_focus { + page_text.clone() + } else { + Vec::new() + }; + assert_eq!(rt.utf16_text(), shown, "{sheet:?} input text"); + assert!( + rt.app.update(|cx| rt.root.editor(cx)).is_none(), + "{sheet:?}" + ); + assert_eq!( + rt.pack_document_selection_floats()[0], + 0.0, + "{sheet:?} hides the page selection handles" + ); + assert!(rt.handle_back(), "back closes {sheet:?}"); + let _ = rt.render_frame(); + assert_eq!(active_sheet(&rt), Some(MobileSheet::None)); + assert_eq!( + rt.shell_route(), + 5, + "back after {sheet:?} stays on the page" + ); + focus_page_text(&mut rt); + assert_eq!(rt.utf16_text(), page_text, "{sheet:?} keeps the page text"); + } + + // Dark mode follows the system while the shell runs. + assert!(!rt.is_dark_theme()); + assert!(rt.set_shell_system_dark(true)); + assert!(rt.is_dark_theme()); + assert!(rt.set_shell_system_dark(false)); + assert!(!rt.is_dark_theme()); + + // System back closes the page, then the Search field takes the IME. + assert!(rt.handle_back()); + let _ = rt.render_frame(); + assert_eq!(rt.shell_route(), 1); + assert_eq!(rt.utf16_len(), 0); + let _ = rt.take_software_keyboard_request(); + tap(&mut rt, 2, "mobile.tab.search"); + assert_eq!(rt.shell_route(), 4); + tap(&mut rt, 3, "mobile.search.input"); + assert!(rt.take_software_keyboard_request() && rt.wants_software_keyboard()); + assert_eq!(rt.utf16_len(), 0, "Search launches with an empty query"); + rt.set_composing_text_utf16(&units("tong"), 1); + rt.commit_text_utf16(&units("同步"), 1); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), "同步"); + + // Back steps through the history to Home, then yields to the Activity. + let mut steps = 0; + while rt.handle_back() { + steps += 1; + assert!(steps < 8, "back must reach the root route"); + } + assert_eq!(rt.shell_route(), 1); + + // The drawer filter, once it holds focus, takes text: the runtime stops dropping edits + // and asks for the keyboard. + open_sheet(&mut rt, MobileSheet::WorkspaceDrawer); + if let Some(shell) = rt.root.shell() { + let _ = rt + .app + .update(|cx| shell.update(cx, |s, window, cx| window.focus(&s.search_focus, cx))); + } + assert!(rt.shell_search_focused() && !rt.shell_blocks_text_input()); + rt.commit_text_utf16(&units("filter"), 1); + assert!(rt.handle_back(), "back closes the drawer"); + let _ = rt.render_frame(); + assert!(!rt.shell_search_focused() && !rt.shell_blocks_text_input()); + assert_eq!(rt.shell_route(), 1); + } + + #[test] + fn shell_local_workspace_loads_pages_on_open_and_autosaves_every_second() { + let base = std::env::temp_dir().join(format!( + "affine-android-shell-workspace-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&base); + let texts = ["Durable 本地", "Second page"]; + let mut writer = + AndroidEditorRuntime::new_shell(412.0, 915.0, 2.625, FormFactor::Phone, &launch()) + .expect("shell runtime"); + assert!(writer.mount_shell_workspace(&base, "workspace", "local", "ws-local", "本地", 10)); + let _ = writer.render_frame(); + assert!( + node_center(&writer, "mobile.home.doc.").is_none(), + "no showcase rows" + ); + for (id, text) in (1..).zip(texts) { + tap(&mut writer, id, "mobile.home.new_doc_btn"); + assert_eq!(writer.shell_route(), 5); + focus_page_text(&mut writer); + writer.commit_text_utf16(&units(text), 1); + // A commit while a sheet covers the page never reaches the stored page. + open_sheet(&mut writer, MobileSheet::DocActions); + writer.commit_text_utf16(&units("LEAK"), 1); + assert!(writer.handle_back(), "back closes the sheet"); + let _ = writer.render_frame(); + back_to_home(&mut writer); + } + + // A page whose load fails is not retried while it stays shown, and is tried again once + // the shell shows it again. + let mut early = + AndroidEditorRuntime::new_shell(412.0, 915.0, 2.625, FormFactor::Phone, &launch()) + .expect("early shell"); + assert!(early.mount_shell_workspace(&base, "workspace", "local", "ws-local", "Local", 15)); + let early_store = early.mounted_workspace().expect("early workspace"); + for attempt in 0..2 { + assert!( + early_store.needs_load(Some("missing-page")), + "attempt {attempt}" + ); + assert!( + !load_page(&mut early, "missing-page"), + "a missing page fails to load" + ); + assert!( + !early_store.needs_load(Some("missing-page")), + "no retry while shown" + ); + assert!(!early_store.needs_load(None), "no page shows"); + } + drop(early); + + // One second of scheduler time commits both pages without an explicit flush. The due + // timer wakes the autosave task through the host waker; once the task has committed, + // it arms the next tick, so the drain reports a pending timer again. + let (wake_tx, wake_rx) = std::sync::mpsc::channel(); + writer.set_waker(Some(std::sync::Arc::new(move || { + let _ = wake_tx.send(()); + }))); + writer + .dispatcher + .advance_test_clock(std::time::Duration::from_millis(1_100)); + while writer.drain_tasks().is_none() { + wake_rx + .recv_timeout(std::time::Duration::from_secs(1)) + .expect("autosave wakeup"); + } + writer.set_waker(None); + + // A second runtime on the same database loads no page at mount and one page on open. + let mut reader = + AndroidEditorRuntime::new_shell(412.0, 915.0, 2.625, FormFactor::Phone, &launch()) + .expect("reader shell"); + assert!(reader.mount_shell_workspace(&base, "workspace", "local", "ws-local", "本地", 20)); + let _ = reader.render_frame(); + assert_eq!(loaded_pages(&reader), 0, "mount decodes no page"); + tap(&mut reader, 30, "mobile.home.doc."); + assert_eq!(reader.shell_route(), 5); + assert_eq!( + loaded_pages(&reader), + 1, + "opening a page loads only that page" + ); + focus_page_text(&mut reader); + let shown = String::from_utf16_lossy(&reader.utf16_text()); + assert!(texts.contains(&shown.as_str()), "reader shows {shown:?}"); + + assert_eq!( + writer.flush_shell_workspace(), + 0, + "autosave left no pending change" + ); + drop((writer, reader)); + let _ = std::fs::remove_dir_all(&base); + } +} diff --git a/packages/frontend/hosts/android/src/shell_workspace.rs b/packages/frontend/hosts/android/src/shell_workspace.rs new file mode 100644 index 0000000000..ebeb5eedc7 --- /dev/null +++ b/packages/frontend/hosts/android/src/shell_workspace.rs @@ -0,0 +1,223 @@ +//! Local SQLite workspace behind the mobile shell, and the shell launch state. +//! +//! The host opens one allowlisted `//.db` workspace in place, loads +//! each page into the [`MobileWorkspaceBridge`] when the shell opens it, and commits shell edits +//! back through `SqliteWorkspaceStore::flush_session_mutations`. + +use std::{cell::RefCell, collections::HashSet, path::Path}; + +use affine_client::{ + ClientError, ClientResult, DirectKind, FolderForestCache, HostKind, LinkGraph, NavHistory, + NavTarget, Origin, Scope, SqliteWorkspaceStore, +}; +use affine_mobile::{ + MobileAppState, MobileLocale, MobileShellView, MobileWorkspaceBridge, ThemePreference, + seed_showcase_state, +}; +use ui::scheduler::Instant; +use ui_tokens::ThemeMode; + +/// Locale, date, and appearance that the platform gives the shell at launch. +#[derive(Clone, Debug)] +pub(crate) struct ShellLaunch { + pub(crate) locale: MobileLocale, + pub(crate) today: String, + pub(crate) dark: bool, +} + +impl ShellLaunch { + /// Resolve the launch values from a BCP 47 language tag, Unix epoch milliseconds, and the + /// local UTC offset in minutes. + pub(crate) fn new( + language_tag: &str, + now_ms: i64, + utc_offset_minutes: i32, + dark: bool, + ) -> Self { + let local_ms = now_ms.saturating_add(i64::from(utc_offset_minutes) * 60_000); + let today = chrono::DateTime::from_timestamp_millis(local_ms) + .map(|t| t.format("%Y-%m-%d").to_string()) + .unwrap_or_else(|| "1970-01-01".to_string()); + let code = language_tag.split(['-', '_']).next().unwrap_or("en"); + Self { + locale: MobileLocale::parse(&code.to_ascii_lowercase()), + today, + dark, + } + } + + /// Deterministic showcase workspaces, shown until the host mounts a local workspace. + pub(crate) fn showcase_state(&self) -> MobileAppState { + let mut state = seed_showcase_state(self.locale, self.theme(), &self.today); + state.settings.theme_preference = ThemePreference::System; + state.system_dark = self.dark; + state.search_query.clear(); + state + } + + /// One empty workspace with id `space_id`, which a mounted bridge fills. + pub(crate) fn local_workspace_state(&self, space_id: &str, name: &str) -> MobileAppState { + let mut state = self.showcase_state(); + state.workspace_store.truncate(1); + state.active_workspace_idx = 0; + state.settings.account_email.clear(); + state.settings.account_plan.clear(); + let scope = Scope::new("local", "", space_id); + let mut history = NavHistory::new(); + history.push( + scope.clone(), + NavTarget::Home, + Origin::Direct(DirectKind::Home), + None, + ); + let ws = &mut state.workspace_store[0]; + let stale: Vec = ws.doc_crdt_updates().keys().cloned().collect(); + for doc_id in stale { + ws.remove_doc_crdt_update(&doc_id); + } + ws.docs_mut().clear(); + ws.summary.id = space_id.to_string(); + ws.summary.name = name.to_string(); + ws.summary.doc_count = 0; + ws.summary.is_cloud = false; + ws.scope = scope; + ws.folder_rows.clear(); + ws.folder_revision = ws.folder_revision.saturating_add(1); + ws.folder_cache = FolderForestCache::new(); + ws.collections.clear(); + ws.tags.clear(); + ws.link_graph = LinkGraph::new(); + ws.history = history; + ws.collapsed_folders.clear(); + state + } + + fn theme(&self) -> ThemeMode { + if self.dark { + ThemeMode::Dark + } else { + ThemeMode::Light + } + } +} + +/// Open local SQLite workspace that the shell edits. +pub(crate) struct ShellWorkspace { + runtime: tokio::runtime::Runtime, + store: SqliteWorkspaceStore, + /// Unix epoch milliseconds and scheduler time when the workspace was mounted. + mounted: (i64, Instant), + /// Pages that loaded from SQLite into the session. + hydrated: RefCell>, + /// Shown page whose last load failed, so the shell does not retry it on every frame. + failed: RefCell>, +} + +impl ShellWorkspace { + /// Open `/workspaces///.db` and load its root + /// document and `db$*` tables into a bridge. Pages load on demand through [`Self::hydrate`]. + pub(crate) fn open( + base_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, + now_ms: i64, + now: Instant, + ) -> ClientResult<(Self, MobileWorkspaceBridge)> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| ClientError::Store(format!("starting the SQLite runtime: {e}")))?; + let client_id = blocksuite_playground_doc::try_random_client_id() + .map_err(|e| ClientError::Store(format!("making a client ID: {e}")))?; + let store = runtime.block_on(SqliteWorkspaceStore::open( + base_dir, space_type, peer, space_id, + ))?; + let session = runtime.block_on(store.load_workspace_session( + "local", + client_id, + HostKind::Native, + "", + "https://app.affine.pro", + now_ms, + ))?; + let workspace = Self { + runtime, + store, + mounted: (now_ms, now), + hydrated: RefCell::default(), + failed: RefCell::default(), + }; + Ok((workspace, MobileWorkspaceBridge::new(session))) + } + + /// Unix epoch milliseconds at scheduler time `now`. + pub(crate) fn now_ms(&self, now: Instant) -> i64 { + let (mounted_ms, mounted_at) = self.mounted; + let elapsed = now.saturating_duration_since(mounted_at).as_millis(); + mounted_ms.saturating_add(elapsed.min(i64::MAX as u128) as i64) + } + + /// Load page `doc_id` from SQLite into the bridge's session. Returns `true` when the page + /// was not in the session and now is. A failed load marks the page so that the shell tries + /// it again only after it leaves and reopens the page. + pub(crate) fn hydrate( + &self, + bridge: &mut MobileWorkspaceBridge, + doc_id: &str, + now_ms: i64, + ) -> bool { + if bridge.session().doc_revision(doc_id).is_some() { + self.hydrated.borrow_mut().insert(doc_id.to_string()); + return false; + } + let loaded = self + .runtime + .block_on( + self.store + .open_or_hydrate_document(bridge.session_mut(), doc_id, now_ms), + ) + .is_ok(); + if loaded { + self.hydrated.borrow_mut().insert(doc_id.to_string()); + } else { + *self.failed.borrow_mut() = Some(doc_id.to_string()); + } + loaded + } + + /// Whether the shown page `doc_id` still needs a load. `None` means that no page shows, + /// which allows another load of a page that failed before. + pub(crate) fn needs_load(&self, doc_id: Option<&str>) -> bool { + let mut failed = self.failed.borrow_mut(); + if failed.as_deref() != doc_id { + *failed = None; + } + doc_id.is_some_and(|id| failed.is_none() && !self.hydrated.borrow().contains(id)) + } + + /// Merge the shell's edits into its bridge and commit the pending local changes. Without + /// pending changes this returns `Ok(0)` before any SQLite access; the WAL checkpoint runs + /// only after rows were written. + pub(crate) fn commit(&self, shell: &MobileShellView, now_ms: i64) -> ClientResult { + let Some(mut bridge) = shell.workspace_bridge() else { + return Ok(0); + }; + bridge.sync_from_state(&shell.state, now_ms)?; + let written = self.runtime.block_on(self.store.flush_session_mutations( + bridge.session_mut(), + None, + now_ms, + ))?; + if written > 0 { + self.runtime.block_on(self.store.checkpoint())?; + } + Ok(written) + } +} + +impl Drop for ShellWorkspace { + fn drop(&mut self) { + self.runtime.block_on(self.store.close()); + } +} diff --git a/packages/frontend/hosts/android/src/storage.rs b/packages/frontend/hosts/android/src/storage.rs new file mode 100644 index 0000000000..acbccf441f --- /dev/null +++ b/packages/frontend/hosts/android/src/storage.rs @@ -0,0 +1,828 @@ +//! In-place Android SQLite WAL co-storage backed by `affine-store`. +//! +//! Enforces: +//! - Exact `0.27.5` path layout: `/workspaces///.db` +//! - Exact `0.27.5` peer character sanitization via `affine_store::sqlite::sanitize_peer_name` +//! - Iron Rule F1: never scan disk `*.db` files to discover local workspaces; +//! open only workspace IDs present in the ordered `affine-local-workspace` allowlist. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +use affine_store::sqlite::{ + DocDiff, SqliteDocStorage, resolve_workspace_db_path, sanitize_peer_name, +}; +pub use affine_store::sync::SpaceType; +use affine_store::workspace_db::PendingDocUpdate; +use tokio::runtime::{Builder, Runtime}; + +/// Explicit SQLite busy timeout (milliseconds) applied to maintenance connections. +pub const SQLITE_BUSY_TIMEOUT_MS: u64 = 5_000; + +/// Result of a non-blocking `PRAGMA wal_checkpoint(PASSIVE);` call. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PassiveCheckpointResult { + pub busy: i64, + pub log: i64, + pub checkpointed: i64, +} + +/// Legacy `localStorage` key storing the ordered list of local workspace IDs. +pub const LOCAL_WORKSPACE_LOCAL_STORAGE_KEY: &str = "affine-local-workspace"; + +/// Filters a raw WebView `evaluateJavascript` snapshot JSON payload using +/// `affine-legacy-import`'s single allowlist, retaining all top-level metadata +/// (`origin`, `length`, sorted `keys`, `removedKeys`, `verified`, `idbBlocked`, +/// `idbTouchCount`) while stripping non-allowlisted keys from `entries`. +/// Returns `None` if `payload_json` is `"null"`, invalid JSON, or not a JSON object. +pub fn filter_legacy_local_storage_probe_json(payload_json: &str) -> Option { + let trimmed = payload_json.trim(); + if trimmed.is_empty() || trimmed == "null" { + return None; + } + let unwrapped_owned: String; + let effective_json = if trimmed.starts_with('"') { + unwrapped_owned = serde_json::from_str::(trimmed).ok()?; + unwrapped_owned.as_str() + } else { + trimmed + }; + let mut obj = + serde_json::from_str::>(effective_json).ok()?; + if let Some(serde_json::Value::Array(keys)) = obj.get_mut("keys") { + let mut sorted: Vec = keys + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect(); + if sorted.len() == keys.len() { + sorted.sort(); + *keys = sorted.into_iter().map(serde_json::Value::String).collect(); + } + } + let mut filtered_entries = serde_json::Map::new(); + if let Some(serde_json::Value::Object(raw_entries)) = obj.get("entries") { + for (k, v) in raw_entries { + if affine_legacy_import::is_permitted_sentinel_entry_key(k) { + filtered_entries.insert(k.clone(), v.clone()); + } + } + } + obj.insert( + "entries".to_string(), + serde_json::Value::Object(filtered_entries), + ); + serde_json::to_string(&serde_json::Value::Object(obj)).ok() +} + +/// Errors returned by the Android SQLite storage bridge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AndroidStorageError { + WorkspaceNotAllowlisted(String), + InvalidSpaceType(String), + NotConnected(String), + InvalidPath(String), + Store(String), + Io(String), +} + +impl std::fmt::Display for AndroidStorageError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::WorkspaceNotAllowlisted(id) => { + write!( + f, + "workspace {id:?} is not in the affine-local-workspace allowlist" + ) + } + Self::InvalidSpaceType(st) => write!(f, "invalid space type: {st:?}"), + Self::NotConnected(key) => write!(f, "sqlite storage not connected: {key:?}"), + Self::InvalidPath(msg) => write!(f, "invalid storage path: {msg}"), + Self::Store(msg) => write!(f, "sqlite store error: {msg}"), + Self::Io(msg) => write!(f, "storage I/O error: {msg}"), + } + } +} + +impl std::error::Error for AndroidStorageError {} + +/// Parses `affine-local-workspace` JSON into an ordered, deduplicated list of workspace IDs +/// via `affine-legacy-import`. +pub use affine_legacy_import::parse_local_workspace_ids; + +/// Resolves `/workspaces///.db`. +pub fn resolve_android_db_path( + files_dir: &Path, + space_type: SpaceType, + peer: &str, + space_id: &str, +) -> Result { + resolve_workspace_db_path(files_dir, space_type.as_str(), peer, space_id) + .map_err(|e| AndroidStorageError::InvalidPath(e.to_string())) +} + +/// Resolves `/workspaces/userspace//.db`. +pub fn resolve_userspace_db_path( + files_dir: &Path, + peer: &str, + user_id: &str, +) -> Result { + resolve_android_db_path(files_dir, SpaceType::Userspace, peer, user_id) +} + +/// Allowlist-only local workspace catalog (Iron Rule F1: zero disk `*.db` scanning). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AndroidWorkspaceCatalog { + ordered_ids: Vec, + id_set: BTreeSet, +} + +impl AndroidWorkspaceCatalog { + /// Builds a catalog from an ordered list of allowlisted workspace IDs. + pub fn from_ids(ids: impl IntoIterator) -> Self { + let mut ordered_ids = Vec::new(); + let mut id_set = BTreeSet::new(); + for id in ids { + if id_set.insert(id.clone()) { + ordered_ids.push(id); + } + } + Self { + ordered_ids, + id_set, + } + } + + /// Builds a catalog directly from the `affine-local-workspace` JSON value. + #[cfg(test)] + pub fn from_local_storage_json(raw_json: &str) -> Self { + Self::from_ids(parse_local_workspace_ids(raw_json)) + } + + /// Returns the ordered allowlisted workspace IDs. + pub fn ids(&self) -> &[String] { + &self.ordered_ids + } + + /// Returns `true` if `space_id` is in the explicit allowlist. + pub fn contains(&self, space_id: &str) -> bool { + self.id_set.contains(space_id) + } + + /// Resolves paths only for allowlisted workspace IDs without scanning disk. + pub fn resolve_all_paths( + &self, + files_dir: &Path, + peer: &str, + ) -> Result, AndroidStorageError> { + let mut out = Vec::with_capacity(self.ordered_ids.len()); + for id in &self.ordered_ids { + let path = resolve_android_db_path(files_dir, SpaceType::Workspace, peer, id)?; + out.push((id.clone(), path)); + } + Ok(out) + } +} + +/// Synchronous bridge over `affine_store::sqlite::SqliteDocStorage` for JNI callers. +pub struct AndroidSqliteBridge { + storages: BTreeMap, + runtime: Option, +} + +impl Drop for AndroidSqliteBridge { + fn drop(&mut self) { + self.close_all(); + } +} + +impl std::fmt::Debug for AndroidSqliteBridge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AndroidSqliteBridge") + .field("connected_keys", &self.storages.keys().collect::>()) + .finish() + } +} + +impl Default for AndroidSqliteBridge { + fn default() -> Self { + Self::new() + } +} + +impl AndroidSqliteBridge { + /// Creates an idle storage bridge without spawning threads until first connect. + pub fn new() -> Self { + Self { + runtime: None, + storages: BTreeMap::new(), + } + } + + fn runtime_ref(slot: &mut Option) -> Result<&Runtime, AndroidStorageError> { + if slot.is_none() { + let rt = Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| AndroidStorageError::Io(e.to_string()))?; + *slot = Some(rt); + } + Ok(slot.as_ref().expect("runtime initialized")) + } + + /// Builds a deterministic connection key for `(space_type, peer, space_id)`. + pub fn connection_key(space_type: SpaceType, peer: &str, space_id: &str) -> String { + format!( + "{}:{}:{space_id}", + space_type.as_str(), + sanitize_peer_name(peer) + ) + } + + /// Opens a workspace SQLite DB in place (WAL + 5-step migrations). + /// + /// - For `peer == "local"`, enforces fail-closed Iron Rule F1: requires + /// `local_import_ready` and `catalog.contains(space_id)` so deleted local + /// workspace `.db` files on disk are never resurrected. + /// - For cloud peers (`peer != "local"`), opens the canonical co-storage path + /// directly without requiring membership in `affine-local-workspace`. + pub fn connect_workspace( + &mut self, + files_dir: &Path, + peer: &str, + space_id: &str, + catalog: &AndroidWorkspaceCatalog, + local_import_ready: bool, + ) -> Result { + if peer == "local" && (!local_import_ready || !catalog.contains(space_id)) { + return Err(AndroidStorageError::WorkspaceNotAllowlisted( + space_id.to_string(), + )); + } + self.connect_internal(files_dir, SpaceType::Workspace, peer, space_id) + } + + /// Opens an allowlisted local workspace SQLite DB in place. + pub fn connect_allowlisted_workspace( + &mut self, + files_dir: &Path, + peer: &str, + space_id: &str, + catalog: &AndroidWorkspaceCatalog, + ) -> Result { + self.connect_workspace(files_dir, peer, space_id, catalog, true) + } + + /// Returns `true` when the local workspace `space_id` is currently connected. + pub fn is_local_workspace_connected(&self, space_id: &str) -> bool { + let key = Self::connection_key(SpaceType::Workspace, "local", space_id); + self.storages.contains_key(&key) + } + + /// Returns `true` when `connection_key` is currently open in `storages`. + pub fn has_connection(&self, connection_key: &str) -> bool { + self.storages.contains_key(connection_key) + } + + /// Returns `true` when at least one SQLite workspace connection is currently open. + pub fn has_any_connection(&self) -> bool { + !self.storages.is_empty() + } + + /// Returns the first connected `workspace:local:` connection key, if any. + pub fn first_connected_local_workspace_key(&self) -> Option { + self.storages + .keys() + .find(|k| k.starts_with("workspace:local:")) + .cloned() + } + + /// Closes and evicts any open `workspace:local:` connections whose ID is + /// no longer in `catalog` (called when the local allowlist shrinks or updates). + pub fn evict_unlisted_local_workspaces(&mut self, catalog: &AndroidWorkspaceCatalog) -> usize { + const LOCAL_PREFIX: &str = "workspace:local:"; + let stale: Vec = self + .storages + .keys() + .filter_map(|k| { + k.strip_prefix(LOCAL_PREFIX) + .filter(|id| !catalog.contains(id)) + .map(|_| k.clone()) + }) + .collect(); + let mut evicted = 0usize; + for key in stale { + if self.close(&key) { + evicted += 1; + } + } + evicted + } + + /// Opens a `userspace` SQLite DB in place (`/workspaces/userspace//.db`). + pub fn open_userspace( + &mut self, + files_dir: &Path, + peer: &str, + user_id: &str, + ) -> Result { + self.connect_internal(files_dir, SpaceType::Userspace, peer, user_id) + } + + fn connect_internal( + &mut self, + files_dir: &Path, + space_type: SpaceType, + peer: &str, + space_id: &str, + ) -> Result { + let key = Self::connection_key(space_type, peer, space_id); + if self.storages.contains_key(&key) { + return Ok(key); + } + let db_path = resolve_android_db_path(files_dir, space_type, peer, space_id)?; + if let Some(parent) = db_path.parent() { + std::fs::create_dir_all(parent).map_err(|e| AndroidStorageError::Io(e.to_string()))?; + } + let path_str = db_path.to_string_lossy().to_string(); + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = rt + .block_on(async { + let storage = SqliteDocStorage::new(path_str); + storage.connect().await?; + storage.set_space_id(space_id).await?; + Ok::(storage) + }) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + + self.storages.insert(key.clone(), storage); + Ok(key) + } + + /// Pushes a single CRDT update with an explicit deterministic timestamp (`now_ms`). + pub fn push_update( + &mut self, + connection_key: &str, + doc_id: &str, + update: &[u8], + now_ms: i64, + ) -> Result { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let ts = rt + .block_on(storage.push_update(doc_id, update, now_ms)) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + Ok(affine_store::sqlite::naive_utc_to_millis(ts)) + } + + /// Atomically pushes a batch of updates inside a single `BEGIN IMMEDIATE` transaction. + pub fn push_updates_batch( + &mut self, + connection_key: &str, + updates: &[PendingDocUpdate], + create_for_peer: Option<&str>, + now_ms: i64, + ) -> Result { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let committed = rt + .block_on(storage.push_updates_batch(updates, create_for_peer, now_ms)) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + Ok(committed.len()) + } + + /// Reads and compacts a document's merged binary state from SQLite. + pub fn get_doc( + &mut self, + connection_key: &str, + doc_id: &str, + ) -> Result>, AndroidStorageError> { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let rec = rt + .block_on(storage.get_doc(doc_id)) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + Ok(rec.map(|r| r.bin)) + } + + /// Reads a non-deleted blob's raw bytes from SQLite by content-addressed key. + pub fn get_blob( + &mut self, + connection_key: &str, + key: &str, + ) -> Result>, AndroidStorageError> { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let rec = rt + .block_on(storage.get_blob(key)) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + Ok(rec.map(|r| r.data)) + } + + /// Atomically ingests a shared item into the connected SQLite workspace using the shared + /// `0.27.5`-compatible `affine_store::share_ingest::ingest_share_item_into_sqlite` transaction. + pub fn ingest_share_item( + &mut self, + connection_key: &str, + req: &affine_store::share_ingest::ShareIngestRequest, + blob_bytes: &[u8], + ) -> Result { + let workspace_id = connection_key.rsplit(':').next().unwrap_or("").to_string(); + let db_path = self + .storages + .get(connection_key) + .map(|s| PathBuf::from(s.path())) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let rt = Self::runtime_ref(&mut self.runtime)?; + rt.block_on(affine_store::share_ingest::ingest_share_item_into_sqlite( + &db_path, + &workspace_id, + req, + blob_bytes, + )) + .map_err(|e| AndroidStorageError::Store(e.to_string())) + } + + /// Returns `true` when `share_id` has a committed receipt in `share_ingest_receipts`. + pub fn is_share_durably_committed( + &mut self, + connection_key: &str, + share_id: &str, + ) -> Result { + let db_path = self + .storages + .get(connection_key) + .map(|s| PathBuf::from(s.path())) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let rt = Self::runtime_ref(&mut self.runtime)?; + rt.block_on(affine_store::share_ingest::is_share_durably_committed( + &db_path, share_id, + )) + .map_err(|e| AndroidStorageError::Store(e.to_string())) + } + + /// Computes the merged diff and state vector for sync round-trips. + pub fn get_doc_diff( + &mut self, + connection_key: &str, + doc_id: &str, + remote_state_vector: Option<&[u8]>, + ) -> Result, AndroidStorageError> { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + rt.block_on(storage.get_doc_diff(doc_id, remote_state_vector)) + .map_err(|e| AndroidStorageError::Store(e.to_string())) + } + + /// Flushes the WAL journal using non-blocking `PRAGMA wal_checkpoint(PASSIVE);`, + /// safe for Android `onStop()`. + pub fn checkpoint_passive( + &mut self, + connection_key: &str, + ) -> Result { + let rt = Self::runtime_ref(&mut self.runtime)?; + let storage = self + .storages + .get(connection_key) + .ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?; + let (busy, log, checkpointed) = rt + .block_on(storage.checkpoint_passive()) + .map_err(|e| AndroidStorageError::Store(e.to_string()))?; + Ok(PassiveCheckpointResult { + busy, + log, + checkpointed, + }) + } + + /// Runs non-blocking `PRAGMA wal_checkpoint(PASSIVE);` on every open SQLite DB + /// (called from `MainActivity.onStop()`), returning the count of checkpointed DBs. + pub fn checkpoint_all_passive(&mut self) -> usize { + let keys: Vec = self.storages.keys().cloned().collect(); + let mut count = 0usize; + for key in keys { + if self.checkpoint_passive(&key).is_ok() { + count += 1; + } + } + count + } + + /// Flushes the WAL journal into the main `.db` file (delegates to non-blocking `PASSIVE`). + pub fn checkpoint(&mut self, connection_key: &str) -> Result<(), AndroidStorageError> { + let _ = self.checkpoint_passive(connection_key)?; + Ok(()) + } + + /// Closes a single connected database cleanly. + pub fn close(&mut self, connection_key: &str) -> bool { + let Some(storage) = self.storages.remove(connection_key) else { + return false; + }; + if let Some(rt) = &self.runtime { + rt.block_on(storage.close()); + } + true + } + + /// Closes all open databases cleanly. + pub fn close_all(&mut self) { + let storages = std::mem::take(&mut self.storages); + if let Some(rt) = &self.runtime { + for (_, storage) in storages { + rt.block_on(storage.close()); + } + } + } +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + use std::time::Duration; + + use affine_store::sqlite::get_migrator; + use sqlx::Connection; + use sqlx::migrate::{MigrateDatabase, Migration, Migrator}; + use sqlx::sqlite::{Sqlite, SqliteConnectOptions}; + use y_octo::DocOptions; + + use super::*; + + fn unique_temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "affine-android-host-{label}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn allowlist_never_resurrects_deleted_workspace_db_on_disk() { + let files_dir = unique_temp_dir("f1-no-resurrection"); + let active_path = + resolve_android_db_path(&files_dir, SpaceType::Workspace, "local", "ws-active") + .unwrap(); + let deleted_path = + resolve_android_db_path(&files_dir, SpaceType::Workspace, "local", "ws-deleted") + .unwrap(); + std::fs::create_dir_all(active_path.parent().unwrap()).unwrap(); + std::fs::write(&deleted_path, b"residual-0275-db").unwrap(); + + let catalog = AndroidWorkspaceCatalog::from_local_storage_json( + r#"["ws-active", 42, "ws-active", null]"#, + ); + assert_eq!(catalog.ids(), &["ws-active".to_string()]); + assert!(!catalog.contains("ws-deleted")); + + let mut bridge = AndroidSqliteBridge::new(); + assert_eq!( + bridge.connect_allowlisted_workspace(&files_dir, "local", "ws-deleted", &catalog), + Err(AndroidStorageError::WorkspaceNotAllowlisted( + "ws-deleted".to_string() + )) + ); + let key = bridge + .connect_workspace(&files_dir, "local", "ws-active", &catalog, true) + .unwrap(); + assert!(active_path.exists()); + + // Cloud workspaces (peer != "local") open directly even when not in affine-local-workspace. + let cloud_key = bridge + .connect_workspace( + &files_dir, + "https://app.affine.pro", + "ws-cloud-1", + &catalog, + false, + ) + .unwrap(); + assert!( + resolve_android_db_path( + &files_dir, + SpaceType::Workspace, + "https://app.affine.pro", + "ws-cloud-1" + ) + .unwrap() + .exists() + ); + + // Shrinking local allowlist to empty evicts old local handles without closing cloud handles. + let empty_catalog = AndroidWorkspaceCatalog::default(); + assert_eq!(bridge.evict_unlisted_local_workspaces(&empty_catalog), 1); + assert!(bridge.get_doc(&key, "doc-1").is_err()); + assert!(bridge.get_doc(&cloud_key, "doc-1").is_ok()); + + bridge.close_all(); + let _ = std::fs::remove_dir_all(&files_dir); + } + + #[test] + fn in_place_0274_db_upgrade_offline_edit_and_sync_roundtrip() { + let files_dir = unique_temp_dir("0274-inplace-roundtrip"); + let db_path = resolve_android_db_path( + &files_dir, + SpaceType::Workspace, + "https://app.affine.pro/", + "ws-legacy", + ) + .unwrap(); + assert!( + db_path + .to_string_lossy() + .ends_with("/workspaces/workspace/https_app.affine.pro/ws-legacy.db") + ); + std::fs::create_dir_all(db_path.parent().unwrap()).unwrap(); + + // Seed a 0.27.4-style DB: 4 migrations with trailing-space migration #3 checksum + initial doc "hello". + let rt = Builder::new_current_thread().enable_all().build().unwrap(); + let path_str = db_path.to_string_lossy().to_string(); + let initial_doc = DocOptions::from_identity(1, "doc-1".into()).build(); + initial_doc + .get_or_create_text("content") + .unwrap() + .insert(0, "hello") + .unwrap(); + let initial_bin = initial_doc.encode_update_v1().unwrap(); + let initial_sv_bytes = y_octo::encode_state_vector_from_update_v1(&initial_bin).unwrap(); + + rt.block_on(async { + Sqlite::create_database(&path_str).await.unwrap(); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect(&path_str) + .await + .unwrap(); + let full = get_migrator(); + let mut migs = full.migrations.to_vec(); + let m3 = migs[2].clone(); + migs[2] = Migration::new( + m3.version, + m3.description.clone(), + m3.migration_type, + Cow::Owned(format!("{} ", m3.sql)), + m3.no_tx, + ); + migs.truncate(4); + let legacy_migrator = Migrator { + migrations: Cow::Owned(migs), + ..Migrator::DEFAULT + }; + legacy_migrator.run(&pool).await.unwrap(); + pool.close().await; + + let legacy_store = SqliteDocStorage::new(&path_str); + legacy_store.set_space_id("ws-legacy").await.unwrap(); + legacy_store + .push_update("doc-1", &initial_bin, 1_700_000_000_000) + .await + .unwrap(); + legacy_store.close().await; + }); + + // Open in place via AndroidSqliteBridge (repairs migration #3 + applies #5 + WAL). + let catalog = AndroidWorkspaceCatalog::from_ids(vec!["ws-legacy".to_string()]); + let mut bridge = AndroidSqliteBridge::new(); + let key = bridge + .connect_allowlisted_workspace( + &files_dir, + "https://app.affine.pro/", + "ws-legacy", + &catalog, + ) + .unwrap(); + + let loaded_bin = bridge.get_doc(&key, "doc-1").unwrap().unwrap(); + let mut offline_doc = DocOptions::from_identity(2, "doc-1".into()).build(); + offline_doc + .apply_update_from_binary_v1(&loaded_bin) + .unwrap(); + assert_eq!( + offline_doc + .get_or_create_text("content") + .unwrap() + .to_string(), + "hello" + ); + + // Offline 1-character edit ("hello" -> "hello!") persisted via BEGIN IMMEDIATE batch. + let before_edit_sv = offline_doc.get_state_vector(); + offline_doc + .get_or_create_text("content") + .unwrap() + .insert(5, "!") + .unwrap(); + let edit_delta = offline_doc + .encode_state_as_update_v1(&before_edit_sv) + .unwrap(); + let committed = bridge + .push_updates_batch( + &key, + &[PendingDocUpdate { + doc_id: "doc-1".into(), + update: edit_delta, + }], + Some("https://app.affine.pro"), + 1_700_000_010_000, + ) + .unwrap(); + assert_eq!(committed, 1); + + // Sync diff against remote's initial state vector carries the offline edit. + let diff = bridge + .get_doc_diff(&key, "doc-1", Some(&initial_sv_bytes)) + .unwrap() + .unwrap(); + let mut remote_0275 = DocOptions::from_identity(99, "doc-1".into()).build(); + remote_0275 + .apply_update_from_binary_v1(&initial_bin) + .unwrap(); + remote_0275 + .apply_update_from_binary_v1(&diff.missing) + .unwrap(); + assert_eq!( + remote_0275 + .get_or_create_text("content") + .unwrap() + .to_string(), + "hello!" + ); + + // Checkpoint, close, and reopen with raw affine-store (simulating 0.27.5 rollback read-back). + bridge.checkpoint(&key).unwrap(); + bridge.close_all(); + + let reopened_bin = rt.block_on(async { + let rollback_store = SqliteDocStorage::new(&path_str); + rollback_store.connect().await.unwrap(); + let rec = rollback_store.get_doc("doc-1").await.unwrap().unwrap(); + rollback_store.close().await; + rec.bin + }); + let mut verify = DocOptions::from_identity(100, "doc-1".into()).build(); + verify.apply_update_from_binary_v1(&reopened_bin).unwrap(); + assert_eq!( + verify.get_or_create_text("content").unwrap().to_string(), + "hello!" + ); + + // Userspace DB path & connect check. + let user_key = bridge + .open_userspace(&files_dir, "https://app.affine.pro/", "user-42") + .unwrap(); + let user_db = + resolve_userspace_db_path(&files_dir, "https://app.affine.pro/", "user-42").unwrap(); + assert!(user_db.exists()); + + // Passive WAL checkpoint must not block even while a concurrent reader holds a read tx. + let mut reader = rt.block_on(async { + let mut conn = sqlx::sqlite::SqliteConnection::connect_with( + &SqliteConnectOptions::new() + .filename(user_db.to_string_lossy().as_ref()) + .busy_timeout(Duration::from_millis(SQLITE_BUSY_TIMEOUT_MS)), + ) + .await + .unwrap(); + sqlx::query("BEGIN TRANSACTION;") + .execute(&mut conn) + .await + .unwrap(); + let _ = sqlx::query("SELECT COUNT(*) FROM meta;") + .fetch_one(&mut conn) + .await + .unwrap(); + conn + }); + bridge + .push_update(&user_key, "u-doc", &[0u8, 0u8], 1_700_000_020_000) + .unwrap(); + let passive = bridge.checkpoint_passive(&user_key).unwrap(); + assert!(passive.log >= 0); + assert_eq!(bridge.checkpoint_all_passive(), 1); + rt.block_on(async { + sqlx::query("COMMIT;").execute(&mut reader).await.unwrap(); + reader.close().await.unwrap(); + }); + + bridge.close(&user_key); + + let _ = std::fs::remove_dir_all(&files_dir); + } +} diff --git a/packages/frontend/hosts/android/src/surface.rs b/packages/frontend/hosts/android/src/surface.rs new file mode 100644 index 0000000000..cc75b4a63f --- /dev/null +++ b/packages/frontend/hosts/android/src/surface.rs @@ -0,0 +1,459 @@ +//! Android `SurfaceHolder.Callback` lifecycle, render backend selection +//! (`Vulkan -> Gles3 -> CpuFallback`), and swapchain-safe frame presentation. +//! +//! Replaces the S1 one-shot `lockCanvas` placeholder and guarantees that +//! `pending_frame` is only cleared after a frame successfully presents. + +/// Default observable first-frame clear color (opaque `#FAFAFC` ARGB, matching iOS light canvas). +pub const DEFAULT_CLEAR_COLOR_ARGB: u32 = 0xFFFA_FAFC; + +/// Logical-dp window insets forwarded across the Android JNI boundary. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct LogicalWindowInsets { + pub safe_top: f32, + pub safe_right: f32, + pub safe_bottom: f32, + pub safe_left: f32, + /// Absolute keyboard overlap height from the window bottom edge in logical `dp`. + /// Does not subtract `safe_bottom`; `ui::WindowInsets::effective()` takes the max. + pub ime_bottom: f32, +} + +impl LogicalWindowInsets { + /// Returns keyboard height strictly above the bottom navigation bar in logical `dp`, + /// preventing double-deduction when combining `safe_bottom` and `ime_bottom`. + pub fn effective_ime_above_nav_bar(&self) -> f32 { + (self.ime_bottom - self.safe_bottom).max(0.0) + } +} + +/// Converts Android `WindowInsets` physical pixel measurements into logical `dp`. +pub fn physical_insets_to_logical_dp( + safe_top_px: i32, + safe_right_px: i32, + safe_bottom_px: i32, + safe_left_px: i32, + ime_bottom_px: i32, + density: f32, +) -> LogicalWindowInsets { + let safe_density = if density.is_finite() && density > 0.0 { + density + } else { + 1.0 + }; + let top = safe_top_px.max(0); + let right = safe_right_px.max(0); + let bottom = safe_bottom_px.max(0); + let left = safe_left_px.max(0); + let ime = ime_bottom_px.max(0); + LogicalWindowInsets { + safe_top: top as f32 / safe_density, + safe_right: right as f32 / safe_density, + safe_bottom: bottom as f32 / safe_density, + safe_left: left as f32 / safe_density, + ime_bottom: ime as f32 / safe_density, + } +} + +/// Active Android presentation backend with deterministic fallback order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum AndroidRenderBackend { + Unselected = 0, + Vulkan = 1, + Gles3 = 2, + CpuFallback = 3, +} + +impl AndroidRenderBackend { + /// Returns the next lower backend on surface loss or driver failure. + pub const fn downgrade(self) -> Self { + match self { + Self::Unselected | Self::Vulkan => Self::Gles3, + Self::Gles3 | Self::CpuFallback => Self::CpuFallback, + } + } +} + +/// Failure reason reported when presenting a frame to an Android `Surface`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SurfacePresentError { + NotReady, + SurfaceLost, + BackendUnavailable, + LockOrPostFailed, +} + +/// Lifecycle state for an Android `SurfaceView` native window binding. +#[derive(Debug, Clone, PartialEq)] +pub struct SurfaceLifecycleState { + pub active: bool, + pub bound: bool, + pub configured_for_generation: bool, + pub generation: u64, + pub texture_generation: u64, + pub recreation_count: u64, + pub format: i32, + pub width_px: u32, + pub height_px: u32, + pub density: f32, + pub scroll_offset_x: f32, + pub scroll_offset_y: f32, + pub frame_count: u64, + pub last_frame_nanos: i64, + pub pending_frame: bool, + pub needs_first_frame_after_recreate: bool, + pub clear_color_argb: u32, + pub backend: AndroidRenderBackend, + pub present_failures: u64, +} + +impl Default for SurfaceLifecycleState { + fn default() -> Self { + Self::new() + } +} + +impl SurfaceLifecycleState { + /// Creates an unbound surface lifecycle state with a pending initial frame. + pub const fn new() -> Self { + Self { + active: false, + bound: false, + configured_for_generation: false, + generation: 0, + texture_generation: 0, + recreation_count: 0, + format: 0, + width_px: 0, + height_px: 0, + density: 1.0, + scroll_offset_x: 0.0, + scroll_offset_y: 0.0, + frame_count: 0, + last_frame_nanos: 0, + pending_frame: true, + needs_first_frame_after_recreate: true, + clear_color_argb: DEFAULT_CLEAR_COLOR_ARGB, + backend: AndroidRenderBackend::Unselected, + present_failures: 0, + } + } + + /// Updates the display density preserved across surface recreation. + pub fn set_density(&mut self, density: f32) { + if density.is_finite() && density > 0.0 { + self.density = density; + } + } + + /// Updates viewport scroll offsets preserved across surface recreation. + pub fn set_scroll_offset(&mut self, scroll_x: f32, scroll_y: f32) { + if scroll_x.is_finite() { + self.scroll_offset_x = scroll_x; + } + if scroll_y.is_finite() { + self.scroll_offset_y = scroll_y; + } + } + + /// Handles a Vulkan device-lost or swapchain init failure by downgrading to GLES3 + /// while preserving viewport, scroll, and session state. + pub fn report_vulkan_device_lost(&mut self) -> AndroidRenderBackend { + self.present_failures = self.present_failures.saturating_add(1); + self.texture_generation = self.texture_generation.saturating_add(1); + self.pending_frame = true; + self.needs_first_frame_after_recreate = true; + if matches!( + self.backend, + AndroidRenderBackend::Unselected | AndroidRenderBackend::Vulkan + ) { + self.backend = AndroidRenderBackend::Gles3; + } + self.backend + } + + /// Selects the highest available backend: `Vulkan -> Gles3 -> CpuFallback`. + pub fn select_backend( + &mut self, + vulkan_available: bool, + gles3_available: bool, + ) -> AndroidRenderBackend { + self.backend = if vulkan_available { + AndroidRenderBackend::Vulkan + } else if gles3_available { + AndroidRenderBackend::Gles3 + } else { + AndroidRenderBackend::CpuFallback + }; + self.backend + } + + /// Handles `SurfaceHolder.Callback.surfaceCreated`. + /// + /// Increments surface and texture generations and marks `configured_for_generation = false` + /// until `surfaceChanged` delivers non-zero dimensions for this generation, while preserving + /// previous viewport dimensions, DPI, and scroll offset for layout memory. + pub fn on_created(&mut self, surface_non_null: bool) { + self.generation = self.generation.saturating_add(1); + self.texture_generation = self.texture_generation.saturating_add(1); + if self.generation > 1 { + self.recreation_count = self.recreation_count.saturating_add(1); + } + self.active = true; + self.bound = surface_non_null; + self.configured_for_generation = false; + self.pending_frame = true; + self.needs_first_frame_after_recreate = true; + } + + /// Handles `SurfaceHolder.Callback.surfaceChanged(format, width, height)`. + pub fn on_changed(&mut self, format: i32, width_px: u32, height_px: u32) { + self.format = format; + self.width_px = width_px; + self.height_px = height_px; + self.configured_for_generation = width_px > 0 && height_px > 0; + if self.configured_for_generation { + self.pending_frame = true; + } + } + + /// Handles `SurfaceHolder.Callback.surfaceDestroyed`. + /// + /// Detaches the native surface while preserving viewport size, DPI, scroll, + /// and backend state so the next `surfaceCreated` + `surfaceChanged` pair + /// immediately presents a recovered first frame. + pub fn on_destroyed(&mut self) { + self.active = false; + self.bound = false; + self.configured_for_generation = false; + self.pending_frame = true; + self.needs_first_frame_after_recreate = true; + } + + /// Schedules a frame render on the next `Choreographer` tick. + pub fn request_frame(&mut self) { + self.pending_frame = true; + } + + /// Returns `true` when the surface is attached and configured with non-zero + /// dimensions for the current generation. + pub const fn is_ready(&self) -> bool { + self.active + && self.bound + && self.configured_for_generation + && self.width_px > 0 + && self.height_px > 0 + } + + /// Begins a frame tick without clearing `pending_frame` until presentation succeeds. + pub fn begin_frame(&self) -> Option { + if !self.is_ready() { + return None; + } + Some(self.clear_color_argb) + } + + /// Records the outcome of submitting a frame to the Android `Surface`. + /// + /// Clears `pending_frame` ONLY on `Ok(())`. Any error keeps `pending_frame = true` + /// so the next `Choreographer` tick retries automatically without new user input, + /// and surface-loss / backend-unavailable errors trigger `Vulkan -> Gles3` downgrade. + pub fn complete_frame( + &mut self, + frame_time_nanos: i64, + result: Result<(), SurfacePresentError>, + ) -> bool { + match result { + Ok(()) => { + self.frame_count = self.frame_count.saturating_add(1); + self.last_frame_nanos = frame_time_nanos; + self.pending_frame = false; + self.needs_first_frame_after_recreate = false; + true + } + Err(err) => { + self.present_failures = self.present_failures.saturating_add(1); + self.pending_frame = true; + if matches!( + err, + SurfacePresentError::SurfaceLost | SurfacePresentError::BackendUnavailable + ) { + self.backend = self.backend.downgrade(); + self.texture_generation = self.texture_generation.saturating_add(1); + } + false + } + } + } + + /// Convenience tick for headless/non-Android hosts where presentation succeeds. + pub fn on_frame_tick(&mut self, frame_time_nanos: i64) -> Option { + let argb = self.begin_frame()?; + self.complete_frame(frame_time_nanos, Ok(())); + Some(argb) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn surface_recreation_preserves_pending_frame_and_advances_generation() { + let mut surface = SurfaceLifecycleState::new(); + assert!(!surface.is_ready()); + assert!(surface.pending_frame); + assert_eq!(surface.on_frame_tick(16_000_000), None); + assert_eq!(surface.frame_count, 0); + + surface.on_created(true); + assert_eq!(surface.generation, 1); + assert!(!surface.is_ready()); + surface.on_changed(1, 1080, 2400); + assert!(surface.is_ready()); + assert!(surface.pending_frame); + + assert_eq!( + surface.on_frame_tick(16_666_667), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert_eq!(surface.frame_count, 1); + assert!(!surface.pending_frame); + + // Background: surface destroyed -> ticks are ignored, pending_frame stays set. + surface.on_destroyed(); + assert!(!surface.is_ready()); + assert!(surface.pending_frame); + assert_eq!(surface.on_frame_tick(33_333_334), None); + assert_eq!(surface.frame_count, 1); + + // Foreground: new surface created with updated dimensions -> seamlessly resumes. + surface.on_created(true); + assert_eq!(surface.generation, 2); + surface.on_changed(1, 2400, 1080); + assert!(surface.is_ready()); + assert!(surface.pending_frame); + assert_eq!( + surface.on_frame_tick(50_000_000), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert_eq!(surface.frame_count, 2); + assert_eq!(surface.width_px, 2400); + assert_eq!(surface.height_px, 1080); + } + + #[test] + fn present_failure_keeps_pending_frame_and_downgrades_vulkan_to_gles3() { + let mut surface = SurfaceLifecycleState::new(); + assert_eq!( + surface.select_backend(true, true), + AndroidRenderBackend::Vulkan + ); + surface.on_created(true); + surface.on_changed(1, 1080, 2400); + + // First submit fails with SurfaceLost -> pending_frame stays true & backend downgrades to Gles3. + assert_eq!(surface.begin_frame(), Some(DEFAULT_CLEAR_COLOR_ARGB)); + assert!(!surface.complete_frame(16_000_000, Err(SurfacePresentError::SurfaceLost))); + assert!(surface.pending_frame); + assert_eq!(surface.frame_count, 0); + assert_eq!(surface.present_failures, 1); + assert_eq!(surface.backend, AndroidRenderBackend::Gles3); + + // Lock/post failure also keeps pending_frame true without incrementing frame_count. + assert!(!surface.complete_frame(32_000_000, Err(SurfacePresentError::LockOrPostFailed))); + assert!(surface.pending_frame); + assert_eq!(surface.frame_count, 0); + assert_eq!(surface.present_failures, 2); + assert_eq!(surface.backend, AndroidRenderBackend::Gles3); + + // BackendUnavailable on Gles3 downgrades to CpuFallback while preserving pending_frame. + assert!(!surface.complete_frame(40_000_000, Err(SurfacePresentError::BackendUnavailable))); + assert!(surface.pending_frame); + assert_eq!(surface.frame_count, 0); + assert_eq!(surface.present_failures, 3); + assert_eq!(surface.backend, AndroidRenderBackend::CpuFallback); + + // Retry succeeds -> clears pending_frame and advances frame_count. + assert!(surface.complete_frame(48_000_000, Ok(()))); + assert!(!surface.pending_frame); + assert_eq!(surface.frame_count, 1); + } + + #[test] + fn null_or_zero_sized_surface_never_presents() { + let mut surface = SurfaceLifecycleState::new(); + surface.on_created(false); + surface.on_changed(1, 1080, 2400); + assert!(!surface.is_ready()); + assert_eq!(surface.on_frame_tick(10_000), None); + + surface.on_created(true); + surface.on_changed(1, 0, 2400); + assert!(!surface.is_ready()); + assert_eq!(surface.on_frame_tick(20_000), None); + } + + #[test] + fn surface_recreation_and_vulkan_device_loss_preserve_viewport_dpi_and_scroll() { + let mut surface = SurfaceLifecycleState::new(); + assert_eq!( + surface.select_backend(true, true), + AndroidRenderBackend::Vulkan + ); + surface.set_density(3.0); + surface.set_scroll_offset(12.5, 420.0); + surface.on_created(true); + surface.on_changed(1, 1080, 2400); + assert!(surface.needs_first_frame_after_recreate); + assert_eq!(surface.recreation_count, 0); + assert_eq!(surface.texture_generation, 1); + + // First frame presented under Vulkan. + assert_eq!( + surface.on_frame_tick(16_000_000), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert!(!surface.needs_first_frame_after_recreate); + + // Simulate Vulkan device loss -> downgrades to GLES3 while keeping state intact. + assert_eq!( + surface.report_vulkan_device_lost(), + AndroidRenderBackend::Gles3 + ); + assert!(surface.pending_frame); + assert!(surface.needs_first_frame_after_recreate); + assert_eq!(surface.texture_generation, 2); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_x, 12.5); + assert_eq!(surface.scroll_offset_y, 420.0); + + // Rotation / backgrounding -> surfaceDestroyed -> surfaceCreated -> surfaceChanged. + surface.on_destroyed(); + assert!(!surface.is_ready()); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_y, 420.0); + + surface.on_created(true); + assert_eq!(surface.generation, 2); + assert_eq!(surface.recreation_count, 1); + assert_eq!(surface.texture_generation, 3); + // Before surfaceChanged arrives for generation 2, is_ready() MUST be false even though + // previous width_px/height_px are remembered for layout, preventing 0x0 present failures. + assert!(!surface.is_ready()); + assert_eq!(surface.on_frame_tick(24_000_000), None); + assert_eq!(surface.present_failures, 1); + + surface.on_changed(1, 2400, 1080); + assert!(surface.is_ready()); + assert_eq!( + surface.on_frame_tick(32_000_000), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert!(!surface.needs_first_frame_after_recreate); + assert_eq!(surface.backend, AndroidRenderBackend::Gles3); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_y, 420.0); + } +} diff --git a/packages/frontend/hosts/android/src/text_layout.rs b/packages/frontend/hosts/android/src/text_layout.rs new file mode 100644 index 0000000000..daa7481aba --- /dev/null +++ b/packages/frontend/hosts/android/src/text_layout.rs @@ -0,0 +1,395 @@ +//! Pure-Rust fallback text layout (per-paragraph UAX #9 first-strong BiDi, +//! soft-wrapping, and proportional/measured glyph advances) used when Android +//! `StaticLayout` is unavailable (headless Rust tests and JVM-only parity checks). +//! On Android devices, `ShapedTextLayout` (`android.text.StaticLayout`) is the +//! single authoritative layout engine for handles, hit-testing, and the loupe. + +use crate::selection::TextDirection; + +/// Layout parameters in viewport pixel space. +#[derive(Debug, Clone, PartialEq)] +pub struct TextLayoutMetrics { + pub origin_x: f32, + pub origin_y: f32, + pub max_width: f32, + pub char_advance: f32, + pub line_height: f32, + /// Optional per-UTF-16-unit advance widths measured by Android `TextPaint.getTextWidths`. + pub measured_advances: Vec, +} + +impl Default for TextLayoutMetrics { + fn default() -> Self { + Self::for_viewport(1080.0, 3.0) + } +} + +impl TextLayoutMetrics { + /// Builds default viewport-scaled text metrics for a given width and density. + pub fn for_viewport(viewport_width: f32, density: f32) -> Self { + let d = if density.is_finite() && density > 0.0 { + density + } else { + 1.0 + }; + let pad = 24.0 * d; + let max_w = if viewport_width.is_finite() && viewport_width > pad * 2.0 { + viewport_width - pad * 2.0 + } else { + 320.0 * d + }; + Self { + origin_x: pad, + origin_y: 80.0 * d, + max_width: max_w, + char_advance: 12.0 * d, + line_height: 28.0 * d, + measured_advances: Vec::new(), + } + } + + /// Updates viewport-derived layout metrics while preserving any explicit `measured_advances`. + pub fn update_viewport(&mut self, viewport_width: f32, density: f32) { + let next = Self::for_viewport(viewport_width, density); + self.origin_x = next.origin_x; + self.origin_y = next.origin_y; + self.max_width = next.max_width; + self.char_advance = next.char_advance; + self.line_height = next.line_height; + } + + /// Replaces the optional measured advance table (sanitizing non-finite values). + pub fn set_measured_advances(&mut self, advances: Vec) { + self.measured_advances = advances + .into_iter() + .map(|w| if w.is_finite() && w >= 0.0 { w } else { 0.0 }) + .collect(); + } +} + +#[derive(Debug, Clone)] +struct VisualLine { + start_utf16: usize, + end_utf16: usize, + direction: TextDirection, + /// `(utf16_offset, step, x_offset_from_line_start, advance)` for each cluster on the line. + clusters: Vec<(usize, usize, f32, f32)>, + total_width: f32, +} + +/// Detects paragraph writing direction from the first strong directional scalar (UAX #9). +pub fn detect_writing_direction(utf16: &[u16]) -> TextDirection { + for ch in char::decode_utf16(utf16.iter().copied()).flatten() { + let cp = ch as u32; + if is_rtl_codepoint(cp) { + return TextDirection::Rtl; + } + if ch.is_alphabetic() { + return TextDirection::Ltr; + } + } + TextDirection::Ltr +} + +const fn is_rtl_codepoint(cp: u32) -> bool { + matches!( + cp, + 0x0590..=0x05FF + | 0x0600..=0x06FF + | 0x0750..=0x077F + | 0x08A0..=0x08FF + | 0x200F + | 0xFB50..=0xFDFF + | 0xFE70..=0xFEFF + ) +} + +/// Returns a proportional fallback glyph advance when `TextPaint` widths are not supplied. +pub fn proportional_char_advance(ch: char, base_advance: f32) -> f32 { + let base = base_advance.max(1.0); + let cp = ch as u32; + if matches!( + ch, + 'i' | 'l' | 'I' | '.' | ',' | ':' | ';' | '!' | '|' | '\'' | '`' + ) { + return base * 0.42; + } + if matches!( + ch, + ' ' | 'j' | 't' | 'f' | 'r' | '1' | '(' | ')' | '[' | ']' + ) { + return base * 0.58; + } + if matches!(ch, 'W' | 'M' | '@' | '%' | 'm' | 'w') { + return base * 1.38; + } + if cp >= 0x2E80 { + return base * 1.55; + } + base +} + +fn decode_cluster(utf16: &[u16], i: usize) -> (char, usize) { + let u = utf16[i]; + if (0xD800..=0xDBFF).contains(&u) + && i + 1 < utf16.len() + && (0xDC00..=0xDFFF).contains(&utf16[i + 1]) + { + let ch = char::decode_utf16([u, utf16[i + 1]]) + .next() + .and_then(Result::ok) + .unwrap_or('\u{FFFD}'); + (ch, 2) + } else { + let ch = char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}'); + (ch, 1) + } +} + +fn cluster_advance( + utf16: &[u16], + i: usize, + step: usize, + ch: char, + metrics: &TextLayoutMetrics, +) -> f32 { + if metrics.measured_advances.len() == utf16.len() { + let sum: f32 = metrics.measured_advances[i..i + step].iter().copied().sum(); + if sum.is_finite() && sum >= 0.0 { + return sum; + } + } + proportional_char_advance(ch, metrics.char_advance) +} + +fn layout_lines(utf16: &[u16], metrics: &TextLayoutMetrics) -> Vec { + let max_w = metrics.max_width.max(metrics.char_advance.max(1.0)); + let mut lines = Vec::new(); + let mut para_start = 0usize; + + loop { + let mut para_end = para_start; + while para_end < utf16.len() && utf16[para_end] != b'\n' as u16 { + para_end += 1; + } + let para_dir = detect_writing_direction(&utf16[para_start..para_end]); + + let mut line_start = para_start; + let mut clusters = Vec::new(); + let mut line_w = 0.0_f32; + let mut i = para_start; + + while i < para_end { + let (ch, step) = decode_cluster(utf16, i); + let adv = cluster_advance(utf16, i, step, ch, metrics); + if !clusters.is_empty() && line_w + adv > max_w { + lines.push(VisualLine { + start_utf16: line_start, + end_utf16: i, + direction: para_dir, + clusters, + total_width: line_w, + }); + line_start = i; + clusters = Vec::new(); + line_w = 0.0; + } + clusters.push((i, step, line_w, adv)); + line_w += adv; + i += step; + } + + lines.push(VisualLine { + start_utf16: line_start, + end_utf16: para_end, + direction: para_dir, + clusters, + total_width: line_w, + }); + + if para_end >= utf16.len() { + break; + } + para_start = para_end + 1; + } + + lines +} + +fn find_line_for_offset(lines: &[VisualLine], clamped_offset: usize) -> usize { + for (idx, line) in lines.iter().enumerate() { + if clamped_offset < line.end_utf16 { + return idx; + } + if clamped_offset == line.end_utf16 { + // Soft-wrap boundary offsets belong to the start of the next visual line. + if let Some(next) = lines.get(idx + 1) + && next.start_utf16 == clamped_offset + { + return idx + 1; + } + return idx; + } + } + lines.len().saturating_sub(1) +} + +/// Returns the paragraph writing direction at UTF-16 `offset`. +pub fn detect_direction_at_offset( + utf16: &[u16], + offset: usize, + metrics: &TextLayoutMetrics, +) -> TextDirection { + let lines = layout_lines(utf16, metrics); + let idx = find_line_for_offset(&lines, offset.min(utf16.len())); + lines[idx].direction +} + +/// Computes the caret baseline `(x, y)` in viewport pixels for UTF-16 `offset`. +pub fn caret_position_for_offset( + utf16: &[u16], + offset: usize, + metrics: &TextLayoutMetrics, +) -> (f32, f32) { + let lines = layout_lines(utf16, metrics); + let clamped = offset.min(utf16.len()); + let line_idx = find_line_for_offset(&lines, clamped); + let line = &lines[line_idx]; + + let mut advance_x = line.total_width; + if clamped <= line.start_utf16 { + advance_x = 0.0; + } else { + for &(c_off, _step, c_x, _c_adv) in &line.clusters { + if c_off >= clamped { + advance_x = c_x; + break; + } + } + } + + let x = match line.direction { + TextDirection::Ltr => metrics.origin_x + advance_x, + TextDirection::Rtl => metrics.origin_x + metrics.max_width - advance_x, + }; + let y = metrics.origin_y + (line_idx as f32 + 1.0) * metrics.line_height; + (x, y) +} + +/// Resolves viewport pixel `(x, y)` to the closest UTF-16 scalar boundary offset. +pub fn closest_offset_for_position( + utf16: &[u16], + x: f32, + y: f32, + metrics: &TextLayoutMetrics, +) -> usize { + let lines = layout_lines(utf16, metrics); + let lh = metrics.line_height.max(1.0); + let rel_line = ((y - metrics.origin_y) / lh - 0.5).floor(); + let line_idx = if rel_line <= 0.0 { + 0 + } else { + (rel_line as usize).min(lines.len().saturating_sub(1)) + }; + let line = &lines[line_idx]; + let target_x = match line.direction { + TextDirection::Ltr => (x - metrics.origin_x).max(0.0), + TextDirection::Rtl => (metrics.origin_x + metrics.max_width - x).max(0.0), + }; + + let mut best_off = line.start_utf16; + let mut best_dist = target_x.abs(); + for &(c_off, step, c_x, c_adv) in &line.clusters { + let end_off = c_off + step; + let end_x = c_x + c_adv; + let dist = (target_x - end_x).abs(); + if dist < best_dist { + best_dist = dist; + best_off = end_off; + } + } + best_off +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_layout_handles_per_paragraph_bidi_and_proportional_widths() { + let metrics = TextLayoutMetrics::for_viewport(1080.0, 3.0); + + // 1. Per-paragraph BiDi ("A\nשלום"): line 0 is LTR (x increases), line 1 is RTL (x decreases). + let mixed: Vec = "A\nשלום".encode_utf16().collect(); + let (x0, y0) = caret_position_for_offset(&mixed, 0, &metrics); + let (x1, y1) = caret_position_for_offset(&mixed, 1, &metrics); + assert!(x1 > x0, "paragraph 0 ('A') must advance LTR"); + assert_eq!(y0, y1); + let (x2, y2) = caret_position_for_offset(&mixed, 2, &metrics); + let (x3, y3) = caret_position_for_offset(&mixed, 3, &metrics); + assert!(y2 > y0, "paragraph 1 must sit on second line"); + assert_eq!(y2, y3); + assert!(x3 < x2, "paragraph 1 ('שלום') must advance RTL"); + assert_eq!( + detect_direction_at_offset(&mixed, 0, &metrics), + TextDirection::Ltr + ); + assert_eq!( + detect_direction_at_offset(&mixed, 2, &metrics), + TextDirection::Rtl + ); + assert_eq!(closest_offset_for_position(&mixed, x3, y3, &metrics), 3); + + // 2. Proportional glyph widths: "WWWW" is strictly wider than "iiii". + let narrow: Vec = "iiii".encode_utf16().collect(); + let wide: Vec = "WWWW".encode_utf16().collect(); + let (nx_end, _) = caret_position_for_offset(&narrow, 4, &metrics); + let (wx_end, _) = caret_position_for_offset(&wide, 4, &metrics); + assert!( + wx_end > nx_end * 1.5, + "WWWW ({wx_end}) must be much wider than iiii ({nx_end})" + ); + + // 3. Explicit measured_advances preserve zero-advance combining marks (e\u{0301}) + // and survive update_viewport calls. + let combining: Vec = "e\u{0301}".encode_utf16().collect(); + let mut custom = metrics.clone(); + custom.set_measured_advances(vec![10.0, 0.0]); + let (c0, _) = caret_position_for_offset(&combining, 0, &custom); + let (c1, _) = caret_position_for_offset(&combining, 1, &custom); + let (c2, _) = caret_position_for_offset(&combining, 2, &custom); + assert!((c1 - c0 - 10.0).abs() < 1e-3); + assert!( + (c2 - c1).abs() < 1e-3, + "combining mark must keep 0.0 advance (got {})", + c2 - c1 + ); + custom.update_viewport(720.0, 2.0); + assert_eq!( + custom.measured_advances, + vec![10.0, 0.0], + "update_viewport must preserve measured_advances" + ); + + // 4. Soft-wrap boundary offset belongs to the start of the next visual line. + let mut wrap = TextLayoutMetrics { + origin_x: 0.0, + origin_y: 0.0, + max_width: 40.0, + char_advance: 10.0, + line_height: 20.0, + measured_advances: vec![10.0, 10.0, 10.0, 10.0, 10.0], + }; + let abcdz: Vec = "ABCDZ".encode_utf16().collect(); + let (wx4, wy4) = caret_position_for_offset(&abcdz, 4, &wrap); + assert!( + wx4.abs() < 1e-3 && (wy4 - 40.0).abs() < 1e-3, + "offset 4 in soft-wrapped 'ABCDZ' must land at line 1 start (got ({wx4}, {wy4}))" + ); + wrap.measured_advances.clear(); + assert_eq!( + detect_direction_at_offset(&abcdz, 4, &wrap), + TextDirection::Ltr + ); + } +} diff --git a/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt b/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt new file mode 100644 index 0000000000..50aa75db82 --- /dev/null +++ b/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt @@ -0,0 +1,3764 @@ +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import android.view.inputmethod.InputConnection +import app.affine.pro.host.AffineImeController +import app.affine.pro.host.AffineSurfaceView +import app.affine.pro.host.ShareDiskInbox +import app.affine.pro.host.ShellAccessibilityNode +import app.affine.pro.host.ShellAccessibilityViews +import app.affine.pro.host.ShareIntentBridge +import app.affine.pro.host.ShareReceiverActivity +import app.affine.pro.host.AndroidAutofillController +import app.affine.pro.host.AndroidBackDispatcher +import app.affine.pro.host.AndroidBootstrapCoordinator +import app.affine.pro.host.BootstrapOutcome +import app.affine.pro.host.AndroidCookieCleaner +import app.affine.pro.host.AndroidPdfPageRenderer +import app.affine.pro.host.AndroidSelectionCoordinator +import app.affine.pro.host.AuthSessionStore +import app.affine.pro.host.AuthTokenCipher +import app.affine.pro.host.AutofillPlatformBackend +import app.affine.pro.host.CaretBounds +import app.affine.pro.host.CookieCleaner +import app.affine.pro.host.HostClipboard +import app.affine.pro.host.HostDocumentBufferController +import app.affine.pro.host.HostDocumentStore +import app.affine.pro.host.HttpUrlConnectionRefreshTransport +import app.affine.pro.host.InMemoryAesKeyProvider +import app.affine.pro.host.LegacyLocalStorageProbe +import app.affine.pro.host.NativeBridge +import app.affine.pro.host.PdfPageBackend +import app.affine.pro.host.RefreshResult +import app.affine.pro.host.RefreshTransport +import app.affine.pro.host.Rfc4648Base64 +import app.affine.pro.host.SelectionGestureController +import app.affine.pro.host.SessionPersistence +import app.affine.pro.host.ShellBootstrapState +import app.affine.pro.host.TextLayoutAuthority +import java.io.File +import java.net.ServerSocket +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference + +private fun checkEq(actual: Any?, expected: Any?, label: String) { + if (actual != expected) { + throw AssertionError("$label: expected=<$expected> actual=<$actual>") + } +} + +private fun withHost(block: (InputConnection, AffineImeController) -> Unit) { + val handle = NativeBridge.nativeCreateHost() + checkEq(handle != 0L, true, "nativeCreateHost returned non-zero handle") + try { + val ic = AffineSurfaceView.createInputConnection({ handle }) + val ime = AffineImeController { handle } + block(ic, ime) + } finally { + NativeBridge.nativeDestroyHost(handle) + } +} + +fun main() { + // 1. Empty editor: commitText("AB", 1) persists and is readable via getTextBeforeCursor(2, 0). + withHost { ic, ime -> + checkEq(ic.commitText("AB", 1), true, "seq1 commitText") + checkEq(ime.readText(), "AB", "seq1 text") + checkEq(ic.getTextBeforeCursor(2, 0), "AB", "seq1 getTextBeforeCursor") + checkEq(ime.selectionStart(), 2, "seq1 selStart") + checkEq(ime.selectionEnd(), 2, "seq1 selEnd") + checkEq(ime.composingStart(), -1, "seq1 compStart") + checkEq(ime.composingEnd(), -1, "seq1 compEnd") + } + + // 2. Empty editor: setComposingText("ab", 1) -> deleteSurroundingText(1, 0) keeps "ab" & composing (0, 2). + withHost { ic, ime -> + checkEq(ic.setComposingText("ab", 1), true, "seq2 setComposingText") + checkEq(ic.deleteSurroundingText(1, 0), true, "seq2 deleteSurroundingText") + checkEq(ime.readText(), "ab", "seq2 text") + checkEq(ic.getTextBeforeCursor(2, 0), "ab", "seq2 getTextBeforeCursor") + checkEq(ime.selectionStart(), 2, "seq2 selStart") + checkEq(ime.selectionEnd(), 2, "seq2 selEnd") + checkEq(ime.composingStart(), 0, "seq2 compStart") + checkEq(ime.composingEnd(), 2, "seq2 compEnd") + } + + // 3. "x" + setComposingText("ab", 1) -> deleteSurroundingText(1, 0) -> commitText("中", 1). + withHost { ic, ime -> + checkEq(ic.commitText("x", 1), true, "seq3 commit x") + checkEq(ic.setComposingText("ab", 1), true, "seq3 composing ab") + checkEq(ic.deleteSurroundingText(1, 0), true, "seq3 delete before composing") + checkEq(ime.readText(), "ab", "seq3 text after delete") + checkEq(ime.composingStart(), 0, "seq3 compStart after delete") + checkEq(ime.composingEnd(), 2, "seq3 compEnd after delete") + checkEq(ic.commitText("中", 1), true, "seq3 commit 中") + checkEq(ime.readText(), "中", "seq3 text after commit") + checkEq(ic.getTextBeforeCursor(1, 0), "中", "seq3 getTextBeforeCursor") + checkEq(ime.selectionStart(), 1, "seq3 selStart") + checkEq(ime.selectionEnd(), 1, "seq3 selEnd") + checkEq(ime.composingStart(), -1, "seq3 compStart") + checkEq(ime.composingEnd(), -1, "seq3 compEnd") + } + + // 4. Negative deleteSurroundingText(-1, 1) and (1, -1) on "a😀b" return false with zero mutation. + withHost { ic, ime -> + checkEq(ic.commitText("a😀b", 1), true, "seq4 commit emoji") + checkEq(ic.deleteSurroundingText(-1, 1), false, "seq4 negative before") + checkEq(ic.deleteSurroundingText(1, -1), false, "seq4 negative after") + checkEq(ime.readText(), "a😀b", "seq4 unchanged text") + } + + // 5. Emoji surrogate-pair boundary: "a😀b" -> setSelection(3, 3) -> deleteSurroundingText(1, 0) => "ab". + withHost { ic, ime -> + checkEq(ic.commitText("a😀b", 1), true, "seq5 commit emoji") + checkEq(ic.setSelection(3, 3), true, "seq5 setSelection after emoji") + checkEq(ic.deleteSurroundingText(1, 0), true, "seq5 delete emoji") + checkEq(ime.readText(), "ab", "seq5 text") + checkEq(ic.getTextBeforeCursor(2, 0), "a", "seq5 before cursor") + checkEq(ic.getTextAfterCursor(2, 0), "b", "seq5 after cursor") + checkEq(ime.selectionStart(), 1, "seq5 selStart") + checkEq(ime.selectionEnd(), 1, "seq5 selEnd") + checkEq(ic.setSelection(0, 1), true, "seq5 select a") + checkEq(ic.getSelectedText(0), "a", "seq5 getSelectedText") + } + + // 6. setComposingRegion: mark, commit over region, clear with empty range, normalize reversed range. + withHost { ic, ime -> + checkEq(ic.commitText("AB", 1), true, "seq6 commit AB") + checkEq(ic.setComposingRegion(0, 1), true, "seq6 setComposingRegion(0, 1)") + checkEq(ime.composingStart(), 0, "seq6 compStart") + checkEq(ime.composingEnd(), 1, "seq6 compEnd") + checkEq(ime.selectionStart(), 2, "seq6 selStart unchanged") + checkEq(ic.commitText("X", 1), true, "seq6 commit X over composing") + checkEq(ime.readText(), "XB", "seq6 text XB") + checkEq(ime.selectionStart(), 1, "seq6 cursor 1") + checkEq(ime.composingStart(), -1, "seq6 composing cleared") + checkEq(ime.composingEnd(), -1, "seq6 composing end cleared") + checkEq(ic.setComposingRegion(2, 0), true, "seq6 reversed setComposingRegion(2, 0)") + checkEq(ime.composingStart(), 0, "seq6 normalized compStart") + checkEq(ime.composingEnd(), 2, "seq6 normalized compEnd") + checkEq(ic.setComposingRegion(1, 1), true, "seq6 empty setComposingRegion(1, 1)") + checkEq(ime.composingStart(), -1, "seq6 cleared compStart") + checkEq(ime.composingEnd(), -1, "seq6 cleared compEnd") + } + + // 7. deleteSurroundingTextInCodePoints backward and forward over emoji surrogate pair. + withHost { ic, ime -> + checkEq(ic.commitText("a😀b", 1), true, "seq7 commit emoji") + checkEq(ic.setSelection(3, 3), true, "seq7 setSelection(3, 3)") + checkEq(ic.deleteSurroundingTextInCodePoints(1, 0), true, "seq7 delete backward code point") + checkEq(ime.readText(), "ab", "seq7 text after backward delete") + checkEq(ic.getTextBeforeCursor(2, 0), "a", "seq7 before cursor") + checkEq(ic.getTextAfterCursor(2, 0), "b", "seq7 after cursor") + checkEq(ime.selectionStart(), 1, "seq7 selStart") + checkEq(ime.selectionEnd(), 1, "seq7 selEnd") + } + withHost { ic, ime -> + checkEq(ic.commitText("a😀b", 1), true, "seq7b commit emoji") + checkEq(ic.setSelection(1, 1), true, "seq7b setSelection(1, 1)") + checkEq(ic.deleteSurroundingTextInCodePoints(0, 1), true, "seq7b delete forward code point") + checkEq(ime.readText(), "ab", "seq7b text after forward delete") + checkEq(ime.selectionStart(), 1, "seq7b selStart") + checkEq(ime.selectionEnd(), 1, "seq7b selEnd") + } + + // 8. replaceText clears composing and unsupported write entrypoints return false with zero mutation. + withHost { ic, ime -> + checkEq(ic.commitText("hello", 1), true, "seq8 commit hello") + checkEq(ic.setComposingRegion(0, 2), true, "seq8 setComposingRegion(0, 2)") + checkEq(ic.replaceText(1, 4, "i", 1, null), true, "seq8 replaceText") + checkEq(ime.readText(), "hio", "seq8 text hio") + checkEq(ime.composingStart(), -1, "seq8 composing cleared") + checkEq(ime.composingEnd(), -1, "seq8 composing end cleared") + checkEq(ime.selectionStart(), 2, "seq8 selStart 2") + checkEq(ime.selectionEnd(), 2, "seq8 selEnd 2") + checkEq(ic.commitCorrection(null), false, "seq8 commitCorrection unsupported") + checkEq(ic.commitCompletion(null), false, "seq8 commitCompletion unsupported") + checkEq(ic.performContextMenuAction(0), false, "seq8 performContextMenuAction unsupported") + checkEq(ic.sendKeyEvent(null), false, "seq8 sendKeyEvent unsupported") + checkEq(ime.readText(), "hio", "seq8 unchanged text after unsupported calls") + checkEq(ime.selectionStart(), 2, "seq8 unchanged selStart") + checkEq(ime.selectionEnd(), 2, "seq8 unchanged selEnd") + } + + // 9. Int.MAX_VALUE, zero, and negative length cursor queries do not overflow. + withHost { ic, _ -> + checkEq(ic.commitText("AB", 1), true, "seq9 commit AB") + checkEq(ic.setSelection(1, 1), true, "seq9 setSelection(1, 1)") + checkEq(ic.getTextAfterCursor(Int.MAX_VALUE, 0), "B", "seq9 after Int.MAX_VALUE") + checkEq(ic.getTextBeforeCursor(Int.MAX_VALUE, 0), "A", "seq9 before Int.MAX_VALUE") + checkEq(ic.getTextAfterCursor(0, 0), "", "seq9 after 0") + checkEq(ic.getTextAfterCursor(-5, 0), "", "seq9 after -5") + checkEq(ic.getTextBeforeCursor(0, 0), "", "seq9 before 0") + checkEq(ic.getTextBeforeCursor(-5, 0), "", "seq9 before -5") + } + + // 10. Closing an InputConnection finishes active composing so a reopened connection appends cleanly. + val reconnectHandle = NativeBridge.nativeCreateHost() + checkEq(reconnectHandle != 0L, true, "seq10 nativeCreateHost returned non-zero handle") + try { + val ime = AffineImeController { reconnectHandle } + val ic1 = AffineSurfaceView.createInputConnection({ reconnectHandle }) + checkEq(ic1.commitText("AB", 1), true, "seq10 commit AB") + checkEq(ic1.setComposingRegion(0, 1), true, "seq10 setComposingRegion(0, 1)") + ic1.closeConnection() + checkEq(ime.composingStart(), -1, "seq10 compStart after closeConnection") + checkEq(ime.composingEnd(), -1, "seq10 compEnd after closeConnection") + checkEq(ime.readText(), "AB", "seq10 text after closeConnection") + checkEq(ime.selectionStart(), 2, "seq10 selStart after closeConnection") + checkEq(ime.selectionEnd(), 2, "seq10 selEnd after closeConnection") + + val ic2 = AffineSurfaceView.createInputConnection({ reconnectHandle }) + checkEq(ic2.commitText("X", 1), true, "seq10 commit X on reopened connection") + checkEq(ime.readText(), "ABX", "seq10 text ABX") + checkEq(ic2.getTextBeforeCursor(3, 0), "ABX", "seq10 getTextBeforeCursor ABX") + checkEq(ime.selectionStart(), 3, "seq10 selStart 3") + checkEq(ime.selectionEnd(), 3, "seq10 selEnd 3") + } finally { + NativeBridge.nativeDestroyHost(reconnectHandle) + } + + // 11. S2 Surface lifecycle: detached ticks return 0, pending frame survives surfaceDestroyed. + val surfaceHandle = NativeBridge.nativeCreateHost() + try { + checkEq(NativeBridge.nativeIsSurfaceReady(surfaceHandle), false, "seq11 initial surface not ready") + checkEq(NativeBridge.nativeOnFrameTick(surfaceHandle, 16_000_000L), 0, "seq11 detached tick 0") + NativeBridge.nativeOnSurfaceChanged(surfaceHandle, 1, 1080, 2400) + checkEq(NativeBridge.nativeIsSurfaceReady(surfaceHandle), false, "seq11 unbound surface not ready") + NativeBridge.nativeOnSurfaceDestroyed(surfaceHandle) + checkEq(NativeBridge.nativeHasPendingFrame(surfaceHandle), true, "seq11 pending frame preserved") + } finally { + NativeBridge.nativeDestroyHost(surfaceHandle) + } + + // 12. S2 Legacy localStorage probe scripts actively hook indexedDB.open & deleteDatabase, + // use real 0.27.5 allowlist keys, enforce zero-IDB import, allowlist-only SQLite WAL co-storage, + // and rollback write-back with both setEntries and removeKeys. + checkEq(LegacyLocalStorageProbe.isAllowedKey("affine-local-workspace"), true, "seq12 allow affine-local-workspace") + checkEq(LegacyLocalStorageProbe.isAllowedKey("global-state:serverConfig:self-host"), true, "seq12 allow serverConfig") + checkEq(LegacyLocalStorageProbe.isAllowedKey("global-state:cloud-auth"), true, "seq12 allow global-state auth") + checkEq(LegacyLocalStorageProbe.isAllowedKey("global-state:cloud-workspace:acct-1"), true, "seq12 allow cloud-workspace cache") + checkEq(LegacyLocalStorageProbe.isAllowedKey("global-state:selfhosted-workspace-s1:acct-1"), true, "seq12 allow selfhosted-workspace cache") + checkEq(LegacyLocalStorageProbe.isAllowedKey("affine-flag:enable_ai"), true, "seq12 allow affine-flag") + checkEq(LegacyLocalStorageProbe.isAllowedKey("affine_theme"), false, "seq12 reject fictional affine_theme") + checkEq(LegacyLocalStorageProbe.isAllowedKey("affine_server_url"), false, "seq12 reject fictional affine_server_url") + + val captureJs = LegacyLocalStorageProbe.buildCaptureScript() + checkEq(captureJs.contains("window.indexedDB"), true, "seq12 capture hooks window.indexedDB") + checkEq(captureJs.contains("'open'"), true, "seq12 capture blocks indexedDB.open") + checkEq(captureJs.contains("'deleteDatabase'"), true, "seq12 capture blocks indexedDB.deleteDatabase") + val writeBackJs = LegacyLocalStorageProbe.buildWriteBackScript( + setEntries = mapOf("affine-local-workspace" to "[\"ws-live\"]", "theme" to "dark"), + removeKeys = listOf("last_workspace_id"), + ) + checkEq(writeBackJs.contains("window.localStorage.setItem"), true, "seq12 writeback uses localStorage.setItem") + checkEq(writeBackJs.contains("window.localStorage.removeItem"), true, "seq12 writeback uses localStorage.removeItem") + checkEq(writeBackJs.contains("'deleteDatabase'"), true, "seq12 writeback blocks indexedDB.deleteDatabase") + checkEq(writeBackJs.contains("AFFINE_WRITEBACK_REMOVE_FORBIDDEN"), true, "seq12 writeback has inline JS allowlist guard") + + // Non-allowlisted removeKeys must throw immediately in buildWriteBackScript before touching localStorage. + var rejectedRemoveThrew = false + try { + LegacyLocalStorageProbe.buildWriteBackScript( + setEntries = mapOf("theme" to "dark"), + removeKeys = listOf("unrelated.pref"), + ) + } catch (_: IllegalArgumentException) { + rejectedRemoveThrew = true + } + checkEq(rejectedRemoveThrew, true, "seq12 non-allowlisted removeKeys rejected by buildWriteBackScript") + + val tmpDir = Files.createTempDirectory("affine-s2-android-parity").toFile() + val s2Handle = NativeBridge.nativeCreateHost() + try { + // Seed a deleted residual .db file on disk (must NEVER be resurrected). + val residualDir = File(tmpDir, "workspaces/workspace/local") + residualDir.mkdirs() + File(residualDir, "ws-deleted.db").writeBytes(byteArrayOf(1, 2, 3)) + + // Un-imported host rejects local workspace open and blocks default workspace creation. + checkEq( + NativeBridge.nativeConnectWorkspace(s2Handle, tmpDir.absolutePath, "local", "ws-live"), + null, + "seq12 un-imported host blocks local workspace open", + ) + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(s2Handle), false, "seq12 pending blocks default") + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, "null", ""), + false, + "seq12 null probe rejected", + ) + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(s2Handle), false, "seq12 failed probe blocks default") + + // Any IDB touch, non-allowlisted entry, or missing allowlisted entry is rejected. + val idbViolated = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-live\"]"},"idbTouchCount":1}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, idbViolated, ""), + false, + "seq12 idbTouchCount>0 rejected", + ) + val badKeySentinel = """{"origin":"https://localhost","length":1,"keys":["affine_theme"],"entries":{"affine_theme":"dark"},"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, badKeySentinel, ""), + false, + "seq12 fictional key in entries rejected", + ) + val missingEntrySentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{},"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, missingEntrySentinel, ""), + false, + "seq12 allowlisted key missing from entries rejected", + ) + + // Genuine fresh install with unrelated Capacitor/a11y noise keys filtered through Rust JNI. + val rawFreshWithNoise = """{"origin":"https://localhost","length":2,"keys":["CapacitorStorage.foo","ally-supports-cache"],"entries":{"CapacitorStorage.foo":"bar","ally-supports-cache":"1"},"idbTouchCount":0}""" + val freshWithNoise = LegacyLocalStorageProbe.filterSnapshotEntries(rawFreshWithNoise)!! + checkEq(freshWithNoise.contains(""""entries":{}"""), true, "seq12 pure noise entries stripped to {}") + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, freshWithNoise, ""), + true, + "seq12 fresh sentinel with noise accepted", + ) + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(s2Handle), true, "seq12 fresh with noise allows default") + + // Existing user who deleted all local workspaces ("affine-local-workspace": "[]") -> Imported, NOT FreshInstall. + val deletedAllSentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[]"},"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, deletedAllSentinel, ""), + true, + "seq12 deleted-all sentinel accepted", + ) + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(s2Handle), false, "seq12 deleted-all blocks default") + + // Mixed 1 allowlisted key + 1 unrelated noise key filtered through Rust JNI. + val rawMixedNoise = """{"origin":"https://localhost","length":2,"keys":["affine-local-workspace","__cap_noise__"],"entries":{"affine-local-workspace":"[\"ws-live\"]","__cap_noise__":"junk"},"idbTouchCount":0}""" + val mixedNoiseSentinel = LegacyLocalStorageProbe.filterSnapshotEntries(rawMixedNoise)!! + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, mixedNoiseSentinel, ""), + true, + "seq12 mixed allowlisted+noise sentinel accepted", + ) + checkEq( + NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(s2Handle), + """["ws-live"]""", + "seq12 mixed sentinel workspace ids", + ) + val rawReadbackWithNoise = """{"origin":"https://localhost","length":2,"keys":["__cap_noise__","affine-local-workspace"],"entries":{"__cap_noise__":"junk","affine-local-workspace":"[\"ws-live\"]"},"removedKeys":[],"verified":true,"idbTouchCount":0}""" + val filteredReadback = LegacyLocalStorageProbe.filterSnapshotEntries(rawReadbackWithNoise)!! + checkEq( + NativeBridge.nativeVerifyLegacyWriteBack( + """{"affine-local-workspace":"[\"ws-live\"]"}""", + "[]", + filteredReadback, + ), + true, + "seq12 filtered mixed rollback readback verified", + ) + + // Upgrade payload with allowlisted workspace IDs, dynamic keys, and 1 unrelated noise key (length=4, keys.len=4). + val upgradeSentinel = """{"origin":"https://localhost","length":4,"keys":["__cap_noise__","affine-local-workspace","global-state:serverConfig:self-host","theme"],"entries":{"affine-local-workspace":"[\"ws-live\"]","global-state:serverConfig:self-host":"{\"url\":\"https://self.example\"}","theme":"dark"},"removedKeys":["last_workspace_id"],"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(s2Handle, upgradeSentinel, ""), + true, + "seq12 upgrade sentinel accepted", + ) + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(s2Handle), false, "seq12 upgrade blocks default") + checkEq( + NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(s2Handle), + """["ws-live"]""", + "seq12 allowlisted workspace ids", + ) + + // F1: deleted residual .db is rejected; allowlisted workspace & userspace connect in place. + checkEq( + NativeBridge.nativeConnectWorkspace(s2Handle, tmpDir.absolutePath, "local", "ws-deleted"), + null, + "seq12 deleted workspace rejected (zero resurrection)", + ) + val wsKey = NativeBridge.nativeConnectWorkspace(s2Handle, tmpDir.absolutePath, "local", "ws-live") + checkEq(wsKey != null, true, "seq12 allowlisted workspace connected") + val emptyUpdateB64 = Rfc4648Base64.encode(byteArrayOf(0, 0)) + val pushedTs = NativeBridge.nativeStoragePushUpdateB64( + s2Handle, + wsKey!!, + "doc-1", + emptyUpdateB64, + 1_795_597_759_000L, + ) + checkEq(pushedTs >= 1_795_597_759_000L, true, "seq12 sqlite push_update persisted") + checkEq(NativeBridge.nativeStorageGetDocB64(s2Handle, wsKey, "doc-1"), emptyUpdateB64, "seq12 sqlite get_doc roundtrip") + checkEq(NativeBridge.nativeStorageCheckpoint(s2Handle, wsKey), true, "seq12 sqlite checkpoint") + + // Cloud workspace (peer != "local") opens directly without membership in affine-local-workspace. + val cloudWsKey = NativeBridge.nativeConnectWorkspace( + s2Handle, + tmpDir.absolutePath, + "https://app.affine.pro", + "ws-cloud-99", + ) + checkEq(cloudWsKey != null, true, "seq12 cloud workspace connected") + checkEq( + File(tmpDir, "workspaces/workspace/https_app.affine.pro/ws-cloud-99.db").exists(), + true, + "seq12 cloud workspace db path matches 0.27.5 sanitization", + ) + + val userKey = NativeBridge.nativeOpenUserspace( + s2Handle, + tmpDir.absolutePath, + "https://app.affine.pro/", + "user-1", + ) + checkEq(userKey != null, true, "seq12 userspace connected") + checkEq( + File(tmpDir, "workspaces/userspace/https_app.affine.pro/user-1.db").exists(), + true, + "seq12 userspace db path matches 0.27.5 sanitization", + ) + // Simulate MainActivity.onStop() non-blocking PASSIVE checkpoint across all open DBs. + checkEq( + NativeBridge.nativeStorageCheckpointAllPassive(s2Handle), + 3, + "seq12 checkpointAllPassive covers local + cloud workspace + userspace", + ) + checkEq(NativeBridge.nativeStorageClose(s2Handle, wsKey), true, "seq12 sqlite close") + checkEq(NativeBridge.nativeStorageClose(s2Handle, cloudWsKey!!), true, "seq12 cloud ws close") + checkEq(NativeBridge.nativeStorageClose(s2Handle, userKey!!), true, "seq12 userspace close") + + // 12b. AndroidBootstrapCoordinator end-to-end: mount legacy DB -> read doc -> onStop checkpoint, + // plus empty-list zero mounts and corrupt raw string preservation. + val bootHandle = NativeBridge.nativeCreateHost() + try { + val coordinator = AndroidBootstrapCoordinator({ bootHandle }, { tmpDir.absolutePath }) + val bootUpgrade = coordinator.completeWithProbePayload(upgradeSentinel) + checkEq(bootUpgrade.imported, true, "seq12b bootstrap imported") + checkEq(bootUpgrade.connectedWorkspaceKeys.size, 1, "seq12b mounted 1 allowlisted workspace") + val mountedKey = bootUpgrade.connectedWorkspaceKeys[0] + checkEq( + NativeBridge.nativeStorageGetDocB64(bootHandle, mountedKey, "doc-1"), + emptyUpdateB64, + "seq12b bootstrap read existing doc from mounted DB", + ) + checkEq( + NativeBridge.nativeStorageCheckpointAllPassive(bootHandle), + 1, + "seq12b onStop passive checkpoint hit mounted DB", + ) + + // Empty list -> zero mounts, evicts previously mounted local DB, and rollback emits "[]" (canCreateDefault=false). + val bootEmpty = coordinator.completeWithProbePayload(deletedAllSentinel) + checkEq(bootEmpty.imported, true, "seq12b empty list imported") + checkEq(bootEmpty.connectedWorkspaceKeys.isEmpty(), true, "seq12b empty list zero mounts") + checkEq(NativeBridge.nativeStorageCheckpointAllPassive(bootHandle), 0, "seq12b evicted old local DB") + val emptyWriteback = NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle) + checkEq(emptyWriteback != null && emptyWriteback.contains("\"affine-local-workspace\":\"[]\""), true, "seq12b empty imported list emits []") + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(bootHandle), false, "seq12b empty imported list canCreateDefault=false") + + // True FreshInstall (missing affine-local-workspace key) -> rollback emits empty setEntries (canCreateDefault=true preserved). + val freshEmptySentinel = """{"origin":"https://localhost","length":0,"keys":[],"entries":{},"idbTouchCount":0}""" + val bootFresh = coordinator.completeWithProbePayload(freshEmptySentinel) + checkEq(bootFresh.imported, true, "seq12b fresh install imported") + checkEq(NativeBridge.nativeCanCreateDefaultWorkspace(bootHandle), true, "seq12b fresh install canCreateDefault=true") + val freshWriteback = NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle) + checkEq(freshWriteback != null && !freshWriteback.contains("affine-local-workspace"), true, "seq12b fresh install writeback omits affine-local-workspace") + + // Corrupt affine-local-workspace JSON -> zero mounts & preserves raw "{broken" string. + val corruptWsSentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"{broken"},"idbTouchCount":0}""" + val bootCorrupt = coordinator.completeWithProbePayload(corruptWsSentinel) + checkEq(bootCorrupt.imported, true, "seq12b corrupt list imported safely") + checkEq(bootCorrupt.connectedWorkspaceKeys.isEmpty(), true, "seq12b corrupt list zero mounts") + checkEq(bootCorrupt.isComplete, true, "seq12b corrupt list has zero failed allowlist ids") + checkEq(bootCorrupt.preservedLocalWorkspaceRaw, "{broken", "seq12b corrupt raw string preserved") + + // Partial mount failure: ["ws-ok", "../bad-id"] exposes failedWorkspaceIds, + // gates rollback write-back, and pruning the allowlist to ["ws-ok"] + retry lifts the gate. + val partialFailSentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-ok\",\"../bad-id\"]"},"idbTouchCount":0}""" + val bootPartial = coordinator.completeWithProbePayload(partialFailSentinel) + checkEq(bootPartial.imported, true, "seq12b partial failure still imported") + checkEq(bootPartial.connectedWorkspaceKeys.size, 1, "seq12b healthy ws-ok mounted") + checkEq(bootPartial.connectedWorkspaceKeys[0].contains("ws-ok"), true, "seq12b mounted key is ws-ok") + checkEq(bootPartial.failedWorkspaceIds, listOf("../bad-id"), "seq12b failedWorkspaceIds recorded") + checkEq(bootPartial.isComplete, false, "seq12b partial failure isComplete=false") + checkEq( + NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle), + null, + "seq12b rollback writeback gated while mount failure unresolved", + ) + + // Update allowlist to ["ws-ok"] and retry: ws-ok stays alive, obsolete ../bad-id pruned, writeback unblocked. + val fixedAllowlistSentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-ok\"]"},"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(bootHandle, fixedAllowlistSentinel, ""), + true, + "seq12b updated allowlist imported", + ) + val bootPruned = coordinator.retryFailedWorkspaces(bootPartial) + checkEq(bootPruned.isComplete, true, "seq12b pruned retry isComplete=true") + checkEq(bootPruned.failedWorkspaceIds.isEmpty(), true, "seq12b obsolete failed id dropped") + checkEq(bootPruned.connectedWorkspaceKeys.size, 1, "seq12b ws-ok handle preserved") + val unblockedPlan = NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle) + checkEq(unblockedPlan != null && unblockedPlan.contains("ws-ok"), true, "seq12b writeback gate lifted") + + // Retryable mount failure: block ws-retry.db with a directory, fail once, remove dir, retry -> isComplete=true. + val blockingDbDir = File(tmpDir, "workspaces/workspace/local/ws-retry.db") + blockingDbDir.mkdirs() + val retrySentinel = """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-ok\",\"ws-retry\"]"},"idbTouchCount":0}""" + val bootBeforeRetry = coordinator.completeWithProbePayload(retrySentinel) + checkEq(bootBeforeRetry.imported, true, "seq12b retryable imported") + checkEq(bootBeforeRetry.connectedWorkspaceKeys.size, 1, "seq12b ws-ok connected before retry") + checkEq(bootBeforeRetry.failedWorkspaceIds, listOf("ws-retry"), "seq12b ws-retry failed while blocked") + checkEq(bootBeforeRetry.isComplete, false, "seq12b before retry isComplete=false") + checkEq(NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle), null, "seq12b blocked writeback while ws-retry failing") + blockingDbDir.deleteRecursively() + val bootAfterRetry = coordinator.retryFailedWorkspaces(bootBeforeRetry) + checkEq(bootAfterRetry.isComplete, true, "seq12b after retry isComplete=true") + checkEq(bootAfterRetry.failedWorkspaceIds.isEmpty(), true, "seq12b failedWorkspaceIds empty after retry") + checkEq(bootAfterRetry.connectedWorkspaceKeys.size, 2, "seq12b both workspaces connected after retry") + checkEq(NativeBridge.nativePlanLegacyLocalStorageWriteBack(bootHandle) != null, true, "seq12b writeback allowed after retry") + } finally { + NativeBridge.nativeDestroyHost(bootHandle) + } + + // Rollback write-back verification with setEntries + removeKeys (and forbidding removing affine-local-workspace). + val expectedSet = """{"affine-local-workspace":"[\"ws-live\"]","theme":"dark"}""" + val expectedRemove = """["last_workspace_id"]""" + checkEq( + NativeBridge.nativeVerifyLegacyWriteBack(expectedSet, expectedRemove, upgradeSentinel), + true, + "seq12 rollback writeback verified with removeKeys", + ) + checkEq( + NativeBridge.nativeVerifyLegacyWriteBack(expectedSet, """["affine-local-workspace"]""", upgradeSentinel), + false, + "seq12 forbid removing affine-local-workspace", + ) + + // 13. Pure-Kotlin RFC 4648 Base64 (API 24 + JVM) + DataStore `v1:` AES-GCM + + // 2-instance single-flight refresh + CookieCleaner on offline logout. + val sampleBytes = ByteArray(256) { it.toByte() } + checkEq(Rfc4648Base64.decode(Rfc4648Base64.encode(sampleBytes)).contentEquals(sampleBytes), true, "seq13 base64 0..255 roundtrip") + checkEq(Rfc4648Base64.encode(byteArrayOf()), "", "seq13 base64 empty") + checkEq(Rfc4648Base64.encode("f".toByteArray()), "Zg==", "seq13 base64 1-byte") + checkEq(Rfc4648Base64.encode("fo".toByteArray()), "Zm8=", "seq13 base64 2-byte") + checkEq(Rfc4648Base64.encode("foo".toByteArray()), "Zm9v", "seq13 base64 3-byte") + + val clearedCookieEndpoints = mutableListOf() + val recordingCookieCleaner = object : CookieCleaner { + override fun clearAuthCookies(canonicalEndpoint: String) { + synchronized(clearedCookieEndpoints) { clearedCookieEndpoints.add(canonicalEndpoint) } + } + } + val sharedKeys = InMemoryAesKeyProvider() + val cipher1 = AuthTokenCipher(keyProvider = sharedKeys, explicitIvForJvm = true) + val cipher2 = AuthTokenCipher(keyProvider = sharedKeys, explicitIvForJvm = true) + val store = AuthSessionStore(tmpDir.absolutePath, cipher1, recordingCookieCleaner) + val store2 = AuthSessionStore(tmpDir.absolutePath, cipher2, recordingCookieCleaner) + + val instId1 = store.getOrCreateInstallationId("inst-fixed-0275") + val instId2 = store2.getOrCreateInstallationId("inst-must-not-replace") + checkEq(instId1, "inst-fixed-0275", "seq13 installationId persisted") + checkEq(instId2, "inst-fixed-0275", "seq13 installationId reused across instances") + + val serverResp = """{ + "tokenType": "Bearer", + "accessToken": "acc-s2-token", + "refreshToken": "ref-s2-token", + "expiresIn": 3600, + "refreshExpiresAt": "2027-01-01T00:00:00.000Z", + "session": { "absoluteExpiresAt": "2027-06-01T00:00:00Z" } + }""" + val rotatedResp = """{ + "tokenType": "Bearer", + "accessToken": "acc-rotated-token", + "refreshToken": "ref-rotated-token", + "expiresIn": 3600, + "refreshExpiresAt": "2027-01-01T00:00:00.000Z", + "session": { "absoluteExpiresAt": "2027-06-01T00:00:00Z" } + }""" + val nowMs = 1_795_597_759_000L + val ep = "https://app.affine.pro" + checkEq( + store.storeServerResponse("https://app.affine.pro:443/graphql", serverResp, nowMs), + true, + "seq13 storeServerResponse encrypted and persisted", + ) + checkEq( + File(tmpDir, "datastore/auth-sessions.preferences_pb").exists(), + true, + "seq13 auth-sessions.preferences_pb written on disk", + ) + val rawCiphertext = NativeBridge.nativeDataStoreGetString( + tmpDir.absolutePath, + "auth-token:$ep", + ) + checkEq(rawCiphertext != null && rawCiphertext.startsWith("v1:"), true, "seq13 stored ciphertext is v1:") + checkEq(NativeBridge.nativeValidateV1Ciphertext(rawCiphertext!!), true, "seq13 v1 envelope valid") + + val decrypted = store2.readSessionJson(ep) + checkEq(decrypted != null && decrypted.contains("\"accessExpiresAt\":${nowMs + 3_600_000L}"), true, "seq13 Unix ms i64 roundtrip") + checkEq(decrypted!!.contains("acc-s2-token"), true, "seq13 accessToken roundtrip") + + // 2 separate AuthSessionStore instances concurrently call refreshSession -> single-flight fires ONLY 1 transport call. + val epochBeforeSingleFlight = store.currentEpoch(ep) + val transportCalls = AtomicInteger(0) + val enteredTransport = CountDownLatch(1) + val releaseTransport = CountDownLatch(1) + val res1 = AtomicReference(false) + val res2 = AtomicReference(false) + val t1 = Thread { + res1.set( + store.refreshSession(ep) { _, _ -> + transportCalls.incrementAndGet() + enteredTransport.countDown() + releaseTransport.await() + RefreshResult.Success(rotatedResp, nowMs + 5_000L) + }, + ) + } + t1.start() + enteredTransport.await() + val t2 = Thread { + res2.set( + store2.refreshSession(ep) { _, _ -> + transportCalls.incrementAndGet() + RefreshResult.Failure("REFRESH_TOKEN_REUSED") + }, + ) + } + t2.start() + while (t2.state != Thread.State.WAITING) { + Thread.yield() + } + releaseTransport.countDown() + t1.join() + t2.join() + checkEq(transportCalls.get(), 1, "seq13 single-flight coalesced 2 instances into 1 transport call") + checkEq(res1.get(), true, "seq13 single-flight caller 1 succeeded") + checkEq(res2.get(), true, "seq13 single-flight caller 2 shared success") + checkEq(store.readSessionJson(ep)?.contains("acc-rotated-token"), true, "seq13 rotated token persisted") + + // Late stale-epoch REFRESH_TOKEN_REUSED must NEVER delete the newly rotated token. + checkEq( + store2.handleRefreshFailureIfEpochMatches(ep, epochBeforeSingleFlight, "REFRESH_TOKEN_REUSED"), + false, + "seq13 stale-epoch REFRESH_TOKEN_REUSED ignored", + ) + checkEq(store.readSessionJson(ep)?.contains("acc-rotated-token"), true, "seq13 rotated token intact") + + // Offline clearSession deletes token AND clears cookies while preserving installationId. + val epochBeforeLogout = store.currentEpoch(ep) + checkEq(store.clearSession(ep), true, "seq13 offline clearSession deleted token") + checkEq(store.readSessionJson(ep), null, "seq13 session empty after clearSession") + checkEq(clearedCookieEndpoints.contains(ep), true, "seq13 CookieCleaner invoked on clearSession") + checkEq( + store2.storeRefreshedSessionIfEpochMatches(ep, epochBeforeLogout, serverResp, nowMs + 10_000L), + false, + "seq13 late refresh response rejected after clearSession", + ) + checkEq(store.readSessionJson(ep), null, "seq13 DataStore remains empty after late refresh") + checkEq( + store.getOrCreateInstallationId("must-still-reuse"), + "inst-fixed-0275", + "seq13 installationId preserved after logout", + ) + + // Corrupt auth-sessions.preferences_pb must throw on getOrCreateInstallationId (never overwrite). + val corruptDir = Files.createTempDirectory("affine-s2-corrupt-ds").toFile() + try { + val dsFile = File(corruptDir, "datastore/auth-sessions.preferences_pb") + dsFile.parentFile.mkdirs() + val badBytes = byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1) + dsFile.writeBytes(badBytes) + val corruptStore = AuthSessionStore(corruptDir.absolutePath, cipher1, recordingCookieCleaner) + var threwOnCorrupt = false + try { + corruptStore.getOrCreateInstallationId("must-not-overwrite") + } catch (_: IllegalStateException) { + threwOnCorrupt = true + } + checkEq(threwOnCorrupt, true, "seq13 corrupt datastore throws instead of overwriting installationId") + checkEq(dsFile.readBytes().contentEquals(badBytes), true, "seq13 corrupt datastore bytes untouched on disk") + } finally { + corruptDir.deleteRecursively() + } + + // 14. Concurrent cold-start getOrCreateInstallationId returns one consistent UUID across racing threads. + val raceDir = Files.createTempDirectory("affine-s2-inst-race").toFile() + try { + val raceStore1 = AuthSessionStore(raceDir.absolutePath, cipher1, recordingCookieCleaner) + val raceStore2 = AuthSessionStore(raceDir.absolutePath, cipher2, recordingCookieCleaner) + val ready = CountDownLatch(2) + val go = CountDownLatch(1) + val idA = AtomicReference(null) + val idB = AtomicReference(null) + val rt1 = Thread { + ready.countDown() + go.await() + idA.set(raceStore1.getOrCreateInstallationId("uuid-a")) + } + val rt2 = Thread { + ready.countDown() + go.await() + idB.set(raceStore2.getOrCreateInstallationId("uuid-b")) + } + rt1.start() + rt2.start() + ready.await() + go.countDown() + rt1.join() + rt2.join() + checkEq(idA.get() != null && idA.get() == idB.get(), true, "seq14 racing threads returned identical installationId") + checkEq(idA.get() == "uuid-a" || idA.get() == "uuid-b", true, "seq14 installationId is one of the candidates") + checkEq( + AuthSessionStore(raceDir.absolutePath, cipher1, recordingCookieCleaner).getOrCreateInstallationId("uuid-c"), + idA.get(), + "seq14 persisted installationId matches racing winner", + ) + } finally { + raceDir.deleteRecursively() + } + + // 15. Named 3 auth cookies cleanup preserves non-auth cookies + DataStore cookie keys cleanup + + // IPv6 canonicalization + serde_json JNI escape handling + HttpUrlConnectionRefreshTransport. + val jar = linkedMapOf( + "affine_session" to "s1", + "affine_csrf_token" to "c1", + "theme_pref" to "dark", + ) + val rawCookieHeader = jar.entries.joinToString("; ") { "${it.key}=${it.value}" } + val expiredHeaders = AndroidCookieCleaner.filterClearedCookieHeaders(rawCookieHeader) + checkEq(expiredHeaders.size, 2, "seq15 only 2 present auth cookies expired") + for (hdr in expiredHeaders) { + val name = hdr.substringBefore("=") + checkEq(hdr.contains("Max-Age=0"), true, "seq15 cookie header expires $name") + jar.remove(name) + } + checkEq(jar.containsKey("affine_session"), false, "seq15 affine_session cleared") + checkEq(jar.containsKey("affine_csrf_token"), false, "seq15 affine_csrf_token cleared") + checkEq(jar["theme_pref"], "dark", "seq15 non-auth theme_pref preserved") + + // DataStore legacy cookie keys (affine_user_id, affine_csrf_token) in + // 0.27.5 datastore/affine.preferences_pb are deleted on clearSession while preserving + // unrelated prefs (theme=dark) and auth-sessions.preferences_pb installationId. + val absentAppDsDir = Files.createTempDirectory("affine-s2-absent-app-ds").toFile() + try { + checkEq( + NativeBridge.nativeLegacyAppDataStoreDeleteKey(absentAppDsDir.absolutePath, "app.affine.proaffine_user_id"), + true, + "seq15 missing affine.preferences_pb delete succeeds", + ) + checkEq( + File(absentAppDsDir, "datastore/affine.preferences_pb").exists(), + false, + "seq15 missing affine.preferences_pb is not created on delete", + ) + } finally { + absentAppDsDir.deleteRecursively() + } + val scratchSeedDir = Files.createTempDirectory("affine-s2-seed-legacy-pb").toFile() + val scratchInspectDir = Files.createTempDirectory("affine-s2-inspect-legacy-pb").toFile() + try { + checkEq(NativeBridge.nativeDataStoreSetString(scratchSeedDir.absolutePath, "app.affine.proaffine_user_id", "u1"), true, "seq15 build legacy user_id pb") + checkEq(NativeBridge.nativeDataStoreSetString(scratchSeedDir.absolutePath, "app.affine.proaffine_csrf_token", "c1"), true, "seq15 build legacy csrf pb") + checkEq(NativeBridge.nativeDataStoreSetString(scratchSeedDir.absolutePath, "theme", "dark"), true, "seq15 build legacy theme pb") + val legacyTargetPb = File(tmpDir, "datastore/affine.preferences_pb") + legacyTargetPb.parentFile.mkdirs() + File(scratchSeedDir, "datastore/auth-sessions.preferences_pb").copyTo(legacyTargetPb, overwrite = true) + + checkEq(store.storeServerResponse(ep, serverResp, nowMs), true, "seq15 re-seed auth session before clear") + + // Simulate transient legacy file failure (corrupt bytes in affine.preferences_pb) -> clearSession returns false while still clearing auth session. + val brokenDir = Files.createTempDirectory("affine-s2-broken-legacy-pb").toFile() + try { + val brokenStore = AuthSessionStore( + filesDir = brokenDir.absolutePath, + cipher = cipher1, + cookieCleaner = recordingCookieCleaner, + ) + checkEq(brokenStore.storeServerResponse(ep, serverResp, nowMs), true, "seq15 seed brokenDir auth") + val brokenLegacyPb = File(brokenDir, "datastore/affine.preferences_pb") + brokenLegacyPb.parentFile.mkdirs() + brokenLegacyPb.writeBytes(byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0x7F)) + checkEq(brokenStore.clearSession(ep), false, "seq15 clearSession surfaces legacy cleanup failure") + checkEq(brokenStore.readSessionJson(ep), null, "seq15 primary auth session still wiped") + brokenLegacyPb.delete() + checkEq(brokenStore.clearSession(ep), true, "seq15 retry clearSession succeeds after legacy file healthy") + } finally { + brokenDir.deleteRecursively() + } + + checkEq(store.clearSession(ep), true, "seq15 clearSession returns true when healthy") + val inspectTargetPb = File(scratchInspectDir, "datastore/auth-sessions.preferences_pb") + inspectTargetPb.parentFile.mkdirs() + legacyTargetPb.copyTo(inspectTargetPb, overwrite = true) + checkEq(NativeBridge.nativeDataStoreGetString(scratchInspectDir.absolutePath, "app.affine.proaffine_user_id"), null, "seq15 affine.preferences_pb user_id deleted") + checkEq(NativeBridge.nativeDataStoreGetString(scratchInspectDir.absolutePath, "app.affine.proaffine_csrf_token"), null, "seq15 affine.preferences_pb csrf deleted") + checkEq(NativeBridge.nativeDataStoreGetString(scratchInspectDir.absolutePath, "theme"), "dark", "seq15 affine.preferences_pb theme preserved") + checkEq(store.getOrCreateInstallationId("must-still-preserve"), "inst-fixed-0275", "seq15 auth-sessions installationId preserved") + } finally { + scratchSeedDir.deleteRecursively() + scratchInspectDir.deleteRecursively() + } + + // IPv6 canonicalization and serde_json JNI escape fidelity. + checkEq(NativeBridge.nativeCanonicalEndpoint("https://[::1]:8443/graphql"), "https://[::1]:8443", "seq15 ipv6 non-default port") + checkEq(NativeBridge.nativeCanonicalEndpoint("https://[::1]:443/graphql"), "https://[::1]", "seq15 ipv6 default port stripped") + checkEq( + NativeBridge.nativeExtractJsonStringField("""{"refreshToken":"tok-\u0041\"\\"}""", "refreshToken"), + "tok-A\"\\", + "seq15 serde_json unescapes \\u0041 quote backslash", + ) + + // AndroidManifest.xml declares minSdkVersion=24 and android.permission.INTERNET. + val manifestFile = listOf( + File("hosts/android/AndroidManifest.xml"), + File("packages/frontend/hosts/android/AndroidManifest.xml"), + ).firstOrNull { it.exists() } + checkEq(manifestFile != null, true, "seq15 AndroidManifest.xml located") + val manifestXml = manifestFile!!.readText(StandardCharsets.UTF_8) + checkEq(manifestXml.contains("""android:minSdkVersion="24""""), true, "seq15 manifest minSdkVersion=24") + checkEq(manifestXml.contains("""android.permission.INTERNET"""), true, "seq15 manifest declares INTERNET permission") + + // Production default HttpUrlConnectionRefreshTransport against local loopback ServerSocket: + // MUST NOT send Authorization: Bearer header (prevents 3-segment refreshToken JWT misclassification). + val capturedRequest = AtomicReference("") + ServerSocket(0).use { server -> + val port = server.localPort + val serverThread = Thread { + server.accept().use { sock -> + val reader = sock.getInputStream().bufferedReader(StandardCharsets.UTF_8) + val reqLines = StringBuilder() + var contentLength = 0 + while (true) { + val line = reader.readLine() ?: break + if (line.isEmpty()) break + reqLines.append(line).append('\n') + if (line.lowercase().startsWith("content-length:")) { + contentLength = line.substringAfter(':').trim().toIntOrNull() ?: 0 + } + } + if (contentLength > 0) { + val bodyChars = CharArray(contentLength) + reader.read(bodyChars) + reqLines.append(String(bodyChars)) + } + capturedRequest.set(reqLines.toString()) + val respBytes = rotatedResp.toByteArray(StandardCharsets.UTF_8) + val httpResp = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${respBytes.size}\r\nConnection: close\r\n\r\n" + sock.getOutputStream().write(httpResp.toByteArray(StandardCharsets.UTF_8)) + sock.getOutputStream().write(respBytes) + sock.getOutputStream().flush() + } + } + serverThread.start() + val httpTransport = HttpUrlConnectionRefreshTransport(appVersion = "0.27.5") + val fixedAttemptId = "11111111-2222-3333-4444-555555555555" + val httpRes = httpTransport.refresh( + "http://127.0.0.1:$port", + "aff_rt_v1.idpart.secretpart", + fixedAttemptId, + ) + serverThread.join() + checkEq(httpRes is RefreshResult.Success, true, "seq15 HttpUrlConnectionRefreshTransport succeeded") + val reqText = capturedRequest.get() + checkEq(reqText.contains("POST /api/auth/session/refresh"), true, "seq15 HTTP POST refresh path") + checkEq(reqText.lowercase().contains("authorization:"), false, "seq15 MUST NOT send Authorization header on refresh") + checkEq(reqText.lowercase().contains("x-affine-client-kind: native"), true, "seq15 x-affine-client-kind sent") + checkEq(reqText.lowercase().contains("x-affine-version: 0.27.5"), true, "seq15 x-affine-version sent") + checkEq(reqText.lowercase().contains("x-affine-refresh-attempt: $fixedAttemptId"), true, "seq15 x-affine-refresh-attempt sent") + checkEq(reqText.contains("aff_rt_v1.idpart.secretpart"), true, "seq15 refreshToken sent in JSON body") + } + + // 16. Refresh idempotency (reuse x-affine-refresh-attempt across transient retries, fresh UUID after rotation) + // + in-memory pendingRotatedSession flush on disk-write failure with 0 network calls on retry. + val retryDir = Files.createTempDirectory("affine-s2-refresh-retry").toFile() + try { + val failNextWrite = AtomicReference(false) + val flakyPersistence = SessionPersistence { dir, key, enc -> + if (failNextWrite.getAndSet(false)) { + false + } else { + NativeBridge.nativeDataStoreSetString(dir, key, enc) + } + } + val retryStore = AuthSessionStore( + filesDir = retryDir.absolutePath, + cipher = cipher1, + cookieCleaner = recordingCookieCleaner, + persistence = flakyPersistence, + ) + val epRetry = "https://retry.affine.pro" + checkEq(retryStore.storeServerResponse(epRetry, serverResp, nowMs), true, "seq16 seed initial session") + + // Part A: transient timeout -> retry reuses exact same lowercase UUID attemptId; next rotation uses new UUID. + val seenAttempts = mutableListOf() + var callNum = 0 + val attemptTransport = RefreshTransport { _, _, attemptId -> + seenAttempts.add(attemptId) + callNum += 1 + when (callNum) { + 1 -> RefreshResult.Failure(null) + 2 -> RefreshResult.Success(rotatedResp, nowMs + 10_000L) + else -> RefreshResult.Success(serverResp, nowMs + 20_000L) + } + } + checkEq(retryStore.refreshSession(epRetry, attemptTransport), false, "seq16 transient timeout returns false") + checkEq(retryStore.refreshSession(epRetry, attemptTransport), true, "seq16 retry succeeds") + checkEq(seenAttempts.size, 2, "seq16 2 attempts recorded") + checkEq(seenAttempts[0] == seenAttempts[1], true, "seq16 transient retry reused identical x-affine-refresh-attempt") + checkEq(seenAttempts[0] == seenAttempts[0].lowercase(), true, "seq16 attemptId is lowercase UUID") + checkEq(retryStore.refreshSession(epRetry, attemptTransport), true, "seq16 subsequent rotation succeeds") + checkEq(seenAttempts.size, 3, "seq16 3rd attempt recorded") + checkEq(seenAttempts[2] != seenAttempts[1], true, "seq16 new logical rotation generated fresh attemptId") + + // Part B: 200 OK received but disk write fails -> next refreshSession flushes cached session with 0 network calls. + val networkCalls = AtomicInteger(0) + failNextWrite.set(true) + val writeFailTransport = RefreshTransport { _, _, _ -> + networkCalls.incrementAndGet() + RefreshResult.Success(rotatedResp, nowMs + 30_000L) + } + checkEq(retryStore.refreshSession(epRetry, writeFailTransport), false, "seq16 disk write failure returns false") + checkEq(networkCalls.get(), 1, "seq16 1 network call made before disk write failure") + checkEq(retryStore.refreshSession(epRetry, writeFailTransport), true, "seq16 second refresh flushes cached rotated session") + checkEq(networkCalls.get(), 1, "seq16 ZERO additional network calls on cached session flush") + checkEq(retryStore.readSessionJson(epRetry)?.contains("acc-rotated-token"), true, "seq16 flushed rotated token readable from disk") + // Part C: Cold process restart recovery — copying only disk DataStore to a brand-new filesDir + // (zero shared in-memory EndpointCoordination!) still reuses the persisted x-affine-refresh-attempt UUID. + val proc1Dir = Files.createTempDirectory("affine-s2-proc1").toFile() + val proc2Dir = Files.createTempDirectory("affine-s2-proc2").toFile() + try { + val proc1Store = AuthSessionStore(filesDir = proc1Dir.absolutePath, cipher = cipher1, cookieCleaner = recordingCookieCleaner) + checkEq(proc1Store.storeServerResponse(epRetry, serverResp, nowMs), true, "seq16 proc1 seed") + var proc1Attempt = "" + checkEq( + proc1Store.refreshSession(epRetry, RefreshTransport { _, _, id -> + proc1Attempt = id + RefreshResult.Failure(null) + }), + false, + "seq16 proc1 transient failure", + ) + val proc2Pb = File(proc2Dir, "datastore/auth-sessions.preferences_pb") + proc2Pb.parentFile.mkdirs() + File(proc1Dir, "datastore/auth-sessions.preferences_pb").copyTo(proc2Pb, overwrite = true) + val proc2Store = AuthSessionStore(filesDir = proc2Dir.absolutePath, cipher = cipher1, cookieCleaner = recordingCookieCleaner) + var proc2Attempt = "" + checkEq( + proc2Store.refreshSession(epRetry, RefreshTransport { _, _, id -> + proc2Attempt = id + RefreshResult.Success(rotatedResp, nowMs + 40_000L) + }), + true, + "seq16 proc2 cold-restart recovery succeeds", + ) + checkEq(proc1Attempt.isNotEmpty() && proc1Attempt == proc2Attempt, true, "seq16 cold-restart reused persisted x-affine-refresh-attempt") + } finally { + proc1Dir.deleteRecursively() + proc2Dir.deleteRecursively() + } + } finally { + retryDir.deleteRecursively() + } + } finally { + NativeBridge.nativeDestroyHost(s2Handle) + tmpDir.deleteRecursively() + } + + // 17. End-to-end Text <-> SelectionCoordinator/InputConnection: pure-Rust fallback layout + // (proportional widths & per-paragraph UAX #9 BiDi), grab-offset 0px drag, vertical drag + // beyond 0.5*line_height, slow drag across length==0 coincidence point (10->8->6->5->3), + // required HostClipboard Copy/Cut/Paste, InputConnection.performContextMenuAction(cut/paste), + // zero-alloc fillOverlayGeometry, and ACTION_CANCEL. + val selHandle = NativeBridge.nativeCreateHost() + try { + var overlayInvalidations = 0 + val ime = AffineImeController({ selHandle }, onMutated = { overlayInvalidations += 1 }) + val sel = AndroidSelectionCoordinator({ selHandle }, onMutated = { overlayInvalidations += 1 }) + sel.setViewport(1080f, 2400f, 3f) + + // Proportional fallback widths: "WWWW" is strictly wider than "iiii". + checkEq(ime.commitText("iiii", 1), true, "seq17 commit iiii") + checkEq(ime.setSelection(0, 4), true, "seq17 select iiii") + val narrowWidth = sel.overlayGeometry()!![9] - sel.overlayGeometry()!![3] + checkEq(ime.replaceText(0, ime.readText().length, "WWWW", 1), true, "seq17 replace with WWWW") + checkEq(ime.setSelection(0, 4), true, "seq17 select WWWW") + val wideWidth = sel.overlayGeometry()!![9] - sel.overlayGeometry()!![3] + checkEq(wideWidth > narrowWidth * 1.5f, true, "seq17 proportional fallback WWWW wider than iiii") + + // Insert "Hello world" and select [6, 11) ("world") -> handles & action menu auto-appear. + val invBefore = overlayInvalidations + checkEq(ime.replaceText(0, ime.readText().length, "Hello world", 1), true, "seq17 commit Hello world") + checkEq(ime.setSelection(6, 11), true, "seq17 select [6, 11)") + checkEq(overlayInvalidations > invBefore, true, "seq17 IME mutations trigger overlay invalidation") + checkEq(ime.getSelectedText(), "world", "seq17 initial selected text") + val g0 = sel.overlayGeometry()!! + checkEq(g0.size, 24, "seq17 fixed 24-float overlay geometry") + checkEq(g0[0], 1f, "seq17 has_selection=1") + checkEq(g0[1], 0f, "seq17 LTR direction=0") + checkEq(g0[19], 1f, "seq17 action menu visible before drag") + + // Grab End handle center and apply authoritative endpoints -> tip & selection stay identical. + val endCx = g0[11] + val endCy = g0[12] + val endTipX = g0[9] + val startTipX = g0[3] + val startTipY = g0[4] + val endTipY = g0[10] + checkEq(sel.beginDrag(endCx, endCy), 2, "seq17 hit End handle") + sel.applyTextDragEndpoints(startTipX, startTipY, endTipX, endTipY, 60f, false, 2) + checkEq(ime.getSelectedText(), "world", "seq17 0px drag preserves selection") + val gDragBuf = FloatArray(24) + checkEq(sel.fillOverlayGeometry(gDragBuf), true, "seq17 zero-alloc fillOverlayGeometry succeeds") + checkEq(gDragBuf[14], 1f, "seq17 magnifier visible during drag") + checkEq(gDragBuf[19], 0f, "seq17 action menu hidden during drag") + // Magnifier anchor_y must sit at the line vertical midpoint (strictly above tip_y). + checkEq(gDragBuf[16] < gDragBuf[10], true, "seq17 magnifier focus_y centered on line midpoint") + + // Vertical drag beyond 0.5*line_height on a single line keeps End active and magnifier at right end. + for (dy in listOf(-43f, -60f, -120f, 0f, 43f, 120f, 0f)) { + sel.applyTextDragEndpoints(startTipX, startTipY, endTipX, endTipY, 60f, false, 2) + checkEq(ime.selectionStart(), 6, "seq17 vertical drag dy=$dy keeps start=6") + checkEq(ime.selectionEnd(), 11, "seq17 vertical drag dy=$dy keeps end=11") + checkEq(sel.fillOverlayGeometry(gDragBuf), true, "seq17 fillOverlayGeometry at dy=$dy") + checkEq( + kotlin.math.abs(gDragBuf[15] - endTipX) < 0.01f, + true, + "seq17 magnifier anchor_x stays on right end at dy=$dy", + ) + } + + // Continuous drag across coincidence point (length==0) -> inverted selection [3, 6) == "lo ". + checkEq(ime.setSelection(3, 6), true, "seq17 inverted selection [3, 6)") + sel.applyTextDragEndpoints(startTipX - 80f, startTipY, startTipX, startTipY, 60f, false, 1) + checkEq(ime.selectionStart(), 3, "seq17 inverted selection start=3") + checkEq(ime.selectionEnd(), 6, "seq17 inverted selection end=6") + checkEq(ime.getSelectedText(), "lo ", "seq17 inverted selection text == 'lo '") + checkEq(sel.endDrag(), true, "seq17 endDrag restores action menu") + + // Real HostClipboard integration: pre-seeded stale value replaced on Copy & Cut, + // failing clipboard aborts Cut before deleting text, Paste restores Cut text. + var clipboardStore: String? = "stale-clipboard" + val mockClipboard = object : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean { + clipboardStore = text + return true + } + override fun getPlainText(): String? = clipboardStore + } + val failingClipboard = object : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean = false + override fun getPlainText(): String? = null + } + checkEq(sel.performCopy(ime, mockClipboard), "lo ", "seq17 Copy returns 'lo '") + checkEq(clipboardStore, "lo ", "seq17 Copy wrote 'lo ' to HostClipboard") + + // ACTION_CANCEL hides magnifier cleanly. + val gBeforeCancel = sel.overlayGeometry()!! + checkEq(sel.beginDrag(gBeforeCancel[5], gBeforeCancel[6]) != 0, true, "seq17 begin drag before cancel") + checkEq(sel.overlayGeometry()!![14], 1f, "seq17 magnifier shown before cancel") + sel.cancelDrag() + checkEq(sel.overlayGeometry()!![14], 0f, "seq17 ACTION_CANCEL hides magnifier") + + // Cut with failing clipboard must NOT delete text; Cut with working clipboard writes BEFORE deleting. + checkEq(sel.performCut(ime, failingClipboard), null, "seq17 Cut aborts when clipboard write fails") + checkEq(ime.readText(), "Hello world", "seq17 text preserved when clipboard write fails") + clipboardStore = "stale-before-cut" + + // Real InputConnection.performContextMenuAction(cut / paste / selectAll) round-trip. + val ctxIc = AffineSurfaceView.createInputConnection( + handleProvider = { selHandle }, + onContextMenuAction = { actionId -> + sel.handleContextMenuAction(actionId, ime, mockClipboard) + }, + ) + checkEq(ctxIc.performContextMenuAction(android.R.id.cut), true, "seq17 IC performContextMenuAction(cut)") + checkEq(clipboardStore, "lo ", "seq17 IC cut wrote 'lo ' to HostClipboard") + checkEq(ime.readText(), "Helworld", "seq17 text after IC cut") + checkEq(sel.overlayGeometry()!![0], 0f, "seq17 collapsed selection auto-hides handles") + checkEq(ctxIc.performContextMenuAction(android.R.id.paste), true, "seq17 IC performContextMenuAction(paste)") + checkEq(ime.readText(), "Hello world", "seq17 IC paste restored exact original text") + checkEq(ime.selectionStart(), 6, "seq17 IC paste placed cursor at end of pasted span") + checkEq(ime.selectionEnd(), 6, "seq17 IC paste collapsed selection") + checkEq(ctxIc.performContextMenuAction(android.R.id.selectAll), true, "seq17 IC selectAll") + checkEq(ime.getSelectedText(), "Hello world", "seq17 IC selectAll selected full text") + + // Per-paragraph ("\n") UAX #9 BiDi: paragraph 0 ("A") is LTR, paragraph 1 ("שלום") is RTL. + checkEq(ime.replaceText(0, ime.readText().length, "A\nשלום", 1), true, "seq17 insert mixed BiDi paragraphs") + checkEq(ime.setSelection(0, 1), true, "seq17 select LTR paragraph 0") + checkEq(sel.overlayGeometry()!![1], 0f, "seq17 paragraph 0 ('A') is LTR") + checkEq(ime.setSelection(2, 6), true, "seq17 select RTL paragraph 1") + val gParaRtl = sel.overlayGeometry()!! + checkEq(gParaRtl[1], 1f, "seq17 paragraph 1 ('שלום') is RTL") + checkEq(gParaRtl[3] > gParaRtl[9], true, "seq17 paragraph 1 Start tip visually right of End tip") + + // Pure RTL ("שלום עולם"): direction=1, Start handle visually right of End handle, drag updates IME. + checkEq(ime.replaceText(0, ime.readText().length, "שלום עולם", 1), true, "seq17 insert RTL text") + checkEq(ime.setSelection(0, 4), true, "seq17 select RTL [0, 4)") + val gRtl = sel.overlayGeometry()!! + checkEq(gRtl[1], 1f, "seq17 RTL direction=1") + checkEq(gRtl[3] > gRtl[9], true, "seq17 RTL Start tip is visually right of End tip") + checkEq(sel.beginDrag(gRtl[11], gRtl[12]), 2, "seq17 hit RTL End handle") + checkEq(ime.setSelection(0, 6), true, "seq17 RTL selection [0, 6)") + sel.applyTextDragEndpoints(gRtl[3], gRtl[4], gRtl[9] - 56.88f, gRtl[10], 60f, true, 2) + checkEq(ime.selectionStart(), 0, "seq17 RTL selection start=0") + checkEq(ime.selectionEnd(), 6, "seq17 RTL selection end=6") + checkEq(sel.endDrag(), true, "seq17 RTL endDrag") + sel.clear() + checkEq(sel.overlayGeometry()!![0], 0f, "seq17 clear hides selection") + } finally { + NativeBridge.nativeDestroyHost(selHandle) + } + + // 18. Surface recreation state preservation (DPI, scroll, IME text, texture generation), + // nav-bar-deducted effective IME inset, cross-generation readiness guard, and Vulkan -> GLES3 recovery. + val recHandle = NativeBridge.nativeCreateHost() + try { + val ime = AffineImeController { recHandle } + checkEq(ime.commitText("persist-me", 1), true, "seq18 seed IME text") + NativeBridge.nativeOnSurfaceInsetsPx(recHandle, 120, 0, 72, 0, 900, 3.0f) + checkEq(NativeBridge.nativeGetSurfaceDensity(recHandle), 3.0f, "seq18 density preserved") + checkEq(NativeBridge.nativeGetEffectiveImeBottomDp(recHandle), 276.0f, "seq18 IME inset deducts nav bar bottom") + NativeBridge.nativeSetSurfaceScrollOffset(recHandle, 0f, 512.5f) + + // Select Vulkan (1), report Vulkan device loss -> downgrades seamlessly to GLES3 (2). + checkEq(NativeBridge.nativeSelectRenderBackend(recHandle, true, true), 1, "seq18 selected Vulkan") + checkEq(NativeBridge.nativeReportVulkanDeviceLost(recHandle), 2, "seq18 Vulkan device loss downgrades to GLES3") + checkEq(NativeBridge.nativeGetRenderBackend(recHandle), 2, "seq18 active backend is GLES3") + checkEq(NativeBridge.nativeGetTextureGeneration(recHandle) >= 1L, true, "seq18 texture generation advanced") + + // Background destroy & rotation size change preserve scroll, density, and IME text; + // before surfaceCreated + surfaceChanged pair completes, surface stays not ready. + NativeBridge.nativeOnSurfaceChanged(recHandle, 1, 1080, 2400) + NativeBridge.nativeOnSurfaceDestroyed(recHandle) + checkEq(NativeBridge.nativeIsSurfaceReady(recHandle), false, "seq18 destroyed surface not ready") + checkEq(NativeBridge.nativeOnFrameTick(recHandle, 20_000_000L), 0, "seq18 detached tick returns 0") + NativeBridge.nativeOnSurfaceChanged(recHandle, 1, 2400, 1080) + checkEq(NativeBridge.nativeHasPendingFrame(recHandle), true, "seq18 pending frame set after destroy") + checkEq(NativeBridge.nativeGetSurfaceScrollY(recHandle), 512.5f, "seq18 scroll offset preserved") + checkEq(NativeBridge.nativeGetSurfaceDensity(recHandle), 3.0f, "seq18 density preserved after destroy") + checkEq(ime.readText(), "persist-me", "seq18 IME text preserved across surface destroy") + } finally { + NativeBridge.nativeDestroyHost(recHandle) + } + + // 19. API 26+ AutofillManager virtual view structure bridge vs API 24/25 silent degradation, + // zero fake placeholders, IME write-back, and sensitive value wipe on commit/cancel. + for (legacySdk in listOf(24, 25)) { + val legacyAfHandle = NativeBridge.nativeCreateHost() + try { + val events = mutableListOf() + val mockBackend = object : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + events.add("enter:$autofillId") + } + override fun notifyViewExited(autofillId: Int) { events.add("exit:$autofillId") } + override fun notifyValueChanged(autofillId: Int, text: String) { events.add("val:$autofillId") } + override fun commit() { events.add("commit") } + override fun cancel() { events.add("cancel") } + } + val af = AndroidAutofillController(legacySdk, { legacyAfHandle }, mockBackend) + checkEq(af.isEnabled, false, "seq19 API $legacySdk autofill disabled") + checkEq(af.registerField(101, 1, 10, 20, 400, 80, false, 0), false, "seq19 API $legacySdk register blocked") + af.onFieldFocusChanged(101) + checkEq(af.onAutofillValues(mapOf(101 to "a@b.com")), 0, "seq19 API $legacySdk autofill ignored") + checkEq(af.commit(), false, "seq19 API $legacySdk commit blocked") + checkEq(events.isEmpty(), true, "seq19 API $legacySdk zero platform AutofillManager calls") + checkEq(af.virtualNodesSnapshot().isEmpty(), true, "seq19 API $legacySdk empty virtual nodes") + } finally { + NativeBridge.nativeDestroyHost(legacyAfHandle) + } + } + val api26Handle = NativeBridge.nativeCreateHost() + try { + val events = mutableListOf() + val mockBackend = object : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + events.add("enter:$autofillId:$left,$top,$right,$bottom") + } + override fun notifyViewExited(autofillId: Int) { events.add("exit:$autofillId") } + override fun notifyValueChanged(autofillId: Int, text: String) { events.add("val:$autofillId:$text") } + override fun commit() { events.add("commit") } + override fun cancel() { events.add("cancel") } + } + var syncingFocus = false + lateinit var af: AndroidAutofillController + val ime = AffineImeController( + handleProvider = { api26Handle }, + onMutated = {}, + onTextEdited = { edited -> + if (!syncingFocus) { + af.onFocusedTextEdited(edited) + } + }, + ) + val afIc = AffineSurfaceView.createInputConnection( + handleProvider = { api26Handle }, + onMutated = {}, + onTextEdited = { edited -> + if (!syncingFocus) { + af.onFocusedTextEdited(edited) + } + }, + ) + af = AndroidAutofillController( + sdkInt = 26, + handleProvider = { api26Handle }, + backend = mockBackend, + onValueCommitted = { id, text -> + if (af.focusedFieldId() == id) { + syncingFocus = true + try { + ime.replaceText(0, ime.readText().length, text, 1) + } finally { + syncingFocus = false + } + } + }, + onFocusedFieldTextSync = { _, text -> + syncingFocus = true + try { + ime.replaceText(0, ime.readText().length, text, 1) + } finally { + syncingFocus = false + } + }, + ) + checkEq(af.isEnabled, true, "seq19 API 26 autofill enabled") + checkEq(af.registerField(101, 1, 20, 100, 800, 180, false, 0), true, "seq19 register email field") + checkEq(af.registerField(102, 2, 20, 200, 800, 280, true, 8), true, "seq19 register password field") + checkEq(af.registerField(103, 3, 20, 300, 800, 380, false, 0), true, "seq19 register OTP field") + // Empty/unset fields MUST return null (never synthetic "********" or spaces). + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 unset password emits null, never fake asterisks") + checkEq(af.virtualNodesSnapshot().size, 3, "seq19 3 virtual autofill nodes exposed") + + // Pure manual typing without any prior Autofill write-back: + // focus email (101) -> type "a@b.c" -> switch to password (102) -> switch back to email (101) => "a@b.c" preserved. + af.onFieldFocusChanged(101) + checkEq(afIc.commitText("a@b.c", 1), true, "seq19 manual type a@b.c without prior autofill") + checkEq(af.readFormValues()["email"], "a@b.c", "seq19 manual typed email stored in autofill state") + af.onFieldFocusChanged(102) + checkEq(ime.readText(), "", "seq19 switching to empty password clears IME") + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "a@b.c", "seq19 returning to email restores manually typed a@b.c") + checkEq(af.readFormValues()["email"], "a@b.c", "seq19 form email remains a@b.c") + + // Matrix test: 2 focus targets (email vs password) x 2 batch orders ([email, password] vs [password, email]). + // IME must ALWAYS equal the currently focused field and NEVER be overwritten by another field's password. + val batchOrders = listOf( + "email_first" to linkedMapOf(101 to "darksky@affine.pro", 102 to "hunter2!"), + "password_first" to linkedMapOf(102 to "hunter2!", 101 to "darksky@affine.pro"), + ) + for ((focusId, expectedIme) in listOf(101 to "darksky@affine.pro", 102 to "hunter2!")) { + for ((orderName, batch) in batchOrders) { + af.onFieldFocusChanged(focusId) + checkEq( + AffineSurfaceView.dispatchAutofillBatch(af, batch), + 2, + "seq19 batch $orderName focus=$focusId applied 2 fields", + ) + checkEq( + ime.readText(), + expectedIme, + "seq19 batch $orderName focus=$focusId keeps IME strictly isolated to focused field", + ) + val form = af.readFormValues() + checkEq(form["email"], "darksky@affine.pro", "seq19 form email preserved ($orderName)") + checkEq(form["password"], "hunter2!", "seq19 form password preserved ($orderName)") + } + } + + // Manual IME edit round-trip: focus email (101) -> autofill A -> manual InputConnection edit to B -> + // switch focus to password (102) -> switch back to email (101) => both IME and form read B (never A). + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "darksky@affine.pro", "seq19 email focused starts with autofilled A") + checkEq(afIc.deleteSurroundingText(18, 0), true, "seq19 manual deleteSurroundingText on email") + checkEq(afIc.commitText("edited@affine.pro", 1), true, "seq19 manual commitText B on email") + checkEq(ime.readText(), "edited@affine.pro", "seq19 IME now has manual edit B") + checkEq(af.readFormValues()["email"], "edited@affine.pro", "seq19 autofill store synced manual edit B") + af.onFieldFocusChanged(102) + checkEq(ime.readText(), "hunter2!", "seq19 switching to password loads password") + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "edited@affine.pro", "seq19 returning to email preserves manual edit B (never clobbered by A)") + checkEq(af.readFormValues()["email"], "edited@affine.pro", "seq19 form email remains B after round-trip") + + // Clearing field text to "" must still notify AutofillManager. + checkEq(af.updateFieldText(102, ""), true, "seq19 clear password text") + checkEq(events.contains("val:102:"), true, "seq19 empty text still notifies notifyValueChanged") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 cleared password resolves to null") + + // Re-fill and verify structure JSON never leaks plaintext, then commit/cancel/clear wipe memory. + checkEq(af.updateFieldText(102, "hunter2!"), true, "seq19 restore password") + val structJson = af.virtualStructureJson() + checkEq(structJson.contains("\"emailAddress\""), true, "seq19 structure includes emailAddress") + checkEq(structJson.contains("\"password\""), true, "seq19 structure includes password") + checkEq(structJson.contains("\"smsOTPCode\""), true, "seq19 structure includes smsOTPCode") + checkEq(structJson.contains("hunter2!"), false, "seq19 structure JSON never leaks plaintext password") + checkEq(af.commit(), true, "seq19 autofill commit succeeded") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 commit wiped cached password") + checkEq(af.updateFieldText(102, "temp-secret"), true, "seq19 updateFieldText updates password") + checkEq(af.cancel(), true, "seq19 cancel wipes cached password") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 password wiped after cancel") + af.clearFields() + checkEq(af.virtualNodesSnapshot().isEmpty(), true, "seq19 clearFields removes all virtual nodes") + checkEq(events.contains("enter:101:20,100,800,180"), true, "seq19 notified enter 101") + checkEq(events.contains("exit:101"), true, "seq19 notified exit 101") + checkEq(events.contains("enter:102:20,200,800,280"), true, "seq19 notified enter 102") + checkEq(events.contains("commit"), true, "seq19 notified commit") + checkEq(events.contains("cancel"), true, "seq19 notified cancel") + } finally { + NativeBridge.nativeDestroyHost(api26Handle) + } + + // 20. Four-phase predictive back dispatcher across API levels (24, 33, 34) with real + // decrementing back_stack_depth, standalone API 34+ button-back, and re-entrancy guard. + val backCases = listOf( + Triple(24, 0, false), + Triple(32, 0, false), + Triple(33, 1, false), + Triple(34, 2, true), + Triple(35, 2, true), + ) + for ((sdk, expectedMode, supportsPredictive) in backCases) { + val backHandle = NativeBridge.nativeCreateHost() + try { + var exitCalls = 0 + var reentrantBlocked = false + var probeReentrantOnNextMutate = false + val visitedDestinations = mutableListOf() + val docStore = HostDocumentStore() + var switchingDoc = false + val navIme = AffineImeController( + handleProvider = { backHandle }, + onMutated = {}, + onTextEdited = { text -> + if (!switchingDoc) { + docStore.saveCurrent(text) + } + }, + ) + lateinit var dispatcher: AndroidBackDispatcher + dispatcher = AndroidBackDispatcher( + sdkInt = sdk, + handleProvider = { backHandle }, + onMutated = { + // Verify re-entrant commit inside Commit callback is blocked without double-popping. + if (probeReentrantOnNextMutate) { + probeReentrantOnNextMutate = false + if (supportsPredictive) { + if (!dispatcher.onBackInvoked()) reentrantBlocked = true + } else { + if (!dispatcher.onLegacyBackPressed()) reentrantBlocked = true + } + } + }, + onDestinationChanged = { dest -> + if (dest != null) { + visitedDestinations.add(dest) + if (docStore.activeDocumentId != dest) { + val targetText = docStore.switchTo(dest, navIme.currentText()) + switchingDoc = true + try { + navIme.replaceText(0, navIme.currentText().length, targetText, 1) + } finally { + switchingDoc = false + } + } + } + }, + onSystemExit = { exitCalls += 1 }, + ) + checkEq(dispatcher.dispatchMode, expectedMode, "seq20 API $sdk dispatchMode") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk starts on root destination") + + if (supportsPredictive) { + // Case A: 3-page real destination stack ("workspace/home" -> "doc/welcome" -> "doc/settings") + // driven via real host navigation entrypoints (navigateTo / openDocument), + // with two consecutive standalone button/key onBackInvoked() WITHOUT onBackStarted(). + checkEq(dispatcher.navigateTo("doc/welcome"), true, "seq20 API $sdk navigateTo doc/welcome") + checkEq(dispatcher.openDocument("settings"), true, "seq20 API $sdk openDocument settings") + checkEq(dispatcher.currentDestination(), "doc/settings", "seq20 API $sdk active route doc/settings") + probeReentrantOnNextMutate = true + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk standalone back #1 pops to doc/welcome") + checkEq(dispatcher.currentDestination(), "doc/welcome", "seq20 API $sdk route now doc/welcome") + checkEq(reentrantBlocked, true, "seq20 API $sdk re-entrant onBackInvoked blocked") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk standalone back #2 pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk route now workspace/home") + checkEq(exitCalls, 0, "seq20 API $sdk no exit while popping stack") + checkEq(dispatcher.onBackInvoked(), false, "seq20 API $sdk standalone back #3 at root returns false") + checkEq(exitCalls, 1, "seq20 API $sdk root delegates to onSystemExit") + + // Case B: Real document content switch (Doc A -> Doc B): + // Gesture Cancel keeps "Doc B"; Gesture Commit restores "Doc A"; + // follow-up standalone button back pops to workspace/home; root exits. + checkEq(dispatcher.openDocument("doc-a"), true, "seq20 API $sdk openDocument doc-a") + checkEq(navIme.commitText("Doc A", 1), true, "seq20 API $sdk write Doc A") + checkEq(dispatcher.openDocument("doc-b"), true, "seq20 API $sdk openDocument doc-b") + checkEq(navIme.commitText("Doc B", 1), true, "seq20 API $sdk write Doc B") + checkEq(docStore.activeDocumentId, "doc/doc-b", "seq20 API $sdk active doc is doc/doc-b") + checkEq(navIme.currentText(), "Doc B", "seq20 API $sdk IME holds Doc B") + checkEq(dispatcher.onBackStarted(0f), true, "seq20 API $sdk gesture Start") + checkEq(dispatcher.onBackProgressed(0.5f), true, "seq20 API $sdk gesture Progress") + checkEq(dispatcher.onBackCancelled(), true, "seq20 API $sdk gesture Cancel") + checkEq(dispatcher.currentDestination(), "doc/doc-b", "seq20 API $sdk Cancel keeps doc/doc-b") + checkEq(navIme.currentText(), "Doc B", "seq20 API $sdk Cancel keeps Doc B content") + checkEq(dispatcher.onBackStarted(0f), true, "seq20 API $sdk second gesture Start") + checkEq(dispatcher.onBackProgressed(0.8f), true, "seq20 API $sdk second gesture Progress") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk gesture Commit pops to doc/doc-a") + checkEq(dispatcher.currentDestination(), "doc/doc-a", "seq20 API $sdk route doc/doc-a after gesture") + checkEq(docStore.activeDocumentId, "doc/doc-a", "seq20 API $sdk activeDocumentId restored to doc/doc-a") + checkEq(navIme.currentText(), "Doc A", "seq20 API $sdk IME content restored to Doc A") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk follow-up button back pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk route workspace/home after button") + checkEq(dispatcher.onBackInvoked(), false, "seq20 API $sdk root back returns false") + checkEq(exitCalls, 2, "seq20 API $sdk second root exit delegated") + checkEq(visitedDestinations.contains("doc/doc-a"), true, "seq20 API $sdk destination callback fired") + } else { + checkEq(dispatcher.navigateTo("doc/welcome"), true, "seq20 API $sdk navigateTo doc/welcome") + checkEq(dispatcher.openDocument("settings"), true, "seq20 API $sdk openDocument settings") + checkEq(dispatcher.onBackStarted(0f), false, "seq20 API $sdk predictive Start disabled") + probeReentrantOnNextMutate = true + checkEq(dispatcher.onLegacyBackPressed(), true, "seq20 API $sdk legacy #1 pops to doc/welcome") + checkEq(dispatcher.currentDestination(), "doc/welcome", "seq20 API $sdk legacy route doc/welcome") + checkEq(reentrantBlocked, true, "seq20 API $sdk re-entrant onLegacyBackPressed blocked") + checkEq(dispatcher.onLegacyBackPressed(), true, "seq20 API $sdk legacy #2 pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk legacy route workspace/home") + checkEq(exitCalls, 0, "seq20 API $sdk no exit while popping stack") + checkEq(dispatcher.onLegacyBackPressed(), false, "seq20 API $sdk legacy root returns false") + checkEq(exitCalls, 1, "seq20 API $sdk legacy root delegates to system exit") + } + } finally { + NativeBridge.nativeDestroyHost(backHandle) + } + } + + // 21. Native PdfRenderer page bridge: valid ARGB_8888 -> RGBA8, negative dpiBucket clamp, + // out-of-bounds & OOM cap rejection, and >4096-pixel multi-chunk streaming conversion. + var backendRenderCalls = 0 + val fakePdfBackend = object : PdfPageBackend { + override fun pageCount(): Int = 3 + override fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray { + backendRenderCalls += 1 + if (widthPx == 2 && heightPx == 2) { + return intArrayOf( + 0xFF112233.toInt(), + 0x80AABBCC.toInt(), + 0xFFFFFFFF.toInt(), + 0x00010203, + ) + } + return IntArray(widthPx * heightPx) { idx -> + if (idx % 2 == 0) 0xFF102030.toInt() else 0x80405060.toInt() + } + } + override fun close() {} + } + AndroidPdfPageRenderer("doc-pdf-1", fakePdfBackend).use { pdf -> + checkEq(pdf.renderPageRgba(-1, 2, 2), null, "seq21 negative page rejected") + checkEq(pdf.renderPageRgba(3, 2, 2), null, "seq21 out-of-bounds page rejected") + checkEq(pdf.renderPageRgba(0, 4097, 2), null, "seq21 OOM width > 4096 rejected") + checkEq(pdf.renderPageRgba(0, 0, 2), null, "seq21 zero width rejected") + checkEq(backendRenderCalls, 0, "seq21 invalid requests never invoke PdfRenderer backend") + + val page = pdf.renderPageRgba(1, 2, 2, dpiBucket = 320) + checkEq(page != null, true, "seq21 valid 2x2 page rendered") + checkEq(backendRenderCalls, 1, "seq21 backend invoked once for valid page") + checkEq(page!!.cacheKey, "pdf:doc-pdf-1:p1:2x2@320dpi", "seq21 deterministic cache key") + val expectedRgba = byteArrayOf( + 0x11, 0x22, 0x33, 0xFF.toByte(), + 0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte(), 0x80.toByte(), + 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), + 0x01, 0x02, 0x03, 0x00, + ) + checkEq(page.rgbaBytes.contentEquals(expectedRgba), true, "seq21 exact ARGB_8888 -> RGBA8 conversion") + + // Negative dpiBucket clamps to 72dpi without NPE. + checkEq( + NativeBridge.nativePdfPageCacheKey("doc-pdf-1", 1, 2, 2, -100), + "pdf:doc-pdf-1:p1:2x2@72dpi", + "seq21 negative dpiBucket clamped to 72dpi without NPE", + ) + // Mismatched array length rejected before conversion. + checkEq( + NativeBridge.nativePdfConvertArgbToRgba(intArrayOf(1, 2, 3), 2, 2), + null, + "seq21 mismatched pixel array length returns null", + ) + // Multi-chunk streaming conversion (> 4096 pixels: 100 x 50 = 5000 pixels). + val largePage = pdf.renderPageRgba(2, 100, 50, dpiBucket = -5) + checkEq(largePage != null, true, "seq21 100x50 multi-chunk streaming page rendered") + checkEq(largePage!!.cacheKey, "pdf:doc-pdf-1:p2:100x50@72dpi", "seq21 negative dpi clamped via renderer") + checkEq(largePage.rgbaBytes.size, 5000 * 4, "seq21 5000-pixel RGBA8 byte length") + checkEq(largePage.rgbaBytes[0], 0x10.toByte(), "seq21 chunk 0 pixel 0 R") + checkEq(largePage.rgbaBytes[4999 * 4 + 3], 0x80.toByte(), "seq21 chunk 1 last pixel A") + } + + // 22. Authoritative TextLayoutAuthority selection parity (zero snap-back to Rust estimates on + // ACTION_UP/ACTION_CANCEL/selectAll), line-midpoint vertical grab probe on multi-line text, + // cross-anchor active_drag flip for loupe tracking, and strict Autofill/Document buffer isolation. + val layoutParityHandle = NativeBridge.nativeCreateHost() + try { + val narrowLayout = object : TextLayoutAuthority { + override var cachedText: String = "" + private val originX = 72f + private val originY = 240f + private val lineH = 60f + + private fun charWidth(c: Char): Float = when (c) { + 'i' -> 8f + ' ' -> 14f + else -> 30f + } + + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean { + cachedText = text + return true + } + + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds { + val off = utf16Offset.coerceIn(0, cachedText.length) + var line = 0 + var x = originX + for (idx in 0 until off) { + val ch = cachedText[idx] + if (ch == '\n') { + line += 1 + x = originX + } else { + x += charWidth(ch) + } + } + val top = originY + line * lineH + return CaretBounds(x = x, top = top, bottom = top + lineH, lineIndex = line, isRtlParagraph = false) + } + + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair = + caretBounds(selStart, false, selStart, selEnd) to caretBounds(selEnd, true, selStart, selEnd) + + override fun closestOffset(x: Float, y: Float): Int { + val lines = cachedText.split('\n') + val targetLine = if (y < originY) 0 else ((y - originY) / lineH).toInt().coerceIn(0, lines.lastIndex) + var lineStartOff = 0 + for (l in 0 until targetLine) { + lineStartOff += lines[l].length + 1 + } + val lineText = lines[targetLine] + var bestOff = lineStartOff + var curX = originX + var bestDist = kotlin.math.abs(x - curX) + for (i in lineText.indices) { + curX += charWidth(lineText[i]) + val d = kotlin.math.abs(x - curX) + if (d < bestDist) { + bestDist = d + bestOff = lineStartOff + i + 1 + } + } + return bestOff + } + } + + val ime = AffineImeController { layoutParityHandle } + val sel = AndroidSelectionCoordinator({ layoutParityHandle }) + sel.setViewport(1080f, 2400f, 3f) + val gesture = SelectionGestureController( + coordinator = sel, + layoutAuthority = narrowLayout, + selectionStartProvider = { ime.selectionStart() }, + selectionEndProvider = { ime.selectionEnd() }, + onSelectionChanged = { lo, hi -> ime.setSelection(lo, hi) }, + ) + + // Part A: "iiiiiiiiii world" [11, 16) -> ACTION_DOWN -> ACTION_MOVE -> ACTION_UP & ACTION_CANCEL + // and performContextMenuAction(selectAll) must keep 0.0px error against TextLayoutAuthority. + checkEq(ime.commitText("iiiiiiiiii world", 1), true, "seq22 commit narrow-i string") + checkEq(ime.setSelection(11, 16), true, "seq22 select [11, 16) world") + gesture.syncSelectionFromLayout(ime.currentText(), 11, 16, 1080, 3f) + val expectedWorld = narrowLayout.selectionEndCarets(11, 16) + val gInit = sel.overlayGeometry()!! + checkEq(gInit[3], expectedWorld.first.x, "seq22 initial start tip matches authoritative layout") + checkEq(gInit[9], expectedWorld.second.x, "seq22 initial end tip matches authoritative layout") + checkEq(gesture.onDown(gInit[11], gInit[12], 3f), 2, "seq22 hit End handle on narrow-i string") + checkEq(gesture.onMove(gInit[11], gInit[12]), true, "seq22 0px drag on narrow-i string") + checkEq(gesture.onUp(1080, 3f), true, "seq22 ACTION_UP restores menu") + val gAfterUp = sel.overlayGeometry()!! + checkEq(gAfterUp[3], expectedWorld.first.x, "seq22 ACTION_UP start tip keeps 0px error (never snaps to Rust estimate)") + checkEq(gAfterUp[9], expectedWorld.second.x, "seq22 ACTION_UP end tip keeps 0px error (never snaps to Rust estimate)") + checkEq(gesture.onDown(gAfterUp[11], gAfterUp[12], 3f), 2, "seq22 hit End handle before cancel") + checkEq(gesture.onCancel(1080, 3f), true, "seq22 ACTION_CANCEL finishes cleanly") + val gAfterCancel = sel.overlayGeometry()!! + checkEq(gAfterCancel[3], expectedWorld.first.x, "seq22 ACTION_CANCEL start tip keeps 0px error") + checkEq(gAfterCancel[9], expectedWorld.second.x, "seq22 ACTION_CANCEL end tip keeps 0px error") + + val dummyClipboard = object : HostClipboard { + var data: String? = null + override fun setPlainText(label: String, text: String): Boolean { data = text; return true } + override fun getPlainText(): String? = data + } + val selectAllIc = AffineSurfaceView.createInputConnection( + handleProvider = { layoutParityHandle }, + onContextMenuAction = { id -> + val ok = sel.handleContextMenuAction(id, ime, dummyClipboard) + if (ok) gesture.syncSelectionFromLayout(ime.currentText(), ime.selectionStart(), ime.selectionEnd(), 1080, 3f) + ok + }, + ) + checkEq(selectAllIc.performContextMenuAction(android.R.id.selectAll), true, "seq22 IC selectAll") + val expectedAll = narrowLayout.selectionEndCarets(0, 16) + val gAll = sel.overlayGeometry()!! + checkEq(gAll[3], expectedAll.first.x, "seq22 selectAll start tip matches layout") + checkEq(gAll[9], expectedAll.second.x, "seq22 selectAll end tip matches layout") + + // Part B: Multi-line line-0 handle grab uses line midpoint (never jumps to line 1), + // and cross-anchor inversion flips Rust active_drag so magnifier follows moving left end. + checkEq(ime.replaceText(0, ime.currentText().length, "First line\nSecond line", 1), true, "seq22 seed 2-line text") + checkEq(ime.setSelection(6, 10), true, "seq22 select line-0 'line' [6, 10)") + gesture.syncSelectionFromLayout(ime.currentText(), 6, 10, 1080, 3f) + val gMulti = sel.overlayGeometry()!! + checkEq(gesture.onDown(gMulti[11], gMulti[12], 3f), 2, "seq22 grab line-0 End handle") + // Stationary / tiny horizontal move must stay on line 0 (never jump to line 1). + checkEq(gesture.onMove(gMulti[11], gMulti[12]), true, "seq22 stationary move on line 0") + checkEq(ime.selectionStart(), 6, "seq22 line-0 grab stayed on line 0 start=6") + checkEq(ime.selectionEnd(), 10, "seq22 line-0 grab stayed on line 0 end=10") + // Drag right handle left past fixed anchor (offset 6) to offset 2 -> active_drag flips to Start + // and magnifier.anchor_x tracks moving left end caret(2).x (NOT stationary right anchor caret(6).x). + val targetLeftX = narrowLayout.caretBounds(2).x + val endTipInitialX = narrowLayout.caretBounds(10).x + checkEq(gesture.onMove(gMulti[11] + (targetLeftX - endTipInitialX), gMulti[12]), true, "seq22 cross-anchor drag to offset 2") + checkEq(ime.selectionStart(), 2, "seq22 cross-anchor inverted start=2") + checkEq(ime.selectionEnd(), 6, "seq22 cross-anchor inverted end=6") + val gCross = sel.overlayGeometry()!! + checkEq(gCross[14], 1f, "seq22 magnifier visible during cross-anchor drag") + checkEq(kotlin.math.abs(gCross[15] - targetLeftX) < 0.01f, true, "seq22 magnifier anchor_x tracks moving left end") + checkEq(gesture.onUp(1080, 3f), true, "seq22 release after cross-anchor drag") + checkEq(ime.selectionStart(), 2, "seq22 post-release inverted start=2") + checkEq(ime.selectionEnd(), 6, "seq22 post-release inverted end=6") + + // Mixed-BiDi outward teardrop orientation: embedded LTR run ("12", start_x < end_x) inside RTL + // paragraph and embedded RTL run ("אב", start_x > end_x) inside LTR paragraph both lean outward. + sel.updateSelection(200f, 300f, 240f, 300f, 60f, rtl = true, hasSelection = true) + val gMixedLtrInRtl = sel.overlayGeometry()!! + checkEq(gMixedLtrInRtl[5] < gMixedLtrInRtl[3], true, "seq22 RTL-para LTR-run start bulb leans left") + checkEq(gMixedLtrInRtl[11] > gMixedLtrInRtl[9], true, "seq22 RTL-para LTR-run end bulb leans right") + checkEq(gMixedLtrInRtl[11] - gMixedLtrInRtl[5] > gMixedLtrInRtl[7] * 2f, true, "seq22 RTL-para LTR-run bulbs never overlap") + + sel.updateSelection(240f, 300f, 200f, 300f, 60f, rtl = false, hasSelection = true) + val gMixedRtlInLtr = sel.overlayGeometry()!! + checkEq(gMixedRtlInLtr[5] > gMixedRtlInLtr[3], true, "seq22 LTR-para RTL-run start bulb leans right") + checkEq(gMixedRtlInLtr[11] < gMixedRtlInLtr[9], true, "seq22 LTR-para RTL-run end bulb leans left") + checkEq(gMixedRtlInLtr[5] - gMixedRtlInLtr[11] > gMixedRtlInLtr[7] * 2f, true, "seq22 LTR-para RTL-run bulbs never overlap") + + // Part C: Strict Autofill vs Document buffer isolation across password fill, editing, and route switch. + val docStore = HostDocumentStore("doc/roadmap", "") + lateinit var afCtrl: AndroidAutofillController + lateinit var bufCtrl: HostDocumentBufferController + val docIme = AffineImeController( + handleProvider = { layoutParityHandle }, + onMutated = {}, + onTextEdited = { t -> bufCtrl.onImeTextEdited(t) }, + ) + afCtrl = AndroidAutofillController( + sdkInt = 26, + handleProvider = { layoutParityHandle }, + ) + bufCtrl = HostDocumentBufferController( + documentStore = docStore, + imeProvider = { docIme }, + autofillProvider = { afCtrl }, + ) + val nav = AndroidBackDispatcher( + sdkInt = 34, + handleProvider = { layoutParityHandle }, + onDestinationChanged = { dest -> if (dest != null) bufCtrl.onRouteChanged(dest) }, + ) + checkEq(nav.openDocument("roadmap"), true, "seq22 open doc/roadmap") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Project roadmap", 1), true, "seq22 write roadmap text") + val seqBeforePollutionChecks = docIme.textInputChangeSeq() + + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 register password field") + bufCtrl.onAutofillFocusChanged(202) + checkEq(afCtrl.onAutofillValues(mapOf(202 to "s3cr3t!")), 1, "seq22 autofill password s3cr3t!") + checkEq(docIme.currentText(), "Project roadmap", "seq22 H-S1: autofill MUST NOT overwrite editor block") + checkEq(docIme.textInputChangeSeq(), seqBeforePollutionChecks, "seq22 H-S1: autofill MUST NOT touch editor undo/seq") + checkEq(docStore.readDocument("doc/roadmap"), "", "seq22 H-S1: host documentStore keeps zero shadow copy") + + // Switch route while password was focused -> editor block remains 100% unpolluted, password preserved. + checkEq(nav.openDocument("notes"), true, "seq22 navigate to doc/notes while password focused") + checkEq(docIme.currentText(), "Project roadmap", "seq22 H-S1: route switch MUST NOT overwrite editor block") + checkEq(nav.onBackInvoked(), true, "seq22 back to doc/roadmap") + checkEq(docIme.currentText(), "Project roadmap", "seq22 doc/roadmap untouched across route switch") + checkEq(docIme.textInputChangeSeq(), seqBeforePollutionChecks, "seq22 route switch MUST NOT pollute undo/seq") + checkEq(afCtrl.readFormValues()["password"], "s3cr3t!", "seq22 autofill password preserved") + + // Part D: Autofill session exit via commit / cancel / clear leaves editor block untouched. + val exitModes = listOf("commit", "cancel", "clear") + for (mode in exitModes) { + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 ($mode) register password field") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Doc-$mode", 1), true, "seq22 ($mode) seed doc text") + val seqSeeded = docIme.textInputChangeSeq() + bufCtrl.onAutofillFocusChanged(202) + checkEq(afCtrl.onAutofillValues(mapOf(202 to "f0rm-secret-99")), 1, "seq22 ($mode) autofill secret") + checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) editor block isolated from form secret") + when (mode) { + "commit" -> checkEq(bufCtrl.commitAutofillSession(), true, "seq22 commitAutofillSession") + "cancel" -> checkEq(bufCtrl.cancelAutofillSession(), true, "seq22 cancelAutofillSession") + "clear" -> bufCtrl.clearAutofillFields() + } + checkEq(bufCtrl.isAutofillFocused(), false, "seq22 ($mode) autofill unfocused after exit") + checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) editor block unchanged after autofill exit") + checkEq(docIme.textInputChangeSeq(), seqSeeded, "seq22 ($mode) zero editor mutations during autofill lifecycle") + checkEq(docIme.currentText().contains("f0rm-secret-99"), false, "seq22 ($mode) no form secret leaked") + } + + // Masked password field selection must clear document selection overlay while keeping form IME selection, + // and must block copy/cut from writing masked password plaintext to the system clipboard. + val maskedClipboard = object : HostClipboard { + var data: String? = "text copied elsewhere" + override fun setPlainText(label: String, text: String): Boolean { + data = text + return true + } + override fun getPlainText(): String? = data + } + val maskedSel = AndroidSelectionCoordinator({ layoutParityHandle }) + maskedSel.setViewport(1080f, 2400f, 3f) + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 masked register password field") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Hello document", 1), true, "seq22 masked seed doc") + bufCtrl.onAutofillFocusChanged(202) + checkEq(bufCtrl.isFocusedAutofillFieldMasked(), true, "seq22 focused password field is masked") + checkEq(docIme.setSelection(0, 6), true, "seq22 select [0, 6) inside masked password") + // Mirror MainActivity.onImeMutated suppression when Autofill is focused. + if (bufCtrl.isAutofillFocused()) { + maskedSel.clear() + } + checkEq(docIme.selectionStart(), 0, "seq22 masked form IME keeps selectionStart=0") + checkEq(docIme.selectionEnd(), 6, "seq22 masked form IME keeps selectionEnd=6") + val gMasked = maskedSel.overlayGeometry()!! + checkEq(gMasked[0], 0f, "seq22 masked password hides document overlay") + val maskedIc = AffineSurfaceView.createInputConnection( + handleProvider = { layoutParityHandle }, + onContextMenuAction = { actionId -> + if (bufCtrl.isAutofillFocused() && + (actionId == android.R.id.copy || actionId == android.R.id.cut) && + bufCtrl.isFocusedAutofillFieldMasked() + ) { + false + } else { + val ok = maskedSel.handleContextMenuAction(actionId, docIme, maskedClipboard) + if (bufCtrl.isAutofillFocused()) maskedSel.clear() + ok + } + }, + ) + checkEq(maskedIc.performContextMenuAction(android.R.id.copy), false, "seq22 masked copy blocked") + checkEq(maskedIc.performContextMenuAction(android.R.id.cut), false, "seq22 masked cut blocked") + checkEq(maskedClipboard.data, "text copied elsewhere", "seq22 clipboard untouched by masked copy/cut") + checkEq(bufCtrl.commitAutofillSession(), true, "seq22 exit masked autofill session") + checkEq(docIme.currentText(), "Hello document", "seq22 doc restored after masked autofill exit") + checkEq(docIme.setSelection(0, 5), true, "seq22 select [0, 5) in restored doc") + checkEq(maskedIc.performContextMenuAction(android.R.id.copy), true, "seq22 doc copy works after exit") + checkEq(maskedClipboard.data, "Hello", "seq22 doc copy wrote Hello to clipboard") + + // Part E: Mixed-direction run boundary disambiguation ("A אבג B") where RTL start offset 2 + // and LTR start offset 5 share one visual X coordinate. + val bidiBoundaryLayout = object : TextLayoutAuthority { + override var cachedText: String = "A \u05d0\u05d1\u05d2 B" + private val originX = 60f + private val originY = 200f + private val lineH = 56f + private val step = 28f + // Visual X positions for "A אבג B" (len 7): + // 0='A'[0..28], 1=' '[28..56], RTL run [2..5) occupies [56..140] (2->140, 3->112, 4->84, 5->56), + // LTR run [5..7) occupies [140..196] (5->140, 6->168, 7->196). + // Notice offset 2 (secondary) and offset 5 (primary) share visual X = originX + 140f! + private fun primX(off: Int): Float = when (off) { + 0 -> 0f + 1 -> step + 2 -> step * 2f + 3 -> step * 4f + 4 -> step * 3f + 5 -> step * 5f + 6 -> step * 6f + else -> step * 7f + } + private fun secX(off: Int): Float = when (off) { + 2 -> step * 5f + 5 -> step * 2f + else -> primX(off) + } + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean { + cachedText = text + return true + } + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds { + val inRtlRun = if (selStart < selEnd) { + val idx = if (isSelectionEnd) (utf16Offset - 1).coerceIn(selStart, cachedText.length - 1) else utf16Offset + idx in 2..4 + } else { + false + } + val lx = if (inRtlRun) secX(utf16Offset) else primX(utf16Offset) + return CaretBounds(originX + lx, originY, originY + lineH, 0, false) + } + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair = + caretBounds(selStart, false, selStart, selEnd) to caretBounds(selEnd, true, selStart, selEnd) + override fun closestOffset(x: Float, y: Float): Int = closestOffset(x, y, -1) + override fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int { + val localX = x - originX + val snapTol = minOf(6f, step * 0.35f) + if (preferredOffset in 0..cachedText.length) { + if (kotlin.math.abs(localX - primX(preferredOffset)) <= snapTol || + kotlin.math.abs(localX - secX(preferredOffset)) <= snapTol + ) { + return preferredOffset + } + } + // Ambiguous point at step*5 always returns 5 when preferredOffset is not matched. + return when { + localX < step * 0.5f -> 0 + localX < step * 1.5f -> 1 + localX < step * 2.5f -> 2 + localX < step * 3.5f -> 4 + localX < step * 4.5f -> 3 + localX < step * 5.5f -> 5 + localX < step * 6.5f -> 6 + else -> 7 + } + } + } + val bidiGesture = SelectionGestureController( + coordinator = sel, + layoutAuthority = bidiBoundaryLayout, + selectionStartProvider = { ime.selectionStart() }, + selectionEndProvider = { ime.selectionEnd() }, + onSelectionChanged = { lo, hi -> ime.setSelection(lo, hi) }, + ) + checkEq(ime.replaceText(0, ime.currentText().length, "A \u05d0\u05d1\u05d2 B", 1), true, "seq22 seed mixed BiDi boundary text") + // Case 1: [2, 5) start handle at shared boundary X -> stationary MOVE(0px) stays [2, 5), inward drag shrinks to [3, 5). + checkEq(ime.setSelection(2, 5), true, "seq22 select RTL [2, 5)") + bidiGesture.syncSelectionFromLayout(ime.currentText(), 2, 5, 1080, 3f) + val gRtl = sel.overlayGeometry()!! + checkEq(bidiGesture.onDown(gRtl[5], gRtl[6], 3f), 1, "seq22 hit RTL [2, 5) start handle") + checkEq(bidiGesture.onMove(gRtl[5], gRtl[6]), true, "seq22 RTL [2, 5) 0px move") + checkEq(ime.selectionStart(), 2, "seq22 RTL [2, 5) 0px move preserves start=2") + checkEq(ime.selectionEnd(), 5, "seq22 RTL [2, 5) 0px move preserves end=5") + checkEq(bidiGesture.onMove(gRtl[5] - 28f, gRtl[6]), true, "seq22 RTL [2, 5) inward 1-glyph drag") + checkEq(bidiGesture.onUp(1080, 3f), true, "seq22 RTL [2, 5) release") + checkEq(ime.selectionStart(), 3, "seq22 RTL [2, 5) inward drag shrinks to start=3") + checkEq(ime.selectionEnd(), 5, "seq22 RTL [2, 5) inward drag keeps end=5") + + // Case 2: [5, 7) start handle at shared boundary X -> stationary MOVE(0px) stays [5, 7), inward drag shrinks to [6, 7). + checkEq(ime.setSelection(5, 7), true, "seq22 select LTR [5, 7)") + bidiGesture.syncSelectionFromLayout(ime.currentText(), 5, 7, 1080, 3f) + val gLtr = sel.overlayGeometry()!! + checkEq(bidiGesture.onDown(gLtr[5], gLtr[6], 3f), 1, "seq22 hit LTR [5, 7) start handle") + checkEq(bidiGesture.onMove(gLtr[5], gLtr[6]), true, "seq22 LTR [5, 7) 0px move") + checkEq(ime.selectionStart(), 5, "seq22 LTR [5, 7) 0px move preserves start=5") + checkEq(ime.selectionEnd(), 7, "seq22 LTR [5, 7) 0px move preserves end=7") + checkEq(bidiGesture.onMove(gLtr[5] + 28f, gLtr[6]), true, "seq22 LTR [5, 7) inward 1-glyph drag") + checkEq(bidiGesture.onUp(1080, 3f), true, "seq22 LTR [5, 7) release") + checkEq(ime.selectionStart(), 6, "seq22 LTR [5, 7) inward drag shrinks to start=6") + checkEq(ime.selectionEnd(), 7, "seq22 LTR [5, 7) inward drag keeps end=7") + } finally { + NativeBridge.nativeDestroyHost(layoutParityHandle) + } + + // Sequence 23: Real JNI parity for [D-1] IPv6 AuthSessionStore single-source DataStore key/alias + // (verifying internal key/alias unity & rollback readback rule) and [D-2] bare `local-auth` + // single-key FreshInstall classification with verbatim rollback preservation. + val seq23Dir = java.nio.file.Files.createTempDirectory("affine-android-seq23-").toFile() + val seq23Handle = NativeBridge.nativeCreateHost() + try { + val seq23Cipher = AuthTokenCipher( + keyProvider = InMemoryAesKeyProvider(), + explicitIvForJvm = true, + ) + val seq23Store = AuthSessionStore( + filesDir = seq23Dir.absolutePath, + cipher = seq23Cipher, + cookieCleaner = object : CookieCleaner { + override fun clearAuthCookies(canonicalEndpoint: String) {} + }, + ) + val ipv6Endpoint = "https://[::1]:8443" + val ipv6ServerResp = """{"tokenType":"Bearer","accessToken":"acc-ipv6-1","expiresIn":3600,"refreshToken":"ref-ipv6-1","refreshExpiresAt":"2027-01-25T00:00:00Z","session":{"id":"sess-ipv6-1","absoluteExpiresAt":"2027-06-25T00:00:00Z"}}""" + checkEq( + seq23Store.storeServerResponse(ipv6Endpoint, ipv6ServerResp, 1_700_000_000_000L), + true, + "seq23 store IPv6 session", + ) + checkEq( + NativeBridge.nativeAuthTokenKey(ipv6Endpoint), + "auth-token:https://::1:8443", + "seq23 nativeAuthTokenKey strips IPv6 brackets in parity with keystore alias", + ) + val rawDisk = NativeBridge.nativeDataStoreReadResult( + seq23Dir.absolutePath, + "auth-token:https://::1:8443", + ) + checkEq( + rawDisk.startsWith("OK:v1:"), + true, + "seq23 DataStore persists encrypted session under auth-token:https://::1:8443", + ) + val decryptedIpv6 = seq23Store.readSessionJson(ipv6Endpoint) + checkEq( + decryptedIpv6 != null && + NativeBridge.nativeExtractJsonStringField(decryptedIpv6, "accessToken") == "acc-ipv6-1", + true, + "seq23 AuthSessionStore reads back and decrypts IPv6 session via single-source key", + ) + + // Bare `local-auth` single key classifies as FreshInstall (canCreateDefaultWorkspace == true, + // 0 workspaces mounted) while preserving `"local-auth": "\"tok\""` verbatim in write-back plan. + val bareAuthPayload = """{"origin":"https://localhost","length":1,"keys":["local-auth"],"entries":{"local-auth":"\"tok\""},"idbTouchCount":0}""" + checkEq( + NativeBridge.nativeImportLegacyLocalStorageProbe(seq23Handle, bareAuthPayload, ""), + true, + "seq23 bare local-auth probe succeeds", + ) + checkEq( + NativeBridge.nativeCanCreateDefaultWorkspace(seq23Handle), + true, + "seq23 bare local-auth classifies as FreshInstall (canCreateDefaultWorkspace=true)", + ) + checkEq( + NativeBridge.nativeGetAllowlistedWorkspaceIdsJson(seq23Handle), + "[]", + "seq23 bare local-auth mounts 0 workspaces", + ) + val bareWriteback = NativeBridge.nativePlanLegacyLocalStorageWriteBack(seq23Handle) + checkEq( + bareWriteback != null && bareWriteback.contains("\"local-auth\":\"\\\"tok\\\"\""), + true, + "seq23 bare local-auth preserved verbatim in rollback writeback plan", + ) + } finally { + NativeBridge.nativeDestroyHost(seq23Handle) + seq23Dir.deleteRecursively() + } + + // 24. S6 native GPU editor mount: H-A1 Gboard composing region, H-S1 Markdown transform & + // getExtractedText, H-S2 change sequence & block hash, sendKeyEvent block split/merge, and T1 readonly. + withHost { ic, ime -> + // H-A1: Gboard backspace-into-word (" hello" -> setComposingRegion(1, 6) -> setComposingText("hellos")) + checkEq(ic.commitText(" hello", 1), true, "seq24 commit ' hello'") + checkEq(ic.setComposingRegion(1, 6), true, "seq24 setComposingRegion(1, 6)") + checkEq(ime.composingStart(), 1, "seq24 composingStart 1") + checkEq(ime.composingEnd(), 6, "seq24 composingEnd 6") + checkEq(ic.setComposingText("hellos", 1), true, "seq24 setComposingText('hellos')") + checkEq(ime.readText(), " hellos", "seq24 Gboard composing region must not duplicate 'hello'") + checkEq(ic.finishComposingText(), true, "seq24 finishComposingText") + + // H-S1: authoritative editor text and collapsed selection after Gboard composing edit + checkEq(ime.readText(), " hellos", "seq24 authoritative text after composing") + checkEq(ime.selectionStart(), 7, "seq24 authoritative selectionStart == 7") + checkEq(ime.selectionEnd(), 7, "seq24 authoritative selectionEnd == 7") + + // sendKeyEvent: KEYCODE_ENTER splits block, KEYCODE_DEL at block start merges back + val seqBefore = ime.textInputChangeSeq() + val blockBefore = ime.focusedBlockHash() + checkEq(ime.sendKeyEvent(66, false, false, false), true, "seq24 KEYCODE_ENTER splits block") + checkEq(ime.readText(), "", "seq24 new split block is empty") + checkEq(ime.textInputChangeSeq() > seqBefore, true, "seq24 H-S2 change seq increments on split") + checkEq(ime.focusedBlockHash() != blockBefore, true, "seq24 H-S2 focused block hash changes on split") + checkEq(ime.sendKeyEvent(67, false, false, false), true, "seq24 KEYCODE_DEL merges with previous block") + checkEq(ime.readText(), " hellos", "seq24 block-start DEL merges back to ' hellos'") + } + + val seq24Handle = NativeBridge.nativeCreateHost() + try { + NativeBridge.nativeSetFormFactor(seq24Handle, 390) + checkEq(NativeBridge.nativeIsEdgelessReadonly(seq24Handle), true, "seq24 Phone edgeless_readonly") + checkEq(NativeBridge.nativeIsDatabaseReadonly(seq24Handle), true, "seq24 Phone database_readonly") + NativeBridge.nativeSetFormFactor(seq24Handle, 720) + checkEq(NativeBridge.nativeIsEdgelessReadonly(seq24Handle), true, "seq24 Tablet edgeless_readonly") + checkEq(NativeBridge.nativeIsDatabaseReadonly(seq24Handle), true, "seq24 Tablet database_readonly") + } finally { + NativeBridge.nativeDestroyHost(seq24Handle) + } + + // 25. AutofillVirtualInputConnection tracks composingRange across Gboard composing updates + // without exponential text duplication and never writes into the Rust document buffer. + val seq25Handle = NativeBridge.nativeCreateHost() + try { + val ime25 = AffineImeController({ seq25Handle }) + checkEq(ime25.commitText("doc-safe", 1), true, "seq25 seed document text") + val mockBackend25 = object : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) {} + override fun notifyViewExited(autofillId: Int) {} + override fun notifyValueChanged(autofillId: Int, text: String) {} + override fun commit() {} + override fun cancel() {} + } + val af25 = AndroidAutofillController(28, { seq25Handle }, mockBackend25) + checkEq(af25.registerField(1, 0, 10, 20, 300, 48, false, 0), true, "seq25 register field") + af25.onFieldFocusChanged(1) + val afIc = app.affine.pro.host.AutofillVirtualInputConnection(af25) + checkEq(afIc.setComposingText("a", 1), true, "seq25 setComposingText('a')") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "a", "seq25 composing 'a'") + checkEq(afIc.setComposingText("al", 1), true, "seq25 setComposingText('al')") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "al", "seq25 composing 'al' replaces 'a'") + checkEq(afIc.setComposingText("ali", 1), true, "seq25 setComposingText('ali')") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "ali", "seq25 composing 'ali' replaces 'al'") + checkEq(afIc.commitText("alice", 1), true, "seq25 commitText('alice')") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "alice", "seq25 committed value is exactly 'alice'") + checkEq(afIc.finishComposingText(), true, "seq25 finishComposingText") + checkEq(afIc.deleteSurroundingText(1, 0), true, "seq25 deleteSurroundingText(1, 0)") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "alic", "seq25 delete trims last char") + checkEq(ime25.readText(), "doc-safe", "seq25 autofill IC never mutates document buffer") + + // Cross-focus generation isolation: switching to field 2 invalidates field 1's IC, + // and focusing an autofill field invalidates a previously bound document IC. + checkEq(af25.registerField(2, 2, 10, 80, 300, 48, true, 0), true, "seq25 register field 2") + var restarts = 0 + af25.onFocusGenerationChanged = { restarts += 1 } + val staleDocGen = af25.currentFocusGeneration() + var contextMenuCalls = 0 + val staleDocIc = app.affine.pro.host.AffineInputConnection( + ime25, + onContextMenuAction = { + contextMenuCalls += 1 + true + }, + isActiveSession = { af25.focusedFieldId() == null && af25.currentFocusGeneration() == staleDocGen }, + ) + af25.onFieldFocusChanged(2) + checkEq(restarts >= 1, true, "seq25 focus switch bumps generation and requests restartInput") + checkEq(afIc.commitText("STALE", 1), false, "seq25 stale field 1 IC rejected after focus switch to field 2") + checkEq(afIc.setSelection(0, 1), false, "seq25 stale field 1 IC setSelection rejected") + checkEq(afIc.setComposingRegion(0, 1), false, "seq25 stale field 1 IC setComposingRegion rejected") + checkEq(af25.resolveVirtualFieldValueForStructure(1), "alic", "seq25 field 1 value untouched by stale IC") + checkEq(af25.resolveVirtualFieldValueForStructure(2), null, "seq25 field 2 value untouched by stale field 1 IC") + checkEq(staleDocIc.commitText("LEAK", 1), false, "seq25 stale doc IC rejected while autofill focused") + checkEq(staleDocIc.setSelection(0, 3), false, "seq25 stale doc IC setSelection rejected while autofill focused") + checkEq( + staleDocIc.performContextMenuAction(android.R.id.cut), + false, + "seq25 stale doc IC performContextMenuAction rejected while autofill focused", + ) + checkEq(contextMenuCalls, 0, "seq25 stale doc IC never invokes context menu callback") + checkEq( + staleDocIc.sendKeyEvent(null), + false, + "seq25 stale doc IC sendKeyEvent rejected while autofill focused", + ) + checkEq(ime25.readText(), "doc-safe", "seq25 document buffer untouched by stale doc IC") + } finally { + NativeBridge.nativeDestroyHost(seq25Handle) + } + + // Sequence 26: Code block toggles EditorInfo.inputType to NO_SUGGESTIONS (no CAP_SENTENCES/AUTO_CORRECT). + val seq26Handle = NativeBridge.nativeCreateHost() + try { + NativeBridge.nativeResetEmptyDocument(seq26Handle) + val proseCodeMode = NativeBridge.nativeWantsCodeInput(seq26Handle) + checkEq(proseCodeMode, false, "seq26 prose wantsCodeInput=false") + val proseInputType = AffineSurfaceView.resolveDocumentInputType(proseCodeMode) + checkEq( + (proseInputType and android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0, + true, + "seq26 prose inputType enables CAP_SENTENCES", + ) + val ic26 = AffineSurfaceView.createInputConnection(handleProvider = { seq26Handle }) + ic26.commitText("``` ", 1) + val codeMode = NativeBridge.nativeWantsCodeInput(seq26Handle) + checkEq(codeMode, true, "seq26 code block wantsCodeInput=true") + val codeInputType = AffineSurfaceView.resolveDocumentInputType(codeMode) + checkEq( + (codeInputType and android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0, + true, + "seq26 code inputType enables NO_SUGGESTIONS", + ) + checkEq( + (codeInputType and (android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or android.text.InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)) == 0, + true, + "seq26 code inputType disables CAP_SENTENCES and AUTO_CORRECT", + ) + } finally { + NativeBridge.nativeDestroyHost(seq26Handle) + } + + // Sequence 27: Android native island (ShareIntentBridge) non-destructive block & SQLite ingestion: + // - Scheme allowlist (`http(s)://` for URLs, `content://`/`http(s)://` + non-empty bytes for images; rejects `file://`) + // - Preserves active word selection (`[6, 12)` = `"native"`) and focused paragraph text untouched (zero IME typing) + // - Read-only page leaves queued shares intact (`pendingCount > 0`) until unlocked + // - Appends real BlockSuite `affine:bookmark`, `affine:paragraph` (`quote`), and SHA-256 `affine:image` blocks + // - Commits atomically into mounted SQLite workspace (`blobs` + `updates` + `share_ingest_receipts`) and survives reopen + val seq27Handle = NativeBridge.nativeCreateHost() + val seq27Dir = java.nio.file.Files.createTempDirectory("affine-share-sqlite-").toFile() + try { + val png1x1 = byteArrayOf( + 0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, + 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, + ) + checkEq( + NativeBridge.nativeShareEnqueue(seq27Handle, "bad-1", ShareIntentBridge.KIND_URL, "Bad", "javascript:alert(1)", "text/plain"), + false, + "seq27 rejects non-http(s) share URL", + ) + checkEq( + NativeBridge.nativeShareEnqueueBytes(seq27Handle, "bad-file-img", ShareIntentBridge.KIND_IMAGE, "Secret", "file:///sdcard/secret.png", "image/png", png1x1), + false, + "seq27 rejects file:// image URI", + ) + checkEq( + NativeBridge.nativeShareEnqueue(seq27Handle, "bad-empty-img", ShareIntentBridge.KIND_IMAGE, "Empty", "content://media/external/images/media/1", "image/png"), + false, + "seq27 rejects image without resolved bytes", + ) + checkEq( + NativeBridge.nativeShareEnqueue(seq27Handle, "share-1", ShareIntentBridge.KIND_URL, "AFFiNE", "https://affine.pro", "text/plain"), + true, + "seq27 accepts https share URL", + ) + checkEq(NativeBridge.nativeSharePendingCount(seq27Handle), 1, "seq27 pendingCount == 1") + val drained = NativeBridge.nativeShareDrainJson(seq27Handle) ?: "" + checkEq(drained.contains("https://affine.pro"), true, "seq27 drained JSON contains shared URL") + checkEq(NativeBridge.nativeSharePendingCount(seq27Handle), 0, "seq27 pendingCount == 0 after drain") + + // Prepare active paragraph `"Hello native world"` with word `"native"` selected (`[6, 12)`). + NativeBridge.nativeResetEmptyDocument(seq27Handle) + val ime27 = AffineImeController { seq27Handle } + checkEq(ime27.commitText("Hello native world", 1), true, "seq27 seed paragraph text") + checkEq(ime27.setSelection(6, 12), true, "seq27 select word 'native' [6, 12)") + checkEq(ime27.selectionStart(), 6, "seq27 pre-share selectionStart == 6") + checkEq(ime27.selectionEnd(), 12, "seq27 pre-share selectionEnd == 12") + + // Enqueue URL + Image (`ACTION_SEND`) and 2 Images + Text (`ACTION_SEND_MULTIPLE` + text). + val shareBridge = ShareIntentBridge(handleProvider = { seq27Handle }) + val streamBytes = mapOf( + "content://media/external/images/media/42" to png1x1, + "content://media/1" to png1x1, + "content://media/2" to png1x1, + ) + val enqueuedBoth = shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Caption + Image", + text = "https://affine.pro/shared", + streamUris = listOf("content://media/external/images/media/42"), + streamBytes = streamBytes, + idPrefix = "main-send", + ) + checkEq(enqueuedBoth, 2, "seq27 ACTION_SEND with EXTRA_TEXT + EXTRA_STREAM enqueues both") + val enqueuedText = shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "", + text = "SHAREDTEXT", + streamUris = emptyList(), + idPrefix = "main-text", + ) + checkEq(enqueuedText, 1, "seq27 plain text share enqueued") + val enqueuedMulti = shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/*", + subject = "Gallery", + text = null, + streamUris = listOf("content://media/1", "content://media/2"), + streamBytes = streamBytes, + idPrefix = "main-multi", + ) + checkEq(enqueuedMulti, 2, "seq27 ACTION_SEND_MULTIPLE enqueues all stream URIs") + checkEq(shareBridge.pendingCount(), 5, "seq27 ShareIntentBridge pendingCount == 5") + + // 1) Standalone editor mode (no SQLite workspace connected yet): + // - Read-only page guard leaves shares queued and drainStagedQueue never re-enqueues an already staged intent; + // - Partial failure (0-byte invalid image) marks ONLY actually committed share IDs consumed. + NativeBridge.nativeSetPageReadonly(seq27Handle, true) + checkEq( + NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_000L), + 0, + "seq27 read-only page leaves shares queued", + ) + checkEq(shareBridge.pendingCount(), 5, "seq27 pendingCount remains 5 when blocked by read-only") + + shareBridge.stageDescriptor( + ShareIntentBridge.PendingShareDescriptor( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Readonly Retry Once", + text = "https://affine.pro/readonly-once", + streamUris = emptyList(), + rawUris = emptyList(), + idPrefix = null, + ), + ) + val drainReadonly = { + shareBridge.drainStagedQueue( + isReady = { true }, + resolveStreamAsync = { _, cb -> cb(emptyMap()) }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_100L) }, + ) + } + drainReadonly() + drainReadonly() + checkEq(shareBridge.pendingCount(), 6, "seq27 retry while read-only never duplicate-enqueues staged intent") + + // Zero-byte attachment is rejected at the enqueue gate; valid PDF attachment is accepted and committed. + checkEq( + NativeBridge.nativeShareEnqueueBytes( + seq27Handle, + "main-empty-bad-img", + ShareIntentBridge.KIND_IMAGE, + "Empty", + "content://media/empty", + "image/png", + ByteArray(0), + ), + false, + "seq27 zero-byte image rejected at enqueue gate", + ) + val pdfSample = "%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n".toByteArray(Charsets.UTF_8) + checkEq( + shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Spec.pdf", + text = null, + streamUris = listOf("content://media/external/file/99"), + streamBytes = mapOf("content://media/external/file/99" to pdfSample), + idPrefix = "main-pdf", + ), + 1, + "seq27 PDF share enqueued as KIND_PDF", + ) + checkEq(shareBridge.pendingCount(), 7, "seq27 pendingCount == 7 before standalone live ingest") + + // Persistent ShareDiskInbox: stays on disk while read-only blocks ingest, removes ONLY after commit, + // and returns null when stream bytes fail to resolve (so ShareReceiverActivity surfaces failure Toast). + val diskInboxDir = java.io.File(seq27Dir, "share-inbox") + val diskInbox = ShareDiskInbox(diskInboxDir) + checkEq( + diskInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Unreadable", + text = null, + streamUris = listOf("content://media/unreadable"), + streamBytes = emptyMap(), + batchId = "bad-batch", + ), + null, + "seq27 unreadable attachment share returns null batch (triggers failure Toast)", + ) + checkEq( + ShareIntentBridge.isHistoryLaunch(0x00100000), + true, + "seq27 FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY detected and suppressed", + ) + val persistedBatch = diskInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "InboxDoc.pdf", + text = "https://affine.pro/from-disk-inbox", + streamUris = listOf("content://media/external/file/100"), + streamBytes = mapOf("content://media/external/file/100" to pdfSample), + batchId = "disk-batch-1", + createdAtMs = 1_795_900_000_150L, + ) + checkEq(persistedBatch != null && persistedBatch.items.size == 2, true, "seq27 disk inbox persisted URL + PDF batch") + // Standalone inbox created first so read-only retention & standalone live delivery run on + // `standaloneInbox`, while `diskInbox` (`disk-batch-1`) stays strictly untouched across + // `PendingBootstrap` and transient probe/mount failure until `DurableWorkspace(wsKey27)` mounts! + val standaloneInboxDir = java.io.File(seq27Dir, "standalone-share-inbox") + val standaloneInbox = ShareDiskInbox(standaloneInboxDir) + val standaloneBatch = standaloneInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "StandaloneOnce.pdf", + text = "https://affine.pro/standalone-once", + streamUris = listOf("content://media/external/file/101"), + streamBytes = mapOf("content://media/external/file/101" to pdfSample), + batchId = "standalone-batch-1", + createdAtMs = 1_795_900_000_155L, + ) + checkEq(standaloneBatch != null && standaloneBatch.items.size == 2, true, "seq27 standalone inbox persisted batch") + + val trueStandaloneOutcome = BootstrapOutcome( + imported = true, + canCreateDefaultWorkspace = true, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + val blockedDiskCommitted = shareBridge.drainDiskInbox( + inbox = standaloneInbox, + drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_160L) }, + ) + checkEq(blockedDiskCommitted, 0, "seq27 disk inbox drain while read-only commits 0") + checkEq( + standaloneInbox.listPendingBatches().size, + 1, + "seq27 standalone inbox manifest retained on disk when page is read-only", + ) + + NativeBridge.nativeSetPageReadonly(seq27Handle, false) + + // Pre-bootstrap, failed probe (`imported=false`), and failed workspace mount (`failedWorkspaceIds` + // non-empty) ALL map via `ShareIntentBridge.resolveDrainTarget` to `PendingBootstrap` so `diskInbox` + // (`disk-batch-1` + PDF attachment) is NEVER prematurely deleted or consumed into the demo doc! + val failedProbeOutcome = BootstrapOutcome( + imported = false, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + val failedMountOutcome = BootstrapOutcome( + imported = true, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = listOf("ws-share-27"), + preservedLocalWorkspaceRaw = "[\"ws-share-27\"]", + ) + val corruptLegacyOutcome = BootstrapOutcome( + imported = true, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = "corrupt-json", + ) + for ((label, target) in listOf( + "pre-bootstrap" to ShareIntentBridge.resolveDrainTarget(false, null), + "probe-failed" to ShareIntentBridge.resolveDrainTarget(true, failedProbeOutcome), + "mount-failed" to ShareIntentBridge.resolveDrainTarget(true, failedMountOutcome), + "corrupt-legacy" to ShareIntentBridge.resolveDrainTarget(true, corruptLegacyOutcome), + )) { + checkEq( + target, + ShareIntentBridge.ShareDrainTarget.PendingBootstrap, + "seq27 resolveDrainTarget($label) == PendingBootstrap", + ) + val drained = shareBridge.drainDiskInbox( + inbox = diskInbox, + drainTargetProvider = { target }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_180L) }, + ) + checkEq(drained, 0, "seq27 $label drains 0 items from diskInbox") + } + val persistedAttachmentNames = persistedBatch!!.items.mapNotNull { it.attachmentFileName } + checkEq( + diskInbox.listPendingBatches().size == 1 && + persistedAttachmentNames.isNotEmpty() && + persistedAttachmentNames.all { java.io.File(diskInboxDir, it).isFile } && + persistedBatch.items.none { NativeBridge.nativeShareIsConsumed(seq27Handle, it.id) }, + true, + "seq27 disk-batch-1 manifest & PDF attachment preserved untouched across pre-bootstrap and mount failure", + ) + + // Healthy standalone (`resolveDrainTarget(true, trueStandaloneOutcome)` == `EphemeralStandalone`): + // delivers into the live in-memory document AND deletes `standaloneInbox` immediately! + val standaloneCommitted = shareBridge.drainDiskInbox( + inbox = standaloneInbox, + drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_200L) }, + ) + checkEq(standaloneCommitted, 9, "seq27 standalone live ingest commits all 9 valid items (7 staged + 2 standalone inbox)") + checkEq(shareBridge.pendingCount(), 0, "seq27 queue clean after standalone live ingest") + checkEq( + NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, "", "standalone-batch-1-0"), + false, + "seq27 unmounted workspace reports nativeShareIsDurablyCommitted == false", + ) + checkEq( + standaloneInbox.listPendingBatches().isEmpty() && + (standaloneInboxDir.listFiles()?.none { it.isFile } ?: true), + true, + "seq27 EphemeralStandalone deletes disk batch immediately after live in-memory delivery", + ) + checkEq( + NativeBridge.nativeShareIsConsumed(seq27Handle, "standalone-batch-1-0") && + NativeBridge.nativeShareIsConsumed(seq27Handle, "standalone-batch-1-pdf-0"), + true, + "seq27 nativeShareIsConsumed confirms both standalone-inbox item IDs delivered in session", + ) + checkEq( + !NativeBridge.nativeShareIsConsumed(seq27Handle, "disk-batch-1-0") && + diskInbox.listPendingBatches().size == 1, + true, + "seq27 disk-batch-1 still untouched on disk waiting for DurableWorkspace mount recovery", + ) + + // Simulate 3 consecutive force-stop + cold restarts on the standalone APK (brand-new native + // host + brand-new ShareIntentBridge against the same standaloneInboxDir): zero replay! + repeat(3) { restartIdx -> + val coldHandle = NativeBridge.nativeCreateHost() + try { + val coldBridge = ShareIntentBridge { coldHandle } + val replayed = coldBridge.drainDiskInbox( + inbox = standaloneInbox, + drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(coldHandle, "", "", 1_795_900_000_300L + restartIdx) }, + ) + checkEq(replayed, 0, "seq27 standalone cold restart #${restartIdx + 1} replays 0 items") + val coldSnap = NativeBridge.nativeGetActivePageSnapshotJson(coldHandle) ?: "" + checkEq( + coldSnap.contains("standalone-once"), + false, + "seq27 standalone cold restart #${restartIdx + 1} snapshot has zero duplicate shared bookmark", + ) + } finally { + NativeBridge.nativeDestroyHost(coldHandle) + } + } + + // Selection `[6, 12)` (`"native"`) and focused paragraph `"Hello native world"` MUST remain 100% untouched! + checkEq( + NativeBridge.nativeGetUtf16Text(seq27Handle), + "Hello native world", + "seq27 focused paragraph text untouched (zero IME typing at caret)", + ) + checkEq(ime27.selectionStart(), 6, "seq27 selectionStart [6, 12) preserved across standalone share") + checkEq(ime27.selectionEnd(), 12, "seq27 selectionEnd [6, 12) preserved across standalone share") + + val sha256Digest = java.security.MessageDigest.getInstance("SHA-256").digest(png1x1) + val expectedBlobKey = java.util.Base64.getEncoder().encodeToString(sha256Digest) + .replace('+', '-') + .replace('/', '_') + val liveSnapJson = NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle) ?: "" + checkEq(liveSnapJson.contains("affine:bookmark"), true, "seq27 standalone snapshot has real affine:bookmark block") + checkEq(liveSnapJson.contains("https://affine.pro/shared"), true, "seq27 standalone snapshot has shared URL") + checkEq(liveSnapJson.contains("SHAREDTEXT"), true, "seq27 standalone snapshot has shared quote text") + checkEq(liveSnapJson.contains("affine:image"), true, "seq27 standalone snapshot has real affine:image block") + checkEq(liveSnapJson.contains(expectedBlobKey), true, "seq27 standalone snapshot references 44-char SHA-256 blob key") + checkEq(liveSnapJson.contains("content://media"), false, "seq27 standalone snapshot never inserts raw content:// URI text") + + // 2) Production SQLite workspace mode (`ws-share-27`): + // - Must commit strictly to SQLite target doc (`share-doc-...` or explicit `doc-target-b`) WITHOUT + // modifying open writable document A (`snapOpenDocABefore`) or being blocked by an unrelated read-only page. + val boot27 = AndroidBootstrapCoordinator( + handleProvider = { seq27Handle }, + filesDirProvider = { seq27Dir.absolutePath }, + ) + val out27 = boot27.completeWithProbePayload( + """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-share-27\"]"}}""", + ) + val wsKey27 = out27.connectedWorkspaceKeys.single() + val snapOpenDocABefore = NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle) ?: "" + + // Now that SQLite workspace `wsKey27` is mounted (`out27.isComplete == true`), `resolveDrainTarget` + // maps to `DurableWorkspace(wsKey27)`, committing `disk-batch-1` into SQLite `share_ingest_receipts` + // and ONLY THEN removing the disk files! + checkEq( + ShareIntentBridge.resolveDrainTarget(true, out27), + ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27), + "seq27 resolveDrainTarget(out27) == DurableWorkspace(wsKey27)", + ) + val diskMountedCommitted = shareBridge.drainDiskInbox( + inbox = diskInbox, + drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, out27) }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_000_500L) }, + ) + checkEq(diskMountedCommitted, 2, "seq27 mounted SQLite workspace commits retained disk-batch-1 (URL + PDF)") + checkEq( + NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, wsKey27, "disk-batch-1-0") && + NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, wsKey27, "disk-batch-1-pdf-0"), + true, + "seq27 nativeShareIsDurablyCommitted confirms SQLite share_ingest_receipts rows", + ) + checkEq( + diskInbox.listPendingBatches().isEmpty(), + true, + "seq27 disk inbox manifest & attachments deleted ONLY after durable SQLite receipt", + ) + + // Partial failure stats for ACTION_SEND_MULTIPLE (1 valid image + 1 unreadable URI). + val partialRes = diskInbox.writeBatchWithStats( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/png", + subject = "Partial Batch", + text = null, + streamUris = listOf("content://media/1", "content://media/unreadable"), + streamBytes = mapOf("content://media/1" to png1x1), + batchId = "partial-batch", + createdAtMs = 1_795_900_000_600L, + ) + checkEq( + partialRes.batch != null && partialRes.batch.items.size == 1 && partialRes.skippedCount == 1, + true, + "seq27 ACTION_SEND_MULTIPLE partial failure reports 1 persisted + 1 skipped (for Toast)", + ) + diskInbox.removeCommittedBatch(partialRes.batch!!) + + // Writer cap at MAX_BATCH_ITEMS (256): 260 valid images -> 256 persisted + 4 skipped, readable back cleanly. + val capUris = (0 until 260).map { "content://media/cap/$it.png" } + val capBytes = capUris.associateWith { png1x1 } + val capRes = diskInbox.writeBatchWithStats( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/png", + subject = "Cap 256 Batch", + text = null, + streamUris = capUris, + streamBytes = capBytes, + batchId = "cap-256-batch", + createdAtMs = 1_795_900_000_650L, + ) + checkEq( + capRes.batch != null && capRes.batch.items.size == 256 && capRes.skippedCount == 4, + true, + "seq27 writer enforces MAX_BATCH_ITEMS=256 and reports 4 skipped items", + ) + val decodedCap = diskInbox.listPendingBatches() + checkEq( + decodedCap.size == 1 && decodedCap.single().items.size == 256, + true, + "seq27 reader decodes full 256-item capped batch without rejection", + ) + diskInbox.removeCommittedBatch(decodedCap.single()) + + // Corrupt or >256 .manifest handling must quarantine BOTH `.manifest` and matching `-att-*.bin` into invalid/ (never silently deleting attachments). + val orphanManifest = java.io.File(diskInboxDir, "corrupt-orphan.manifest") + val orphanAtt = java.io.File(diskInboxDir, "corrupt-orphan-att-0.bin") + orphanManifest.writeBytes(byteArrayOf(0x00, 0x01, 0x02)) + orphanAtt.writeBytes(png1x1) + val overcapManifest = java.io.File(diskInboxDir, "overcap-257.manifest") + val overcapAtt = java.io.File(diskInboxDir, "overcap-257-att-0.bin") + java.io.DataOutputStream(java.io.FileOutputStream(overcapManifest)).use { out -> + out.writeInt(0x41465348) // "AFSH" + out.writeInt(1) + out.writeUTF("overcap-257") + out.writeLong(1_795_900_000_680L) + out.writeInt(257) + } + overcapAtt.writeBytes(png1x1) + checkEq(diskInbox.listPendingBatches().isEmpty(), true, "seq27 corrupt and >256 manifests excluded from pending list") + checkEq( + !orphanManifest.exists() && !orphanAtt.exists() && + java.io.File(diskInbox.invalidDir, "corrupt-orphan.manifest").isFile && + java.io.File(diskInbox.invalidDir, "corrupt-orphan-att-0.bin").isFile && + java.io.File(diskInbox.invalidDir, "overcap-257.manifest").isFile && + java.io.File(diskInbox.invalidDir, "overcap-257-att-0.bin").isFile, + true, + "seq27 corrupt and >256 manifests + attachments quarantined into share-inbox/invalid/", + ) + + // Missing attachment file referenced by a valid manifest must be quarantined into invalid/ (never treated as committed). + val missingAttBatch = diskInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Missing Att", + text = null, + streamUris = listOf("content://media/1"), + streamBytes = mapOf("content://media/1" to png1x1), + batchId = "missing-att-batch", + createdAtMs = 1_795_900_000_700L, + )!! + java.io.File(diskInboxDir, missingAttBatch.items.single().attachmentFileName!!).delete() + val quarantinedIds = mutableListOf() + shareBridge.drainDiskInbox( + inbox = diskInbox, + drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27) }, + isReady = { true }, + ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_000_750L) }, + onBatchQuarantined = { quarantinedIds.add(it) }, + ) + checkEq(quarantinedIds, listOf("missing-att-batch"), "seq27 missing attachment triggers quarantine callback") + checkEq( + java.io.File(diskInbox.invalidDir, "missing-att-batch.manifest").isFile && + diskInbox.listPendingBatches().isEmpty(), + true, + "seq27 missing attachment batch moved into share-inbox/invalid/", + ) + + // Repeated failed ingest attempts (>= 3) quarantine the batch into invalid/ instead of looping infinitely. + val retryFailBatch = diskInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Failing Ingest", + text = "https://affine.pro/will-fail-3x", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "retry-fail-batch", + createdAtMs = 1_795_900_000_800L, + )!! + quarantinedIds.clear() + repeat(ShareDiskInbox.MAX_INGEST_ATTEMPTS) { + shareBridge.drainDiskInbox( + inbox = diskInbox, + drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27) }, + isReady = { true }, + ingestNative = { 0 }, // Simulate failed ingest with no SQLite commit + onBatchQuarantined = { quarantinedIds.add(it) }, + ) + } + checkEq(quarantinedIds, listOf(retryFailBatch.batchId), "seq27 3 failed attempts quarantine batch into invalid/") + checkEq( + java.io.File(diskInbox.invalidDir, "${retryFailBatch.batchId}.manifest").isFile && + diskInbox.listPendingBatches().isEmpty(), + true, + "seq27 quarantined retry-fail batch resides in invalid/ with clean inbox", + ) + // Clear any unconsumed item from simulated 0-return ingest so subsequent checks start clean. + NativeBridge.nativeShareDrainJson(seq27Handle) + + checkEq( + shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "SQLite Share", + text = "https://affine.pro/sqlite-only", + streamUris = listOf("content://media/external/images/media/42"), + streamBytes = streamBytes, + idPrefix = "sql-send", + ), + 2, + "seq27 enqueue SQLite default-route share", + ) + val sqlDefaultIngested = NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_001_000L) + checkEq(sqlDefaultIngested, 2, "seq27 SQLite default-route commits both items") + checkEq( + NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle), + snapOpenDocABefore, + "seq27 default SQLite route NEVER double-writes into open writable document A", + ) + + checkEq( + shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Target B", + text = "https://affine.pro/only-in-doc-b", + streamUris = emptyList(), + idPrefix = "sql-doc-b", + ), + 1, + "seq27 enqueue explicit target doc B share", + ) + checkEq( + NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "doc-target-b", 1_795_900_002_000L), + 1, + "seq27 explicit target doc B committed", + ) + checkEq( + NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle), + snapOpenDocABefore, + "seq27 explicit target doc B leaves open writable document A 100% unchanged", + ) + checkEq(ime27.selectionStart(), 6, "seq27 open document A selectionStart [6, 12) untouched") + checkEq(ime27.selectionEnd(), 12, "seq27 open document A selectionEnd [6, 12) untouched") + + // 3) Interleaved consecutive ACTION_SEND image intents (`interleave-a` in flight when `interleave-b` arrives): + // Both must resolve, commit, and survive workspace reopen with exact count == 1 each. + var capturedResolveA: ((Map) -> Unit)? = null + var capturedResolveB: ((Map) -> Unit)? = null + val runInterleavedDrain = { + shareBridge.drainStagedQueue( + isReady = { true }, + resolveStreamAsync = { desc, onResolved -> + if (desc.idPrefix == "interleave-a") { + capturedResolveA = onResolved + } else { + capturedResolveB = onResolved + } + }, + ingestNative = { + NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_005_000L) + }, + ) + } + shareBridge.stageDescriptor( + ShareIntentBridge.PendingShareDescriptor( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Interleave A", + text = null, + streamUris = listOf("content://media/1"), + rawUris = emptyList(), + idPrefix = "interleave-a", + ), + ) + runInterleavedDrain() + checkEq(shareBridge.isResolveInFlight(), true, "seq27 interleave-a stream read is in flight") + checkEq(capturedResolveA != null, true, "seq27 interleave-a resolver captured") + + // Arrive via onNewIntent while interleave-a is still reading bytes on background thread! + shareBridge.stageDescriptor( + ShareIntentBridge.PendingShareDescriptor( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Interleave B", + text = null, + streamUris = listOf("content://media/2"), + rawUris = emptyList(), + idPrefix = "interleave-b", + ), + ) + runInterleavedDrain() + checkEq(shareBridge.stagedIntentCount(), 1, "seq27 interleave-b queued without overwriting interleave-a") + checkEq(capturedResolveB == null, true, "seq27 interleave-b waits until interleave-a finishes") + + capturedResolveA!!.invoke(streamBytes) + checkEq(capturedResolveB != null, true, "seq27 completing interleave-a automatically launches interleave-b") + capturedResolveB!!.invoke(streamBytes) + checkEq(shareBridge.isResolveInFlight(), false, "seq27 interleaved queue fully idle after both complete") + checkEq(shareBridge.stagedIntentCount(), 0, "seq27 zero staged intents left") + checkEq(shareBridge.pendingCount(), 0, "seq27 zero native share_queue items left") + + // Close and reopen SQLite workspace: verify all SQLite docs (`sql-send`, `doc-target-b`, `interleave-a`, `interleave-b`) & SHA-256 blob! + checkEq(NativeBridge.nativeStorageClose(seq27Handle, wsKey27), true, "seq27 close SQLite workspace") + val reopenedKey27 = NativeBridge.nativeConnectWorkspace(seq27Handle, seq27Dir.absolutePath, "local", "ws-share-27") + checkEq(reopenedKey27, wsKey27, "seq27 reopen SQLite workspace") + checkEq( + !NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-sql-send-0").isNullOrEmpty(), + true, + "seq27 SQLite persisted share-doc-sql-send-0 across reopen", + ) + checkEq( + !NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "doc-target-b").isNullOrEmpty(), + true, + "seq27 SQLite persisted explicit doc-target-b across reopen", + ) + checkEq( + !NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-interleave-a-img-0").isNullOrEmpty(), + true, + "seq27 SQLite persisted interleaved intent A across reopen", + ) + checkEq( + !NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-interleave-b-img-0").isNullOrEmpty(), + true, + "seq27 SQLite persisted interleaved intent B across reopen", + ) + val persistedBlobB64 = NativeBridge.nativeStorageGetBlobB64(seq27Handle, wsKey27, expectedBlobKey) + checkEq( + persistedBlobB64, + java.util.Base64.getEncoder().encodeToString(png1x1), + "seq27 SQLite persisted exact SHA-256 image bytes in blobs table across reopen", + ) + + val dupEnqueued = shareBridge.enqueueParsedPayloads( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "SQLite Share", + text = "https://affine.pro/sqlite-only", + streamUris = listOf("content://media/external/images/media/42"), + streamBytes = streamBytes, + idPrefix = "sql-send", + ) + checkEq(dupEnqueued, 0, "seq27 duplicate share IDs rejected idempotently after ingest") + } finally { + NativeBridge.nativeDestroyHost(seq27Handle) + seq27Dir.deleteRecursively() + } + + // Sequence 28: 0.27.5 https://localhost same-signature upgrade + rollback writeback drill. + val seq28Handle = NativeBridge.nativeCreateHost() + val seq28Dir = java.nio.file.Files.createTempDirectory("affine-0275-drill-").toFile() + try { + val probePayload = """ + { + "origin": "https://localhost", + "length": 4, + "keys": ["affine-local-workspace", "theme", "last_workspace_id", "capacitor_noise"], + "entries": { + "affine-local-workspace": "[\"ws-0275-a\"]", + "theme": "dark", + "last_workspace_id": "ws-0275-a" + } + } + """.trimIndent() + val coordinator28 = AndroidBootstrapCoordinator( + handleProvider = { seq28Handle }, + filesDirProvider = { seq28Dir.absolutePath }, + ) + val outcome = coordinator28.completeWithProbePayload(probePayload) + checkEq(outcome.imported, true, "seq28 0.27.5 probe imported") + checkEq(outcome.connectedWorkspaceKeys.size, 1, "seq28 allowlisted ws-0275-a mounted in place") + val writebackJson = NativeBridge.nativePlanLegacyLocalStorageWriteBack(seq28Handle) ?: "" + checkEq(writebackJson.contains("ws-0275-a"), true, "seq28 rollback writeback preserves ws-0275-a") + checkEq(writebackJson.contains("capacitor_noise"), false, "seq28 rollback writeback never deletes noise key") + } finally { + NativeBridge.nativeDestroyHost(seq28Handle) + seq28Dir.deleteRecursively() + } + + // Sequence 29: Readonly page and incomplete runNative timeout never burn inbox attempts. + val seq29Handle = NativeBridge.nativeCreateHost() + val seq29Dir = java.nio.file.Files.createTempDirectory("affine-share-guard-").toFile() + try { + NativeBridge.nativeLoadShowcaseDocument(seq29Handle) + val inbox29Dir = java.io.File(seq29Dir, ShareDiskInbox.DEFAULT_DIR_NAME) + val inbox29 = ShareDiskInbox(inbox29Dir) + val bridge29 = ShareIntentBridge { seq29Handle } + val batch29 = inbox29.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Guard Test", + text = "Should wait while readonly or timed out", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "seq29-batch-1", + ) + checkEq(batch29 != null, true, "seq29 persisted disk inbox batch") + val attemptsFile29 = java.io.File(inbox29Dir, "seq29-batch-1.attempts") + + // 1. Readonly page must skip drain without incrementing attempts or quarantining. + NativeBridge.nativeSetPageReadonly(seq29Handle, true) + checkEq(NativeBridge.nativeIsPageReadonly(seq29Handle), true, "seq29 page is readonly") + var quarantined29 = 0 + val drainedReadonly = bridge29.drainDiskInbox( + inbox = inbox29, + drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace("ws-guard") }, + isReady = { true }, + ingestNative = { 0 }, + onBatchQuarantined = { quarantined29 += 1 }, + ) + checkEq(drainedReadonly, 0, "seq29 readonly page skips share ingest") + checkEq(quarantined29, 0, "seq29 readonly page does not quarantine batch") + checkEq(attemptsFile29.exists(), false, "seq29 readonly page keeps attempts == 0") + checkEq(inbox29.listPendingBatches().size, 1, "seq29 readonly page retains pending batch") + + // 2. Timed-out / aborted runNative (returns before block finishes) must not burn attempts. + NativeBridge.nativeSetPageReadonly(seq29Handle, false) + checkEq(NativeBridge.nativeIsPageReadonly(seq29Handle), false, "seq29 page restored writable") + val drainedTimeout = bridge29.drainDiskInbox( + inbox = inbox29, + drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace("ws-guard") }, + isReady = { true }, + ingestNative = { 0 }, + onBatchQuarantined = { quarantined29 += 1 }, + runNative = { _ -> /* simulate 5s CountDownLatch timeout before main-thread completion */ }, + ) + checkEq(drainedTimeout, 0, "seq29 timed-out runNative returns 0") + checkEq(quarantined29, 0, "seq29 timed-out runNative does not quarantine batch") + checkEq(attemptsFile29.exists(), false, "seq29 timed-out runNative keeps attempts == 0") + checkEq(inbox29.listPendingBatches().size, 1, "seq29 timed-out runNative retains pending batch") + + // 3. ShareDiskInbox enforces MAX_PENDING_BATCHES cap against unbounded disk growth. + val capInbox = ShareDiskInbox(java.io.File(seq29Dir, "cap-inbox")) + for (i in 0 until ShareDiskInbox.MAX_PENDING_BATCHES) { + val b = capInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Cap $i", + text = "item $i", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "cap-batch-$i", + ) + checkEq(b != null, true, "seq29 cap batch $i accepted") + } + val overflow = capInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Overflow", + text = "overflow", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "cap-batch-overflow", + ) + checkEq(overflow == null, true, "seq29 inbox rejects batch beyond MAX_PENDING_BATCHES") + } finally { + NativeBridge.nativeDestroyHost(seq29Handle) + seq29Dir.deleteRecursively() + } + + // Sequence 30: Exact UTF-8 manifest byte accounting (3-byte CJK near 128 MiB cap) + bounded invalid/ quarantine. + val seq30Dir = java.nio.file.Files.createTempDirectory("affine-share-utf8-cap-").toFile() + try { + val inbox30Dir = java.io.File(seq30Dir, ShareDiskInbox.DEFAULT_DIR_NAME) + val inbox30 = ShareDiskInbox(inbox30Dir) + inbox30Dir.mkdirs() + + // Seed a valid manifested pending batch occupying MAX_TOTAL_INBOX_BYTES - 24 KiB so remaining budget is 24 KiB. + val prefillBatch = inbox30.writeBatch( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Prefill", + text = null, + streamUris = listOf("content://provider/prefill.pdf"), + streamBytes = mapOf("content://provider/prefill.pdf" to byteArrayOf(0x25, 0x50, 0x44, 0x46)), + batchId = "prefill", + )!! + val prefillManifest = java.io.File(inbox30Dir, "prefill.manifest") + val prefillFile = java.io.File(inbox30Dir, "prefill-att-0.bin") + java.io.RandomAccessFile(prefillFile, "rw").use { raf -> + raf.setLength(ShareDiskInbox.MAX_TOTAL_INBOX_BYTES - 24L * 1024L - prefillManifest.length()) + } + + // 10_000 CJK chars = 10_000 UTF-16 code units (< 24 KiB if miscounted by String.length), + // but 30_000 UTF-8 bytes (> 24 KiB remaining budget) -> MUST be rejected while prefill stays intact! + val cjkOverflow = "中".repeat(10_000) + val rejectedCjk = inbox30.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "CJK Cap Check", + text = cjkOverflow, + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "seq30-cjk-overflow", + ) + checkEq( + rejectedCjk, + null, + "seq30 multi-byte UTF-8 CJK manifest exceeding 128 MiB cap is rejected before write", + ) + checkEq( + prefillManifest.isFile && prefillFile.isFile, + true, + "seq30 manifested pending batch stays intact under quota rejection", + ) + checkEq( + inbox30Dir.walkTopDown().filter { it.isFile }.sumOf { it.length() } <= ShareDiskInbox.MAX_TOTAL_INBOX_BYTES, + true, + "seq30 total recursive inbox bytes stay <= MAX_TOTAL_INBOX_BYTES", + ) + + // Remove prefill batch and verify >64 KiB CJK plain text (25_000 chars = 75_000 UTF-8 bytes) round-trips cleanly! + inbox30.removeCommittedBatch(prefillBatch) + val cjkLarge = "测".repeat(25_000) + val largeAccepted = inbox30.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Large CJK", + text = cjkLarge, + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "seq30-cjk-large", + ) + checkEq(largeAccepted != null, true, "seq30 >64 KiB CJK share manifest accepted without UTFDataFormatException") + val decoded30 = inbox30.listPendingBatches() + checkEq(decoded30.size, 1, "seq30 decoded 1 pending batch") + checkEq(decoded30[0].items[0].content, cjkLarge, "seq30 >64 KiB CJK text round-trips losslessly") + + // Quarantine files inside invalid/ count toward total inbox bytes and are bounded to 80 MiB + // (>= 64 MiB single-attachment cap so >16 MiB quarantined batches survive intact without self-eviction). + val invalidDir30 = inbox30.invalidDir + invalidDir30.mkdirs() + val largeFailedBatch = inbox30.writeBatch( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Large Quarantined PDF", + text = null, + streamUris = listOf("content://provider/large.pdf"), + streamBytes = mapOf("content://provider/large.pdf" to ByteArray(16) { 0x25 }), + batchId = "seq30-large-quarantine", + )!! + java.io.RandomAccessFile(java.io.File(inbox30Dir, "seq30-large-quarantine-att-0.bin"), "rw").use { + it.setLength(24L * 1024L * 1024L) + } + val pending30b = inbox30.listPendingBatches().first { it.batchId == largeFailedBatch.batchId } + inbox30.quarantineBatch(pending30b) + checkEq( + java.io.File(invalidDir30, "seq30-large-quarantine.manifest").isFile && + java.io.File(invalidDir30, "seq30-large-quarantine-att-0.bin").isFile, + true, + "seq30 >16 MiB quarantined batch retains both manifest and attachment in invalid/", + ) + + val oldQuarantine = java.io.File(invalidDir30, "old-corrupt.bin") + java.io.RandomAccessFile(oldQuarantine, "rw").use { it.setLength(50L * 1024L * 1024L) } + oldQuarantine.setLastModified(1_000L) + val newerQuarantine = java.io.File(invalidDir30, "newer-corrupt.bin") + java.io.RandomAccessFile(newerQuarantine, "rw").use { it.setLength(20L * 1024L * 1024L) } + newerQuarantine.setLastModified(2_000L) + java.io.File(invalidDir30, "seq30-large-quarantine.manifest").setLastModified(3_000L) + java.io.File(invalidDir30, "seq30-large-quarantine-att-0.bin").setLastModified(3_000L) + inbox30.quarantineBatch(decoded30[0]) + val invalidBytesAfter = invalidDir30.walkTopDown().filter { it.isFile }.sumOf { it.length() } + checkEq( + invalidBytesAfter <= ShareDiskInbox.MAX_INVALID_QUARANTINE_BYTES, + true, + "seq30 invalid/ quarantine directory pruned within MAX_INVALID_QUARANTINE_BYTES", + ) + checkEq(oldQuarantine.exists(), false, "seq30 oldest quarantined file pruned first") + } finally { + seq30Dir.deleteRecursively() + } + + // Sequence 31: Concurrent ShareDiskInbox instances racing on MAX_PENDING_BATCHES (64th slot) + // and MAX_TOTAL_INBOX_BYTES (128 MiB budget) must strictly serialize and accept only 1 winner. + val seq31Dir = java.nio.file.Files.createTempDirectory("affine-share-inbox-seq31-").toFile() + try { + // Part A: Race two separate ShareDiskInbox instances for the 64th pending batch slot. + val batchRaceDir = java.io.File(seq31Dir, "batch-cap-race") + val seedInbox = ShareDiskInbox(batchRaceDir) + for (i in 1 until ShareDiskInbox.MAX_PENDING_BATCHES) { + val seeded = seedInbox.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Seed $i", + text = "seed-$i", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "seed-$i", + createdAtMs = i.toLong(), + ) + checkEq(seeded != null, true, "seq31 seeded batch $i accepted") + } + checkEq( + seedInbox.listPendingBatches().size, + ShareDiskInbox.MAX_PENDING_BATCHES - 1, + "seq31 63 pending batches ready before final-slot race", + ) + + repeat(16) { round -> + val readyLatch = java.util.concurrent.CountDownLatch(2) + val goLatch = java.util.concurrent.CountDownLatch(1) + val results = java.util.concurrent.ConcurrentLinkedQueue() + val t1 = Thread { + val writerA = ShareDiskInbox(batchRaceDir) + readyLatch.countDown() + goLatch.await() + val res = writerA.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Contender A $round", + text = "payload-a-$round", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "race-$round-a", + createdAtMs = 10_000L + round, + ) + results.add(res != null) + } + val t2 = Thread { + val writerB = ShareDiskInbox(batchRaceDir) + readyLatch.countDown() + goLatch.await() + val res = writerB.writeBatch( + action = "android.intent.action.SEND", + mimeType = "text/plain", + subject = "Contender B $round", + text = "payload-b-$round", + streamUris = emptyList(), + streamBytes = emptyMap(), + batchId = "race-$round-b", + createdAtMs = 10_000L + round, + ) + results.add(res != null) + } + t1.start() + t2.start() + readyLatch.await() + goLatch.countDown() + t1.join() + t2.join() + + val acceptedCount = results.count { it } + checkEq(acceptedCount, 1, "seq31 round $round exactly 1 contender wins the 64th slot") + val pendingNow = seedInbox.listPendingBatches() + checkEq( + pendingNow.size, + ShareDiskInbox.MAX_PENDING_BATCHES, + "seq31 round $round pending count never exceeds MAX_PENDING_BATCHES", + ) + val winner = pendingNow.first { it.batchId.startsWith("race-$round-") } + seedInbox.removeCommittedBatch(winner) + } + + // Part B: Race two separate ShareDiskInbox instances for the last ~64 KiB under MAX_TOTAL_INBOX_BYTES. + val byteRaceDir = java.io.File(seq31Dir, "byte-cap-race") + byteRaceDir.mkdirs() + ShareDiskInbox(byteRaceDir).writeBatch( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Prefill Race", + text = null, + streamUris = listOf("content://provider/prefill-race.pdf"), + streamBytes = mapOf("content://provider/prefill-race.pdf" to byteArrayOf(0x25, 0x50, 0x44, 0x46)), + batchId = "prefill", + )!! + val prefillRaceManifest = java.io.File(byteRaceDir, "prefill.manifest") + val prefill = java.io.File(byteRaceDir, "prefill-att-0.bin") + java.io.RandomAccessFile(prefill, "rw").use { raf -> + raf.setLength(ShareDiskInbox.MAX_TOTAL_INBOX_BYTES - 64L * 1024L - prefillRaceManifest.length()) + } + val payload40k = ByteArray(40 * 1024) { (it and 0xFF).toByte() } + val readyBytes = java.util.concurrent.CountDownLatch(2) + val goBytes = java.util.concurrent.CountDownLatch(1) + val byteResults = java.util.concurrent.ConcurrentLinkedQueue() + val b1 = Thread { + val writerA = ShareDiskInbox(byteRaceDir) + readyBytes.countDown() + goBytes.await() + val res = writerA.writeBatch( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Byte Race A", + text = null, + streamUris = listOf("content://provider/a.png"), + streamBytes = mapOf("content://provider/a.png" to payload40k), + batchId = "byte-race-a", + ) + byteResults.add(res != null) + } + val b2 = Thread { + val writerB = ShareDiskInbox(byteRaceDir) + readyBytes.countDown() + goBytes.await() + val res = writerB.writeBatch( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Byte Race B", + text = null, + streamUris = listOf("content://provider/b.png"), + streamBytes = mapOf("content://provider/b.png" to payload40k), + batchId = "byte-race-b", + ) + byteResults.add(res != null) + } + b1.start() + b2.start() + readyBytes.await() + goBytes.countDown() + b1.join() + b2.join() + + checkEq(byteResults.count { it }, 1, "seq31 concurrent 40 KiB attachments accept strictly 1 under 64 KiB budget") + val finalBytes = byteRaceDir.walkTopDown().filter { it.isFile }.sumOf { it.length() } + checkEq( + finalBytes <= ShareDiskInbox.MAX_TOTAL_INBOX_BYTES, + true, + "seq31 concurrent total recursive inbox bytes never exceed MAX_TOTAL_INBOX_BYTES", + ) + } finally { + seq31Dir.deleteRecursively() + } + + // Sequence 32: Lock-free hasPendingManifests(), stale unmanifested orphan sweep before 128 MiB + // quota accounting, and explicit ShareRejectReason Toast classification. + val seq32Dir = java.nio.file.Files.createTempDirectory("affine-share-inbox-seq32-").toFile() + try { + val inbox32Dir = java.io.File(seq32Dir, ShareDiskInbox.DEFAULT_DIR_NAME) + val inbox32 = ShareDiskInbox(inbox32Dir) + inbox32Dir.mkdirs() + checkEq(inbox32.hasPendingManifests(), false, "seq32 empty inbox hasPendingManifests is false") + + // Leave 100 MiB crashed attachment + .tmp residue without a .manifest (older than grace window). + val staleOrphanBin = java.io.File(inbox32Dir, "crashed-batch-att-0.bin") + java.io.RandomAccessFile(staleOrphanBin, "rw").use { raf -> + raf.setLength(100L * 1024L * 1024L) + } + staleOrphanBin.setLastModified(1_000L) + val staleManifestTmp = java.io.File(inbox32Dir, "crashed-batch.manifest.tmp") + staleManifestTmp.writeBytes(byteArrayOf(1, 2, 3, 4)) + staleManifestTmp.setLastModified(1_000L) + + // A new 40 MiB PDF share would exceed 128 MiB if the 100 MiB orphan were not swept first. + val pdf40m = ByteArray(40 * 1024 * 1024) + pdf40m[0] = 0x25 // '%' + pdf40m[1] = 0x50 // 'P' + pdf40m[2] = 0x44 // 'D' + pdf40m[3] = 0x46 // 'F' + val recoveredWrite = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Recovered Share", + text = null, + streamUris = listOf("content://provider/spec.pdf"), + streamBytes = mapOf("content://provider/spec.pdf" to pdf40m), + batchId = "seq32-recovered", + createdAtMs = 120_000L, + ) + checkEq(recoveredWrite.batch != null, true, "seq32 stale 100 MiB orphan swept before 128 MiB quota check") + checkEq( + recoveredWrite.rejectReason, + ShareDiskInbox.ShareRejectReason.NONE, + "seq32 accepted batch reports ShareRejectReason.NONE", + ) + checkEq(staleOrphanBin.exists(), false, "seq32 stale unmanifested -att-0.bin removed") + checkEq(staleManifestTmp.exists(), false, "seq32 stale .manifest.tmp removed") + checkEq(inbox32.hasPendingManifests(), true, "seq32 lock-free hasPendingManifests is true after commit") + + // Verify ShareRejectReason classification: unsupported MIME, oversize (>64 MiB), and quota exceeded (>128 MiB). + val unsupportedRes = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/x-msdownload", + subject = "Unsupported", + text = null, + streamUris = listOf("content://provider/app.exe"), + streamBytes = mapOf("content://provider/app.exe" to byteArrayOf(1, 2, 3)), + batchId = "seq32-unsupported", + createdAtMs = 121_000L, + ) + checkEq(unsupportedRes.batch, null, "seq32 unsupported payload rejected") + checkEq( + unsupportedRes.rejectReason, + ShareDiskInbox.ShareRejectReason.UNSUPPORTED_PAYLOAD, + "seq32 unsupported MIME classified as UNSUPPORTED_PAYLOAD", + ) + + val oversizeRes = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Oversize", + text = null, + streamUris = emptyList(), + streamBytes = emptyMap(), + preOversizeCount = 1, + batchId = "seq32-oversize", + createdAtMs = 122_000L, + ) + checkEq(oversizeRes.batch, null, "seq32 oversize payload rejected") + checkEq( + oversizeRes.rejectReason, + ShareDiskInbox.ShareRejectReason.OVERSIZE_ITEM, + "seq32 >64 MiB stream classified as OVERSIZE_ITEM", + ) + + // Fill another 60 MiB + 40 MiB -> second 60 MiB exceeds 128 MiB (40 + 60 + 60 > 128) -> QUOTA_EXCEEDED! + val pdf60m = ByteArray(60 * 1024 * 1024) + val secondAccepted = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Second PDF", + text = null, + streamUris = listOf("content://provider/second.pdf"), + streamBytes = mapOf("content://provider/second.pdf" to pdf60m), + batchId = "seq32-second", + createdAtMs = 123_000L, + ) + checkEq(secondAccepted.batch != null, true, "seq32 40 MiB + 60 MiB fits within 128 MiB inbox cap") + val quotaRes = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Quota Overflow", + text = null, + streamUris = listOf("content://provider/third.pdf"), + streamBytes = mapOf("content://provider/third.pdf" to pdf60m), + batchId = "seq32-quota", + createdAtMs = 124_000L, + ) + checkEq(quotaRes.batch, null, "seq32 third 60 MiB batch rejected at 128 MiB cap") + checkEq( + quotaRes.rejectReason, + ShareDiskInbox.ShareRejectReason.QUOTA_EXCEEDED, + "seq32 128 MiB cap overflow classified as QUOTA_EXCEEDED", + ) + // Fresh (<60s) crash orphan occupying 100 MiB with zero pending manifests must be reclaimed + // immediately under quota pressure without waiting for ORPHAN_SWEEP_AGE_MS. + val freshOrphanDir = java.io.File(seq32Dir, "fresh-orphan-inbox") + val freshInbox = ShareDiskInbox(freshOrphanDir) + freshOrphanDir.mkdirs() + val freshOrphanBin = java.io.File(freshOrphanDir, "just-crashed-att-0.bin") + java.io.RandomAccessFile(freshOrphanBin, "rw").use { raf -> + raf.setLength(100L * 1024L * 1024L) + } + freshOrphanBin.setLastModified(125_000L) + val freshRecovered = freshInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Immediate Reclaim", + text = null, + streamUris = listOf("content://provider/fresh.pdf"), + streamBytes = mapOf("content://provider/fresh.pdf" to pdf40m), + batchId = "seq32-fresh-recovered", + createdAtMs = 126_000L, + ) + checkEq(freshRecovered.batch != null, true, "seq32 fresh <60s orphan reclaimed under quota pressure when no manifests pending") + checkEq(freshOrphanBin.exists(), false, "seq32 fresh <60s orphan deleted during aggressive quota sweep") + + val unreadableRes = inbox32.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Unreadable", + text = null, + streamUris = emptyList(), + streamBytes = emptyMap(), + preUnavailableCount = 1, + batchId = "seq32-unreadable", + createdAtMs = 126_500L, + ) + checkEq(unreadableRes.batch, null, "seq32 unreadable stream rejected") + checkEq( + unreadableRes.rejectReason, + ShareDiskInbox.ShareRejectReason.STREAM_UNREADABLE, + "seq32 unreadable stream classified as STREAM_UNREADABLE", + ) + checkEq( + ShareReceiverActivity.toastMessageForFailure(ShareDiskInbox.ShareRejectReason.STREAM_UNREADABLE), + "Unable to read shared content", + "seq32 STREAM_UNREADABLE surfaces dedicated Toast copy", + ) + checkEq( + ShareReceiverActivity.toastMessageForFailure( + ShareDiskInbox.ShareRejectReason.QUOTA_EXCEEDED, + hasPendingManifests = false, + ).contains("open AFFiNE"), + false, + "seq32 QUOTA_EXCEEDED without pending manifests does not tell user to open AFFiNE", + ) + checkEq( + ShareReceiverActivity.toastMessageForFailure(ShareDiskInbox.ShareRejectReason.QUOTA_EXCEEDED) != + ShareReceiverActivity.toastMessageForFailure(ShareDiskInbox.ShareRejectReason.OVERSIZE_ITEM), + true, + "seq32 ShareReceiverActivity surfaces distinct Toast copy for quota vs oversize", + ) + + // Mixed share (1 valid URI + 1 unreadable URI) must count skipped == 1 (never double-counted as 2), + // AND aggressive quota sweep must still reclaim unmanifested <60s orphans even when a valid manifest exists. + val mixedDir = java.io.File(seq32Dir, "mixed-skip-inbox") + val mixedInbox = ShareDiskInbox(mixedDir) + val smallPng = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47) + val mixedFromReceiver = mixedInbox.writeBatchWithStats( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/*", + subject = "Mixed Receiver", + text = null, + streamUris = listOf("content://provider/good.png"), + streamBytes = mapOf("content://provider/good.png" to smallPng), + preUnavailableCount = 1, + batchId = "seq32-mixed-receiver", + createdAtMs = 127_000L, + ) + checkEq(mixedFromReceiver.batch?.items?.size, 1, "seq32 mixed receiver share imports 1 valid URI") + checkEq(mixedFromReceiver.skippedCount, 1, "seq32 mixed receiver share counts 1 unreadable URI once") + + val mixedDirect = mixedInbox.writeBatchWithStats( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/*", + subject = "Mixed Direct", + text = null, + streamUris = listOf("content://provider/good2.png", "content://provider/unreadable.png"), + streamBytes = mapOf("content://provider/good2.png" to smallPng), + batchId = "seq32-mixed-direct", + createdAtMs = 127_500L, + ) + checkEq(mixedDirect.batch?.items?.size, 1, "seq32 mixed direct share imports 1 valid URI") + checkEq(mixedDirect.skippedCount, 1, "seq32 mixed direct share counts 1 unreadable URI in streamUris") + + val cappedOnly = mixedInbox.writeBatchWithStats( + action = "android.intent.action.SEND_MULTIPLE", + mimeType = "image/*", + subject = "Capped Only", + text = null, + streamUris = emptyList(), + streamBytes = emptyMap(), + preCappedCount = 1, + batchId = "seq32-capped-only", + createdAtMs = 127_600L, + ) + checkEq( + cappedOnly.rejectReason, + ShareDiskInbox.ShareRejectReason.BATCH_LIMIT_EXCEEDED, + "seq32 excess >MAX_BATCH_ITEMS items classified as BATCH_LIMIT_EXCEEDED instead of STREAM_UNREADABLE", + ) + + // With 2 valid manifests now in mixedDir, add a 100 MiB <60s crash orphan and write a 40 MiB PDF: + // orphan must be swept while the 2 valid manifests stay intact! + val orphanAlongsideManifest = java.io.File(mixedDir, "crash-alongside-att-0.bin") + java.io.RandomAccessFile(orphanAlongsideManifest, "rw").use { it.setLength(100L * 1024L * 1024L) } + orphanAlongsideManifest.setLastModified(127_800L) + val alongsideAccepted = mixedInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Alongside Valid", + text = null, + streamUris = listOf("content://provider/alongside.pdf"), + streamBytes = mapOf("content://provider/alongside.pdf" to pdf40m), + batchId = "seq32-alongside", + createdAtMs = 128_000L, + ) + checkEq(alongsideAccepted.batch != null, true, "seq32 fresh orphan swept even when valid manifests exist") + checkEq(orphanAlongsideManifest.exists(), false, "seq32 unmanifested orphan deleted while valid manifests remain") + checkEq(mixedInbox.listPendingBatches().size, 3, "seq32 all 3 valid manifested batches preserved") + + // Batch ID itself containing `-att-` must keep its manifested attachment intact during orphan sweep. + val attInBatchId = mixedInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "image/png", + subject = "Dash Att Batch", + text = null, + streamUris = listOf("content://provider/dash.png"), + streamBytes = mapOf("content://provider/dash.png" to smallPng), + batchId = "seq32-note-att-valid", + createdAtMs = 128_500L, + ) + checkEq(attInBatchId.batch != null, true, "seq32 batchId containing -att- accepted") + val keptBytes = mixedInbox.readAttachmentBytes(attInBatchId.batch!!.items.single()) + checkEq(keptBytes?.size, smallPng.size, "seq32 attachment for batchId containing -att- survives sweep") + val afterSweep = mixedInbox.listPendingBatches(nowMs = 300_000L) + checkEq(afterSweep.size, 4, "seq32 all 4 batches including -att- batchId survive 60s+ sweep") + checkEq( + mixedInbox.readAttachmentBytes(afterSweep.last().items.single())?.size, + smallPng.size, + "seq32 attachment bytes for -att- batchId still readable after 60s+ sweep", + ) + + // Quarantine eviction under quota pressure (scoped in `run` to avoid name collisions and let + // large test buffers become eligible for GC immediately). + run { + // Case A: 80 MiB in invalid/ (oldest 50 MiB group + newer 30 MiB group) must yield to a + // legitimate 60 MiB share by deleting only the oldest complete quarantine group. + val qEvictDir = java.io.File(seq32Dir, "quarantine-evict") + val qEvictInbox = ShareDiskInbox(qEvictDir) + qEvictInbox.invalidDir.mkdirs() + val oldQManifest = java.io.File(qEvictInbox.invalidDir, "q-old.manifest") + val oldQAtt = java.io.File(qEvictInbox.invalidDir, "q-old-att-0.bin") + oldQManifest.writeBytes(ByteArray(128) { 0x11.toByte() }) + java.io.RandomAccessFile(oldQAtt, "rw").use { it.setLength(50L * 1024L * 1024L - 128L) } + oldQManifest.setLastModified(1_000L) + oldQAtt.setLastModified(1_000L) + val newQManifest = java.io.File(qEvictInbox.invalidDir, "q-new.manifest") + val newQAtt = java.io.File(qEvictInbox.invalidDir, "q-new-att-0.bin") + newQManifest.writeBytes(ByteArray(128) { 0x22.toByte() }) + java.io.RandomAccessFile(newQAtt, "rw").use { it.setLength(30L * 1024L * 1024L - 128L) } + newQManifest.setLastModified(2_000L) + newQAtt.setLastModified(2_000L) + + val qEvictPdf60m = ByteArray(60 * 1024 * 1024) + qEvictPdf60m[0] = 0x25 // '%' + qEvictPdf60m[1] = 0x50 // 'P' + qEvictPdf60m[2] = 0x44 // 'D' + qEvictPdf60m[3] = 0x46 // 'F' + val admitted60m = qEvictInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Large Valid Share", + text = null, + streamUris = listOf("content://provider/large60.pdf"), + streamBytes = mapOf("content://provider/large60.pdf" to qEvictPdf60m), + batchId = "seq32-large-60m", + createdAtMs = 301_000L, + ) + checkEq(admitted60m.batch != null, true, "seq32 60 MiB valid share admitted after evicting oldest quarantine group") + checkEq(admitted60m.rejectReason, ShareDiskInbox.ShareRejectReason.NONE, "seq32 60 MiB share rejectReason NONE") + checkEq(oldQManifest.exists() || oldQAtt.exists(), false, "seq32 oldest complete quarantine group evicted") + checkEq(newQManifest.isFile && newQAtt.isFile, true, "seq32 newer quarantine group preserved when oldest suffices") + checkEq( + qEvictDir.walkTopDown().filter { it.isFile }.sumOf { it.length() } <= ShareDiskInbox.MAX_TOTAL_INBOX_BYTES, + true, + "seq32 inbox total bytes remain <= 128 MiB after quarantine eviction", + ) + + // Case B: When valid pending batches (60 MiB + 20 MiB = 80 MiB) + 30 MiB quarantine cannot fit + // an incoming 60 MiB batch even if all quarantine were evicted (80 + 60 > 128), reject with + // QUOTA_EXCEEDED without deleting valid pending batches OR quarantine files. + val qEvictValid20m = ByteArray(20 * 1024 * 1024) + qEvictValid20m[0] = 0x25 // '%' + qEvictValid20m[1] = 0x50 // 'P' + qEvictValid20m[2] = 0x44 // 'D' + qEvictValid20m[3] = 0x46 // 'F' + val admitted20m = qEvictInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Second Valid Share", + text = null, + streamUris = listOf("content://provider/valid20.pdf"), + streamBytes = mapOf("content://provider/valid20.pdf" to qEvictValid20m), + batchId = "seq32-valid-20m", + createdAtMs = 302_000L, + ) + checkEq(admitted20m.batch != null, true, "seq32 second valid 20 MiB share fits under 128 MiB") + + val rejectedWhenInsufficient = qEvictInbox.writeBatchWithStats( + action = "android.intent.action.SEND", + mimeType = "application/pdf", + subject = "Impossible 60 MiB", + text = null, + streamUris = listOf("content://provider/impossible60.pdf"), + streamBytes = mapOf("content://provider/impossible60.pdf" to qEvictPdf60m), + batchId = "seq32-impossible-60m", + createdAtMs = 303_000L, + ) + checkEq(rejectedWhenInsufficient.batch, null, "seq32 60 MiB share rejected when valid pending batches leave < 60 MiB") + checkEq( + rejectedWhenInsufficient.rejectReason, + ShareDiskInbox.ShareRejectReason.QUOTA_EXCEEDED, + "seq32 impossible share returns QUOTA_EXCEEDED", + ) + checkEq(newQManifest.isFile && newQAtt.isFile, true, "seq32 quarantine untouched when eviction would not suffice") + checkEq(qEvictInbox.listPendingBatches().size, 2, "seq32 valid pending batches never touched on quota rejection") + } + } finally { + seq32Dir.deleteRecursively() + } + + // 33. Mobile shell root: Home 4-TabBar -> Page InputConnection CJK -> back -> Search + // InputConnection -> back unwind -> SQLite flush and cold reopen. + val shellBase = File(System.getProperty("java.io.tmpdir"), "affine-shell-${System.nanoTime()}") + try { + fun openShell(): Long { + val h = NativeBridge.nativeCreateShellHost("en-US", 1_764_000_000_000L, 480, false) + checkEq(h != 0L, true, "seq33 nativeCreateShellHost returned non-zero handle") + return h + } + fun shellTap(h: Long, id: Long, prefix: String) { + val json = NativeBridge.nativeShellAccessibilityJson(h) + ?: throw AssertionError("seq33 shell must publish an accessibility tree") + val num = "(-?[0-9.eE+-]+)" + val node = Regex( + "\"id\":\"(" + Regex.escape(prefix) + "[^\"]*)\".*?\"bounds\":\\{\"x\":$num,\"y\":$num,\"width\":$num,\"height\":$num\\}", + ).findAll(json) + .map { m -> m.groupValues.drop(2).map { it.toFloat() } } + .filter { it[2] > 0f && it[3] > 0f } + .minByOrNull { it[1] } + ?: throw AssertionError("seq33 shell node $prefix must have bounds") + val x = node[0] + node[2] / 2f + val y = node[1] + node[3] / 2f + NativeBridge.nativeOnTouchEvent(h, id, 0, x, y) + NativeBridge.nativeOnTouchEvent(h, id, 2, x, y) + NativeBridge.nativeOnFrameTick(h, id * 16_000_000L) + } + + val shell = openShell() + try { + val ic = AffineSurfaceView.createInputConnection({ shell }) + val ime = AffineImeController { shell } + NativeBridge.nativeOnFrameTick(shell, 1L) + checkEq(NativeBridge.nativeShellRoute(shell), 1, "seq33 shell launches on Home") + val a11yNodes = ShellAccessibilityNode.parse(NativeBridge.nativeShellAccessibilityJson(shell) ?: "") + val tabs = a11yNodes.filter { it.role == "tab" } + checkEq(tabs.size, 4, "seq33 accessibility publishes the 4 tabs") + checkEq(tabs.all { it.clickable && it.className == "android.widget.Button" }, true, "seq33 tabs are clickable buttons") + checkEq(a11yNodes.any { it.id.startsWith("mobile.home.doc.") && it.clickable }, true, "seq33 document rows are clickable") + val views = ShellAccessibilityViews() + views.update(a11yNodes) + val searchId = views.virtualId("mobile.tab.search") + ?: throw AssertionError("seq33 Search tab must have a virtual view ID") + checkEq(searchId > 0, true, "seq33 virtual view IDs are positive") + checkEq(views.focus(searchId), true, "seq33 Search tab takes accessibility focus") + checkEq(views.focusedVirtualId, searchId, "seq33 Search tab holds accessibility focus") + checkEq(views.focus(searchId), false, "seq33 focusing the focused node is a no-op") + checkEq(views.clearFocus(searchId), true, "seq33 Search tab clears accessibility focus") + checkEq(views.focusedVirtualId, -1, "seq33 no node holds accessibility focus") + val firstNode = a11yNodes.first() + val firstId = views.virtualId(firstNode.id) + views.focus(searchId) + views.update(a11yNodes.drop(1) + ShellAccessibilityNode("seq33.extra", "button", "Extra", 0f, 0f, 10f, 10f)) + checkEq(views.virtualId("mobile.tab.search"), searchId, "seq33 virtual view IDs survive removed and added nodes") + checkEq(views.virtualId(firstNode.id), null, "seq33 a removed node has no virtual view") + checkEq(views.focusedVirtualId, searchId, "seq33 focus stays on a node that remains") + views.update(a11yNodes) + checkEq(views.virtualId(firstNode.id), firstId, "seq33 a node that returns keeps its virtual view ID") + checkEq(views.virtualId("seq33.extra"), null, "seq33 the added node left again") + views.update(a11yNodes.filter { it.id != "mobile.tab.search" }) + checkEq(views.focusedVirtualId, -1, "seq33 focus on a node that left clears") + + // The last accessibility service stops while a node holds focus: the system clears the + // focus, and the host must send no event (the platform throws then). A service that + // starts again focuses and clears the same nodes with events. + var serviceOn = true + val events = mutableListOf>() + val guarded = ShellAccessibilityViews( + accessibilityEnabled = { serviceOn }, + sendEvent = { id, type -> + if (!serviceOn) throw IllegalStateException("Accessibility off. Did you forget to check that?") + events += id to type + }, + ) + guarded.update(a11yNodes) + val homeId = guarded.virtualId("mobile.tab.home") + ?: throw AssertionError("seq33 Home tab must have a virtual view ID") + val focusAction = AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS + val clearAction = AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS + val focusedEvent = AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED + val clearedEvent = AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED + // `(service runs, action, focus changes, focused node after, event sent)` + listOf( + listOf(true, focusAction, true, homeId, focusedEvent), + listOf(false, clearAction, true, -1, null), + listOf(false, clearAction, false, -1, null), + listOf(true, focusAction, true, homeId, focusedEvent), + listOf(true, clearAction, true, -1, clearedEvent), + ).forEachIndexed { step, row -> + serviceOn = row[0] as Boolean + events.clear() + val changed = guarded.performFocusAction(homeId, row[1] as Int) + checkEq(changed, row[2], "seq33 accessibility focus step $step changes the focus") + checkEq(guarded.focusedVirtualId, row[3], "seq33 accessibility focus step $step focused node") + checkEq(events.map { it.second }, listOfNotNull(row[4]), "seq33 accessibility focus step $step events") + } + serviceOn = false + events.clear() + guarded.announce(homeId, AccessibilityEvent.TYPE_VIEW_CLICKED) + checkEq(events.isEmpty(), true, "seq33 a click sends no event while accessibility is off") + checkEq(NativeBridge.nativeShellSetSystemDark(shell, true), true, "seq33 shell follows system dark") + checkEq(NativeBridge.nativeIsDarkTheme(shell), true, "seq33 shell turns dark") + checkEq(NativeBridge.nativeShellSetSystemDark(shell, false), true, "seq33 shell follows system light") + checkEq(NativeBridge.nativeIsDarkTheme(shell), false, "seq33 shell turns light") + shellTap(shell, 1, "mobile.home.doc.") + checkEq(NativeBridge.nativeShellRoute(shell), 5, "seq33 Home row opens the Page route") + shellTap(shell, 2, "mobile.page.block.") + val before = ime.readText() + checkEq(ic.setComposingText("ni", 1), true, "seq33 page setComposingText") + checkEq(ic.commitText("你好 Hi", 1), true, "seq33 page commitText") + checkEq(ime.readText().length, before.length + 5, "seq33 page text grows by the committed text") + checkEq(ime.readText().contains("你好 Hi"), true, "seq33 page text holds the committed text") + checkEq(NativeBridge.nativeHandleBack(shell), true, "seq33 system back leaves the page") + checkEq(NativeBridge.nativeShellRoute(shell), 1, "seq33 back returns to Home") + NativeBridge.nativeTakeSoftwareKeyboardRequest(shell) + shellTap(shell, 3, "mobile.tab.search") + checkEq(NativeBridge.nativeShellRoute(shell), 4, "seq33 Search tab opens Search") + shellTap(shell, 4, "mobile.search.input") + checkEq(NativeBridge.nativeTakeSoftwareKeyboardRequest(shell), true, "seq33 Search focus requests the IME once") + checkEq(NativeBridge.nativeWantsSoftwareKeyboard(shell), true, "seq33 focused Search wants the IME") + checkEq(ime.readText(), "", "seq33 Search launches with an empty query") + checkEq(ic.commitText("同步", 1), true, "seq33 Search commitText") + checkEq(ime.readText(), "同步", "seq33 Search query holds the committed text") + var steps = 0 + while (NativeBridge.nativeHandleBack(shell)) { + steps += 1 + checkEq(steps < 8, true, "seq33 back reaches the root route") + } + checkEq(NativeBridge.nativeShellRoute(shell), 1, "seq33 back unwinds to Home") + } finally { + NativeBridge.nativeDestroyHost(shell) + } + + val first = openShell() + var saved = "" + try { + checkEq( + NativeBridge.nativeShellMountWorkspace(first, shellBase.absolutePath, "workspace", "local", "ws-local", "Local", 10L), + true, + "seq33 shell mounts the local SQLite workspace", + ) + NativeBridge.nativeOnFrameTick(first, 1L) + shellTap(first, 10, "mobile.home.new_doc_btn") + checkEq(NativeBridge.nativeShellRoute(first), 5, "seq33 new document opens the Page route") + shellTap(first, 11, "mobile.page.block.") + val ic = AffineSurfaceView.createInputConnection({ first }) + checkEq(ic.commitText("Saved 本地", 1), true, "seq33 local page commitText") + saved = NativeBridge.nativeGetUtf16Text(first) + checkEq(saved.contains("Saved 本地"), true, "seq33 local page holds the committed text") + checkEq(NativeBridge.nativeShellFlushWorkspace(first) >= 0L, true, "seq33 flush commits the shell edits") + } finally { + NativeBridge.nativeDestroyHost(first) + } + val reopened = openShell() + try { + checkEq( + NativeBridge.nativeShellMountWorkspace(reopened, shellBase.absolutePath, "workspace", "local", "ws-local", "Local", 2_000L), + true, + "seq33 reopened shell mounts the workspace", + ) + NativeBridge.nativeOnFrameTick(reopened, 1L) + shellTap(reopened, 12, "mobile.home.doc.") + checkEq(NativeBridge.nativeShellRoute(reopened), 5, "seq33 reopened row opens the page") + shellTap(reopened, 13, "mobile.page.block.") + checkEq(NativeBridge.nativeGetUtf16Text(reopened), saved, "seq33 cold reopen shows the flushed text") + } finally { + NativeBridge.nativeDestroyHost(reopened) + } + + // Retry plan: an outcome without a mounted shell workspace reads the allowlist again. + val completeOutcome = BootstrapOutcome( + imported = true, + canCreateDefaultWorkspace = false, + connectedWorkspaceKeys = emptyList(), + failedWorkspaceIds = emptyList(), + preservedLocalWorkspaceRaw = null, + ) + listOf( + Triple(null, false, AndroidBootstrapCoordinator.Retry.RESTART), + Triple(completeOutcome.copy(imported = false), false, AndroidBootstrapCoordinator.Retry.RESTART), + Triple(completeOutcome, false, AndroidBootstrapCoordinator.Retry.RESTART), + Triple(completeOutcome, true, AndroidBootstrapCoordinator.Retry.NONE), + Triple( + completeOutcome.copy(failedWorkspaceIds = listOf("ws-missing")), + false, + AndroidBootstrapCoordinator.Retry.FAILED_WORKSPACES, + ), + ).forEach { (outcome, mounted, expected) -> + checkEq( + AndroidBootstrapCoordinator.retryPlan(outcome, mounted), + expected, + "seq33 retry plan for imported=${outcome?.imported} complete=${outcome?.isComplete} mounted=$mounted", + ) + } + + // Lifecycle entries (`onResume`, `onNewIntent`): while no shell workspace is mounted (the + // mount failed, or the allowlist had no workspace yet), the same activity reads the + // allowlist again until a workspace mounts, at most three times in a row, and drains shares + // once nothing is left to retry or the retries ran out. + // `(mount results of the runs, resumes, bootstrap runs, share drains, mounted)` + listOf( + listOf(listOf(false, true), 2, 2, 1, true), + listOf(listOf(false, false, false, false, false), 5, 4, 2, false), + listOf(listOf(null, true), 2, 2, 1, true), + listOf(listOf(null, null, null, null, null), 5, 4, 2, false), + listOf(listOf(true), 1, 1, 1, true), + ).forEach { row -> + @Suppress("UNCHECKED_CAST") + val mounts = ArrayDeque(row[0] as List) + val resumes = row[1] as Int + val state = ShellBootstrapState(maxAutoRetries = 3) + var runs = 0 + var drains = 0 + fun bootstrapRun(manual: Boolean) { + val run = state.begin(manual) ?: return + runs += 1 + state.finish(run, completeOutcome) { if (mounts.isEmpty()) false else mounts.removeFirst() } + } + bootstrapRun(manual = true) + repeat(resumes) { + state.onLifecycleEntry(retry = { bootstrapRun(manual = false) }, drainShares = { drains += 1 }) + } + val label = "seq33 lifecycle mounts=${row[0]} resumes=$resumes" + checkEq(runs, row[2], "$label bootstrap runs") + checkEq(drains, row[3], "$label share drains") + checkEq(state.workspaceMounted, row[4], "$label mounted") + } + // A manual retry after the automatic retries ran out starts a fresh budget, and an + // outcome of a replaced run is dropped. + run { + val state = ShellBootstrapState(maxAutoRetries = 1) + val first = state.begin(manual = true)!! + state.finish(first, completeOutcome) { null } + val auto = state.begin(manual = false)!! + state.finish(auto, completeOutcome) { null } + checkEq(state.begin(manual = false), null, "seq33 automatic retries stop at the limit") + val manual = state.begin(manual = true)!! + checkEq(state.begin(manual = true), null, "seq33 a run in flight blocks another run") + checkEq(state.finish(auto, completeOutcome) { true }, false, "seq33 a replaced run is dropped") + checkEq(state.finish(manual, completeOutcome) { true }, true, "seq33 the manual retry records its outcome") + checkEq(state.workspaceMounted, true, "seq33 the manual retry mounts the workspace") + checkEq(state.wantsAutoRetry, false, "seq33 nothing is left to retry") + } + + // A first bootstrap without an allowlist keeps the showcase; a retried bootstrap that + // mounts the allowlisted workspace shows it in the same host. + val bootShell = openShell() + try { + val coordinator = AndroidBootstrapCoordinator({ bootShell }, { shellBase.absolutePath }) + val fresh = coordinator.completeWithProbePayload( + """{"origin":"https://localhost","length":0,"keys":[],"entries":{},"idbTouchCount":0}""", + ) + checkEq(coordinator.shellWorkspaceId(fresh), null, "seq33 fresh install keeps the showcase") + val listed = coordinator.completeWithProbePayload( + """{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-local\"]"},"idbTouchCount":0}""", + ) + val workspaceId = coordinator.shellWorkspaceId(listed) + checkEq(workspaceId, "ws-local", "seq33 retried bootstrap finds the mounted allowlisted workspace") + checkEq( + NativeBridge.nativeShellMountWorkspace(bootShell, shellBase.absolutePath, "workspace", "local", workspaceId!!, workspaceId, 3_000L), + true, + "seq33 retried bootstrap mounts the workspace in the running host", + ) + NativeBridge.nativeOnFrameTick(bootShell, 1L) + checkEq( + ShellAccessibilityNode.parse(NativeBridge.nativeShellAccessibilityJson(bootShell) ?: "") + .any { it.id.startsWith("mobile.home.doc.") }, + true, + "seq33 mounted workspace shows its page on Home", + ) + } finally { + NativeBridge.nativeDestroyHost(bootShell) + } + } finally { + shellBase.deleteRecursively() + } + + println("Kotlin JNI Android host parity check passed (33/33 sequences)") +} diff --git a/packages/frontend/hosts/ios/AGENTS.md b/packages/frontend/hosts/ios/AGENTS.md new file mode 100644 index 0000000000..e1ca5ac285 --- /dev/null +++ b/packages/frontend/hosts/ios/AGENTS.md @@ -0,0 +1,35 @@ +# Working in `packages/frontend/hosts/ios/` (for agents) + +This directory holds the zero-CocoaPods iOS thin host for AFFiNE. +It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction`, per-frame keyboard avoidance (`KeyboardAvoidanceCoordinator`), system `PDFKit` page rasterization (`PdfRendererBridge`), UIKit haptics (`HapticsBridge`), and three zero-CocoaPods native-island bridges (`ShareExtensionBridge`, `AffinePaywallBridge`, `OnboardingSignInBridge`) to the Rust client workspace through a C ABI. + +## Hard boundaries + +- Do not add `Podfile`, `Podfile.lock`, or `package.json` in `packages/frontend/hosts/ios/`. +- Keep the main app shell free of any persistent `WKWebView`. +- Use `LegacyLocalStorageProbe.swift` only as a one-shot sentinel and rollback writer under `capacitor://localhost` for whitelisted `localStorage` keys. Keep the `window.indexedDB` runtime trap active so IndexedDB access stays strictly zero. +- Share `/workspaces///.db` in place through `affine-store` and mount local workspaces strictly from the `affine-local-workspace` allowlist without scanning disk for `*.db` files. +- Keep `LegacyAuthBridge.swift` and `src/auth.rs` aligned with Keychain service `app.affine.pro.auth-token` (2001 reference epoch `f64` timestamps) and `UserDefaults` key `app.affine.pro.auth-installation-id`. +- Drive iOS text selection, handles, loupe, and edit menus through system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction` over full-document `AffineTextPosition` / `AffineTextRange` value semantics (`isEqual:`/`hash`, `affine_ios_host_doc_document_bounds`, zero synchronous `inputDelegate` echo in `setSelectedTextRange:`) with zero `SelectionOverlayView`, rendering the live pure-Rust GPU `PlaygroundView` directly through `IosEditorPlatform` + `MetalRenderer`'s `CAMetalLayer` (`affine_ios_host_metal_layer`) with zero `HostTextPreviewView` subview mounted in `MetalHostViewController` and zero host-side `backingText` copy (`UITextInput` reads directly from `PlatformInputHandler` via `affine_ios_host_utf16_len`/`copy_utf16` and receives editor mutations through `affine_ios_host_set_text_input_callback`). +- `MetalHostViewController(root: .shell)` (the app default) mounts the `affine-mobile` `MobileShellView` through `affine_ios_host_create_shell`; `MetalHostViewController(root: .pageEditor)` and `affine_ios_host_create` keep one bare `PlaygroundView` for editor-only smoke tests. `src/runtime_root.rs` resolves the editor that owns `UITextInput`, document positions, and selection actions: the root editor, or the shell's embedded `page_editor()` while the `Page` route shows with no sheet or drawer above it. The shell's focused `EntityInputHandler` takes `UITextInput` text on the Search route with no sheet above it and in the drawer once its filter holds `search_focus`; while any other sheet, or the drawer without a focused filter, covers the shell, the runtime drops text and composition edits. Outside the page editor every touch goes straight to Rust. `affine_ios_host_handle_back` lets the page editor close its overlay first, then runs `MobileBackCoordinator`. After bootstrap the host mounts the allowlisted local workspace that bootstrap opened with `affine_ios_host_shell_mount_workspace` (`src/shell_workspace.rs`): the mount loads only the root document and `db$*` tables, each page loads when the shell opens it (a failed load retries the next time the page shows), a scheduler task commits edits every second (zero SQLite access without pending changes), and `affine_ios_host_shell_flush_workspace` commits them when the app enters the background. The shell follows the system appearance through `traitCollectionDidChange`. +- Stage-1 touch defaults apply via `FormFactor::from_ios_idiom` (`UIDevice.current.userInterfaceIdiom == .pad` -> `Tablet`, otherwise `Phone`): `edgeless_readonly = true`, `database_readonly = true`, `page_readonly = false`. +- Use `scripts/package-sim-app.sh` to assemble an installable `AffineIosHost.app` bundle for the iOS Simulator. +- Keep `KeyboardAvoidanceCoordinator.swift` aligned with `ui::WindowInsets::effective()` (`ime_bottom` is the absolute docked keyboard overlap from the window bottom edge, `effective_bottom = max(safe_bottom, ime_bottom)`, and `affine_ios_host_ime_above_safe_bottom` exposes `max(0, ime_bottom - safe_bottom)` to avoid double-deducting safe area), returning `0` for floating, split, and external hardware keyboards. +- Keep `PdfRendererBridge.swift` backed by Apple's system `PDFKit` framework (zero C++ PDFium) with explicit `affine_ios_host_pdf_open`/`close` document handles (zero persistent cache) and enforce the shared Rust header, page-bounds, and pixel-budget limits in `src/pdf.rs`. +- Pin Rust builds in `scripts/build-rust-ios.sh` to `rustup run 1.98.1`, `--manifest-path packages/frontend/Cargo.toml`, and `CARGO_ENCODED_RUSTFLAGS=""`. Never modify `packages/frontend/apps/ios/` (`1.97.1`). + +## Verification + +On macOS with Xcode installed, build `libaffine_ios_host.a` and link the Swift host executable against the iOS Simulator SDK: + +```sh +CARGO_ENCODED_RUSTFLAGS="" rustup run 1.98.1 cargo build --locked \ + --manifest-path packages/frontend/Cargo.toml -p affine-ios-host \ + --target aarch64-apple-ios-sim +SDK=$(xcrun --sdk iphonesimulator --show-sdk-path) +swiftc -emit-executable -sdk "$SDK" -target arm64-apple-ios16.0-simulator \ + -import-objc-header packages/frontend/hosts/ios/include/affine_mobile_host.h \ + -L packages/frontend/target/aarch64-apple-ios-sim/debug -laffine_ios_host \ + -framework UIKit -framework QuartzCore -framework Metal -framework WebKit \ + -o /tmp/AffineIosHost packages/frontend/hosts/ios/Sources/*.swift +``` diff --git a/packages/frontend/hosts/ios/CLAUDE.md b/packages/frontend/hosts/ios/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/frontend/hosts/ios/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/frontend/hosts/ios/Cargo.toml b/packages/frontend/hosts/ios/Cargo.toml new file mode 100644 index 0000000000..4e29907656 --- /dev/null +++ b/packages/frontend/hosts/ios/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "affine-ios-host" +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true +workspace = "../.." + +[lib] +crate-type = ["staticlib", "rlib"] + +[features] +default = ["preview-typst"] +preview-typst = ["playground/preview-typst"] + +[dependencies] +affine-client = { path = "../../client" } +affine-legacy-import = { path = "../../legacy-import" } +affine-mobile = { path = "../../mobile" } +affine-store = { path = "../../../common/store" } +anyhow.workspace = true +blocksuite-playground-doc = { path = "../../../../blocksuite/crates/doc", default-features = false } +chrono.workspace = true +futures.workspace = true +parking_lot.workspace = true +playground = { path = "../../../../blocksuite/crates/playground", default-features = false } +raw-window-handle.workspace = true +serde.workspace = true +serde_json.workspace = true +smallvec.workspace = true +sqlx.workspace = true +thiserror.workspace = true +tokio.workspace = true +ui = { path = "../../../ui/ui" } +ui-tokens = { path = "../../../ui/tokens" } +uuid.workspace = true + +[lints] +workspace = true diff --git a/packages/frontend/hosts/ios/Info.plist b/packages/frontend/hosts/ios/Info.plist new file mode 100644 index 0000000000..aeba1adaed --- /dev/null +++ b/packages/frontend/hosts/ios/Info.plist @@ -0,0 +1,58 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + AffineIosHost + CFBundleIdentifier + app.affine.pro + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + AFFiNE + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.27.5 + CFBundleVersion + 1 + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLName + app.affine.pro + CFBundleURLSchemes + + affine + + + + LSRequiresIPhoneOS + + UIApplicationSupportsIndirectInputEvents + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + AffineSceneDelegate + + + + + UILaunchScreen + + + diff --git a/packages/frontend/hosts/ios/Sources/AffinePaywallBridge.swift b/packages/frontend/hosts/ios/Sources/AffinePaywallBridge.swift new file mode 100644 index 0000000000..f10043530a --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/AffinePaywallBridge.swift @@ -0,0 +1,283 @@ +import Foundation + +/// Authoritative verified StoreKit 2 entitlement snapshot persisted atomically on disk. +struct PaywallEntitlementSnapshot: Codable, Equatable, Sendable { + let transactionId: String + let productId: String + let jwsRepresentation: String + let expirationDate: Date? + let revocationDate: Date? +} + +/// Zero-CocoaPods StoreKit 2 paywall narrow bridge (`AffinePaywall`). +/// +/// Architectural safety contract: +/// - Never starts a `Transaction.updates` listener on the app launch path, never invokes +/// `product.purchase()`, and never calls `transaction.finish()`. +/// - Filters all entitlement snapshots through the 3-product `0.27.5` allowlist + compact +/// 3-segment JWS check before persisting to disk or selecting the primary Rust entitlement. +/// - Reconciles persisted snapshots atomically between disk and Rust state, rolling back both +/// if persistence or FFI synchronization fails. +@MainActor +final class AffinePaywallBridge { + /// Exact `0.27.5` App Store Connect product identifiers (`PricingConfiguration.swift`). + nonisolated static let defaultProductIds: [String] = [ + "app.affine.pro.Monthly", + "app.affine.pro.Annual", + "app.affine.pro.ai.Annual", + ] + + private var hostHandle: OpaquePointer? + private let entitlementFileUrl: URL + private(set) var activeEntitlements: [String: PaywallEntitlementSnapshot] = [:] + + private static func makeEncoder() -> JSONEncoder { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return encoder + } + + private static func makeDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + } + + /// Validates that `productId` is in the `0.27.5` 3-product allowlist. + nonisolated static func isAllowlistedProduct(_ productId: String) -> Bool { + defaultProductIds.contains(productId) + } + + /// Validates a compact 3-segment base64url JWS string (`header.payload.signature`). + nonisolated static func isValidJwsEnvelope(_ jws: String) -> Bool { + let parts = jws.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 3 else { + return false + } + return parts.allSatisfy { seg in + !seg.isEmpty && seg.utf8.allSatisfy { b in + (b >= 0x30 && b <= 0x39) + || (b >= 0x41 && b <= 0x5A) + || (b >= 0x61 && b <= 0x7A) + || b == 0x2D + || b == 0x5F + } + } + } + + /// Single authoritative entitlement active predicate: not revoked and not expired. + nonisolated static func isActiveEntitlement( + revocationDate: Date?, + expirationDate: Date?, + now: Date = Date() + ) -> Bool { + guard revocationDate == nil else { + return false + } + if let expirationDate { + return expirationDate > now + } + return true + } + + nonisolated static func isEligibleSnapshot( + _ snapshot: PaywallEntitlementSnapshot, + now: Date = Date() + ) -> Bool { + guard + !snapshot.transactionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + isAllowlistedProduct(snapshot.productId), + isValidJwsEnvelope(snapshot.jwsRepresentation) + else { + return false + } + return isActiveEntitlement( + revocationDate: snapshot.revocationDate, + expirationDate: snapshot.expirationDate, + now: now + ) + } + + init(entitlementFileUrl: URL? = nil) { + if let entitlementFileUrl { + self.entitlementFileUrl = entitlementFileUrl + } else if Bundle.main.bundleIdentifier == nil { + self.entitlementFileUrl = ShareExtensionBridge.unbundledStorageDirectory + .appendingPathComponent("affine-paywall-entitlements.json") + } else if let appSupport = FileManager.default.urls( + for: .applicationSupportDirectory, + in: .userDomainMask + ).first { + self.entitlementFileUrl = appSupport + .appendingPathComponent("affine-paywall", isDirectory: true) + .appendingPathComponent("verified-entitlements.json") + } else { + self.entitlementFileUrl = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-paywall-entitlements.json") + } + } + + func attach(host: OpaquePointer, now: Date = Date()) { + hostHandle = host + _ = restorePersistedEntitlements(into: host, now: now) + } + + func detach() { + hostHandle = nil + } + + private func writeEntitlementsToDisk(_ map: [String: PaywallEntitlementSnapshot]) -> Bool { + let fm = FileManager.default + if map.isEmpty { + if fm.fileExists(atPath: entitlementFileUrl.path) { + do { + try fm.removeItem(at: entitlementFileUrl) + } catch { + return false + } + } + return true + } + let sorted = map.values.sorted { $0.transactionId < $1.transactionId } + do { + try fm.createDirectory( + at: entitlementFileUrl.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + let data = try Self.makeEncoder().encode(sorted) + try data.write(to: entitlementFileUrl, options: .atomic) + return true + } catch { + return false + } + } + + private func syncRustEntitlementState( + from map: [String: PaywallEntitlementSnapshot], + host: OpaquePointer + ) -> Bool { + guard let primary = map.values.sorted(by: { $0.transactionId < $1.transactionId }).first else { + return affine_ios_island_paywall_clear_entitlements(host) + } + return primary.productId.withCString { cPid in + primary.transactionId.withCString { cTx in + primary.jwsRepresentation.withCString { cJws in + affine_ios_island_paywall_complete_jws(host, cPid, cTx, cJws) + } + } + } + } + + private func commitEntitlementMapAtomically( + _ nextMap: [String: PaywallEntitlementSnapshot], + host: OpaquePointer + ) -> Bool { + let previous = activeEntitlements + guard writeEntitlementsToDisk(nextMap) else { + activeEntitlements = previous + return false + } + guard syncRustEntitlementState(from: nextMap, host: host) else { + _ = writeEntitlementsToDisk(previous) + _ = syncRustEntitlementState(from: previous, host: host) + activeEntitlements = previous + return false + } + activeEntitlements = nextMap + return true + } + + @discardableResult + func restorePersistedEntitlements(into host: OpaquePointer, now: Date = Date()) -> Bool { + guard + let data = try? Data(contentsOf: entitlementFileUrl), + let records = try? Self.makeDecoder().decode([PaywallEntitlementSnapshot].self, from: data) + else { + activeEntitlements = [:] + _ = affine_ios_island_paywall_clear_entitlements(host) + return false + } + return reconcileCurrentEntitlements(records, host: host, now: now) + } + + @discardableResult + func reconcileCurrentEntitlements( + _ snapshots: [PaywallEntitlementSnapshot], + host: OpaquePointer? = nil, + now: Date = Date() + ) -> Bool { + guard let activeHost = host ?? hostHandle else { + return false + } + var nextActive: [String: PaywallEntitlementSnapshot] = [:] + for snap in snapshots where Self.isEligibleSnapshot(snap, now: now) { + nextActive[snap.transactionId] = snap + } + return commitEntitlementMapAtomically(nextActive, host: activeHost) + } + + @discardableResult + func applyVerifiedTransactionUpdate( + _ snapshot: PaywallEntitlementSnapshot, + host: OpaquePointer? = nil, + now: Date = Date() + ) -> Bool { + guard let activeHost = host ?? hostHandle else { + return false + } + var nextMap = activeEntitlements.filter { _, existing in + Self.isEligibleSnapshot(existing, now: now) + } + + let trimmedTxId = snapshot.transactionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedTxId.isEmpty else { + "empty transaction id".withCString { + _ = affine_ios_island_paywall_finish_non_verified(activeHost, 2, $0) + } + return false + } + + if !Self.isAllowlistedProduct(snapshot.productId) || !Self.isValidJwsEnvelope(snapshot.jwsRepresentation) { + if nextMap.isEmpty { + "invalid StoreKit product or JWS envelope".withCString { + _ = affine_ios_island_paywall_finish_non_verified(activeHost, 2, $0) + } + } + return false + } + + if Self.isActiveEntitlement( + revocationDate: snapshot.revocationDate, + expirationDate: snapshot.expirationDate, + now: now + ) { + nextMap[trimmedTxId] = snapshot + return commitEntitlementMapAtomically(nextMap, host: activeHost) + } else { + nextMap.removeValue(forKey: trimmedTxId) + return commitEntitlementMapAtomically(nextMap, host: activeHost) + } + } + + func syncProductsPayload(host: OpaquePointer, payload: [[String: String]]) -> Bool { + guard + let data = try? JSONSerialization.data(withJSONObject: payload), + let json = String(data: data, encoding: .utf8) + else { + return false + } + return json.withCString { affine_ios_island_paywall_set_products_json(host, $0) } + } + + func beginPurchase(host: OpaquePointer, productId: String) -> Bool { + productId.withCString { affine_ios_island_paywall_begin_purchase(host, $0) } + } + + func stateJson(host: OpaquePointer) -> String { + guard let ptr = affine_ios_island_paywall_state_json(host) else { + return "{}" + } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } +} diff --git a/packages/frontend/hosts/ios/Sources/AppDelegate.swift b/packages/frontend/hosts/ios/Sources/AppDelegate.swift new file mode 100644 index 0000000000..3c8cba3dcf --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/AppDelegate.swift @@ -0,0 +1,56 @@ +import UIKit + +@main +final class AppDelegate: UIResponder, UIApplicationDelegate { + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil + ) -> Bool { + true + } + + func application( + _ application: UIApplication, + configurationForConnecting connectingSceneSession: UISceneSession, + options: UIScene.ConnectionOptions + ) -> UISceneConfiguration { + let config = UISceneConfiguration( + name: "Default Configuration", + sessionRole: connectingSceneSession.role + ) + config.delegateClass = SceneDelegate.self + return config + } +} + +@objc(AffineSceneDelegate) +final class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + guard let windowScene = scene as? UIWindowScene else { + return + } + let window = UIWindow(windowScene: windowScene) + let rootVC = MetalHostViewController() + window.rootViewController = rootVC + window.makeKeyAndVisible() + self.window = window + for context in connectionOptions.urlContexts { + _ = rootVC.handleIncomingUrl(context.url) + } + } + + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { + guard let rootVC = window?.rootViewController as? MetalHostViewController else { + return + } + for context in URLContexts { + _ = rootVC.handleIncomingUrl(context.url) + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/HapticsBridge.swift b/packages/frontend/hosts/ios/Sources/HapticsBridge.swift new file mode 100644 index 0000000000..4dd8d2a0d6 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/HapticsBridge.swift @@ -0,0 +1,134 @@ +import Foundation +import UIKit + +enum AffineHapticPatternSwift: UInt8, CaseIterable, Equatable { + case lightImpact = 0 + case mediumImpact = 1 + case heavyImpact = 2 + case selectionChanged = 3 + case success = 4 + case warning = 5 + case error = 6 +} + +/// Bridges Rust haptic pattern triggers to UIKit feedback generators with pre-warming +/// and main-thread-safe dispatch. +final class HapticsBridge { + static let maxRecordedPatterns = 64 + + private let lock = NSLock() + private var recordedPatterns: [AffineHapticPatternSwift] = [] + + private var lightGenerator: UIImpactFeedbackGenerator? + private var mediumGenerator: UIImpactFeedbackGenerator? + private var heavyGenerator: UIImpactFeedbackGenerator? + private var selectionGenerator: UISelectionFeedbackGenerator? + private var notificationGenerator: UINotificationFeedbackGenerator? + + var dispatchedPatterns: [AffineHapticPatternSwift] { + lock.lock() + defer { lock.unlock() } + return recordedPatterns + } + + func resetDispatchedPatterns() { + lock.lock() + recordedPatterns.removeAll() + lock.unlock() + } + + func prepareAll() { + dispatchOnMain { + self.ensureGeneratorsOnMain() + self.lightGenerator?.prepare() + self.mediumGenerator?.prepare() + self.heavyGenerator?.prepare() + self.selectionGenerator?.prepare() + self.notificationGenerator?.prepare() + } + } + + func trigger(_ pattern: AffineHapticPatternSwift) { + lock.lock() + if recordedPatterns.count >= Self.maxRecordedPatterns { + recordedPatterns.removeFirst(recordedPatterns.count - Self.maxRecordedPatterns + 1) + } + recordedPatterns.append(pattern) + lock.unlock() + + dispatchOnMain { + self.ensureGeneratorsOnMain() + switch pattern { + case .lightImpact: + self.lightGenerator?.impactOccurred() + self.lightGenerator?.prepare() + case .mediumImpact: + self.mediumGenerator?.impactOccurred() + self.mediumGenerator?.prepare() + case .heavyImpact: + self.heavyGenerator?.impactOccurred() + self.heavyGenerator?.prepare() + case .selectionChanged: + self.selectionGenerator?.selectionChanged() + self.selectionGenerator?.prepare() + case .success: + self.notificationGenerator?.notificationOccurred(.success) + self.notificationGenerator?.prepare() + case .warning: + self.notificationGenerator?.notificationOccurred(.warning) + self.notificationGenerator?.prepare() + case .error: + self.notificationGenerator?.notificationOccurred(.error) + self.notificationGenerator?.prepare() + } + } + } + + func attach(to host: OpaquePointer) { + let userData = Unmanaged.passUnretained(self).toOpaque() + affine_ios_host_set_haptics_callback( + host, + { rawPattern, ctx in + guard + let ctx, + let pattern = AffineHapticPatternSwift(rawValue: rawPattern) + else { + return + } + let bridge = Unmanaged.fromOpaque(ctx).takeUnretainedValue() + bridge.trigger(pattern) + }, + userData + ) + } + + func detach(from host: OpaquePointer) { + affine_ios_host_set_haptics_callback(host, nil, nil) + } + + private func dispatchOnMain(_ work: @escaping () -> Void) { + if Thread.isMainThread { + work() + } else { + DispatchQueue.main.async(execute: work) + } + } + + private func ensureGeneratorsOnMain() { + if lightGenerator == nil { + lightGenerator = UIImpactFeedbackGenerator(style: .light) + } + if mediumGenerator == nil { + mediumGenerator = UIImpactFeedbackGenerator(style: .medium) + } + if heavyGenerator == nil { + heavyGenerator = UIImpactFeedbackGenerator(style: .heavy) + } + if selectionGenerator == nil { + selectionGenerator = UISelectionFeedbackGenerator() + } + if notificationGenerator == nil { + notificationGenerator = UINotificationFeedbackGenerator() + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/HostBootstrapCoordinator.swift b/packages/frontend/hosts/ios/Sources/HostBootstrapCoordinator.swift new file mode 100644 index 0000000000..4702a3c292 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/HostBootstrapCoordinator.swift @@ -0,0 +1,214 @@ +import Foundation + +struct ParsedLegacyStateSummary: Decodable, Equatable { + let localWorkspaceIds: [String] +} + +struct ParsedLegacyDisposition: Decodable, Equatable { + let status: String + let state: ParsedLegacyStateSummary +} + +struct LegacyWriteBackPlan: Decodable, Equatable { + let set: [String: String] + let remove: [String] +} + +enum HostBootstrapError: Error, Equatable { + case invalidSentinelSnapshot + case missingImportedState + case writeBackPlanFailed + case mountFailures([String]) +} + +/// Startup coordinator wiring `LegacyLocalStorageProbe` -> Rust sentinel validation -> +/// allowlist-only `WorkspaceStorageBridge` mounting (with eviction on shrink/clear) -> +/// rollback write-back planning -> background `PASSIVE` WAL checkpoints. +@MainActor +final class HostBootstrapCoordinator { + private let probe: LegacyLocalStorageProbe + private let documentsDirectory: URL? + private(set) var imported: Bool = false + private(set) var allowlistedLocalIds: [String] = [] + private(set) var lastFailedMountIds: [String] = [] + private(set) var lastSnapshot: LegacyLocalStorageSnapshot? + private(set) var importedStateJson: String? + private var activeWorkspaces: [String: WorkspaceStorageBridge] = [:] + + /// True only after legacy storage bootstrap completed cleanly with zero local workspaces. + /// Remains false when `LegacyLocalStorageProbe` fails or times out (fail-closed). + var canCreateDefaultWorkspace: Bool { + imported && lastFailedMountIds.isEmpty && allowlistedLocalIds.isEmpty + } + + init(documentsDirectory: URL? = nil, probe: LegacyLocalStorageProbe? = nil) { + self.documentsDirectory = documentsDirectory + self.probe = probe ?? LegacyLocalStorageProbe() + } + + /// Run the one-shot legacy `capacitor://localhost` probe and mount allowlisted local workspaces. + func bootstrapFromLegacyStorage() async throws -> ParsedLegacyDisposition { + let snapshot = try await probe.capture() + return try applySnapshot(snapshot) + } + + /// Validate a captured sentinel through Rust, retain full imported whitelisted state + /// (preserving any corrupt raw `affine-local-workspace` verbatim), and reconcile mounted + /// local workspaces against the parsed allowlist. + func applySnapshot(_ snapshot: LegacyLocalStorageSnapshot) throws -> ParsedLegacyDisposition { + let snapshotData = try JSONEncoder().encode(snapshot) + guard let snapshotJson = String(data: snapshotData, encoding: .utf8) else { + throw HostBootstrapError.invalidSentinelSnapshot + } + let dispositionPtr = snapshotJson.withCString { + affine_ios_legacy_storage_parse_snapshot_json($0) + } + guard let dispositionPtr else { + throw HostBootstrapError.invalidSentinelSnapshot + } + defer { affine_ios_string_free(dispositionPtr) } + let dispositionData = Data(String(cString: dispositionPtr).utf8) + let disposition = try JSONDecoder().decode(ParsedLegacyDisposition.self, from: dispositionData) + + guard + let rootObj = try JSONSerialization.jsonObject(with: dispositionData) as? [String: Any], + let stateObj = rootObj["state"], + let stateBytes = try? JSONSerialization.data(withJSONObject: stateObj), + let stateJson = String(data: stateBytes, encoding: .utf8) + else { + throw HostBootstrapError.invalidSentinelSnapshot + } + + lastSnapshot = snapshot + importedStateJson = stateJson + try reconcileActiveWorkspaces(disposition.state.localWorkspaceIds) + imported = true + return disposition + } + + /// Explicitly update the local workspace allowlist after bootstrap: + /// syncs `importedStateJson` (clearing any prior corrupt raw `affine-local-workspace` so + /// deleted workspaces never resurrect on rollback), evicts removed handles, mounts all + /// valid entries, and throws a summarized error if any entry fails to mount. + func applyLocalWorkspaceAllowlist(_ nextAllowlist: [String]) throws { + updateImportedLocalWorkspaceIds(nextAllowlist) + try reconcileActiveWorkspaces(nextAllowlist) + } + + /// Generate a rollback write-back plan preserving all imported whitelisted entries + /// (including server configs, theme, preferences, and any corrupt raw `affine-local-workspace`). + func buildRollbackWriteBackPlan() throws -> LegacyWriteBackPlan { + guard lastFailedMountIds.isEmpty else { + throw HostBootstrapError.mountFailures(lastFailedMountIds) + } + guard let stateJson = importedStateJson, let snapshot = lastSnapshot else { + throw HostBootstrapError.missingImportedState + } + let prevKeysData = try JSONEncoder().encode(snapshot.keys) + guard let prevKeysJson = String(data: prevKeysData, encoding: .utf8) else { + throw HostBootstrapError.writeBackPlanFailed + } + let planPtr = stateJson.withCString { cState in + prevKeysJson.withCString { cKeys in + affine_ios_legacy_storage_plan_write_back_json(cState, cKeys) + } + } + guard let planPtr else { + throw HostBootstrapError.writeBackPlanFailed + } + defer { affine_ios_string_free(planPtr) } + let planData = Data(String(cString: planPtr).utf8) + return try JSONDecoder().decode(LegacyWriteBackPlan.self, from: planData) + } + + func registerActiveWorkspace(id: String, bridge: WorkspaceStorageBridge) { + activeWorkspaces[id] = bridge + } + + func workspace(id: String) -> WorkspaceStorageBridge? { + activeWorkspaces[id] + } + + func mountedWorkspacesSnapshot() -> [String: WorkspaceStorageBridge] { + activeWorkspaces + } + + /// Non-blocking `PRAGMA wal_checkpoint(PASSIVE)` across all active workspaces on background entry. + @discardableResult + func checkpointAllPassive() -> Bool { + var allSucceeded = true + for bridge in activeWorkspaces.values { + if !bridge.checkpointPassive() { + allSucceeded = false + } + } + return allSucceeded + } + + func closeAll() { + for bridge in activeWorkspaces.values { + bridge.close() + } + activeWorkspaces.removeAll() + } + + private func reconcileActiveWorkspaces(_ nextAllowlist: [String]) throws { + let nextSet = Set(nextAllowlist) + let removedIds = activeWorkspaces.keys.filter { !nextSet.contains($0) } + for id in removedIds { + activeWorkspaces[id]?.close() + activeWorkspaces.removeValue(forKey: id) + } + + allowlistedLocalIds = nextAllowlist + var failedIds: [String] = [] + for workspaceId in allowlistedLocalIds where activeWorkspaces[workspaceId] == nil { + do { + let bridge = try WorkspaceStorageBridge( + spaceType: "workspace", + peer: "local", + spaceId: workspaceId, + allowlistedLocalIds: allowlistedLocalIds, + documentsDirectory: documentsDirectory + ) + activeWorkspaces[workspaceId] = bridge + } catch { + failedIds.append(workspaceId) + } + } + lastFailedMountIds = failedIds + if !failedIds.isEmpty { + throw HostBootstrapError.mountFailures(failedIds) + } + } + + private func updateImportedLocalWorkspaceIds(_ nextAllowlist: [String]) { + guard + let currentJson = importedStateJson, + let data = currentJson.data(using: .utf8), + var stateObj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + else { + return + } + let previousLocalIds = (stateObj["localWorkspaceIds"] as? [String]) ?? allowlistedLocalIds + let removedLocalIds = Set(previousLocalIds).subtracting(Set(nextAllowlist)) + stateObj["localWorkspaceIds"] = nextAllowlist + if var rawEntries = stateObj["rawUnparsedEntries"] as? [String: String] { + rawEntries.removeValue(forKey: LegacyLocalStorageProbe.localWorkspaceKey) + stateObj["rawUnparsedEntries"] = rawEntries + } + let currentFlavour = (stateObj["lastWorkspaceFlavour"] as? String) ?? "local" + if let lastId = stateObj["lastWorkspaceId"] as? String, + removedLocalIds.contains(lastId), + currentFlavour == "local" + { + stateObj["lastWorkspaceId"] = NSNull() + stateObj["lastWorkspaceFlavour"] = NSNull() + } + if let updatedData = try? JSONSerialization.data(withJSONObject: stateObj), + let updatedJson = String(data: updatedData, encoding: .utf8) + { + importedStateJson = updatedJson + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift b/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift new file mode 100644 index 0000000000..6b4a0aaee3 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift @@ -0,0 +1,161 @@ +import QuartzCore +import UIKit + +/// Observes UIKit keyboard frame notifications and samples non-double-counted keyboard +/// avoidance insets on every `CADisplayLink` tick through the Rust C ABI. +final class KeyboardAvoidanceCoordinator { + weak var hostView: UIView? + var hostHandle: OpaquePointer? + var currentTimeProvider: () -> Double = { CACurrentMediaTime() } + + private(set) var lastMetrics = AffineKeyboardAvoidanceMetrics() + private(set) var lastInsets = AffineWindowInsets( + safe_top: 0, + safe_right: 0, + safe_bottom: 0, + safe_left: 0, + ime_bottom: 0 + ) + private var lastDisplayTimestamp: Double = 0 + private var observing = false + + func startObserving() { + guard !observing else { + return + } + observing = true + let center = NotificationCenter.default + center.addObserver( + self, + selector: #selector(handleKeyboardWillChangeFrame(_:)), + name: UIResponder.keyboardWillChangeFrameNotification, + object: nil + ) + center.addObserver( + self, + selector: #selector(handleKeyboardWillHide(_:)), + name: UIResponder.keyboardWillHideNotification, + object: nil + ) + } + + func stopObserving() { + guard observing else { + return + } + observing = false + NotificationCenter.default.removeObserver(self) + } + + deinit { + stopObserving() + } + + /// Sample the current eased keyboard avoidance height on each `CADisplayLink` tick. + @discardableResult + func sampleDisplayLinkFrame( + timestamp: Double, + safeAreaInsets: UIEdgeInsets + ) -> AffineWindowInsets { + lastDisplayTimestamp = timestamp + guard let handle = hostHandle else { + return lastInsets + } + let next = affine_ios_host_sample_keyboard_frame( + handle, + Float(safeAreaInsets.top), + Float(safeAreaInsets.right), + Float(safeAreaInsets.bottom), + Float(safeAreaInsets.left), + timestamp + ) + lastInsets = next + return next + } + + /// Deterministic entry point for evaluating a keyboard frame change against window bounds. + @discardableResult + func applyKeyboardFrame( + windowBounds: CGRect, + keyboardFrameInView: CGRect, + safeAreaInsets: UIEdgeInsets, + isHidden: Bool, + durationSec: Double, + timestampSec: Double + ) -> AffineKeyboardAvoidanceMetrics { + lastDisplayTimestamp = timestampSec + let cWindow = AffineRect( + x: Float(windowBounds.origin.x), + y: Float(windowBounds.origin.y), + width: Float(windowBounds.size.width), + height: Float(windowBounds.size.height) + ) + let cKeyboard = AffineRect( + x: Float(keyboardFrameInView.origin.x), + y: Float(keyboardFrameInView.origin.y), + width: Float(keyboardFrameInView.size.width), + height: Float(keyboardFrameInView.size.height) + ) + let metrics = affine_ios_keyboard_compute_avoidance( + cWindow, + cKeyboard, + Float(safeAreaInsets.bottom), + isHidden + ) + lastMetrics = metrics + + if let handle = hostHandle { + affine_ios_host_begin_keyboard_transition( + handle, + metrics.ime_bottom_pt, + timestampSec, + durationSec + ) + lastInsets = affine_ios_host_sample_keyboard_frame( + handle, + Float(safeAreaInsets.top), + Float(safeAreaInsets.right), + Float(safeAreaInsets.bottom), + Float(safeAreaInsets.left), + timestampSec + ) + } + return metrics + } + + @objc private func handleKeyboardWillChangeFrame(_ notification: Notification) { + handleKeyboardNotification(notification, isHidden: false) + } + + @objc private func handleKeyboardWillHide(_ notification: Notification) { + handleKeyboardNotification(notification, isHidden: true) + } + + private func handleKeyboardNotification(_ notification: Notification, isHidden: Bool) { + guard + let view = hostView, + let userInfo = notification.userInfo, + let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect + else { + return + } + let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25 + let converted: CGRect + if let window = view.window { + converted = view.convert(endFrame, from: window.screen.coordinateSpace) + } else { + converted = view.convert(endFrame, from: nil) + } + // Always sample fresh monotonic media time so resuming after background suspension + // never reuses a stale pre-background `CADisplayLink` timestamp and skips animation frames. + let nowTs = currentTimeProvider() + _ = applyKeyboardFrame( + windowBounds: view.bounds, + keyboardFrameInView: converted, + safeAreaInsets: view.safeAreaInsets, + isHidden: isHidden, + durationSec: duration, + timestampSec: nowTs + ) + } +} diff --git a/packages/frontend/hosts/ios/Sources/LegacyAuthBridge.swift b/packages/frontend/hosts/ios/Sources/LegacyAuthBridge.swift new file mode 100644 index 0000000000..239fdcc1f1 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/LegacyAuthBridge.swift @@ -0,0 +1,588 @@ +import Foundation +import Security +import WebKit + +/// Matches 0.27.5 `AuthPlugin.swift` `AuthSessionInfo`. +struct LegacyAuthSessionInfo: Codable, Equatable, Sendable { + let id: String + let absoluteExpiresAt: String +} + +/// Matches 0.27.5 `AuthPlugin.swift` `StoredAuthTokenPair`. +/// +/// Foundation's default `JSONEncoder`/`JSONDecoder` encodes `Date` as +/// `timeIntervalSinceReferenceDate` (2001-01-01T00:00:00Z `Double`), ensuring +/// zero-logout compatibility across upgrade, token rotation, and rollback. +struct LegacyStoredAuthTokenPair: Codable, Equatable, Sendable { + let version: Int + let tokenType: String + let accessToken: String + let accessExpiresAt: Date + let refreshToken: String + let refreshExpiresAt: String + let session: LegacyAuthSessionInfo +} + +enum LegacyAuthBridgeError: Error, Equatable, Sendable { + case invalidEndpoint + case invalidPayload + case tokenNotFound + case operationCancelled + case credentialStoreUnavailable + case keychainFailure(OSStatus) + case httpFailure(statusCode: Int, permanentlyInvalidatesSession: Bool) +} + +/// Persistence abstraction backing `LegacyAuthBridge` (defaults to iOS Keychain). +protocol LegacyAuthTokenPersistence: Sendable { + func readRawData(service: String, account: String) throws -> Data? + func writeRawData(_ data: Data, service: String, account: String) throws + func deleteRawData(service: String, account: String) throws +} + +/// Production Keychain persistence aligned with 0.27.5 `AuthPlugin.swift:215-269`. +struct KeychainAuthTokenPersistence: LegacyAuthTokenPersistence { + private func baseQuery(service: String, account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + } + + func readRawData(service: String, account: String) throws -> Data? { + var query = baseQuery(service: service, account: account) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + if status == errSecItemNotFound { + return nil + } + if status == errSecInteractionNotAllowed || status == errSecNotAvailable { + throw LegacyAuthBridgeError.credentialStoreUnavailable + } + guard status == errSecSuccess, let data = item as? Data else { + throw LegacyAuthBridgeError.keychainFailure(status) + } + return data + } + + func writeRawData(_ data: Data, service: String, account: String) throws { + var add = baseQuery(service: service, account: account) + add[kSecValueData as String] = data + add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + let update = [kSecValueData as String: data] + let status = SecItemUpdate(baseQuery(service: service, account: account) as CFDictionary, update as CFDictionary) + if status == errSecItemNotFound { + let addStatus = SecItemAdd(add as CFDictionary, nil) + guard addStatus == errSecSuccess else { + throw LegacyAuthBridgeError.keychainFailure(addStatus) + } + } else if status != errSecSuccess { + throw LegacyAuthBridgeError.keychainFailure(status) + } + } + + func deleteRawData(service: String, account: String) throws { + let status = SecItemDelete(baseQuery(service: service, account: account) as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw LegacyAuthBridgeError.keychainFailure(status) + } + } +} + +private struct AuthRefreshOperation { + let id: UUID + let task: Task +} + +/// Actor-isolated single-flight session broker aligned with 0.27.5 `AuthPlugin.swift:70-150`. +private actor AuthSessionBroker { + private let persistence: LegacyAuthTokenPersistence + private let clientVersion: String + private var refreshTasks: [String: AuthRefreshOperation] = [:] + private var mutationEpochs: [String: UInt64] = [:] + + init(persistence: LegacyAuthTokenPersistence, clientVersion: String) { + self.persistence = persistence + self.clientVersion = clientVersion + } + + func readTokenPair(for endpoint: String) throws -> LegacyStoredAuthTokenPair? { + let account = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + guard let data = try persistence.readRawData(service: LegacyAuthBridge.keychainService, account: account) else { + return nil + } + guard let json = String(data: data, encoding: .utf8) else { + try persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: account) + return nil + } + + var isValid = false + var expiresUnix = 0.0 + let normalizedPtr = json.withCString { cJson in + affine_ios_auth_parse_keychain_json( + cJson, + Date().timeIntervalSince1970, + 120.0, + &isValid, + &expiresUnix + ) + } + guard let normalizedPtr else { + try persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: account) + return nil + } + defer { affine_ios_string_free(normalizedPtr) } + let normalizedData = Data(String(cString: normalizedPtr).utf8) + guard let pair = try? JSONDecoder().decode(LegacyStoredAuthTokenPair.self, from: normalizedData) else { + try persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: account) + return nil + } + return pair + } + + func writeTokenPair(_ pair: LegacyStoredAuthTokenPair, for endpoint: String) throws { + let key = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + invalidateRefresh(key) + let data = try JSONEncoder().encode(pair) + try persistence.writeRawData(data, service: LegacyAuthBridge.keychainService, account: key) + } + + func storeServerTokenResponse( + _ responseData: Data, + for endpoint: String, + nowUnixMs: Int64 + ) throws -> LegacyStoredAuthTokenPair { + let key = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + invalidateRefresh(key) + let (pair, payloadData) = try encodeTokenResponse(responseData, nowUnixMs: nowUnixMs) + try persistence.writeRawData(payloadData, service: LegacyAuthBridge.keychainService, account: key) + return pair + } + + func deleteTokenPair(for endpoint: String) throws { + let key = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + invalidateRefresh(key) + try persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: key) + } + + func validAccessToken( + for endpoint: String, + minValidity: TimeInterval, + session: URLSession + ) async throws -> LegacyStoredAuthTokenPair? { + guard let pair = try readTokenPair(for: endpoint) else { + return nil + } + if pair.accessExpiresAt.timeIntervalSinceNow > minValidity { + return pair + } + return try await refreshSession(endpoint: endpoint, session: session) + } + + func refreshSession( + endpoint: String, + session: URLSession + ) async throws -> LegacyStoredAuthTokenPair { + let key = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + if let existing = refreshTasks[key] { + return try await existing.task.value + } + guard let current = try readTokenPair(for: endpoint) else { + throw LegacyAuthBridgeError.tokenNotFound + } + let startEpoch = mutationEpochs[key, default: 0] + let opId = UUID() + let version = clientVersion + let task = Task { + do { + let data = try await LegacyAuthBridge.postSessionAction( + endpoint: endpoint, + action: "/api/auth/session/refresh", + body: ["refreshToken": current.refreshToken], + clientVersion: version, + session: session + ) + return try self.commitRefreshedResponse( + data, + key: key, + expectedEpoch: startEpoch, + nowUnixMs: Int64(Date().timeIntervalSince1970 * 1000.0) + ) + } catch let error as LegacyAuthBridgeError { + if case .httpFailure(_, permanentlyInvalidatesSession: true) = error { + self.deleteIfEpochMatches(key: key, expectedEpoch: startEpoch) + } + throw error + } + } + refreshTasks[key] = AuthRefreshOperation(id: opId, task: task) + defer { + if refreshTasks[key]?.id == opId { + refreshTasks[key] = nil + } + } + return try await task.value + } + + func prepareRevoke(endpoint: String) throws -> LegacyStoredAuthTokenPair? { + let key = LegacyAuthBridge.legacyStorageEndpointKey(endpoint) + let current = try readTokenPair(for: endpoint) + invalidateRefresh(key) + try persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: key) + return current + } + + private func commitRefreshedResponse( + _ responseData: Data, + key: String, + expectedEpoch: UInt64, + nowUnixMs: Int64 + ) throws -> LegacyStoredAuthTokenPair { + guard !Task.isCancelled, mutationEpochs[key, default: 0] == expectedEpoch else { + throw LegacyAuthBridgeError.operationCancelled + } + let (pair, payloadData) = try encodeTokenResponse(responseData, nowUnixMs: nowUnixMs) + guard !Task.isCancelled, mutationEpochs[key, default: 0] == expectedEpoch else { + throw LegacyAuthBridgeError.operationCancelled + } + try persistence.writeRawData(payloadData, service: LegacyAuthBridge.keychainService, account: key) + return pair + } + + private func deleteIfEpochMatches(key: String, expectedEpoch: UInt64) { + guard mutationEpochs[key, default: 0] == expectedEpoch else { + return + } + try? persistence.deleteRawData(service: LegacyAuthBridge.keychainService, account: key) + } + + private func invalidateRefresh(_ key: String) { + mutationEpochs[key, default: 0] &+= 1 + refreshTasks[key]?.task.cancel() + refreshTasks[key] = nil + } + + private func encodeTokenResponse( + _ responseData: Data, + nowUnixMs: Int64 + ) throws -> (LegacyStoredAuthTokenPair, Data) { + guard let responseJson = String(data: responseData, encoding: .utf8) else { + throw LegacyAuthBridgeError.invalidPayload + } + let encodedPtr = responseJson.withCString { cJson in + affine_ios_auth_encode_token_response_json(cJson, nowUnixMs) + } + guard let encodedPtr else { + throw LegacyAuthBridgeError.invalidPayload + } + defer { affine_ios_string_free(encodedPtr) } + let payloadData = Data(String(cString: encodedPtr).utf8) + let pair = try JSONDecoder().decode(LegacyStoredAuthTokenPair.self, from: payloadData) + return (pair, payloadData) + } +} + +private final class AuthBrokerRegistry: @unchecked Sendable { + static let shared = AuthBrokerRegistry() + + private let lock = NSLock() + private var defaultKeychainBroker: AuthSessionBroker? + private var customBrokers: [ObjectIdentifier: AuthSessionBroker] = [:] + + func broker( + for persistence: LegacyAuthTokenPersistence, + clientVersion: String + ) -> AuthSessionBroker { + lock.lock() + defer { lock.unlock() } + if persistence is KeychainAuthTokenPersistence { + if let existing = defaultKeychainBroker { + return existing + } + let created = AuthSessionBroker(persistence: persistence, clientVersion: clientVersion) + defaultKeychainBroker = created + return created + } + if type(of: persistence) is AnyClass { + let obj = persistence as AnyObject + let key = ObjectIdentifier(obj) + if let existing = customBrokers[key] { + return existing + } + let created = AuthSessionBroker(persistence: persistence, clientVersion: clientVersion) + customBrokers[key] = created + return created + } + return AuthSessionBroker(persistence: persistence, clientVersion: clientVersion) + } +} + +/// Native iOS Keychain (`app.affine.pro.auth-token`) and `UserDefaults` +/// (`app.affine.pro.auth-installation-id`) bridge aligned with 0.27.5 `AuthPlugin.swift`. +final class LegacyAuthBridge: @unchecked Sendable { + static let keychainService = "app.affine.pro.auth-token" + static let installationIdDefaultsKey = "app.affine.pro.auth-installation-id" + static let clientKindHeader = "x-affine-client-kind" + static let clientKindValue = "native" + static let affineVersionHeader = "x-affine-version" + static let defaultClientVersion = "0.27.5" + private static let authCookieNames: Set = [ + "affine_session", + "affine_user_id", + "affine_csrf_token", + ] + + private let userDefaults: UserDefaults + private let cookieStorage: HTTPCookieStorage + private let clearWebKitCookies: Bool + private let clientVersion: String + private let broker: AuthSessionBroker + + init( + userDefaults: UserDefaults = .standard, + persistence: LegacyAuthTokenPersistence = KeychainAuthTokenPersistence(), + cookieStorage: HTTPCookieStorage = .shared, + clearWebKitCookies: Bool = true, + bundle: Bundle = .main + ) { + self.userDefaults = userDefaults + self.cookieStorage = cookieStorage + self.clearWebKitCookies = clearWebKitCookies + let resolvedVersion = Self.resolvedClientVersion(bundle: bundle) + self.clientVersion = resolvedVersion + self.broker = AuthBrokerRegistry.shared.broker( + for: persistence, + clientVersion: resolvedVersion + ) + } + + /// Resolve `x-affine-version` from `CFBundleShortVersionString`, falling back to `"0.27.5"`. + static func resolvedClientVersion(bundle: Bundle = .main) -> String { + if let raw = bundle.infoDictionary?["CFBundleShortVersionString"] as? String { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + return trimmed + } + } + return defaultClientVersion + } + + static func canonicalEndpoint(_ endpoint: String) -> String { + let ptr = endpoint.withCString { affine_ios_auth_canonical_endpoint($0) } + guard let ptr else { return endpoint } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } + + static func legacyStorageEndpointKey(_ endpoint: String) -> String { + let ptr = endpoint.withCString { affine_ios_auth_legacy_storage_endpoint_key($0) } + guard let ptr else { return endpoint } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } + + func canonicalEndpoint(_ endpoint: String) -> String { + Self.canonicalEndpoint(endpoint) + } + + /// Reuse the existing `app.affine.pro.auth-installation-id` value without mutation, + /// generating and persisting a new lowercase UUID only on a genuine fresh install. + func installationId() -> String { + let existing = userDefaults.string(forKey: Self.installationIdDefaultsKey) + var created = false + let resolvedPtr: UnsafeMutablePointer? = existing.map { current in + current.withCString { cStr in + affine_ios_auth_resolve_installation_id(cStr, &created) + } + } ?? affine_ios_auth_resolve_installation_id(nil, &created) + + guard let resolvedPtr else { + let fallback = UUID().uuidString.lowercased() + userDefaults.set(fallback, forKey: Self.installationIdDefaultsKey) + return fallback + } + defer { affine_ios_string_free(resolvedPtr) } + let resolved = String(cString: resolvedPtr) + if created { + userDefaults.set(resolved, forKey: Self.installationIdDefaultsKey) + } + return resolved + } + + func readTokenPair(for endpoint: String) async throws -> LegacyStoredAuthTokenPair? { + try await broker.readTokenPair(for: endpoint) + } + + func writeTokenPair(_ pair: LegacyStoredAuthTokenPair, for endpoint: String) async throws { + try await broker.writeTokenPair(pair, for: endpoint) + } + + func storeServerTokenResponse( + _ responseData: Data, + for endpoint: String, + nowUnixMs: Int64 = Int64(Date().timeIntervalSince1970 * 1000.0) + ) async throws -> LegacyStoredAuthTokenPair { + try await broker.storeServerTokenResponse(responseData, for: endpoint, nowUnixMs: nowUnixMs) + } + + func deleteTokenPair(for endpoint: String) async throws { + try await broker.deleteTokenPair(for: endpoint) + } + + /// Clear local Keychain credentials, increment shared mutation epoch, and clear auth cookies + /// without issuing a network request (`AuthPlugin.swift:107-110`). + func clearSession(for endpoint: String) async throws { + try await broker.deleteTokenPair(for: endpoint) + await clearAuthCookies(for: endpoint) + } + + /// Return a valid access token pair or coalesce concurrent refreshes through the actor broker. + func validAccessToken( + for endpoint: String, + minValidity: TimeInterval = 120, + session: URLSession = .shared + ) async throws -> LegacyStoredAuthTokenPair? { + try await broker.validAccessToken(for: endpoint, minValidity: minValidity, session: session) + } + + /// Rotate tokens via `/api/auth/session/refresh` with single-flight coalescing and epoch guard. + func refreshSession( + endpoint: String, + session: URLSession = .shared + ) async throws -> LegacyStoredAuthTokenPair { + try await broker.refreshSession(endpoint: endpoint, session: session) + } + + /// Exchange an auth code using the preserved `installationId`, store tokens, and clear auth cookies. + func exchangeSession( + endpoint: String, + code: String, + deviceName: String, + session: URLSession = .shared + ) async throws -> LegacyStoredAuthTokenPair { + let body: [String: String] = [ + "code": code, + "installationId": installationId(), + "platform": "ios", + "deviceName": deviceName, + ] + let data = try await Self.postSessionAction( + endpoint: endpoint, + action: "/api/auth/session/exchange", + body: body, + clientVersion: clientVersion, + session: session + ) + let pair = try await broker.storeServerTokenResponse( + data, + for: endpoint, + nowUnixMs: Int64(Date().timeIntervalSince1970 * 1000.0) + ) + await clearAuthCookies(for: endpoint) + return pair + } + + /// Clear local Keychain credentials, increment mutation epoch, and clear auth cookies first, + /// then revoke the remote session while preserving `installationId`. + func revokeSession( + endpoint: String, + session: URLSession = .shared + ) async throws { + let current = try await broker.prepareRevoke(endpoint: endpoint) + await clearAuthCookies(for: endpoint) + guard let current else { return } + _ = try await Self.postSessionAction( + endpoint: endpoint, + action: "/api/auth/session/revoke", + body: ["refreshToken": current.refreshToken], + clientVersion: clientVersion, + session: session + ) + } + + /// Clear legacy auth cookies for the endpoint domain from both `HTTPCookieStorage` + /// and `WKWebsiteDataStore.default().httpCookieStore` without touching unrelated domains. + func clearAuthCookies(for endpoint: String) async { + guard let url = URL(string: canonicalEndpoint(endpoint)), let host = url.host else { + return + } + let normalizedHost = host.lowercased() + let matches: (HTTPCookie) -> Bool = { cookie in + let domain = cookie.domain.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) + let domainMatches = normalizedHost == domain || normalizedHost.hasSuffix(".\(domain)") + return domainMatches && Self.authCookieNames.contains(cookie.name) + } + + cookieStorage.cookies?.forEach { cookie in + if matches(cookie) { + cookieStorage.deleteCookie(cookie) + } + } + + if clearWebKitCookies { + await clearWebKitAuthCookies(matching: matches) + } + } + + @MainActor + private func clearWebKitAuthCookies(matching predicate: @escaping (HTTPCookie) -> Bool) async { + let store = WKWebsiteDataStore.default().httpCookieStore + let cookies: [HTTPCookie] = await withCheckedContinuation { continuation in + store.getAllCookies { items in + continuation.resume(returning: items) + } + } + for cookie in cookies where predicate(cookie) { + await withCheckedContinuation { (continuation: CheckedContinuation) in + store.delete(cookie) { + continuation.resume() + } + } + } + } + + fileprivate static func postSessionAction( + endpoint: String, + action: String, + body: [String: String], + clientVersion: String, + session: URLSession + ) async throws -> Data { + let base = canonicalEndpoint(endpoint) + guard let url = URL(string: "\(base)\(action)") else { + throw LegacyAuthBridgeError.invalidEndpoint + } + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.httpShouldHandleCookies = false + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue(clientKindValue, forHTTPHeaderField: clientKindHeader) + request.setValue(clientVersion, forHTTPHeaderField: affineVersionHeader) + request.httpBody = try JSONEncoder().encode(body) + request.timeoutInterval = 10 + + let (data, response) = try await session.data(for: request) + guard let httpResponse = response as? HTTPURLResponse else { + throw LegacyAuthBridgeError.httpFailure(statusCode: -1, permanentlyInvalidatesSession: false) + } + guard httpResponse.statusCode < 400 else { + let permanent: Bool + if let errorJson = String(data: data, encoding: .utf8) { + permanent = errorJson.withCString { + affine_ios_auth_error_permanently_invalidates_session($0) + } + } else { + permanent = false + } + throw LegacyAuthBridgeError.httpFailure( + statusCode: httpResponse.statusCode, + permanentlyInvalidatesSession: permanent + ) + } + return data + } +} diff --git a/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift b/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift new file mode 100644 index 0000000000..c368b9a230 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift @@ -0,0 +1,466 @@ +import Foundation +import UIKit +import WebKit + +/// Unified `WebViewStorageSentinel` payload captured from the legacy Capacitor origin. +struct LegacyLocalStorageSnapshot: Codable, Equatable { + let origin: String + let length: Int + let keys: [String] + let entries: [String: String] + let idbAccessCount: Int +} + +enum LegacyLocalStorageProbeError: Error, Equatable { + case alreadyInProgress + case invalidOrigin(String) + case invalidPayload + case indexedDbAccessForbidden(Int) + case keyNotWhitelisted(String) + case protectedKeyRemovalForbidden(String) + case writeBackMismatch(String) + case timedOut + case webViewFailure(String) + case webContentProcessTerminated +} + +private final class LegacyCapacitorSchemeHandler: NSObject, WKURLSchemeHandler { + private static let emptyHtml = Data("".utf8) + + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { + guard let url = urlSchemeTask.request.url else { + urlSchemeTask.didFailWithError(LegacyLocalStorageProbeError.invalidOrigin("missing")) + return + } + if let response = HTTPURLResponse( + url: url, + statusCode: 200, + httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "text/html; charset=utf-8"] + ) { + urlSchemeTask.didReceive(response) + urlSchemeTask.didReceive(Self.emptyHtml) + urlSchemeTask.didFinish() + } + } + + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {} +} + +/// One-shot migration sentinel and rollback writer for the legacy `capacitor://localhost` +/// origin with a hard runtime trap forbidding any IndexedDB access (`idbAccessCount == 0`). +@MainActor +final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate { + typealias TimeoutScheduler = + @MainActor (_ delaySeconds: TimeInterval, _ onTimeout: @escaping @MainActor () -> Void) -> () -> Void + + static let legacyOrigin = "capacitor://localhost" + static let probeURLString = "capacitor://localhost/__affine_probe__" + static let localWorkspaceKey = "affine-local-workspace" + /// Wall-clock ceilings for production probes. The first `WKWebView` on a cold iOS Simulator + /// can wait more than 15 s for the WebContent XPC handshake, so these budgets cover a cold + /// start. Tests that inject a `timeoutScheduler` ignore these values and complete in 0 ms. + nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 45.0 + nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 20.0 + + /// Shared warm WebContent process pool reused across probe calls to avoid cold XPC churn. + private static let sharedProcessPool = WKProcessPool() + + private static func defaultTimeoutScheduler( + delaySeconds: TimeInterval, + onTimeout: @escaping @MainActor () -> Void + ) -> () -> Void { + let clamped = max(0.1, delaySeconds) + let task = Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(clamped * 1_000_000_000)) + guard !Task.isCancelled else { + return + } + onTimeout() + } + return { task.cancel() } + } + + private static func activeForegroundWindow() -> UIWindow? { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let foregroundScenes = scenes.filter { + $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive + } + for scene in foregroundScenes + scenes { + if let key = scene.windows.first(where: { $0.isKeyWindow && !$0.isHidden }) { + return key + } + if let visible = scene.windows.first(where: { !$0.isHidden }) { + return visible + } + } + return nil + } + + /// Delegate allowlist membership directly to `affine-legacy-import` via Rust C-ABI. + static func isWhitelistedKey(_ key: String) -> Bool { + key.withCString { affine_ios_legacy_is_permitted_key($0) } + } + + /// Validate write-back mutations before touching `capacitor://localhost` `localStorage`. + static func validateWriteBackKeys(set: [String: String], remove: [String]) throws { + for key in set.keys { + guard isWhitelistedKey(key) else { + throw LegacyLocalStorageProbeError.keyNotWhitelisted(key) + } + } + for key in remove { + guard isWhitelistedKey(key) else { + throw LegacyLocalStorageProbeError.keyNotWhitelisted(key) + } + guard key != localWorkspaceKey else { + throw LegacyLocalStorageProbeError.protectedKeyRemovalForbidden(key) + } + } + } + + /// Document-start trap injected into every probe WKWebView to guarantee zero IDB access. + private static let idbGuardUserScriptSource = """ + (() => { + window.__affineIdbAccessCount = 0; + const idb = window.indexedDB; + if (!idb) { + return; + } + const trap = (methodName) => function () { + window.__affineIdbAccessCount += 1; + throw new Error("IndexedDB." + methodName + " is forbidden during legacy localStorage probe"); + }; + try { + Object.defineProperty(idb, "open", { value: trap("open"), configurable: true }); + Object.defineProperty(idb, "deleteDatabase", { value: trap("deleteDatabase"), configurable: true }); + } catch (_) { + idb.open = trap("open"); + idb.deleteDatabase = trap("deleteDatabase"); + } + })(); + """ + + private enum Mode { + case capture(allowedKeys: [String]) + case writeBack(set: [String: String], remove: [String]) + } + + private let timeoutScheduler: TimeoutScheduler + private let hostWindowProvider: () -> UIWindow? + + private var webView: WKWebView? + private var mode: Mode = .capture(allowedKeys: []) + private var continuation: CheckedContinuation? + private var cancelTimeout: (() -> Void)? + private var activeRunId: UInt64 = 0 + private var activeEvaluationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds + + init( + timeoutScheduler: TimeoutScheduler? = nil, + hostWindowProvider: (() -> UIWindow?)? = nil + ) { + self.timeoutScheduler = timeoutScheduler ?? Self.defaultTimeoutScheduler + self.hostWindowProvider = hostWindowProvider ?? Self.activeForegroundWindow + super.init() + } + + /// Capture the unified `WebViewStorageSentinel` from `capacitor://localhost`: + /// `keys` holds all sorted `localStorage` keys (`keys.count == length`), while `entries` + /// contains strictly whitelisted key-value pairs. + func capture( + allowedKeys: [String] = [], + timeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds, + navigationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultNavigationTimeoutSeconds + ) async throws -> LegacyLocalStorageSnapshot { + try await run( + mode: .capture(allowedKeys: allowedKeys), + navigationTimeoutSeconds: navigationTimeoutSeconds, + evaluationTimeoutSeconds: timeoutSeconds + ) + } + + /// Write whitelisted mutated state back to `capacitor://localhost` `localStorage` and + /// verify readback synchronously under the same zero-IndexedDB runtime guard. + func writeBackLegacyLocalStorage( + set: [String: String], + remove: [String], + timeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds, + navigationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultNavigationTimeoutSeconds + ) async throws -> LegacyLocalStorageSnapshot { + try Self.validateWriteBackKeys(set: set, remove: remove) + let snapshot = try await run( + mode: .writeBack(set: set, remove: remove), + navigationTimeoutSeconds: navigationTimeoutSeconds, + evaluationTimeoutSeconds: timeoutSeconds + ) + for (key, expected) in set { + guard snapshot.entries[key] == expected else { + throw LegacyLocalStorageProbeError.writeBackMismatch(key) + } + } + for key in remove { + guard snapshot.entries[key] == nil else { + throw LegacyLocalStorageProbeError.writeBackMismatch(key) + } + } + return snapshot + } + + private func armTimeout(seconds: TimeInterval, runId: UInt64) { + cancelTimeout?() + cancelTimeout = timeoutScheduler(seconds) { [weak self] in + self?.finish(runId: runId, result: .failure(LegacyLocalStorageProbeError.timedOut)) + } + } + + private func run( + mode: Mode, + navigationTimeoutSeconds: TimeInterval, + evaluationTimeoutSeconds: TimeInterval + ) async throws -> LegacyLocalStorageSnapshot { + guard continuation == nil else { + throw LegacyLocalStorageProbeError.alreadyInProgress + } + activeRunId &+= 1 + let currentRunId = activeRunId + self.mode = mode + self.activeEvaluationTimeoutSeconds = evaluationTimeoutSeconds + + let userContent = WKUserContentController() + let idbGuard = WKUserScript( + source: Self.idbGuardUserScriptSource, + injectionTime: .atDocumentStart, + forMainFrameOnly: true + ) + userContent.addUserScript(idbGuard) + + let configuration = WKWebViewConfiguration() + configuration.processPool = Self.sharedProcessPool + configuration.userContentController = userContent + configuration.websiteDataStore = .default() + configuration.setURLSchemeHandler(LegacyCapacitorSchemeHandler(), forURLScheme: "capacitor") + + let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: configuration) + webView.alpha = 0.0 + webView.isUserInteractionEnabled = false + webView.accessibilityElementsHidden = true + webView.navigationDelegate = self + if let hostWindow = hostWindowProvider() { + hostWindow.addSubview(webView) + } + self.webView = webView + + return try await withCheckedThrowingContinuation { continuation in + self.continuation = continuation + self.armTimeout(seconds: navigationTimeoutSeconds, runId: currentRunId) + guard self.continuation != nil else { + return + } + guard let probeURL = URL(string: Self.probeURLString) else { + self.finish( + runId: currentRunId, + result: .failure(LegacyLocalStorageProbeError.invalidOrigin(Self.legacyOrigin)) + ) + return + } + webView.load(URLRequest(url: probeURL)) + } + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + let runId = activeRunId + guard continuation != nil else { + return + } + // Start the JS evaluation safety ceiling after navigation finishes (WebContent is warm). + armTimeout(seconds: activeEvaluationTimeoutSeconds, runId: runId) + guard continuation != nil else { + return + } + + let script: String + switch mode { + case .capture(let allowedKeys): + script = buildCaptureScript(allowedKeys: allowedKeys) + case .writeBack(let setEntries, let removeKeys): + script = buildWriteBackScript(setEntries: setEntries, removeKeys: removeKeys) + } + + webView.evaluateJavaScript(script) { [weak self] result, error in + guard let self else { + return + } + if let error { + self.finish( + runId: runId, + result: .failure(LegacyLocalStorageProbeError.webViewFailure(error.localizedDescription)) + ) + return + } + guard + let jsonString = result as? String, + let data = jsonString.data(using: .utf8), + let snapshot = try? JSONDecoder().decode(LegacyLocalStorageSnapshot.self, from: data) + else { + self.finish(runId: runId, result: .failure(LegacyLocalStorageProbeError.invalidPayload)) + return + } + guard snapshot.origin == Self.legacyOrigin else { + self.finish( + runId: runId, + result: .failure(LegacyLocalStorageProbeError.invalidOrigin(snapshot.origin)) + ) + return + } + guard snapshot.idbAccessCount == 0 else { + self.finish( + runId: runId, + result: .failure( + LegacyLocalStorageProbeError.indexedDbAccessForbidden(snapshot.idbAccessCount) + ) + ) + return + } + let filteredEntries: [String: String] + switch self.mode { + case .capture(let allowedKeys) where !allowedKeys.isEmpty: + let allowSet = Set(allowedKeys) + filteredEntries = snapshot.entries.filter { allowSet.contains($0.key) } + default: + filteredEntries = snapshot.entries.filter { Self.isWhitelistedKey($0.key) } + } + let filtered = LegacyLocalStorageSnapshot( + origin: snapshot.origin, + length: snapshot.length, + keys: snapshot.keys, + entries: filteredEntries, + idbAccessCount: snapshot.idbAccessCount + ) + self.finish(runId: runId, result: .success(filtered)) + } + } + + private func buildCaptureScript(allowedKeys: [String]) -> String { + _ = allowedKeys + return """ + (() => { + const keys = []; + const entries = {}; + const total = window.localStorage.length; + for (let i = 0; i < total; i += 1) { + const k = window.localStorage.key(i); + if (k !== null) { + keys.push(k); + const v = window.localStorage.getItem(k); + if (v !== null) { + entries[k] = v; + } + } + } + keys.sort(); + return JSON.stringify({ + origin: window.location.origin, + length: total, + keys, + entries, + idbAccessCount: Number(window.__affineIdbAccessCount || 0) + }); + })() + """ + } + + private func buildWriteBackScript(setEntries: [String: String], removeKeys: [String]) -> String { + let encodedSet = encodeJson(setEntries, fallback: "{}") + let encodedRemove = encodeJson(removeKeys, fallback: "[]") + return """ + (() => { + const toSet = \(encodedSet); + const toRemove = \(encodedRemove); + for (const k of toRemove) { + if (k === "\(Self.localWorkspaceKey)") { + throw new Error("Forbidden key in write-back remove: " + k); + } + } + for (const [k, v] of Object.entries(toSet)) { + window.localStorage.setItem(k, v); + } + for (const k of toRemove) { + window.localStorage.removeItem(k); + } + const keys = []; + const entries = {}; + const total = window.localStorage.length; + for (let i = 0; i < total; i += 1) { + const k = window.localStorage.key(i); + if (k !== null) { + keys.push(k); + const v = window.localStorage.getItem(k); + if (v !== null) { + entries[k] = v; + } + } + } + keys.sort(); + return JSON.stringify({ + origin: window.location.origin, + length: total, + keys, + entries, + idbAccessCount: Number(window.__affineIdbAccessCount || 0) + }); + })() + """ + } + + private func encodeJson(_ value: T, fallback: String) -> String { + guard + let data = try? JSONEncoder().encode(value), + let json = String(data: data, encoding: .utf8) + else { + return fallback + } + return json + } + + func webView( + _ webView: WKWebView, + didFail navigation: WKNavigation!, + withError error: Error + ) { + finish( + runId: activeRunId, + result: .failure(LegacyLocalStorageProbeError.webViewFailure(error.localizedDescription)) + ) + } + + func webView( + _ webView: WKWebView, + didFailProvisionalNavigation navigation: WKNavigation!, + withError error: Error + ) { + finish( + runId: activeRunId, + result: .failure(LegacyLocalStorageProbeError.webViewFailure(error.localizedDescription)) + ) + } + + func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + finish(runId: activeRunId, result: .failure(LegacyLocalStorageProbeError.webContentProcessTerminated)) + } + + private func finish(runId: UInt64, result: Result) { + guard runId == activeRunId, let activeContinuation = continuation else { + return + } + continuation = nil + cancelTimeout?() + cancelTimeout = nil + webView?.stopLoading() + webView?.configuration.userContentController.removeAllUserScripts() + webView?.navigationDelegate = nil + webView?.removeFromSuperview() + webView = nil + activeContinuation.resume(with: result) + } +} diff --git a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift new file mode 100644 index 0000000000..2152778269 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift @@ -0,0 +1,2732 @@ +import Darwin +import QuartzCore +import UIKit +import UniformTypeIdentifiers + +@MainActor +struct IosHostStartupTiming { + static var enabled = false + + private let wallStart = DispatchTime.now().uptimeNanoseconds + private let cpuStart = clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID) + + func finish(_ label: String) { + let cpuMs = Double(clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID) - cpuStart) / 1_000_000 + let wallMs = Double(DispatchTime.now().uptimeNanoseconds - wallStart) / 1_000_000 + print(String(format: "iOS startup %@ wall_ms=%.3f cpu_ms=%.3f", label, wallMs, cpuMs)) + fflush(stdout) + } + + static func measure(_ label: String, _ makeValue: () -> Value) -> Value { + let timing = enabled ? Self() : nil + let value = makeValue() + timing?.finish(label) + return value + } +} + +private let affineBlocksuiteSnapshotUti = "pro.affine.blocksuite-snapshot" +private let affineMarkdownUti = "net.daringfireball.markdown" +private let affineHasSystemPasteboardRunLoop: Bool = (Bundle.main.bundleIdentifier != nil) +private var affineHeadlessPasteboard: [String: String] = [:] + +private func affineIosHasPasteboardContent() -> Bool { + guard affineHasSystemPasteboardRunLoop else { + return !affineHeadlessPasteboard.isEmpty + } + let pb = UIPasteboard.general + if pb.hasStrings { + return true + } + return pb.contains(pasteboardTypes: [ + affineBlocksuiteSnapshotUti, + UTType.html.identifier, + affineMarkdownUti, + UTType.utf8PlainText.identifier, + UTType.plainText.identifier, + ]) +} + +private func affineIosWriteSystemPasteboard(_ dict: [String: String]) { + var item: [String: Any] = [:] + if let plain = dict["text/plain"] { + item[UTType.utf8PlainText.identifier] = plain + item[UTType.plainText.identifier] = plain + } + if let html = dict["text/html"], let htmlData = html.data(using: .utf8) { + item[UTType.html.identifier] = htmlData + } + if let md = dict["text/markdown"], let mdData = md.data(using: .utf8) { + item[affineMarkdownUti] = mdData + } + if let snap = dict["application/x-blocksuite-snapshot"], let snapData = snap.data(using: .utf8) { + item[affineBlocksuiteSnapshotUti] = snapData + } + if !item.isEmpty { + UIPasteboard.general.setItems([item], options: [:]) + } +} + +private func affineIosClipboardWriteTrampoline( + _ utf8Ptr: UnsafePointer?, + _ utf8Len: Int, + _ userData: UnsafeMutableRawPointer? +) { + guard let utf8Ptr, utf8Len > 0 else { return } + let data = Data(bytes: utf8Ptr, count: utf8Len) + guard + let obj = try? JSONSerialization.jsonObject(with: data, options: []), + let dict = obj as? [String: String] + else { + return + } + let changeCount: Int + if affineHasSystemPasteboardRunLoop { + affineIosWriteSystemPasteboard(dict) + changeCount = UIPasteboard.general.changeCount + } else { + affineHeadlessPasteboard = dict + changeCount = 1 + } + if let userData { + let controller = Unmanaged.fromOpaque(userData).takeUnretainedValue() + controller.recordLastWrittenClipboard(dict, changeCount: changeCount) + } +} + +private func affineIosClipboardReadTrampoline( + _ sink: AffineClipboardReadSinkFn?, + _ ctx: UnsafeMutableRawPointer?, + _ userData: UnsafeMutableRawPointer? +) { + guard let sink else { return } + var dict: [String: String] = [:] + if affineHasSystemPasteboardRunLoop { + let pb = UIPasteboard.general + if let plain = pb.string, !plain.isEmpty { + dict["text/plain"] = plain + } + if let htmlData = pb.data(forPasteboardType: UTType.html.identifier), + let html = String(data: htmlData, encoding: .utf8), + !html.isEmpty + { + dict["text/html"] = html + } + if let mdData = pb.data(forPasteboardType: affineMarkdownUti), + let md = String(data: mdData, encoding: .utf8), + !md.isEmpty + { + dict["text/markdown"] = md + } + if let snapData = pb.data(forPasteboardType: affineBlocksuiteSnapshotUti), + let snap = String(data: snapData, encoding: .utf8), + !snap.isEmpty + { + dict["application/x-blocksuite-snapshot"] = snap + } + if dict.isEmpty, let userData { + let controller = Unmanaged.fromOpaque(userData).takeUnretainedValue() + if pb.changeCount == controller.lastWrittenPasteboardChangeCount { + dict = controller.lastWrittenClipboard + } + } + } else { + dict = affineHeadlessPasteboard + } + guard + !dict.isEmpty, + let encoded = try? JSONSerialization.data(withJSONObject: dict, options: []) + else { + return + } + encoded.withUnsafeBytes { raw in + if let base = raw.bindMemory(to: UInt8.self).baseAddress { + sink(base, encoded.count, ctx) + } + } +} + +final class AffineTextPosition: UITextPosition { + let utf16Offset: Int + let blockOrder: Int32 + let endpointToken: UInt64 + + init( + utf16Offset: Int, + blockOrder: Int32 = -1, + endpointToken: UInt64 = 0 + ) { + self.utf16Offset = max(0, utf16Offset) + self.blockOrder = blockOrder + self.endpointToken = endpointToken + super.init() + } + + static func from(_ raw: AffineDocPosition) -> AffineTextPosition { + AffineTextPosition( + utf16Offset: Int(raw.utf16_offset), + blockOrder: raw.block_order, + endpointToken: raw.endpoint_token + ) + } + + override func isEqual(_ object: Any?) -> Bool { + guard let other = object as? AffineTextPosition else { + return false + } + if self === other { + return true + } + if endpointToken != 0 || other.endpointToken != 0 { + return endpointToken == other.endpointToken + } + return blockOrder == other.blockOrder && utf16Offset == other.utf16Offset + } + + override var hash: Int { + var hasher = Hasher() + if endpointToken != 0 { + hasher.combine(1) + hasher.combine(endpointToken) + } else { + hasher.combine(0) + hasher.combine(blockOrder) + hasher.combine(utf16Offset) + } + return hasher.finalize() + } +} + +final class AffineTextRange: UITextRange { + let startPos: AffineTextPosition + let endPos: AffineTextPosition + + var utf16Range: NSRange { + if startPos.blockOrder == endPos.blockOrder + || startPos.blockOrder == -1 + || endPos.blockOrder == -1 + { + let lo = min(startPos.utf16Offset, endPos.utf16Offset) + let hi = max(startPos.utf16Offset, endPos.utf16Offset) + return NSRange(location: lo, length: hi - lo) + } + return NSRange(location: max(0, startPos.utf16Offset), length: 1) + } + + convenience init(utf16Range: NSRange, blockOrder: Int32 = -1) { + self.init( + startPos: AffineTextPosition(utf16Offset: utf16Range.location, blockOrder: blockOrder), + endPos: AffineTextPosition( + utf16Offset: utf16Range.location + utf16Range.length, + blockOrder: blockOrder + ) + ) + } + + init(startPos: AffineTextPosition, endPos: AffineTextPosition) { + self.startPos = startPos + self.endPos = endPos + super.init() + } + + override var start: UITextPosition { + startPos + } + + override var end: UITextPosition { + endPos + } + + override var isEmpty: Bool { + startPos.isEqual(endPos) + } + + override func isEqual(_ object: Any?) -> Bool { + guard let other = object as? AffineTextRange else { + return false + } + if self === other { + return true + } + return startPos.isEqual(other.startPos) && endPos.isEqual(other.endPos) + } + + override var hash: Int { + var hasher = Hasher() + hasher.combine(startPos.hash) + hasher.combine(endPos.hash) + return hasher.finalize() + } +} + +private final class AffineDocTextTokenizer: UITextInputStringTokenizer { + private weak var hostView: MetalHostView? + + init(hostView: MetalHostView) { + self.hostView = hostView + super.init(textInput: hostView) + } + + private func enclosingTokenRange( + for pos: AffineTextPosition, + granularity: UITextGranularity, + view: MetalHostView + ) -> AffineTextRange? { + guard pos.endpointToken != 0 else { + return nil + } + switch granularity { + case .word: + return view.wordRange(at: pos) + case .character: + return view.characterUnitRange(at: pos) + case .line: + return view.visualLineRange(at: pos) + case .paragraph, .sentence: + return view.blockParagraphRange(at: pos) + default: + return nil + } + } + + override func rangeEnclosingPosition( + _ position: UITextPosition, + with granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> UITextRange? { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + return range + } + return super.rangeEnclosingPosition(position, with: granularity, inDirection: direction) + } + + override func isPosition( + _ position: UITextPosition, + atBoundary granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> Bool { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + let backward = direction.rawValue == UITextStorageDirection.backward.rawValue + || direction.rawValue == UITextLayoutDirection.left.rawValue + return backward + ? view.compare(pos, to: range.start) == .orderedSame + : view.compare(pos, to: range.end) == .orderedSame + } + return super.isPosition(position, atBoundary: granularity, inDirection: direction) + } + + override func isPosition( + _ position: UITextPosition, + withinTextUnit granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> Bool { + if let pos = position as? AffineTextPosition, + let view = hostView, + enclosingTokenRange(for: pos, granularity: granularity, view: view) != nil + { + return true + } + return super.isPosition(position, withinTextUnit: granularity, inDirection: direction) + } + + override func position( + from position: UITextPosition, + toBoundary granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> UITextPosition? { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + let backward = direction.rawValue == UITextStorageDirection.backward.rawValue + || direction.rawValue == UITextLayoutDirection.left.rawValue + return backward ? range.startPos : range.endPos + } + return super.position(from: position, toBoundary: granularity, inDirection: direction) + } +} + +final class AffineTextSelectionRect: UITextSelectionRect { + private let selectionRect: CGRect + private let isStart: Bool + private let isEnd: Bool + private let dir: NSWritingDirection + + init( + rect: CGRect, + containsStart: Bool, + containsEnd: Bool, + writingDirection: NSWritingDirection = .leftToRight + ) { + self.selectionRect = rect + self.isStart = containsStart + self.isEnd = containsEnd + self.dir = writingDirection + super.init() + } + + override var rect: CGRect { + selectionRect + } + + override var writingDirection: NSWritingDirection { + dir + } + + override var containsStart: Bool { + isStart + } + + override var containsEnd: Bool { + isEnd + } + + override var isVertical: Bool { + false + } +} + +private final class DisplayLinkProxy: NSObject { + weak var target: MetalHostViewController? + + init(target: MetalHostViewController) { + self.target = target + super.init() + } + + @objc func onDisplayLink(_ link: CADisplayLink) { + target?.handleDisplayLinkTick(link) + } +} + +private func affineIosTextInputChangedTrampoline(_ changeKind: UInt8, _ userData: UnsafeMutableRawPointer?) { + guard let userData else { + return + } + let view = Unmanaged.fromOpaque(userData).takeUnretainedValue() + view.handleEditorTextInputStateChanged(kind: changeKind) +} + +private func affineIosFrameWakeTrampoline(_ userData: UnsafeMutableRawPointer?) { + guard let userData else { + return + } + let controller = Unmanaged.fromOpaque(userData).takeUnretainedValue() + if Thread.isMainThread { + controller.wakeDisplayLink() + } else { + DispatchQueue.main.async { [weak controller] in + controller?.wakeDisplayLink() + } + } +} + +private func affineIosOpenUrlTrampoline(_ urlUtf8: UnsafePointer?, _ userData: UnsafeMutableRawPointer?) { + guard let urlUtf8, let raw = String(validatingUTF8: urlUtf8) else { + return + } + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.hasPrefix("https://") || trimmed.hasPrefix("http://"), + let url = URL(string: trimmed) + else { + return + } + DispatchQueue.main.async { + UIApplication.shared.open(url, options: [:], completionHandler: nil) + } +} + +final class MetalHostView: UIView, UITextInput { + override class var layerClass: AnyClass { + CAMetalLayer.self + } + + var metalLayer: CAMetalLayer { + guard let metal = layer as? CAMetalLayer else { + preconditionFailure("MetalHostView requires CAMetalLayer") + } + return metal + } + + weak var inputDelegate: UITextInputDelegate? + lazy var tokenizer: UITextInputTokenizer = AffineDocTextTokenizer(hostView: self) + + var hostHandle: OpaquePointer? + var onSelectedRangeChanged: ((NSRange) -> Void)? + var onSystemSelectionApplied: (() -> Void)? + var onInteractionWake: (() -> Void)? + var onDismissEditMenu: (() -> Void)? + var onFallbackCopiedText: (() -> String?)? + var onQuerySystemGestureActive: (() -> Bool)? + var onQueryShouldLetTextInteractionOwnTouch: ((CGPoint) -> Bool)? + var onDidMoveToWindow: (() -> Void)? + private(set) var lastCopiedText: String? + private(set) var editorInputNotificationCount: Int = 0 + + private let emptyInputView = IosHostStartupTiming.measure("empty input UIView") { + UIView(frame: .zero) + } + private var lastPresentedSystemKeyboard = false + private var lastWantsCodeInput = false + private(set) var isInsideImeMutation = false + private(set) var isApplyingSystemSelection = false + private var pendingExternalChangeKind: UInt8 = 0 + private var activeTouchIds: [ObjectIdentifier: UInt64] = [:] + private var touchStartPoints: [UInt64: CGPoint] = [:] + private var touchStartTimes: [UInt64: Double] = [:] + private var touchExceededPanThreshold: Set = [] + private var touchForwardedToRust: Set = [] + private var nextTouchId: UInt64 = 1 + private(set) var lastTouchDownTimestamp: Double = 0 + private(set) var lastTouchUpTimestamp: Double = 0 + private(set) var lastTouchTapCount: Int = 1 + + private var wantsCodeInput: Bool { + guard let handle = hostHandle else { + return false + } + return affine_ios_host_wants_code_input(handle) + } + + var autocorrectionType: UITextAutocorrectionType { + get { wantsCodeInput ? .no : .default } + set {} + } + + var autocapitalizationType: UITextAutocapitalizationType { + get { wantsCodeInput ? .none : .sentences } + set {} + } + + var smartQuotesType: UITextSmartQuotesType { + get { wantsCodeInput ? .no : .default } + set {} + } + + var smartDashesType: UITextSmartDashesType { + get { wantsCodeInput ? .no : .default } + set {} + } + + var keyboardAppearance: UIKeyboardAppearance = .default + + func syncCodeInputTraitsIfNeeded() { + let next = wantsCodeInput + if next != lastWantsCodeInput { + lastWantsCodeInput = next + if isFirstResponder { + reloadInputViews() + } + } + } + + /// Authoritative UTF-16 code units read directly from Rust `PlatformInputHandler` (zero host copy). + var currentAuthoritativeUtf16Units: [UInt16] { + guard let handle = hostHandle else { + return [] + } + let len = affine_ios_host_utf16_len(handle) + guard len > 0 else { + return [] + } + var buf = Array(repeating: UInt16(0), count: len) + let copied = buf.withUnsafeMutableBufferPointer { ptr in + affine_ios_host_copy_utf16(handle, ptr.baseAddress, len) + } + if copied < len { + return Array(buf.prefix(copied)) + } + return buf + } + + private var currentAuthoritativeString: NSString { + let units = currentAuthoritativeUtf16Units + guard !units.isEmpty else { + return "" + } + return NSString(characters: units, length: units.count) + } + + var currentSelectedUtf16Range: NSRange { + guard let handle = hostHandle else { + return NSRange(location: 0, length: 0) + } + let r = affine_ios_host_selected_range(handle) + return clampRange(NSRange(location: Int(r.location), length: Int(r.length))) + } + + var currentWritingDirection: UInt8 { + guard let handle = hostHandle else { + return 0 + } + return affine_ios_host_text_writing_direction(handle) + } + + func attachTextInputObserver() { + guard let handle = hostHandle else { + return + } + let rawSelf = Unmanaged.passUnretained(self).toOpaque() + affine_ios_host_set_text_input_callback(handle, affineIosTextInputChangedTrampoline, rawSelf) + affine_ios_host_set_open_url_callback(handle, affineIosOpenUrlTrampoline, rawSelf) + } + + func detachTextInputObserver() { + guard let handle = hostHandle else { + return + } + affine_ios_host_set_text_input_callback(handle, nil, nil) + affine_ios_host_set_open_url_callback(handle, nil, nil) + } + + /// H-S2: Editor-initiated content/selection change notifies `UITextInputDelegate`. + /// Suppressed during UIKit-initiated `setSelectedTextRange:` (Single-Writer invariant). + func handleEditorTextInputStateChanged(kind: UInt8) { + if isApplyingSystemSelection { + return + } + if isInsideImeMutation { + pendingExternalChangeKind = max(pendingExternalChangeKind, kind) + return + } + notifyInputDelegate(kind: kind) + } + + private func notifyInputDelegate(kind: UInt8) { + guard !isApplyingSystemSelection else { + return + } + editorInputNotificationCount += 1 + if kind == 4 { + inputDelegate?.textWillChange(self) + inputDelegate?.selectionWillChange(self) + inputDelegate?.selectionDidChange(self) + inputDelegate?.textDidChange(self) + } else { + inputDelegate?.selectionWillChange(self) + inputDelegate?.selectionDidChange(self) + } + onSelectedRangeChanged?(currentSelectedUtf16Range) + syncCodeInputTraitsIfNeeded() + syncKeyboardInputViewIfNeeded() + if let handle = hostHandle, + !affine_ios_host_wants_software_keyboard(handle), + !affine_ios_host_document_selection_snapshot(handle).has_selection, + isFirstResponder + { + _ = resignFirstResponder() + } + } + + private var currentMarkedUtf16Range: NSRange? { + guard let handle = hostHandle else { + return nil + } + let r = affine_ios_host_marked_range(handle) + if r.location == UInt32.max { + return nil + } + return clampRange(NSRange(location: Int(r.location), length: Int(r.length))) + } + + private func expectedUnitsReplacing( + _ range: NSRange, + with replacement: [UInt16], + in before: [UInt16] + ) -> [UInt16] { + let lo = max(0, min(range.location, before.count)) + let hi = max(lo, min(range.location + range.length, before.count)) + var out: [UInt16] = [] + out.reserveCapacity(before.count - (hi - lo) + replacement.count) + out.append(contentsOf: before[.. Void + ) { + let wasInside = isInsideImeMutation + isInsideImeMutation = true + pendingExternalChangeKind = 0 + body() + isInsideImeMutation = wasInside + let pending = pendingExternalChangeKind + pendingExternalChangeKind = 0 + guard !wasInside else { + return + } + var diverged = expectedUnits == nil && expectedSelected == nil && expectedMarked == nil + if let expUnits = expectedUnits, currentAuthoritativeUtf16Units != expUnits { + diverged = true + } + if let expSel = expectedSelected, currentSelectedUtf16Range != expSel { + diverged = true + } + if let expMarked = expectedMarked, currentMarkedUtf16Range != expMarked { + diverged = true + } + if pending != 0 && diverged { + notifyInputDelegate(kind: pending) + } else { + onSelectedRangeChanged?(currentSelectedUtf16Range) + syncCodeInputTraitsIfNeeded() + } + onInteractionWake?() + } + + override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { + guard let handle = hostHandle else { + return super.canPerformAction(action, withSender: sender) + } + let mask = affine_ios_host_document_selection_snapshot(handle).action_mask + if action == #selector(copy(_:)) { + return (mask & 1) != 0 + } + if action == #selector(cut(_:)) { + return (mask & 2) != 0 + } + if action == #selector(paste(_:)) { + return (mask & 4) != 0 && affineIosHasPasteboardContent() + } + if action == #selector(selectAll(_:)) { + return (mask & 8) != 0 + } + if action == #selector(select(_:)) { + let snap = affine_ios_host_document_selection_snapshot(handle) + return snap.has_selection && snap.is_collapsed && affine_ios_host_utf16_len(handle) > 0 + } + return super.canPerformAction(action, withSender: sender) + } + + override func copy(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + affine_ios_host_selection_action_copy(handle) + lastCopiedText = onFallbackCopiedText?() + onDismissEditMenu?() + onInteractionWake?() + } + + override func cut(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + affine_ios_host_selection_action_cut(handle) + lastCopiedText = onFallbackCopiedText?() + onDismissEditMenu?() + onInteractionWake?() + } + + override func paste(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + affine_ios_host_selection_action_paste(handle) + onDismissEditMenu?() + onInteractionWake?() + } + + override func selectAll(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + affine_ios_host_selection_action_select_all(handle) + onInteractionWake?() + } + + override func select(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection { + _ = affine_ios_host_select_word_at_point( + handle, + snap.start_caret.x, + snap.start_caret.y + max(snap.start_caret.height * 0.5, 4.0) + ) + onInteractionWake?() + } + } + + override var canBecomeFirstResponder: Bool { + true + } + + override func becomeFirstResponder() -> Bool { + if let handle = hostHandle, !affine_ios_host_is_surface_readonly(handle) { + affine_ios_host_restore_software_keyboard(handle) + } + let ok = super.becomeFirstResponder() + syncKeyboardInputViewIfNeeded() + return ok + } + + override func resignFirstResponder() -> Bool { + let ok = super.resignFirstResponder() + if ok { + lastPresentedSystemKeyboard = false + } + return ok + } + + override var inputView: UIView? { + guard let handle = hostHandle else { + lastPresentedSystemKeyboard = true + return nil + } + let showSystemKeyboard = !affine_ios_host_is_surface_readonly(handle) + && affine_ios_host_wants_software_keyboard(handle) + lastPresentedSystemKeyboard = showSystemKeyboard + return showSystemKeyboard ? nil : emptyInputView + } + + func syncKeyboardInputViewIfNeeded() { + guard let handle = hostHandle else { + return + } + let wants = !affine_ios_host_is_surface_readonly(handle) + && affine_ios_host_wants_software_keyboard(handle) + if isFirstResponder && wants != lastPresentedSystemKeyboard { + reloadInputViews() + } + } + + func notifySystemSelectionUpdated() { + guard !isInsideImeMutation && !isApplyingSystemSelection else { + return + } + inputDelegate?.selectionWillChange(self) + inputDelegate?.selectionDidChange(self) + } + + var hasText: Bool { + guard let handle = hostHandle else { + return false + } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid, + sRaw.endpoint_token != 0, + eRaw.endpoint_token != 0 + { + return sRaw.endpoint_token != eRaw.endpoint_token + } + return affine_ios_host_utf16_len(handle) > 0 + } + + func insertText(_ text: String) { + guard let handle = hostHandle else { + return + } + let utf16 = Array(text.utf16) + let before = currentAuthoritativeUtf16Units + let replaceRange = currentMarkedUtf16Range ?? currentSelectedUtf16Range + let expUnits = expectedUnitsReplacing(replaceRange, with: utf16, in: before) + let expSel = NSRange(location: replaceRange.location + utf16.count, length: 0) + performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) { + utf16.withUnsafeBufferPointer { buf in + affine_ios_host_insert_text(handle, buf.baseAddress, buf.count) + } + } + } + + func deleteBackward() { + guard let handle = hostHandle else { + return + } + let before = currentAuthoritativeUtf16Units + let sel = currentSelectedUtf16Range + if sel.length > 0 { + let expUnits = expectedUnitsReplacing(sel, with: [], in: before) + let expSel = NSRange(location: sel.location, length: 0) + performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) { + affine_ios_host_delete_backward(handle) + } + } else if sel.location > 0 { + let ns = NSString(characters: before, length: before.count) + let delRange = ns.rangeOfComposedCharacterSequence(at: sel.location - 1) + let expUnits = expectedUnitsReplacing(delRange, with: [], in: before) + let expSel = NSRange(location: delRange.location, length: 0) + performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) { + affine_ios_host_delete_backward(handle) + } + } else { + performImeMutation { + affine_ios_host_delete_backward(handle) + } + } + } + + private var hasCrossBlockSelectionOnEmptyFocus: Bool { + guard let handle = hostHandle, affine_ios_host_utf16_len(handle) == 0 else { + return false + } + let snap = affine_ios_host_document_selection_snapshot(handle) + return snap.has_selection && !snap.is_collapsed + } + + private var effectiveDocumentUtf16Length: Int { + guard let handle = hostHandle else { + return 0 + } + let raw = Int(affine_ios_host_utf16_len(handle)) + if raw == 0 && hasCrossBlockSelectionOnEmptyFocus { + return 1 + } + return raw + } + + /// Single-Writer system selection apply: commits UIKit's `selectedTextRange` into Rust and + /// updates host signature/menu state WITHOUT synchronously echoing back into `inputDelegate`. + private func applySystemSelectionMutation(_ body: () -> Void) { + let wasApplying = isApplyingSystemSelection + let wasInside = isInsideImeMutation + isApplyingSystemSelection = true + isInsideImeMutation = true + pendingExternalChangeKind = 0 + body() + if !wasApplying { + onSystemSelectionApplied?() + syncCodeInputTraitsIfNeeded() + syncKeyboardInputViewIfNeeded() + } + isApplyingSystemSelection = wasApplying + isInsideImeMutation = wasInside + pendingExternalChangeKind = 0 + } + + private var currentFocusedBlockOrder: Int32 { + guard let handle = hostHandle else { + return 0 + } + return affine_ios_host_focused_block_order(handle) + } + + private func resolvedBlockOrder(for pos: AffineTextPosition) -> Int32 { + pos.blockOrder >= 0 ? pos.blockOrder : currentFocusedBlockOrder + } + + private func resolvedEndpointToken(for pos: AffineTextPosition) -> UInt64 { + if pos.endpointToken != 0 { + return pos.endpointToken + } + guard let handle = hostHandle else { + return 0 + } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_selection_positions(handle, &sRaw, &eRaw), + sRaw.valid, + sRaw.block_order == resolvedBlockOrder(for: pos) + { + let delta = pos.utf16Offset - Int(sRaw.utf16_offset) + if delta == 0 { + return sRaw.endpoint_token + } + let stepped = affine_ios_host_doc_step_position(handle, sRaw.endpoint_token, delta) + if stepped.valid { + return stepped.endpoint_token + } + } + var docStart = AffineDocPosition() + var docEnd = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &docStart, &docEnd), + docStart.valid, + pos.blockOrder <= 0 + { + if pos.utf16Offset == 0 { + return docStart.endpoint_token + } + let stepped = affine_ios_host_doc_step_position(handle, docStart.endpoint_token, pos.utf16Offset) + if stepped.valid { + return stepped.endpoint_token + } + } + return 0 + } + + func wordRange(at pos: AffineTextPosition) -> AffineTextRange? { + guard let handle = hostHandle else { + return nil + } + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + guard affine_ios_host_doc_word_range(handle, tok, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid + else { + return nil + } + return AffineTextRange(startPos: .from(sRaw), endPos: .from(eRaw)) + } + + func characterUnitRange(at pos: AffineTextPosition) -> AffineTextRange? { + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + let anchoredPos = pos.endpointToken != 0 + ? pos + : AffineTextPosition(utf16Offset: pos.utf16Offset, blockOrder: pos.blockOrder, endpointToken: tok) + if let para = blockParagraphRange(at: anchoredPos), + let paraText = text(in: para) + { + let nsText = paraText as NSString + if nsText.length == 0 { + return AffineTextRange(startPos: anchoredPos, endPos: anchoredPos) + } + let localOffset = max(0, min(anchoredPos.utf16Offset, nsText.length)) + let probeIndex = localOffset < nsText.length ? localOffset : nsText.length - 1 + let composed = nsText.rangeOfComposedCharacterSequence(at: probeIndex) + if let startPos = position(from: para.startPos, offset: composed.location) as? AffineTextPosition, + let endPos = position(from: para.startPos, offset: composed.location + composed.length) as? AffineTextPosition + { + return AffineTextRange(startPos: startPos, endPos: endPos) + } + } + if let next1 = position(from: anchoredPos, offset: 1) as? AffineTextPosition { + return AffineTextRange(startPos: anchoredPos, endPos: next1) + } + if let prev1 = position(from: anchoredPos, offset: -1) as? AffineTextPosition { + return AffineTextRange(startPos: prev1, endPos: anchoredPos) + } + return AffineTextRange(startPos: anchoredPos, endPos: anchoredPos) + } + + func blockParagraphRange(at pos: AffineTextPosition) -> AffineTextRange? { + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + let anchoredPos = pos.endpointToken != 0 + ? pos + : AffineTextPosition(utf16Offset: pos.utf16Offset, blockOrder: pos.blockOrder, endpointToken: tok) + let startPos = (position(from: anchoredPos, offset: -anchoredPos.utf16Offset) as? AffineTextPosition) ?? anchoredPos + var endPos = anchoredPos + for step in [256, 64, 16, 4, 1] { + while let next = position(from: endPos, offset: step) as? AffineTextPosition, + next.blockOrder == anchoredPos.blockOrder + { + endPos = next + } + } + return AffineTextRange(startPos: startPos, endPos: endPos) + } + + func visualLineRange(at pos: AffineTextPosition) -> AffineTextRange? { + guard let para = blockParagraphRange(at: pos) else { + return nil + } + let baseRect = caretRect(for: pos) + let tol = max(baseRect.height * 0.45, 6.0) + let curOff = pos.utf16Offset + let maxOff = para.endPos.utf16Offset + var lo = 0 + var hi = curOff + var lineStart = pos + while lo <= hi { + let mid = (lo + hi) / 2 + if let cand = position(from: para.startPos, offset: mid) as? AffineTextPosition, + abs(caretRect(for: cand).midY - baseRect.midY) <= tol + { + lineStart = cand + if mid == 0 { break } + hi = mid - 1 + } else { + lo = mid + 1 + } + } + lo = curOff + hi = maxOff + var lineEnd = pos + while lo <= hi { + let mid = (lo + hi) / 2 + if let cand = position(from: para.startPos, offset: mid) as? AffineTextPosition, + abs(caretRect(for: cand).midY - baseRect.midY) <= tol + { + lineEnd = cand + lo = mid + 1 + } else { + if mid == 0 { break } + hi = mid - 1 + } + } + return AffineTextRange(startPos: lineStart, endPos: lineEnd) + } + + func text(in range: UITextRange) -> String? { + guard let affineRange = range as? AffineTextRange else { + return nil + } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if let handle = hostHandle, sTok != 0, eTok != 0 { + if sTok == eTok { + return "" + } + if let rawPtr = affine_ios_host_doc_text_between_tokens(handle, sTok, eTok) { + defer { affine_ios_string_free(rawPtr) } + return String(cString: rawPtr) + } + return "" + } + if let handle = hostHandle, currentSelectedUtf16Range.length == 0 { + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed && !affineRange.isEmpty { + if let rawPtr = affine_ios_host_selected_plain_text(handle) { + defer { affine_ios_string_free(rawPtr) } + return String(cString: rawPtr) + } + return "\n" + } + } + let text = currentAuthoritativeString + let clamped = clampRange(affineRange.utf16Range, maxLen: text.length) + return text.substring(with: clamped) + } + + func replace(_ range: UITextRange, withText text: String) { + guard let affineRange = range as? AffineTextRange, let handle = hostHandle else { + return + } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + let focusedOrder = currentFocusedBlockOrder + if sTok != 0, + eTok != 0, + resolvedBlockOrder(for: affineRange.startPos) != focusedOrder + || resolvedBlockOrder(for: affineRange.endPos) != focusedOrder + { + performImeMutation { + _ = affine_ios_host_doc_selection_select_between_endpoint_tokens(handle, sTok, eTok) + let utf16 = Array(text.utf16) + utf16.withUnsafeBufferPointer { buf in + affine_ios_host_insert_text(handle, buf.baseAddress, buf.count) + } + } + return + } + let clamped = clampRange(affineRange.utf16Range) + let utf16 = Array(text.utf16) + let before = currentAuthoritativeUtf16Units + let expUnits = expectedUnitsReplacing(clamped, with: utf16, in: before) + performImeMutation(expectedUnits: expUnits) { + let cRange = AffineUtf16Range( + location: UInt32(clamped.location), + length: UInt32(clamped.length) + ) + utf16.withUnsafeBufferPointer { buf in + affine_ios_host_replace_range(handle, cRange, buf.baseAddress, buf.count) + } + } + } + + var selectedTextRange: UITextRange? { + get { + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_selection_positions(handle, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid + { + return AffineTextRange(startPos: .from(sRaw), endPos: .from(eRaw)) + } + } + return AffineTextRange( + utf16Range: currentSelectedUtf16Range, + blockOrder: currentFocusedBlockOrder + ) + } + set { + guard let affineRange = newValue as? AffineTextRange, let handle = hostHandle else { + return + } + let bumpMenuIfNonCollapsed = { [weak self] in + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed { + affine_ios_host_bump_selection_menu_request_seq(handle) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { + self?.onInteractionWake?() + } + } + } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if sTok != 0 && eTok != 0 { + applySystemSelectionMutation { + var curStart: UInt64 = 0 + var curEnd: UInt64 = 0 + affine_ios_host_doc_selection_endpoint_tokens(handle, &curStart, &curEnd) + let changed = !(curStart == sTok && curEnd == eTok) + _ = affine_ios_host_doc_selection_select_between_endpoint_tokens(handle, sTok, eTok) + if changed && sTok != eTok { + bumpMenuIfNonCollapsed() + } + } + return + } + let clamped = clampRange(affineRange.utf16Range) + applySystemSelectionMutation { + affine_ios_host_set_selected_range( + handle, + AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) + ) + if clamped.length > 0 { + bumpMenuIfNonCollapsed() + } + } + } + } + + var markedTextRange: UITextRange? { + guard let range = currentMarkedUtf16Range else { + return nil + } + return AffineTextRange(utf16Range: range, blockOrder: currentFocusedBlockOrder) + } + + var markedTextStyle: [NSAttributedString.Key: Any]? + + func setMarkedText(_ markedText: String?, selectedRange: NSRange) { + guard let handle = hostHandle else { + return + } + let text = markedText ?? "" + let utf16 = Array(text.utf16) + let utf16Len = utf16.count + let clampedLoc = max(0, min(selectedRange.location, utf16Len)) + let clampedLen = max(0, min(selectedRange.length, utf16Len - clampedLoc)) + let before = currentAuthoritativeUtf16Units + let replaceRange = currentMarkedUtf16Range ?? currentSelectedUtf16Range + let expUnits = expectedUnitsReplacing(replaceRange, with: utf16, in: before) + let expSel = NSRange(location: replaceRange.location + clampedLoc, length: clampedLen) + let expMarked: NSRange? = utf16.isEmpty + ? nil + : NSRange(location: replaceRange.location, length: utf16Len) + performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(expMarked)) { + let cRange = AffineUtf16Range(location: UInt32(clampedLoc), length: UInt32(clampedLen)) + utf16.withUnsafeBufferPointer { buf in + affine_ios_host_set_marked_text(handle, buf.baseAddress, buf.count, cRange) + } + } + } + + func unmarkText() { + guard let handle = hostHandle else { + return + } + performImeMutation(expectedUnits: currentAuthoritativeUtf16Units, expectedMarked: .some(nil)) { + affine_ios_host_unmark_text(handle) + } + } + + var beginningOfDocument: UITextPosition { + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), sRaw.valid { + return AffineTextPosition.from(sRaw) + } + } + return AffineTextPosition(utf16Offset: 0, blockOrder: 0) + } + + var endOfDocument: UITextPosition { + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), eRaw.valid { + return AffineTextPosition.from(eRaw) + } + } + return AffineTextPosition( + utf16Offset: effectiveDocumentUtf16Length, + blockOrder: currentFocusedBlockOrder + ) + } + + func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? { + guard + let from = fromPosition as? AffineTextPosition, + let to = toPosition as? AffineTextPosition + else { + return nil + } + if compare(from, to: to) != .orderedDescending { + return AffineTextRange(startPos: from, endPos: to) + } + return AffineTextRange(startPos: to, endPos: from) + } + + func position(from position: UITextPosition, offset: Int) -> UITextPosition? { + guard let pos = position as? AffineTextPosition else { + return nil + } + if offset == 0 { + return pos + } + if let handle = hostHandle { + let tok = resolvedEndpointToken(for: pos) + if tok != 0 { + let stepped = affine_ios_host_doc_step_position(handle, tok, offset) + return stepped.valid ? AffineTextPosition.from(stepped) : nil + } + } + let maxLen = effectiveDocumentUtf16Length + let next = pos.utf16Offset + offset + guard next >= 0 && next <= maxLen else { + return nil + } + return AffineTextPosition(utf16Offset: next, blockOrder: resolvedBlockOrder(for: pos)) + } + + func position( + from position: UITextPosition, + in direction: UITextLayoutDirection, + offset: Int + ) -> UITextPosition? { + guard let pos = position as? AffineTextPosition else { + return nil + } + if offset == 0 { + return pos + } + switch direction { + case .left: + return self.position(from: pos, offset: -offset) + case .right: + return self.position(from: pos, offset: offset) + case .up, .down: + let cr = caretRect(for: pos) + let lineStep = max(cr.height, 22.0) * CGFloat(offset) + let dy = direction == .up ? -lineStep : lineStep + return closestPosition(to: CGPoint(x: cr.midX, y: cr.midY + dy)) + @unknown default: + return self.position(from: pos, offset: offset) + } + } + + func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult { + guard + let lhs = position as? AffineTextPosition, + let rhs = other as? AffineTextPosition + else { + return .orderedSame + } + let lo = resolvedBlockOrder(for: lhs) + let ro = resolvedBlockOrder(for: rhs) + if lo != ro { + return lo < ro ? .orderedAscending : .orderedDescending + } + if lhs.utf16Offset < rhs.utf16Offset { + return .orderedAscending + } + if lhs.utf16Offset > rhs.utf16Offset { + return .orderedDescending + } + return .orderedSame + } + + func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int { + guard + let start = from as? AffineTextPosition, + let end = toPosition as? AffineTextPosition + else { + return 0 + } + let so = resolvedBlockOrder(for: start) + let eo = resolvedBlockOrder(for: end) + if so == eo { + return end.utf16Offset - start.utf16Offset + } + if let handle = hostHandle { + let sTok = resolvedEndpointToken(for: start) + let eTok = resolvedEndpointToken(for: end) + if sTok != 0 && eTok != 0 { + return Int(affine_ios_host_doc_offset_between_tokens(handle, sTok, eTok)) + } + } + return Int(eo - so) * 1024 + (end.utf16Offset - start.utf16Offset) + } + + func position( + within range: UITextRange, + farthestIn direction: UITextLayoutDirection + ) -> UITextPosition? { + guard let affineRange = range as? AffineTextRange else { + return nil + } + switch direction { + case .left, .up: + return affineRange.startPos + case .right, .down: + return affineRange.endPos + @unknown default: + return affineRange.startPos + } + } + + func characterRange( + byExtending position: UITextPosition, + in direction: UITextLayoutDirection + ) -> UITextRange? { + guard let pos = position as? AffineTextPosition else { + return nil + } + if pos.endpointToken != 0 { + switch direction { + case .left, .up: + if let start = self.position(from: pos, offset: -pos.utf16Offset) as? AffineTextPosition { + return AffineTextRange(startPos: start, endPos: pos) + } + case .right, .down: + if let para = blockParagraphRange(at: pos) { + return AffineTextRange(startPos: pos, endPos: para.endPos) + } + @unknown default: + break + } + } + let maxLen = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) + switch direction { + case .left, .up: + return AffineTextRange( + utf16Range: clampRange(NSRange(location: 0, length: pos.utf16Offset), maxLen: maxLen), + blockOrder: resolvedBlockOrder(for: pos) + ) + case .right, .down: + return AffineTextRange( + utf16Range: clampRange( + NSRange(location: pos.utf16Offset, length: max(0, maxLen - pos.utf16Offset)), + maxLen: maxLen + ), + blockOrder: resolvedBlockOrder(for: pos) + ) + @unknown default: + return nil + } + } + + func baseWritingDirection( + for position: UITextPosition, + in direction: UITextStorageDirection + ) -> NSWritingDirection { + currentWritingDirection == 1 ? .rightToLeft : .leftToRight + } + + func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} + + func firstRect(for range: UITextRange) -> CGRect { + guard let affineRange = range as? AffineTextRange else { + return .zero + } + if affineRange.isEmpty { + return caretRect(for: affineRange.startPos) + } + if let first = selectionRects(for: affineRange).first { + return first.rect + } + return caretRect(for: affineRange.startPos) + } + + func caretRect(for position: UITextPosition) -> CGRect { + guard + let pos = position as? AffineTextPosition, + let handle = hostHandle + else { + return .zero + } + let tok = resolvedEndpointToken(for: pos) + if tok != 0 { + var tokenRect = AffineRect() + if affine_ios_host_doc_caret_rect_for_token(handle, tok, &tokenRect) { + return CGRect( + x: CGFloat(tokenRect.x), + y: CGFloat(tokenRect.y), + width: CGFloat(max(tokenRect.width, 2.0)), + height: CGFloat(max(tokenRect.height, 18.0)) + ) + } + } + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && snap.is_collapsed { + if pos.utf16Offset == currentSelectedUtf16Range.location + && resolvedBlockOrder(for: pos) == currentFocusedBlockOrder + { + if !snap.start_visible { + return CGRect(x: -1000.0, y: -1000.0, width: 0.0, height: 0.0) + } + return CGRect( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y), + width: CGFloat(max(snap.start_caret.width, 2.0)), + height: CGFloat(max(snap.start_caret.height, 18.0)) + ) + } + } + let cRect = affine_ios_host_text_caret_rect(handle, UInt32(max(0, pos.utf16Offset))) + return CGRect( + x: CGFloat(cRect.x), + y: CGFloat(cRect.y), + width: CGFloat(cRect.width), + height: CGFloat(cRect.height) + ) + } + + func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { + guard + let affineRange = range as? AffineTextRange, + let handle = hostHandle + else { + return [] + } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if sTok != 0 && eTok != 0 { + if sTok == eTok { + return [] + } + let count = affine_ios_host_doc_selection_rects_between_tokens(handle, sTok, eTok, nil, 0) + if count > 0 { + var rects = Array(repeating: AffineDocumentSelectionRect(), count: count) + _ = rects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_doc_selection_rects_between_tokens( + handle, + sTok, + eTok, + buf.baseAddress, + count + ) + } + return rects.map { item in + AffineTextSelectionRect( + rect: CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ), + containsStart: item.contains_start, + containsEnd: item.contains_end, + writingDirection: item.is_rtl ? .rightToLeft : .leftToRight + ) + } + } + return [] + } + let snap = affine_ios_host_document_selection_snapshot(handle) + let cur = currentSelectedUtf16Range + let matchesActiveSelection = snap.has_selection + && !snap.is_collapsed + && snap.rect_count > 0 + && affineRange.utf16Range == cur + if matchesActiveSelection { + let count = affine_ios_host_document_selection_rects(handle, nil, 0) + if count > 0 { + var docRects = Array(repeating: AffineDocumentSelectionRect(), count: count) + _ = docRects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_document_selection_rects(handle, buf.baseAddress, count) + } + return docRects.map { item in + AffineTextSelectionRect( + rect: CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ), + containsStart: item.contains_start, + containsEnd: item.contains_end, + writingDirection: item.is_rtl ? .rightToLeft : .leftToRight + ) + } + } + } + let clamped = clampRange(affineRange.utf16Range) + guard clamped.length > 0 else { + return [] + } + let cRange = AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) + let count = affine_ios_host_text_selection_rects(handle, cRange, nil, 0) + guard count > 0 else { + return [] + } + var rawRects = Array(repeating: AffineSelectionRect(), count: count) + _ = rawRects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_text_selection_rects(handle, cRange, buf.baseAddress, count) + } + let dir: NSWritingDirection = currentWritingDirection == 1 ? .rightToLeft : .leftToRight + return rawRects.map { item in + AffineTextSelectionRect( + rect: CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ), + containsStart: item.contains_start, + containsEnd: item.contains_end, + writingDirection: dir + ) + } + } + + func closestPosition(to point: CGPoint) -> UITextPosition? { + guard let handle = hostHandle else { + return AffineTextPosition(utf16Offset: 0, blockOrder: 0) + } + let hit = affine_ios_host_doc_hit_position(handle, Float(point.x), Float(point.y)) + if hit.valid { + return AffineTextPosition.from(hit) + } + let offset = affine_ios_host_text_closest_offset( + handle, + AffinePoint(x: Float(point.x), y: Float(point.y)) + ) + return AffineTextPosition(utf16Offset: Int(offset), blockOrder: currentFocusedBlockOrder) + } + + func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { + guard let affineRange = range as? AffineTextRange else { + return closestPosition(to: point) + } + guard let pos = closestPosition(to: point) as? AffineTextPosition else { + return affineRange.endPos + } + if compare(pos, to: affineRange.startPos) == .orderedAscending { + return affineRange.startPos + } + if compare(pos, to: affineRange.endPos) == .orderedDescending { + return affineRange.endPos + } + return pos + } + + func characterRange(at point: CGPoint) -> UITextRange? { + guard let pos = closestPosition(to: point) as? AffineTextPosition else { + return nil + } + return characterUnitRange(at: pos) + } + + // MARK: - UIKit Touch & Hardware Keyboard Forwarding + + private func touchId(for touch: UITouch, remove: Bool) -> UInt64 { + let key = ObjectIdentifier(touch) + if let existing = activeTouchIds[key] { + if remove { + activeTouchIds.removeValue(forKey: key) + } + return existing + } + let assigned = nextTouchId + nextTouchId &+= 1 + if !remove { + activeTouchIds[key] = assigned + } + return assigned + } + + private static let panSlopPt: CGFloat = 10.0 + + func handleForwardedTouchCompletion(endedEditableTap: Bool = true) { + guard let handle = hostHandle else { return } + syncCodeInputTraitsIfNeeded() + syncKeyboardInputViewIfNeeded() + let requestedKb = affine_ios_host_take_software_keyboard_request(handle) + if affine_ios_host_wants_software_keyboard(handle), + !affine_ios_host_is_surface_readonly(handle) + { + if requestedKb && endedEditableTap && !isFirstResponder && window != nil { + _ = becomeFirstResponder() + } + } else if !affine_ios_host_document_selection_snapshot(handle).has_selection, + isFirstResponder + { + _ = resignFirstResponder() + } + } + override func didMoveToWindow() { + super.didMoveToWindow() + onDidMoveToWindow?() + } + + override func touchesBegan(_ touches: Set, with event: UIEvent?) { + guard let handle = hostHandle else { return } + let now = CACurrentMediaTime() + lastTouchDownTimestamp = now + for touch in touches { + lastTouchTapCount = max(1, touch.tapCount) + let loc = touch.location(in: self) + let id = touchId(for: touch, remove: false) + touchStartPoints[id] = loc + touchStartTimes[id] = now + touchExceededPanThreshold.remove(id) + touchForwardedToRust.remove(id) + if !(onQueryShouldLetTextInteractionOwnTouch?(loc) ?? true) { + touchForwardedToRust.insert(id) + affine_ios_host_touch_event(handle, id, 0, Float(loc.x), Float(loc.y)) + } + } + onInteractionWake?() + } + + override func touchesMoved(_ touches: Set, with event: UIEvent?) { + guard let handle = hostHandle else { return } + let systemGestureActive = onQuerySystemGestureActive?() ?? false + for touch in touches { + let loc = touch.location(in: self) + let id = touchId(for: touch, remove: false) + if touchForwardedToRust.contains(id) { + affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y)) + continue + } + if let start = touchStartPoints[id] { + let dx = loc.x - start.x + let dy = loc.y - start.y + if hypot(dx, dy) > Self.panSlopPt { + touchExceededPanThreshold.insert(id) + if !systemGestureActive { + touchForwardedToRust.insert(id) + affine_ios_host_touch_event(handle, id, 0, Float(start.x), Float(start.y)) + affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y)) + } + } + } + } + onInteractionWake?() + } + + override func touchesEnded(_ touches: Set, with event: UIEvent?) { + guard let handle = hostHandle else { return } + lastTouchUpTimestamp = CACurrentMediaTime() + var hadUnforwardedEditableTap = false + for touch in touches { + let loc = touch.location(in: self) + let id = touchId(for: touch, remove: true) + touchStartPoints.removeValue(forKey: id) + touchStartTimes.removeValue(forKey: id) + let exceededPan = touchExceededPanThreshold.remove(id) != nil + if touchForwardedToRust.remove(id) != nil { + affine_ios_host_touch_event(handle, id, 2, Float(loc.x), Float(loc.y)) + } else if !exceededPan { + hadUnforwardedEditableTap = true + } + } + if hadUnforwardedEditableTap, + isFirstResponder, + !affine_ios_host_is_surface_readonly(handle), + !affine_ios_host_wants_software_keyboard(handle) + { + affine_ios_host_restore_software_keyboard(handle) + } + handleForwardedTouchCompletion() + onInteractionWake?() + } + + override func touchesCancelled(_ touches: Set, with event: UIEvent?) { + guard let handle = hostHandle else { return } + for touch in touches { + let loc = touch.location(in: self) + let id = touchId(for: touch, remove: true) + touchStartPoints.removeValue(forKey: id) + touchStartTimes.removeValue(forKey: id) + touchExceededPanThreshold.remove(id) + if touchForwardedToRust.remove(id) != nil { + affine_ios_host_touch_event(handle, id, 3, Float(loc.x), Float(loc.y)) + } + } + onInteractionWake?() + } + + override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { + if markedTextRange != nil { + super.pressesBegan(presses, with: event) + return + } + guard let handle = hostHandle else { + super.pressesBegan(presses, with: event) + return + } + var handled = false + for press in presses { + guard let key = press.key else { continue } + let mods = key.modifierFlags + let shift = mods.contains(.shift) + let cmd = mods.contains(.command) + let ctrl = mods.contains(.control) + let alt = mods.contains(.alternate) + let mapped: String? + switch key.keyCode { + case .keyboardLeftArrow: mapped = "left" + case .keyboardRightArrow: mapped = "right" + case .keyboardUpArrow: mapped = "up" + case .keyboardDownArrow: mapped = "down" + case .keyboardDeleteOrBackspace: mapped = "backspace" + case .keyboardDeleteForward: mapped = "delete" + case .keyboardReturnOrEnter: mapped = "enter" + case .keyboardEscape: mapped = "escape" + case .keyboardTab: mapped = "tab" + case .keyboardZ where cmd: mapped = "z" + default: mapped = nil + } + if let name = mapped { + name.withCString { cKey in + affine_ios_host_key_down(handle, cKey, nil, shift, cmd, ctrl, alt) + } + handled = true + } + } + if handled { + onInteractionWake?() + } else { + super.pressesBegan(presses, with: event) + } + } + + private func clampRange(_ range: NSRange, maxLen: Int? = nil) -> NSRange { + let limit = maxLen ?? Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) + let loc = max(0, min(range.location, limit)) + let len = max(0, min(range.length, limit - loc)) + return NSRange(location: loc, length: len) + } +} + +private struct SelectionSyncSignature: Equatable { + let hasSelection: Bool + let isCollapsed: Bool + let isReversed: Bool + let startVisible: Bool + let endVisible: Bool + let startX: Int + let startY: Int + let startH: Int + let endX: Int + let endY: Int + let endH: Int + let rectCount: Int +} + +/// Root view that `MetalHostViewController` mounts in its Rust runtime. +enum MetalHostRoot { + /// Mobile product shell: `Home`, `Explorer`, `Journals`, `Search`, `Settings`, and `Page`. + case shell + /// One bare page editor with the showcase document. + case pageEditor +} + +final class MetalHostViewController: + UIViewController, + UITextInteractionDelegate, + UIEditMenuInteractionDelegate +{ + let root: MetalHostRoot + private var shellWorkspaceMounted = false + + init(root: MetalHostRoot = .shell) { + self.root = root + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { + root = .shell + super.init(coder: coder) + } + + private static var nowMs: Int64 { + Int64((Date().timeIntervalSince1970 * 1000).rounded()) + } + + private let hostView = MetalHostView() + private let keyboardAvoidanceCoordinator = KeyboardAvoidanceCoordinator() + private let pdfRendererBridge = PdfRendererBridge() + private let textRenderingBridge = IosHostStartupTiming.measure("TextRenderingBridge") { + TextRenderingBridge() + } + private let hapticsBridge = HapticsBridge() + private let bootstrapCoordinator = HostBootstrapCoordinator() + private let shareExtensionBridge = IosHostStartupTiming.measure("ShareExtensionBridge") { + ShareExtensionBridge() + } + private let paywallBridge = IosHostStartupTiming.measure("AffinePaywallBridge") { + AffinePaywallBridge() + } + private let onboardingSignInBridge = OnboardingSignInBridge() + private var editorMetalLayer: CAMetalLayer? + private var textInteraction: UITextInteraction? + private var textInteractionIsReadonly = false + var isTextInteractionReadonlyForTesting: Bool { textInteractionIsReadonly } + private var editMenuInteraction: UIEditMenuInteraction? + private var systemGestureStartPoint: [ObjectIdentifier: CGPoint] = [:] + private var observedSystemGestures: Set = [] + private var lastSelectionSyncSignature: SelectionSyncSignature? + private var lastPresentedMenuWasCollapsed = false + private var lastCollapsedMenuCaretKey: (Int, Int) = (-1, -1) + private(set) var presentedMenuAnchorRect: CGRect? + private var lastPresentedMenuSeq: UInt64 = 0 + private var menuSuppressedByMotion = false + private(set) var lastWrittenClipboard: [String: String] = [:] + private(set) var lastWrittenPasteboardChangeCount: Int = -1 + + func recordLastWrittenClipboard( + _ dict: [String: String], + changeCount: Int = affineHasSystemPasteboardRunLoop ? UIPasteboard.general.changeCount : 1 + ) { + lastWrittenClipboard = dict + lastWrittenPasteboardChangeCount = changeCount + } + + static func seedExternalPasteboard(_ dict: [String: String]) { + if affineHasSystemPasteboardRunLoop { + affineIosWriteSystemPasteboard(dict) + } else { + affineHeadlessPasteboard = dict + } + } + + private var lastSyncedInsets = AffineWindowInsets( + safe_top: 0, + safe_right: 0, + safe_bottom: 0, + safe_left: 0, + ime_bottom: 0 + ) + private(set) var lastBootstrapError: Error? + private var bootstrapCompleted = false + private var bootstrapTask: Task? + private var hostHandle: OpaquePointer? + private var displayLink: CADisplayLink? + private var displayLinkProxy: DisplayLinkProxy? + private var timerWakeWorkItem: DispatchWorkItem? + + var textHostView: MetalHostView { hostView } + var keyboardCoordinator: KeyboardAvoidanceCoordinator { keyboardAvoidanceCoordinator } + var haptics: HapticsBridge { hapticsBridge } + var textRenderer: TextRenderingBridge { textRenderingBridge } + var hostPointer: OpaquePointer? { hostHandle } + var shareExtension: ShareExtensionBridge { shareExtensionBridge } + var paywall: AffinePaywallBridge { paywallBridge } + var onboardingSignIn: OnboardingSignInBridge { onboardingSignInBridge } + + /// Routes incoming `affine://auth/callback?...` and `affine://share-inbox` URLs from `SceneDelegate` + /// without exposing any raw host pointers outside the view controller. + @discardableResult + func handleIncomingUrl(_ url: URL) -> Bool { + guard let handle = hostHandle else { + return false + } + guard url.scheme?.lowercased() == "affine" else { + return false + } + let hostComponent = url.host?.lowercased() ?? "" + if hostComponent == "share-inbox" { + drainPendingShareInboxInBackground() + affine_ios_host_request_frame(handle) + wakeDisplayLink() + return true + } + guard hostComponent == "auth" else { + return false + } + let handled = onboardingSignInBridge.handleOAuthCallbackUrl(url, host: handle) + if handled { + affine_ios_host_request_frame(handle) + wakeDisplayLink() + } + return handled + } + + private func drainPendingShareInboxInBackground() { + guard bootstrapCompleted else { + return + } + let preferredWorkspaceId = bootstrapCoordinator.lastSnapshot?.entries["last_workspace_id"] + let activeWorkspace = preferredWorkspaceId.flatMap { bootstrapCoordinator.workspace(id: $0) } + ?? bootstrapCoordinator.allowlistedLocalIds + .compactMap { bootstrapCoordinator.workspace(id: $0) } + .first + let mountedMap = bootstrapCoordinator.mountedWorkspacesSnapshot() + shareExtensionBridge.drainInBackground( + workspace: activeWorkspace, + mountedWorkspaces: mountedMap, + onMainThreadCompletion: { [weak self] (ingested: Int) in + guard let self, ingested > 0, let handle = self.hostHandle else { + return + } + affine_ios_host_request_frame(handle) + self.wakeDisplayLink() + } + ) + } + + override func loadView() { + let root = IosHostStartupTiming.measure("root UIView") { UIView() } + root.backgroundColor = .white + view = root + } + + override func viewDidLoad() { + let timing = IosHostStartupTiming.enabled ? IosHostStartupTiming() : nil + defer { timing?.finish("viewDidLoad") } + super.viewDidLoad() + view.backgroundColor = .white + hostView.isMultipleTouchEnabled = true + hostView.backgroundColor = .white + let initialFrame = view.bounds.inset(by: view.safeAreaInsets) + let clampedInitial = CGRect( + x: initialFrame.origin.x, + y: initialFrame.origin.y, + width: max(initialFrame.width, 1.0), + height: max(initialFrame.height, 1.0) + ) + hostView.frame = clampedInitial + view.addSubview(hostView) + + let scale = Float(view.window?.screen.scale ?? UIScreen.main.scale) + let rawLayer = Unmanaged.passUnretained(hostView.metalLayer).toOpaque() + let width = Float(max(initialFrame.width, 390.0)) + let height = Float(max(initialFrame.height, 844.0)) + let handle: OpaquePointer? + switch root { + case .shell: + let language = Locale.preferredLanguages.first ?? "en" + handle = language.withCString { tag in + affine_ios_host_create_shell( + rawLayer, + width, + height, + scale, + tag, + Self.nowMs, + Int32(TimeZone.current.secondsFromGMT() / 60), + traitCollection.userInterfaceStyle == .dark + ) + } + case .pageEditor: + handle = affine_ios_host_create(rawLayer, width, height, scale) + } + hostHandle = handle + hostView.hostHandle = handle + hostView.attachTextInputObserver() + + if let handle { + let rawSelf = Unmanaged.passUnretained(self).toOpaque() + affine_ios_host_set_frame_wake_callback(handle, affineIosFrameWakeTrampoline, rawSelf) + affine_ios_host_set_clipboard_provider( + handle, + AffineClipboardProvider( + write_json: affineIosClipboardWriteTrampoline, + read_json: affineIosClipboardReadTrampoline, + user_data: rawSelf + ) + ) + let isPad = UIDevice.current.userInterfaceIdiom == .pad + affine_ios_host_set_form_factor(handle, isPad ? 1 : 0) + if let rawEditorLayer = affine_ios_host_metal_layer(handle) { + let metalLayer = Unmanaged.fromOpaque(rawEditorLayer).takeUnretainedValue() + metalLayer.frame = hostView.bounds + metalLayer.contentsScale = CGFloat(scale) + hostView.layer.insertSublayer(metalLayer, at: 0) + editorMetalLayer = metalLayer + } + paywallBridge.attach(host: handle) + } + applyClearColor(TextRenderingBridge.defaultClearColorRgba) + + installTextInteraction(readonly: false) + let menuInteraction = UIEditMenuInteraction(delegate: self) + hostView.addInteraction(menuInteraction) + editMenuInteraction = menuInteraction + + hostView.onDidMoveToWindow = { [weak self] in + self?.attachSystemGestureObservers() + if let self, self.view.window != nil { + self.retryBootstrapIfNeeded() + } + } + hostView.onQuerySystemGestureActive = { [weak self] in + self?.isSystemSelectionGestureActive ?? false + } + hostView.onQueryShouldLetTextInteractionOwnTouch = { [weak self] point in + self?.shouldLetTextInteractionOwnTouch(at: point) ?? false + } + hostView.onSelectedRangeChanged = { [weak self] _ in + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + hostView.onSystemSelectionApplied = { [weak self] in + self?.wakeDisplayLink() + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: true) + } + hostView.onInteractionWake = { [weak self] in + self?.wakeDisplayLink() + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + hostView.onDismissEditMenu = { [weak self] in + self?.menuSuppressedByMotion = false + self?.editMenuInteraction?.dismissMenu() + self?.presentedMenuAnchorRect = nil + } + hostView.onFallbackCopiedText = { [weak self] in + self?.lastWrittenClipboard["text/plain"] + } + + keyboardAvoidanceCoordinator.hostView = hostView + keyboardAvoidanceCoordinator.hostHandle = handle + keyboardAvoidanceCoordinator.startObserving() + + if let handle { + textRenderingBridge.attach(to: handle) + pdfRendererBridge.attach(to: handle) + hapticsBridge.attach(to: handle) + hapticsBridge.prepareAll() + } + observeNotifications() + startDisplayLink() + if view.window != nil { + retryBootstrapIfNeeded() + } + } + + private func installTextInteraction(readonly: Bool) { + if let existing = textInteraction { + hostView.removeInteraction(existing) + textInteraction = nil + } + observedSystemGestures.removeAll() + systemGestureStartPoint.removeAll() + textInteractionIsReadonly = readonly + let interaction = UITextInteraction(for: readonly ? .nonEditable : .editable) + interaction.delegate = self + interaction.textInput = hostView + hostView.addInteraction(interaction) + textInteraction = interaction + attachSystemGestureObservers() + } + + private func syncTextInteractionModeIfNeeded(handle: OpaquePointer) { + let readonly = affine_ios_host_is_surface_readonly(handle) + if readonly != textInteractionIsReadonly { + installTextInteraction(readonly: readonly) + } + } + + @MainActor + func retryBootstrapIfNeeded() { + guard !bootstrapCompleted, bootstrapTask == nil else { + return + } + bootstrapTask = Task { @MainActor [weak self] in + guard let self else { + return + } + defer { self.bootstrapTask = nil } + do { + _ = try await self.bootstrapCoordinator.bootstrapFromLegacyStorage() + guard !Task.isCancelled else { return } + self.lastBootstrapError = nil + self.bootstrapCompleted = true + self.mountShellWorkspaceIfNeeded() + self.drainPendingShareInboxInBackground() + } catch { + self.lastBootstrapError = error + } + } + } + + override func viewSafeAreaInsetsDidChange() { + super.viewSafeAreaInsetsDidChange() + updateEditorMetalLayout() + sampleInsets(timestamp: CACurrentMediaTime()) + wakeDisplayLink() + } + + private func updateEditorMetalLayout() { + let scale = view.window?.screen.scale ?? UIScreen.main.scale + let editorFrame = view.bounds.inset(by: view.safeAreaInsets) + let clampedWidth = max(editorFrame.width, 1.0) + let clampedHeight = max(editorFrame.height, 1.0) + let clampedFrame = CGRect( + x: editorFrame.origin.x, + y: editorFrame.origin.y, + width: clampedWidth, + height: clampedHeight + ) + hostView.frame = clampedFrame + hostView.metalLayer.contentsScale = scale + hostView.metalLayer.drawableSize = CGSize( + width: clampedWidth * scale, + height: clampedHeight * scale + ) + if let editorLayer = editorMetalLayer { + CATransaction.begin() + CATransaction.setDisableActions(true) + editorLayer.frame = hostView.bounds + editorLayer.contentsScale = scale + CATransaction.commit() + } + if let handle = hostHandle { + affine_ios_host_resize( + handle, + Float(clampedWidth), + Float(clampedHeight), + Float(scale) + ) + } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + attachSystemGestureObservers() + updateEditorMetalLayout() + sampleInsets(timestamp: CACurrentMediaTime()) + wakeDisplayLink() + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + + private func attachSystemGestureObservers() { + let allGestures = (textInteraction?.gesturesForFailureRequirements ?? []) + + (hostView.gestureRecognizers ?? []) + for gesture in allGestures { + let className = NSStringFromClass(type(of: gesture)) + guard className.localizedCaseInsensitiveContains("loupe") else { + continue + } + let id = ObjectIdentifier(gesture) + if observedSystemGestures.insert(id).inserted { + gesture.addTarget(self, action: #selector(handleSystemTextGestureState(_:))) + } + } + } + + deinit { + bootstrapTask?.cancel() + bootstrapTask = nil + timerWakeWorkItem?.cancel() + timerWakeWorkItem = nil + displayLink?.invalidate() + keyboardAvoidanceCoordinator.stopObserving() + keyboardAvoidanceCoordinator.hostHandle = nil + NotificationCenter.default.removeObserver(self) + hostView.detachTextInputObserver() + hostView.hostHandle = nil + editorMetalLayer?.removeFromSuperlayer() + editorMetalLayer = nil + if let handle = hostHandle { + affine_ios_host_set_frame_wake_callback(handle, nil, nil) + affine_ios_host_set_clipboard_provider( + handle, + AffineClipboardProvider(write_json: nil, read_json: nil, user_data: nil) + ) + MainActor.assumeIsolated { + paywallBridge.detach() + } + textRenderingBridge.detach() + pdfRendererBridge.detach(from: handle) + hapticsBridge.detach(from: handle) + affine_ios_host_destroy(handle) + hostHandle = nil + } + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + textRenderingBridge.isDarkCanvas ? .lightContent : .darkContent + } + + private func applyClearColor(_ rgba: UInt32) { + let wasDark = textRenderingBridge.isDarkCanvas + let bg = textRenderingBridge.applyClearColorRgba(rgba) + if view.backgroundColor != bg { + view.backgroundColor = bg + } + if hostView.backgroundColor != bg { + hostView.backgroundColor = bg + } + if view.window?.backgroundColor != bg { + view.window?.backgroundColor = bg + } + let expectedStyle: UIUserInterfaceStyle = textRenderingBridge.isDarkCanvas ? .dark : .light + let targetKeyboard: UIKeyboardAppearance = textRenderingBridge.isDarkCanvas ? .dark : .light + if overrideUserInterfaceStyle != expectedStyle + || textRenderingBridge.isDarkCanvas != wasDark + || hostView.keyboardAppearance != targetKeyboard + { + overrideUserInterfaceStyle = expectedStyle + view.overrideUserInterfaceStyle = expectedStyle + hostView.overrideUserInterfaceStyle = expectedStyle + view.window?.overrideUserInterfaceStyle = expectedStyle + if hostView.keyboardAppearance != targetKeyboard { + hostView.keyboardAppearance = targetKeyboard + if hostView.isFirstResponder { + hostView.reloadInputViews() + } + } + setNeedsStatusBarAppearanceUpdate() + } + } + + /// Renders one dirty frame immediately and syncs background/dark-chrome appearance. + @discardableResult + func renderFrameNow(timestamp: Double = CACurrentMediaTime()) -> UInt32 { + guard let handle = hostHandle else { return 0 } + let clearRgba = affine_ios_host_render_frame(handle, timestamp) + if clearRgba != 0 { + applyClearColor(clearRgba) + } + return clearRgba + } + + private var isSystemSelectionGestureActive: Bool { + let gestures = textInteraction?.gesturesForFailureRequirements ?? [] + return gestures.contains { $0.state == .began || $0.state == .changed } + } + + func shouldLetTextInteractionOwnTouch(at point: CGPoint) -> Bool { + guard let handle = hostHandle else { + return false + } + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed { + if snap.start_visible { + let startDot = CGPoint( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y) - 6.0 + ) + let startStem = CGPoint( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y + snap.start_caret.height * 0.5) + ) + if hypot(point.x - startDot.x, point.y - startDot.y) <= 24.0 + || hypot(point.x - startStem.x, point.y - startStem.y) <= 20.0 + { + return true + } + } + if snap.end_visible { + let endDot = CGPoint( + x: CGFloat(snap.end_caret.x), + y: CGFloat(snap.end_caret.y + snap.end_caret.height) + 6.0 + ) + let endStem = CGPoint( + x: CGFloat(snap.end_caret.x), + y: CGFloat(snap.end_caret.y + snap.end_caret.height * 0.5) + ) + if hypot(point.x - endDot.x, point.y - endDot.y) <= 24.0 + || hypot(point.x - endStem.x, point.y - endStem.y) <= 20.0 + { + return true + } + } + } + return !affine_ios_host_should_forward_touch_immediately( + handle, + Float(point.x), + Float(point.y) + ) + } + + func interactionShouldBegin(_ interaction: UITextInteraction, at point: CGPoint) -> Bool { + shouldLetTextInteractionOwnTouch(at: point) + } + + @objc private func handleSystemTextGestureState(_ gesture: UIGestureRecognizer) { + let key = ObjectIdentifier(gesture) + let loc = gesture.location(in: hostView) + switch gesture.state { + case .began: + systemGestureStartPoint[key] = loc + editMenuInteraction?.dismissMenu() + case .ended: + let start = systemGestureStartPoint.removeValue(forKey: key) ?? loc + let moved = hypot(loc.x - start.x, loc.y - start.y) + if moved <= 12.0 { + let holdLoc = loc + DispatchQueue.main.async { [weak self] in + guard let self, let h = self.hostHandle else { return } + let postSnap = affine_ios_host_document_selection_snapshot(h) + let isReadonly = affine_ios_host_is_surface_readonly(h) + if isReadonly { + if postSnap.is_collapsed || !postSnap.has_selection { + _ = affine_ios_host_select_word_at_point(h, Float(holdLoc.x), Float(holdLoc.y)) + self.hostView.notifySystemSelectionUpdated() + } else { + affine_ios_host_bump_selection_menu_request_seq(h) + } + } else if postSnap.has_selection { + affine_ios_host_bump_selection_menu_request_seq(h) + } + self.wakeDisplayLink() + self.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + } + case .cancelled, .failed: + systemGestureStartPoint.removeValue(forKey: key) + default: + break + } + } + + func syncDocumentSelectionFromEditor(suppressInputDelegateNotification: Bool = false) { + guard let handle = hostHandle else { + return + } + syncTextInteractionModeIfNeeded(handle: handle) + hostView.syncKeyboardInputViewIfNeeded() + let snap = affine_ios_host_document_selection_snapshot(handle) + let hideReadonlyCaret = snap.has_selection + && snap.is_collapsed + && affine_ios_host_is_surface_readonly(handle) + && !isSystemSelectionGestureActive + let desiredTint: UIColor = hideReadonlyCaret ? .clear : .systemBlue + if hostView.tintColor != desiredTint { + hostView.tintColor = desiredTint + } + let hasVisibleRange = snap.has_selection + && !snap.is_collapsed + && (snap.start_visible || snap.end_visible) + if hasVisibleRange && !hostView.isFirstResponder && hostView.window != nil { + _ = hostView.becomeFirstResponder() + } + let nextSig = SelectionSyncSignature( + hasSelection: snap.has_selection, + isCollapsed: snap.is_collapsed, + isReversed: snap.is_reversed, + startVisible: snap.start_visible, + endVisible: snap.end_visible, + startX: Int((snap.start_caret.x * 4.0).rounded()), + startY: Int((snap.start_caret.y * 4.0).rounded()), + startH: Int((snap.start_caret.height * 4.0).rounded()), + endX: Int((snap.end_caret.x * 4.0).rounded()), + endY: Int((snap.end_caret.y * 4.0).rounded()), + endH: Int((snap.end_caret.height * 4.0).rounded()), + rectCount: snap.rect_count + ) + if nextSig != lastSelectionSyncSignature { + lastSelectionSyncSignature = nextSig + if !suppressInputDelegateNotification + && !hostView.isInsideImeMutation + && !hostView.isApplyingSystemSelection + && !isSystemSelectionGestureActive + && snap.has_selection + { + hostView.notifySystemSelectionUpdated() + } + } + if !snap.has_selection || snap.action_mask == 0 { + menuSuppressedByMotion = false + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + if !snap.menu_anchor_visible || snap.menu_suppressed_for_motion { + if !snap.is_collapsed + && (presentedMenuAnchorRect != nil + || menuSuppressedByMotion + || (lastPresentedMenuSeq > 0 && snap.menu_request_seq == lastPresentedMenuSeq)) + { + menuSuppressedByMotion = true + } else if snap.is_collapsed { + menuSuppressedByMotion = false + } + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + let seqAdvanced = snap.menu_request_seq != lastPresentedMenuSeq && snap.menu_request_seq > 0 + let restoreAfterMotion = menuSuppressedByMotion && !snap.is_collapsed && lastPresentedMenuSeq > 0 + let caretKey = (Int(affine_ios_host_selected_range(handle).location), Int(affine_ios_host_utf16_len(handle))) + if !seqAdvanced && snap.is_collapsed && (!lastPresentedMenuWasCollapsed || caretKey != lastCollapsedMenuCaretKey) { + menuSuppressedByMotion = false + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + let rect = CGRect( + x: CGFloat(snap.menu_anchor_rect.x), + y: CGFloat(snap.menu_anchor_rect.y), + width: CGFloat(max(snap.menu_anchor_rect.width, 2.0)), + height: CGFloat(max(snap.menu_anchor_rect.height, 2.0)) + ) + guard + !rect.isNull, + rect.origin.x.isFinite, + rect.origin.y.isFinite, + rect.size.width.isFinite, + rect.size.height.isFinite + else { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + return + } + let anchorMoved = presentedMenuAnchorRect.map { + abs($0.minX - rect.minX) > 1.0 || abs($0.minY - rect.minY) > 1.0 + } ?? false + presentedMenuAnchorRect = rect + if seqAdvanced || restoreAfterMotion { + if isSystemSelectionGestureActive { + return + } + menuSuppressedByMotion = false + lastPresentedMenuWasCollapsed = snap.is_collapsed + lastCollapsedMenuCaretKey = caretKey + guard let interaction = editMenuInteraction, hostView.window != nil else { + return + } + if seqAdvanced { + lastPresentedMenuSeq = snap.menu_request_seq + } + if !hostView.isFirstResponder { + _ = hostView.becomeFirstResponder() + } + let clampedX = min(max(rect.midX, 1.0), max(hostView.bounds.width - 1.0, 1.0)) + let clampedY = min(max(rect.minY, 1.0), max(hostView.bounds.height - 1.0, 1.0)) + let config = UIEditMenuConfiguration( + identifier: nil, + sourcePoint: CGPoint(x: clampedX, y: clampedY) + ) + DispatchQueue.main.async { [weak self, weak interaction] in + guard + let self, + let interaction, + self.hostView.window != nil, + self.presentedMenuAnchorRect != nil + else { + return + } + interaction.dismissMenu() + interaction.presentEditMenu(with: config) + } + } else if anchorMoved { + editMenuInteraction?.updateVisibleMenuPosition(animated: false) + } + } + + func editMenuInteraction( + _ interaction: UIEditMenuInteraction, + targetRectFor configuration: UIEditMenuConfiguration + ) -> CGRect { + guard + let rect = presentedMenuAnchorRect, + !rect.isNull, + rect.origin.x.isFinite, + rect.origin.y.isFinite, + rect.size.width.isFinite, + rect.size.height.isFinite + else { + return CGRect( + x: max(hostView.bounds.midX, 1.0), + y: max(hostView.bounds.midY, 1.0), + width: 1.0, + height: 1.0 + ) + } + return CGRect( + x: min(max(rect.origin.x, 0.0), max(hostView.bounds.width - 1.0, 0.0)), + y: min(max(rect.origin.y, 0.0), max(hostView.bounds.height - 1.0, 0.0)), + width: max(rect.size.width, 1.0), + height: max(rect.size.height, 1.0) + ) + } + + func editMenuInteraction( + _ interaction: UIEditMenuInteraction, + menuFor configuration: UIEditMenuConfiguration, + suggestedActions: [UIMenuElement] + ) -> UIMenu? { + nil + } + + private func startDisplayLink() { + let proxy = DisplayLinkProxy(target: self) + displayLinkProxy = proxy + let link = CADisplayLink(target: proxy, selector: #selector(DisplayLinkProxy.onDisplayLink(_:))) + link.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: 120, preferred: 120) + link.add(to: .main, forMode: .common) + displayLink = link + } + + func wakeDisplayLink() { + timerWakeWorkItem?.cancel() + timerWakeWorkItem = nil + displayLink?.isPaused = false + } + + private func pauseDisplayLinkUntilNextTimer(handle: OpaquePointer) { + let nextDelayMs = affine_ios_host_next_timer_delay_ms(handle) + if affine_ios_host_is_dirty(handle) { + displayLink?.isPaused = false + return + } + displayLink?.isPaused = true + timerWakeWorkItem?.cancel() + timerWakeWorkItem = nil + if nextDelayMs >= 0 { + let delayMs = max(16, Int(min(nextDelayMs, Int64(Int.max)))) + let work = DispatchWorkItem { [weak self] in + guard let self, let h = self.hostHandle else { return } + _ = affine_ios_host_next_timer_delay_ms(h) + if affine_ios_host_is_dirty(h) { + self.displayLink?.isPaused = false + } else { + self.pauseDisplayLinkUntilNextTimer(handle: h) + } + } + timerWakeWorkItem = work + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayMs), execute: work) + } + } + + func handleDisplayLinkTick(_ link: CADisplayLink) { + sampleInsets(timestamp: link.timestamp) + guard let handle = hostHandle else { + displayLink?.isPaused = true + return + } + if affine_ios_host_is_dirty(handle) { + let clearRgba = affine_ios_host_render_frame(handle, link.timestamp) + if clearRgba != 0 { + applyClearColor(clearRgba) + } + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + if !affine_ios_host_is_dirty(handle) { + pauseDisplayLinkUntilNextTimer(handle: handle) + } + } + + private func observeNotifications() { + let center = NotificationCenter.default + center.addObserver( + self, + selector: #selector(handleDidEnterBackground), + name: UIApplication.didEnterBackgroundNotification, + object: nil + ) + center.addObserver( + self, + selector: #selector(handleWillEnterForeground), + name: UIApplication.willEnterForegroundNotification, + object: nil + ) + center.addObserver( + self, + selector: #selector(handleKeyboardNotification), + name: UIResponder.keyboardWillChangeFrameNotification, + object: nil + ) + center.addObserver( + self, + selector: #selector(handleKeyboardNotification), + name: UIResponder.keyboardWillHideNotification, + object: nil + ) + } + + @objc private func handleKeyboardNotification() { + sampleInsets(timestamp: CACurrentMediaTime()) + wakeDisplayLink() + } + + @objc private func handleDidEnterBackground() { + timerWakeWorkItem?.cancel() + timerWakeWorkItem = nil + displayLink?.isPaused = true + flushShellWorkspace() + bootstrapCoordinator.checkpointAllPassive() + } + + /// Shows the last used, else the first, allowlisted local workspace that bootstrap mounted in + /// the shell in place of the showcase. + private func mountShellWorkspaceIfNeeded() { + let lastUsed = bootstrapCoordinator.lastSnapshot?.entries["last_workspace_id"] + let candidates = (lastUsed.map { [$0] } ?? []) + bootstrapCoordinator.allowlistedLocalIds + guard root == .shell, !shellWorkspaceMounted, let handle = hostHandle, + let spaceId = candidates.first(where: { bootstrapCoordinator.workspace(id: $0) != nil }), + let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first + else { + return + } + shellWorkspaceMounted = documents.path.withCString { base in + spaceId.withCString { id in + affine_ios_host_shell_mount_workspace(handle, base, "workspace", "local", id, id, Self.nowMs) + } + } + affine_ios_host_request_frame(handle) + wakeDisplayLink() + } + + /// Lets the shell follow the system appearance while the app runs. + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + super.traitCollectionDidChange(previousTraitCollection) + guard root == .shell, let handle = hostHandle, + traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle + else { + return + } + affine_ios_host_set_dark_theme(handle, traitCollection.userInterfaceStyle == .dark) + wakeDisplayLink() + } + + /// Commits the shell's local changes to its SQLite workspace. + func flushShellWorkspace() { + guard shellWorkspaceMounted, let handle = hostHandle else { + return + } + _ = affine_ios_host_shell_flush_workspace(handle) + } + + @objc private func handleWillEnterForeground() { + shareExtensionBridge.resetFailedBackoff() + drainPendingShareInboxInBackground() + if let handle = hostHandle { + affine_ios_host_request_frame(handle) + } + wakeDisplayLink() + } + + func sampleInsets(timestamp: Double) { + let next = keyboardAvoidanceCoordinator.sampleDisplayLinkFrame( + timestamp: timestamp, + safeAreaInsets: view.safeAreaInsets + ) + let changed = next.safe_top != lastSyncedInsets.safe_top + || next.safe_right != lastSyncedInsets.safe_right + || next.safe_bottom != lastSyncedInsets.safe_bottom + || next.safe_left != lastSyncedInsets.safe_left + || next.ime_bottom != lastSyncedInsets.ime_bottom + if changed { + lastSyncedInsets = next + wakeDisplayLink() + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/OnboardingSignInBridge.swift b/packages/frontend/hosts/ios/Sources/OnboardingSignInBridge.swift new file mode 100644 index 0000000000..224e15c028 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/OnboardingSignInBridge.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Zero-CocoaPods Onboarding + Native Sign-In narrow bridge. +/// +/// Enforces the two-stage sign-in state machine in Rust without issuing network requests directly: +/// 1. Stage 1 (`pending_exchange`): validates CSRF `state` (OAuth deep-link callback) or compact +/// 3-segment JWS (Sign in with Apple) in Rust without prematurely marking sign-in completed. +/// 2. Stage 2 (`completed` / `sign_in_choice`): records the verified session subject via +/// `confirmSessionExchange` or resets on error via `failSessionExchange`. +@MainActor +final class OnboardingSignInBridge { + /// Begins OAuth flow with CSRF state registered in Rust (`authenticating`). + func beginOAuth(host: OpaquePointer, csrfState: String) -> Bool { + csrfState.withCString { affine_ios_island_onboarding_begin_oauth(host, $0) } + } + + /// Stage 1: handles `affine://auth/callback?code=...&state=...` deep link, verifies CSRF state in + /// Rust, and transitions into `pending_exchange` without marking sign-in completed prematurely. + func handleOAuthCallbackUrl(_ url: URL, host: OpaquePointer) -> Bool { + guard + let components = URLComponents(url: url, resolvingAgainstBaseURL: false), + let items = components.queryItems, + let code = items.first(where: { $0.name == "code" })?.value, + let state = items.first(where: { $0.name == "state" })?.value + else { + return false + } + return code.withCString { cCode in + state.withCString { cState in + affine_ios_island_onboarding_complete_oauth(host, cCode, cState) + } + } + } + + /// Records a verified Apple Sign-In credential into `pending_exchange` awaiting session confirmation. + func completeAppleCredential( + host: OpaquePointer, + userIdentifier: String, + identityTokenJws: String + ) -> Bool { + userIdentifier.withCString { cUid in + identityTokenJws.withCString { cJws in + affine_ios_island_onboarding_complete_apple(host, cUid, cJws) + } + } + } + + /// Finalizes session exchange with the verified user `subject` (`completed`). + func confirmSessionExchange(host: OpaquePointer, subject: String) -> Bool { + subject.withCString { affine_ios_island_onboarding_confirm_session(host, $0) } + } + + /// Marks session exchange as failed (`sign_in_choice`) so the user can retry. + func failSessionExchange(host: OpaquePointer, reason: String) -> Bool { + reason.withCString { affine_ios_island_onboarding_fail_session(host, $0) } + } + + func stateJson(host: OpaquePointer) -> String { + guard let ptr = affine_ios_island_onboarding_state_json(host) else { + return "{}" + } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } +} diff --git a/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift b/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift new file mode 100644 index 0000000000..b2e0aa1d04 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift @@ -0,0 +1,327 @@ +import CoreGraphics +import Foundation +import PDFKit + +enum PdfRendererError: Error, Equatable { + case invalidArgument + case emptyDocument + case documentTooLarge + case invalidOrEncryptedPdf + case pathOutsideAllowedDirectory + case pageOutOfRange + case invalidDimensions + case pixelLimitExceeded + case renderFailed +} + +struct PdfDocumentHandle { + let document: PDFDocument + + var pageCount: Int { + document.pageCount + } +} + +struct PdfRenderedPage: Equatable { + let widthPx: Int + let heightPx: Int + let rgba8: Data +} + +/// Native iOS `PDFKit` page renderer bridge (zero C++ PDFium dependency). +/// Shares header, page-bounds, and OOM pixel-budget invariants with Rust `src/pdf.rs` +/// and manages explicit open/close document handles with zero persistent cache. +final class PdfRendererBridge { + static let maxDocumentBytes = 128 * 1024 * 1024 + + private let handleLock = NSLock() + private var nextDocId: UInt64 = 1 + private var openDocuments: [UInt64: PdfDocumentHandle] = [:] + + var openDocumentCount: Int { + handleLock.lock() + defer { handleLock.unlock() } + return openDocuments.count + } + + func open(data: Data) throws -> PdfDocumentHandle { + let validationCode = data.withUnsafeBytes { rawBuf -> UInt32 in + let ptr = rawBuf.bindMemory(to: UInt8.self).baseAddress + return affine_ios_pdf_validate_bytes(ptr, data.count) + } + if validationCode != 0 { + throw mapErrorCode(validationCode) + } + // Check `!doc.isLocked` (not `!doc.isEncrypted`) so PDFs with only an owner + // permission password and no user reading password still open cleanly. + guard let doc = PDFDocument(data: data), !doc.isLocked, doc.pageCount > 0 else { + throw PdfRendererError.invalidOrEncryptedPdf + } + return PdfDocumentHandle(document: doc) + } + + /// Open a PDF from a controlled local file path strictly contained inside `allowedDirectory`. + func open(fileURL: URL, allowedDirectory: URL) throws -> PdfDocumentHandle { + guard fileURL.isFileURL, allowedDirectory.isFileURL else { + throw PdfRendererError.invalidArgument + } + let canonicalRoot = allowedDirectory.standardizedFileURL.resolvingSymlinksInPath() + let canonicalFile = fileURL.standardizedFileURL.resolvingSymlinksInPath() + let rootPrefix = canonicalRoot.path.hasSuffix("/") ? canonicalRoot.path : canonicalRoot.path + "/" + guard canonicalFile.path.hasPrefix(rootPrefix) else { + throw PdfRendererError.pathOutsideAllowedDirectory + } + let attrs = try FileManager.default.attributesOfItem(atPath: canonicalFile.path) + if let fileSize = attrs[.size] as? NSNumber, fileSize.intValue > Self.maxDocumentBytes { + throw PdfRendererError.documentTooLarge + } + let data = try Data(contentsOf: canonicalFile, options: [.mappedIfSafe]) + return try open(data: data) + } + + /// Return the displayed `.cropBox` size in PDF points after applying `/Rotate`. + func pageSizePoints(of handle: PdfDocumentHandle, pageIndex: Int) throws -> CGSize { + guard pageIndex >= 0, pageIndex < handle.pageCount, let page = handle.document.page(at: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + let shownSize = displayedPageSize(page) + guard shownSize.width > 0, shownSize.height > 0 else { + throw PdfRendererError.invalidDimensions + } + return shownSize + } + + /// Rasterize a single PDF page onto a white anti-aliased RGBA8 canvas. + func renderPageRgba8( + of handle: PdfDocumentHandle, + pageIndex: Int, + targetWidthPx: Int, + targetHeightPx: Int + ) throws -> PdfRenderedPage { + guard pageIndex >= 0, let pageIdx32 = UInt32(exactly: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + guard targetWidthPx >= 0, targetHeightPx >= 0 else { + throw PdfRendererError.invalidDimensions + } + guard + let width32 = UInt32(exactly: targetWidthPx), + let height32 = UInt32(exactly: targetHeightPx) + else { + throw PdfRendererError.pixelLimitExceeded + } + let plan = affine_ios_pdf_plan_render( + pageIdx32, + UInt32(handle.pageCount), + width32, + height32 + ) + if plan.error != 0 { + throw mapErrorCode(plan.error) + } + guard let page = handle.document.page(at: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + var rgba = Data(count: plan.byte_len) + let ok = rgba.withUnsafeMutableBytes { rawBuf -> Bool in + guard let base = rawBuf.baseAddress else { + return false + } + return rasterizePage( + page, + widthPx: Int(plan.target_width_px), + heightPx: Int(plan.target_height_px), + into: base, + byteLen: plan.byte_len + ) + } + guard ok else { + throw PdfRendererError.renderFailed + } + return PdfRenderedPage( + widthPx: Int(plan.target_width_px), + heightPx: Int(plan.target_height_px), + rgba8: rgba + ) + } + + /// Register this bridge as the explicit-handle C-ABI `AffinePdfProvider` on `host`. + func attach(to host: OpaquePointer) { + let provider = AffinePdfProvider( + open_doc: { pdfPtr, pdfLen, userData in + guard let pdfPtr, pdfLen > 0, let userData else { + return 0 + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + // Copy into owned Data once on open; freed immediately on `close_doc`. + let owned = Data(bytes: pdfPtr, count: pdfLen) + guard let handle = try? bridge.open(data: owned) else { + return 0 + } + return bridge.insertDocument(handle) + }, + close_doc: { docId, userData in + guard docId != 0, let userData else { + return + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + bridge.removeDocument(id: docId) + }, + doc_page_count: { docId, userData in + guard docId != 0, let userData else { + return 0 + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard let handle = bridge.lookupDocument(id: docId) else { + return 0 + } + return UInt32(handle.pageCount) + }, + doc_page_size: { docId, pageIndex, outSize, userData in + guard docId != 0, let outSize, let userData else { + return false + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard + let handle = bridge.lookupDocument(id: docId), + let size = try? bridge.pageSizePoints(of: handle, pageIndex: Int(pageIndex)) + else { + return false + } + outSize.pointee = AffinePdfPageSize( + width_pt: Float(size.width), + height_pt: Float(size.height) + ) + return true + }, + doc_render_rgba8: { docId, pageIndex, widthPx, heightPx, outRgbaPtr, outRgbaLen, userData in + guard docId != 0, let outRgbaPtr, outRgbaLen > 0, let userData else { + return false + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard + let handle = bridge.lookupDocument(id: docId), + let page = handle.document.page(at: Int(pageIndex)) + else { + return false + } + return bridge.rasterizePage( + page, + widthPx: Int(widthPx), + heightPx: Int(heightPx), + into: outRgbaPtr, + byteLen: outRgbaLen + ) + }, + user_data: Unmanaged.passUnretained(self).toOpaque() + ) + affine_ios_host_set_pdf_provider(host, provider) + } + + func detach(from host: OpaquePointer) { + let empty = AffinePdfProvider( + open_doc: nil, + close_doc: nil, + doc_page_count: nil, + doc_page_size: nil, + doc_render_rgba8: nil, + user_data: nil + ) + affine_ios_host_set_pdf_provider(host, empty) + handleLock.lock() + openDocuments.removeAll() + handleLock.unlock() + } + + private func insertDocument(_ handle: PdfDocumentHandle) -> UInt64 { + handleLock.lock() + defer { handleLock.unlock() } + let id = nextDocId + nextDocId &+= 1 + if nextDocId == 0 { + nextDocId = 1 + } + openDocuments[id] = handle + return id + } + + private func lookupDocument(id: UInt64) -> PdfDocumentHandle? { + handleLock.lock() + defer { handleLock.unlock() } + return openDocuments[id] + } + + private func removeDocument(id: UInt64) { + handleLock.lock() + openDocuments.removeValue(forKey: id) + handleLock.unlock() + } + + private func displayedPageSize(_ page: PDFPage) -> CGSize { + let box = page.bounds(for: .cropBox) + let rot = ((page.rotation % 360) + 360) % 360 + return (rot == 90 || rot == 270) + ? CGSize(width: box.height, height: box.width) + : box.size + } + + private func rasterizePage( + _ page: PDFPage, + widthPx: Int, + heightPx: Int, + into buffer: UnsafeMutableRawPointer, + byteLen: Int + ) -> Bool { + let expectedBytes = widthPx * heightPx * 4 + guard widthPx > 0, heightPx > 0, byteLen == expectedBytes else { + return false + } + let shownSize = displayedPageSize(page) + guard shownSize.width > 0, shownSize.height > 0 else { + return false + } + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmapInfo = + CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + guard let ctx = CGContext( + data: buffer, + width: widthPx, + height: heightPx, + bitsPerComponent: 8, + bytesPerRow: widthPx * 4, + space: colorSpace, + bitmapInfo: bitmapInfo + ) else { + return false + } + ctx.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) + ctx.fill(CGRect(x: 0, y: 0, width: widthPx, height: heightPx)) + ctx.setAllowsAntialiasing(true) + ctx.setShouldAntialias(true) + ctx.interpolationQuality = .high + + // `PDFPage.draw(with: .cropBox, to:)` already applies `-cropBox.origin` translation + // and `/Rotate` transforms; apply only the target pixel scale factor here. + ctx.saveGState() + ctx.scaleBy( + x: CGFloat(widthPx) / shownSize.width, + y: CGFloat(heightPx) / shownSize.height + ) + page.draw(with: .cropBox, to: ctx) + ctx.restoreGState() + return true + } + + private func mapErrorCode(_ code: UInt32) -> PdfRendererError { + switch code { + case 1: return .invalidArgument + case 2: return .emptyDocument + case 3: return .documentTooLarge + case 4: return .invalidOrEncryptedPdf + case 5: return .pageOutOfRange + case 6: return .invalidDimensions + case 7: return .pixelLimitExceeded + default: return .renderFailed + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/ShareExtensionBridge.swift b/packages/frontend/hosts/ios/Sources/ShareExtensionBridge.swift new file mode 100644 index 0000000000..abb0f90dfe --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/ShareExtensionBridge.swift @@ -0,0 +1,619 @@ +import CryptoKit +import Foundation + +/// 1:1 mirror of `packages/frontend/apps/ios/App/Shared/ShareInbox/ShareInboxModels.swift` +/// so the thin iOS host consumes the exact files written by the shipping ShareExtension +/// under `/ShareInbox/.json` and +/// `ShareInbox/Attachments//`. +struct ShareInboxAttachment: Codable, Equatable { + var fileName: String + var mimeType: String + /// Relative to `ShareInbox/Attachments/` (i.e. `"/"`). + var relativePath: String +} + +enum ShareInboxContentKind: String, Codable { + case url + case text + case image + case pdf +} + +struct ShareInboxContent: Codable, Equatable { + var kind: ShareInboxContentKind + var url: String? + var text: String? +} + +struct ShareInboxTarget: Codable, Equatable { + var workspaceId: String + var workspaceFlavour: String + var tagIds: [String] + var collectionId: String? +} + +struct ShareInboxResult: Codable, Equatable { + var docId: String + var committedAt: Date +} + +struct ShareInboxItem: Codable, Equatable { + static let currentSchemaVersion = 2 + + var schemaVersion: Int + var importAttemptId: String + var id: String + var documentId: String + var createdAt: Date + var title: String + var content: ShareInboxContent + var target: ShareInboxTarget? + var previewRoute: String? + var previewText: String? + var attachments: [ShareInboxAttachment] + var result: ShareInboxResult? + var lastError: String? + + enum CodingKeys: String, CodingKey { + case schemaVersion + case importAttemptId + case id + case documentId + case createdAt + case title + case content + case target + case previewRoute + case previewText + case attachments + case result + case lastError + } + + init( + id: String = UUID().uuidString, + documentId: String = UUID().uuidString, + importAttemptId: String = UUID().uuidString, + createdAt: Date = Date(), + title: String, + content: ShareInboxContent, + target: ShareInboxTarget? = nil, + previewRoute: String? = "deferred", + previewText: String? = nil, + attachments: [ShareInboxAttachment] = [], + result: ShareInboxResult? = nil, + lastError: String? = nil + ) { + self.schemaVersion = Self.currentSchemaVersion + self.importAttemptId = importAttemptId + self.id = id + self.documentId = documentId + self.createdAt = createdAt + self.title = title + self.content = content + self.target = target + self.previewRoute = previewRoute + self.previewText = previewText + self.attachments = attachments + self.result = result + self.lastError = lastError + } + + /// Matches `ShareInboxModels.swift:123-152`: supports schemaVersion 1 (defaults missing + /// `importAttemptId` & optional fields) and schemaVersion 2 (requires non-empty `importAttemptId`). + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let schemaVersion = try container.decodeIfPresent(Int.self, forKey: .schemaVersion) ?? 1 + self.schemaVersion = schemaVersion + if schemaVersion == 1 { + importAttemptId = UUID().uuidString + } else { + let importAttemptId = try container.decode(String.self, forKey: .importAttemptId) + guard !importAttemptId.isEmpty else { + throw DecodingError.dataCorruptedError( + forKey: .importAttemptId, + in: container, + debugDescription: "importAttemptId must not be empty" + ) + } + self.importAttemptId = importAttemptId + } + id = try container.decode(String.self, forKey: .id) + documentId = try container.decode(String.self, forKey: .documentId) + createdAt = try container.decode(Date.self, forKey: .createdAt) + title = try container.decode(String.self, forKey: .title) + content = try container.decode(ShareInboxContent.self, forKey: .content) + target = try container.decodeIfPresent(ShareInboxTarget.self, forKey: .target) + previewRoute = (try? container.decodeIfPresent(String.self, forKey: .previewRoute)) ?? "deferred" + previewText = try container.decodeIfPresent(String.self, forKey: .previewText) + attachments = + try container.decodeIfPresent([ShareInboxAttachment].self, forKey: .attachments) ?? [] + result = try container.decodeIfPresent(ShareInboxResult.self, forKey: .result) + lastError = try container.decodeIfPresent(String.self, forKey: .lastError) + } +} + +private struct ShareIngestAttachmentSpecPayload: Encodable { + let blob_key: String + let file_name: String + let mime_type: String + let byte_offset: Int + let byte_len: Int +} + +private struct ShareIngestRequestPayload: Encodable { + let share_id: String + let import_attempt_id: String + let doc_id: String + let kind: String + let title: String + let text_or_url: String + let secondary_text: String + let tag_ids: [String] + let collection_id: String? + let attachments: [ShareIngestAttachmentSpecPayload] + let client_id: UInt64 + let now_ms: Int64 +} + +private struct ShareIngestOutcomePayload: Decodable { + let already_committed: Bool + let doc_id: String + let inserted_text: String + let blob_keys: [String] +} + +/// Zero-CocoaPods App Group ShareExtension inbox coordinator. +/// Consumes `/ShareInbox/.json` and +/// `ShareInbox/Attachments//` through a single atomic Rust SQLite transaction +/// (`blobs` + `updates` + `clocks` + `db$docProperties` + `share_ingest_receipts`). +final class ShareExtensionBridge: @unchecked Sendable { + static let appGroupIdentifier = "group.app.affine.pro" + static let unbundledStorageDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-\(UUID().uuidString)", isDirectory: true) + + static let inboxDirectoryName = "ShareInbox" + static let attachmentsDirectoryName = "Attachments" + static let invalidDirectoryName = "Invalid" + static let maxShareAttachmentBytes = 64 * 1024 * 1024 + /// Cooldown before retrying an unchanged failing manifest within the same foreground stay; + /// `resetFailedBackoff()` clears it immediately on foreground entry or workspace mount change. + static let failureRetryCooldownSec: TimeInterval = 5.0 + + private let inboxDirectory: URL + private let lock = NSLock() + private var drainInFlight = false + /// Tracks `(manifestPath -> (modDate, failedAt))` so large failing attachments are not tight-looped + /// within the same 5 s window while still recovering automatically after cooldown or foreground re-entry. + private var failedManifestBackoff: [String: (modDate: Date, failedAt: Date)] = [:] + + /// Optional test hook overriding the post-commit passive WAL checkpoint step. + var checkpointHook: ((WorkspaceStorageBridge) -> Bool)? + + private static func makeEncoder() -> JSONEncoder { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return encoder + } + + private static func makeDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + } + + /// Computes 44-char padded base64url SHA-256 matching `0.27.5` `blobSync.set` (`import.ts:212`). + static func sha256Base64Url(_ data: Data) -> String { + let digest = SHA256.hash(data: data) + return Data(digest) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + } + + init(inboxDirectory: URL? = nil) { + if let inboxDirectory { + self.inboxDirectory = inboxDirectory + } else if Bundle.main.bundleIdentifier == nil { + self.inboxDirectory = Self.unbundledStorageDirectory + .appendingPathComponent(Self.inboxDirectoryName, isDirectory: true) + } else if let groupUrl = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: Self.appGroupIdentifier + ) { + self.inboxDirectory = groupUrl.appendingPathComponent( + Self.inboxDirectoryName, + isDirectory: true + ) + } else { + self.inboxDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent(Self.inboxDirectoryName, isDirectory: true) + } + } + + var attachmentsDirectory: URL { + inboxDirectory.appendingPathComponent(Self.attachmentsDirectoryName, isDirectory: true) + } + + var invalidDirectory: URL { + inboxDirectory.appendingPathComponent(Self.invalidDirectoryName, isDirectory: true) + } + + /// Clears in-memory failed-manifest backoff (used on foreground entry, workspace mounts, or retry tests). + func resetFailedBackoff() { + lock.lock() + failedManifestBackoff.removeAll() + lock.unlock() + } + + /// Resolves an attachment `relativePath` (relative to `ShareInbox/Attachments/`, + /// e.g. `"/"`) and enforces strict symlink-resolved containment. + func safeAttachmentURL(relativePath: String) -> URL? { + let cleaned = relativePath.trimmingCharacters(in: .whitespacesAndNewlines) + guard + !cleaned.isEmpty, + !cleaned.hasPrefix("/"), + !cleaned.split(separator: "/").contains("..") + else { + return nil + } + let base = attachmentsDirectory.standardizedFileURL + let candidate = base.appendingPathComponent(cleaned).standardizedFileURL + let resolvedBase = base.resolvingSymlinksInPath().standardizedFileURL + let resolvedCandidate = candidate.resolvingSymlinksInPath().standardizedFileURL + guard + candidate.path.hasPrefix(base.path + "/"), + resolvedCandidate.path.hasPrefix(resolvedBase.path + "/") + else { + return nil + } + return candidate + } + + private func itemAttachmentsDirectory(itemId: String) -> URL? { + let cleaned = itemId.trimmingCharacters(in: .whitespacesAndNewlines) + guard + !cleaned.isEmpty, + !cleaned.contains("/"), + cleaned != ".", + cleaned != ".." + else { + return nil + } + return attachmentsDirectory.appendingPathComponent(cleaned, isDirectory: true) + } + + /// Atomically writes one canonical `ShareInbox/.json` item and optional attachments + /// under `ShareInbox/Attachments/` (`"/"`). + func stageItem(_ item: ShareInboxItem, attachmentBlobs: [String: Data] = [:]) throws -> URL { + let fm = FileManager.default + try fm.createDirectory(at: inboxDirectory, withIntermediateDirectories: true) + if !attachmentBlobs.isEmpty { + try fm.createDirectory(at: attachmentsDirectory, withIntermediateDirectories: true) + for (relativePath, blob) in attachmentBlobs { + guard let dest = safeAttachmentURL(relativePath: relativePath) else { + continue + } + try fm.createDirectory( + at: dest.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try blob.write(to: dest, options: .atomic) + } + } + let sanitizedId = item.id.replacingOccurrences(of: "/", with: "_") + let target = inboxDirectory.appendingPathComponent("\(sanitizedId).json") + let data = try Self.makeEncoder().encode(item) + try data.write(to: target, options: .atomic) + lock.lock() + failedManifestBackoff.removeValue(forKey: target.path) + lock.unlock() + return target + } + + private static func peekSchemaVersion(from data: Data) -> Int? { + guard + let obj = try? JSONSerialization.jsonObject(with: data, options: []), + let dict = obj as? [String: Any] + else { + return nil + } + if let version = dict["schemaVersion"] as? Int { + return version + } + if dict["schemaVersion"] == nil { + return 1 + } + return nil + } + + private func quarantineManifest(at url: URL) { + let fm = FileManager.default + try? fm.createDirectory(at: invalidDirectory, withIntermediateDirectories: true) + let dest = invalidDirectory.appendingPathComponent(url.lastPathComponent) + try? fm.removeItem(at: dest) + do { + try fm.moveItem(at: url, to: dest) + } catch { + try? fm.removeItem(at: url) + } + } + + private func cleanupConsumedItem(manifestUrl: URL, item: ShareInboxItem) { + let fm = FileManager.default + lock.lock() + failedManifestBackoff.removeValue(forKey: manifestUrl.path) + lock.unlock() + try? fm.removeItem(at: manifestUrl) + if let itemAttDir = itemAttachmentsDirectory(itemId: item.id), + fm.fileExists(atPath: itemAttDir.path) + { + try? fm.removeItem(at: itemAttDir) + } else { + for att in item.attachments { + if let attUrl = safeAttachmentURL(relativePath: att.relativePath) { + try? fm.removeItem(at: attUrl) + } + } + } + } + + /// Drains pending `ShareInbox` items on a background utility queue so file I/O (up to 64 MiB) + /// and SQLite `BEGIN IMMEDIATE ... COMMIT` + WAL checkpoint never block the UI main thread. + func drainInBackground( + workspace: WorkspaceStorageBridge?, + mountedWorkspaces: [String: WorkspaceStorageBridge] = [:], + onMainThreadCompletion: @escaping @MainActor @Sendable (Int) -> Void + ) { + guard workspace != nil || !mountedWorkspaces.isEmpty else { + Task { @MainActor in onMainThreadCompletion(0) } + return + } + let bridge = self + Task.detached(priority: .utility) { + let count = bridge.drainAndIngestIntoHost( + nil, + workspace: workspace, + resolveWorkspace: mountedWorkspaces.isEmpty ? nil : { wsId in mountedWorkspaces[wsId] } + ) + await onMainThreadCompletion(count) + } + } + + /// Atomically ingests pending `ShareInbox/.json` items into their target local `workspace` + /// SQLite (`blobs` + `updates` + `clocks` + `db$docProperties` + `share_ingest_receipts`). + @discardableResult + func drainAndIngestIntoHost( + _ host: OpaquePointer?, + workspace: WorkspaceStorageBridge?, + resolveWorkspace: ((String) -> WorkspaceStorageBridge?)? = nil, + docId overrideDocId: String? = nil + ) -> Int { + guard workspace != nil || resolveWorkspace != nil else { + return 0 + } + lock.lock() + if drainInFlight { + lock.unlock() + return 0 + } + drainInFlight = true + lock.unlock() + defer { + lock.lock() + drainInFlight = false + lock.unlock() + } + + let fm = FileManager.default + let decoder = Self.makeDecoder() + guard let urls = try? fm.contentsOfDirectory( + at: inboxDirectory, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { + return 0 + } + let manifestUrls = urls + .filter { $0.pathExtension.lowercased() == "json" } + .sorted { $0.lastPathComponent < $1.lastPathComponent } + + var decodedEntries: [(url: URL, modDate: Date?, item: ShareInboxItem)] = [] + for url in manifestUrls { + let modDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))? + .contentModificationDate + let now = Date() + lock.lock() + let skipUnchangedFailure: Bool + if let modDate, let record = failedManifestBackoff[url.path], record.modDate == modDate { + skipUnchangedFailure = now.timeIntervalSince(record.failedAt) < Self.failureRetryCooldownSec + } else { + skipUnchangedFailure = false + } + lock.unlock() + if skipUnchangedFailure { + continue + } + guard let data = try? Data(contentsOf: url) else { + continue + } + guard let schemaVersion = Self.peekSchemaVersion(from: data) else { + quarantineManifest(at: url) + continue + } + if schemaVersion > ShareInboxItem.currentSchemaVersion { + continue + } + guard let item = try? decoder.decode(ShareInboxItem.self, from: data) else { + quarantineManifest(at: url) + continue + } + decodedEntries.append((url, modDate, item)) + } + + decodedEntries.sort { $0.item.createdAt < $1.item.createdAt } + + var newlyIngested = 0 + + for entry in decodedEntries { + let item = entry.item + if item.result != nil { + cleanupConsumedItem(manifestUrl: entry.url, item: item) + continue + } + + let targetWorkspace: WorkspaceStorageBridge? + if let target = item.target { + let flavour = target.workspaceFlavour.trimmingCharacters(in: .whitespacesAndNewlines) + if !flavour.isEmpty && flavour != "local" { + continue + } + let requestedId = target.workspaceId.trimmingCharacters(in: .whitespacesAndNewlines) + if requestedId.isEmpty { + targetWorkspace = workspace + } else if let resolved = resolveWorkspace?(requestedId) { + targetWorkspace = resolved + } else if let workspace, workspace.spaceId == requestedId { + targetWorkspace = workspace + } else { + continue + } + } else { + targetWorkspace = workspace + } + guard let targetWorkspace else { + continue + } + + let targetDocId = (overrideDocId?.trimmingCharacters(in: .whitespacesAndNewlines)).flatMap { + $0.isEmpty ? nil : $0 + } ?? item.documentId + + var blobBuffer = Data() + var attachmentSpecs: [ShareIngestAttachmentSpecPayload] = [] + var attachmentsValid = true + + for att in item.attachments { + guard + !att.fileName.isEmpty, + att.fileName == (att.fileName as NSString).lastPathComponent, + att.fileName != ".", + att.fileName != "..", + att.relativePath == "\(item.id)/\(att.fileName)", + let attUrl = safeAttachmentURL(relativePath: att.relativePath), + let values = try? attUrl.resourceValues( + forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey] + ), + values.isSymbolicLink != true, + values.isRegularFile == true, + let fileSize = values.fileSize, + fileSize > 0, + fileSize <= Self.maxShareAttachmentBytes, + blobBuffer.count + fileSize <= Self.maxShareAttachmentBytes, + let bytes = try? Data(contentsOf: attUrl), + !bytes.isEmpty, + bytes.count <= Self.maxShareAttachmentBytes, + blobBuffer.count + bytes.count <= Self.maxShareAttachmentBytes + else { + attachmentsValid = false + break + } + let offset = blobBuffer.count + blobBuffer.append(bytes) + let blobKey = Self.sha256Base64Url(bytes) + attachmentSpecs.append( + ShareIngestAttachmentSpecPayload( + blob_key: blobKey, + file_name: att.fileName, + mime_type: att.mimeType, + byte_offset: offset, + byte_len: bytes.count + ) + ) + } + + if !attachmentsValid { + quarantineManifest(at: entry.url) + continue + } + + let textOrUrl: String + let secondaryText: String + switch item.content.kind { + case .url: + let rawUrl = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + guard rawUrl.hasPrefix("https://") || rawUrl.hasPrefix("http://") else { + quarantineManifest(at: entry.url) + continue + } + textOrUrl = rawUrl + secondaryText = (item.content.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + case .text: + let rawText = (item.content.text ?? item.previewText ?? "").trimmingCharacters( + in: .whitespacesAndNewlines + ) + guard !rawText.isEmpty else { + quarantineManifest(at: entry.url) + continue + } + textOrUrl = rawText + secondaryText = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + case .image, .pdf: + guard !attachmentSpecs.isEmpty else { + quarantineManifest(at: entry.url) + continue + } + textOrUrl = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + secondaryText = (item.content.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + } + + let request = ShareIngestRequestPayload( + share_id: item.id, + import_attempt_id: item.importAttemptId, + doc_id: targetDocId, + kind: item.content.kind.rawValue, + title: item.title, + text_or_url: textOrUrl, + secondary_text: secondaryText, + tag_ids: item.target?.tagIds ?? [], + collection_id: item.target?.collectionId, + attachments: attachmentSpecs, + client_id: UInt64(UInt32.random(in: 1...UInt32.max)), + now_ms: Int64(Date().timeIntervalSince1970 * 1000.0) + ) + guard + let reqData = try? JSONEncoder().encode(request), + let reqJson = String(data: reqData, encoding: .utf8), + let outcomeJson = targetWorkspace.ingestShareItem( + requestJson: reqJson, + blobBytes: blobBuffer + ), + let outcomeData = outcomeJson.data(using: .utf8), + let outcome = try? JSONDecoder().decode(ShareIngestOutcomePayload.self, from: outcomeData) + else { + if let modDate = entry.modDate { + lock.lock() + failedManifestBackoff[entry.url.path] = (modDate: modDate, failedAt: Date()) + lock.unlock() + } + continue + } + + if !outcome.already_committed { + newlyIngested += 1 + } + + let checkpointOk = checkpointHook?(targetWorkspace) ?? targetWorkspace.checkpointPassive() + guard checkpointOk else { + continue + } + + cleanupConsumedItem(manifestUrl: entry.url, item: item) + } + + if let host, newlyIngested > 0 { + affine_ios_host_request_frame(host) + } + + return newlyIngested + } +} diff --git a/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift new file mode 100644 index 0000000000..152764ce93 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift @@ -0,0 +1,939 @@ +import CoreGraphics +import CoreText +import UIKit + +/// Native CoreText `CTTypesetter`/`CTLine`/`CTRun` text geometry, BiDi glyph-slot +/// selection rects, affinity-aware endpoint carets, whole-line `CTLineDraw` preview, +/// and Retina anti-aliased loupe rasterizer. +final class TextRenderingBridge { + static let contentInsetPt: CGFloat = 16.0 + static let lineHeightPt: CGFloat = 22.0 + static let defaultClearColorRgba: UInt32 = 0xFAFA_FCFF + + let font = UIFont.systemFont(ofSize: 17, weight: .regular) + private(set) var isDarkCanvas = false + private var canvasBackgroundColor = UIColor( + red: 250.0 / 255.0, + green: 250.0 / 255.0, + blue: 252.0 / 255.0, + alpha: 1.0 + ) + private var textColor = UIColor(white: 0.1, alpha: 1.0) + private var selectionColor = UIColor(red: 0.808, green: 0.910, blue: 1.0, alpha: 1.0) + private let caretColor = UIColor(red: 0.118, green: 0.588, blue: 0.922, alpha: 1.0) + + private struct LayoutKey: Equatable { + let utf16Units: [UInt16] + let viewportWidthBits: UInt32 + let safeLeftBits: UInt32 + let safeTopBits: UInt32 + let safeRightBits: UInt32 + let isDarkCanvas: Bool + } + + struct ShapedVisualLine { + let ctLine: CTLine + let paragraphStart: Int + let start: Int + let end: Int + let isSoftWrapped: Bool + let writingDirection: NSWritingDirection + let originX: CGFloat + let topY: CGFloat + let width: CGFloat + let height: CGFloat + let ascent: CGFloat + let descent: CGFloat + } + + private struct GlyphSlot { + let docStart: Int + let docEnd: Int + let xLeft: CGFloat + let xRight: CGFloat + let isRtl: Bool + let topY: CGFloat + let height: CGFloat + } + + private struct CachedLayout { + let key: LayoutKey + let nsText: NSString + let originX: CGFloat + let originY: CGFloat + let maxWidth: CGFloat + let lines: [ShapedVisualLine] + } + + private var cachedLayout: CachedLayout? + private var attachedHost: OpaquePointer? + + /// Adapt text & selection colors to the host's current clear color and return its `UIColor`. + @discardableResult + func applyClearColorRgba(_ rgba: UInt32) -> UIColor { + let r = CGFloat((rgba >> 24) & 0xFF) / 255.0 + let g = CGFloat((rgba >> 16) & 0xFF) / 255.0 + let b = CGFloat((rgba >> 8) & 0xFF) / 255.0 + let a = CGFloat(rgba & 0xFF) / 255.0 + let bg = UIColor(red: r, green: g, blue: b, alpha: a) + canvasBackgroundColor = bg + let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b + let dark = luma < 0.35 + if dark != isDarkCanvas { + isDarkCanvas = dark + if dark { + textColor = UIColor(red: 242.0 / 255.0, green: 242.0 / 255.0, blue: 245.0 / 255.0, alpha: 1.0) + selectionColor = UIColor(red: 0.118, green: 0.588, blue: 0.922, alpha: 0.35) + } else { + textColor = UIColor(white: 0.1, alpha: 1.0) + selectionColor = UIColor(red: 0.808, green: 0.910, blue: 1.0, alpha: 1.0) + } + cachedLayout = nil + } + return bg + } + + func attach(to host: OpaquePointer) { + detach() + attachedHost = host + let provider = AffineTextProvider( + caret_rect: affineTextCaretRectTrampoline, + closest_offset: affineTextClosestOffsetTrampoline, + selection_rects: affineTextSelectionRectsTrampoline, + selection_endpoint_carets: affineTextSelectionEndpointCaretsTrampoline, + render_loupe_rgba8: affineTextRenderLoupeRgba8Trampoline, + user_data: Unmanaged.passUnretained(self).toOpaque() + ) + affine_ios_host_set_text_provider(host, provider) + } + + func detach() { + guard let host = attachedHost else { + return + } + let empty = AffineTextProvider( + caret_rect: nil, + closest_offset: nil, + selection_rects: nil, + selection_endpoint_carets: nil, + render_loupe_rgba8: nil, + user_data: nil + ) + affine_ios_host_set_text_provider(host, empty) + attachedHost = nil + cachedLayout = nil + } + + deinit { + detach() + } + + private func utf16ArrayFrom(_ ptr: UnsafePointer?, _ len: Int) -> [UInt16] { + guard let ptr, len > 0 else { return [] } + return Array(UnsafeBufferPointer(start: ptr, count: len)) + } + + private func layoutFor( + utf16Units: [UInt16], + viewportWidth: Float, + insets: AffineWindowInsets + ) -> CachedLayout { + let key = LayoutKey( + utf16Units: utf16Units, + viewportWidthBits: viewportWidth.bitPattern, + safeLeftBits: insets.safe_left.bitPattern, + safeTopBits: insets.safe_top.bitPattern, + safeRightBits: insets.safe_right.bitPattern, + isDarkCanvas: isDarkCanvas + ) + if let existing = cachedLayout, existing.key == key { + return existing + } + + let safeLeft = CGFloat(max(0.0, insets.safe_left.isFinite ? insets.safe_left : 0.0)) + let safeTop = CGFloat(max(0.0, insets.safe_top.isFinite ? insets.safe_top : 0.0)) + let safeRight = CGFloat(max(0.0, insets.safe_right.isFinite ? insets.safe_right : 0.0)) + let vw = CGFloat(max(0.0, viewportWidth.isFinite ? viewportWidth : 0.0)) + let originX = safeLeft + Self.contentInsetPt + let originY = safeTop + Self.contentInsetPt + let maxWidth = max(40.0, vw - originX - (safeRight + Self.contentInsetPt)) + + let nsText: NSString = utf16Units.isEmpty + ? "" + : NSString(characters: utf16Units, length: utf16Units.count) + let totalLen = nsText.length + var lines: [ShapedVisualLine] = [] + var lineIndex = 0 + + func emitEmptyLine(at docOffset: Int, dir: NSWritingDirection) { + let emptyAttr = NSAttributedString(string: "", attributes: [.font: font]) + let ctLine = CTLineCreateWithAttributedString(emptyAttr) + let x = dir == .rightToLeft ? (originX + maxWidth) : originX + lines.append( + ShapedVisualLine( + ctLine: ctLine, + paragraphStart: docOffset, + start: docOffset, + end: docOffset, + isSoftWrapped: false, + writingDirection: dir, + originX: x, + topY: originY + CGFloat(lineIndex) * Self.lineHeightPt, + width: 0.0, + height: Self.lineHeightPt, + ascent: font.ascender, + descent: abs(font.descender) + ) + ) + lineIndex += 1 + } + + var paraStart = 0 + while paraStart <= totalLen { + var paraEnd = paraStart + while paraEnd < totalLen && nsText.character(at: paraEnd) != 0x000A { + paraEnd += 1 + } + let paraLen = paraEnd - paraStart + let paraRange = NSRange(location: paraStart, length: paraLen) + let paraStr = paraLen > 0 ? nsText.substring(with: paraRange) : "" + let dir = detectBaseWritingDirection(paraStr) + + if paraLen == 0 { + emitEmptyLine(at: paraStart, dir: dir) + } else { + let paraStyle = NSMutableParagraphStyle() + paraStyle.baseWritingDirection = dir + paraStyle.alignment = (dir == .rightToLeft) ? .right : .left + let attrStr = NSAttributedString( + string: paraStr, + attributes: [ + .font: font, + .foregroundColor: textColor, + .paragraphStyle: paraStyle, + ] + ) + let typesetter = CTTypesetterCreateWithAttributedString(attrStr) + var localStart = 0 + while localStart < paraLen { + var count = CTTypesetterSuggestLineBreak(typesetter, localStart, Double(maxWidth)) + if count <= 0 { + let seq = (paraStr as NSString).rangeOfComposedCharacterSequence(at: localStart) + count = max(1, seq.length) + } + let localEnd = min(paraLen, localStart + count) + let ctLine = CTTypesetterCreateLine( + typesetter, + CFRange(location: localStart, length: localEnd - localStart) + ) + var ascent: CGFloat = 0 + var descent: CGFloat = 0 + var leading: CGFloat = 0 + let lineW = CGFloat(CTLineGetTypographicBounds(ctLine, &ascent, &descent, &leading)) + let flush: CGFloat = (dir == .rightToLeft) ? 1.0 : 0.0 + let penOffset = CGFloat(CTLineGetPenOffsetForFlush(ctLine, flush, Double(maxWidth))) + let lineOriginX = originX + max(0.0, penOffset) + lines.append( + ShapedVisualLine( + ctLine: ctLine, + paragraphStart: paraStart, + start: paraStart + localStart, + end: paraStart + localEnd, + isSoftWrapped: localEnd < paraLen, + writingDirection: dir, + originX: lineOriginX, + topY: originY + CGFloat(lineIndex) * Self.lineHeightPt, + width: lineW, + height: Self.lineHeightPt, + ascent: ascent > 0 ? ascent : font.ascender, + descent: descent > 0 ? descent : abs(font.descender) + ) + ) + lineIndex += 1 + localStart = localEnd + } + } + + if paraEnd < totalLen && nsText.character(at: paraEnd) == 0x000A { + paraStart = paraEnd + 1 + } else { + break + } + } + + if lines.isEmpty { + emitEmptyLine(at: 0, dir: .leftToRight) + } + + let built = CachedLayout( + key: key, + nsText: nsText, + originX: originX, + originY: originY, + maxWidth: maxWidth, + lines: lines + ) + cachedLayout = built + return built + } + + private func snapToGraphemeBoundary(_ nsText: NSString, offset: Int) -> Int { + let clamped = max(0, min(offset, nsText.length)) + guard clamped > 0 && clamped < nsText.length else { + return clamped + } + let seq = nsText.rangeOfComposedCharacterSequence(at: clamped) + if clamped > seq.location && clamped < seq.location + seq.length { + let distStart = clamped - seq.location + let distEnd = (seq.location + seq.length) - clamped + return distStart <= distEnd ? seq.location : (seq.location + seq.length) + } + return clamped + } + + /// Extract exact visual glyph slots (`[docStart, docEnd)` -> `[xLeft, xRight]`) from `CTRun`s + /// so BiDi direction boundaries never collapse or jump to the outer run's primary caret edge. + private func glyphSlots(in line: ShapedVisualLine) -> [GlyphSlot] { + let runs = CTLineGetGlyphRuns(line.ctLine) as? [CTRun] ?? [] + var slots: [GlyphSlot] = [] + for run in runs { + let count = CTRunGetGlyphCount(run) + guard count > 0 else { continue } + let runRange = CTRunGetStringRange(run) + let runEnd = runRange.location + runRange.length + let isRtl = CTRunGetStatus(run).contains(.rightToLeft) + + var indices = Array(repeating: CFIndex(0), count: count) + var positions = Array(repeating: CGPoint.zero, count: count) + var advances = Array(repeating: CGSize.zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: count), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: count), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: count), &advances) + + var uniqueSorted = Array(Set(indices)).sorted() + if uniqueSorted.last != runEnd { + uniqueSorted.append(runEnd) + } + var nextBoundaryByIndex: [CFIndex: CFIndex] = [:] + for i in 0..<(uniqueSorted.count - 1) { + nextBoundaryByIndex[uniqueSorted[i]] = uniqueSorted[i + 1] + } + + for g in 0.. (minX: CGFloat, maxX: CGFloat) { + let totalUnits = max(1, slot.docEnd - slot.docStart) + if ovStart <= slot.docStart && ovEnd >= slot.docEnd { + return (slot.xLeft, slot.xRight) + } + let fracStart = CGFloat(max(0, ovStart - slot.docStart)) / CGFloat(totalUnits) + let fracEnd = CGFloat(min(totalUnits, ovEnd - slot.docStart)) / CGFloat(totalUnits) + let span = slot.xRight - slot.xLeft + if slot.isRtl { + return (slot.xRight - fracEnd * span, slot.xRight - fracStart * span) + } + return (slot.xLeft + fracStart * span, slot.xLeft + fracEnd * span) + } + + private func caretRectInLayout(_ layout: CachedLayout, utf16Offset: UInt32) -> AffineRect { + let offset = snapToGraphemeBoundary(layout.nsText, offset: Int(utf16Offset)) + let targetLine = layout.lines.first { line in + if line.isSoftWrapped { + return offset >= line.start && offset < line.end + } + return offset >= line.start && offset <= line.end + } ?? layout.lines.last! + let localIdx = max(0, offset - targetLine.paragraphStart) + let xOff = CTLineGetOffsetForStringIndex(targetLine.ctLine, localIdx, nil) + return AffineRect( + x: Float(targetLine.originX + xOff), + y: Float(targetLine.topY), + width: 2.0, + height: Float(targetLine.height) + ) + } + + private func selectionEndpointCaretsInLayout( + _ layout: CachedLayout, + range: AffineUtf16Range + ) -> (start: AffineRect, end: AffineRect) { + let selStart = snapToGraphemeBoundary(layout.nsText, offset: Int(range.location)) + let selEnd = snapToGraphemeBoundary( + layout.nsText, + offset: Int(range.location) + Int(range.length) + ) + if selEnd <= selStart || layout.nsText.length == 0 { + let c = caretRectInLayout(layout, utf16Offset: UInt32(max(0, selStart))) + return (c, c) + } + + var startRect: AffineRect? + var endRect: AffineRect? + let lastUnit = selEnd - 1 + + for line in layout.lines { + if selEnd < line.start || selStart > line.end { + continue + } + let slots = glyphSlots(in: line) + if startRect == nil && selStart >= line.start && selStart < line.end { + if let slot = slots.first(where: { selStart >= $0.docStart && selStart < $0.docEnd }) { + let bounds = slicedBounds( + for: slot, + ovStart: selStart, + ovEnd: min(slot.docEnd, selEnd) + ) + let edgeX = slot.isRtl ? bounds.maxX : bounds.minX + startRect = AffineRect( + x: Float(edgeX), + y: Float(slot.topY), + width: 2.0, + height: Float(slot.height) + ) + } + } + if endRect == nil && lastUnit >= line.start && lastUnit < line.end { + if let slot = slots.last(where: { lastUnit >= $0.docStart && lastUnit < $0.docEnd }) { + let bounds = slicedBounds( + for: slot, + ovStart: max(slot.docStart, selStart), + ovEnd: selEnd + ) + let edgeX = slot.isRtl ? bounds.minX : bounds.maxX + endRect = AffineRect( + x: Float(edgeX), + y: Float(slot.topY), + width: 2.0, + height: Float(slot.height) + ) + } + } + if startRect != nil && endRect != nil { + break + } + } + + let resolvedStart = startRect ?? caretRectInLayout(layout, utf16Offset: UInt32(selStart)) + let resolvedEnd = endRect ?? caretRectInLayout(layout, utf16Offset: UInt32(selEnd)) + return (resolvedStart, resolvedEnd) + } + + func caretRect( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + utf16Offset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets + ) -> AffineRect { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + return caretRectInLayout(layout, utf16Offset: utf16Offset) + } + + func selectionEndpointCarets( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outStart: UnsafeMutablePointer?, + outEnd: UnsafeMutablePointer? + ) -> Bool { + guard let outStart, let outEnd else { return false } + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let pair = selectionEndpointCaretsInLayout(layout, range: range) + outStart.pointee = pair.start + outEnd.pointee = pair.end + return true + } + + func closestOffset( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + point: AffinePoint, + preferredOffset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets + ) -> UInt32 { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + guard !units.isEmpty else { return 0 } + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let px = CGFloat(point.x.isFinite ? point.x : 0.0) + let py = CGFloat(point.y.isFinite ? point.y : 0.0) + + var targetLine = layout.lines[0] + var bestDy = CGFloat.greatestFiniteMagnitude + for line in layout.lines { + let dy = abs(py - (line.topY + line.height * 0.5)) + if dy < bestDy { + bestDy = dy + targetLine = line + } + } + + // At BiDi direction-change boundaries, one visual x maps to two logical UTF-16 offsets. + // When the drag probe sits within 2.0pt of a glyph boundary matching `preferredOffset`, + // keep `preferredOffset` so in-place or micro-jitter drags never collapse the selection. + if preferredOffset != UInt32.max { + let pref = snapToGraphemeBoundary(layout.nsText, offset: Int(preferredOffset)) + let slots = glyphSlots(in: targetLine) + let boundaryTolerance: CGFloat = 2.0 + for slot in slots { + let leadX = slot.isRtl ? slot.xRight : slot.xLeft + let trailX = slot.isRtl ? slot.xLeft : slot.xRight + if slot.docStart == pref && abs(px - leadX) <= boundaryTolerance { + return UInt32(max(0, pref)) + } + if slot.docEnd == pref && abs(px - trailX) <= boundaryTolerance { + return UInt32(max(0, pref)) + } + } + } + + let localPos = CGPoint(x: px - targetLine.originX, y: targetLine.height * 0.5) + let rawLocalIdx = CTLineGetStringIndexForPosition(targetLine.ctLine, localPos) + if rawLocalIdx == kCFNotFound { + return UInt32(max(0, targetLine.start)) + } + let docOffset = max(targetLine.start, min(targetLine.paragraphStart + rawLocalIdx, targetLine.end)) + let snapped = snapToGraphemeBoundary(layout.nsText, offset: docOffset) + return UInt32(max(0, snapped)) + } + + private func computeSelectionRects( + layout: CachedLayout, + range: AffineUtf16Range + ) -> [AffineSelectionRect] { + guard range.length > 0 && layout.nsText.length > 0 else { + return [] + } + let selStart = snapToGraphemeBoundary(layout.nsText, offset: Int(range.location)) + let selEnd = snapToGraphemeBoundary( + layout.nsText, + offset: Int(range.location) + Int(range.length) + ) + guard selEnd > selStart else { + return [] + } + + var result: [AffineSelectionRect] = [] + for line in layout.lines { + if selEnd < line.start || selStart > line.end { + continue + } + let segStart = max(line.start, selStart) + let segEnd = min(line.end, selEnd) + let emptyHardInside = + line.start == line.end && !line.isSoftWrapped && selStart < line.start && selEnd > line.end + if segEnd <= segStart && !emptyHardInside { + continue + } + + if emptyHardInside { + result.append( + AffineSelectionRect( + rect: AffineRect( + x: Float(line.originX), + y: Float(line.topY), + width: 2.0, + height: Float(line.height) + ), + contains_start: false, + contains_end: false + ) + ) + continue + } + + let slots = glyphSlots(in: line) + var intervals: [(minX: CGFloat, maxX: CGFloat, hasStart: Bool, hasEnd: Bool)] = [] + let lastUnit = selEnd - 1 + + for slot in slots { + let ovStart = max(slot.docStart, segStart) + let ovEnd = min(slot.docEnd, segEnd) + guard ovEnd > ovStart else { continue } + let bounds = slicedBounds(for: slot, ovStart: ovStart, ovEnd: ovEnd) + let hasStart = selStart >= ovStart && selStart < ovEnd + let hasEnd = lastUnit >= ovStart && lastUnit < ovEnd + intervals.append((bounds.minX, bounds.maxX, hasStart, hasEnd)) + } + + if intervals.isEmpty { + let localStart = segStart - line.paragraphStart + let localEnd = segEnd - line.paragraphStart + let x0 = line.originX + CTLineGetOffsetForStringIndex(line.ctLine, localStart, nil) + let x1 = line.originX + CTLineGetOffsetForStringIndex(line.ctLine, localEnd, nil) + intervals.append((min(x0, x1), max(x0, x1), selStart == segStart, selEnd == segEnd)) + } + + intervals.sort { $0.minX < $1.minX } + var merged: [(minX: CGFloat, maxX: CGFloat, hasStart: Bool, hasEnd: Bool)] = [] + for item in intervals { + if let last = merged.last, item.minX <= last.maxX + 0.75 { + merged[merged.count - 1] = ( + min(last.minX, item.minX), + max(last.maxX, item.maxX), + last.hasStart || item.hasStart, + last.hasEnd || item.hasEnd + ) + } else { + merged.append(item) + } + } + + for seg in merged { + result.append( + AffineSelectionRect( + rect: AffineRect( + x: Float(seg.minX), + y: Float(line.topY), + width: Float(max(2.0, seg.maxX - seg.minX)), + height: Float(line.height) + ), + contains_start: seg.hasStart, + contains_end: seg.hasEnd + ) + ) + } + } + return result + } + + func selectionRects( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outRects: UnsafeMutablePointer?, + capacity: Int + ) -> Int { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let rects = computeSelectionRects(layout: layout, range: range) + if let outRects, capacity > 0 { + let count = min(rects.count, capacity) + for i in 0.. 0 { + let rects = computeSelectionRects(layout: layout, range: selectedRange) + ctx.setFillColor(selectionColor.cgColor) + for item in rects { + ctx.fill( + CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ) + ) + } + } + + for line in layout.lines { + let contentH = line.ascent + line.descent + let baselineY = line.topY + max(0.0, (line.height - contentH) * 0.5) + line.ascent + ctx.saveGState() + ctx.translateBy(x: line.originX, y: baselineY) + ctx.scaleBy(x: 1.0, y: -1.0) + ctx.textMatrix = .identity + ctx.textPosition = .zero + CTLineDraw(line.ctLine, ctx) + ctx.restoreGState() + } + } + + func renderLoupeRgba8( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + selectedRange: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + focusX: Float, + focusY: Float, + diameterPx: UInt32, + zoomScale: Float, + outPtr: UnsafeMutablePointer?, + outLen: Int + ) -> Bool { + let dim = Int(diameterPx) + guard dim >= 16, let outPtr, outLen >= dim * dim * 4 else { + return false + } + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmapInfo = + CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + guard + let ctx = CGContext( + data: outPtr, + width: dim, + height: dim, + bitsPerComponent: 8, + bytesPerRow: dim * 4, + space: colorSpace, + bitmapInfo: bitmapInfo + ) + else { + return false + } + + ctx.setAllowsAntialiasing(true) + ctx.setShouldAntialias(true) + ctx.setAllowsFontSmoothing(true) + ctx.setShouldSmoothFonts(true) + ctx.interpolationQuality = .high + + ctx.setFillColor(canvasBackgroundColor.cgColor) + ctx.fill(CGRect(x: 0, y: 0, width: dim, height: dim)) + + ctx.saveGState() + ctx.translateBy(x: 0, y: CGFloat(dim)) + ctx.scaleBy(x: 1.0, y: -1.0) + let half = CGFloat(dim) * 0.5 + let zoom = CGFloat(zoomScale) + ctx.translateBy(x: half, y: half) + ctx.scaleBy(x: zoom, y: zoom) + ctx.translateBy(x: -CGFloat(focusX), y: -CGFloat(focusY)) + + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + drawShapedLayout(in: ctx, layout: layout, selectedRange: selectedRange) + + // Snap the loupe caret bar to the nearest affinity-aware selection endpoint edge. + let endpoints = selectionEndpointCaretsInLayout(layout, range: selectedRange) + let startDist = hypot( + CGFloat(endpoints.start.x) - CGFloat(focusX), + CGFloat(endpoints.start.y + endpoints.start.height * 0.5) - CGFloat(focusY) + ) + let endDist = hypot( + CGFloat(endpoints.end.x) - CGFloat(focusX), + CGFloat(endpoints.end.y + endpoints.end.height * 0.5) - CGFloat(focusY) + ) + let snappedCaret = startDist <= endDist ? endpoints.start : endpoints.end + ctx.setFillColor(caretColor.cgColor) + ctx.fill( + CGRect( + x: CGFloat(snappedCaret.x) - 0.85, + y: CGFloat(snappedCaret.y), + width: 1.7, + height: CGFloat(snappedCaret.height) + ) + ) + ctx.restoreGState() + return true + } + + private func detectBaseWritingDirection(_ text: String) -> NSWritingDirection { + for scalar in text.unicodeScalars { + let v = scalar.value + if (0x0590...0x08FF).contains(v) + || (0xFB1D...0xFDFF).contains(v) + || (0xFE70...0xFEFC).contains(v) + { + return .rightToLeft + } + if (0x0041...0x005A).contains(v) + || (0x0061...0x007A).contains(v) + || (0x00C0...0x024F).contains(v) + || (0x0370...0x052F).contains(v) + || (0x4E00...0x9FFF).contains(v) + { + return .leftToRight + } + } + return .leftToRight + } +} + +private func affineTextCaretRectTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + utf16Offset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets, + userData: UnsafeMutableRawPointer? +) -> AffineRect { + guard let userData else { return AffineRect() } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.caretRect( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + utf16Offset: utf16Offset, + viewportWidth: viewportWidth, + insets: insets + ) +} + +private func affineTextClosestOffsetTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + point: AffinePoint, + preferredOffset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets, + userData: UnsafeMutableRawPointer? +) -> UInt32 { + guard let userData else { return 0 } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.closestOffset( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + point: point, + preferredOffset: preferredOffset, + viewportWidth: viewportWidth, + insets: insets + ) +} + +private func affineTextSelectionRectsTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outRects: UnsafeMutablePointer?, + capacity: Int, + userData: UnsafeMutableRawPointer? +) -> Int { + guard let userData else { return 0 } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.selectionRects( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + range: range, + viewportWidth: viewportWidth, + insets: insets, + outRects: outRects, + capacity: capacity + ) +} + +private func affineTextSelectionEndpointCaretsTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outStart: UnsafeMutablePointer?, + outEnd: UnsafeMutablePointer?, + userData: UnsafeMutableRawPointer? +) -> Bool { + guard let userData else { return false } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.selectionEndpointCarets( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + range: range, + viewportWidth: viewportWidth, + insets: insets, + outStart: outStart, + outEnd: outEnd + ) +} + +private func affineTextRenderLoupeRgba8Trampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + selectedRange: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + focusX: Float, + focusY: Float, + diameterPx: UInt32, + zoomScale: Float, + outPtr: UnsafeMutablePointer?, + outLen: Int, + userData: UnsafeMutableRawPointer? +) -> Bool { + guard let userData else { return false } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.renderLoupeRgba8( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + selectedRange: selectedRange, + viewportWidth: viewportWidth, + insets: insets, + focusX: focusX, + focusY: focusY, + diameterPx: diameterPx, + zoomScale: zoomScale, + outPtr: outPtr, + outLen: outLen + ) +} diff --git a/packages/frontend/hosts/ios/Sources/WorkspaceStorageBridge.swift b/packages/frontend/hosts/ios/Sources/WorkspaceStorageBridge.swift new file mode 100644 index 0000000000..e30865d504 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/WorkspaceStorageBridge.swift @@ -0,0 +1,230 @@ +import Foundation + +enum WorkspaceStorageBridgeError: Error, Equatable { + case documentsDirectoryUnavailable + case localAllowlistRequired + case openFailed + case operationFailed +} + +/// Thin Swift wrapper over the in-place 0.27.5 SQLite WAL C ABI in `affine_mobile_host.h`. +/// Thread-safe: all access to `handle` (including `close()`) is serialized under `lock`. +final class WorkspaceStorageBridge: @unchecked Sendable { + let spaceType: String + let peer: String + let spaceId: String + private let lock = NSLock() + private var handle: OpaquePointer? + + init( + spaceType: String, + peer: String, + spaceId: String, + allowlistedLocalIds: [String]? = nil, + documentsDirectory: URL? = nil + ) throws { + let isLocalWorkspace = spaceType == "workspace" && peer == "local" + if isLocalWorkspace { + guard let ids = allowlistedLocalIds, ids.contains(spaceId) else { + throw WorkspaceStorageBridgeError.localAllowlistRequired + } + } + + guard + let docsDir = documentsDirectory + ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first + else { + throw WorkspaceStorageBridgeError.documentsDirectoryUnavailable + } + + let allowlistJson: String? + if let ids = allowlistedLocalIds { + guard + let data = try? JSONEncoder().encode(ids), + let json = String(data: data, encoding: .utf8) + else { + throw WorkspaceStorageBridgeError.openFailed + } + allowlistJson = json + } else { + allowlistJson = nil + } + + let opened: OpaquePointer? = docsDir.path.withCString { cDocs in + spaceType.withCString { cType in + peer.withCString { cPeer in + spaceId.withCString { cSpace in + if let allowlistJson { + return allowlistJson.withCString { cAllow in + affine_ios_workspace_open(cDocs, cType, cPeer, cSpace, cAllow) + } + } + return affine_ios_workspace_open(cDocs, cType, cPeer, cSpace, nil) + } + } + } + } + guard let opened else { + throw WorkspaceStorageBridgeError.openFailed + } + self.spaceType = spaceType + self.peer = peer + self.spaceId = spaceId + self.handle = opened + } + + deinit { + close() + } + + func close() { + lock.lock() + defer { lock.unlock() } + if let current = handle { + self.handle = nil + affine_ios_workspace_close(current) + } + } + + func readDoc(docId: String) -> Data? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let buffer = docId.withCString { affine_ios_workspace_read_doc(handle, $0) } + return takeBytes(buffer) + } + + func readPageSnapshotJson(docId: String, clientId: UInt64) -> String? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let ptr = docId.withCString { affine_ios_workspace_read_page_snapshot_json(handle, $0, clientId) } + guard let ptr else { return nil } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } + + func editParagraphText( + docId: String, + blockId: String, + utf16Index: UInt64, + deleteLen: UInt64, + insertText: String, + clientId: UInt64, + nowMs: Int64 + ) -> Data? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let buffer = docId.withCString { cDoc in + blockId.withCString { cBlock in + insertText.withCString { cText in + affine_ios_workspace_edit_paragraph_text( + handle, + cDoc, + cBlock, + utf16Index, + deleteLen, + cText, + clientId, + nowMs + ) + } + } + } + return takeBytes(buffer) + } + + func exportPendingDiff(docId: String, remoteStateVector: Data? = nil) -> Data? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let buffer: AffineIosByteBuffer = docId.withCString { cDoc in + if let remoteStateVector, !remoteStateVector.isEmpty { + return remoteStateVector.withUnsafeBytes { raw in + let bytes = raw.bindMemory(to: UInt8.self).baseAddress + return affine_ios_workspace_export_doc_diff(handle, cDoc, bytes, remoteStateVector.count) + } + } + return affine_ios_workspace_export_doc_diff(handle, cDoc, nil, 0) + } + return takeBytes(buffer) + } + + func applyRemoteUpdate( + docId: String, + update: Data, + peer: String, + remoteClockMs: Int64, + localNowMs: Int64 + ) -> Data? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let buffer: AffineIosByteBuffer = docId.withCString { cDoc in + peer.withCString { cPeer in + update.withUnsafeBytes { raw in + let bytes = raw.bindMemory(to: UInt8.self).baseAddress + return affine_ios_workspace_apply_remote_update( + handle, + cDoc, + bytes, + update.count, + cPeer, + remoteClockMs, + localNowMs + ) + } + } + } + return takeBytes(buffer) + } + + func checkpointPassive() -> Bool { + lock.lock() + defer { lock.unlock() } + guard let handle else { return false } + return affine_ios_workspace_checkpoint_passive(handle) + } + + func checkpoint() -> Bool { + lock.lock() + defer { lock.unlock() } + guard let handle else { return false } + return affine_ios_workspace_checkpoint(handle) + } + + func readBlob(key: String) -> Data? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let buffer = key.withCString { affine_ios_workspace_read_blob(handle, $0) } + return takeBytes(buffer) + } + + func ingestShareItem(requestJson: String, blobBytes: Data) -> String? { + lock.lock() + defer { lock.unlock() } + guard let handle else { return nil } + let ptr: UnsafeMutablePointer? = requestJson.withCString { cReq in + if blobBytes.isEmpty { + return affine_ios_workspace_ingest_share_item(handle, cReq, nil, 0) + } + return blobBytes.withUnsafeBytes { raw in + let base = raw.bindMemory(to: UInt8.self).baseAddress + return affine_ios_workspace_ingest_share_item(handle, cReq, base, blobBytes.count) + } + } + guard let ptr else { return nil } + defer { affine_ios_string_free(ptr) } + return String(cString: ptr) + } + + private func takeBytes(_ buffer: AffineIosByteBuffer) -> Data? { + defer { affine_ios_bytes_free(buffer) } + guard let ptr = buffer.ptr, buffer.len > 0 else { + return nil + } + return Data(bytes: ptr, count: buffer.len) + } +} diff --git a/packages/frontend/hosts/ios/include/affine_mobile_host.h b/packages/frontend/hosts/ios/include/affine_mobile_host.h new file mode 100644 index 0000000000..9520d1d2e6 --- /dev/null +++ b/packages/frontend/hosts/ios/include/affine_mobile_host.h @@ -0,0 +1,902 @@ +#ifndef AFFINE_MOBILE_HOST_H +#define AFFINE_MOBILE_HOST_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct AffineIosHost AffineIosHost; +typedef struct AffineIosWorkspace AffineIosWorkspace; + +typedef struct AffineIosByteBuffer { + uint8_t *ptr; + size_t len; +} AffineIosByteBuffer; + +typedef struct AffineWindowInsets { + float safe_top; + float safe_right; + float safe_bottom; + float safe_left; + /* Absolute docked keyboard overlap height from the window bottom edge in logical points + * (0 for floating, split, hardware, or hidden keyboards). Do not subtract safe_bottom; + * Rust ui::WindowInsets::effective() computes safe_area.bottom.max(ime.bottom). */ + float ime_bottom; +} AffineWindowInsets; + +typedef struct AffineUtf16Range { + uint32_t location; + uint32_t length; +} AffineUtf16Range; + +typedef struct AffinePoint { + float x; + float y; +} AffinePoint; + +typedef struct AffineRect { + float x; + float y; + float width; + float height; +} AffineRect; + +typedef struct AffineTeardropHandleLayout { + bool visible; + bool drop_above; + float stem_x; + float stem_top_y; + float stem_bottom_y; + float stem_width; + float drop_center_x; + float drop_center_y; + float drop_radius; + float drop_offset_x; +} AffineTeardropHandleLayout; + +typedef struct AffineLoupeLayout { + bool visible; + float center_x; + float center_y; + float focus_x; + float focus_y; + float diameter; + float zoom_scale; +} AffineLoupeLayout; + +typedef struct AffineSelectionOverlayState { + bool has_selection; + bool is_collapsed; + bool is_rtl; + uint8_t active_drag_handle; + bool show_floating_menu; + AffineUtf16Range range; + AffinePoint drag_probe_point; + AffineTeardropHandleLayout start_handle; + AffineTeardropHandleLayout end_handle; + AffineLoupeLayout loupe; + AffineRect menu_anchor_rect; +} AffineSelectionOverlayState; + +typedef struct AffineKeyboardAvoidanceMetrics { + float raw_overlap_pt; + float ime_bottom_pt; + float ime_above_safe_bottom_pt; + float effective_bottom_pt; + bool is_floating_or_split; + bool is_hardware_or_hidden; +} AffineKeyboardAvoidanceMetrics; + +typedef struct AffinePdfPageSize { + float width_pt; + float height_pt; +} AffinePdfPageSize; + +typedef struct AffinePdfRenderPlan { + uint32_t target_width_px; + uint32_t target_height_px; + size_t byte_len; + uint32_t error; +} AffinePdfRenderPlan; + +typedef void (*AffineHapticsCallback)(uint8_t pattern, void *user_data); + +typedef uint64_t (*AffinePdfOpenDocFn)( + const uint8_t *pdf_ptr, + size_t pdf_len, + void *user_data); + +typedef void (*AffinePdfCloseDocFn)( + uint64_t doc_id, + void *user_data); + +typedef uint32_t (*AffinePdfDocPageCountFn)( + uint64_t doc_id, + void *user_data); + +typedef bool (*AffinePdfDocPageSizeFn)( + uint64_t doc_id, + uint32_t page_index, + AffinePdfPageSize *out_size, + void *user_data); + +typedef bool (*AffinePdfDocRenderRgba8Fn)( + uint64_t doc_id, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint8_t *out_rgba_ptr, + size_t out_rgba_len, + void *user_data); + +typedef struct AffinePdfProvider { + AffinePdfOpenDocFn open_doc; + AffinePdfCloseDocFn close_doc; + AffinePdfDocPageCountFn doc_page_count; + AffinePdfDocPageSizeFn doc_page_size; + AffinePdfDocRenderRgba8Fn doc_render_rgba8; + void *user_data; +} AffinePdfProvider; + +typedef struct AffineSelectionRect { + AffineRect rect; + bool contains_start; + bool contains_end; +} AffineSelectionRect; + +typedef AffineRect (*AffineTextCaretRectFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + uint32_t utf16_offset, + float viewport_w, + AffineWindowInsets insets, + void *user_data); + +typedef uint32_t (*AffineTextClosestOffsetFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffinePoint point, + uint32_t preferred_offset, + float viewport_w, + AffineWindowInsets insets, + void *user_data); + +typedef size_t (*AffineTextSelectionRectsFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range range, + float viewport_w, + AffineWindowInsets insets, + AffineSelectionRect *out_rects, + size_t capacity, + void *user_data); + +typedef bool (*AffineTextSelectionEndpointCaretsFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range range, + float viewport_w, + AffineWindowInsets insets, + AffineRect *out_start, + AffineRect *out_end, + void *user_data); + +typedef bool (*AffineTextRenderLoupeRgba8Fn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range selected_range, + float viewport_w, + AffineWindowInsets insets, + float focus_x, + float focus_y, + uint32_t diameter_px, + float zoom_scale, + uint8_t *out_rgba_ptr, + size_t out_rgba_len, + void *user_data); + +typedef struct AffineTextProvider { + AffineTextCaretRectFn caret_rect; + AffineTextClosestOffsetFn closest_offset; + AffineTextSelectionRectsFn selection_rects; + AffineTextSelectionEndpointCaretsFn selection_endpoint_carets; + AffineTextRenderLoupeRgba8Fn render_loupe_rgba8; + void *user_data; +} AffineTextProvider; + +void affine_ios_string_free(char *ptr); + +void affine_ios_bytes_free(AffineIosByteBuffer buf); + +AffineIosHost *affine_ios_host_create( + void *metal_layer, + float width_pt, + float height_pt, + float scale_factor); + +/* Mobile product shell root (Home, Explorer, Journals, Search, Settings, Page). */ +AffineIosHost *affine_ios_host_create_shell( + void *metal_layer, + float width_pt, + float height_pt, + float scale_factor, + const char *language_tag, + int64_t now_ms, + int32_t utc_offset_minutes, + bool dark); + +/* 0 bare editor root, 1 Home, 2 Explorer, 3 Journals, 4 Search, 5 Page, 6 Settings. */ +uint8_t affine_ios_host_shell_route(const AffineIosHost *host); + +bool affine_ios_host_handle_back(AffineIosHost *host); + +/* Free with affine_ios_string_free. */ +char *affine_ios_host_shell_accessibility_json(const AffineIosHost *host); + +bool affine_ios_host_shell_mount_workspace( + AffineIosHost *host, + const char *base_dir, + const char *space_type, + const char *peer, + const char *space_id, + const char *name, + int64_t now_ms); + +int64_t affine_ios_host_shell_flush_workspace(AffineIosHost *host); + +void affine_ios_host_destroy(AffineIosHost *host); + +void affine_ios_host_resize( + AffineIosHost *host, + float width_pt, + float height_pt, + float scale_factor); + +void affine_ios_host_set_insets( + AffineIosHost *host, + AffineWindowInsets insets); + +uint32_t affine_ios_host_render_frame( + AffineIosHost *host, + double frame_timestamp_sec); + +bool affine_ios_host_is_dirty(const AffineIosHost *host); + +int64_t affine_ios_host_next_timer_delay_ms(AffineIosHost *host); + +typedef void (*AffineFrameWakeCallback)(void *user_data); + +void affine_ios_host_set_frame_wake_callback( + AffineIosHost *host, + AffineFrameWakeCallback callback, + void *user_data); + +void affine_ios_host_request_frame(AffineIosHost *host); + +void affine_ios_host_insert_text( + AffineIosHost *host, + const uint16_t *utf16_ptr, + size_t utf16_len); + +void affine_ios_host_delete_backward(AffineIosHost *host); + +void affine_ios_host_delete_range( + AffineIosHost *host, + AffineUtf16Range range); + +void affine_ios_host_set_selected_range( + AffineIosHost *host, + AffineUtf16Range range); + +void affine_ios_host_replace_range( + AffineIosHost *host, + AffineUtf16Range range, + const uint16_t *utf16_ptr, + size_t utf16_len); + +void affine_ios_host_set_marked_text( + AffineIosHost *host, + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range selected_range); + +void affine_ios_host_unmark_text(AffineIosHost *host); + +AffineUtf16Range affine_ios_host_selected_range(const AffineIosHost *host); + +AffineUtf16Range affine_ios_host_marked_range(const AffineIosHost *host); + +bool affine_ios_host_wants_code_input(const AffineIosHost *host); + +typedef void (*AffineTextInputChangedCallback)(uint8_t change_kind, void *user_data); + +bool affine_ios_host_is_dark_theme(const AffineIosHost *host); + +void affine_ios_host_set_dark_theme(AffineIosHost *host, bool dark); + +void *affine_ios_host_metal_layer(const AffineIosHost *host); + +size_t affine_ios_host_utf16_len(const AffineIosHost *host); + +size_t affine_ios_host_copy_utf16( + const AffineIosHost *host, + uint16_t *out_ptr, + size_t capacity); + +void affine_ios_host_touch_event( + AffineIosHost *host, + uint64_t touch_id, + uint8_t phase, + float x, + float y); + +void affine_ios_host_key_down( + AffineIosHost *host, + const char *key, + const char *key_char, + bool shift, + bool cmd, + bool ctrl, + bool alt); + +void affine_ios_host_set_form_factor( + AffineIosHost *host, + uint8_t form_factor); + +bool affine_ios_host_edgeless_readonly(const AffineIosHost *host); + +bool affine_ios_host_database_readonly(const AffineIosHost *host); + +bool affine_ios_host_wants_software_keyboard(const AffineIosHost *host); + +bool affine_ios_host_take_software_keyboard_request(AffineIosHost *host); + +void affine_ios_host_set_mode( + AffineIosHost *host, + uint8_t mode); + +void affine_ios_host_set_text_input_callback( + AffineIosHost *host, + AffineTextInputChangedCallback cb, + void *user_data); + +typedef void (*AffineOpenUrlCallback)(const char *url_utf8, void *user_data); + +void affine_ios_host_set_open_url_callback( + AffineIosHost *host, + AffineOpenUrlCallback cb, + void *user_data); + +uint64_t affine_ios_host_text_input_change_seq(const AffineIosHost *host); + +void affine_ios_host_reset_empty_doc(AffineIosHost *host); + +void affine_ios_host_load_showcase_doc(AffineIosHost *host); + +char *affine_ios_auth_canonical_endpoint(const char *endpoint); + +char *affine_ios_auth_legacy_storage_endpoint_key(const char *endpoint); + +char *affine_ios_auth_parse_keychain_json( + const char *json, + double now_unix_secs, + double min_validity_secs, + bool *out_is_valid, + double *out_access_expires_unix_secs); + +char *affine_ios_auth_encode_token_response_json( + const char *response_json, + int64_t now_unix_ms); + +char *affine_ios_auth_resolve_installation_id( + const char *existing, + bool *out_created); + +bool affine_ios_auth_error_permanently_invalidates_session(const char *error_json); + +bool affine_ios_legacy_is_permitted_key(const char *key); +char *affine_ios_legacy_storage_parse_snapshot_json(const char *snapshot_json); + +char *affine_ios_legacy_storage_plan_write_back_json( + const char *state_json, + const char *previous_keys_json); + +bool affine_ios_legacy_storage_verify_write_back_json( + const char *plan_json, + const char *readback_snapshot_json); + +char *affine_ios_workspace_resolve_path( + const char *documents_dir, + const char *space_type, + const char *peer, + const char *space_id); + +AffineIosWorkspace *affine_ios_workspace_open( + const char *documents_dir, + const char *space_type, + const char *peer, + const char *space_id, + const char *allowlist_json_or_null); + +void affine_ios_workspace_close(AffineIosWorkspace *ws); + +AffineIosByteBuffer affine_ios_workspace_read_doc( + const AffineIosWorkspace *ws, + const char *doc_id); + +char *affine_ios_workspace_read_page_snapshot_json( + const AffineIosWorkspace *ws, + const char *doc_id, + uint64_t client_id); + +AffineIosByteBuffer affine_ios_workspace_edit_paragraph_text( + const AffineIosWorkspace *ws, + const char *doc_id, + const char *block_id, + uint64_t utf16_index, + uint64_t delete_len, + const char *insert_text, + uint64_t client_id, + int64_t now_ms); + +AffineIosByteBuffer affine_ios_workspace_export_doc_diff( + const AffineIosWorkspace *ws, + const char *doc_id, + const uint8_t *remote_sv_ptr, + size_t remote_sv_len); + +AffineIosByteBuffer affine_ios_workspace_apply_remote_update( + const AffineIosWorkspace *ws, + const char *doc_id, + const uint8_t *update_ptr, + size_t update_len, + const char *peer, + int64_t remote_clock_ms, + int64_t local_now_ms); + +bool affine_ios_workspace_checkpoint_passive(const AffineIosWorkspace *ws); + +bool affine_ios_workspace_checkpoint(const AffineIosWorkspace *ws); + +AffineWindowInsets affine_ios_host_insets(const AffineIosHost *host); + +float affine_ios_host_ime_above_safe_bottom(const AffineIosHost *host); + +AffineKeyboardAvoidanceMetrics affine_ios_keyboard_compute_avoidance( + AffineRect window_bounds, + AffineRect keyboard_frame_in_window, + float safe_bottom, + bool is_hidden); + +void affine_ios_host_begin_keyboard_transition( + AffineIosHost *host, + float target_ime_bottom_pt, + double start_timestamp_sec, + double duration_sec); + +AffineWindowInsets affine_ios_host_sample_keyboard_frame( + AffineIosHost *host, + float safe_top, + float safe_right, + float safe_bottom, + float safe_left, + double frame_timestamp_sec); + +AffineSelectionOverlayState affine_ios_host_selection_set( + AffineIosHost *host, + AffineRect start_caret, + AffineRect end_caret, + AffineUtf16Range range, + uint8_t writing_direction); + +void affine_ios_host_selection_clear(AffineIosHost *host); + +AffineSelectionOverlayState affine_ios_host_selection_state( + const AffineIosHost *host); + +uint8_t affine_ios_host_selection_hit_test( + const AffineIosHost *host, + AffinePoint point, + float hit_radius_pt); + +bool affine_ios_host_selection_begin_drag( + AffineIosHost *host, + uint8_t handle_kind, + AffinePoint touch_point); + +AffinePoint affine_ios_host_selection_drag_probe( + const AffineIosHost *host, + AffinePoint touch_point); + +uint32_t affine_ios_host_selection_drag_anchor( + const AffineIosHost *host); + +AffineSelectionOverlayState affine_ios_host_selection_apply_drag_endpoints( + AffineIosHost *host, + AffinePoint touch_point, + uint32_t target_offset, + AffineRect start_caret, + AffineRect end_caret); + +AffineSelectionOverlayState affine_ios_host_selection_end_drag( + AffineIosHost *host); + +void affine_ios_host_set_text_provider( + AffineIosHost *host, + AffineTextProvider provider); + +uint8_t affine_ios_host_text_writing_direction( + const AffineIosHost *host); + +AffineRect affine_ios_host_text_caret_rect( + const AffineIosHost *host, + uint32_t utf16_offset); + +size_t affine_ios_host_text_selection_rects( + const AffineIosHost *host, + AffineUtf16Range range, + AffineSelectionRect *out_rects, + size_t capacity); + +bool affine_ios_host_text_selection_endpoint_carets( + const AffineIosHost *host, + AffineUtf16Range range, + AffineRect *out_start, + AffineRect *out_end); + +uint32_t affine_ios_host_text_closest_offset( + const AffineIosHost *host, + AffinePoint point); + +uint32_t affine_ios_host_text_closest_offset_preferred( + const AffineIosHost *host, + AffinePoint point, + uint32_t preferred_offset); + +AffineIosByteBuffer affine_ios_host_render_loupe_rgba8( + const AffineIosHost *host, + float focus_x, + float focus_y, + uint32_t diameter_px, + float zoom_scale); + +uint32_t affine_ios_pdf_validate_bytes( + const uint8_t *pdf_ptr, + size_t pdf_len); + +AffinePdfRenderPlan affine_ios_pdf_plan_render( + uint32_t page_index, + uint32_t page_count, + uint32_t target_width_px, + uint32_t target_height_px); + +void affine_ios_host_set_pdf_provider( + AffineIosHost *host, + AffinePdfProvider provider); + +uint64_t affine_ios_host_pdf_open( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t *out_error); + +void affine_ios_host_pdf_close( + const AffineIosHost *host, + uint64_t doc_id); + +uint32_t affine_ios_host_pdf_doc_page_count( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t *out_error); + +bool affine_ios_host_pdf_doc_page_size( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t page_index, + AffinePdfPageSize *out_size, + uint32_t *out_error); + +AffineIosByteBuffer affine_ios_host_pdf_doc_render_page_rgba8( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint32_t *out_error); + +/* Stateless convenience wrappers; production callers should prefer affine_ios_host_pdf_open/close handles. */ +uint32_t affine_ios_host_pdf_page_count( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t *out_error); + +AffineIosByteBuffer affine_ios_host_pdf_render_page_rgba8( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint32_t *out_error); + +void affine_ios_host_set_haptics_callback( + AffineIosHost *host, + AffineHapticsCallback callback, + void *user_data); + +bool affine_ios_host_trigger_haptic( + AffineIosHost *host, + uint8_t pattern); + +uint64_t affine_ios_host_haptic_count( + const AffineIosHost *host, + uint8_t pattern); + +uint64_t affine_ios_host_haptic_total_count( + const AffineIosHost *host); + +/* Document-level selection, multi-MIME clipboard, and full-document UITextPosition C ABI. */ + +typedef void (*AffineClipboardWriteFn)( + const uint8_t *utf8_ptr, + size_t utf8_len, + void *user_data); + +typedef void (*AffineClipboardReadSinkFn)( + const uint8_t *utf8_ptr, + size_t utf8_len, + void *ctx); + +typedef void (*AffineClipboardReadFn)( + AffineClipboardReadSinkFn sink, + void *ctx, + void *user_data); + +typedef struct AffineClipboardProvider { + AffineClipboardWriteFn write_json; + AffineClipboardReadFn read_json; + void *user_data; +} AffineClipboardProvider; + +typedef struct AffineDocumentSelectionSnapshot { + bool has_selection; + bool is_collapsed; + bool is_reversed; + bool start_is_rtl; + bool end_is_rtl; + bool start_visible; + bool end_visible; + bool menu_anchor_visible; + bool menu_suppressed_for_motion; + AffineRect start_caret; + AffineRect end_caret; + AffineRect menu_anchor_rect; + uint32_t action_mask; + uint64_t menu_request_seq; + size_t rect_count; +} AffineDocumentSelectionSnapshot; + +typedef struct AffineDocumentSelectionRect { + AffineRect rect; + bool is_rtl; + bool contains_start; + bool contains_end; +} AffineDocumentSelectionRect; + +typedef struct AffineDocPosition { + bool valid; + int32_t block_order; + uint32_t utf16_offset; + uint64_t endpoint_token; +} AffineDocPosition; + +void affine_ios_host_set_clipboard_provider( + AffineIosHost *host, + AffineClipboardProvider provider); + +void affine_ios_host_set_page_readonly( + AffineIosHost *host, + bool readonly); + +bool affine_ios_host_is_surface_readonly( + const AffineIosHost *host); + +void affine_ios_host_restore_software_keyboard( + AffineIosHost *host); + +AffineDocumentSelectionSnapshot affine_ios_host_document_selection_snapshot( + const AffineIosHost *host); + +void affine_ios_host_doc_selection_endpoint_tokens( + const AffineIosHost *host, + uint64_t *out_start, + uint64_t *out_end); + +size_t affine_ios_host_document_selection_rects( + const AffineIosHost *host, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +size_t affine_ios_host_doc_selection_preview_rects( + const AffineIosHost *host, + uint64_t fixed_endpoint_token, + float fx, + float fy, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +bool affine_ios_host_doc_caret_rect_at_point( + const AffineIosHost *host, + float x, + float y, + AffineRect *out_rect); + +char *affine_ios_host_selected_plain_text( + const AffineIosHost *host); + +bool affine_ios_host_should_forward_touch_immediately( + const AffineIosHost *host, + float x, + float y); + +bool affine_ios_host_select_word_at_point( + AffineIosHost *host, + float x, + float y); + +void affine_ios_host_bump_selection_menu_request_seq( + AffineIosHost *host); + +bool affine_ios_host_doc_selection_begin_drag( + AffineIosHost *host, + uint8_t handle); + +bool affine_ios_host_doc_selection_update_drag( + AffineIosHost *host, + float x, + float y); + +void affine_ios_host_doc_selection_end_drag( + AffineIosHost *host); + +bool affine_ios_host_doc_selection_select_from_endpoint_token( + AffineIosHost *host, + uint64_t fixed_endpoint_token, + float fx, + float fy); + +bool affine_ios_host_doc_selection_select_between_points( + AffineIosHost *host, + float ax, + float ay, + float fx, + float fy); + +bool affine_ios_host_doc_selection_select_between_endpoint_tokens( + AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token); + +void affine_ios_host_selection_action_copy(AffineIosHost *host); +void affine_ios_host_selection_action_cut(AffineIosHost *host); +void affine_ios_host_selection_action_paste(AffineIosHost *host); +void affine_ios_host_selection_action_select_all(AffineIosHost *host); + +int32_t affine_ios_host_focused_block_order(const AffineIosHost *host); + +bool affine_ios_host_doc_document_bounds( + const AffineIosHost *host, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +bool affine_ios_host_doc_selection_positions( + const AffineIosHost *host, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +AffineDocPosition affine_ios_host_doc_hit_position( + const AffineIosHost *host, + float x, + float y); + +bool affine_ios_host_doc_caret_rect_for_token( + const AffineIosHost *host, + uint64_t endpoint_token, + AffineRect *out_rect); + +size_t affine_ios_host_doc_selection_rects_between_tokens( + const AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +AffineDocPosition affine_ios_host_doc_step_position( + const AffineIosHost *host, + uint64_t endpoint_token, + ptrdiff_t delta); + +bool affine_ios_host_doc_word_range( + const AffineIosHost *host, + uint64_t endpoint_token, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +int32_t affine_ios_host_doc_offset_between_tokens( + const AffineIosHost *host, + uint64_t from_token, + uint64_t to_token); + +char *affine_ios_host_doc_text_between_tokens( + const AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token); + +/* Zero-CocoaPods iOS Native Islands (Atomic SQLite ShareExtension, AffinePaywall, Onboarding/SignIn). */ + +char *affine_ios_workspace_ingest_share_item( + const AffineIosWorkspace *ws, + const char *request_json, + const uint8_t *blob_bytes_ptr, + size_t blob_bytes_len); + +AffineIosByteBuffer affine_ios_workspace_read_blob( + const AffineIosWorkspace *ws, + const char *blob_key); + +bool affine_ios_island_paywall_set_products_json( + AffineIosHost *host, + const char *products_json); + +bool affine_ios_island_paywall_begin_purchase( + AffineIosHost *host, + const char *product_id); + +bool affine_ios_island_paywall_complete_jws( + AffineIosHost *host, + const char *product_id, + const char *transaction_id, + const char *jws_representation); + +bool affine_ios_island_paywall_finish_non_verified( + AffineIosHost *host, + uint8_t outcome_kind, + const char *reason); + +bool affine_ios_island_paywall_clear_entitlements(AffineIosHost *host); + +char *affine_ios_island_paywall_state_json(const AffineIosHost *host); + +bool affine_ios_island_onboarding_begin_oauth( + AffineIosHost *host, + const char *csrf_state); + +bool affine_ios_island_onboarding_complete_apple( + AffineIosHost *host, + const char *user_identifier, + const char *identity_token_jws); + +bool affine_ios_island_onboarding_complete_oauth( + AffineIosHost *host, + const char *code, + const char *state); + +bool affine_ios_island_onboarding_confirm_session( + AffineIosHost *host, + const char *subject); + +bool affine_ios_island_onboarding_fail_session( + AffineIosHost *host, + const char *reason); + +char *affine_ios_island_onboarding_state_json(const AffineIosHost *host); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/frontend/hosts/ios/scripts/build-rust-ios.sh b/packages/frontend/hosts/ios/scripts/build-rust-ios.sh new file mode 100755 index 0000000000..51f0c6efab --- /dev/null +++ b/packages/frontend/hosts/ios/scripts/build-rust-ios.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Zero-CocoaPods iOS Rust build helper. +# Explicitly pins Rust 1.98.1 and packages/frontend/Cargo.toml so legacy +# packages/frontend/apps/ios (1.97.1) stays completely isolated. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)" +MANIFEST="$REPO_ROOT/packages/frontend/Cargo.toml" + +TARGET="${1:-aarch64-apple-ios-sim}" +PROFILE="${2:-release}" + +case "$TARGET" in + aarch64-apple-ios | aarch64-apple-ios-sim) ;; + *) + echo "ERROR: unsupported iOS target '$TARGET' (expected aarch64-apple-ios or aarch64-apple-ios-sim)" >&2 + exit 1 + ;; +esac + +PROFILE_ARGS=() +if [ "$PROFILE" = "release" ]; then + PROFILE_ARGS+=(--release) +fi + +CARGO_ENCODED_RUSTFLAGS="" rustup run 1.98.1 cargo build \ + --locked \ + --manifest-path "$MANIFEST" \ + -p affine-ios-host \ + --target "$TARGET" \ + "${PROFILE_ARGS[@]}" diff --git a/packages/frontend/hosts/ios/scripts/check-sim-host.sh b/packages/frontend/hosts/ios/scripts/check-sim-host.sh new file mode 100644 index 0000000000..32952f6ae3 --- /dev/null +++ b/packages/frontend/hosts/ios/scripts/check-sim-host.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -euo pipefail + +state_dir=$(mktemp -d "${RUNNER_TEMP:-/tmp}/ios-sim.XXXXXXXX") +enum_pid= +cleanup() { + if [[ -n "$enum_pid" ]]; then + kill -KILL -- "-$enum_pid" 2>/dev/null || true + wait "$enum_pid" 2>/dev/null || true + fi + rm -rf "$state_dir" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +# Put device enumeration and its children in one process group. +set -m +( + enum_rc=0 + python3 - > "$state_dir/device" <<'PYTHON' || enum_rc=$? +import json +import subprocess +import sys +import uuid + +try: + result = subprocess.run( + ["xcrun", "simctl", "list", "devices", "available", "-j"], + stdout=subprocess.PIPE, check=True, text=True, timeout=180, + ) + devices = json.loads(result.stdout)["devices"] + for runtime, entries in sorted(devices.items(), reverse=True): + if not runtime.startswith("com.apple.CoreSimulator.SimRuntime.iOS-"): + continue + for device in entries: + state = device["state"] + if (device.get("isAvailable") and "iPhone" in device["name"] + and state in ("Shutdown", "Booted", "Booting")): + print(str(uuid.UUID(device["udid"])).upper(), state) + sys.exit(0) + sys.exit("No available iPhone Simulator.") +except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc: + sys.exit(f"Simulator enumeration failed: {exc}") +PYTHON + printf '%s\n' "$enum_rc" > "$state_dir/status" +) & +enum_pid=$! +set +m + +started=$SECONDS +build_rc=0 +cargo build --locked -p affine-ios-host --target aarch64-apple-ios-sim || build_rc=$? +echo "cargo_build_s=$(( SECONDS - started ))" +if [[ "$build_rc" -ne 0 ]]; then + exit "$build_rc" +fi + +archive=target/aarch64-apple-ios-sim/debug/libaffine_ios_host.a +test -s "$archive" +bytes=$(stat -f '%z' "$archive") +echo "iOS staticlib libaffine_ios_host.a bytes: $bytes" +test "$bytes" -le 650000000 +echo "$(date -u +%FT%TZ) Rust staticlib ready" + +started=$SECONDS +wait "$enum_pid" +echo "sim_enum_wait_s=$(( SECONDS - started ))" +read -r enum_rc < "$state_dir/status" +if [[ "$enum_rc" -ne 0 ]]; then + exit "$enum_rc" +fi +enum_pid= +read -r sim_udid sim_state < "$state_dir/device" +printf 'SIM_UDID=%s\nSIM_STATE=%s\n' "$sim_udid" "$sim_state" >> "$GITHUB_ENV" diff --git a/packages/frontend/hosts/ios/scripts/package-sim-app.sh b/packages/frontend/hosts/ios/scripts/package-sim-app.sh new file mode 100755 index 0000000000..b6a1e75e73 --- /dev/null +++ b/packages/frontend/hosts/ios/scripts/package-sim-app.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build and assemble an installable iOS Simulator `.app` bundle (`AffineIosHost.app`) +# with zero CocoaPods and zero Xcode project files. +# +# Usage: +# ./packages/frontend/hosts/ios/scripts/package-sim-app.sh [debug|release] [out_dir] + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +IOS_HOST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +REPO_ROOT="$(cd "$IOS_HOST_DIR/../../../.." && pwd)" +MANIFEST="$REPO_ROOT/packages/frontend/Cargo.toml" + +PROFILE="${1:-debug}" +OUT_DIR="${2:-$REPO_ROOT/packages/frontend/target/ios-sim-app}" +TARGET="aarch64-apple-ios-sim" + +PROFILE_ARGS=() +PROFILE_SUBDIR="debug" +if [ "$PROFILE" = "release" ]; then + PROFILE_ARGS+=(--release) + PROFILE_SUBDIR="release" +fi + +echo "==> Building libaffine_ios_host.a ($TARGET, $PROFILE)" +CARGO_ENCODED_RUSTFLAGS="" rustup run 1.98.1 cargo build \ + --locked \ + --manifest-path "$MANIFEST" \ + -p affine-ios-host \ + --target "$TARGET" \ + "${PROFILE_ARGS[@]}" + +LIB_DIR="$REPO_ROOT/packages/frontend/target/$TARGET/$PROFILE_SUBDIR" +test -s "$LIB_DIR/libaffine_ios_host.a" + +APP_DIR="$OUT_DIR/AffineIosHost.app" +rm -rf "$APP_DIR" +mkdir -p "$APP_DIR" + +SDK="$(xcrun --sdk iphonesimulator --show-sdk-path)" +echo "==> Linking AffineIosHost against iOS Simulator SDK: $SDK" +swiftc -emit-executable \ + -sdk "$SDK" \ + -target arm64-apple-ios16.0-simulator \ + -import-objc-header "$IOS_HOST_DIR/include/affine_mobile_host.h" \ + -L "$LIB_DIR" \ + -laffine_ios_host \ + -framework UIKit \ + -framework QuartzCore \ + -framework Metal \ + -framework WebKit \ + -framework PDFKit \ + -framework CoreText \ + -framework CoreGraphics \ + -framework CoreVideo \ + -framework CoreFoundation \ + -framework Foundation \ + -framework UniformTypeIdentifiers \ + -framework StoreKit \ + -framework AuthenticationServices \ + -o "$APP_DIR/AffineIosHost" \ + "$IOS_HOST_DIR"/Sources/*.swift + +cp "$IOS_HOST_DIR/Info.plist" "$APP_DIR/Info.plist" +printf 'APPL????' > "$APP_DIR/PkgInfo" +codesign --force --sign - "$APP_DIR" + +test -s "$APP_DIR/AffineIosHost" +test -s "$APP_DIR/Info.plist" +echo "==> Assembled iOS Simulator bundle: $APP_DIR" diff --git a/packages/frontend/hosts/ios/src/auth.rs b/packages/frontend/hosts/ios/src/auth.rs new file mode 100644 index 0000000000..d1e738453d --- /dev/null +++ b/packages/frontend/hosts/ios/src/auth.rs @@ -0,0 +1,538 @@ +pub use affine_store::auth::{ + auth_error_json_permanently_invalidates_session as auth_error_permanently_invalidates_session, + canonical_endpoint, legacy_storage_endpoint_key, +}; +use affine_store::{ + api_client::{ + ApiClientKind, ApiHttpRequest, ApiRequestContext, AuthSessionExchangeRequest, + HEADER_AFFINE_VERSION, HEADER_CLIENT_KIND, build_auth_session_exchange_request, + build_auth_session_refresh_request, build_auth_session_revoke_request, + }, + auth::{ + MAX_EXPIRES_IN_SECS as STORE_MAX_EXPIRES_IN_SECS, STORED_TOKEN_PAIR_VERSION, + is_bearer_token_type, is_valid_rfc3339, + }, + sync::DEFAULT_CLIENT_VERSION, +}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use uuid::Uuid; + +/// Exact offset in seconds between the Unix epoch (1970-01-01T00:00:00Z) and +/// Apple's Foundation reference date (2001-01-01T00:00:00Z). +pub const APPLE_REFERENCE_EPOCH_OFFSET_SECS: f64 = 978_307_200.0; + +/// Keychain `kSecAttrService` used by 0.27.5 `AuthPlugin.swift`. +pub const KEYCHAIN_TOKEN_SERVICE: &str = "app.affine.pro.auth-token"; + +/// `UserDefaults.standard` key storing the persistent device installation ID. +pub const INSTALLATION_ID_DEFAULTS_KEY: &str = "app.affine.pro.auth-installation-id"; + +/// Header identifying native mobile auth requests to AFFiNE backend endpoints. +pub const CLIENT_KIND_HEADER: &str = HEADER_CLIENT_KIND; +pub const CLIENT_KIND_NATIVE: &str = ApiClientKind::Native.as_str(); + +/// Header carrying the AFFiNE client version required by `/api/auth/session/*`. +pub const AFFINE_VERSION_HEADER: &str = HEADER_AFFINE_VERSION; +pub const AFFINE_CLIENT_VERSION: &str = DEFAULT_CLIENT_VERSION; + +/// Maximum valid access-token lifetime accepted from `/api/auth/session/*` responses. +pub const MAX_EXPIRES_IN_SECS: i64 = STORE_MAX_EXPIRES_IN_SECS as i64; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum AuthError { + #[error("invalid JSON payload: {0}")] + InvalidJson(String), + #[error("unsupported stored token pair version: {0}")] + UnsupportedVersion(u32), + #[error("invalid token type: {0}")] + InvalidTokenType(String), + #[error("missing required auth field: {0}")] + MissingField(&'static str), + #[error("invalid expires_in value: {0}")] + InvalidExpiresIn(i64), + #[error("non-finite accessExpiresAt timestamp")] + NonFiniteTimestamp, + #[error("invalid ISO-8601 timestamp in {field}: {value}")] + InvalidIsoTimestamp { field: &'static str, value: String }, + #[error("invalid endpoint URL: {0}")] + InvalidEndpoint(String), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionInfo { + pub id: String, + pub absolute_expires_at: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthTokenResponse { + pub token_type: String, + pub access_token: String, + pub expires_in: i64, + pub refresh_token: String, + pub refresh_expires_at: String, + pub session: AuthSessionInfo, +} + +/// Keychain payload matching 0.27.5 `AuthPlugin.swift` `StoredAuthTokenPair`. +/// +/// `access_expires_at` stores Apple `Date.timeIntervalSinceReferenceDate` +/// (seconds since 2001-01-01T00:00:00Z) so rotated tokens stay valid when +/// downgrading back to the 0.27.5 shell. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredAuthTokenPair { + pub version: u32, + pub token_type: String, + pub access_token: String, + pub access_expires_at: f64, + pub refresh_token: String, + pub refresh_expires_at: String, + pub session: AuthSessionInfo, +} + +/// Canonicalized HTTP request descriptor for `/api/auth/session/{exchange,refresh,revoke}`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionHttpRequest { + pub method: String, + pub url: String, + pub client_kind_header: String, + pub client_kind_value: String, + pub version_header: String, + pub version_value: String, + pub body_json: String, +} + +/// Convert Unix epoch seconds (1970-01-01) to Apple reference epoch seconds (2001-01-01). +pub fn unix_secs_to_apple_reference_secs(unix_secs: f64) -> f64 { + unix_secs - APPLE_REFERENCE_EPOCH_OFFSET_SECS +} + +/// Convert Apple reference epoch seconds (2001-01-01) to Unix epoch seconds (1970-01-01). +pub fn apple_reference_secs_to_unix_secs(apple_secs: f64) -> f64 { + apple_secs + APPLE_REFERENCE_EPOCH_OFFSET_SECS +} + +fn validate_iso8601(field: &'static str, value: &str) -> Result<(), AuthError> { + if !is_valid_rfc3339(value) { + return Err(AuthError::InvalidIsoTimestamp { + field, + value: value.to_string(), + }); + } + Ok(()) +} + +impl StoredAuthTokenPair { + /// Parse and validate a Keychain JSON payload matching `AuthPlugin.swift:236-245`. + pub fn from_json(json: &str) -> Result { + let pair: Self = + serde_json::from_str(json).map_err(|err| AuthError::InvalidJson(err.to_string()))?; + pair.validate()?; + Ok(pair) + } + + /// Validate all invariants enforced by 0.27.5 `AuthSessionBroker.read`. + pub fn validate(&self) -> Result<(), AuthError> { + if self.version != STORED_TOKEN_PAIR_VERSION { + return Err(AuthError::UnsupportedVersion(self.version)); + } + if !is_bearer_token_type(&self.token_type) { + return Err(AuthError::InvalidTokenType(self.token_type.clone())); + } + if self.access_token.is_empty() { + return Err(AuthError::MissingField("accessToken")); + } + if self.refresh_token.is_empty() { + return Err(AuthError::MissingField("refreshToken")); + } + if !self.access_expires_at.is_finite() || !self.access_expires_at_unix_secs().is_finite() { + return Err(AuthError::NonFiniteTimestamp); + } + validate_iso8601("refreshExpiresAt", &self.refresh_expires_at)?; + validate_iso8601( + "session.absoluteExpiresAt", + &self.session.absolute_expires_at, + )?; + Ok(()) + } + + /// Convert a server `/api/auth/session/{exchange,refresh}` response into a + /// Keychain-ready `StoredAuthTokenPair` using an explicit `now_unix_ms` clock. + pub fn from_token_response( + response: &AuthTokenResponse, + now_unix_ms: i64, + ) -> Result { + if !is_bearer_token_type(&response.token_type) { + return Err(AuthError::InvalidTokenType(response.token_type.clone())); + } + if response.access_token.is_empty() { + return Err(AuthError::MissingField("accessToken")); + } + if response.refresh_token.is_empty() { + return Err(AuthError::MissingField("refreshToken")); + } + if !(1..=MAX_EXPIRES_IN_SECS).contains(&response.expires_in) { + return Err(AuthError::InvalidExpiresIn(response.expires_in)); + } + validate_iso8601("refreshExpiresAt", &response.refresh_expires_at)?; + validate_iso8601( + "session.absoluteExpiresAt", + &response.session.absolute_expires_at, + )?; + + let expires_unix_secs = (now_unix_ms as f64) / 1000.0 + (response.expires_in as f64); + let pair = Self { + version: STORED_TOKEN_PAIR_VERSION, + token_type: response.token_type.clone(), + access_token: response.access_token.clone(), + access_expires_at: unix_secs_to_apple_reference_secs(expires_unix_secs), + refresh_token: response.refresh_token.clone(), + refresh_expires_at: response.refresh_expires_at.clone(), + session: response.session.clone(), + }; + pair.validate()?; + Ok(pair) + } + + /// Serialize to 0.27.5-compatible Keychain JSON (`accessExpiresAt` in 2001 epoch seconds). + pub fn to_json(&self) -> Result { + self.validate()?; + serde_json::to_string(self).map_err(|err| AuthError::InvalidJson(err.to_string())) + } + + /// Return `accessExpiresAt` converted to Unix epoch seconds (1970-01-01 UTC). + pub fn access_expires_at_unix_secs(&self) -> f64 { + apple_reference_secs_to_unix_secs(self.access_expires_at) + } + + /// Return whether the access token has strictly more than `min_validity_secs` + /// remaining relative to `now_unix_secs`. + pub fn is_access_token_valid(&self, now_unix_secs: f64, min_validity_secs: f64) -> bool { + let remaining = self.access_expires_at_unix_secs() - now_unix_secs; + remaining.is_finite() && remaining > min_validity_secs + } +} + +/// Reuse an existing persisted `app.affine.pro.auth-installation-id` value without +/// modifying it; generate a new lowercase UUID v4 only on a genuine fresh install. +/// +/// Returns `(installation_id, created_new)`. +pub fn resolve_installation_id(existing: Option<&str>) -> (String, bool) { + if let Some(value) = existing { + if !value.trim().is_empty() { + return (value.to_string(), false); + } + } + (Uuid::new_v4().as_hyphenated().to_string(), true) +} + +fn require_canonical_endpoint(endpoint: &str) -> Result { + let canonical = canonical_endpoint(endpoint); + if !canonical.starts_with("http://") && !canonical.starts_with("https://") { + return Err(AuthError::InvalidEndpoint(endpoint.to_string())); + } + Ok(canonical) +} + +fn to_ios_http_request( + base: &str, + req: ApiHttpRequest, +) -> Result { + let body_json = String::from_utf8(req.body.unwrap_or_default()) + .map_err(|err| AuthError::InvalidJson(err.to_string()))?; + Ok(AuthSessionHttpRequest { + method: "POST".to_string(), + url: format!("{base}{}", req.path), + client_kind_header: CLIENT_KIND_HEADER.to_string(), + client_kind_value: CLIENT_KIND_NATIVE.to_string(), + version_header: AFFINE_VERSION_HEADER.to_string(), + version_value: AFFINE_CLIENT_VERSION.to_string(), + body_json, + }) +} + +/// Build the `/api/auth/session/exchange` request payload with `x-affine-client-kind: native`. +pub fn build_exchange_request( + endpoint: &str, + code: &str, + installation_id: &str, + device_name: &str, +) -> Result { + if code.is_empty() { + return Err(AuthError::MissingField("code")); + } + if installation_id.trim().is_empty() { + return Err(AuthError::MissingField("installationId")); + } + let base = require_canonical_endpoint(endpoint)?; + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_exchange_request( + &ctx, + &AuthSessionExchangeRequest { + code: code.to_string(), + installation_id: installation_id.to_string(), + platform: "ios".to_string(), + device_name: Some(device_name.to_string()), + }, + ) + .map_err(|err| AuthError::InvalidJson(err.to_string()))?; + to_ios_http_request(&base, req) +} + +/// Build the `/api/auth/session/refresh` request payload with `x-affine-client-kind: native`. +pub fn build_refresh_request( + endpoint: &str, + refresh_token: &str, +) -> Result { + if refresh_token.is_empty() { + return Err(AuthError::MissingField("refreshToken")); + } + let base = require_canonical_endpoint(endpoint)?; + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_refresh_request(&ctx, refresh_token, None) + .map_err(|err| AuthError::InvalidJson(err.to_string()))?; + to_ios_http_request(&base, req) +} + +/// Build the `/api/auth/session/revoke` request payload with `x-affine-client-kind: native`. +pub fn build_revoke_request( + endpoint: &str, + refresh_token: &str, +) -> Result { + if refresh_token.is_empty() { + return Err(AuthError::MissingField("refreshToken")); + } + let base = require_canonical_endpoint(endpoint)?; + let ctx = ApiRequestContext::native(None); + let req = build_auth_session_revoke_request(&ctx, refresh_token) + .map_err(|err| AuthError::InvalidJson(err.to_string()))?; + to_ios_http_request(&base, req) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_endpoint_matches_0275_swift_rules() { + let cases = [ + ("https://APP.AFFINE.PRO", "https://app.affine.pro"), + ( + "https://app.affine.pro:443/graphql", + "https://app.affine.pro", + ), + ("http://LOCALHOST:80/api", "http://localhost"), + ( + "https://self-host.example.com:3010/ws?x=1", + "https://self-host.example.com:3010", + ), + ("http://127.0.0.1:8080/", "http://127.0.0.1:8080"), + ("https://[::1]:443/graphql", "https://[::1]"), + ("https://[::1]:8443/graphql", "https://[::1]:8443"), + ("not-a-url", "not-a-url"), + ]; + for (input, expected) in cases { + assert_eq!(canonical_endpoint(input), expected, "input={input}"); + } + assert_eq!( + legacy_storage_endpoint_key("https://[::1]:443/graphql"), + "https://::1" + ); + assert_eq!( + legacy_storage_endpoint_key("https://[::1]:8443/graphql"), + "https://::1:8443" + ); + } + + #[test] + fn keychain_2001_epoch_roundtrip_and_rotation_preserve_0275_compatibility() { + // 2026-11-25T10:00:00Z in Unix seconds = 1_795_600_800.0 + // In Apple 2001 reference epoch seconds = 1_795_600_800.0 - 978_307_200.0 = 817_293_600.0 + let now_unix_secs = 1_795_600_000.0; + let legacy_access_expires_2001 = unix_secs_to_apple_reference_secs(now_unix_secs + 800.0); + assert_eq!(legacy_access_expires_2001, 817_293_600.0); + + let legacy_keychain_json = format!( + r#"{{ + "version": 1, + "tokenType": "Bearer", + "accessToken": "acc-legacy-0275", + "accessExpiresAt": {legacy_access_expires_2001}, + "refreshToken": "ref-legacy-0275", + "refreshExpiresAt": "2026-12-25T10:00:00.000Z", + "session": {{ + "id": "sess-0275", + "absoluteExpiresAt": "2027-05-25T10:00:00.000Z" + }} + }}"# + ); + + let parsed = StoredAuthTokenPair::from_json(&legacy_keychain_json).unwrap(); + assert_eq!(parsed.access_expires_at, 817_293_600.0); + assert_eq!(parsed.access_expires_at_unix_secs(), now_unix_secs + 800.0); + assert!(parsed.is_access_token_valid(now_unix_secs, 120.0)); + assert!(!parsed.is_access_token_valid(now_unix_secs + 700.0, 120.0)); + + // Rotate token via refresh response and encode back for Keychain write-back. + let rotated_resp = AuthTokenResponse { + token_type: "Bearer".into(), + access_token: "acc-rotated-s2".into(), + expires_in: 3600, + refresh_token: "ref-rotated-s2".into(), + refresh_expires_at: "2027-01-25T10:00:00.000Z".into(), + session: AuthSessionInfo { + id: "sess-0275".into(), + absolute_expires_at: "2027-05-25T10:00:00.000Z".into(), + }, + }; + let rotated = + StoredAuthTokenPair::from_token_response(&rotated_resp, (now_unix_secs as i64) * 1000) + .unwrap(); + let written_json = rotated.to_json().unwrap(); + let raw_value: serde_json::Value = serde_json::from_str(&written_json).unwrap(); + let written_epoch_2001 = raw_value["accessExpiresAt"].as_f64().unwrap(); + assert_eq!( + written_epoch_2001, + unix_secs_to_apple_reference_secs(now_unix_secs + 3600.0) + ); + // Rollback check: 0.27.5 reads the written JSON as 2001-epoch Date seconds. + let rolled_back = StoredAuthTokenPair::from_json(&written_json).unwrap(); + assert_eq!(rolled_back.access_token, "acc-rotated-s2"); + assert!(rolled_back.is_access_token_valid(now_unix_secs, 120.0)); + } + + #[test] + fn installation_id_reuses_legacy_value_and_generates_lowercase_uuid_only_on_fresh_install() { + let (reused, created) = + resolve_installation_id(Some("A1B2C3D4-E5F6-4789-ABCD-EF0123456789")); + assert!(!created); + assert_eq!(reused, "A1B2C3D4-E5F6-4789-ABCD-EF0123456789"); + + let (fresh, created_fresh) = resolve_installation_id(None); + assert!(created_fresh); + assert_eq!(fresh, fresh.to_ascii_lowercase()); + assert!(Uuid::parse_str(&fresh).is_ok()); + + let (fresh_empty, created_empty) = resolve_installation_id(Some(" ")); + assert!(created_empty); + assert_eq!(fresh_empty, fresh_empty.to_ascii_lowercase()); + assert!(Uuid::parse_str(&fresh_empty).is_ok()); + + let exchange = build_exchange_request( + "https://APP.AFFINE.PRO:443/login", + "ex-code-1", + &reused, + "iPhone 16 Pro", + ) + .unwrap(); + assert_eq!( + exchange.url, + "https://app.affine.pro/api/auth/session/exchange" + ); + assert_eq!(exchange.client_kind_header, "x-affine-client-kind"); + assert_eq!(exchange.client_kind_value, "native"); + assert_eq!(exchange.version_header, "x-affine-version"); + assert_eq!(exchange.version_value, "0.27.5"); + let body: serde_json::Value = serde_json::from_str(&exchange.body_json).unwrap(); + assert_eq!(body["installationId"], reused); + assert_eq!(body["platform"], "ios"); + + let refresh = build_refresh_request("https://app.affine.pro", "ref-1").unwrap(); + assert_eq!( + refresh.url, + "https://app.affine.pro/api/auth/session/refresh" + ); + assert_eq!(refresh.version_header, "x-affine-version"); + assert_eq!(refresh.version_value, "0.27.5"); + let revoke = build_revoke_request("https://app.affine.pro", "ref-1").unwrap(); + assert_eq!(revoke.url, "https://app.affine.pro/api/auth/session/revoke"); + assert_eq!(revoke.version_header, "x-affine-version"); + assert_eq!(revoke.version_value, "0.27.5"); + } + + #[test] + fn permanent_session_invalidation_matches_0275_error_codes() { + let cases = [ + (r#"{"code":"AUTH_SESSION_EXPIRED"}"#, true), + (r#"{"code":"AUTH_SESSION_REVOKED"}"#, true), + (r#"{"code":"REFRESH_TOKEN_INVALID"}"#, true), + (r#"{"code":"REFRESH_TOKEN_REUSED"}"#, true), + (r#"{"code":"UNSUPPORTED_CLIENT_VERSION"}"#, true), + (r#"{"name":"ACCESS_TOKEN_INVALID"}"#, true), + (r#"{"code":"INTERNAL_SERVER_ERROR"}"#, false), + (r#"{"message":"temporary failure"}"#, false), + ("not-json", false), + ]; + for (body, expected) in cases { + assert_eq!( + auth_error_permanently_invalidates_session(body), + expected, + "body={body}" + ); + } + } + + #[test] + fn rejects_invalid_keychain_payloads_and_responses() { + let invalid_cases = [ + r#"{"version":2,"tokenType":"Bearer","accessToken":"a","accessExpiresAt":1.0,"refreshToken":"r","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#, + r#"{"version":1,"tokenType":"Basic","accessToken":"a","accessExpiresAt":1.0,"refreshToken":"r","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#, + r#"{"version":1,"tokenType":"Bearer","accessToken":"","accessExpiresAt":1.0,"refreshToken":"r","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#, + r#"{"version":1,"tokenType":"Bearer","accessToken":"a","accessExpiresAt":1.0,"refreshToken":"r","refreshExpiresAt":"not-a-date","session":{"id":"s","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#, + ]; + for raw in invalid_cases { + assert!(StoredAuthTokenPair::from_json(raw).is_err(), "raw={raw}"); + } + + let bad_resp = AuthTokenResponse { + token_type: "Bearer".into(), + access_token: "a".into(), + expires_in: 0, + refresh_token: "r".into(), + refresh_expires_at: "2026-12-01T00:00:00Z".into(), + session: AuthSessionInfo { + id: "s".into(), + absolute_expires_at: "2027-01-01T00:00:00Z".into(), + }, + }; + assert_eq!( + StoredAuthTokenPair::from_token_response(&bad_resp, 1_795_600_000_000), + Err(AuthError::InvalidExpiresIn(0)) + ); + + // Table-driven cross-platform parity: case-insensitive Bearer and RFC3339 timezone offsets. + let valid_variants = [ + ("Bearer", "2026-12-01T00:00:00Z", "2027-01-01T00:00:00Z"), + ( + "bearer", + "2026-12-01T08:00:00+08:00", + "2027-01-01T00:00:00-05:00", + ), + ( + "BEARER", + "2026-12-01T08:00:00.250+08:00", + "2027-01-01T00:00:00.5Z", + ), + ]; + for (token_type, refresh_ts, abs_ts) in valid_variants { + let resp = AuthTokenResponse { + token_type: token_type.into(), + access_token: "acc".into(), + expires_in: 600, + refresh_token: "ref".into(), + refresh_expires_at: refresh_ts.into(), + session: AuthSessionInfo { + id: "sess".into(), + absolute_expires_at: abs_ts.into(), + }, + }; + let pair = StoredAuthTokenPair::from_token_response(&resp, 1_795_600_000_000).unwrap(); + assert!(StoredAuthTokenPair::from_json(&pair.to_json().unwrap()).is_ok()); + } + } +} diff --git a/packages/frontend/hosts/ios/src/clipboard.rs b/packages/frontend/hosts/ios/src/clipboard.rs new file mode 100644 index 0000000000..315eb1f2f8 --- /dev/null +++ b/packages/frontend/hosts/ios/src/clipboard.rs @@ -0,0 +1,182 @@ +//! Multi-MIME `UIPasteboard.general` bridge for `IosEditorPlatform`. + +use std::{cell::RefCell, ffi::c_void}; + +use ui::ClipboardItem; + +/// Combined in-process fallback and `UIPasteboard.general` provider store for `IosEditorPlatform`. +#[derive(Default)] +pub(crate) struct IosClipboardStore { + item: RefCell>, + provider: RefCell>, +} + +impl IosClipboardStore { + pub(crate) fn set_provider(&self, provider: Option) { + *self.provider.borrow_mut() = provider; + } + + pub(crate) fn write(&self, item: ClipboardItem) { + write_via_provider(*self.provider.borrow(), &item); + *self.item.borrow_mut() = Some(item); + } + + pub(crate) fn read(&self) -> Option { + let provider = *self.provider.borrow(); + if provider.is_some() { + read_via_provider(provider) + } else { + self.item.borrow().clone() + } + } +} + +/// Callback invoked by Rust to write a multi-MIME clipboard JSON payload to `UIPasteboard.general`. +pub type IosClipboardWriteFn = extern "C" fn(*const u8, usize, *mut c_void); + +/// Sink passed into `IosClipboardReadFn` so Swift can synchronously hand back UTF-8 JSON bytes +/// without requiring cross-FFI heap allocation. +pub type IosClipboardReadSinkFn = extern "C" fn(*const u8, usize, *mut c_void); + +/// Callback invoked by Rust to read a multi-MIME clipboard JSON payload from `UIPasteboard.general`. +pub type IosClipboardReadFn = extern "C" fn(IosClipboardReadSinkFn, *mut c_void, *mut c_void); + +/// C-ABI clipboard provider table registered by Swift `MetalHostViewController`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffineClipboardProvider { + pub write_json: Option, + pub read_json: Option, + pub user_data: *mut c_void, +} + +pub(crate) fn clipboard_item_to_json(item: &ClipboardItem) -> String { + let mut map = serde_json::Map::new(); + if let Some(text) = item.text() { + map.insert("text/plain".to_string(), serde_json::Value::String(text)); + } + if let Some(meta_str) = item.metadata() + && let Ok(serde_json::Value::Object(meta)) = + serde_json::from_str::(meta_str) + { + for (k, v) in meta { + if k == "application/x-blocksuite-snapshot" { + let serialized = match v { + serde_json::Value::String(s) => s, + other => other.to_string(), + }; + map.insert(k, serde_json::Value::String(serialized)); + } else if let serde_json::Value::String(s) = v { + map.insert(k, serde_json::Value::String(s)); + } + } + } + serde_json::Value::Object(map).to_string() +} + +pub(crate) fn clipboard_item_from_json(raw: &str) -> Option { + let serde_json::Value::Object(map) = serde_json::from_str::(raw).ok()? + else { + return None; + }; + let plain = map + .get("text/plain") + .and_then(serde_json::Value::as_str) + .unwrap_or("") + .to_string(); + let mut meta = serde_json::Map::new(); + for key in [ + "application/x-blocksuite-snapshot", + "text/html", + "text/markdown", + ] { + if let Some(val) = map.get(key) + && !val.is_null() + { + if let Some(s) = val.as_str() { + if !s.is_empty() { + meta.insert(key.to_string(), serde_json::Value::String(s.to_string())); + } + } else { + meta.insert(key.to_string(), val.clone()); + } + } + } + if !meta.is_empty() { + Some(ClipboardItem::new_string_with_json_metadata( + plain, + serde_json::Value::Object(meta), + )) + } else if !plain.is_empty() { + Some(ClipboardItem::new_string(plain)) + } else { + None + } +} + +pub(crate) fn write_via_provider(provider: Option, item: &ClipboardItem) { + if let Some(p) = provider + && let Some(write_fn) = p.write_json + { + let json = clipboard_item_to_json(item); + write_fn(json.as_ptr(), json.len(), p.user_data); + } +} + +pub(crate) fn read_via_provider( + provider: Option, +) -> Option { + let p = provider?; + let read_fn = p.read_json?; + #[allow(unsafe_code)] + extern "C" fn capture_sink(ptr: *const u8, len: usize, ctx: *mut c_void) { + if ptr.is_null() || len == 0 || ctx.is_null() { + return; + } + // SAFETY: `ctx` points to our local `String`, and `ptr..ptr+len` is valid for this call. + let out = unsafe { &mut *(ctx as *mut String) }; + let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; + if let Ok(s) = core::str::from_utf8(bytes) { + out.clear(); + out.push_str(s); + } + } + let mut captured = String::new(); + read_fn( + capture_sink, + (&mut captured as *mut String).cast::(), + p.user_data, + ); + (!captured.is_empty()) + .then(|| clipboard_item_from_json(&captured)) + .flatten() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleared_system_provider_does_not_resurrect_stale_in_process_item() { + extern "C" fn empty_read( + _sink: IosClipboardReadSinkFn, + _ctx: *mut c_void, + _ud: *mut c_void, + ) { + } + + let store = IosClipboardStore::default(); + store.write(ClipboardItem::new_string("PREVIOUS".to_string())); + assert_eq!(store.read().and_then(|c| c.text()), Some("PREVIOUS".into())); + + store.set_provider(Some(AffineClipboardProvider { + write_json: None, + read_json: Some(empty_read), + user_data: core::ptr::null_mut(), + })); + assert!( + store.read().is_none(), + "registered system provider returning empty must never resurrect stale PREVIOUS text" + ); + } +} diff --git a/packages/frontend/hosts/ios/src/editor_doc_positions.rs b/packages/frontend/hosts/ios/src/editor_doc_positions.rs new file mode 100644 index 0000000000..f176498f15 --- /dev/null +++ b/packages/frontend/hosts/ios/src/editor_doc_positions.rs @@ -0,0 +1,598 @@ +//! Read-only full-document position, document-bounds, and cross-block stepping helpers +//! on [`IosEditorRuntime`]. +//! +//! Bridges `PlaygroundView`'s multi-block `SelectionEndpointAnchor` queries to Swift +//! `UITextPosition` / `UITextRange` across the entire addressable document without +//! mutating editor selection on hit-tests or coordinate queries. + +use playground::{SelectionEndpointAnchor, editor_session::DocPoint}; + +use super::{editor_runtime::IosEditorRuntime, selection::AffineRect}; + +/// C-ABI document-level text position (`block_order`, `utf16_offset`, `endpoint_token`). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AffineDocPosition { + pub valid: bool, + pub block_order: i32, + pub utf16_offset: u32, + pub endpoint_token: u64, +} + +impl IosEditorRuntime { + pub(crate) fn focused_block_order(&mut self) -> i32 { + let view = self.view(); + self.app + .update(|cx| view.read_with(cx, |v, _| v.focused_selection_block_order())) + .unwrap_or(0) + } + + /// Full-document addressable bounds `(beginningOfDocument, endOfDocument)` spanning all + /// editable blocks in layout order (never truncated to the currently focused block). + pub(crate) fn doc_document_bounds(&mut self) -> Option<(AffineDocPosition, AffineDocPosition)> { + let view = self.view(); + let bounds = self + .app + .update(|cx| { + view.read_with(cx, |v, _| { + let layout = v.flow_layout()?; + let mut first: Option<(i32, SelectionEndpointAnchor, u32)> = None; + let mut last: Option<(i32, SelectionEndpointAnchor, u32)> = None; + for (idx, block) in layout.blocks.iter().enumerate() { + if !block.editable() { + continue; + } + if first.is_none() { + first = Some(( + idx as i32, + SelectionEndpointAnchor::Doc(DocPoint::new(&block.block_id, 0)), + 0, + )); + } + let u16_len = block.body.plain.encode_utf16().count() as u32; + last = Some(( + idx as i32, + SelectionEndpointAnchor::Doc(DocPoint::new( + &block.block_id, + u64::from(u16_len), + )), + u16_len, + )); + } + Some((first?, last?)) + }) + }) + .ok() + .flatten()?; + let ((s_ord, s_ep, s_off), (e_ord, e_ep, e_off)) = bounds; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + pub(crate) fn current_selection_doc_positions( + &mut self, + ) -> Option<(AffineDocPosition, AffineDocPosition)> { + let view = self.view(); + let pair = self + .app + .update(|cx| view.read_with(cx, |v, _| v.current_selection_doc_endpoints())) + .ok() + .flatten()?; + let ((s_ep, s_ord, s_off), (e_ep, e_ord, e_off)) = pair; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + /// Pure read-only viewport hit-test: resolves `(block_order, utf16_offset, endpoint_token)` + /// without changing `editor.selection` or focused block state. + pub(crate) fn doc_hit_position(&mut self, x: f32, y: f32) -> Option { + let view = self.view(); + let (ep, ord, off) = self + .app + .update(|cx| view.update(cx, |v, w, _| v.hit_test_doc_position(x, y, w))) + .ok() + .flatten()?; + let tok = self.intern_endpoint_token(ep); + Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: tok, + }) + } + + pub(crate) fn doc_caret_rect_for_token(&mut self, token: u64) -> Option { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view(); + let geom = self + .app + .update(|cx| view.update(cx, |v, w, _| v.caret_rect_for_anchor(&anchor, w))) + .ok() + .flatten()?; + Some(AffineRect { + x: geom.x, + y: geom.y, + width: geom.width.max(2.0), + height: geom.height.max(18.0), + }) + } + + pub(crate) fn doc_selection_rects_between_tokens( + &mut self, + start_token: u64, + end_token: u64, + ) -> Vec { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return Vec::new(); + }; + let view = self.view(); + self.app + .update(|cx| view.update(cx, |v, w, _| v.selection_rects_between_anchors(a, b, w))) + .unwrap_or_default() + } + + /// Step `delta` UTF-16 units from `token`, seamlessly crossing editable block boundaries + /// (`+1` per newline separator, matching `offset_between_anchors`). + pub(crate) fn doc_step_position( + &mut self, + token: u64, + delta: isize, + ) -> Option { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view(); + if let Some((next_ep, ord, off)) = self + .app + .update(|cx| view.read_with(cx, |v, _| v.step_anchor_utf16(&anchor, delta))) + .ok() + .flatten() + { + let next_tok = self.intern_endpoint_token(next_ep); + return Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: next_tok, + }); + } + // Cross-block step for `SelectionEndpointAnchor::Doc`: resolve cumulative UTF-16 offset + // across editable blocks (`+1` newline separator between editable blocks). + let SelectionEndpointAnchor::Doc(pt) = anchor else { + return None; + }; + let cross = self + .app + .update(|cx| { + view.read_with(cx, |v, _| { + let layout = v.flow_layout()?; + let mut editable_spans: Vec<(i32, &str, isize, isize)> = Vec::new(); + let mut acc: isize = 0; + let mut current_cum: Option = None; + for (idx, block) in layout.blocks.iter().enumerate() { + if !block.editable() { + continue; + } + let len = block.body.plain.encode_utf16().count() as isize; + if block.block_id == pt.block_id { + let local = (pt.offset() as isize).clamp(0, len); + current_cum = Some(acc + local); + } + editable_spans.push((idx as i32, block.block_id.as_str(), acc, len)); + acc += len + 1; + } + let total_max = acc.saturating_sub(1).max(0); + let target = current_cum?.checked_add(delta)?; + if target < 0 || target > total_max { + return None; + } + for (i, &(ord, block_id, start, len)) in editable_spans.iter().enumerate() { + let end = start + len; + if target <= end { + let local = (target - start).clamp(0, len) as u32; + return Some(( + SelectionEndpointAnchor::Doc(DocPoint::new( + block_id, + u64::from(local), + )), + ord, + local, + )); + } + // Target landed on the virtual `\n` separator between block `i` and `i+1`. + if target == end + 1 && i + 1 < editable_spans.len() { + let (next_ord, next_id, _, _) = editable_spans[i + 1]; + return Some(( + SelectionEndpointAnchor::Doc(DocPoint::new(next_id, 0)), + next_ord, + 0, + )); + } + } + None + }) + }) + .ok() + .flatten()?; + let (next_ep, ord, off) = cross; + let next_tok = self.intern_endpoint_token(next_ep); + Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: next_tok, + }) + } + + pub(crate) fn doc_word_range( + &mut self, + token: u64, + ) -> Option<(AffineDocPosition, AffineDocPosition)> { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view(); + let ((s_ep, s_ord, s_off), (e_ep, e_ord, e_off)) = self + .app + .update(|cx| view.read_with(cx, |v, _| v.word_anchors_at(&anchor))) + .ok() + .flatten()?; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + pub(crate) fn doc_offset_between_tokens(&mut self, from_token: u64, to_token: u64) -> i32 { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(from_token), + self.lookup_endpoint_token(to_token), + ) else { + return 0; + }; + let view = self.view(); + self.app + .update(|cx| view.read_with(cx, |v, _| v.offset_between_anchors(&a, &b))) + .unwrap_or(0) + } + + pub(crate) fn doc_text_between_tokens(&mut self, start_token: u64, end_token: u64) -> String { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return String::new(); + }; + let view = self.view(); + self.app + .update(|cx| view.read_with(cx, |v, _| v.plain_text_between_anchors(&a, &b))) + .unwrap_or_default() + } + + pub(crate) fn document_selection_geometry(&mut self) -> playground::DocumentSelectionGeometry { + self.app + .update(|cx| { + self.view().update(cx, |view, window, _| { + view.document_selection_geometry(window) + }) + }) + .unwrap_or_default() + } + + pub(crate) fn begin_document_selection_drag(&mut self, handle: u8) -> bool { + self.app + .update(|cx| { + self.view().update(cx, |view, window, _| { + view.begin_document_selection_drag(handle, window) + }) + }) + .unwrap_or(false) + } + + pub(crate) fn update_document_selection_drag(&mut self, x: f32, y: f32) -> bool { + let ok = self + .app + .update(|cx| { + self.view().update(cx, |view, window, cx| { + view.update_document_selection_drag(x, y, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn end_document_selection_drag(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.end_document_selection_drag(window, cx) + }); + }); + self.window.request_frame_now(); + } + + pub(crate) fn intern_endpoint_token( + &mut self, + endpoint: playground::SelectionEndpointAnchor, + ) -> u64 { + if let Some((tok, _)) = self + .endpoint_tokens + .iter() + .find(|(_, existing)| *existing == endpoint) + { + return *tok; + } + let tok = self.next_endpoint_token; + self.next_endpoint_token = self.next_endpoint_token.wrapping_add(1).max(1); + if self.endpoint_tokens.len() >= 4096 { + let active = self + .app + .update(|cx| { + self.view() + .read_with(cx, |v, _| v.ordered_selection_endpoints()) + }) + .ok() + .flatten(); + if let Some(evict_idx) = self + .endpoint_tokens + .iter() + .position(|(_, ep)| active.as_ref().is_none_or(|(s, e)| ep != s && ep != e)) + { + self.endpoint_tokens.remove(evict_idx); + } else { + self.endpoint_tokens.remove(0); + } + } + self.endpoint_tokens.push((tok, endpoint)); + tok + } + + pub(crate) fn current_selection_endpoint_tokens(&mut self) -> (u64, u64) { + let pair = self + .app + .update(|cx| { + self.view() + .read_with(cx, |view, _| view.ordered_selection_endpoints()) + }) + .ok() + .flatten(); + let Some((start_ep, end_ep)) = pair else { + return (0, 0); + }; + let s = self.intern_endpoint_token(start_ep); + let e = self.intern_endpoint_token(end_ep); + (s, e) + } + + pub(crate) fn lookup_endpoint_token( + &self, + token: u64, + ) -> Option { + self.endpoint_tokens + .iter() + .find(|(t, _)| *t == token) + .map(|(_, ep)| ep.clone()) + } + + pub(crate) fn select_from_endpoint_token( + &mut self, + fixed_token: u64, + fx: f32, + fy: f32, + ) -> bool { + let Some(fixed) = self.lookup_endpoint_token(fixed_token) else { + return false; + }; + let ok = self + .app + .update(|cx| { + self.view().update(cx, |view, window, cx| { + view.select_from_anchor_to_viewport_point(fixed, fx, fy, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn select_between_viewport_points( + &mut self, + ax: f32, + ay: f32, + fx: f32, + fy: f32, + ) -> bool { + let ok = self + .app + .update(|cx| { + self.view().update(cx, |view, window, cx| { + view.select_between_viewport_points(ax, ay, fx, fy, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn select_between_endpoint_tokens( + &mut self, + start_token: u64, + end_token: u64, + ) -> bool { + let (Some(start), Some(end)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return false; + }; + let ok = self + .app + .update(|cx| { + self.view().update(cx, |view, window, cx| { + view.select_between_anchors(start, end, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn selection_copy(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |view, window, cx| view.selection_copy(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_cut(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |view, window, cx| view.selection_cut(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_paste(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |view, window, cx| view.selection_paste(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_select_all(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |view, window, cx| view.selection_select_all(window, cx)); + }); + self.window.request_frame_now(); + } +} + +#[cfg(test)] +mod tests { + use playground::FormFactor; + + use crate::{ + AffineUtf16Range, AffineWindowInsets, editor_runtime::IosEditorRuntime, + selection::AffinePoint, + }; + + #[test] + fn full_document_bounds_cross_block_step_and_transient_kb_inset_do_not_lock() { + let mut rt = + IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, false).expect("runtime"); + let p1: Vec = "甲乙丙丁🚀".encode_utf16().collect(); + rt.insert_text(&p1); + let nl: Vec = "\n".encode_utf16().collect(); + let p2: Vec = "Second paragraph".encode_utf16().collect(); + rt.insert_text(&nl); + rt.insert_text(&p2); + let _ = rt.render_frame(1.0); + + // Full-document bounds must span from block 0 offset 0 to last editable block's end, + // even when a different block is focused. + let (doc_start, doc_end) = rt.doc_document_bounds().expect("doc bounds"); + assert!(doc_start.valid && doc_end.valid); + assert!( + doc_end.block_order > doc_start.block_order, + "endOfDocument must reach the last editable block, not just focused block" + ); + let total_len = + rt.doc_offset_between_tokens(doc_start.endpoint_token, doc_end.endpoint_token); + assert!(total_len >= (p1.len() + 1 + p2.len()) as i32); + + // Stepping from doc_start across the first block boundary lands cleanly in the next block. + let stepped = rt + .doc_step_position(doc_start.endpoint_token, (total_len - 1).max(1) as isize) + .expect("cross-block step"); + assert!(stepped.block_order > doc_start.block_order); + + // Transient keyboard inset 300 -> 0 must not self-lock wants_software_keyboard(). + assert!(rt.wants_software_keyboard()); + rt.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 300.0, + }); + assert!(rt.wants_software_keyboard()); + rt.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 0.0, + }); + assert!( + rt.wants_software_keyboard(), + "transient ime_bottom -> 0 must never self-lock software keyboard" + ); + + // Read-only hit-test in an unfocused block must never mutate focused block. + let focused_before = rt.focused_block_order(); + let c0 = rt.caret_rect(0).expect("caret"); + let _ = rt.closest_offset(AffinePoint { + x: c0.x, + y: c0.y + c0.height * 0.5, + }); + assert_eq!(rt.focused_block_order(), focused_before); + let _ = AffineUtf16Range { + location: 0, + length: 0, + }; + } +} diff --git a/packages/frontend/hosts/ios/src/editor_fallback.rs b/packages/frontend/hosts/ios/src/editor_fallback.rs new file mode 100644 index 0000000000..3dc594f08b --- /dev/null +++ b/packages/frontend/hosts/ios/src/editor_fallback.rs @@ -0,0 +1,274 @@ +//! Deterministic non-iOS host dispatcher, atlas, and text system for `affine-ios-host` tests. + +use std::{borrow::Cow, collections::VecDeque, sync::Mutex, time::Duration}; + +use anyhow::Result; +use ui::scheduler::{Clock, TestClock}; +use ui::{ + AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, BaseDirection, Bounds, DevicePixels, + Font, FontId, FontMetrics, FontRun, GlyphId, LineLayout, Pixels, PlatformAtlas, + PlatformDispatcher, PlatformTextSystem, Priority, RenderGlyphParams, RunnableVariant, + ShapedGlyph, ShapedRun, Size, TextRenderingMode, TileId, point, px, size, +}; + +struct ScheduledTimer { + due: ui::scheduler::Instant, + runnable: RunnableVariant, +} + +pub(crate) struct SyncHostDispatcher { + clock: TestClock, + queue: Mutex>, + timers: Mutex>, +} + +impl SyncHostDispatcher { + pub(crate) fn new() -> Self { + Self { + clock: TestClock::new(), + queue: Mutex::new(VecDeque::new()), + timers: Mutex::new(Vec::new()), + } + } + + #[cfg(test)] + pub(crate) fn advance_test_clock(&self, delta: Duration) { + self.clock.advance(delta); + } + + pub(crate) fn has_pending_tasks(&self) -> bool { + self.queue + .lock() + .unwrap_or_else(|e| e.into_inner()) + .front() + .is_some() + } + + pub(crate) fn drain_ready(&self) -> Option { + let now = self.clock.now(); + loop { + let due_timers: Vec = { + let mut timers = self.timers.lock().unwrap_or_else(|e| e.into_inner()); + let mut ready = Vec::new(); + let mut i = 0; + while i < timers.len() { + if timers[i].due <= now { + ready.push(timers.swap_remove(i).runnable); + } else { + i += 1; + } + } + ready + }; + let queued: Vec = { + let mut q = self.queue.lock().unwrap_or_else(|e| e.into_inner()); + q.drain(..).collect() + }; + if due_timers.is_empty() && queued.is_empty() { + break; + } + for runnable in due_timers.into_iter().chain(queued) { + runnable.run(); + } + } + let timers = self.timers.lock().unwrap_or_else(|e| e.into_inner()); + timers + .iter() + .map(|t| t.due.saturating_duration_since(now)) + .min() + } +} + +impl PlatformDispatcher for SyncHostDispatcher { + fn is_main_thread(&self) -> bool { + true + } + + fn now(&self) -> ui::scheduler::Instant { + self.clock.advance(Duration::from_millis(16)); + self.clock.now() + } + + fn dispatch(&self, runnable: RunnableVariant, _priority: Priority) { + if let Ok(mut q) = self.queue.lock() { + q.push_back(runnable); + } + } + + fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) { + if let Ok(mut q) = self.queue.lock() { + q.push_back(runnable); + } + } + + fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) { + let due = self.clock.now() + duration; + if let Ok(mut timers) = self.timers.lock() { + timers.push(ScheduledTimer { due, runnable }); + } + } + + fn spawn_realtime(&self, f: Box) { + f(); + } +} + +pub(crate) struct FallbackAtlas; + +impl PlatformAtlas for FallbackAtlas { + fn get_or_insert_with<'a>( + &self, + _key: AtlasKey, + _build: &mut dyn FnMut() -> Result, Cow<'a, [u8]>)>>, + ) -> Result> { + Ok(Some(AtlasTile { + texture_id: AtlasTextureId { + index: 0, + kind: AtlasTextureKind::Monochrome, + }, + tile_id: TileId(0), + padding: 0, + bounds: Bounds::new( + point(DevicePixels(0), DevicePixels(0)), + size(DevicePixels(1), DevicePixels(1)), + ), + })) + } + + fn remove(&self, _key: &AtlasKey) {} +} + +pub(crate) struct FallbackTextSystem; + +impl PlatformTextSystem for FallbackTextSystem { + fn add_fonts(&self, _fonts: Vec>) -> Result<()> { + Ok(()) + } + + fn all_font_names(&self) -> Vec { + vec!["Inter".to_string(), "IBM Plex Mono".to_string()] + } + + fn font_id(&self, _descriptor: &Font) -> Result { + Ok(FontId(0)) + } + + fn font_metrics(&self, _font_id: FontId) -> FontMetrics { + FontMetrics { + units_per_em: 1000, + ascent: 800.0, + descent: -200.0, + line_gap: 0.0, + underline_position: -100.0, + underline_thickness: 50.0, + cap_height: 700.0, + x_height: 500.0, + bounding_box: Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)), + } + } + + fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result> { + Ok(Bounds::new(point(0.0, -200.0), size(600.0, 1000.0))) + } + + fn advance(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result> { + Ok(size(600.0, 0.0)) + } + + fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { + Some(GlyphId(ch as u32)) + } + + fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result> { + Ok(Bounds::new( + point(DevicePixels(0), DevicePixels(0)), + size(DevicePixels(8), DevicePixels(14)), + )) + } + + fn rasterize_glyph( + &self, + _params: &RenderGlyphParams, + raster_bounds: Bounds, + ) -> Result<(Size, Vec)> { + let w = raster_bounds.size.width.0.max(1) as usize; + let h = raster_bounds.size.height.0.max(1) as usize; + Ok((raster_bounds.size, vec![0u8; w * h])) + } + + fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { + let cell = f32::from(font_size) * 0.56; + let mut x = 0.0f32; + let mut shaped_runs = Vec::new(); + let mut offset = 0usize; + for run in runs { + let end = (offset + run.len).min(text.len()); + let slice = &text[offset..end]; + let mut glyphs = Vec::new(); + for (rel_idx, ch) in slice.char_indices() { + let adv = if ch == ' ' { cell * 0.65 } else { cell }; + glyphs.push(ShapedGlyph { + id: GlyphId(ch as u32), + position: point(px(x), px(0.0)), + index: offset + rel_idx, + is_emoji: false, + }); + x += adv; + } + shaped_runs.push(ShapedRun { + font_id: run.font_id, + glyphs, + bidi_level: 0, + }); + offset = end; + } + LineLayout { + font_size, + width: px(x), + ascent: px(f32::from(font_size) * 0.8), + descent: px(f32::from(font_size) * 0.2), + runs: shaped_runs, + len: text.len(), + base_direction: BaseDirection::Ltr, + } + } + + fn recommended_rendering_mode( + &self, + _font_id: FontId, + _font_size: Pixels, + ) -> TextRenderingMode { + TextRenderingMode::Grayscale + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + #[test] + fn sync_host_dispatcher_drains_delayed_timers() { + let dispatcher = Arc::new(SyncHostDispatcher::new()); + let bg = ui::BackgroundExecutor::new(dispatcher.clone()); + let fg = ui::ForegroundExecutor::new(dispatcher.clone()); + let hits = Arc::new(AtomicUsize::new(0)); + let hits_clone = Arc::clone(&hits); + let bg_clone = bg.clone(); + let _task = fg.spawn(async move { + bg_clone.timer(Duration::from_millis(80)).await; + hits_clone.fetch_add(1, Ordering::SeqCst); + }); + + let pending = dispatcher.drain_ready(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + assert!(pending.is_some(), "timer must report remaining delay"); + + dispatcher.clock.advance(Duration::from_millis(100)); + let after = dispatcher.drain_ready(); + assert_eq!(hits.load(Ordering::SeqCst), 1); + assert_eq!(after, None); + } +} diff --git a/packages/frontend/hosts/ios/src/editor_platform.rs b/packages/frontend/hosts/ios/src/editor_platform.rs new file mode 100644 index 0000000000..c31c8dab08 --- /dev/null +++ b/packages/frontend/hosts/ios/src/editor_platform.rs @@ -0,0 +1,821 @@ +//! Platform and window bridge mounting the pure-Rust GPU `PlaygroundView` +//! inside the iOS thin host without modifying `packages/ui/ui/src/**`. +//! +//! On `target_os = "ios"`, `IosEditorPlatform` and `IosEditorWindow` reuse +//! `ui::platform::apple::{AppleDispatcher, AppleTextSystem, metal_renderer::MetalRenderer}` +//! and expose `MetalRenderer::layer_ptr()` (`CAMetalLayer`) directly to UIKit. +//! On non-iOS hosts (`cargo test -p affine-ios-host`), a deterministic in-process +//! platform drives the exact same `PlaygroundView` and `PlatformInputHandler`. + +use std::{ + cell::RefCell, + ffi::{OsString, c_void}, + path::{Path, PathBuf}, + rc::Rc, + sync::Arc, +}; + +use anyhow::Result; +use futures::channel::oneshot; +#[cfg(target_os = "ios")] +use parking_lot::Mutex; +use raw_window_handle::{ + DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, + UiKitDisplayHandle, WindowHandle, +}; +use smallvec::SmallVec; +#[cfg(target_os = "ios")] +use ui::DevicePixels; +#[cfg(target_os = "ios")] +use ui::apple::{ + AppleDispatcher, AppleTextSystem, + metal_renderer::{self, InstanceBufferPool, MetalRenderer}, +}; +use ui::{ + Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ClipboardItem, + CursorStyle, DispatchEventResult, DummyKeyboardMapper, ForegroundExecutor, GpuSpecs, Keymap, + Menu, MenuItem, Modifiers, OperatingSystem, PathPromptOptions, Pixels, Platform, PlatformAtlas, + PlatformDisplay, PlatformInfo, PlatformInput, PlatformInputHandler, PlatformKeyboardLayout, + PlatformKeyboardMapper, PlatformTarget, PlatformTextSystem, PlatformWindow, Point, + PromptButton, PromptLevel, RequestFrameOptions, Scene, Size, Task, TextInputConfiguration, + TextInputStateChange, ThermalState, WindowAppearance, WindowBackgroundAppearance, WindowBounds, + WindowControlArea, WindowInsets, WindowParams, WindowVisibility, point, px, size, +}; + +#[cfg(not(target_os = "ios"))] +use super::editor_fallback as fallback; +use super::editor_runtime::{IosEditorDisplay, IosEditorKeyboardLayout}; + +pub(crate) type TextInputObserver = Box; + +pub(crate) struct IosEditorWindowState { + pub(crate) bounds: Bounds, + pub(crate) scale_factor: f32, + pub(crate) insets: WindowInsets, + pub(crate) input_handler: Option, + pub(crate) request_frame: Option>, + pub(crate) input: Option DispatchEventResult>>, + pub(crate) resize: Option, f32)>>, + pub(crate) visual_viewport_changed: Option>, + pub(crate) appearance_changed: Option>, + pub(crate) active_status_change: Option>, + pub(crate) visibility_change: Option>, + pub(crate) close: Option>, + pub(crate) mouse_position: Point, + pub(crate) modifiers: Modifiers, + pub(crate) ime_position: Option>, + pub(crate) dirty: bool, + pub(crate) text_input_change_seq: u64, + pub(crate) last_text_input_change: Option, + pub(crate) pending_text_input_changes: Vec, + pub(crate) text_input_observer: Option, + pub(crate) frame_wake_observer: Option>, + pub(crate) soft_keyboard_requested: bool, +} + +/// Shared handle to the live GPUI `PlatformWindow` owned by `affine-ios-host`. +#[derive(Clone)] +pub(crate) struct IosEditorWindow { + #[cfg(target_os = "ios")] + renderer: Rc>, + #[cfg(not(target_os = "ios"))] + atlas: Arc, + display: Rc, + pub(crate) state: Rc>, +} + +impl IosEditorWindow { + fn new( + #[cfg(target_os = "ios")] instance_buffer_pool: Arc>, + bounds: Bounds, + scale_factor: f32, + ) -> Result { + let safe_scale = if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + 2.0 + }; + #[cfg(target_os = "ios")] + let renderer = { + let mut r = metal_renderer::new_renderer(instance_buffer_pool, false, true)?; + let dw = (f32::from(bounds.size.width) * safe_scale).round().max(1.0) as i32; + let dh = (f32::from(bounds.size.height) * safe_scale) + .round() + .max(1.0) as i32; + r.update_drawable_size(size(DevicePixels(dw), DevicePixels(dh))); + Rc::new(RefCell::new(r)) + }; + let display: Rc = Rc::new(IosEditorDisplay { bounds }); + Ok(Self { + #[cfg(target_os = "ios")] + renderer, + #[cfg(not(target_os = "ios"))] + atlas: Arc::new(fallback::FallbackAtlas), + display, + state: Rc::new(RefCell::new(IosEditorWindowState { + bounds, + scale_factor: safe_scale, + insets: WindowInsets::default(), + input_handler: None, + request_frame: None, + input: None, + resize: None, + visual_viewport_changed: None, + appearance_changed: None, + active_status_change: None, + visibility_change: None, + close: None, + mouse_position: Point::default(), + modifiers: Modifiers::default(), + ime_position: None, + dirty: true, + text_input_change_seq: 0, + last_text_input_change: None, + pending_text_input_changes: Vec::new(), + text_input_observer: None, + frame_wake_observer: None, + soft_keyboard_requested: false, + })), + }) + } + + /// Returns the raw `CAMetalLayer *` owned by `MetalRenderer` on iOS, or null on non-iOS. + pub(crate) fn metal_layer_ptr(&self) -> *mut c_void { + #[cfg(target_os = "ios")] + { + self.renderer.borrow().layer_ptr().cast() + } + #[cfg(not(target_os = "ios"))] + { + core::ptr::null_mut() + } + } + + fn mark_dirty_and_wake(state: &Rc>) { + let observer = { + let mut st = state.borrow_mut(); + let was_dirty = st.dirty; + st.dirty = true; + (!was_dirty) + .then(|| st.frame_wake_observer.clone()) + .flatten() + }; + if let Some(cb) = observer { + cb(); + } + } + + pub(crate) fn request_frame_now(&self) { + self.state.borrow_mut().dirty = false; + let callback = self.state.borrow_mut().request_frame.take(); + if let Some(mut cb) = callback { + cb(RequestFrameOptions { + require_presentation: true, + ..RequestFrameOptions::default() + }); + self.state.borrow_mut().request_frame = Some(cb); + } + } + + /// Delivers queued `TextInputStateChange` notifications after any active GPUI `App` + /// borrow has ended so UIKit `UITextInputDelegate` callbacks can safely query FFI. + pub(crate) fn flush_text_input_changes(&self) { + let (pending, observer) = { + let mut st = self.state.borrow_mut(); + if st.pending_text_input_changes.is_empty() { + return; + } + let pending = std::mem::take(&mut st.pending_text_input_changes); + let observer = st.text_input_observer.take(); + (pending, observer) + }; + if let Some(obs) = observer { + for change in pending { + obs(change); + } + let mut st = self.state.borrow_mut(); + if st.text_input_observer.is_none() { + st.text_input_observer = Some(obs); + } + } + } + + pub(crate) fn dispatch_input(&self, event: PlatformInput) -> DispatchEventResult { + let callback = { + let mut st = self.state.borrow_mut(); + match &event { + PlatformInput::MouseDown(e) => st.mouse_position = e.position, + PlatformInput::MouseUp(e) => st.mouse_position = e.position, + PlatformInput::MouseMove(e) => st.mouse_position = e.position, + PlatformInput::Touch(e) => st.mouse_position = e.position, + _ => {} + } + st.dirty = true; + st.input.take() + }; + let Some(mut cb) = callback else { + return DispatchEventResult::default(); + }; + let res = cb(event); + self.state.borrow_mut().input = Some(cb); + res + } + + pub(crate) fn set_viewport(&self, width_pt: f32, height_pt: f32, scale_factor: f32) { + let w = width_pt.max(1.0); + let h = height_pt.max(1.0); + let scale = if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + self.state.borrow().scale_factor + }; + #[cfg(target_os = "ios")] + { + let dw = (w * scale).round().max(1.0) as i32; + let dh = (h * scale).round().max(1.0) as i32; + self.renderer + .borrow_mut() + .update_drawable_size(size(DevicePixels(dw), DevicePixels(dh))); + } + let cb = { + let mut st = self.state.borrow_mut(); + st.bounds.size = size(px(w), px(h)); + st.scale_factor = scale; + st.dirty = true; + st.resize.take() + }; + if let Some(mut resize_cb) = cb { + resize_cb(size(px(w), px(h)), scale); + self.state.borrow_mut().resize = Some(resize_cb); + } + } + + pub(crate) fn set_insets(&self, insets: WindowInsets) { + let cb = { + let mut st = self.state.borrow_mut(); + if st.insets == insets { + return; + } + st.insets = insets; + st.dirty = true; + st.visual_viewport_changed.take() + }; + if let Some(mut vvp_cb) = cb { + vvp_cb(); + self.state.borrow_mut().visual_viewport_changed = Some(vvp_cb); + } + } + + pub(crate) fn with_input_handler( + &self, + f: impl FnOnce(&mut PlatformInputHandler) -> R, + ) -> Option { + let mut handler = self.state.borrow_mut().input_handler.take()?; + let out = f(&mut handler); + self.state.borrow_mut().input_handler = Some(handler); + Some(out) + } + + pub(crate) fn set_text_input_observer(&self, observer: Option) { + self.state.borrow_mut().text_input_observer = observer; + } + + pub(crate) fn text_input_change_seq(&self) -> u64 { + self.state.borrow().text_input_change_seq + } +} + +impl HasWindowHandle for IosEditorWindow { + fn window_handle(&self) -> std::result::Result, HandleError> { + Err(HandleError::Unavailable) + } +} + +impl HasDisplayHandle for IosEditorWindow { + fn display_handle(&self) -> std::result::Result, HandleError> { + #[allow(unsafe_code)] + // SAFETY: UiKitDisplayHandle has no lifetime-bound pointer. + Ok( + unsafe { + DisplayHandle::borrow_raw(RawDisplayHandle::UiKit(UiKitDisplayHandle::new())) + }, + ) + } +} + +impl PlatformWindow for IosEditorWindow { + fn bounds(&self) -> Bounds { + self.state.borrow().bounds + } + + fn is_maximized(&self) -> bool { + true + } + + fn window_bounds(&self) -> WindowBounds { + WindowBounds::Windowed(self.state.borrow().bounds) + } + + fn content_size(&self) -> Size { + self.state.borrow().bounds.size + } + + fn resize(&mut self, size: Size) { + let scale = self.state.borrow().scale_factor; + self.set_viewport(f32::from(size.width), f32::from(size.height), scale); + } + + fn scale_factor(&self) -> f32 { + self.state.borrow().scale_factor + } + + fn appearance(&self) -> WindowAppearance { + WindowAppearance::Light + } + + fn display(&self) -> Option> { + Some(Rc::clone(&self.display)) + } + + fn mouse_position(&self) -> Point { + self.state.borrow().mouse_position + } + + fn modifiers(&self) -> Modifiers { + self.state.borrow().modifiers + } + + fn capslock(&self) -> Capslock { + Capslock::default() + } + + fn set_input_handler(&mut self, input_handler: PlatformInputHandler) { + self.state.borrow_mut().input_handler = Some(input_handler); + } + + fn take_input_handler(&mut self) -> Option { + self.state.borrow_mut().input_handler.take() + } + + fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {} + + fn prompt( + &self, + _level: PromptLevel, + _msg: &str, + _detail: Option<&str>, + _answers: &[PromptButton], + ) -> Option> { + None + } + + fn activate(&self) {} + + fn is_active(&self) -> bool { + true + } + + fn visibility(&self) -> WindowVisibility { + WindowVisibility::Visible + } + + fn is_hovered(&self) -> bool { + false + } + + fn background_appearance(&self) -> WindowBackgroundAppearance { + WindowBackgroundAppearance::Opaque + } + + fn set_title(&mut self, _title: &str) {} + + fn set_background_appearance(&self, _background_appearance: WindowBackgroundAppearance) {} + + fn minimize(&self) {} + + fn zoom(&self) {} + + fn toggle_fullscreen(&self) {} + + fn is_fullscreen(&self) -> bool { + true + } + + fn frame_waker(&self) -> Option> { + let weak = Rc::downgrade(&self.state); + Some(Rc::new(move || { + if let Some(state) = weak.upgrade() { + Self::mark_dirty_and_wake(&state); + } + })) + } + + fn schedule_frame(&self) { + Self::mark_dirty_and_wake(&self.state); + } + + fn on_request_frame(&self, callback: Box) { + self.state.borrow_mut().request_frame = Some(callback); + } + + fn on_input(&self, callback: Box DispatchEventResult>) { + self.state.borrow_mut().input = Some(callback); + } + + fn on_active_status_change(&self, callback: Box) { + self.state.borrow_mut().active_status_change = Some(callback); + } + + fn on_visibility_change(&self, callback: Box) { + self.state.borrow_mut().visibility_change = Some(callback); + } + + fn on_hover_status_change(&self, _callback: Box) {} + + fn on_resize(&self, callback: Box, f32)>) { + self.state.borrow_mut().resize = Some(callback); + } + + fn on_moved(&self, _callback: Box) {} + + fn on_display_changed(&self, _callback: Box) {} + + fn on_should_close(&self, _callback: Box bool>) {} + + fn on_close(&self, callback: Box) { + self.state.borrow_mut().close = Some(callback); + } + + fn on_hit_test_window_control(&self, _callback: Box Option>) { + } + + fn on_appearance_changed(&self, callback: Box) { + self.state.borrow_mut().appearance_changed = Some(callback); + } + + fn on_visual_viewport_changed(&self, callback: Box) { + self.state.borrow_mut().visual_viewport_changed = Some(callback); + } + + fn insets(&self) -> WindowInsets { + self.state.borrow().insets.clone() + } + + fn draw(&self, scene: &Scene) { + // Clear dirty at present time so pre-draw `App::flush_effects()` calls cannot leave + // `dirty` stuck true, while post-draw `schedule_frame()` still re-arms `dirty = true`. + self.state.borrow_mut().dirty = false; + #[cfg(target_os = "ios")] + self.renderer.borrow_mut().draw(scene); + #[cfg(not(target_os = "ios"))] + let _ = scene; + } + + fn sprite_atlas(&self) -> Arc { + #[cfg(target_os = "ios")] + return self.renderer.borrow().sprite_atlas().clone(); + #[cfg(not(target_os = "ios"))] + Arc::clone(&self.atlas) + } + + fn is_subpixel_rendering_supported(&self) -> bool { + false + } + + fn gpu_specs(&self) -> Option { + None + } + + fn update_ime_position(&self, bounds: Bounds) { + self.state.borrow_mut().ime_position = Some(bounds); + } + + fn show_soft_keyboard(&self) { + self.state.borrow_mut().soft_keyboard_requested = true; + } + + fn text_input_state_changed(&self, change: TextInputStateChange) { + let mut st = self.state.borrow_mut(); + st.text_input_change_seq = st.text_input_change_seq.saturating_add(1); + st.last_text_input_change = Some(change); + st.pending_text_input_changes.push(change); + } +} + +pub(crate) type OpenUrlObserver = Box; + +pub(crate) struct IosEditorPlatform { + background_executor: BackgroundExecutor, + foreground_executor: ForegroundExecutor, + #[cfg(not(target_os = "ios"))] + fallback_dispatcher: Arc, + text_system: Arc, + #[cfg(target_os = "ios")] + instance_buffer_pool: Arc>, + initial_bounds: Bounds, + initial_scale: f32, + opened_window: RefCell>, + pub(crate) clipboard: super::clipboard::IosClipboardStore, + open_url_observer: RefCell>, +} + +impl IosEditorPlatform { + pub(crate) fn new(width_pt: f32, height_pt: f32, scale_factor: f32) -> Self { + let bounds = Bounds::new( + point(px(0.0), px(0.0)), + size(px(width_pt.max(1.0)), px(height_pt.max(1.0))), + ); + #[cfg(target_os = "ios")] + let (dispatcher, text_system): ( + Arc, + Arc, + ) = ( + Arc::new(AppleDispatcher::new()), + Arc::new(AppleTextSystem::new()), + ); + #[cfg(not(target_os = "ios"))] + let fallback_dispatcher = Arc::new(fallback::SyncHostDispatcher::new()); + #[cfg(not(target_os = "ios"))] + let (dispatcher, text_system): ( + Arc, + Arc, + ) = ( + Arc::clone(&fallback_dispatcher) as Arc, + Arc::new(fallback::FallbackTextSystem), + ); + let background_executor = BackgroundExecutor::new(dispatcher.clone()); + let foreground_executor = ForegroundExecutor::new(dispatcher); + Self { + background_executor, + foreground_executor, + #[cfg(not(target_os = "ios"))] + fallback_dispatcher, + text_system, + #[cfg(target_os = "ios")] + instance_buffer_pool: Arc::new(Mutex::new(InstanceBufferPool::default())), + initial_bounds: bounds, + initial_scale: if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + 2.0 + }, + opened_window: RefCell::new(None), + clipboard: super::clipboard::IosClipboardStore::default(), + open_url_observer: RefCell::new(None), + } + } + + #[cfg(not(target_os = "ios"))] + pub(crate) fn fallback_dispatcher(&self) -> Arc { + Arc::clone(&self.fallback_dispatcher) + } + + pub(crate) fn opened_window(&self) -> Option { + self.opened_window.borrow().clone() + } + + pub(crate) fn set_open_url_observer(&self, observer: Option) { + *self.open_url_observer.borrow_mut() = observer; + } +} + +impl Platform for IosEditorPlatform { + fn platform_info(&self) -> PlatformInfo { + PlatformInfo { + os: OperatingSystem::Ios, + target: PlatformTarget::Native, + } + } + + fn background_executor(&self) -> BackgroundExecutor { + self.background_executor.clone() + } + + fn foreground_executor(&self) -> ForegroundExecutor { + self.foreground_executor.clone() + } + + fn text_system(&self) -> Arc { + self.text_system.clone() + } + + fn run(&self, on_finish_launching: Box) { + on_finish_launching(); + } + + fn quit(&self) {} + fn restart(&self, _binary_path: Option, _arguments: Vec) {} + fn activate(&self, _ignoring_other_apps: bool) {} + fn hide(&self) {} + fn hide_other_apps(&self) {} + fn unhide_other_apps(&self) {} + + fn displays(&self) -> Vec> { + vec![Rc::new(IosEditorDisplay { + bounds: self.initial_bounds, + })] + } + + fn primary_display(&self) -> Option> { + Some(Rc::new(IosEditorDisplay { + bounds: self.initial_bounds, + })) + } + + fn on_displays_changed(&self, _callback: Box) {} + + fn active_window(&self) -> Option { + None + } + + fn open_window( + &self, + _handle: AnyWindowHandle, + options: WindowParams, + ) -> Result> { + let bounds = if f32::from(options.bounds.size.width) > 0.0 + && f32::from(options.bounds.size.height) > 0.0 + { + options.bounds + } else { + self.initial_bounds + }; + let window = IosEditorWindow::new( + #[cfg(target_os = "ios")] + self.instance_buffer_pool.clone(), + bounds, + self.initial_scale, + )?; + *self.opened_window.borrow_mut() = Some(window.clone()); + Ok(Box::new(window)) + } + + fn window_appearance(&self) -> WindowAppearance { + WindowAppearance::Light + } + + fn open_url(&self, url: &str) { + let clean = url.trim(); + if !url.chars().any(char::is_control) + && (clean.starts_with("https://") || clean.starts_with("http://")) + && let Some(observer) = self.open_url_observer.borrow_mut().as_mut() + { + observer(clean); + } + } + fn on_open_urls(&self, _callback: Box)>) {} + + fn register_url_scheme(&self, _url: &str) -> Task> { + Task::ready(Ok(())) + } + + fn prompt_for_paths( + &self, + _options: PathPromptOptions, + ) -> oneshot::Receiver>>> { + let (tx, rx) = oneshot::channel(); + let _ = tx.send(Ok(None)); + rx + } + + fn prompt_for_new_path( + &self, + _directory: &Path, + _suggested_name: Option<&str>, + ) -> oneshot::Receiver>> { + let (tx, rx) = oneshot::channel(); + let _ = tx.send(Ok(None)); + rx + } + + fn can_select_mixed_files_and_dirs(&self) -> bool { + false + } + + fn reveal_path(&self, _path: &Path) {} + fn open_with_system(&self, _path: &Path) {} + fn on_quit(&self, _callback: Box bool>) {} + fn on_reopen(&self, _callback: Box) {} + fn on_system_sleep(&self, _callback: Box) {} + fn on_system_wake(&self, _callback: Box) {} + fn set_menus(&self, _menus: Vec, _keymap: &Keymap) {} + fn set_dock_menu(&self, _menu: Vec, _keymap: &Keymap) {} + + fn update_jump_list( + &self, + _menus: Vec, + _entries: Vec>, + ) -> Task>> { + Task::ready(Vec::new()) + } + + fn on_app_menu_action(&self, _callback: Box) {} + fn on_will_open_app_menu(&self, _callback: Box) {} + fn on_validate_app_menu_command(&self, _callback: Box bool>) {} + + fn app_path(&self) -> Result { + Ok(PathBuf::new()) + } + + fn path_for_auxiliary_executable(&self, _name: &str) -> Result { + Ok(PathBuf::new()) + } + + fn set_cursor_style(&self, _style: CursorStyle) {} + fn hide_cursor_until_mouse_moves(&self) {} + + fn is_cursor_visible(&self) -> bool { + false + } + + fn should_auto_hide_scrollbars(&self) -> bool { + true + } + + fn write_to_clipboard(&self, item: ClipboardItem) { + self.clipboard.write(item); + } + + fn read_from_clipboard(&self) -> Option { + self.clipboard.read() + } + + #[cfg(target_os = "linux")] + fn write_to_primary(&self, _item: ClipboardItem) {} + + #[cfg(target_os = "linux")] + fn read_from_primary(&self) -> Option { + None + } + + #[cfg(target_os = "macos")] + fn read_from_find_pasteboard(&self) -> Option { + None + } + + #[cfg(target_os = "macos")] + fn write_to_find_pasteboard(&self, _item: ClipboardItem) {} + + fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task> { + Task::ready(Ok(())) + } + + fn read_credentials(&self, _url: &str) -> Task)>>> { + Task::ready(Ok(None)) + } + + fn delete_credentials(&self, _url: &str) -> Task> { + Task::ready(Ok(())) + } + + fn keyboard_layout(&self) -> Box { + Box::new(IosEditorKeyboardLayout) + } + + fn keyboard_mapper(&self) -> Rc { + Rc::new(DummyKeyboardMapper) + } + + fn on_keyboard_layout_change(&self, _callback: Box) {} + + fn thermal_state(&self) -> ThermalState { + ThermalState::Nominal + } + + fn on_thermal_state_change(&self, _callback: Box) {} + + fn prevent_idle_sleep(&self, _reason: &str) -> Task> { + Task::ready(Ok(ActivityGuard::noop())) + } +} + +#[cfg(test)] +mod open_url_tests { + use std::cell::RefCell; + use std::rc::Rc; + + use ui::Platform; + + use super::*; + + #[test] + fn ios_open_url_allows_only_http_and_https_and_invokes_observer() { + let platform = IosEditorPlatform::new(390.0, 844.0, 3.0); + let seen: Rc>> = Rc::new(RefCell::new(Vec::new())); + let seen_cb = Rc::clone(&seen); + platform.set_open_url_observer(Some(Box::new(move |url| { + seen_cb.borrow_mut().push(url.to_string()); + }))); + for bad in [ + "javascript:alert(1)", + "file:///etc/passwd", + "intent://evil", + "https://example.com/\nnewline", + ] { + platform.open_url(bad); + } + assert!(seen.borrow().is_empty()); + platform.open_url(" https://affine.pro/docs "); + assert_eq!(seen.borrow().as_slice(), &["https://affine.pro/docs"]); + } +} diff --git a/packages/frontend/hosts/ios/src/editor_runtime.rs b/packages/frontend/hosts/ios/src/editor_runtime.rs new file mode 100644 index 0000000000..a7f97ae577 --- /dev/null +++ b/packages/frontend/hosts/ios/src/editor_runtime.rs @@ -0,0 +1,1092 @@ +//! Live pure-Rust BlockSuite GPU editor runtime hosted inside `AffineIosHost`. +//! +//! Owns the embedded GPUI [`ui::ApplicationHandle`], [`IosEditorWindow`], and +//! [`playground::PlaygroundView`] so `UITextInput`, touch gestures, hardware keys, +//! and Metal frame rendering all talk to one authoritative `PlatformInputHandler` +//! and CRDT document (zero host text copy). + +use std::{ffi::c_void, rc::Rc}; + +use playground::{FormFactor, PlaygroundMode, PlaygroundOptions, PlaygroundView}; +use ui::{ + App, AppContext, Application, ApplicationHandle, Bounds, Edges, Entity, KeyDownEvent, + Keystroke, Modifiers, PlatformInput, Render, TextInputStateChange, TouchEvent, TouchId, + TouchPhase, Window, WindowBounds, WindowInsets, WindowOptions, point, px, size, +}; + +use super::{ + AffineUtf16Range, AffineWindowInsets, IosHostState, + editor_platform::{IosEditorPlatform, IosEditorWindow, OpenUrlObserver, TextInputObserver}, + runtime_root::{EditorView, RuntimeRoot, ShellHost}, + selection::{AffinePoint, AffineRect, AffineWritingDirection}, + text_layout::{AffineSelectionRect, detect_paragraph_writing_direction}, +}; + +pub(crate) struct IosEditorKeyboardLayout; + +impl ui::PlatformKeyboardLayout for IosEditorKeyboardLayout { + fn id(&self) -> &str { + "ios.editor" + } + + fn name(&self) -> &str { + "iOS" + } +} + +#[derive(Debug)] +pub(crate) struct IosEditorDisplay { + pub(crate) bounds: Bounds, +} + +impl ui::PlatformDisplay for IosEditorDisplay { + fn id(&self) -> ui::DisplayId { + ui::DisplayId::new(0) + } + + fn uuid(&self) -> anyhow::Result { + Ok(uuid::Uuid::nil()) + } + + fn bounds(&self) -> Bounds { + self.bounds + } + + fn refresh_interval(&self) -> Option { + Some(std::time::Duration::from_secs(1) / 120) + } +} + +/// Live GPU editor runtime embedded in `AffineIosHost`. +pub(crate) struct IosEditorRuntime { + pub(crate) app: ApplicationHandle, + pub(crate) platform: Rc, + pub(crate) window: IosEditorWindow, + pub(crate) root: RuntimeRoot, + pub(crate) shell: Option, + #[cfg(not(target_os = "ios"))] + pub(crate) dispatcher: std::sync::Arc, + form_factor: FormFactor, + frame_count: u64, + last_frame_timestamp_sec: f64, + pub(crate) endpoint_tokens: Vec<(u64, playground::SelectionEndpointAnchor)>, + pub(crate) next_endpoint_token: u64, +} + +impl IosEditorRuntime { + pub(crate) fn new( + width_pt: f32, + height_pt: f32, + scale_factor: f32, + form_factor: FormFactor, + load_showcase: bool, + ) -> Option { + let mut options = PlaygroundOptions::for_form_factor(form_factor); + options.native_selection_ui = true; + options.native_suppresses_gpu_caret_and_selection = true; + Self::open( + width_pt, + height_pt, + scale_factor, + form_factor, + None, + move |window, cx| { + let entity = cx.new(|cx| PlaygroundView::with_options(options, cx)); + entity.update(cx, |view, cx| { + if !load_showcase { + view.load_empty_page_document(window, cx); + } else if !form_factor.is_touch_form_factor() { + view.focus_first_text_block(window, cx); + } + }); + entity + }, + RuntimeRoot::Editor, + ) + } + + /// Open the embedded window with the root view that `build` creates. + pub(crate) fn open( + width_pt: f32, + height_pt: f32, + scale_factor: f32, + form_factor: FormFactor, + shell: Option, + build: impl FnOnce(&mut Window, &mut App) -> Entity + 'static, + root: fn(ui::WindowHandle) -> RuntimeRoot, + ) -> Option { + let w = if width_pt.is_finite() && width_pt > 1.0 { + width_pt + } else { + 390.0 + }; + let h = if height_pt.is_finite() && height_pt > 1.0 { + height_pt + } else { + 844.0 + }; + let scale = if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + 2.0 + }; + + let platform = Rc::new(IosEditorPlatform::new(w, h, scale)); + let platform_ref = Rc::clone(&platform); + let root_slot: Rc>> = + Rc::new(std::cell::RefCell::new(None)); + let root_slot_init = Rc::clone(&root_slot); + let bounds = Bounds::new(point(px(0.0), px(0.0)), size(px(w), px(h))); + + let app = Application::with_platform(platform).run_embedded(move |cx| { + let _ = affine_mobile::register_mobile_fonts(cx); + let _ = playground::register_bundled_fonts(cx); + if let Ok(handle) = cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + ..WindowOptions::default() + }, + move |window, cx| { + window.set_touch_gestures_enabled(true); + build(window, cx) + }, + ) { + *root_slot_init.borrow_mut() = Some(root(handle)); + } + }); + + let window = platform_ref.opened_window()?; + let root = root_slot.borrow_mut().take()?; + #[cfg(not(target_os = "ios"))] + let dispatcher = platform_ref.fallback_dispatcher(); + let runtime = Self { + app, + platform: platform_ref, + window, + root, + shell, + #[cfg(not(target_os = "ios"))] + dispatcher, + form_factor, + frame_count: 0, + last_frame_timestamp_sec: 0.0, + endpoint_tokens: Vec::with_capacity(256), + next_endpoint_token: 1, + }; + // Render initial frame so layout and `PlatformInputHandler` are live immediately. + runtime.window.request_frame_now(); + runtime.window.state.borrow_mut().soft_keyboard_requested = false; + Some(runtime) + } + + /// The page editor that owns text input right now (see [`RuntimeRoot::editor`]). + pub(crate) fn view(&self) -> EditorView { + EditorView(self.root) + } + + pub(crate) fn metal_layer_ptr(&self) -> *mut c_void { + self.window.metal_layer_ptr() + } + + pub(crate) fn window_handle(&self) -> IosEditorWindow { + self.window.clone() + } + + pub(crate) fn resize(&mut self, width_pt: f32, height_pt: f32, scale_factor: f32) { + self.window.set_viewport(width_pt, height_pt, scale_factor); + self.window.request_frame_now(); + } + + pub(crate) fn set_insets(&mut self, insets: AffineWindowInsets) { + // `KeyboardAvoidanceCoordinator` computes `insets.ime_bottom` relative to + // `hostView` (which is already framed inside `view.safeAreaInsets`), so + // `insets.ime_bottom` is already the non-double-counted keyboard overlap + // above the bottom safe area. + let ime_above_safe = insets.ime_bottom.max(0.0); + let ui_insets = WindowInsets { + safe_area: Edges::default(), + ime: Edges { + top: px(0.0), + right: px(0.0), + bottom: px(ime_above_safe), + left: px(0.0), + }, + ..WindowInsets::default() + }; + let prev = self.window.state.borrow().insets.clone(); + if prev != ui_insets { + let was_wants_keyboard = self.wants_software_keyboard(); + self.window.set_insets(ui_insets); + self.window.request_frame_now(); + // Prevent transient `ime_bottom == 0` samples during `becomeFirstResponder` or + // keyboard frame transitions from flipping `keyboard_toolbar_dismissed = true` + // in `PlaygroundView::render`. Explicit toolbar dismiss already cleared + // `wants_software_keyboard()` before this inset update arrived. + if ime_above_safe == 0.0 && was_wants_keyboard && !self.wants_software_keyboard() { + self.restore_software_keyboard(); + } + } + } + + pub(crate) fn request_frame(&mut self) { + self.window.state.borrow_mut().dirty = true; + } + + pub(crate) fn set_frame_wake_observer(&mut self, observer: Option>) { + self.window.state.borrow_mut().frame_wake_observer = observer; + } + + pub(crate) fn is_dirty(&self) -> bool { + #[cfg(not(target_os = "ios"))] + if self.dispatcher.has_pending_tasks() { + return true; + } + self.window.state.borrow().dirty + } + + pub(crate) fn next_timer_delay_ms(&self) -> i64 { + #[cfg(not(target_os = "ios"))] + { + self.dispatcher + .drain_ready() + .map(|d| d.as_millis().min(i64::MAX as u128) as i64) + .unwrap_or(-1) + } + #[cfg(target_os = "ios")] + { + -1 + } + } + + #[cfg(all(test, not(target_os = "ios")))] + pub(crate) fn drain_tasks(&self) -> Option { + self.dispatcher.drain_ready() + } + + pub(crate) fn is_dark_theme(&self) -> bool { + self.root_theme() == Some(playground::PlaygroundTheme::Dark) + } + + pub(crate) fn set_dark_theme(&mut self, dark: bool) { + if self.set_shell_system_dark(dark) { + self.request_frame(); + return; + } + let target = if dark { + playground::PlaygroundTheme::Dark + } else { + playground::PlaygroundTheme::Light + }; + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, _window, cx| { + if view.theme() != target { + view.set_theme(target, cx); + } + }); + }); + self.request_frame(); + } + + pub(crate) fn clear_color_rgba(&self) -> u32 { + match self.root_theme().map(|theme| theme.palette().background) { + Some(hsla) => { + let rgba: ui::Rgba = hsla.into(); + let r = (rgba.r.clamp(0.0, 1.0) * 255.0).round() as u32; + let g = (rgba.g.clamp(0.0, 1.0) * 255.0).round() as u32; + let b = (rgba.b.clamp(0.0, 1.0) * 255.0).round() as u32; + let a = (rgba.a.clamp(0.0, 1.0) * 255.0).round() as u32; + (r << 24) | (g << 16) | (b << 8) | a + } + None => IosHostState::DEFAULT_CLEAR_COLOR_RGBA, + } + } + + pub(crate) fn render_frame(&mut self, timestamp_sec: f64) -> u32 { + #[cfg(not(target_os = "ios"))] + let _ = self.dispatcher.drain_ready(); + if !self.is_dirty() { + return 0; + } + self.hydrate_shown_page(); + self.window.request_frame_now(); + self.frame_count = self.frame_count.saturating_add(1); + if timestamp_sec.is_finite() { + self.last_frame_timestamp_sec = timestamp_sec; + } + self.clear_color_rgba() + } + + pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) { + self.form_factor = form_factor; + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.set_form_factor(form_factor, window, cx); + }); + }); + self.window.request_frame_now(); + ui::PlatformWindow::text_input_state_changed( + &self.window, + TextInputStateChange::SelectionChanged, + ); + } + + #[cfg(test)] + pub(crate) fn form_factor(&self) -> FormFactor { + self.form_factor + } + + pub(crate) fn edgeless_readonly(&self) -> bool { + self.app + .update(|cx| { + self.view() + .read_with(cx, |view, _| view.edgeless_readonly()) + }) + .unwrap_or(true) + } + + pub(crate) fn wants_software_keyboard(&self) -> bool { + if self.shell_search_focused() { + return true; + } + self.app + .update(|cx| { + self.view() + .read_with(cx, |view, _| view.wants_software_keyboard()) + }) + .unwrap_or(false) + } + + pub(crate) fn take_software_keyboard_request(&self) -> bool { + std::mem::take(&mut self.window.state.borrow_mut().soft_keyboard_requested) + } + + pub(crate) fn wants_code_input(&self) -> bool { + self.app + .update(|cx| { + self.view() + .read_with(cx, |view, _| view.wants_code_input_mode()) + }) + .unwrap_or(false) + } + + pub(crate) fn database_readonly(&self) -> bool { + self.app + .update(|cx| { + self.view() + .read_with(cx, |view, _| view.database_readonly()) + }) + .unwrap_or(true) + } + + pub(crate) fn set_mode(&mut self, mode: PlaygroundMode) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.set_mode(mode, window, cx); + }); + }); + self.window.request_frame_now(); + ui::PlatformWindow::text_input_state_changed( + &self.window, + TextInputStateChange::SelectionChanged, + ); + } + + pub(crate) fn reset_empty_document(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.load_empty_page_document(window, cx); + }); + }); + self.window.request_frame_now(); + } + + pub(crate) fn load_showcase_document(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view().update(cx, |view, window, cx| { + view.load_showcase_document(window, cx); + }); + }); + self.window.request_frame_now(); + } + + pub(crate) fn dispatch_touch(&mut self, touch_id: u64, phase: u8, x: f32, y: f32) { + if phase == 0 { + self.window.state.borrow_mut().soft_keyboard_requested = false; + } + let touch_phase = match phase { + 0 => TouchPhase::Started, + 1 => TouchPhase::Moved, + 2 => TouchPhase::Ended, + _ => TouchPhase::Cancelled, + }; + let event = TouchEvent { + id: TouchId(touch_id), + phase: touch_phase, + position: point(px(x), px(y)), + predicted_position: None, + force: None, + }; + let _ = self.window.dispatch_input(PlatformInput::Touch(event)); + self.hydrate_shown_page(); + self.window.request_frame_now(); + if matches!(touch_phase, TouchPhase::Ended) { + self.request_keyboard_for_search_focus(); + } + } + + pub(crate) fn dispatch_key_down( + &mut self, + key: &str, + key_char: Option<&str>, + shift: bool, + cmd: bool, + ctrl: bool, + alt: bool, + ) { + if key != "escape" && self.shell_blocks_text_input() { + return; + } + let event = KeyDownEvent { + keystroke: Keystroke { + modifiers: Modifiers { + control: ctrl, + alt, + shift, + platform: cmd, + function: false, + }, + key: key.to_string(), + key_char: key_char.map(str::to_string), + }, + is_held: false, + prefer_character_input: false, + }; + let _ = self.window.dispatch_input(PlatformInput::KeyDown(event)); + self.window.request_frame_now(); + } + + pub(crate) fn set_text_input_observer(&self, observer: Option) { + self.window.set_text_input_observer(observer); + } + + pub(crate) fn set_open_url_observer(&self, observer: Option) { + self.platform.set_open_url_observer(observer); + } + + pub(crate) fn text_input_change_seq(&self) -> u64 { + self.window.text_input_change_seq() + } + + fn ensure_input_handler(&mut self) { + if self.window.state.borrow().input_handler.is_none() { + self.window.request_frame_now(); + } + } + + pub(crate) fn utf16_len(&mut self) -> usize { + self.ensure_input_handler(); + self.window + .with_input_handler(|h| { + // Handlers that do not report a length (the shell's Search field) still answer + // `text_for_range`, which clamps the range to their text. + h.text_length_utf16().or_else(|| { + h.text_for_range(0..usize::MAX, &mut None) + .map(|text| text.encode_utf16().count()) + }) + }) + .flatten() + .unwrap_or(0) + } + + pub(crate) fn utf16_text(&mut self) -> Vec { + self.ensure_input_handler(); + let len = self.utf16_len(); + if len == 0 { + return Vec::new(); + } + let mut adjusted = None; + let text = self + .window + .with_input_handler(|h| h.text_for_range(0..len, &mut adjusted)) + .flatten() + .unwrap_or_default(); + text.encode_utf16().collect() + } + + pub(crate) fn selected_range(&mut self) -> AffineUtf16Range { + self.ensure_input_handler(); + self.window + .with_input_handler(|h| h.selected_text_range(true)) + .flatten() + .map(|sel| AffineUtf16Range { + location: sel.range.start.min(u32::MAX as usize) as u32, + length: sel.range.len().min(u32::MAX as usize) as u32, + }) + .unwrap_or(AffineUtf16Range { + location: 0, + length: 0, + }) + } + + pub(crate) fn marked_range(&mut self) -> AffineUtf16Range { + self.ensure_input_handler(); + self.window + .with_input_handler(|h| h.marked_text_range()) + .flatten() + .map(|r| AffineUtf16Range { + location: r.start.min(u32::MAX as usize) as u32, + length: r.len().min(u32::MAX as usize) as u32, + }) + .unwrap_or(AffineUtf16Range { + location: u32::MAX, + length: 0, + }) + } + + pub(crate) fn insert_text(&mut self, utf16: &[u16]) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let text = String::from_utf16_lossy(utf16); + if text == "\n" || text == "\r" { + self.dispatch_key_down("enter", None, false, false, false, false); + return; + } + let _ = self + .window + .with_input_handler(|h| h.replace_text_in_range(None, &text)); + self.window.request_frame_now(); + } + + pub(crate) fn delete_backward(&mut self) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + // Dispatch through editor key handler so block-start Backspace merges with previous block + // and non-collapsed selections delete across blocks cleanly. + self.dispatch_key_down("backspace", None, false, false, false, false); + } + + pub(crate) fn delete_range(&mut self, range: AffineUtf16Range) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + if range.length == 0 { + return; + } + let start = range.location as usize; + let end = start.saturating_add(range.length as usize); + let _ = self + .window + .with_input_handler(|h| h.replace_text_in_range(Some(start..end), "")); + self.window.request_frame_now(); + } + + pub(crate) fn replace_range(&mut self, range: AffineUtf16Range, utf16: &[u16]) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let text = String::from_utf16_lossy(utf16); + let start = range.location as usize; + let end = start.saturating_add(range.length as usize); + let _ = self + .window + .with_input_handler(|h| h.replace_text_in_range(Some(start..end), &text)); + self.window.request_frame_now(); + } + + pub(crate) fn set_selected_range(&mut self, range: AffineUtf16Range) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + self.restore_software_keyboard(); + let start = range.location as usize; + let end = start.saturating_add(range.length as usize); + let _ = self + .window + .with_input_handler(|h| h.set_selected_text_range(start..end)); + self.window.request_frame_now(); + } + + pub(crate) fn set_marked_text(&mut self, utf16: &[u16], selected_in_marked: AffineUtf16Range) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let text = String::from_utf16_lossy(utf16); + let sel_start = selected_in_marked.location as usize; + let sel_end = sel_start.saturating_add(selected_in_marked.length as usize); + let _ = self.window.with_input_handler(|h| { + h.replace_and_mark_text_in_range(None, &text, Some(sel_start..sel_end)) + }); + self.window.request_frame_now(); + } + + pub(crate) fn unmark_text(&mut self) { + if self.shell_blocks_text_input() { + return; + } + self.ensure_input_handler(); + let _ = self.window.with_input_handler(|h| h.unmark_text()); + self.window.request_frame_now(); + } + + pub(crate) fn writing_direction(&mut self) -> AffineWritingDirection { + let units = self.utf16_text(); + let sel = self.selected_range(); + detect_paragraph_writing_direction(&units, sel.location as usize) + } + + pub(crate) fn caret_rect(&mut self, utf16_offset: u32) -> Option { + self.ensure_input_handler(); + let off = utf16_offset as usize; + let bounds = self + .window + .with_input_handler(|h| h.bounds_for_range(off..off)) + .flatten()?; + Some(AffineRect { + x: f32::from(bounds.origin.x), + y: f32::from(bounds.origin.y), + width: f32::from(bounds.size.width).max(2.0), + height: f32::from(bounds.size.height).max(20.0), + }) + } + + pub(crate) fn selection_rects(&mut self, range: AffineUtf16Range) -> Vec { + self.ensure_input_handler(); + let start = range.location as usize; + let end = start.saturating_add(range.length as usize); + let bounds_list = self + .window + .with_input_handler(|h| h.selection_bounds_for_range(start..end)) + .unwrap_or_default(); + let count = bounds_list.len(); + bounds_list + .into_iter() + .enumerate() + .map(|(idx, b)| AffineSelectionRect { + rect: AffineRect { + x: f32::from(b.origin.x), + y: f32::from(b.origin.y), + width: f32::from(b.size.width).max(2.0), + height: f32::from(b.size.height).max(20.0), + }, + contains_start: idx == 0, + contains_end: idx + 1 == count, + }) + .collect() + } + + pub(crate) fn closest_offset(&mut self, pt: AffinePoint) -> Option { + self.ensure_input_handler(); + if let Some(off) = self + .window + .with_input_handler(|h| h.character_index_for_point(point(px(pt.x), px(pt.y)))) + .flatten() + { + return Some(off.min(u32::MAX as usize) as u32); + } + self.doc_hit_position(pt.x, pt.y).map(|p| p.utf16_offset) + } + + pub(crate) fn change_kind_code(change: TextInputStateChange) -> u8 { + match change { + TextInputStateChange::FocusGained => 1, + TextInputStateChange::FocusLost => 2, + TextInputStateChange::SelectionChanged => 3, + TextInputStateChange::ContentChanged => 4, + } + } + + pub(crate) fn set_clipboard_provider( + &self, + provider: Option, + ) { + self.platform.clipboard.set_provider(provider); + } + + pub(crate) fn set_page_readonly(&mut self, readonly: bool) { + let _ = self.app.update(|cx| { + let _ = self + .view() + .update(cx, |view, _, cx| view.set_page_readonly(readonly, cx)); + }); + self.window.request_frame_now(); + ui::PlatformWindow::text_input_state_changed( + &self.window, + TextInputStateChange::SelectionChanged, + ); + } + + pub(crate) fn is_surface_readonly(&self) -> bool { + if self.shell_search_focused() { + return false; + } + self.app + .update(|cx| { + self.view().read_with(cx, |view, _| match view.mode() { + PlaygroundMode::Page => view.page_readonly(), + PlaygroundMode::Edgeless => view.edgeless_readonly(), + }) + }) + .unwrap_or(true) + } + + /// Platform back action: the page editor closes its own overlay first, then the shell + /// closes a sheet or the drawer, or steps back through its route history. + pub(crate) fn handle_back(&mut self) -> bool { + let handled = self.app.update(|cx| { + self.view() + .update(cx, |v, w, cx| v.handle_back(w, cx)) + .unwrap_or(false) + }); + if handled { + self.window.request_frame_now(); + } + handled || self.shell_back() + } + + pub(crate) fn restore_software_keyboard(&mut self) { + let view = self.view(); + let _ = self.app.update(|cx| { + let _ = view.update(cx, |v, _, _| v.restore_software_keyboard_on_focus()); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ios_editor_runtime_authoritative_ime_markdown_and_stage_one_readonly() { + let mut rt = + IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, false).expect("runtime"); + assert!(rt.edgeless_readonly()); + assert!(rt.database_readonly()); + assert_eq!(rt.form_factor(), FormFactor::Phone); + + // H-S1 + H-S2: typing "# " converts paragraph into heading and clears "# " from focused block text. + let seq_before = rt.text_input_change_seq(); + let prefix: Vec = "# Hello".encode_utf16().collect(); + rt.insert_text(&prefix); + assert!(rt.text_input_change_seq() > seq_before); + let text = String::from_utf16_lossy(&rt.utf16_text()); + assert!( + text.contains("Hello"), + "focused block text should contain Hello, got {text:?}" + ); + + // Block split on newline + block-start deleteBackward merge. + let nl: Vec = "\n".encode_utf16().collect(); + rt.insert_text(&nl); + let after_split = String::from_utf16_lossy(&rt.utf16_text()); + assert_eq!(after_split, ""); + rt.delete_backward(); + let after_merge = String::from_utf16_lossy(&rt.utf16_text()); + assert!( + after_merge.contains("Hello"), + "deleteBackward at block start should merge back into previous block, got {after_merge:?}" + ); + + // Tablet stays touch read-only; Desktop unlocks Edgeless authoring. + rt.set_form_factor(FormFactor::Tablet); + assert!(rt.edgeless_readonly()); + assert!(rt.database_readonly()); + rt.set_form_factor(FormFactor::Desktop); + assert!(!rt.edgeless_readonly()); + assert!(!rt.database_readonly()); + + // Explicit page_readonly=true blocks Enter, Backspace, and text insertion, + // and is preserved across set_form_factor transitions. + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |view, _window, cx| { + view.set_page_readonly(true, cx); + }); + }); + rt.set_form_factor(FormFactor::Phone); + let before_ro = String::from_utf16_lossy(&rt.utf16_text()); + let extra: Vec = "MUTATED".encode_utf16().collect(); + rt.insert_text(&extra); + rt.dispatch_key_down("enter", None, false, false, false, false); + rt.delete_backward(); + let after_ro = String::from_utf16_lossy(&rt.utf16_text()); + assert_eq!( + after_ro, before_ro, + "page_readonly=true must suppress text insertion, Enter, and Backspace" + ); + } + + #[cfg(not(target_os = "ios"))] + #[test] + fn ios_editor_runtime_timer_drain_idle_caret_blink_and_toast_dismiss() { + let mut rt = + IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, false).expect("runtime"); + // Clear selection so editor is completely idle (no blinking caret). + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |view, window, cx| { + view.dispatch_overlay( + playground::overlays::OverlayEvent::SetSelection(None), + window, + cx, + ); + }); + }); + let _ = rt.render_frame(1.0); + assert!( + !rt.is_dirty(), + "idle iOS frame must leave is_dirty == false" + ); + // Advance 5 seconds while idle: 0 dirty frames. + rt.dispatcher + .advance_test_clock(std::time::Duration::from_secs(5)); + let _ = rt.drain_tasks(); + assert!( + !rt.is_dirty(), + "5s idle with no focused caret must produce 0 dirty frames" + ); + + // Focus caret: caret blink timer (530ms) must wake and mark dirty when clock advances. + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |view, window, cx| { + view.focus_first_text_block(window, cx); + }); + }); + let _ = rt.render_frame(2.0); + assert!(!rt.is_dirty()); + let next_ms = rt.next_timer_delay_ms(); + assert!( + next_ms > 0 && next_ms <= 600, + "focused caret must schedule blink timer within 600ms, got {next_ms}" + ); + rt.dispatcher + .advance_test_clock(std::time::Duration::from_millis(550)); + let _ = rt.drain_tasks(); + assert!( + rt.is_dirty(), + "advancing clock past caret blink interval must mark frame dirty" + ); + assert_ne!(rt.render_frame(2.55), 0); + assert!(!rt.is_dirty()); + + // Mobile read-only database toast must auto-dismiss after 2500ms and mark dirty. + rt.load_showcase_document(); + let _ = rt.render_frame(3.0); + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |view, window, cx| { + view.dispatch_overlay( + playground::overlays::OverlayEvent::SetSelection(None), + window, + cx, + ); + let _ = + view.click_database_point("showcase-database", 10.0, 10.0, Some(window), cx); + // Explicitly open a record sheet / readonly tap to guarantee toast is shown. + view.open_database_record_sheet("showcase-database", "showcase-db-row-1", cx); + }); + }); + let _ = rt.render_frame(3.1); + // Trigger a read-only database cell click to raise the auto-dismissing toast. + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |view, window, cx| { + view.close_database_record_sheet(cx); + let hits = view.database_hits("showcase-database").to_vec(); + if let Some(hit) = hits.iter().find(|h| { + matches!( + h.kind, + playground::database::DatabaseHitKind::OpenRecord { .. } + | playground::database::DatabaseHitKind::CellReadOnly + ) + }) { + let _ = view.click_database_point( + "showcase-database", + hit.rect.x + 2.0, + hit.rect.y + 2.0, + Some(window), + cx, + ); + } + }); + }); + let _ = rt.render_frame(3.2); + let has_toast_before = rt + .app + .update(|cx| { + rt.view().read_with(cx, |view, _| { + view.overlays().context_toast_message().is_some() + }) + }) + .unwrap_or(false); + assert!(has_toast_before, "readonly database tap must show toast"); + rt.dispatcher + .advance_test_clock(std::time::Duration::from_millis(2500)); + let _ = rt.drain_tasks(); + assert!( + rt.is_dirty(), + "toast auto-dismiss timer must mark frame dirty via frame_waker" + ); + let has_toast_after = rt + .app + .update(|cx| { + rt.view().read_with(cx, |view, _| { + view.overlays().context_toast_message().is_some() + }) + }) + .unwrap_or(true); + assert!(!has_toast_after, "toast must auto-dismiss after 2500ms"); + } + + #[cfg(not(target_os = "ios"))] + #[test] + fn touch_cold_start_showcase_does_not_request_keyboard_on_control_tap_and_supports_tail_undo() { + let mut rt = + IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, true).expect("runtime"); + let _ = rt.render_frame(1.0); + assert!( + !rt.wants_software_keyboard() && !rt.take_software_keyboard_request(), + "cold-start showcase on Phone must not pre-arm software keyboard" + ); + + // Scroll to showcase To-Do item and tap both its inner 24x24 checkbox AND outer 44x44 + // touch halo: toggles checked state, keeps scroll steady, and never requests keyboard. + let _ = rt.app.update(|cx| { + let _ = rt.view().update(cx, |v, _, cx| { + assert!(v.scroll_to_block("showcase-todo-open", cx)); + }); + }); + let _ = rt.render_frame(1.1); + let (inner_x, halo_x, check_y, scroll_before) = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + let layout = v.flow_layout().expect("layout"); + let b = layout.block("showcase-todo-open").expect("todo-open"); + let col_x = ((390.0 - b.rect().w) * 0.5).max(0.0); + let sy = playground::TOPBAR_HEIGHT + b.y - v.scroll_offset() + 12.0; + (col_x + b.x + 12.0, col_x + b.x - 6.0, sy, v.scroll_offset()) + }) + }) + .expect("coords"); + assert!(scroll_before > 50.0); + let checked_0 = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + format!( + "{:?}", + v.page_snapshot() + .and_then(|s| s.block("showcase-todo-open")) + ) + }) + }) + .unwrap_or_default(); + rt.dispatch_touch(2, 0, inner_x, check_y); + rt.dispatch_touch(2, 2, inner_x, check_y); + let _ = rt.render_frame(1.2); + assert!( + !rt.take_software_keyboard_request() && !rt.wants_software_keyboard(), + "checkbox inner tap after cold start must not request software keyboard" + ); + let checked_1 = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + format!( + "{:?}", + v.page_snapshot() + .and_then(|s| s.block("showcase-todo-open")) + ) + }) + }) + .unwrap_or_default(); + assert_ne!(checked_1, checked_0, "inner checkbox tap must toggle todo"); + rt.dispatch_touch(3, 0, halo_x, check_y); + rt.dispatch_touch(3, 2, halo_x, check_y); + let _ = rt.render_frame(1.3); + assert!( + !rt.take_software_keyboard_request() && !rt.wants_software_keyboard(), + "checkbox 44x44 halo tap after cold start must not request software keyboard" + ); + let checked_2 = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + format!( + "{:?}", + v.page_snapshot() + .and_then(|s| s.block("showcase-todo-open")) + ) + }) + }) + .unwrap_or_default(); + assert_eq!( + checked_2, checked_0, + "halo checkbox tap must toggle todo back" + ); + let scroll_after = rt + .app + .update(|cx| rt.view().read_with(cx, |v, _| v.scroll_offset())) + .unwrap_or(0.0); + assert!((scroll_after - scroll_before).abs() < 1.0); + + // Scroll to bottom, tap empty canvas space below last block -> requests keyboard; + // Undo + typing writes into a visible editable block (never Surface EdgelessText). + for step in 0..16_u64 { + let tid = 10 + step; + rt.dispatch_touch(tid, 0, 195.0, 720.0); + for y in [560.0_f32, 400.0, 240.0, 120.0] { + rt.dispatch_touch(tid, 1, 195.0, y); + } + rt.dispatch_touch(tid, 2, 195.0, 120.0); + let _ = rt.render_frame(2.0 + step as f64 * 0.05); + } + let _ = rt.take_software_keyboard_request(); + rt.dispatch_touch(99, 0, 195.0, 828.0); + rt.dispatch_touch(99, 2, 195.0, 828.0); + let _ = rt.render_frame(3.0); + assert!( + rt.take_software_keyboard_request() && rt.wants_software_keyboard(), + "tapping empty tail below page must edge-request software keyboard" + ); + rt.dispatch_key_down("z", Some("z"), false, true, false, false); + let _ = rt.render_frame(3.1); + assert!( + !rt.wants_software_keyboard(), + "undoing empty-tail append from cold-start (no prior caret) must clear keyboard state" + ); + let zy: Vec = "ZY".encode_utf16().collect(); + rt.insert_text(&zy); + assert!(rt.utf16_text().is_empty()); + let et_debug = rt + .app + .update(|cx| { + rt.view().read_with(cx, |v, _| { + assert!(v.document_selection().is_none()); + format!( + "{:?}", + v.page_snapshot() + .and_then(|s| s.block("showcase-edgeless-text-p")) + ) + }) + }) + .unwrap_or_default(); + assert!( + !et_debug.contains("ZY"), + "typing after cold-start tail undo must never mutate hidden EdgelessText, got {et_debug}" + ); + + // Tap tail again and type into the newly appended visible Page paragraph. + rt.dispatch_touch(100, 0, 195.0, 828.0); + rt.dispatch_touch(100, 2, 195.0, 828.0); + let _ = rt.render_frame(3.2); + assert!(rt.take_software_keyboard_request() && rt.wants_software_keyboard()); + rt.insert_text(&zy); + let focused_text = String::from_utf16_lossy(&rt.utf16_text()); + assert_eq!(focused_text, "ZY"); + } +} diff --git a/packages/frontend/hosts/ios/src/ffi.rs b/packages/frontend/hosts/ios/src/ffi.rs new file mode 100644 index 0000000000..479390a48f --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi.rs @@ -0,0 +1,950 @@ +#![allow(unsafe_code)] + +use std::{ + ffi::{CStr, CString, c_char, c_void}, + path::Path, +}; + +use super::{ + AffineWindowInsets, IosHostState, + auth::{ + AuthTokenResponse, StoredAuthTokenPair, auth_error_permanently_invalidates_session, + canonical_endpoint, resolve_installation_id, + }, + legacy_storage::{ + ImportedLegacyState, LegacyLocalStorageSnapshot, LegacyWriteBackPlan, + is_whitelisted_legacy_key, parse_legacy_snapshot, verify_write_back_readback, + }, + workspace_store::{IosWorkspaceHandle, resolve_ios_space_db_path}, +}; + +/// Opaque C-ABI handle matching `typedef struct AffineIosHost AffineIosHost`. +pub struct AffineIosHost { + pub(crate) state: IosHostState, + pub(crate) editor: std::cell::RefCell>, + _metal_layer: *mut c_void, + pub(crate) haptics_callback: Option, + pub(crate) haptics_user_data: *mut c_void, + pub(crate) pdf_provider: Option, + pub(crate) text_provider: Option, + pub(crate) islands: super::native_islands::IosNativeIslandsState, +} + +/// Opaque C-ABI handle matching `typedef struct AffineIosWorkspace AffineIosWorkspace`. +pub struct AffineIosWorkspace { + pub(crate) handle: IosWorkspaceHandle, +} + +/// Owned byte buffer returned across the C ABI. Free with `affine_ios_bytes_free`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct AffineIosByteBuffer { + pub ptr: *mut u8, + pub len: usize, +} + +impl AffineIosByteBuffer { + pub(crate) fn empty() -> Self { + Self { + ptr: core::ptr::null_mut(), + len: 0, + } + } + + pub(crate) fn from_vec(bytes: Vec) -> Self { + if bytes.is_empty() { + return Self::empty(); + } + let boxed = bytes.into_boxed_slice(); + let len = boxed.len(); + let ptr = Box::into_raw(boxed) as *mut u8; + Self { ptr, len } + } +} + +unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> { + if ptr.is_null() { + return None; + } + // SAFETY: Caller guarantees `ptr` is a valid NUL-terminated C string. + unsafe { CStr::from_ptr(ptr) }.to_str().ok() +} + +fn into_c_string(value: String) -> *mut c_char { + CString::new(value) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} + +/// # Safety +/// `ptr` must be null or returned once by an `affine_ios_*` function returning `char *`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_string_free(ptr: *mut c_char) { + if ptr.is_null() { + return; + } + // SAFETY: Ownership transfers back to Rust exactly once. + let _ = unsafe { CString::from_raw(ptr) }; +} + +/// # Safety +/// `buf` must be empty or returned once by an `affine_ios_*` function returning `AffineIosByteBuffer`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_bytes_free(buf: AffineIosByteBuffer) { + if buf.ptr.is_null() || buf.len == 0 { + return; + } + // SAFETY: `buf.ptr` and `buf.len` came from `Box::<[u8]>::into_raw`. + let slice = core::ptr::slice_from_raw_parts_mut(buf.ptr, buf.len); + let _ = unsafe { Box::from_raw(slice) }; +} + +impl AffineIosHost { + pub(crate) fn into_raw( + metal_layer: *mut c_void, + width_pt: f32, + height_pt: f32, + scale_factor: f32, + editor: Option, + ) -> *mut Self { + Box::into_raw(Box::new(Self { + state: IosHostState::new(width_pt, height_pt, scale_factor), + editor: std::cell::RefCell::new(editor), + _metal_layer: metal_layer, + haptics_callback: None, + haptics_user_data: core::ptr::null_mut(), + pdf_provider: None, + text_provider: None, + islands: super::native_islands::IosNativeIslandsState::default(), + })) + } +} + +/// Creates a host whose root view is a bare page editor with the showcase document. +#[unsafe(no_mangle)] +pub extern "C" fn affine_ios_host_create( + metal_layer: *mut c_void, + width_pt: f32, + height_pt: f32, + scale_factor: f32, +) -> *mut AffineIosHost { + let editor = super::editor_runtime::IosEditorRuntime::new( + width_pt, + height_pt, + scale_factor, + playground::FormFactor::Phone, + true, + ); + AffineIosHost::into_raw(metal_layer, width_pt, height_pt, scale_factor, editor) +} + +/// # Safety +/// `host` must be null or a pointer returned once by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_destroy(host: *mut AffineIosHost) { + if host.is_null() { + return; + } + // SAFETY: Caller transfers ownership back to Rust exactly once. + let _ = unsafe { Box::from_raw(host) }; +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_resize( + host: *mut AffineIosHost, + width_pt: f32, + height_pt: f32, + scale_factor: f32, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state.resize(width_pt, height_pt, scale_factor); + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.resize(width_pt, height_pt, scale_factor); + } + super::ffi_editor::flush_text_input_changes(host); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_insets( + host: *mut AffineIosHost, + insets: AffineWindowInsets, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state.set_insets(insets); + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_insets(host.state.insets()); + } +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_render_frame( + host: *mut AffineIosHost, + frame_timestamp_sec: f64, +) -> u32 { + let Some(host) = (unsafe { host.as_mut() }) else { + return 0; + }; + let rendered = if let Some(editor) = host.editor.borrow_mut().as_mut() { + if host.state.is_dirty() { + editor.request_frame(); + } + let color = editor.render_frame(frame_timestamp_sec); + let _ = host.state.render_frame(frame_timestamp_sec); + Some(color) + } else { + None + }; + if let Some(color) = rendered { + super::ffi_editor::flush_text_input_changes(host); + return color; + } + host.state.render_frame(frame_timestamp_sec) +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_is_dirty(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + if let Some(editor) = host.editor.borrow().as_ref() { + return editor.is_dirty() || host.state.is_dirty(); + } + host.state.is_dirty() +} + +/// Drains due timers (on non-iOS fallback hosts) and returns milliseconds until the next pending +/// timer (`-1` when idle with no pending timer). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_next_timer_delay_ms(host: *mut AffineIosHost) -> i64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return -1; + }; + host.editor + .borrow() + .as_ref() + .map_or(-1, |editor| editor.next_timer_delay_ms()) +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_request_frame(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state.request_frame(); + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.request_frame(); + } +} + +/// Callback invoked when Rust marks a previously clean frame dirty (e.g., from a timer or async task) +/// so the iOS host can unpause `CADisplayLink` immediately. +pub type AffineFrameWakeCallback = Option; + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +/// `user_data` must remain valid until unregistered with `callback = NULL` or host destruction. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_frame_wake_callback( + host: *mut AffineIosHost, + callback: AffineFrameWakeCallback, + user_data: *mut core::ffi::c_void, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + let observer = callback.map(|cb| { + let raw = user_data as usize; + std::rc::Rc::new(move || unsafe { + cb(raw as *mut core::ffi::c_void); + }) as std::rc::Rc + }); + editor.set_frame_wake_observer(observer); + } +} + +/// # Safety +/// `endpoint` must be null or a valid NUL-terminated UTF-8 C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_canonical_endpoint( + endpoint: *const c_char, +) -> *mut c_char { + let Some(ep) = (unsafe { c_str_opt(endpoint) }) else { + return core::ptr::null_mut(); + }; + into_c_string(canonical_endpoint(ep)) +} + +/// # Safety +/// `endpoint` must be null or a valid NUL-terminated UTF-8 C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_legacy_storage_endpoint_key( + endpoint: *const c_char, +) -> *mut c_char { + let Some(ep) = (unsafe { c_str_opt(endpoint) }) else { + return core::ptr::null_mut(); + }; + into_c_string(crate::auth::legacy_storage_endpoint_key(ep)) +} + +/// Parse a 0.27.5 Keychain JSON payload (2001-epoch `accessExpiresAt`) and check validity. +/// Returns normalized Keychain JSON (still 2001-epoch) or null if invalid. +/// +/// # Safety +/// `json` must be a valid NUL-terminated UTF-8 string; output pointers may be null or writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_parse_keychain_json( + json: *const c_char, + now_unix_secs: f64, + min_validity_secs: f64, + out_is_valid: *mut bool, + out_access_expires_unix_secs: *mut f64, +) -> *mut c_char { + let Some(raw) = (unsafe { c_str_opt(json) }) else { + return core::ptr::null_mut(); + }; + let Ok(pair) = StoredAuthTokenPair::from_json(raw) else { + return core::ptr::null_mut(); + }; + if let Some(valid_slot) = unsafe { out_is_valid.as_mut() } { + *valid_slot = pair.is_access_token_valid(now_unix_secs, min_validity_secs); + } + if let Some(exp_slot) = unsafe { out_access_expires_unix_secs.as_mut() } { + *exp_slot = pair.access_expires_at_unix_secs(); + } + pair.to_json() + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()) +} + +/// Convert a server `/api/auth/session/{exchange,refresh}` JSON response into 0.27.5-compatible +/// Keychain JSON with 2001-epoch `f64` `accessExpiresAt`. +/// +/// # Safety +/// `response_json` must be null or a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_encode_token_response_json( + response_json: *const c_char, + now_unix_ms: i64, +) -> *mut c_char { + let Some(raw) = (unsafe { c_str_opt(response_json) }) else { + return core::ptr::null_mut(); + }; + let Ok(resp) = serde_json::from_str::(raw) else { + return core::ptr::null_mut(); + }; + let Ok(pair) = StoredAuthTokenPair::from_token_response(&resp, now_unix_ms) else { + return core::ptr::null_mut(); + }; + pair.to_json() + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()) +} + +/// Reuse an existing persisted `app.affine.pro.auth-installation-id` or generate a lowercase +/// UUID v4 on fresh install. +/// +/// # Safety +/// `existing` may be null or a valid NUL-terminated UTF-8 string; `out_created` may be null or writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_resolve_installation_id( + existing: *const c_char, + out_created: *mut bool, +) -> *mut c_char { + let existing_opt = unsafe { c_str_opt(existing) }; + let (id, created) = resolve_installation_id(existing_opt); + if let Some(slot) = unsafe { out_created.as_mut() } { + *slot = created; + } + into_c_string(id) +} + +/// Return true when an auth error response JSON permanently invalidates the stored +/// Keychain session (`AuthPlugin.swift:44-52`). +/// +/// # Safety +/// `error_json` may be null or a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_auth_error_permanently_invalidates_session( + error_json: *const c_char, +) -> bool { + let Some(raw) = (unsafe { c_str_opt(error_json) }) else { + return false; + }; + auth_error_permanently_invalidates_session(raw) +} + +/// Return true when `key` is permitted by `affine-legacy-import`'s single authoritative allowlist. +/// +/// # Safety +/// `key` must be null or a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_legacy_is_permitted_key(key: *const c_char) -> bool { + let Some(raw) = (unsafe { c_str_opt(key) }) else { + return false; + }; + is_whitelisted_legacy_key(raw) +} + +/// Validate a positive sentinel `LegacyLocalStorageSnapshot` JSON (requiring `capacitor://localhost` +/// and `idbAccessCount == 0`) and return the `LegacyUpgradeDisposition` JSON, or null on error. +/// +/// # Safety +/// `snapshot_json` must be null or a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_legacy_storage_parse_snapshot_json( + snapshot_json: *const c_char, +) -> *mut c_char { + let Some(raw) = (unsafe { c_str_opt(snapshot_json) }) else { + return core::ptr::null_mut(); + }; + let Ok(snapshot) = serde_json::from_str::(raw) else { + return core::ptr::null_mut(); + }; + let Ok(disposition) = parse_legacy_snapshot(&snapshot) else { + return core::ptr::null_mut(); + }; + serde_json::to_string(&disposition) + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()) +} + +/// Build a rollback write-back plan JSON from `ImportedLegacyState` JSON and previously seen keys. +/// +/// # Safety +/// Both pointers must be null or valid NUL-terminated UTF-8 strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_legacy_storage_plan_write_back_json( + state_json: *const c_char, + previous_keys_json: *const c_char, +) -> *mut c_char { + let Some(state_raw) = (unsafe { c_str_opt(state_json) }) else { + return core::ptr::null_mut(); + }; + let Ok(state) = serde_json::from_str::(state_raw) else { + return core::ptr::null_mut(); + }; + let prev_keys: Vec = unsafe { c_str_opt(previous_keys_json) } + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default(); + let Ok(plan) = state.to_write_back_plan(&prev_keys) else { + return core::ptr::null_mut(); + }; + serde_json::to_string(&plan) + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()) +} + +/// Verify a write-back readback snapshot JSON against its plan JSON (enforcing zero IDB access). +/// +/// # Safety +/// Both pointers must be null or valid NUL-terminated UTF-8 strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_legacy_storage_verify_write_back_json( + plan_json: *const c_char, + readback_snapshot_json: *const c_char, +) -> bool { + let (Some(plan_raw), Some(readback_raw)) = (unsafe { c_str_opt(plan_json) }, unsafe { + c_str_opt(readback_snapshot_json) + }) else { + return false; + }; + let (Ok(plan), Ok(readback)) = ( + serde_json::from_str::(plan_raw), + serde_json::from_str::(readback_raw), + ) else { + return false; + }; + verify_write_back_readback(&plan, &readback).is_ok() +} + +/// Resolve the 0.27.5-compatible in-place SQLite WAL path for a space. +/// +/// # Safety +/// All pointers must be null or valid NUL-terminated UTF-8 strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_resolve_path( + documents_dir: *const c_char, + space_type: *const c_char, + peer: *const c_char, + space_id: *const c_char, +) -> *mut c_char { + let (Some(docs), Some(st), Some(p), Some(sid)) = ( + unsafe { c_str_opt(documents_dir) }, + unsafe { c_str_opt(space_type) }, + unsafe { c_str_opt(peer) }, + unsafe { c_str_opt(space_id) }, + ) else { + return core::ptr::null_mut(); + }; + resolve_ios_space_db_path(Path::new(docs), st, p, sid) + .map(|path| into_c_string(path.to_string_lossy().into_owned())) + .unwrap_or(core::ptr::null_mut()) +} + +/// Open an in-place SQLite WAL workspace or userspace database. +/// +/// Fail-closed: if `allowlist_json_or_null` is non-null but contains invalid UTF-8 or +/// malformed JSON, returns null immediately without touching disk. +/// +/// # Safety +/// String pointers must be null or valid NUL-terminated UTF-8 strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_open( + documents_dir: *const c_char, + space_type: *const c_char, + peer: *const c_char, + space_id: *const c_char, + allowlist_json_or_null: *const c_char, +) -> *mut AffineIosWorkspace { + let (Some(docs), Some(st), Some(p), Some(sid)) = ( + unsafe { c_str_opt(documents_dir) }, + unsafe { c_str_opt(space_type) }, + unsafe { c_str_opt(peer) }, + unsafe { c_str_opt(space_id) }, + ) else { + return core::ptr::null_mut(); + }; + let allowlist: Option> = if allowlist_json_or_null.is_null() { + None + } else { + let Some(raw) = (unsafe { c_str_opt(allowlist_json_or_null) }) else { + return core::ptr::null_mut(); + }; + let Ok(parsed) = serde_json::from_str::>(raw) else { + return core::ptr::null_mut(); + }; + Some(parsed) + }; + match IosWorkspaceHandle::open(Path::new(docs), st, p, sid, allowlist.as_deref()) { + Ok(handle) => Box::into_raw(Box::new(AffineIosWorkspace { handle })), + Err(_) => core::ptr::null_mut(), + } +} + +/// # Safety +/// `ws` must be null or a pointer returned once by `affine_ios_workspace_open`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_close(ws: *mut AffineIosWorkspace) { + if ws.is_null() { + return; + } + // SAFETY: Ownership transfers back to Rust exactly once. + let boxed = unsafe { Box::from_raw(ws) }; + boxed.handle.close(); +} + +/// # Safety +/// `ws` must be a live workspace handle; `doc_id` must be a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_read_doc( + ws: *const AffineIosWorkspace, + doc_id: *const c_char, +) -> AffineIosByteBuffer { + let (Some(ws), Some(doc_id)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(doc_id) }) else { + return AffineIosByteBuffer::empty(); + }; + ws.handle + .read_doc_binary(doc_id) + .ok() + .flatten() + .map(AffineIosByteBuffer::from_vec) + .unwrap_or_else(AffineIosByteBuffer::empty) +} + +/// # Safety +/// `ws` must be a live workspace handle; `doc_id` must be a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_read_page_snapshot_json( + ws: *const AffineIosWorkspace, + doc_id: *const c_char, + client_id: u64, +) -> *mut c_char { + let (Some(ws), Some(doc_id)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(doc_id) }) else { + return core::ptr::null_mut(); + }; + ws.handle + .read_page_snapshot_json(doc_id, client_id) + .ok() + .flatten() + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()) +} + +/// # Safety +/// `ws` must be a live workspace handle; string pointers must be valid NUL-terminated UTF-8 strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_edit_paragraph_text( + ws: *const AffineIosWorkspace, + doc_id: *const c_char, + block_id: *const c_char, + utf16_index: u64, + delete_len: u64, + insert_text: *const c_char, + client_id: u64, + now_ms: i64, +) -> AffineIosByteBuffer { + let (Some(ws), Some(doc_id), Some(block_id)) = ( + unsafe { ws.as_ref() }, + unsafe { c_str_opt(doc_id) }, + unsafe { c_str_opt(block_id) }, + ) else { + return AffineIosByteBuffer::empty(); + }; + let text = unsafe { c_str_opt(insert_text) }.unwrap_or(""); + ws.handle + .edit_paragraph_text( + doc_id, + block_id, + utf16_index, + delete_len, + text, + client_id, + now_ms, + ) + .map(|res| AffineIosByteBuffer::from_vec(res.update_bytes)) + .unwrap_or_else(|_| AffineIosByteBuffer::empty()) +} + +/// # Safety +/// `ws` must be a live workspace handle; `remote_sv_ptr` must be valid for `remote_sv_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_export_doc_diff( + ws: *const AffineIosWorkspace, + doc_id: *const c_char, + remote_sv_ptr: *const u8, + remote_sv_len: usize, +) -> AffineIosByteBuffer { + let (Some(ws), Some(doc_id)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(doc_id) }) else { + return AffineIosByteBuffer::empty(); + }; + let remote_sv = if remote_sv_ptr.is_null() || remote_sv_len == 0 { + None + } else { + // SAFETY: Caller guarantees `remote_sv_ptr` points to `remote_sv_len` bytes. + Some(unsafe { core::slice::from_raw_parts(remote_sv_ptr, remote_sv_len) }) + }; + ws.handle + .export_pending_diff(doc_id, remote_sv) + .ok() + .flatten() + .map(|diff| AffineIosByteBuffer::from_vec(diff.missing)) + .unwrap_or_else(AffineIosByteBuffer::empty) +} + +/// # Safety +/// `ws` must be a live workspace handle; `update_ptr` must be valid for `update_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_apply_remote_update( + ws: *const AffineIosWorkspace, + doc_id: *const c_char, + update_ptr: *const u8, + update_len: usize, + peer: *const c_char, + remote_clock_ms: i64, + local_now_ms: i64, +) -> AffineIosByteBuffer { + let (Some(ws), Some(doc_id), Some(peer)) = ( + unsafe { ws.as_ref() }, + unsafe { c_str_opt(doc_id) }, + unsafe { c_str_opt(peer) }, + ) else { + return AffineIosByteBuffer::empty(); + }; + let update = if update_ptr.is_null() || update_len == 0 { + &[] + } else { + // SAFETY: Caller guarantees `update_ptr` points to `update_len` bytes. + unsafe { core::slice::from_raw_parts(update_ptr, update_len) } + }; + ws.handle + .apply_remote_update(doc_id, update, peer, remote_clock_ms, local_now_ms) + .map(AffineIosByteBuffer::from_vec) + .unwrap_or_else(|_| AffineIosByteBuffer::empty()) +} + +/// # Safety +/// `ws` must be null or a live pointer returned by `affine_ios_workspace_open`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_checkpoint_passive( + ws: *const AffineIosWorkspace, +) -> bool { + let Some(ws) = (unsafe { ws.as_ref() }) else { + return false; + }; + ws.handle.checkpoint_passive().is_ok() +} + +/// # Safety +/// `ws` must be null or a live pointer returned by `affine_ios_workspace_open`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_checkpoint(ws: *const AffineIosWorkspace) -> bool { + let Some(ws) = (unsafe { ws.as_ref() }) else { + return false; + }; + ws.handle.checkpoint().is_ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use blocksuite_playground_doc::{ + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + }; + + unsafe fn take_c_string(ptr: *mut c_char) -> String { + assert!(!ptr.is_null(), "expected non-null C string"); + let s = unsafe { CStr::from_ptr(ptr) }.to_str().unwrap().to_string(); + unsafe { affine_ios_string_free(ptr) }; + s + } + + #[test] + fn c_abi_auth_legacy_storage_and_workspace_roundtrip() { + let ep = CString::new("https://APP.AFFINE.PRO:443/graphql").unwrap(); + let canonical = unsafe { take_c_string(affine_ios_auth_canonical_endpoint(ep.as_ptr())) }; + assert_eq!(canonical, "https://app.affine.pro"); + + let mut created = false; + let fresh_id = unsafe { + take_c_string(affine_ios_auth_resolve_installation_id( + core::ptr::null(), + &mut created, + )) + }; + assert!(created); + assert_eq!(fresh_id, fresh_id.to_ascii_lowercase()); + + let resp_json = CString::new( + r#"{"tokenType":"Bearer","accessToken":"tok-1","expiresIn":600,"refreshToken":"ref-1","refreshExpiresAt":"2026-12-25T00:00:00Z","session":{"id":"s-1","absoluteExpiresAt":"2027-01-25T00:00:00Z"}}"#, + ) + .unwrap(); + let encoded_kc = unsafe { + take_c_string(affine_ios_auth_encode_token_response_json( + resp_json.as_ptr(), + 1_795_600_000_000, + )) + }; + let encoded_c = CString::new(encoded_kc).unwrap(); + let mut is_valid = false; + let mut exp_unix = 0.0; + let parsed_kc = unsafe { + take_c_string(affine_ios_auth_parse_keychain_json( + encoded_c.as_ptr(), + 1_795_600_100.0, + 120.0, + &mut is_valid, + &mut exp_unix, + )) + }; + assert!(is_valid); + assert_eq!(exp_unix, 1_795_600_600.0); + assert!(parsed_kc.contains("tok-1")); + + let perm_err = CString::new(r#"{"code":"REFRESH_TOKEN_REUSED"}"#).unwrap(); + assert!(unsafe { + affine_ios_auth_error_permanently_invalidates_session(perm_err.as_ptr()) + }); + let temp_err = CString::new(r#"{"code":"INTERNAL_SERVER_ERROR"}"#).unwrap(); + assert!(!unsafe { + affine_ios_auth_error_permanently_invalidates_session(temp_err.as_ptr()) + }); + + // Legacy storage C-ABI: zero-IDB positive sentinel + write-back verification. + let snap = CString::new( + r#"{"origin":"capacitor://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-c\"]"},"idbAccessCount":0}"#, + ) + .unwrap(); + let disp = + unsafe { take_c_string(affine_ios_legacy_storage_parse_snapshot_json(snap.as_ptr())) }; + assert!(disp.contains("existing_user")); + + let bad_idb = CString::new( + r#"{"origin":"capacitor://localhost","length":0,"keys":[],"entries":{},"idbAccessCount":1}"#, + ) + .unwrap(); + assert!( + unsafe { affine_ios_legacy_storage_parse_snapshot_json(bad_idb.as_ptr()) }.is_null() + ); + + // Workspace C-ABI: open allowlisted DB, seed doc, edit paragraph offline, checkpoint, close. + let temp_dir = std::env::temp_dir().join(format!( + "affine-ios-ffi-test-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&temp_dir).unwrap(); + let docs_c = CString::new(temp_dir.to_string_lossy().as_ref()).unwrap(); + let st_c = CString::new("workspace").unwrap(); + let peer_c = CString::new("local").unwrap(); + let space_c = CString::new("ws-c").unwrap(); + let allow_c = CString::new(r#"["ws-c"]"#).unwrap(); + + let bad_allow_c = CString::new("{not-json").unwrap(); + assert!( + unsafe { + affine_ios_workspace_open( + docs_c.as_ptr(), + st_c.as_ptr(), + peer_c.as_ptr(), + space_c.as_ptr(), + core::ptr::null(), + ) + } + .is_null() + ); + assert!( + unsafe { + affine_ios_workspace_open( + docs_c.as_ptr(), + st_c.as_ptr(), + peer_c.as_ptr(), + space_c.as_ptr(), + bad_allow_c.as_ptr(), + ) + } + .is_null() + ); + + let ws = unsafe { + affine_ios_workspace_open( + docs_c.as_ptr(), + st_c.as_ptr(), + peer_c.as_ptr(), + space_c.as_ptr(), + allow_c.as_ptr(), + ) + }; + assert!(!ws.is_null()); + + let mut doc = PageDocSession::new("doc-c", 7).unwrap(); + doc.add_block( + "p1", + BlockSpec::Page { + title: "FFI".into(), + }, + None, + None, + 1_000, + ) + .unwrap(); + doc.add_block( + "n1", + BlockSpec::Note { + xywh: Some("[0,0,600,400]".into()), + }, + Some("p1"), + None, + 1_001, + ) + .unwrap(); + doc.add_block( + "b1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Hi".into(), + }, + Some("n1"), + None, + 1_002, + ) + .unwrap(); + let seed_bytes = doc.encode_update_v1().unwrap(); + let doc_id_c = CString::new("doc-c").unwrap(); + let block_id_c = CString::new("b1").unwrap(); + let remote_peer_c = CString::new("cloud").unwrap(); + let insert_c = CString::new("!").unwrap(); + + let merged = unsafe { + affine_ios_workspace_apply_remote_update( + ws, + doc_id_c.as_ptr(), + seed_bytes.as_ptr(), + seed_bytes.len(), + remote_peer_c.as_ptr(), + 1_900, + 2_000, + ) + }; + assert!(merged.len > 0); + unsafe { affine_ios_bytes_free(merged) }; + + let delta = unsafe { + affine_ios_workspace_edit_paragraph_text( + ws, + doc_id_c.as_ptr(), + block_id_c.as_ptr(), + 2, + 0, + insert_c.as_ptr(), + 8, + 3_000, + ) + }; + assert!(delta.len > 0); + unsafe { affine_ios_bytes_free(delta) }; + + let diff = unsafe { + affine_ios_workspace_export_doc_diff(ws, doc_id_c.as_ptr(), core::ptr::null(), 0) + }; + assert!(diff.len > 0); + unsafe { affine_ios_bytes_free(diff) }; + + let snapshot = unsafe { + take_c_string(affine_ios_workspace_read_page_snapshot_json( + ws, + doc_id_c.as_ptr(), + 9, + )) + }; + assert!(snapshot.contains("Hi!"), "snapshot={snapshot}"); + assert!(unsafe { affine_ios_workspace_checkpoint_passive(ws) }); + assert!(unsafe { affine_ios_workspace_checkpoint(ws) }); + unsafe { affine_ios_workspace_close(ws) }; + let _ = std::fs::remove_dir_all(&temp_dir); + } + + #[test] + fn keyboard_transition_keeps_c_abi_host_dirty_across_intermediate_frames() { + let host = affine_ios_host_create(core::ptr::null_mut(), 390.0, 844.0, 3.0); + assert!(!host.is_null()); + unsafe { + let _ = affine_ios_host_render_frame(host, 1.0); + crate::ffi_s3::affine_ios_host_begin_keyboard_transition(host, 302.0, 10.0, 0.25); + assert!(affine_ios_host_is_dirty(host)); + let f1 = crate::ffi_s3::affine_ios_host_sample_keyboard_frame( + host, 59.0, 0.0, 34.0, 0.0, 10.016, + ); + assert!(f1.ime_bottom > 0.0 && f1.ime_bottom < 302.0); + let _ = affine_ios_host_render_frame(host, 10.016); + assert!( + affine_ios_host_is_dirty(host), + "C-ABI host must remain dirty after Frame 1 while keyboard transition is active" + ); + let f_end = crate::ffi_s3::affine_ios_host_sample_keyboard_frame( + host, 59.0, 0.0, 34.0, 0.0, 10.30, + ); + assert!((f_end.ime_bottom - 302.0).abs() < 1e-3); + let _ = affine_ios_host_render_frame(host, 10.30); + affine_ios_host_destroy(host); + } + } +} diff --git a/packages/frontend/hosts/ios/src/ffi_doc_positions.rs b/packages/frontend/hosts/ios/src/ffi_doc_positions.rs new file mode 100644 index 0000000000..dc7f2c383c --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_doc_positions.rs @@ -0,0 +1,278 @@ +#![allow(unsafe_code)] + +//! C-ABI exports for pure read-only full-document `UITextPosition` queries, +//! document bounds, cross-block stepping, word boundaries, caret rects, and selection rects. + +use std::ffi::CString; + +use super::{ + editor_doc_positions::AffineDocPosition, ffi::AffineIosHost, + ffi_selection::AffineDocumentSelectionRect, selection::AffineRect, +}; + +fn to_affine_rect(r: playground::SelectionRectGeometry) -> AffineRect { + AffineRect { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + } +} + +/// Layout index (`0..`) of the currently focused block. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_focused_block_order(host: *const AffineIosHost) -> i32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow_mut() + .as_mut() + .map_or(0, |e| e.focused_block_order()) +} + +/// Query full-document addressable bounds `(beginningOfDocument, endOfDocument)` across all +/// editable blocks in layout order. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_document_bounds( + host: *const AffineIosHost, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_document_bounds()) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Query ordered `(start, end)` `AffineDocPosition`s for the active selection (collapsed or range). +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_positions( + host: *const AffineIosHost, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.current_selection_doc_positions()) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Pure read-only viewport hit-test returning `AffineDocPosition` (`valid = false` when no text hit). +/// Never mutates `editor.selection` or focused block state. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_hit_position( + host: *const AffineIosHost, + x: f32, + y: f32, +) -> AffineDocPosition { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocPosition::default(); + }; + host.editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_hit_position(x, y)) + .unwrap_or_default() +} + +/// Pure read-only viewport caret rectangle for an interned `endpoint_token`. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rect` may be null or a writable pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_caret_rect_for_token( + host: *const AffineIosHost, + endpoint_token: u64, + out_rect: *mut AffineRect, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some(rect) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_caret_rect_for_token(endpoint_token)) + else { + return false; + }; + if !out_rect.is_null() { + unsafe { *out_rect = rect }; + } + true +} + +/// Pure read-only selection rectangles between two interned endpoint tokens. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rects` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_rects_between_tokens( + host: *const AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let raw = host + .editor + .borrow_mut() + .as_mut() + .map(|ed| ed.doc_selection_rects_between_tokens(start_endpoint_token, end_endpoint_token)) + .unwrap_or_default(); + let mapped: Vec = raw + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Step `delta` UTF-16 code units from `endpoint_token` across addressable document blocks. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_step_position( + host: *const AffineIosHost, + endpoint_token: u64, + delta: isize, +) -> AffineDocPosition { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocPosition::default(); + }; + host.editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_step_position(endpoint_token, delta)) + .unwrap_or_default() +} + +/// Resolve authoritative ICU word boundaries `(out_start, out_end)` around `endpoint_token`. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_word_range( + host: *const AffineIosHost, + endpoint_token: u64, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_word_range(endpoint_token)) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Signed UTF-16 offset distance from `from_token` to `to_token` across document blocks. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_offset_between_tokens( + host: *const AffineIosHost, + from_token: u64, + to_token: u64, +) -> i32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow_mut() + .as_mut() + .map_or(0, |ed| ed.doc_offset_between_tokens(from_token, to_token)) +} + +/// Newly allocated UTF-8 C string of plain text between two interned endpoint tokens +/// (caller frees via `affine_ios_string_free`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_text_between_tokens( + host: *const AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, +) -> *mut core::ffi::c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let s = host + .editor + .borrow_mut() + .as_mut() + .map(|ed| ed.doc_text_between_tokens(start_endpoint_token, end_endpoint_token)) + .unwrap_or_default(); + CString::new(s) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} diff --git a/packages/frontend/hosts/ios/src/ffi_editor.rs b/packages/frontend/hosts/ios/src/ffi_editor.rs new file mode 100644 index 0000000000..4cfb023373 --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_editor.rs @@ -0,0 +1,792 @@ +#![allow(unsafe_code)] + +//! C-ABI entry points for the live GPU `PlaygroundView` mounted inside `AffineIosHost`. + +use std::{ + ffi::{CStr, CString, c_char, c_void}, + path::Path, +}; + +use playground::{FormFactor, PlaygroundMode}; + +use super::{ + AffineUtf16Range, editor_runtime::IosEditorRuntime, ffi::AffineIosHost, + shell_workspace::ShellLaunch, +}; + +/// Callback fired when the editor mutates text or selection (`H-S2`). +pub type AffineTextInputChangedCallback = extern "C" fn(u8, *mut c_void); + +/// Callback fired when the editor opens a validated `http(s)://` external URL. +pub type AffineOpenUrlCallback = extern "C" fn(*const c_char, *mut c_void); + +/// Flushes queued `TextInputStateChange` notifications after `host.editor` borrow has ended +/// so UIKit `UITextInputDelegate` callbacks can safely re-enter FFI queries without panicking. +pub(crate) fn flush_text_input_changes(host: &AffineIosHost) { + let window = host + .editor + .borrow() + .as_ref() + .map(IosEditorRuntime::window_handle); + if let Some(window) = window { + window.flush_text_input_changes(); + } +} + +unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> { + if ptr.is_null() { + return None; + } + // SAFETY: Caller guarantees `ptr` is a valid NUL-terminated C string. + unsafe { CStr::from_ptr(ptr) }.to_str().ok() +} + +/// Returns whether the live `PlaygroundView` is currently rendering in dark theme. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_is_dark_theme(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + host.editor + .borrow() + .as_ref() + .is_some_and(IosEditorRuntime::is_dark_theme) +} + +/// Switches the live `PlaygroundView` between light (`false`) and dark (`true`) themes. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_dark_theme(host: *mut AffineIosHost, dark: bool) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_dark_theme(dark); + } else { + host.state.request_frame(); + } +} + +/// Returns the `CAMetalLayer *` owned by `MetalRenderer` on iOS, or null on non-iOS hosts. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_metal_layer(host: *const AffineIosHost) -> *mut c_void { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::metal_layer_ptr) + .unwrap_or(core::ptr::null_mut()) +} + +/// Returns the authoritative UTF-16 length of the currently focused editor block (`H-S1`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_utf16_len(host: *const AffineIosHost) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + return editor.utf16_len(); + } + host.state.utf16_text().len() +} + +/// Copies the authoritative UTF-16 code units of the currently focused editor block into +/// `out_ptr` (up to `capacity` units) and returns the total UTF-16 length (`H-S1`). +/// +/// # Safety +/// `host` must be null or a live pointer; `out_ptr` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_copy_utf16( + host: *const AffineIosHost, + out_ptr: *mut u16, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let units = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.utf16_text() + } else { + host.state.utf16_text().to_vec() + }; + if !out_ptr.is_null() && capacity > 0 && !units.is_empty() { + let count = units.len().min(capacity); + // SAFETY: Caller guarantees `out_ptr` points to `capacity` writable `u16` elements. + unsafe { + core::ptr::copy_nonoverlapping(units.as_ptr(), out_ptr, count); + } + } + units.len() +} + +/// Dispatches a UIKit touch event (`0=Started, 1=Moved, 2=Ended, 3=Cancelled`) into the GPU editor. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_touch_event( + host: *mut AffineIosHost, + touch_id: u64, + phase: u8, + x: f32, + y: f32, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.dispatch_touch(touch_id, phase, x, y); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Dispatches a hardware keyboard or editor key event (`enter`, `backspace`, `left`, `right`, +/// `up`, `down`, `escape`, `tab`, etc.) into the GPU editor. +/// +/// # Safety +/// `host` must be null or a live pointer; `key` and `key_char` must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_key_down( + host: *mut AffineIosHost, + key: *const c_char, + key_char: *const c_char, + shift: bool, + cmd: bool, + ctrl: bool, + alt: bool, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let Some(key_str) = (unsafe { c_str_opt(key) }) else { + return; + }; + let char_str = unsafe { c_str_opt(key_char) }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.dispatch_key_down(key_str, char_str, shift, cmd, ctrl, alt); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Updates the host form factor (`0=Phone, 1=Tablet, 2=Desktop`) and applies Stage-1 defaults. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_form_factor( + host: *mut AffineIosHost, + form_factor: u8, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let ff = match form_factor { + 1 => FormFactor::Tablet, + 2 => FormFactor::Desktop, + _ => FormFactor::Phone, + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_form_factor(ff); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Returns `true` when Edgeless authoring is gated read-only (`T1` Stage 1 on touch hosts). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_edgeless_readonly(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return true; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::edgeless_readonly) + .unwrap_or(true) +} + +/// Returns `true` when Database mutations are gated read-only (`T1` Stage 1 on touch hosts). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_database_readonly(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return true; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::database_readonly) + .unwrap_or(true) +} + +/// Switches the mounted editor between Page (`0`) and Edgeless (`1`) modes. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_mode(host: *mut AffineIosHost, mode: u8) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let next = if mode == 1 { + PlaygroundMode::Edgeless + } else { + PlaygroundMode::Page + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_mode(next); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Registers an observer invoked when the editor changes text or selection (`H-S2`). +/// +/// # Safety +/// `host` must be null or a live pointer; `user_data` must outlive the registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_text_input_callback( + host: *mut AffineIosHost, + cb: Option, + user_data: *mut c_void, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let ud_addr = user_data as usize; + if let Some(editor) = host.editor.borrow().as_ref() { + let observer = cb.map(|func| { + Box::new(move |change| { + func( + IosEditorRuntime::change_kind_code(change), + ud_addr as *mut c_void, + ); + }) as super::editor_platform::TextInputObserver + }); + editor.set_text_input_observer(observer); + } +} + +/// Registers a host callback invoked when the editor opens a validated `http(s)://` URL. +/// +/// # Safety +/// `host` must be null or a live pointer; `user_data` must outlive the registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_open_url_callback( + host: *mut AffineIosHost, + cb: Option, + user_data: *mut c_void, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let ud_addr = user_data as usize; + if let Some(editor) = host.editor.borrow().as_ref() { + let observer = cb.map(|func| { + Box::new(move |url: &str| { + if let Ok(c_url) = std::ffi::CString::new(url) { + func(c_url.as_ptr(), ud_addr as *mut c_void); + } + }) as super::editor_platform::OpenUrlObserver + }); + editor.set_open_url_observer(observer); + } +} + +/// Monotonic counter incremented on every editor `TextInputStateChange` notification (`H-S2`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_input_change_seq(host: *const AffineIosHost) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::text_input_change_seq) + .unwrap_or(0) +} + +/// Whether the mounted editor currently wants the system software keyboard shown. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_wants_software_keyboard( + host: *const AffineIosHost, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::wants_software_keyboard) + .unwrap_or(false) +} + +/// Atomically consumes any edge-triggered software-keyboard request emitted during the +/// latest touch/gesture (`Window::request_virtual_keyboard`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_take_software_keyboard_request( + host: *mut AffineIosHost, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::take_software_keyboard_request) + .unwrap_or(false) +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_wants_code_input(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + host.editor + .borrow() + .as_ref() + .map(IosEditorRuntime::wants_code_input) + .unwrap_or(false) +} + +/// Replaces the mounted document with an empty single-paragraph page and focuses it. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_reset_empty_doc(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.reset_empty_document(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Reloads the built-in BlockSuite showcase document into the mounted GPU editor. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_load_showcase_doc(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.load_showcase_document(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// # Safety +/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_insert_text( + host: *mut AffineIosHost, + utf16_ptr: *const u16, + utf16_len: usize, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let slice = if utf16_len == 0 || utf16_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s. + unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) } + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.insert_text(slice); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.selection_overlay_mut().clear(); + host.state.request_frame(); + return; + } + host.state.insert_text(slice); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_delete_backward(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.delete_backward(); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.selection_overlay_mut().clear(); + host.state.request_frame(); + return; + } + host.state.delete_backward(); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_delete_range( + host: *mut AffineIosHost, + range: AffineUtf16Range, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.delete_range(range); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.selection_overlay_mut().clear(); + host.state.request_frame(); + return; + } + host.state.delete_range(range); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_selected_range( + host: *mut AffineIosHost, + range: AffineUtf16Range, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_selected_range(range); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + if range.length == 0 + && host.state.selection_overlay().active_drag_handle() + == super::selection::AffineSelectionHandleKind::None + { + host.state.selection_overlay_mut().clear(); + } + host.state.request_frame(); + return; + } + host.state.set_selected_range(range); +} + +/// # Safety +/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_replace_range( + host: *mut AffineIosHost, + range: AffineUtf16Range, + utf16_ptr: *const u16, + utf16_len: usize, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let slice = if utf16_len == 0 || utf16_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s. + unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) } + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.replace_range(range, slice); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.selection_overlay_mut().clear(); + host.state.request_frame(); + return; + } + host.state.replace_range(range, slice); +} + +/// # Safety +/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_marked_text( + host: *mut AffineIosHost, + utf16_ptr: *const u16, + utf16_len: usize, + selected_range: AffineUtf16Range, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let slice = if utf16_len == 0 || utf16_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s. + unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) } + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_marked_text(slice, selected_range); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.request_frame(); + return; + } + host.state.set_marked_text(slice, selected_range); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_unmark_text(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.unmark_text(); + true + } else { + false + }; + if handled { + flush_text_input_changes(host); + host.state.request_frame(); + return; + } + host.state.unmark_text(); +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selected_range( + host: *const AffineIosHost, +) -> AffineUtf16Range { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineUtf16Range::default(); + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + return editor.selected_range(); + } + host.state.selected_range() +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_marked_range( + host: *const AffineIosHost, +) -> AffineUtf16Range { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineUtf16Range { + location: u32::MAX, + length: 0, + }; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + return editor.marked_range(); + } + host.state.marked_range() +} + +/// Creates a host whose root view is the mobile product shell (4-TabBar `Home`, `Explorer`, +/// `Journals`, `Search`, `Settings`, and the `Page` route with its embedded editor). +/// +/// The shell shows the showcase workspaces until `affine_ios_host_shell_mount_workspace` +/// mounts a local workspace. `language_tag` is a BCP 47 tag (null means English), +/// `now_ms` is Unix epoch milliseconds, and `utc_offset_minutes` sets the local date. +/// +/// # Safety +/// `language_tag` must be null or a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_create_shell( + metal_layer: *mut c_void, + width_pt: f32, + height_pt: f32, + scale_factor: f32, + language_tag: *const c_char, + now_ms: i64, + utc_offset_minutes: i32, + dark: bool, +) -> *mut AffineIosHost { + let tag = unsafe { c_str_opt(language_tag) }.unwrap_or("en"); + let launch = ShellLaunch::new(tag, now_ms, utc_offset_minutes, dark); + let editor = IosEditorRuntime::new_shell( + width_pt, + height_pt, + scale_factor, + FormFactor::Phone, + &launch, + ); + AffineIosHost::into_raw(metal_layer, width_pt, height_pt, scale_factor, editor) +} + +/// Returns the shell route: `0` bare editor root, `1` Home, `2` Explorer, `3` Journals, +/// `4` Search, `5` Page, `6` Settings. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create_shell`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_shell_route(host: *const AffineIosHost) -> u8 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow() + .as_ref() + .map_or(0, IosEditorRuntime::shell_route) +} + +/// Runs the platform back action through `MobileBackCoordinator`: closes the open sheet or +/// drawer, or steps back through the route history. Returns `false` at the root route. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create_shell`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_handle_back(host: *mut AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let handled = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(IosEditorRuntime::handle_back); + if handled { + flush_text_input_changes(host); + host.state.request_frame(); + } + handled +} + +/// Returns the shell's latest accessibility tree as JSON (`rootId`, `nodes` with `bounds` in +/// points), or null before the first frame. Free with `affine_ios_string_free`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create_shell`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_shell_accessibility_json( + host: *const AffineIosHost, +) -> *mut c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + host.editor + .borrow() + .as_ref() + .and_then(IosEditorRuntime::shell_accessibility_json) + .and_then(|json| CString::new(json).ok()) + .map_or(core::ptr::null_mut(), CString::into_raw) +} + +/// Replaces the showcase with the allowlisted local workspace +/// `/workspaces///.db` (created when absent). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create_shell`; the +/// strings must be null or valid NUL-terminated UTF-8. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_shell_mount_workspace( + host: *mut AffineIosHost, + base_dir: *const c_char, + space_type: *const c_char, + peer: *const c_char, + space_id: *const c_char, + name: *const c_char, + now_ms: i64, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let (Some(base_dir), Some(space_type), Some(peer), Some(space_id)) = (unsafe { + ( + c_str_opt(base_dir), + c_str_opt(space_type), + c_str_opt(peer), + c_str_opt(space_id), + ) + }) else { + return false; + }; + let name = unsafe { c_str_opt(name) }.unwrap_or(space_id); + let mounted = host.editor.borrow_mut().as_mut().is_some_and(|editor| { + editor.mount_shell_workspace( + Path::new(base_dir), + space_type, + peer, + space_id, + name, + now_ms, + ) + }); + host.state.request_frame(); + mounted +} + +/// Commits the shell's local changes to the mounted workspace now; the host also commits them +/// every second. Returns the number of written rows (`0` without pending changes), or `-1` when +/// no workspace is mounted or the commit fails. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create_shell`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_shell_flush_workspace(host: *mut AffineIosHost) -> i64 { + let Some(host) = (unsafe { host.as_mut() }) else { + return -1; + }; + host.editor + .borrow_mut() + .as_mut() + .map_or(-1, IosEditorRuntime::flush_shell_workspace) +} diff --git a/packages/frontend/hosts/ios/src/ffi_islands.rs b/packages/frontend/hosts/ios/src/ffi_islands.rs new file mode 100644 index 0000000000..cec53f197e --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_islands.rs @@ -0,0 +1,322 @@ +#![allow(unsafe_code)] + +//! C-ABI narrow-bridge exports for iOS native islands +//! (Atomic SQLite `ShareExtension`, `AffinePaywall`, `Onboarding + NativeSignIn`). + +use std::ffi::{CStr, CString, c_char}; + +use super::{ + ffi::{AffineIosByteBuffer, AffineIosHost, AffineIosWorkspace}, + native_islands::PaywallProduct, + share_ingest::ShareIngestRequest, +}; + +unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> { + if ptr.is_null() { + return None; + } + unsafe { CStr::from_ptr(ptr) }.to_str().ok() +} + +fn into_c_string(value: String) -> *mut c_char { + CString::new(value) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} + +/// Atomically ingest one ShareExtension item (`blobs` + `updates` + `clocks` + +/// `share_ingest_receipts`) inside a single SQLite `BEGIN IMMEDIATE ... COMMIT` transaction. +/// +/// Returns a JSON-encoded `ShareIngestOutcome` (caller frees via `affine_ios_string_free`), +/// or NULL on validation/database failure. +/// +/// # Safety +/// `ws` must be a live workspace handle; `request_json` must be a valid NUL-terminated UTF-8 string; +/// `blob_bytes_ptr` must be valid for `blob_bytes_len` reads when `blob_bytes_len > 0`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_ingest_share_item( + ws: *const AffineIosWorkspace, + request_json: *const c_char, + blob_bytes_ptr: *const u8, + blob_bytes_len: usize, +) -> *mut c_char { + let (Some(ws), Some(raw_json)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(request_json) }) + else { + return core::ptr::null_mut(); + }; + let Ok(req) = serde_json::from_str::(raw_json) else { + return core::ptr::null_mut(); + }; + let blob_bytes: &[u8] = if blob_bytes_ptr.is_null() || blob_bytes_len == 0 { + &[] + } else { + // SAFETY: Caller guarantees `blob_bytes_ptr` points to `blob_bytes_len` readable bytes. + unsafe { core::slice::from_raw_parts(blob_bytes_ptr, blob_bytes_len) } + }; + match ws.handle.ingest_share_item(&req, blob_bytes) { + Ok(outcome) => serde_json::to_string(&outcome) + .map(into_c_string) + .unwrap_or(core::ptr::null_mut()), + Err(_) => core::ptr::null_mut(), + } +} + +/// Read a non-deleted blob from the workspace SQLite `blobs` table. +/// +/// # Safety +/// `ws` must be a live workspace handle; `blob_key` must be a valid NUL-terminated UTF-8 string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_workspace_read_blob( + ws: *const AffineIosWorkspace, + blob_key: *const c_char, +) -> AffineIosByteBuffer { + let (Some(ws), Some(key)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(blob_key) }) else { + return AffineIosByteBuffer::empty(); + }; + ws.handle + .read_blob(key) + .ok() + .flatten() + .map(AffineIosByteBuffer::from_vec) + .unwrap_or_else(AffineIosByteBuffer::empty) +} + +/// Register StoreKit 2 products JSON array (`[{product_id, display_name, display_price}]`). +/// +/// # Safety +/// `host` must be null or a live pointer; `products_json` must be null or a valid C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_set_products_json( + host: *mut AffineIosHost, + products_json: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(raw) = (unsafe { c_str_opt(products_json) }) else { + return false; + }; + let Ok(products) = serde_json::from_str::>(raw) else { + return false; + }; + host.islands.paywall.begin_load_products(); + host.islands.paywall.set_products(products).is_ok() +} + +/// Transition StoreKit 2 paywall into `Purchasing` for an allowlisted `product_id`. +/// +/// # Safety +/// `host` must be null or a live pointer; `product_id` must be null or a valid C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_begin_purchase( + host: *mut AffineIosHost, + product_id: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(pid) = (unsafe { c_str_opt(product_id) }) else { + return false; + }; + host.islands.paywall.begin_purchase(pid).is_ok() +} + +/// Complete a verified StoreKit 2 purchase with its `product_id`, `transaction_id`, and compact JWS string. +/// +/// # Safety +/// `host` and string pointers must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_complete_jws( + host: *mut AffineIosHost, + product_id: *const c_char, + transaction_id: *const c_char, + jws_representation: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let (Some(pid), Some(tx_id), Some(jws)) = ( + unsafe { c_str_opt(product_id) }, + unsafe { c_str_opt(transaction_id) }, + unsafe { c_str_opt(jws_representation) }, + ) else { + return false; + }; + host.islands + .paywall + .complete_verified_transaction(pid, tx_id, jws) + .is_ok() +} + +/// Update non-verified StoreKit 2 purchase outcome (`0 = pending`, `1 = cancelled`, `2 = failed`). +/// +/// # Safety +/// `host` must be null or a live pointer; `reason` must be null or a valid C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_finish_non_verified( + host: *mut AffineIosHost, + outcome_kind: u8, + reason: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + match outcome_kind { + 0 => host.islands.paywall.mark_pending(), + 1 => host.islands.paywall.mark_cancelled(), + _ => { + let msg = unsafe { c_str_opt(reason) }.unwrap_or("StoreKit purchase failed"); + host.islands.paywall.mark_failed(msg); + } + } + true +} + +/// Clear all active StoreKit 2 entitlements (on expiration, refund, or revocation). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_clear_entitlements( + host: *mut AffineIosHost, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.islands.paywall.clear_entitlement(); + true +} + +/// Serialize current `PaywallStateMachine` as JSON (caller frees via `affine_ios_string_free`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_paywall_state_json( + host: *const AffineIosHost, +) -> *mut c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let json = serde_json::to_string(&host.islands.paywall).unwrap_or_else(|_| "{}".to_string()); + into_c_string(json) +} + +/// Begin OAuth sign-in during onboarding with an expected CSRF `state` token. +/// +/// # Safety +/// `host` must be null or a live pointer; `csrf_state` must be null or a valid C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_begin_oauth( + host: *mut AffineIosHost, + csrf_state: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(state) = (unsafe { c_str_opt(csrf_state) }) else { + return false; + }; + host.islands.onboarding.advance_to_sign_in(); + host.islands.onboarding.begin_oauth(state).is_ok() +} + +/// Complete Sign in with Apple (`ASAuthorizationAppleIDCredential`) with user ID + identity token JWS. +/// +/// # Safety +/// `host` and string pointers must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_complete_apple( + host: *mut AffineIosHost, + user_identifier: *const c_char, + identity_token_jws: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let (Some(uid), Some(jws)) = (unsafe { c_str_opt(user_identifier) }, unsafe { + c_str_opt(identity_token_jws) + }) else { + return false; + }; + host.islands + .onboarding + .receive_apple_credential(uid, jws) + .is_ok() +} + +/// Record OAuth callback (`affine://auth/callback?code=...&state=...`) with CSRF check (`PendingExchange`). +/// +/// # Safety +/// `host` and string pointers must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_complete_oauth( + host: *mut AffineIosHost, + code: *const c_char, + state: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let (Some(code), Some(state)) = (unsafe { c_str_opt(code) }, unsafe { c_str_opt(state) }) + else { + return false; + }; + host.islands + .onboarding + .receive_oauth_callback(code, state) + .is_ok() +} + +/// Confirm server session exchange with the verified user `subject` (`PendingExchange -> Completed`). +/// +/// # Safety +/// `host` and `subject` must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_confirm_session( + host: *mut AffineIosHost, + subject: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(subject) = (unsafe { c_str_opt(subject) }) else { + return false; + }; + host.islands + .onboarding + .confirm_session_exchange(subject) + .is_ok() +} + +/// Mark a pending server session exchange as failed so the user returns to `SignInChoice`. +/// +/// # Safety +/// `host` and `reason` must be null or valid C strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_fail_session( + host: *mut AffineIosHost, + reason: *const c_char, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let msg = unsafe { c_str_opt(reason) }.unwrap_or("session exchange failed"); + host.islands.onboarding.fail_session_exchange(msg); + true +} + +/// Serialize current `OnboardingSignInState` as JSON (caller frees via `affine_ios_string_free`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_island_onboarding_state_json( + host: *const AffineIosHost, +) -> *mut c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let json = serde_json::to_string(&host.islands.onboarding).unwrap_or_else(|_| "{}".to_string()); + into_c_string(json) +} diff --git a/packages/frontend/hosts/ios/src/ffi_s3.rs b/packages/frontend/hosts/ios/src/ffi_s3.rs new file mode 100644 index 0000000000..19a2ccd8df --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_s3.rs @@ -0,0 +1,893 @@ +#![allow(unsafe_code)] + +use std::ffi::c_void; + +use super::{ + AffineUtf16Range, AffineWindowInsets, + ffi::{AffineIosByteBuffer, AffineIosHost}, + haptics::AffineHapticPattern, + keyboard_insets::{AffineKeyboardAvoidanceMetrics, compute_keyboard_avoidance}, + pdf::{ + AffinePdfErrorCode, AffinePdfPageSize, AffinePdfRenderPlan, plan_pdf_page_render, + validate_pdf_bytes, + }, + selection::{ + AffinePoint, AffineRect, AffineSelectionHandleKind, AffineSelectionOverlayState, + AffineWritingDirection, + }, +}; + +/// C-ABI callback invoked by Rust when a haptic pattern is triggered. +pub type AffineHapticsCallback = extern "C" fn(u8, *mut c_void); + +/// C-ABI callback opening an in-memory PDF into an explicit native document handle (`0` on error). +pub type AffinePdfOpenDocFn = extern "C" fn(*const u8, usize, *mut c_void) -> u64; + +/// C-ABI callback closing an explicit native PDF document handle. +pub type AffinePdfCloseDocFn = extern "C" fn(u64, *mut c_void); + +/// C-ABI callback querying total page count of an open native PDF document handle. +pub type AffinePdfDocPageCountFn = extern "C" fn(u64, *mut c_void) -> u32; + +/// C-ABI callback querying displayed point size of one page on an open PDF handle. +pub type AffinePdfDocPageSizeFn = + extern "C" fn(u64, u32, *mut AffinePdfPageSize, *mut c_void) -> bool; + +/// C-ABI callback rasterizing one page on an open PDF handle into a caller RGBA8 buffer. +pub type AffinePdfDocRenderRgba8Fn = + extern "C" fn(u64, u32, u32, u32, *mut u8, usize, *mut c_void) -> bool; + +/// Native PDFKit provider table registered by Swift `PdfRendererBridge`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffinePdfProvider { + pub open_doc: Option, + pub close_doc: Option, + pub doc_page_count: Option, + pub doc_page_size: Option, + pub doc_render_rgba8: Option, + pub user_data: *mut c_void, +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_insets(host: *const AffineIosHost) -> AffineWindowInsets { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineWindowInsets::default(); + }; + host.state.insets() +} + +/// Query keyboard height strictly above `safe_bottom` (`max(0, ime_bottom - safe_bottom)`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_ime_above_safe_bottom(host: *const AffineIosHost) -> f32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0.0; + }; + host.state.ime_above_safe_bottom() +} + +/// Compute keyboard avoidance metrics from window bounds and keyboard frame. +#[unsafe(no_mangle)] +pub extern "C" fn affine_ios_keyboard_compute_avoidance( + window_bounds: AffineRect, + keyboard_frame_in_window: AffineRect, + safe_bottom: f32, + is_hidden: bool, +) -> AffineKeyboardAvoidanceMetrics { + compute_keyboard_avoidance( + window_bounds, + keyboard_frame_in_window, + safe_bottom, + is_hidden, + ) +} + +/// Begin a per-frame eased keyboard avoidance transition on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_begin_keyboard_transition( + host: *mut AffineIosHost, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state + .begin_keyboard_transition(target_ime_bottom_pt, start_timestamp_sec, duration_sec); +} + +/// Sample the active keyboard transition at `frame_timestamp_sec` and sync `AffineWindowInsets`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_sample_keyboard_frame( + host: *mut AffineIosHost, + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + frame_timestamp_sec: f64, +) -> AffineWindowInsets { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineWindowInsets::default(); + }; + let insets = host.state.sample_keyboard_frame( + safe_top, + safe_right, + safe_bottom, + safe_left, + frame_timestamp_sec, + ); + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_insets(insets); + } + insets +} + +/// Update selection caret geometry, UTF-16 range, and writing direction on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_set( + host: *mut AffineIosHost, + start_caret: AffineRect, + end_caret: AffineRect, + range: AffineUtf16Range, + writing_direction: u8, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + host.state.selection_overlay_mut().set_selection( + start_caret, + end_caret, + range, + AffineWritingDirection::from_u8(writing_direction), + ); + host.state.selection_overlay_state() +} + +/// Clear active selection overlay state on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_clear(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state.selection_overlay_mut().clear(); +} + +/// Query the current computed selection overlay state (teardrop handles, loupe, menu anchor). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_state( + host: *const AffineIosHost, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineSelectionOverlayState::default(); + }; + host.state.selection_overlay_state() +} + +/// Hit-test teardrop selection handles at `point` (`0 = none, 1 = start, 2 = end`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_hit_test( + host: *const AffineIosHost, + point: AffinePoint, + hit_radius_pt: f32, +) -> u8 { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineSelectionHandleKind::None as u8; + }; + let (vw, vh) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + host.state + .selection_overlay() + .hit_test_handle(point, hit_radius_pt, vw, vh, insets) as u8 +} + +/// Begin dragging a teardrop selection handle and activate the magnifier loupe. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_begin_drag( + host: *mut AffineIosHost, + handle_kind: u8, + touch_point: AffinePoint, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.state + .selection_overlay_mut() + .begin_drag(AffineSelectionHandleKind::from_u8(handle_kind), touch_point) +} + +/// Compute the caret-aligned probe point (`touch + grab_offset`) for an active drag. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_drag_probe( + host: *const AffineIosHost, + touch_point: AffinePoint, +) -> AffinePoint { + let Some(host) = (unsafe { host.as_ref() }) else { + return touch_point; + }; + host.state + .selection_overlay() + .drag_probe_point_for(touch_point) +} + +/// Query the fixed UTF-16 anchor offset of an active handle drag (`u32::MAX` when idle). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_drag_anchor(host: *const AffineIosHost) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return u32::MAX; + }; + host.state + .selection_overlay() + .drag_anchor_utf16() + .unwrap_or(u32::MAX) +} + +/// Update an in-progress drag from authoritative UTF-16 target offset and shaped start/end carets. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_apply_drag_endpoints( + host: *mut AffineIosHost, + touch_point: AffinePoint, + target_offset: u32, + start_caret: AffineRect, + end_caret: AffineRect, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + let _ = host + .state + .selection_overlay_mut() + .apply_text_drag_endpoints(touch_point, target_offset, start_caret, end_caret); + host.state.selection_overlay_state() +} + +/// Finish an active handle drag, hiding the loupe and exposing `menu_anchor_rect`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_end_drag( + host: *mut AffineIosHost, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + let _ = host.state.selection_overlay_mut().end_drag(); + host.state.selection_overlay_state() +} + +/// Validate raw PDF bytes (`0 = ok`, otherwise `AffinePdfErrorCode`). +/// +/// # Safety +/// `pdf_ptr` must be valid for `pdf_len` reads when `pdf_len > 0`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_pdf_validate_bytes(pdf_ptr: *const u8, pdf_len: usize) -> u32 { + let slice = if pdf_len == 0 || pdf_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `pdf_ptr` points to `pdf_len` initialized bytes. + unsafe { core::slice::from_raw_parts(pdf_ptr, pdf_len) } + }; + match validate_pdf_bytes(slice) { + Ok(()) => AffinePdfErrorCode::Ok as u32, + Err(code) => code as u32, + } +} + +/// Validate page index and target pixel dimensions and compute the RGBA8 byte budget. +#[unsafe(no_mangle)] +pub extern "C" fn affine_ios_pdf_plan_render( + page_index: u32, + page_count: u32, + target_width_px: u32, + target_height_px: u32, +) -> AffinePdfRenderPlan { + plan_pdf_page_render(page_index, page_count, target_width_px, target_height_px) +} + +/// Register the Swift `PDFKit` provider callback table on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; callbacks and `user_data` must outlive registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_pdf_provider( + host: *mut AffineIosHost, + provider: AffinePdfProvider, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if provider.open_doc.is_none() + && provider.close_doc.is_none() + && provider.doc_page_count.is_none() + && provider.doc_page_size.is_none() + && provider.doc_render_rgba8.is_none() + { + host.pdf_provider = None; + } else { + host.pdf_provider = Some(provider); + } +} + +fn write_pdf_err(out_error: *mut u32, code: AffinePdfErrorCode) { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = code as u32; + } +} + +/// Open an in-memory PDF into an explicit native document handle (`0` on error). +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_open( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + out_error: *mut u32, +) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + }; + let slice = if pdf_len == 0 || pdf_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `pdf_ptr` points to `pdf_len` bytes. + unsafe { core::slice::from_raw_parts(pdf_ptr, pdf_len) } + }; + if let Err(code) = validate_pdf_bytes(slice) { + write_pdf_err(out_error, code); + return 0; + } + let Some(provider) = host.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let Some(open_fn) = provider.open_doc else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let doc_id = open_fn(slice.as_ptr(), slice.len(), provider.user_data); + if doc_id == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidOrEncryptedPdf); + } else { + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + } + doc_id +} + +/// Close an explicit native PDF document handle, releasing its `PDFDocument` immediately. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_close(host: *const AffineIosHost, doc_id: u64) { + if doc_id == 0 { + return; + } + let Some(host) = (unsafe { host.as_ref() }) else { + return; + }; + if let Some(provider) = host.pdf_provider + && let Some(close_fn) = provider.close_doc + { + close_fn(doc_id, provider.user_data); + } +} + +/// Query page count on an open PDF handle (`O(1)` lookup, zero hashing). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_page_count( + host: *const AffineIosHost, + doc_id: u64, + out_error: *mut u32, +) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + }; + if doc_id == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + } + let Some(provider) = host.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let Some(count_fn) = provider.doc_page_count else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let count = count_fn(doc_id, provider.user_data); + if count == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + } else { + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + } + count +} + +/// Query displayed page point size on an open PDF handle. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_size` must be writable when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_page_size( + host: *const AffineIosHost, + doc_id: u64, + page_index: u32, + out_size: *mut AffinePdfPageSize, + out_error: *mut u32, +) -> bool { + let Some(host_ref) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return false; + }; + if doc_id == 0 || out_size.is_null() { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return false; + } + let mut count_err = AffinePdfErrorCode::Ok as u32; + let count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, &mut count_err) }; + if count_err != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = count_err; + } + return false; + } + if page_index >= count { + write_pdf_err(out_error, AffinePdfErrorCode::PageOutOfRange); + return false; + } + let Some(provider) = host_ref.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return false; + }; + let Some(size_fn) = provider.doc_page_size else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return false; + }; + let ok = size_fn(doc_id, page_index, out_size, provider.user_data); + write_pdf_err( + out_error, + if ok { + AffinePdfErrorCode::Ok + } else { + AffinePdfErrorCode::RenderFailed + }, + ); + ok +} + +/// Rasterize one page on an open PDF handle to RGBA8 with bounds/OOM checks. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_render_page_rgba8( + host: *const AffineIosHost, + doc_id: u64, + page_index: u32, + target_width_px: u32, + target_height_px: u32, + out_error: *mut u32, +) -> AffineIosByteBuffer { + let Some(host_ref) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return AffineIosByteBuffer::empty(); + }; + let mut count_err = AffinePdfErrorCode::Ok as u32; + let page_count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, &mut count_err) }; + if count_err != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = count_err; + } + return AffineIosByteBuffer::empty(); + } + let plan = plan_pdf_page_render(page_index, page_count, target_width_px, target_height_px); + if plan.error != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = plan.error; + } + return AffineIosByteBuffer::empty(); + } + let Some(provider) = host_ref.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + }; + let Some(render_fn) = provider.doc_render_rgba8 else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + }; + let mut rgba = vec![0u8; plan.byte_len]; + let ok = render_fn( + doc_id, + page_index, + plan.target_width_px, + plan.target_height_px, + rgba.as_mut_ptr(), + rgba.len(), + provider.user_data, + ); + if !ok { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + } + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + AffineIosByteBuffer::from_vec(rgba) +} + +/// Stateless convenience wrapper: opens, queries page count, and immediately closes the PDF handle. +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_page_count( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + out_error: *mut u32, +) -> u32 { + let mut open_err = AffinePdfErrorCode::Ok as u32; + let doc_id = unsafe { affine_ios_host_pdf_open(host, pdf_ptr, pdf_len, &mut open_err) }; + if doc_id == 0 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = open_err; + } + return 0; + } + let count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, out_error) }; + unsafe { affine_ios_host_pdf_close(host, doc_id) }; + count +} + +/// Stateless convenience wrapper: opens, rasterizes one page, and immediately closes the PDF handle. +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_render_page_rgba8( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + page_index: u32, + target_width_px: u32, + target_height_px: u32, + out_error: *mut u32, +) -> AffineIosByteBuffer { + let mut open_err = AffinePdfErrorCode::Ok as u32; + let doc_id = unsafe { affine_ios_host_pdf_open(host, pdf_ptr, pdf_len, &mut open_err) }; + if doc_id == 0 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = open_err; + } + return AffineIosByteBuffer::empty(); + } + let buf = unsafe { + affine_ios_host_pdf_doc_render_page_rgba8( + host, + doc_id, + page_index, + target_width_px, + target_height_px, + out_error, + ) + }; + unsafe { affine_ios_host_pdf_close(host, doc_id) }; + buf +} + +/// Register the Swift `HapticsBridge` callback on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; `user_data` must outlive the registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_haptics_callback( + host: *mut AffineIosHost, + callback: Option, + user_data: *mut c_void, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.haptics_callback = callback; + host.haptics_user_data = user_data; +} + +/// Trigger one haptic pattern (`0..=6`), increment counters, and invoke any registered callback. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_trigger_haptic( + host: *mut AffineIosHost, + pattern: u8, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(parsed) = AffineHapticPattern::from_u8(pattern) else { + return false; + }; + host.state.record_haptic(parsed); + if let Some(cb) = host.haptics_callback { + cb(pattern, host.haptics_user_data); + } + true +} + +/// Query dispatch count for a single haptic pattern (`0..=6`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_haptic_count( + host: *const AffineIosHost, + pattern: u8, +) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let Some(parsed) = AffineHapticPattern::from_u8(pattern) else { + return 0; + }; + host.state.haptics().count_for(parsed) +} + +/// Query total haptic dispatch count across all patterns. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_haptic_total_count(host: *const AffineIosHost) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.state.haptics().total_count() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ffi::{affine_ios_bytes_free, affine_ios_host_create, affine_ios_host_destroy}; + + extern "C" fn test_haptic_cb(pattern: u8, user_data: *mut c_void) { + let log = unsafe { &mut *(user_data as *mut Vec) }; + log.push(pattern); + } + + extern "C" fn test_pdf_open(_ptr: *const u8, _len: usize, _ud: *mut c_void) -> u64 { + 42 + } + + extern "C" fn test_pdf_close(_doc_id: u64, _ud: *mut c_void) {} + + extern "C" fn test_pdf_doc_count(doc_id: u64, _ud: *mut c_void) -> u32 { + if doc_id == 42 { 2 } else { 0 } + } + + extern "C" fn test_pdf_doc_size( + doc_id: u64, + _page_index: u32, + out_size: *mut AffinePdfPageSize, + _ud: *mut c_void, + ) -> bool { + if doc_id != 42 || out_size.is_null() { + return false; + } + unsafe { + *out_size = AffinePdfPageSize { + width_pt: 200.0, + height_pt: 300.0, + }; + } + true + } + + extern "C" fn test_pdf_doc_render( + doc_id: u64, + page_index: u32, + w: u32, + h: u32, + out_ptr: *mut u8, + out_len: usize, + _ud: *mut c_void, + ) -> bool { + let expected = (w as usize) * (h as usize) * 4; + if doc_id != 42 || out_ptr.is_null() || out_len != expected { + return false; + } + let buf = unsafe { core::slice::from_raw_parts_mut(out_ptr, out_len) }; + buf.fill(if page_index == 0 { 0x22 } else { 0x88 }); + true + } + + #[test] + fn c_abi_s3_selection_keyboard_pdf_and_haptics_roundtrip() { + let host = affine_ios_host_create(core::ptr::null_mut(), 390.0, 844.0, 3.0); + assert!(!host.is_null()); + + // Keyboard avoidance + per-frame transition. + let metrics = affine_ios_keyboard_compute_avoidance( + AffineRect { + x: 0.0, + y: 0.0, + width: 390.0, + height: 844.0, + }, + AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + 34.0, + false, + ); + assert_eq!(metrics.ime_bottom_pt, 302.0); + assert_eq!(metrics.ime_above_safe_bottom_pt, 268.0); + assert_eq!(metrics.effective_bottom_pt, 302.0); + + unsafe { + affine_ios_host_begin_keyboard_transition(host, metrics.ime_bottom_pt, 1.0, 0.25); + let mid = affine_ios_host_sample_keyboard_frame(host, 59.0, 0.0, 34.0, 0.0, 1.125); + assert!(mid.ime_bottom > 150.0 && mid.ime_bottom < 302.0); + let end = affine_ios_host_sample_keyboard_frame(host, 59.0, 0.0, 34.0, 0.0, 1.25); + assert_eq!(end.ime_bottom, 302.0); + assert_eq!(affine_ios_host_insets(host), end); + assert_eq!(affine_ios_host_ime_above_safe_bottom(host), 268.0); + } + + // Selection teardrop + loupe drag lifecycle. + let sel = unsafe { + affine_ios_host_selection_set( + host, + AffineRect { + x: 60.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 180.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 8, + }, + 0, + ) + }; + assert!(sel.start_handle.visible && sel.end_handle.visible && sel.show_floating_menu); + let hit = unsafe { + affine_ios_host_selection_hit_test(host, AffinePoint { x: 183.0, y: 186.0 }, 22.0) + }; + assert_eq!(hit, AffineSelectionHandleKind::End as u8); + assert!(unsafe { + affine_ios_host_selection_begin_drag(host, hit, AffinePoint { x: 183.0, y: 186.0 }) + }); + let dragged = unsafe { + affine_ios_host_selection_apply_drag_endpoints( + host, + AffinePoint { x: 220.0, y: 186.0 }, + 12, + AffineRect { + x: 40.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 220.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + ) + }; + assert!(dragged.loupe.visible && !dragged.show_floating_menu); + let ended = unsafe { affine_ios_host_selection_end_drag(host) }; + assert!(!ended.loupe.visible && ended.show_floating_menu); + + // Explicit PDF handle lifecycle + stateless convenience wrapper. + unsafe { + affine_ios_host_set_pdf_provider( + host, + AffinePdfProvider { + open_doc: Some(test_pdf_open), + close_doc: Some(test_pdf_close), + doc_page_count: Some(test_pdf_doc_count), + doc_page_size: Some(test_pdf_doc_size), + doc_render_rgba8: Some(test_pdf_doc_render), + user_data: core::ptr::null_mut(), + }, + ); + let sample_pdf = b"%PDF-1.4\n%%EOF\n"; + let mut err = 99u32; + let doc_id = + affine_ios_host_pdf_open(host, sample_pdf.as_ptr(), sample_pdf.len(), &mut err); + assert_eq!(err, AffinePdfErrorCode::Ok as u32); + assert_eq!(doc_id, 42); + + let mut size = AffinePdfPageSize::default(); + assert!(affine_ios_host_pdf_doc_page_size( + host, doc_id, 0, &mut size, &mut err + )); + assert_eq!(size.width_pt, 200.0); + assert_eq!(size.height_pt, 300.0); + + let buf = affine_ios_host_pdf_doc_render_page_rgba8(host, doc_id, 0, 4, 4, &mut err); + assert_eq!(err, AffinePdfErrorCode::Ok as u32); + assert_eq!(buf.len, 64); + let bytes = core::slice::from_raw_parts(buf.ptr, buf.len); + assert_eq!(bytes[0], 0x22); + affine_ios_bytes_free(buf); + + // Out-of-range page rejected before calling provider. + let bad = affine_ios_host_pdf_doc_render_page_rgba8(host, doc_id, 2, 4, 4, &mut err); + assert_eq!(err, AffinePdfErrorCode::PageOutOfRange as u32); + assert_eq!(bad.len, 0); + affine_ios_host_pdf_close(host, doc_id); + } + + // Haptics callback + counters. + let mut received = Vec::::new(); + unsafe { + affine_ios_host_set_haptics_callback( + host, + Some(test_haptic_cb), + (&mut received as *mut Vec).cast(), + ); + assert!(affine_ios_host_trigger_haptic(host, 0)); + assert!(affine_ios_host_trigger_haptic(host, 4)); + assert!(!affine_ios_host_trigger_haptic(host, 99)); + assert_eq!(affine_ios_host_haptic_count(host, 0), 1); + assert_eq!(affine_ios_host_haptic_count(host, 4), 1); + assert_eq!(affine_ios_host_haptic_total_count(host), 2); + affine_ios_host_destroy(host); + } + assert_eq!(received, vec![0, 4]); + } +} diff --git a/packages/frontend/hosts/ios/src/ffi_selection.rs b/packages/frontend/hosts/ios/src/ffi_selection.rs new file mode 100644 index 0000000000..aed6b4c738 --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_selection.rs @@ -0,0 +1,618 @@ +#![allow(unsafe_code)] + +//! C-ABI exports for document-level selection geometry, cross-block handle drag, +//! live drag preview, authoritative selection actions, keyboard-focus restoration, +//! and multi-MIME `UIPasteboard` bridging. + +use std::ffi::CString; + +use super::{ + clipboard::AffineClipboardProvider, editor_runtime::IosEditorRuntime, ffi::AffineIosHost, + ffi_editor::flush_text_input_changes, selection::AffineRect, +}; + +/// C-ABI document-level selection geometry and capabilities snapshot. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct AffineDocumentSelectionSnapshot { + pub has_selection: bool, + pub is_collapsed: bool, + pub is_reversed: bool, + pub start_is_rtl: bool, + pub end_is_rtl: bool, + pub start_visible: bool, + pub end_visible: bool, + pub menu_anchor_visible: bool, + pub menu_suppressed_for_motion: bool, + pub start_caret: AffineRect, + pub end_caret: AffineRect, + pub menu_anchor_rect: AffineRect, + pub action_mask: u32, + pub menu_request_seq: u64, + pub rect_count: usize, +} + +/// C-ABI per-line/per-block document selection rect with writing direction. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct AffineDocumentSelectionRect { + pub rect: AffineRect, + pub is_rtl: bool, + pub contains_start: bool, + pub contains_end: bool, +} + +fn to_affine_rect(r: playground::SelectionRectGeometry) -> AffineRect { + AffineRect { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + } +} + +/// Register the Swift `UIPasteboard.general` multi-MIME clipboard provider on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; callbacks and `user_data` must outlive registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_clipboard_provider( + host: *mut AffineIosHost, + provider: AffineClipboardProvider, +) { + let Some(host) = (unsafe { host.as_ref() }) else { + return; + }; + let opt = if provider.write_json.is_none() && provider.read_json.is_none() { + None + } else { + Some(provider) + }; + if let Some(editor) = host.editor.borrow().as_ref() { + editor.set_clipboard_provider(opt); + } +} + +/// Toggle Page-mode read-only gating on the mounted editor. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_page_readonly( + host: *mut AffineIosHost, + readonly: bool, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_page_readonly(readonly); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Returns `true` when the active editor surface is read-only (Page readonly or Edgeless readonly). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_is_surface_readonly(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return true; + }; + host.editor + .borrow() + .as_ref() + .map_or(true, IosEditorRuntime::is_surface_readonly) +} + +/// Re-enable software keyboard requests before `becomeFirstResponder` on an editable focus. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_restore_software_keyboard(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.restore_software_keyboard(); + } +} + +/// Query document-level selection geometry, visibility, action mask, and menu request seq. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_document_selection_snapshot( + host: *const AffineIosHost, +) -> AffineDocumentSelectionSnapshot { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocumentSelectionSnapshot::default(); + }; + let Some(geom) = host + .editor + .borrow_mut() + .as_mut() + .map(IosEditorRuntime::document_selection_geometry) + else { + return AffineDocumentSelectionSnapshot::default(); + }; + AffineDocumentSelectionSnapshot { + has_selection: geom.has_selection, + is_collapsed: geom.is_collapsed, + is_reversed: geom.is_reversed, + start_is_rtl: geom.start_caret.is_rtl, + end_is_rtl: geom.end_caret.is_rtl, + start_visible: geom.start_visible, + end_visible: geom.end_visible, + menu_anchor_visible: geom.menu_anchor_visible, + menu_suppressed_for_motion: geom.menu_suppressed_for_motion, + start_caret: to_affine_rect(geom.start_caret), + end_caret: to_affine_rect(geom.end_caret), + menu_anchor_rect: to_affine_rect(geom.menu_anchor_rect), + action_mask: geom.action_mask, + menu_request_seq: geom.menu_request_seq, + rect_count: geom.selection_rects.len(), + } +} + +/// Intern and return `(start_token, end_token)` for the current ordered non-collapsed selection. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_endpoint_tokens( + host: *const AffineIosHost, + out_start: *mut u64, + out_end: *mut u64, +) { + let (mut s, mut e) = (0u64, 0u64); + if let Some(host) = unsafe { host.as_ref() } + && let Some(editor) = host.editor.borrow_mut().as_mut() + { + (s, e) = editor.current_selection_endpoint_tokens(); + } + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } +} + +/// Copy per-line/per-block document selection rects into `out_rects` (up to `capacity`). +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rects` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_document_selection_rects( + host: *const AffineIosHost, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let Some(geom) = host + .editor + .borrow_mut() + .as_mut() + .map(IosEditorRuntime::document_selection_geometry) + else { + return 0; + }; + let mapped: Vec = geom + .selection_rects + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Preview document selection rects from `fixed_endpoint_token` to viewport `(fx, fy)` without mutating selection. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rects` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_preview_rects( + host: *const AffineIosHost, + fixed_endpoint_token: u64, + fx: f32, + fy: f32, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return 0; + }; + let Some(fixed) = editor.lookup_endpoint_token(fixed_endpoint_token) else { + return 0; + }; + let view = editor.view(); + let raw = editor + .app + .update(|cx| { + view.update(cx, |v, w, _| { + v.preview_selection_rects_for_drag(fixed, fx, fy, w) + }) + }) + .unwrap_or_default(); + let mapped: Vec = raw + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Query document-level caret rect at viewport point `(x, y)`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_caret_rect_at_point( + host: *const AffineIosHost, + x: f32, + y: f32, + out_rect: *mut AffineRect, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return false; + }; + let view = editor.view(); + let Some(r) = editor + .app + .update(|cx| view.update(cx, |v, w, _| v.caret_rect_at_viewport_point(x, y, w))) + .ok() + .flatten() + else { + return false; + }; + if !out_rect.is_null() { + unsafe { *out_rect = to_affine_rect(r) }; + } + true +} + +/// Return newly allocated UTF-8 C string of the active single-block or cross-block selected text +/// (caller frees via `affine_ios_string_free`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selected_plain_text( + host: *const AffineIosHost, +) -> *mut core::ffi::c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return core::ptr::null_mut(); + }; + let view = editor.view(); + let s = editor + .app + .update(|cx| view.read_with(cx, |v, _| v.selected_plain_text())) + .unwrap_or_default(); + CString::new(s) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} + +/// Returns `true` when an iOS touch starting at `(x, y)` hits chrome, overlays, Edgeless, or +/// non-text interactive widgets and should bypass `UITextInteraction` tap buffering. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_should_forward_touch_immediately( + host: *const AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return false; + }; + let view = editor.view(); + // Shell screens without a page editor own every touch: tabs, rows, and the Search field. + let without_editor = editor.root.shell().is_some(); + editor + .app + .update(|cx| { + view.update(cx, |v, w, _| { + v.should_forward_ios_touch_immediately(x, y, w) + }) + }) + .unwrap_or(without_editor) +} + +/// Select the word at `(x, y)` and bump `menu_request_seq` (used on read-only stationary long-press). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_select_word_at_point( + host: *mut AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = if let Some(editor) = host.editor.borrow_mut().as_mut() { + let view = editor.view(); + let selected = editor + .app + .update(|cx| view.update(cx, |v, w, cx| v.select_word_at_viewport_point(x, y, w, cx))) + .unwrap_or(false); + if selected { + editor.window.request_frame_now(); + } + selected + } else { + false + }; + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Increment `selection_menu_request_seq` when UIKit finishes a selection gesture. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_bump_selection_menu_request_seq(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + let view = editor.view(); + let _ = editor.app.update(|cx| { + let _ = view.update(cx, |v, w, _| { + if v.document_selection_geometry(w).action_mask != 0 { + v.bump_selection_menu_request_seq(); + } + }); + }); + } + host.state.request_frame(); +} + +/// Begin dragging a document-level selection handle (`1 = Start`, `2 = End`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_begin_drag( + host: *mut AffineIosHost, + handle: u8, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.begin_document_selection_drag(handle)) +} + +/// Update an active document-level selection handle drag to viewport point `(x, y)`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_update_drag( + host: *mut AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.update_document_selection_drag(x, y)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Finish an active document-level selection handle drag. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_end_drag(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.end_document_selection_drag(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Update document-level selection from an interned endpoint token to viewport point `(fx, fy)`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_select_from_endpoint_token( + host: *mut AffineIosHost, + fixed_endpoint_token: u64, + fx: f32, + fy: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.select_from_endpoint_token(fixed_endpoint_token, fx, fy)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Update document-level selection directly between two viewport points `(ax, ay)` and `(fx, fy)`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_select_between_points( + host: *mut AffineIosHost, + ax: f32, + ay: f32, + fx: f32, + fy: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.select_between_viewport_points(ax, ay, fx, fy)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Update document-level selection directly between two interned endpoint tokens. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_select_between_endpoint_tokens( + host: *mut AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host.editor.borrow_mut().as_mut().is_some_and(|e| { + e.select_between_endpoint_tokens(start_endpoint_token, end_endpoint_token) + }); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Execute editor-authoritative `Copy` (writes rich multi-MIME slice to `UIPasteboard`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_action_copy(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_copy(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Cut` (blocked in read-only modes). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_action_cut(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_cut(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Paste` (reads multi-MIME `UIPasteboard`, blocked in read-only modes). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_action_paste(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_paste(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Select All`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_action_select_all(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_select_all(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} diff --git a/packages/frontend/hosts/ios/src/ffi_text.rs b/packages/frontend/hosts/ios/src/ffi_text.rs new file mode 100644 index 0000000000..2b1573d23f --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_text.rs @@ -0,0 +1,439 @@ +#![allow(unsafe_code)] + +use std::ffi::c_void; + +use super::{ + AffineUtf16Range, AffineWindowInsets, + ffi::{AffineIosByteBuffer, AffineIosHost}, + selection::{AffinePoint, AffineRect, AffineWritingDirection}, + text_layout::{ + AffineSelectionRect, caret_rect_for_offset, closest_offset_for_point, render_loupe_rgba8, + selection_rects_for_range, + }, +}; + +/// C-ABI callback computing the shaped visual caret rect via native CoreText `CTLine`. +pub type AffineTextCaretRectFn = + extern "C" fn(*const u16, usize, u32, f32, AffineWindowInsets, *mut c_void) -> AffineRect; + +/// C-ABI callback hit-testing the closest grapheme-aligned UTF-16 offset via native CoreText, +/// disambiguating BiDi direction boundaries using `preferred_offset` (`u32::MAX` = none). +pub type AffineTextClosestOffsetFn = + extern "C" fn(*const u16, usize, AffinePoint, u32, f32, AffineWindowInsets, *mut c_void) -> u32; + +/// C-ABI callback computing BiDi-aware per-line selection rects via native CoreText `CTLine`. +pub type AffineTextSelectionRectsFn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + *mut AffineSelectionRect, + usize, + *mut c_void, +) -> usize; + +/// C-ABI callback computing affinity-aware start/end caret rects for a selection range. +pub type AffineTextSelectionEndpointCaretsFn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + *mut AffineRect, + *mut AffineRect, + *mut c_void, +) -> bool; + +/// C-ABI callback rasterizing the magnifier loupe via whole-line CoreText `CTLineDraw`. +pub type AffineTextRenderLoupeRgba8Fn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + f32, + f32, + u32, + f32, + *mut u8, + usize, + *mut c_void, +) -> bool; + +/// Native CoreText `CTTypesetter`/`CTLine` text geometry and vector loupe provider. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffineTextProvider { + pub caret_rect: Option, + pub closest_offset: Option, + pub selection_rects: Option, + pub selection_endpoint_carets: Option, + pub render_loupe_rgba8: Option, + pub user_data: *mut c_void, +} + +/// Register the native CoreText `CTTypesetter`/`CTLine` provider on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; callbacks and `user_data` must outlive registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_text_provider( + host: *mut AffineIosHost, + provider: AffineTextProvider, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if provider.caret_rect.is_none() + && provider.closest_offset.is_none() + && provider.selection_rects.is_none() + && provider.selection_endpoint_carets.is_none() + && provider.render_loupe_rgba8.is_none() + { + host.text_provider = None; + } else { + host.text_provider = Some(provider); + } +} + +/// Query detected base writing direction of the host text buffer (`0 = LTR, 1 = RTL`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_writing_direction(host: *const AffineIosHost) -> u8 { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineWritingDirection::Ltr as u8; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + return editor.writing_direction() as u8; + } + host.state.text_writing_direction() as u8 +} + +/// Compute visual caret rect for `utf16_offset` via the live GPU editor `PlatformInputHandler` +/// (or CoreText / headless fallback). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_caret_rect( + host: *const AffineIosHost, + utf16_offset: u32, +) -> AffineRect { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineRect::default(); + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() + && let Some(rect) = editor.caret_rect(utf16_offset) + { + return rect; + } + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host + .editor + .borrow_mut() + .as_mut() + .map(|e| e.utf16_text()) + .unwrap_or_else(|| host.state.utf16_text().to_vec()); + if let Some(p) = host.text_provider + && let Some(f) = p.caret_rect + { + return f( + utf16.as_ptr(), + utf16.len(), + utf16_offset, + vw, + insets, + p.user_data, + ); + } + caret_rect_for_offset(&utf16, utf16_offset, vw, insets) +} + +/// Compute BiDi-aware per-line selection rectangles across soft-wrapped visual lines. +/// Returns total rectangle count; writes up to `capacity` items into `out_rects` when non-null. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rects` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_selection_rects( + host: *const AffineIosHost, + range: AffineUtf16Range, + out_rects: *mut AffineSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + let rects = editor.selection_rects(range); + if !rects.is_empty() { + if !out_rects.is_null() && capacity > 0 { + let count = rects.len().min(capacity); + // SAFETY: Caller guarantees `out_rects` points to `capacity` writable elements. + unsafe { + core::ptr::copy_nonoverlapping(rects.as_ptr(), out_rects, count); + } + } + return rects.len(); + } + } + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host + .editor + .borrow_mut() + .as_mut() + .map(|e| e.utf16_text()) + .unwrap_or_else(|| host.state.utf16_text().to_vec()); + if let Some(p) = host.text_provider + && let Some(f) = p.selection_rects + { + return f( + utf16.as_ptr(), + utf16.len(), + range, + vw, + insets, + out_rects, + capacity, + p.user_data, + ); + } + let rects = selection_rects_for_range(&utf16, range, vw, insets); + if !out_rects.is_null() && capacity > 0 { + let count = rects.len().min(capacity); + // SAFETY: Caller guarantees `out_rects` points to `capacity` writable elements. + unsafe { + core::ptr::copy_nonoverlapping(rects.as_ptr(), out_rects, count); + } + } + rects.len() +} + +/// Compute affinity-aware start and end caret rects for `range` so handles align with +/// the visual leading/trailing edges of the first/last selected glyphs across BiDi boundaries. +/// +/// # Safety +/// `host`, `out_start`, and `out_end` must be valid pointers (or null for safe no-op). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_selection_endpoint_carets( + host: *const AffineIosHost, + range: AffineUtf16Range, + out_start: *mut AffineRect, + out_end: *mut AffineRect, +) -> bool { + let (Some(host), Some(start_slot), Some(end_slot)) = ( + unsafe { host.as_ref() }, + unsafe { out_start.as_mut() }, + unsafe { out_end.as_mut() }, + ) else { + return false; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + let start_caret = editor.caret_rect(range.location); + let end_caret = editor.caret_rect(range.location.saturating_add(range.length)); + if let (Some(s), Some(e)) = (start_caret, end_caret) + && (range.length == 0 || (s.x - e.x).abs() >= 1.0 || (s.y - e.y).abs() >= 1.0) + { + *start_slot = s; + *end_slot = e; + return true; + } + // At BiDi run boundaries, logical start and end carets share one visual X; + // derive handle edges from `editor.selection_rects(range)` in editor space. + if range.length > 0 { + let rects = editor.selection_rects(range); + if let (Some(first), Some(last)) = (rects.first(), rects.last()) { + let units = editor.utf16_text(); + let lo = (range.location as usize).min(units.len()); + let hi = (range.location.saturating_add(range.length) as usize).min(units.len()); + let slice_rtl = super::text_layout::detect_writing_direction(&units[lo..hi]) + == super::selection::AffineWritingDirection::Rtl; + let (sx, ex) = if slice_rtl { + (first.rect.x + first.rect.width, last.rect.x) + } else { + (first.rect.x, last.rect.x + last.rect.width) + }; + *start_slot = AffineRect { + x: sx, + y: first.rect.y, + width: 2.0, + height: first.rect.height, + }; + *end_slot = AffineRect { + x: ex, + y: last.rect.y, + width: 2.0, + height: last.rect.height, + }; + return true; + } + } + } + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host + .editor + .borrow_mut() + .as_mut() + .map(|e| e.utf16_text()) + .unwrap_or_else(|| host.state.utf16_text().to_vec()); + if let Some(p) = host.text_provider + && let Some(f) = p.selection_endpoint_carets + && f( + utf16.as_ptr(), + utf16.len(), + range, + vw, + insets, + start_slot, + end_slot, + p.user_data, + ) + { + return true; + } + *start_slot = caret_rect_for_offset(&utf16, range.location, vw, insets); + *end_slot = caret_rect_for_offset( + &utf16, + range.location.saturating_add(range.length), + vw, + insets, + ); + true +} + +/// Hit-test closest grapheme-safe UTF-16 offset for `point` in host coordinates. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_closest_offset( + host: *const AffineIosHost, + point: AffinePoint, +) -> u32 { + unsafe { affine_ios_host_text_closest_offset_preferred(host, point, u32::MAX) } +} + +/// Hit-test closest grapheme-safe UTF-16 offset for `point`, preferring `preferred_offset` +/// (`u32::MAX` = none) when `point` sits on a BiDi direction boundary shared by two offsets. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_closest_offset_preferred( + host: *const AffineIosHost, + point: AffinePoint, + preferred_offset: u32, +) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() + && let Some(off) = editor.closest_offset(point) + { + return off; + } + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host + .editor + .borrow_mut() + .as_mut() + .map(|e| e.utf16_text()) + .unwrap_or_else(|| host.state.utf16_text().to_vec()); + if let Some(p) = host.text_provider + && let Some(f) = p.closest_offset + { + return f( + utf16.as_ptr(), + utf16.len(), + point, + preferred_offset, + vw, + insets, + p.user_data, + ); + } + closest_offset_for_point(&utf16, point, vw, insets) +} + +/// Rasterize the magnifier loupe around `(focus_x, focus_y)` as RGBA8 via whole-line `CTLineDraw` +/// (or software fallback in headless environments). Free with `affine_ios_bytes_free`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_render_loupe_rgba8( + host: *const AffineIosHost, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, +) -> AffineIosByteBuffer { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineIosByteBuffer::empty(); + }; + let dim = diameter_px.clamp(16, 512) as usize; + let zoom = if zoom_scale.is_finite() && zoom_scale > 0.25 { + zoom_scale.min(12.0) + } else { + 1.75 + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let (utf16, selected, editor_origin_caret) = + if let Some(editor) = host.editor.borrow_mut().as_mut() { + ( + editor.utf16_text(), + editor.selected_range(), + editor.caret_rect(0), + ) + } else { + ( + host.state.utf16_text().to_vec(), + host.state.selected_range(), + None, + ) + }; + + if let Some(p) = host.text_provider + && let Some(render_fn) = p.render_loupe_rgba8 + { + let (loupe_focus_x, loupe_focus_y) = if let Some(c0) = editor_origin_caret + && let Some(caret_fn) = p.caret_rect + { + let ct0 = caret_fn(utf16.as_ptr(), utf16.len(), 0, vw, insets, p.user_data); + (focus_x - c0.x + ct0.x, focus_y - c0.y + ct0.y) + } else { + (focus_x, focus_y) + }; + let mut rgba = vec![0u8; dim * dim * 4]; + let ok = render_fn( + utf16.as_ptr(), + utf16.len(), + selected, + vw, + insets, + loupe_focus_x, + loupe_focus_y, + dim as u32, + zoom, + rgba.as_mut_ptr(), + rgba.len(), + p.user_data, + ); + if ok { + return AffineIosByteBuffer::from_vec(rgba); + } + } + + let rgba = render_loupe_rgba8( + &utf16, selected, vw, insets, focus_x, focus_y, dim as u32, zoom, + ); + AffineIosByteBuffer::from_vec(rgba) +} diff --git a/packages/frontend/hosts/ios/src/haptics.rs b/packages/frontend/hosts/ios/src/haptics.rs new file mode 100644 index 0000000000..471627c21b --- /dev/null +++ b/packages/frontend/hosts/ios/src/haptics.rs @@ -0,0 +1,90 @@ +//! Native iOS Haptics pattern definitions and deterministic dispatch accounting. + +/// Number of valid `AffineHapticPattern` variants. +pub const HAPTIC_PATTERN_COUNT: usize = 7; + +/// C-ABI haptic pattern enum matching `include/affine_mobile_host.h`. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AffineHapticPattern { + LightImpact = 0, + MediumImpact = 1, + HeavyImpact = 2, + SelectionChanged = 3, + Success = 4, + Warning = 5, + Error = 6, +} + +impl AffineHapticPattern { + pub fn from_u8(raw: u8) -> Option { + match raw { + 0 => Some(Self::LightImpact), + 1 => Some(Self::MediumImpact), + 2 => Some(Self::HeavyImpact), + 3 => Some(Self::SelectionChanged), + 4 => Some(Self::Success), + 5 => Some(Self::Warning), + 6 => Some(Self::Error), + _ => None, + } + } +} + +/// Deterministic counter state for triggered haptic events. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HapticsState { + counts: [u64; HAPTIC_PATTERN_COUNT], + total: u64, + last_pattern: Option, +} + +impl HapticsState { + pub fn record(&mut self, pattern: AffineHapticPattern) { + let idx = pattern as usize; + self.counts[idx] = self.counts[idx].saturating_add(1); + self.total = self.total.saturating_add(1); + self.last_pattern = Some(pattern); + } + + pub fn count_for(&self, pattern: AffineHapticPattern) -> u64 { + self.counts[pattern as usize] + } + + pub fn total_count(&self) -> u64 { + self.total + } + + pub fn last_pattern(&self) -> Option { + self.last_pattern + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn haptics_pattern_mapping_and_counters_cover_all_seven_variants() { + let all = [ + (0, AffineHapticPattern::LightImpact), + (1, AffineHapticPattern::MediumImpact), + (2, AffineHapticPattern::HeavyImpact), + (3, AffineHapticPattern::SelectionChanged), + (4, AffineHapticPattern::Success), + (5, AffineHapticPattern::Warning), + (6, AffineHapticPattern::Error), + ]; + + let mut state = HapticsState::default(); + for (raw, expected) in all { + assert_eq!(AffineHapticPattern::from_u8(raw), Some(expected)); + state.record(expected); + assert_eq!(state.count_for(expected), 1); + assert_eq!(state.last_pattern(), Some(expected)); + } + assert_eq!(state.total_count(), 7); + assert_eq!(AffineHapticPattern::from_u8(7), None); + assert_eq!(AffineHapticPattern::from_u8(255), None); + } +} diff --git a/packages/frontend/hosts/ios/src/keyboard_insets.rs b/packages/frontend/hosts/ios/src/keyboard_insets.rs new file mode 100644 index 0000000000..4814226588 --- /dev/null +++ b/packages/frontend/hosts/ios/src/keyboard_insets.rs @@ -0,0 +1,374 @@ +use crate::{AffineWindowInsets, selection::AffineRect}; + +/// Deterministic result of evaluating a keyboard frame against window bounds and safe area. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineKeyboardAvoidanceMetrics { + /// Raw vertical intersection between the docked software keyboard and window bounds. + pub raw_overlap_pt: f32, + /// Absolute docked keyboard overlap height from the window bottom edge in logical points + /// (`0.0` for floating, split, hardware, or hidden keyboards). Matches `ui::WindowInsets.ime.bottom`. + pub ime_bottom_pt: f32, + /// Additional keyboard height above `safe_bottom` (`max(0, ime_bottom_pt - safe_bottom)`). + /// Provided for local containers that already deduct `safeAreaInsets.bottom`. + pub ime_above_safe_bottom_pt: f32, + /// Effective total bottom avoidance inset (`max(safe_bottom, ime_bottom_pt)`), + /// matching `ui::WindowInsets::effective().bottom` and `safe_bottom + ime_above_safe_bottom_pt`. + pub effective_bottom_pt: f32, + /// True when the keyboard is floating or split (iPad) and does not dock to the bottom edge. + pub is_floating_or_split: bool, + /// True when no docked software keyboard overlaps the window (hidden or hardware keyboard). + pub is_hardware_or_hidden: bool, +} + +/// Active keyboard height animation tracked deterministically by `CADisplayLink` timestamps. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct KeyboardFrameTransition { + pub active: bool, + pub start_ime_bottom_pt: f32, + pub target_ime_bottom_pt: f32, + pub start_timestamp_sec: f64, + pub duration_sec: f64, +} + +impl KeyboardFrameTransition { + /// Begin a smooth transition toward `target_ime_bottom_pt` starting at `start_timestamp_sec`. + pub fn begin( + current_ime_bottom_pt: f32, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, + ) -> Self { + let cur = sanitize_non_neg(current_ime_bottom_pt); + let tgt = sanitize_non_neg(target_ime_bottom_pt); + let dur = if duration_sec.is_finite() && duration_sec > 0.0 { + duration_sec + } else { + 0.0 + }; + let ts = if start_timestamp_sec.is_finite() { + start_timestamp_sec + } else { + 0.0 + }; + Self { + active: dur > 0.0 && (cur - tgt).abs() > 0.01, + start_ime_bottom_pt: cur, + target_ime_bottom_pt: tgt, + start_timestamp_sec: ts, + duration_sec: dur, + } + } + + /// Sample the eased keyboard inset at `timestamp_sec` (monotonic `CADisplayLink.timestamp`). + /// Uses a cubic ease-out curve approximating UIKit's keyboard animation curve (`options: 7`). + pub fn sample(&mut self, timestamp_sec: f64) -> f32 { + if !self.active || self.duration_sec <= 0.0 { + self.active = false; + return self.target_ime_bottom_pt; + } + let now = if timestamp_sec.is_finite() { + timestamp_sec + } else { + self.start_timestamp_sec + self.duration_sec + }; + let elapsed = (now - self.start_timestamp_sec).max(0.0); + let t = (elapsed / self.duration_sec).clamp(0.0, 1.0); + if t >= 1.0 { + self.active = false; + return self.target_ime_bottom_pt; + } + let inv = 1.0 - t; + let eased = 1.0 - inv * inv * inv; + let value = f64::from(self.start_ime_bottom_pt) + + (f64::from(self.target_ime_bottom_pt) - f64::from(self.start_ime_bottom_pt)) * eased; + sanitize_non_neg(value as f32) + } +} + +/// Compute keyboard avoidance metrics from a keyboard frame in window coordinates, +/// isomorphic with `ui::WindowInsets::effective()` (`safe_area.bottom.max(ime.bottom)`). +/// +/// - Floating or split iPad keyboards (narrower than the window or detached from the bottom edge) +/// produce `ime_bottom_pt = 0.0`, `ime_above_safe_bottom_pt = 0.0`, and `is_floating_or_split = true`. +/// - External hardware keyboards or hidden keyboards produce `ime_bottom_pt = 0.0`, +/// `ime_above_safe_bottom_pt = 0.0`, and `is_hardware_or_hidden = true`. +/// - Docked software keyboards report `ime_bottom_pt = overlap_h` (from window bottom edge), +/// `ime_above_safe_bottom_pt = (overlap_h - safe_bottom).max(0.0)`, and +/// `effective_bottom_pt = safe_bottom.max(ime_bottom_pt)` with zero double deduction. +pub fn compute_keyboard_avoidance( + window_bounds: AffineRect, + keyboard_frame_in_window: AffineRect, + safe_bottom: f32, + is_hidden: bool, +) -> AffineKeyboardAvoidanceMetrics { + let wb = window_bounds.sanitized(); + let kb = keyboard_frame_in_window.sanitized(); + let safe_b = sanitize_non_neg(safe_bottom); + + if is_hidden || wb.width <= 0.0 || wb.height <= 0.0 || kb.width <= 0.0 || kb.height <= 0.0 { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: false, + is_hardware_or_hidden: true, + }; + } + + let inter_top = wb.y.max(kb.y); + let inter_bottom = wb.bottom().min(kb.bottom()); + let inter_left = wb.x.max(kb.x); + let inter_right = wb.right().min(kb.right()); + let overlap_h = (inter_bottom - inter_top).max(0.0); + let overlap_w = (inter_right - inter_left).max(0.0); + + if overlap_h <= 0.5 || overlap_w <= 0.5 { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: false, + is_hardware_or_hidden: true, + }; + } + + // Floating or split/slide-over keyboards either overlap less than the full window width + // or hover above the bottom edge of the window. + let edge_tolerance = 1.5; + let touches_bottom = kb.bottom() >= wb.bottom() - edge_tolerance; + let spans_full_width = overlap_w >= wb.width - edge_tolerance; + if !touches_bottom || !spans_full_width { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: true, + is_hardware_or_hidden: false, + }; + } + + let ime_above_safe_bottom_pt = (overlap_h - safe_b).max(0.0); + AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: overlap_h, + ime_bottom_pt: overlap_h, + ime_above_safe_bottom_pt, + effective_bottom_pt: safe_b.max(overlap_h), + is_floating_or_split: false, + is_hardware_or_hidden: false, + } +} + +/// Build an `AffineWindowInsets` snapshot from safe areas and non-double-counted `ime_bottom_pt`. +pub fn build_window_insets( + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + ime_bottom_pt: f32, +) -> AffineWindowInsets { + AffineWindowInsets { + safe_top: sanitize_non_neg(safe_top), + safe_right: sanitize_non_neg(safe_right), + safe_bottom: sanitize_non_neg(safe_bottom), + safe_left: sanitize_non_neg(safe_left), + ime_bottom: sanitize_non_neg(ime_bottom_pt), + } +} + +fn sanitize_non_neg(v: f32) -> f32 { + if v.is_finite() { v.max(0.0) } else { 0.0 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyboard_avoidance_table_covers_docked_safe_area_floating_split_and_hardware() { + struct Case { + name: &'static str, + window: AffineRect, + keyboard: AffineRect, + safe_bottom: f32, + is_hidden: bool, + expect_ime_bottom: f32, + expect_ime_above_safe: f32, + expect_effective: f32, + expect_floating: bool, + expect_hidden_or_hw: bool, + } + + let iphone_window = AffineRect { + x: 0.0, + y: 0.0, + width: 390.0, + height: 844.0, + }; + let ipad_window = AffineRect { + x: 0.0, + y: 0.0, + width: 1024.0, + height: 768.0, + }; + + let cases = [ + Case { + name: "iphone_docked_matches_ui_window_insets_and_exposes_above_safe", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 302.0, + expect_ime_above_safe: 268.0, + expect_effective: 302.0, + expect_floating: false, + expect_hidden_or_hw: false, + }, + Case { + name: "overlap_smaller_than_safe_bottom_keeps_effective_at_safe_bottom", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 820.0, + width: 390.0, + height: 24.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 24.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: false, + }, + Case { + name: "hardware_keyboard_offscreen_frame_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 844.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: true, + }, + Case { + name: "explicit_hide_notification_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: true, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: true, + }, + Case { + name: "ipad_floating_keyboard_narrower_than_window_yields_zero_ime", + window: ipad_window, + keyboard: AffineRect { + x: 640.0, + y: 420.0, + width: 320.0, + height: 280.0, + }, + safe_bottom: 20.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 20.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + Case { + name: "ipad_split_undocked_keyboard_above_bottom_yields_zero_ime", + window: ipad_window, + keyboard: AffineRect { + x: 0.0, + y: 380.0, + width: 1024.0, + height: 260.0, + }, + safe_bottom: 20.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 20.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + Case { + name: "slide_over_full_width_keyboard_partial_horizontal_overlap_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 380.0, + y: 544.0, + width: 390.0, + height: 300.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + ]; + + for c in cases { + let m = compute_keyboard_avoidance(c.window, c.keyboard, c.safe_bottom, c.is_hidden); + assert_eq!(m.ime_bottom_pt, c.expect_ime_bottom, "{}", c.name); + assert_eq!( + m.ime_above_safe_bottom_pt, c.expect_ime_above_safe, + "{}", + c.name + ); + assert_eq!(m.effective_bottom_pt, c.expect_effective, "{}", c.name); + assert_eq!( + m.effective_bottom_pt, + c.safe_bottom + m.ime_above_safe_bottom_pt, + "{}", + c.name + ); + assert_eq!(m.is_floating_or_split, c.expect_floating, "{}", c.name); + assert_eq!(m.is_hardware_or_hidden, c.expect_hidden_or_hw, "{}", c.name); + } + } + + #[test] + fn per_frame_keyboard_transition_interpolates_monotonically_to_target() { + let mut tr = KeyboardFrameTransition::begin(0.0, 302.0, 10.0, 0.25); + assert!(tr.active); + let f0 = tr.sample(10.0); + let f1 = tr.sample(10.05); + let f2 = tr.sample(10.125); + let f3 = tr.sample(10.25); + assert_eq!(f0, 0.0); + assert!(f1 > f0 && f1 < f2); + assert!(f2 > 151.0 && f2 < 302.0); + assert_eq!(f3, 302.0); + assert!(!tr.active); + } +} diff --git a/packages/frontend/hosts/ios/src/legacy_storage.rs b/packages/frontend/hosts/ios/src/legacy_storage.rs new file mode 100644 index 0000000000..751f0f7cea --- /dev/null +++ b/packages/frontend/hosts/ios/src/legacy_storage.rs @@ -0,0 +1,449 @@ +//! Thin iOS wrapper delegating `capacitor://localhost` `localStorage` sentinel validation, +//! parsing, and rollback write-back planning to `affine-legacy-import`. + +use std::collections::{BTreeMap, BTreeSet}; + +use affine_legacy_import::{ + KEY_AFFINE_SETTINGS, KEY_I18N_LNG, KEY_LAST_WORKSPACE_FLAVOUR, KEY_LAST_WORKSPACE_ID, + KEY_LOCAL_WORKSPACE_LIST, KEY_SERVER_LIST, KEY_THEME, LegacyImportError, + LegacyLocalStorageSnapshot as CanonicalSnapshot, LegacyServerMetadata, PREFIX_FEATURE_FLAG, + PREFIX_GLOBAL_STATE, PREFIX_GLOBAL_STATE_FEATURE_FLAG, PREFIX_SERVER_CONFIG, + SUFFIX_SERVER_AUTH, SentinelEvaluation, SentinelFailureReason, WebViewStorageSentinel, + import_from_sentinel, is_permitted_sentinel_entry_key, writeback::serialize_snapshot_entries, +}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Exact origin used by Capacitor 0.27.5 on iOS. +pub const LEGACY_CAPACITOR_ORIGIN: &str = "capacitor://localhost"; + +pub const LOCAL_WORKSPACE_KEY: &str = KEY_LOCAL_WORKSPACE_LIST; +pub const SERVER_LIST_KEY: &str = KEY_SERVER_LIST; +pub const SERVER_CONFIG_PREFIX: &str = PREFIX_SERVER_CONFIG; +pub const GLOBAL_STATE_PREFIX: &str = PREFIX_GLOBAL_STATE; +pub const AUTH_KEY_SUFFIX: &str = SUFFIX_SERVER_AUTH; +pub const FLAG_PREFIX: &str = PREFIX_FEATURE_FLAG; +pub const GLOBAL_STATE_FLAG_PREFIX: &str = PREFIX_GLOBAL_STATE_FEATURE_FLAG; +pub const I18N_KEY: &str = KEY_I18N_LNG; +pub const LAST_WORKSPACE_ID_KEY: &str = KEY_LAST_WORKSPACE_ID; +pub const LAST_WORKSPACE_FLAVOUR_KEY: &str = KEY_LAST_WORKSPACE_FLAVOUR; +pub const AFFINE_SETTINGS_KEY: &str = KEY_AFFINE_SETTINGS; +pub const THEME_KEY: &str = KEY_THEME; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum LegacyStorageError { + #[error("invalid JSON payload: {0}")] + InvalidJson(String), + #[error("unexpected WebView origin: expected {LEGACY_CAPACITOR_ORIGIN}, got {0}")] + WrongOrigin(String), + #[error("forbidden IndexedDB access detected during legacy probe ({0} calls)")] + IndexedDbTouched(u64), + #[error("invalid legacy localStorage sentinel: {0}")] + InvalidSentinel(String), + #[error("write-back readback mismatch for key {key}: expected {expected:?}, got {actual:?}")] + WriteBackMismatch { + key: String, + expected: Option, + actual: Option, + }, +} + +/// Unified `WebViewStorageSentinel` payload returned by `LegacyLocalStorageProbe.swift`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LegacyLocalStorageSnapshot { + pub origin: String, + pub length: usize, + pub keys: Vec, + pub entries: BTreeMap, + #[serde(default)] + pub idb_access_count: u64, +} + +/// Structured state imported from allowlisted `capacitor://localhost` `localStorage` keys +/// (camelCase wire DTO for `HostBootstrapCoordinator.swift`, backed by `affine-legacy-import`). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportedLegacyState { + pub local_workspace_ids: Vec, + #[serde(default)] + pub has_local_workspace_key: bool, + pub servers: Vec, + #[serde(default)] + pub has_server_list_key: bool, + pub server_configs: BTreeMap, + pub auth_caches: BTreeMap, + #[serde(default)] + pub cloud_workspace_caches: BTreeMap, + pub feature_flags: BTreeMap, + pub i18n_lng: Option, + pub last_workspace_id: Option, + pub last_workspace_flavour: Option, + pub affine_settings: Option, + pub theme: Option, + #[serde(default)] + pub raw_unparsed_entries: BTreeMap, +} + +/// Result of classifying a positive sentinel snapshot before creating any default workspace. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum LegacyUpgradeDisposition { + FreshInstall { state: ImportedLegacyState }, + ExistingUser { state: ImportedLegacyState }, +} + +/// Deterministic mutation plan written back to `capacitor://localhost` `localStorage`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LegacyWriteBackPlan { + pub set: BTreeMap, + pub remove: Vec, +} + +/// Return true if `key` is permitted by `affine-legacy-import`'s single authoritative allowlist. +pub fn is_whitelisted_legacy_key(key: &str) -> bool { + is_permitted_sentinel_entry_key(key) +} + +fn from_canonical(snap: CanonicalSnapshot) -> ImportedLegacyState { + let servers = snap + .server_list + .into_iter() + .filter_map(|s| serde_json::to_value(s).ok()) + .collect(); + let auth_caches = snap + .server_auth_sessions + .into_iter() + .map(|(sid, v)| (format!("{PREFIX_GLOBAL_STATE}{sid}{SUFFIX_SERVER_AUTH}"), v)) + .collect(); + let feature_flags = snap + .feature_flags + .into_iter() + .map(|(name, v)| { + let key = if snap.global_state_flag_names.contains(&name) { + format!("{PREFIX_GLOBAL_STATE_FEATURE_FLAG}{name}") + } else { + format!("{PREFIX_FEATURE_FLAG}{name}") + }; + (key, v) + }) + .collect(); + ImportedLegacyState { + local_workspace_ids: snap.local_workspace_ids, + has_local_workspace_key: snap.has_local_workspace_key, + servers, + has_server_list_key: snap.has_server_list_key, + server_configs: snap.server_configs, + auth_caches, + cloud_workspace_caches: snap.cloud_workspace_caches, + feature_flags, + i18n_lng: snap.i18n_lng, + last_workspace_id: snap.last_workspace_id, + last_workspace_flavour: snap.last_workspace_flavour, + affine_settings: snap.affine_settings, + theme: snap.theme, + raw_unparsed_entries: snap.preserved_raw_entries, + } +} + +fn to_canonical(state: &ImportedLegacyState) -> CanonicalSnapshot { + let server_list = state + .servers + .iter() + .filter_map(|v| serde_json::from_value::(v.clone()).ok()) + .collect(); + let mut server_auth_sessions = BTreeMap::new(); + let mut preserved = state.raw_unparsed_entries.clone(); + for (key, value) in &state.auth_caches { + if let Some(sid) = key + .strip_prefix(PREFIX_GLOBAL_STATE) + .and_then(|r| r.strip_suffix(SUFFIX_SERVER_AUTH)) + && !sid.is_empty() + && !sid.contains(':') + { + server_auth_sessions.insert(sid.to_string(), value.clone()); + } else if is_permitted_sentinel_entry_key(key) + && let Ok(encoded) = serde_json::to_string(value) + { + preserved.insert(key.clone(), encoded); + } + } + let mut feature_flags = BTreeMap::new(); + let mut global_state_flag_names = BTreeSet::new(); + for (key, value) in &state.feature_flags { + if let Some(name) = key.strip_prefix(PREFIX_GLOBAL_STATE_FEATURE_FLAG) + && !name.is_empty() + { + feature_flags.insert(name.to_string(), value.clone()); + global_state_flag_names.insert(name.to_string()); + } else if let Some(name) = key.strip_prefix(PREFIX_FEATURE_FLAG) + && !name.is_empty() + { + feature_flags.insert(name.to_string(), value.clone()); + } + } + CanonicalSnapshot { + local_workspace_ids: state.local_workspace_ids.clone(), + has_local_workspace_key: state.has_local_workspace_key, + server_list, + has_server_list_key: state.has_server_list_key, + server_configs: state.server_configs.clone(), + server_auth_sessions, + cloud_workspace_caches: state.cloud_workspace_caches.clone(), + feature_flags, + global_state_flag_names, + i18n_lng: state.i18n_lng.clone(), + last_workspace_id: state.last_workspace_id.clone(), + last_workspace_flavour: state.last_workspace_flavour.clone(), + affine_settings: state.affine_settings.clone(), + theme: state.theme.clone(), + preserved_raw_entries: preserved, + } +} + +/// Validate the unified `WebViewStorageSentinel` and parse allowlisted `localStorage` entries +/// via `affine-legacy-import` (checking `idb_access_count == 0` first). +pub fn parse_legacy_snapshot( + snapshot: &LegacyLocalStorageSnapshot, +) -> Result { + if snapshot.idb_access_count != 0 { + return Err(LegacyStorageError::IndexedDbTouched( + snapshot.idb_access_count, + )); + } + let sentinel = WebViewStorageSentinel { + origin: snapshot.origin.clone(), + length: snapshot.length, + keys: snapshot.keys.clone(), + entries: snapshot.entries.clone(), + }; + let (eval, canonical) = + import_from_sentinel(&sentinel, &[LEGACY_CAPACITOR_ORIGIN]).map_err(|err| match err { + LegacyImportError::SentinelFailed(SentinelFailureReason::OriginMismatch { actual }) => { + LegacyStorageError::WrongOrigin(actual) + } + LegacyImportError::SentinelFailed(SentinelFailureReason::EmptyOrigin) => { + LegacyStorageError::WrongOrigin(snapshot.origin.clone()) + } + LegacyImportError::SentinelFailed(reason) => { + LegacyStorageError::InvalidSentinel(format!("{reason:?}")) + } + other => LegacyStorageError::InvalidSentinel(other.to_string()), + })?; + let state = from_canonical(canonical); + match eval { + SentinelEvaluation::ValidEmpty + | SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: false, + } => Ok(LegacyUpgradeDisposition::FreshInstall { state }), + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true, + } => Ok(LegacyUpgradeDisposition::ExistingUser { state }), + SentinelEvaluation::UnreadyOrMismatch(reason) => { + Err(LegacyStorageError::InvalidSentinel(format!("{reason:?}"))) + } + } +} + +impl ImportedLegacyState { + /// Build a rollback write-back plan for `capacitor://localhost` `localStorage` using + /// `affine-legacy-import`'s serializer, propagating serialization errors instead of + /// silently emitting empty `set` / destructive `remove` plans. + pub fn to_write_back_plan( + &self, + previous_keys: &[String], + ) -> Result { + let mut canonical = to_canonical(self); + if !canonical + .preserved_raw_entries + .contains_key(KEY_LOCAL_WORKSPACE_LIST) + { + canonical.has_local_workspace_key = true; + } + if previous_keys.iter().any(|k| k == KEY_SERVER_LIST) + && !canonical + .preserved_raw_entries + .contains_key(KEY_SERVER_LIST) + { + canonical.has_server_list_key = true; + } + let set = serialize_snapshot_entries(&canonical).map_err(|err| match err { + LegacyImportError::DisallowedKey(key) => LegacyStorageError::InvalidSentinel(key), + LegacyImportError::MalformedJson { key, message } => { + LegacyStorageError::InvalidJson(format!("{key}: {message}")) + } + LegacyImportError::SentinelFailed(reason) => { + LegacyStorageError::InvalidSentinel(format!("{reason:?}")) + } + })?; + let mut remove: Vec = previous_keys + .iter() + .filter(|prev| { + is_permitted_sentinel_entry_key(prev) + && prev.as_str() != KEY_LOCAL_WORKSPACE_LIST + && !set.contains_key(prev.as_str()) + }) + .cloned() + .collect(); + remove.sort(); + remove.dedup(); + Ok(LegacyWriteBackPlan { set, remove }) + } +} + +/// Verify that a post-write-back readback snapshot matches the plan with zero IDB access. +pub fn verify_write_back_readback( + plan: &LegacyWriteBackPlan, + readback: &LegacyLocalStorageSnapshot, +) -> Result<(), LegacyStorageError> { + if readback.origin != LEGACY_CAPACITOR_ORIGIN { + return Err(LegacyStorageError::WrongOrigin(readback.origin.clone())); + } + if readback.idb_access_count != 0 { + return Err(LegacyStorageError::IndexedDbTouched( + readback.idb_access_count, + )); + } + for (key, expected) in &plan.set { + let actual = readback.entries.get(key); + if actual != Some(expected) { + return Err(LegacyStorageError::WriteBackMismatch { + key: key.clone(), + expected: Some(expected.clone()), + actual: actual.cloned(), + }); + } + } + for key in &plan.remove { + if let Some(actual) = readback.entries.get(key) { + return Err(LegacyStorageError::WriteBackMismatch { + key: key.clone(), + expected: None, + actual: Some(actual.clone()), + }); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corrupt_workspace_preservation_writeback_roundtrip_and_disallowed_error() { + assert!(is_whitelisted_legacy_key( + "global-state:cloud-workspace:acct-1" + )); + assert!(is_whitelisted_legacy_key( + "global-state:selfhosted-workspace-s1:acct-2" + )); + assert!(!is_whitelisted_legacy_key("unrelated-key")); + + let idb_touched = LegacyLocalStorageSnapshot { + origin: LEGACY_CAPACITOR_ORIGIN.into(), + length: 0, + keys: vec![], + entries: BTreeMap::new(), + idb_access_count: 1, + }; + assert_eq!( + parse_legacy_snapshot(&idb_touched), + Err(LegacyStorageError::IndexedDbTouched(1)) + ); + + // 1. Corrupt affine-local-workspace -> ExistingUser with 0 local workspaces + verbatim write-back. + for raw_corrupt in ["{broken", "{}", "\"abc\""] { + let corrupt_ws = LegacyLocalStorageSnapshot { + origin: LEGACY_CAPACITOR_ORIGIN.into(), + length: 2, + keys: vec![LOCAL_WORKSPACE_KEY.into(), THEME_KEY.into()], + entries: BTreeMap::from([ + (LOCAL_WORKSPACE_KEY.into(), raw_corrupt.into()), + (THEME_KEY.into(), "dark".into()), + ]), + idb_access_count: 0, + }; + let LegacyUpgradeDisposition::ExistingUser { mut state } = + parse_legacy_snapshot(&corrupt_ws).expect("corrupt list must preserve verbatim") + else { + panic!("corrupt affine-local-workspace must classify as ExistingUser"); + }; + assert!(state.local_workspace_ids.is_empty()); + assert!(state.has_local_workspace_key); + state.theme = Some("light".into()); + let plan = state.to_write_back_plan(&corrupt_ws.keys).unwrap(); + assert_eq!( + plan.set.get(LOCAL_WORKSPACE_KEY).map(String::as_str), + Some(raw_corrupt), + "untouched corrupt affine-local-workspace must write back verbatim" + ); + assert_eq!(plan.set.get(THEME_KEY).map(String::as_str), Some("light")); + assert!(plan.remove.is_empty()); + + // Retiring the preserved raw entry and updating local_workspace_ids emits new JSON array. + state.raw_unparsed_entries.remove(LOCAL_WORKSPACE_KEY); + state.local_workspace_ids = vec!["ws-new".into()]; + state.has_local_workspace_key = true; + let updated_plan = state.to_write_back_plan(&corrupt_ws.keys).unwrap(); + assert_eq!( + updated_plan + .set + .get(LOCAL_WORKSPACE_KEY) + .map(String::as_str), + Some(r#"["ws-new"]"#) + ); + } + + // 2. import -> mutate -> to_write_back_plan -> verify_write_back_readback closed loop. + let valid = LegacyLocalStorageSnapshot { + origin: LEGACY_CAPACITOR_ORIGIN.into(), + length: 3, + keys: vec![ + "__cap_noise__".into(), + LOCAL_WORKSPACE_KEY.into(), + THEME_KEY.into(), + ], + entries: BTreeMap::from([ + ( + LOCAL_WORKSPACE_KEY.into(), + r#"["ws-1","ws-2","ws-1"]"#.into(), + ), + (THEME_KEY.into(), "dark".into()), + ]), + idb_access_count: 0, + }; + let LegacyUpgradeDisposition::ExistingUser { mut state } = + parse_legacy_snapshot(&valid).unwrap() + else { + panic!("expected existing user"); + }; + assert_eq!(state.local_workspace_ids, vec!["ws-1", "ws-2"]); + state.theme = Some("light".into()); + let plan = state.to_write_back_plan(&valid.keys).unwrap(); + assert_eq!( + plan.set.get(LOCAL_WORKSPACE_KEY).map(String::as_str), + Some(r#"["ws-1","ws-2"]"#) + ); + assert_eq!(plan.set.get(THEME_KEY).map(String::as_str), Some("light")); + assert!(plan.remove.is_empty()); + let readback = LegacyLocalStorageSnapshot { + origin: LEGACY_CAPACITOR_ORIGIN.into(), + length: 3, + keys: valid.keys.clone(), + entries: plan.set.clone(), + idb_access_count: 0, + }; + verify_write_back_readback(&plan, &readback).unwrap(); + + // 3. Disallowed key in raw_unparsed_entries must return Err instead of wiping all keys. + state + .raw_unparsed_entries + .insert("unrelated.preference".into(), "x".into()); + assert!(matches!( + state.to_write_back_plan(&valid.keys), + Err(LegacyStorageError::InvalidSentinel(_)) + )); + } +} diff --git a/packages/frontend/hosts/ios/src/lib.rs b/packages/frontend/hosts/ios/src/lib.rs new file mode 100644 index 0000000000..c6b6957337 --- /dev/null +++ b/packages/frontend/hosts/ios/src/lib.rs @@ -0,0 +1,636 @@ +#![deny(unsafe_code)] + +//! Thin iOS C-ABI host crate (`affine-ios-host`). +//! +//! Owns the authoritative UTF-16 text editing state (surrogate-pair safe), +//! clamped selection/marked ranges, safe-area and IME insets, frame tick +//! accounting, in-place 0.27.5 SQLite WAL co-storage, Keychain 2001-epoch +//! token compatibility, and zero-IDB `capacitor://localhost` upgrade/rollback +//! bridges behind `include/affine_mobile_host.h`. + +pub mod auth; +pub mod clipboard; +pub(crate) mod editor_doc_positions; +#[cfg(not(target_os = "ios"))] +pub(crate) mod editor_fallback; +pub(crate) mod editor_platform; +pub(crate) mod editor_runtime; +pub mod ffi; +pub mod ffi_doc_positions; +pub mod ffi_editor; +pub mod ffi_islands; +pub mod ffi_s3; +pub mod ffi_selection; +pub mod ffi_text; +pub mod haptics; +pub mod keyboard_insets; +pub mod legacy_storage; +pub mod native_islands; +pub mod pdf; +pub(crate) mod runtime_root; +pub mod selection; +pub mod share_ingest; +pub(crate) mod shell_runtime; +pub(crate) mod shell_workspace; +pub mod text_layout; +pub mod workspace_store; + +/// C-ABI window insets matching `AffineWindowInsets` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineWindowInsets { + pub safe_top: f32, + pub safe_right: f32, + pub safe_bottom: f32, + pub safe_left: f32, + /// Absolute keyboard overlap height from the window bottom edge in logical points. + /// Does not subtract `safe_bottom`; `ui::WindowInsets::effective()` takes the max. + pub ime_bottom: f32, +} + +/// C-ABI UTF-16 range matching `AffineUtf16Range` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AffineUtf16Range { + pub location: u32, + pub length: u32, +} + +/// Pure safe-Rust state backing an `AffineIosHost` handle. +#[derive(Debug, Clone, Default)] +pub struct IosHostState { + width_pt: f32, + height_pt: f32, + scale_factor: f32, + insets: AffineWindowInsets, + frame_count: u64, + last_frame_timestamp_sec: f64, + dirty: bool, + utf16_text: Vec, + selected_range: AffineUtf16Range, + marked_range: Option, + selection_overlay: selection::SelectionOverlayController, + keyboard_transition: keyboard_insets::KeyboardFrameTransition, + haptics: haptics::HapticsState, +} + +impl IosHostState { + pub fn new(width_pt: f32, height_pt: f32, scale_factor: f32) -> Self { + Self { + width_pt: width_pt.max(0.0), + height_pt: height_pt.max(0.0), + scale_factor: if scale_factor.is_finite() && scale_factor > 0.0 { + scale_factor + } else { + 1.0 + }, + dirty: true, + ..Self::default() + } + } + + pub fn resize(&mut self, width_pt: f32, height_pt: f32, scale_factor: f32) { + self.width_pt = width_pt.max(0.0); + self.height_pt = height_pt.max(0.0); + if scale_factor.is_finite() && scale_factor > 0.0 { + self.scale_factor = scale_factor; + } + self.dirty = true; + } + + pub fn set_insets(&mut self, insets: AffineWindowInsets) { + let next = AffineWindowInsets { + safe_top: insets.safe_top.max(0.0), + safe_right: insets.safe_right.max(0.0), + safe_bottom: insets.safe_bottom.max(0.0), + safe_left: insets.safe_left.max(0.0), + ime_bottom: insets.ime_bottom.max(0.0), + }; + if next != self.insets { + self.insets = next; + self.dirty = true; + } + } + + pub fn insets(&self) -> AffineWindowInsets { + self.insets + } + + /// Additional keyboard height above `safe_bottom` (`(ime_bottom - safe_bottom).max(0.0)`), + /// for containers that already apply `safe_bottom` separately. + pub fn ime_above_safe_bottom(&self) -> f32 { + (self.insets.ime_bottom - self.insets.safe_bottom).max(0.0) + } + + pub fn viewport_size_pt(&self) -> (f32, f32) { + (self.width_pt, self.height_pt) + } + + pub fn selection_overlay(&self) -> &selection::SelectionOverlayController { + &self.selection_overlay + } + + pub fn selection_overlay_mut(&mut self) -> &mut selection::SelectionOverlayController { + self.dirty = true; + &mut self.selection_overlay + } + + pub fn selection_overlay_state(&self) -> selection::AffineSelectionOverlayState { + self.selection_overlay + .layout(self.width_pt, self.height_pt, self.insets) + } + + pub fn text_writing_direction(&self) -> selection::AffineWritingDirection { + text_layout::detect_paragraph_writing_direction( + &self.utf16_text, + self.selected_range().location as usize, + ) + } + + pub fn text_caret_rect(&self, utf16_offset: u32) -> selection::AffineRect { + text_layout::caret_rect_for_offset( + &self.utf16_text, + utf16_offset, + self.width_pt, + self.insets, + ) + } + + pub fn text_closest_offset(&self, point: selection::AffinePoint) -> u32 { + text_layout::closest_offset_for_point(&self.utf16_text, point, self.width_pt, self.insets) + } + + pub fn render_loupe_rgba8( + &self, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, + ) -> Vec { + text_layout::render_loupe_rgba8( + &self.utf16_text, + self.selected_range(), + self.width_pt, + self.insets, + focus_x, + focus_y, + diameter_px, + zoom_scale, + ) + } + + pub fn begin_keyboard_transition( + &mut self, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, + ) { + self.keyboard_transition = keyboard_insets::KeyboardFrameTransition::begin( + self.insets.ime_bottom, + target_ime_bottom_pt, + start_timestamp_sec, + duration_sec, + ); + if self.keyboard_transition.active { + self.dirty = true; + } else { + let mut next = self.insets; + next.ime_bottom = self.keyboard_transition.target_ime_bottom_pt; + self.set_insets(next); + } + } + + pub fn sample_keyboard_frame( + &mut self, + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + frame_timestamp_sec: f64, + ) -> AffineWindowInsets { + let sampled_ime = if self.keyboard_transition.active { + self.keyboard_transition.sample(frame_timestamp_sec) + } else { + self.insets.ime_bottom + }; + let next = keyboard_insets::build_window_insets( + safe_top, + safe_right, + safe_bottom, + safe_left, + sampled_ime, + ); + self.set_insets(next); + self.insets + } + + pub fn haptics(&self) -> &haptics::HapticsState { + &self.haptics + } + + pub fn record_haptic(&mut self, pattern: haptics::AffineHapticPattern) { + self.haptics.record(pattern); + } + + /// AFFiNE light canvas clear color (`#FAFAFC`, contrast > 16:1 against `#1A1A1A` text). + pub const DEFAULT_CLEAR_COLOR_RGBA: u32 = 0xFAFA_FCFF; + + /// Mark the host surface dirty so the next `render_frame` tick draws. + pub fn request_frame(&mut self) { + self.dirty = true; + } + + pub fn is_dirty(&self) -> bool { + self.dirty || self.keyboard_transition.active + } + + pub fn render_frame(&mut self, timestamp_sec: f64) -> u32 { + if !self.dirty { + return 0; + } + self.dirty = false; + self.frame_count = self.frame_count.saturating_add(1); + if timestamp_sec.is_finite() { + self.last_frame_timestamp_sec = timestamp_sec; + } + Self::DEFAULT_CLEAR_COLOR_RGBA + } + + pub fn frame_count(&self) -> u64 { + self.frame_count + } + + pub fn utf16_text(&self) -> &[u16] { + &self.utf16_text + } + + pub fn selected_range(&self) -> AffineUtf16Range { + self.clamp_range(self.selected_range) + } + + pub fn marked_range(&self) -> AffineUtf16Range { + self.marked_range + .map(|r| self.clamp_range(r)) + .unwrap_or(AffineUtf16Range { + location: u32::MAX, + length: 0, + }) + } + + pub fn insert_text(&mut self, utf16: &[u16]) { + let target = self.clamp_range(self.marked_range.unwrap_or(self.selected_range)); + let start = target.location as usize; + let end = start + target.length as usize; + self.utf16_text.splice(start..end, utf16.iter().copied()); + let new_loc = (start + utf16.len()).min(u32::MAX as usize) as u32; + self.selected_range = AffineUtf16Range { + location: new_loc, + length: 0, + }; + self.marked_range = None; + self.selection_overlay.clear(); + self.dirty = true; + } + + /// Deletes the active selection, or one full UTF-16 scalar (including + /// surrogate pairs such as Emoji) before the caret. + pub fn delete_backward(&mut self) { + let sel = self.clamp_range(self.selected_range); + if sel.length > 0 { + let start = sel.location as usize; + let end = start + sel.length as usize; + self.utf16_text.drain(start..end); + self.selected_range = AffineUtf16Range { + location: sel.location, + length: 0, + }; + self.shrink_marked_range(start, end); + self.selection_overlay.clear(); + self.dirty = true; + return; + } + if sel.location == 0 { + return; + } + let end = sel.location as usize; + let mut start = end - 1; + if start > 0 { + let prev = self.utf16_text[start]; + let before = self.utf16_text[start - 1]; + if (0xDC00..=0xDFFF).contains(&prev) && (0xD800..=0xDBFF).contains(&before) { + start -= 1; + } + } + self.utf16_text.drain(start..end); + self.selected_range = AffineUtf16Range { + location: start as u32, + length: 0, + }; + self.shrink_marked_range(start, end); + self.selection_overlay.clear(); + self.dirty = true; + } + + /// Deletes an explicit UTF-16 range (for grapheme clusters such as multi-codepoint + /// ZWJ Emoji computed by UIKit `rangeOfComposedCharacterSequence`) and places the + /// caret at the start of the deleted range. + pub fn delete_range(&mut self, range: AffineUtf16Range) { + let clamped = self.clamp_range(range); + if clamped.length == 0 { + return; + } + let start = clamped.location as usize; + let end = start + clamped.length as usize; + self.utf16_text.drain(start..end); + self.selected_range = AffineUtf16Range { + location: clamped.location, + length: 0, + }; + self.shrink_marked_range(start, end); + self.selection_overlay.clear(); + self.dirty = true; + } + + /// Updates the active UTF-16 selection range (clamped to current buffer bounds). + pub fn set_selected_range(&mut self, range: AffineUtf16Range) { + let next = self.clamp_range(range); + if next.length == 0 + && self.selection_overlay.active_drag_handle() + == selection::AffineSelectionHandleKind::None + { + self.selection_overlay.clear(); + } + if next != self.selected_range { + self.selected_range = next; + self.dirty = true; + } + } + + /// Replaces an explicit UTF-16 range with `utf16`, moves the caret to the end + /// of the replacement, and clears any active marked range. + pub fn replace_range(&mut self, range: AffineUtf16Range, utf16: &[u16]) { + let clamped = self.clamp_range(range); + let start = clamped.location as usize; + let end = start + clamped.length as usize; + self.utf16_text.splice(start..end, utf16.iter().copied()); + let new_loc = start.saturating_add(utf16.len()).min(u32::MAX as usize) as u32; + self.selected_range = AffineUtf16Range { + location: new_loc, + length: 0, + }; + self.marked_range = None; + self.selection_overlay.clear(); + self.dirty = true; + } + + pub fn set_marked_text(&mut self, utf16: &[u16], selected_in_marked: AffineUtf16Range) { + let target = self.clamp_range(self.marked_range.unwrap_or(self.selected_range)); + let start = target.location as usize; + let end = start + target.length as usize; + self.utf16_text.splice(start..end, utf16.iter().copied()); + if utf16.is_empty() { + self.marked_range = None; + self.selected_range = AffineUtf16Range { + location: target.location, + length: 0, + }; + } else { + let marked_len = utf16.len().min(u32::MAX as usize) as u32; + self.marked_range = Some(AffineUtf16Range { + location: target.location, + length: marked_len, + }); + let rel_loc = selected_in_marked.location.min(marked_len); + let rel_len = selected_in_marked.length.min(marked_len - rel_loc); + self.selected_range = AffineUtf16Range { + location: target.location.saturating_add(rel_loc), + length: rel_len, + }; + } + self.dirty = true; + } + + pub fn unmark_text(&mut self) { + if self.marked_range.take().is_some() { + self.dirty = true; + } + } + + fn clamp_range(&self, range: AffineUtf16Range) -> AffineUtf16Range { + let max_len = self.utf16_text.len().min(u32::MAX as usize) as u32; + let loc = range.location.min(max_len); + let len = range.length.min(max_len - loc); + AffineUtf16Range { + location: loc, + length: len, + } + } + + fn shrink_marked_range(&mut self, del_start: usize, del_end: usize) { + let Some(marked) = self.marked_range else { + return; + }; + let m_start = marked.location as usize; + let m_end = m_start + marked.length as usize; + let del_len = del_end - del_start; + if del_end <= m_start { + self.marked_range = Some(AffineUtf16Range { + location: (m_start - del_len) as u32, + length: marked.length, + }); + } else if del_start < m_end { + let overlap = m_end.min(del_end).saturating_sub(m_start.max(del_start)); + let remaining = (marked.length as usize).saturating_sub(overlap); + if remaining == 0 { + self.marked_range = None; + } else { + self.marked_range = Some(AffineUtf16Range { + location: m_start.min(del_start) as u32, + length: remaining as u32, + }); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ios_host_state_handles_emoji_surrogate_delete_and_marked_text() { + let mut state = IosHostState::new(390.0, 844.0, 3.0); + let emoji: Vec = "A😀".encode_utf16().collect(); + assert_eq!(emoji.len(), 3); + state.insert_text(&emoji); + assert_eq!( + state.selected_range(), + AffineUtf16Range { + location: 3, + length: 0 + } + ); + + state.delete_backward(); + assert_eq!(String::from_utf16(state.utf16_text()).unwrap(), "A"); + assert_eq!( + state.selected_range(), + AffineUtf16Range { + location: 1, + length: 0 + } + ); + + let marked: Vec = "ni".encode_utf16().collect(); + state.set_marked_text( + &marked, + AffineUtf16Range { + location: 2, + length: 0, + }, + ); + assert_eq!( + state.marked_range(), + AffineUtf16Range { + location: 1, + length: 2 + } + ); + state.delete_backward(); + assert_eq!( + state.marked_range(), + AffineUtf16Range { + location: 1, + length: 1 + } + ); + state.unmark_text(); + assert_eq!(state.marked_range().location, u32::MAX); + + let zwj_family: Vec = "👨‍👩‍👧‍👦".encode_utf16().collect(); + assert_eq!(zwj_family.len(), 11); + state.insert_text(&zwj_family); + assert_eq!(state.utf16_text().len(), 13); + state.delete_range(AffineUtf16Range { + location: 2, + length: 11, + }); + assert_eq!(String::from_utf16(state.utf16_text()).unwrap(), "An"); + assert_eq!( + state.selected_range(), + AffineUtf16Range { + location: 2, + length: 0 + } + ); + } + + #[test] + fn ios_host_insets_and_frame_counter_clamp_negatives() { + let mut state = IosHostState::new(390.0, 844.0, 3.0); + state.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: -5.0, + }); + assert_eq!(state.insets().ime_bottom, 0.0); + state.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 302.0, + }); + assert_eq!(state.insets().safe_bottom, 34.0); + assert_eq!(state.insets().ime_bottom, 302.0); + let color = state.render_frame(1.25); + assert_eq!(color, IosHostState::DEFAULT_CLEAR_COLOR_RGBA); + assert_eq!(state.frame_count(), 1); + // Idle frame returns 0 and skips GPU submission until dirty again. + assert_eq!(state.render_frame(1.266), 0); + assert_eq!(state.frame_count(), 1); + state.request_frame(); + assert_eq!( + state.render_frame(1.283), + IosHostState::DEFAULT_CLEAR_COLOR_RGBA + ); + assert_eq!(state.frame_count(), 2); + } + + #[test] + fn ios_host_replace_range_and_set_selected_range_match_uikit_autocorrect() { + let mut state = IosHostState::new(390.0, 844.0, 3.0); + let ab: Vec = "AB".encode_utf16().collect(); + state.insert_text(&ab); + assert_eq!(state.selected_range().location, 2); + + let x: Vec = "X".encode_utf16().collect(); + state.replace_range( + AffineUtf16Range { + location: 0, + length: 1, + }, + &x, + ); + assert_eq!(String::from_utf16(state.utf16_text()).unwrap(), "XB"); + assert_eq!( + state.selected_range(), + AffineUtf16Range { + location: 1, + length: 0 + } + ); + + let mut spell = IosHostState::new(390.0, 844.0, 3.0); + let teh_cat: Vec = "teh cat".encode_utf16().collect(); + spell.insert_text(&teh_cat); + assert_eq!(spell.selected_range().location, 7); + let the: Vec = "the".encode_utf16().collect(); + spell.replace_range( + AffineUtf16Range { + location: 0, + length: 3, + }, + &the, + ); + assert_eq!(String::from_utf16(spell.utf16_text()).unwrap(), "the cat"); + assert_eq!( + spell.selected_range(), + AffineUtf16Range { + location: 3, + length: 0 + } + ); + + spell.set_selected_range(AffineUtf16Range { + location: 4, + length: 3, + }); + assert_eq!( + spell.selected_range(), + AffineUtf16Range { + location: 4, + length: 3 + } + ); + + let mut kb = IosHostState::new(390.0, 844.0, 3.0); + let _ = kb.render_frame(1.0); + assert!(!kb.is_dirty()); + kb.begin_keyboard_transition(302.0, 10.0, 0.25); + assert!(kb.is_dirty()); + let f1 = kb.sample_keyboard_frame(59.0, 0.0, 34.0, 0.0, 10.016); + assert!(f1.ime_bottom > 0.0 && f1.ime_bottom < 302.0); + let _ = kb.render_frame(10.016); + assert!( + kb.is_dirty(), + "in-progress keyboard transition must keep IosHostState::is_dirty() true after Frame 1" + ); + let f_end = kb.sample_keyboard_frame(59.0, 0.0, 34.0, 0.0, 10.30); + assert!((f_end.ime_bottom - 302.0).abs() < 1e-3); + let _ = kb.render_frame(10.30); + assert!(!kb.is_dirty()); + } +} diff --git a/packages/frontend/hosts/ios/src/native_islands.rs b/packages/frontend/hosts/ios/src/native_islands.rs new file mode 100644 index 0000000000..da9697b04e --- /dev/null +++ b/packages/frontend/hosts/ios/src/native_islands.rs @@ -0,0 +1,437 @@ +//! Zero-CocoaPods iOS native-island narrow state machines: +//! 1. `AffinePaywall`: StoreKit 2 product catalog, purchase state machine, and JWS envelope check. +//! 2. `OnboardingSignIn`: First-launch onboarding + Sign in with Apple / OAuth CSRF narrow bridge, +//! explicitly separating callback/credential receipt (`PendingExchange`) from server-verified +//! session establishment (`Completed`). +//! (ShareExtension ingest runs atomically against SQLite in `crate::share_ingest`.) + +use serde::{Deserialize, Serialize}; + +pub use crate::share_ingest::IOS_APP_GROUP_ID; + +/// StoreKit 2 paywall narrow bridge state. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PaywallPhase { + Idle, + LoadingProducts, + Ready, + Purchasing, + Verified, + Pending, + Cancelled, + Failed, +} + +/// StoreKit 2 product descriptor bridged from Swift `Product`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PaywallProduct { + pub product_id: String, + pub display_name: String, + pub display_price: String, +} + +/// StoreKit 2 paywall state machine + JWS transaction verifier. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaywallStateMachine { + pub phase: PaywallPhase, + pub products: Vec, + pub active_product_id: Option, + pub verified_transaction_id: Option, + pub last_error: Option, +} + +impl Default for PaywallStateMachine { + fn default() -> Self { + Self { + phase: PaywallPhase::Idle, + products: Vec::new(), + active_product_id: None, + verified_transaction_id: None, + last_error: None, + } + } +} + +impl PaywallStateMachine { + /// Exact `0.27.5` App Store Connect product allowlist (`PricingConfiguration.swift`). + pub fn is_known_product_id(product_id: &str) -> bool { + matches!( + product_id, + "app.affine.pro.Monthly" | "app.affine.pro.Annual" | "app.affine.pro.ai.Annual" + ) + } + + /// Validates a compact 3-part JWS string (`header.payload.signature`) with non-empty segments. + pub fn is_valid_jws_envelope(jws: &str) -> bool { + let mut parts = jws.split('.'); + let (Some(h), Some(p), Some(s), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return false; + }; + let valid_seg = |seg: &str| { + !seg.is_empty() + && seg + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + }; + valid_seg(h) && valid_seg(p) && valid_seg(s) + } + + pub fn begin_load_products(&mut self) { + self.phase = PaywallPhase::LoadingProducts; + self.last_error = None; + } + + pub fn set_products(&mut self, products: Vec) -> Result<(), &'static str> { + let filtered: Vec = products + .into_iter() + .filter(|p| Self::is_known_product_id(&p.product_id)) + .collect(); + if filtered.is_empty() { + self.phase = PaywallPhase::Failed; + self.active_product_id = None; + self.verified_transaction_id = None; + self.last_error = Some("no allowlisted StoreKit products".to_string()); + return Err("no allowlisted StoreKit products"); + } + self.products = filtered; + if self.phase != PaywallPhase::Verified { + self.phase = PaywallPhase::Ready; + } + self.last_error = None; + Ok(()) + } + + pub fn begin_purchase(&mut self, product_id: &str) -> Result<(), &'static str> { + if !Self::is_known_product_id(product_id) { + return Err("unknown StoreKit product id"); + } + self.active_product_id = Some(product_id.to_string()); + self.phase = PaywallPhase::Purchasing; + self.last_error = None; + Ok(()) + } + + pub fn complete_verified_transaction( + &mut self, + product_id: &str, + transaction_id: &str, + jws_representation: &str, + ) -> Result<(), &'static str> { + if !Self::is_known_product_id(product_id) { + self.mark_failed("unknown StoreKit product id"); + return Err("unknown StoreKit product id"); + } + if transaction_id.trim().is_empty() { + self.mark_failed("empty transaction id"); + return Err("empty transaction id"); + } + if !Self::is_valid_jws_envelope(jws_representation) { + self.mark_failed("invalid JWS receipt envelope"); + return Err("invalid JWS receipt envelope"); + } + self.active_product_id = Some(product_id.to_string()); + self.verified_transaction_id = Some(transaction_id.to_string()); + self.phase = PaywallPhase::Verified; + self.last_error = None; + Ok(()) + } + + pub fn mark_pending(&mut self) { + self.verified_transaction_id = None; + self.phase = PaywallPhase::Pending; + } + + pub fn mark_cancelled(&mut self) { + self.verified_transaction_id = None; + self.active_product_id = None; + self.phase = PaywallPhase::Cancelled; + } + + pub fn mark_failed(&mut self, reason: &str) { + self.verified_transaction_id = None; + self.active_product_id = None; + self.phase = PaywallPhase::Failed; + self.last_error = Some(reason.to_string()); + } + + /// Clear all active entitlements (used when StoreKit 2 `currentEntitlements` is empty, + /// when cache decode fails, or when a verified transaction update reports revocation/expiration). + pub fn clear_entitlement(&mut self) { + self.verified_transaction_id = None; + self.active_product_id = None; + self.last_error = None; + self.phase = if self.products.is_empty() { + PaywallPhase::Idle + } else { + PaywallPhase::Ready + }; + } +} + +/// Onboarding + Native Sign-In (`ASAuthorizationController` / OAuth) state machine. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OnboardingStage { + Welcome, + SignInChoice, + Authenticating, + PendingExchange, + Completed, + Skipped, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OnboardingSignInState { + pub stage: OnboardingStage, + pub expected_oauth_state: Option, + pub authenticated_provider: Option, + /// One-time OAuth authorization code or Apple credential awaiting server session exchange. + pub pending_credential: Option, + /// Server-confirmed user subject, populated ONLY after `confirm_session_exchange` succeeds. + pub authenticated_subject: Option, + pub last_error: Option, +} + +impl Default for OnboardingSignInState { + fn default() -> Self { + Self { + stage: OnboardingStage::Welcome, + expected_oauth_state: None, + authenticated_provider: None, + pending_credential: None, + authenticated_subject: None, + last_error: None, + } + } +} + +impl OnboardingSignInState { + pub fn advance_to_sign_in(&mut self) { + self.stage = OnboardingStage::SignInChoice; + self.pending_credential = None; + self.last_error = None; + } + + pub fn skip_sign_in(&mut self) { + self.stage = OnboardingStage::Skipped; + self.expected_oauth_state = None; + self.pending_credential = None; + self.authenticated_subject = None; + self.last_error = None; + } + + pub fn begin_oauth(&mut self, csrf_state: &str) -> Result<(), &'static str> { + if csrf_state.trim().len() < 8 { + return Err("oauth state token too short"); + } + self.expected_oauth_state = Some(csrf_state.to_string()); + self.pending_credential = None; + self.authenticated_subject = None; + self.stage = OnboardingStage::Authenticating; + self.last_error = None; + Ok(()) + } + + /// Record a verified local Apple Sign-In credential and enter `PendingExchange` until the + /// AFFiNE server confirms the session subject. + pub fn receive_apple_credential( + &mut self, + user_identifier: &str, + identity_token_jws: &str, + ) -> Result<(), &'static str> { + if user_identifier.trim().is_empty() { + self.last_error = Some("empty apple user identifier".to_string()); + return Err("empty apple user identifier"); + } + if !PaywallStateMachine::is_valid_jws_envelope(identity_token_jws) { + self.last_error = Some("invalid apple identity token JWS".to_string()); + return Err("invalid apple identity token JWS"); + } + self.authenticated_provider = Some("apple".to_string()); + self.pending_credential = Some(user_identifier.to_string()); + self.authenticated_subject = None; + self.expected_oauth_state = None; + self.stage = OnboardingStage::PendingExchange; + self.last_error = None; + Ok(()) + } + + /// Validate CSRF `state` + non-empty authorization `code` and enter `PendingExchange` + /// without storing the one-time authorization code as `authenticated_subject`. + pub fn receive_oauth_callback(&mut self, code: &str, state: &str) -> Result<(), &'static str> { + let Some(expected) = self.expected_oauth_state.as_deref() else { + return Err("no pending oauth state"); + }; + if state != expected { + self.last_error = Some("oauth state mismatch".to_string()); + return Err("oauth state mismatch"); + } + if code.trim().is_empty() { + self.last_error = Some("empty oauth authorization code".to_string()); + return Err("empty oauth authorization code"); + } + self.authenticated_provider = Some("oauth".to_string()); + self.pending_credential = Some(code.to_string()); + self.authenticated_subject = None; + self.expected_oauth_state = None; + self.stage = OnboardingStage::PendingExchange; + self.last_error = None; + Ok(()) + } + + /// Finalize server code/token exchange with the confirmed user `subject`. + pub fn confirm_session_exchange(&mut self, subject: &str) -> Result<(), &'static str> { + if self.stage != OnboardingStage::PendingExchange || self.pending_credential.is_none() { + return Err("no pending credential exchange"); + } + let trimmed = subject.trim(); + if trimmed.is_empty() { + self.last_error = Some("empty confirmed subject".to_string()); + return Err("empty confirmed subject"); + } + self.pending_credential = None; + self.authenticated_subject = Some(trimmed.to_string()); + self.stage = OnboardingStage::Completed; + self.last_error = None; + Ok(()) + } + + /// Record a server code/token exchange failure and return to `SignInChoice` so the user can retry. + pub fn fail_session_exchange(&mut self, reason: &str) { + self.pending_credential = None; + self.authenticated_subject = None; + self.expected_oauth_state = None; + self.stage = OnboardingStage::SignInChoice; + self.last_error = Some(if reason.trim().is_empty() { + "session exchange failed".to_string() + } else { + reason.to_string() + }); + } +} + +/// Combined narrow-bridge state for the iOS native islands. +#[derive(Debug, Default)] +pub struct IosNativeIslandsState { + pub paywall: PaywallStateMachine, + pub onboarding: OnboardingSignInState, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ios_native_islands_cover_paywall_invariants_and_two_step_onboarding_exchange() { + let mut islands = IosNativeIslandsState::default(); + + // 1. AffinePaywall 3-product allowlist, JWS validation, and clean failure state clearing. + assert!(!PaywallStateMachine::is_known_product_id( + "app.affine.pro.ai.Monthly" + )); + islands.paywall.begin_load_products(); + islands + .paywall + .set_products(vec![PaywallProduct { + product_id: "app.affine.pro.Monthly".into(), + display_name: "AFFiNE Pro Monthly".into(), + display_price: "$9.99".into(), + }]) + .expect("products"); + islands + .paywall + .begin_purchase("app.affine.pro.Monthly") + .expect("begin purchase"); + assert!( + islands + .paywall + .complete_verified_transaction("app.affine.pro.Monthly", "tx-1", "not-a-jws") + .is_err() + ); + assert_eq!(islands.paywall.phase, PaywallPhase::Failed); + assert!(islands.paywall.verified_transaction_id.is_none()); + assert!(islands.paywall.active_product_id.is_none()); + + islands + .paywall + .complete_verified_transaction( + "app.affine.pro.Monthly", + "tx-1", + "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", + ) + .expect("verified jws"); + assert_eq!(islands.paywall.phase, PaywallPhase::Verified); + + // Rejecting a subsequent unknown product must clear stale `verified_transaction_id`. + assert!( + islands + .paywall + .complete_verified_transaction( + "com.unknown.Item", + "tx-2", + "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", + ) + .is_err() + ); + assert_eq!(islands.paywall.phase, PaywallPhase::Failed); + assert!(islands.paywall.verified_transaction_id.is_none()); + assert!(islands.paywall.active_product_id.is_none()); + + islands.paywall.clear_entitlement(); + assert_eq!(islands.paywall.phase, PaywallPhase::Ready); + + // 2. Two-phase OAuth / Apple credential exchange: callback enters `PendingExchange` + // without populating `authenticated_subject`, covers exchange failure + retry + success. + islands.onboarding.advance_to_sign_in(); + islands + .onboarding + .begin_oauth("csrf-state-123456") + .expect("oauth begin"); + assert!( + islands + .onboarding + .receive_oauth_callback("auth-code-once", "wrong-state") + .is_err() + ); + islands + .onboarding + .receive_oauth_callback("auth-code-once", "csrf-state-123456") + .expect("oauth callback received"); + assert_eq!(islands.onboarding.stage, OnboardingStage::PendingExchange); + assert!(islands.onboarding.authenticated_subject.is_none()); + assert_eq!( + islands.onboarding.pending_credential.as_deref(), + Some("auth-code-once") + ); + + // Simulate server exchange failure -> returns to `SignInChoice` so retry works cleanly. + islands.onboarding.fail_session_exchange("invalid_grant"); + assert_eq!(islands.onboarding.stage, OnboardingStage::SignInChoice); + assert!(islands.onboarding.pending_credential.is_none()); + assert!(islands.onboarding.authenticated_subject.is_none()); + + // Retry via Apple Sign-In -> `PendingExchange` -> `confirm_session_exchange` -> `Completed`. + islands + .onboarding + .receive_apple_credential( + "001234.abcdef", + "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1MSJ9.c2ln", + ) + .expect("apple credential"); + assert_eq!(islands.onboarding.stage, OnboardingStage::PendingExchange); + assert!(islands.onboarding.authenticated_subject.is_none()); + islands + .onboarding + .confirm_session_exchange("usr_confirmed_42") + .expect("confirm session"); + assert_eq!(islands.onboarding.stage, OnboardingStage::Completed); + assert_eq!( + islands.onboarding.authenticated_subject.as_deref(), + Some("usr_confirmed_42") + ); + assert!(islands.onboarding.pending_credential.is_none()); + } +} diff --git a/packages/frontend/hosts/ios/src/pdf.rs b/packages/frontend/hosts/ios/src/pdf.rs new file mode 100644 index 0000000000..a6e6865b0f --- /dev/null +++ b/packages/frontend/hosts/ios/src/pdf.rs @@ -0,0 +1,221 @@ +//! Pure-Rust PDFKit bridge validation, render-budget planning, and C-ABI data types. +//! +//! Enforces strict document size, header, page-index, and pixel-budget limits before +//! delegating page rasterization to Apple's system `PDFKit` framework in Swift. + +/// Maximum accepted PDF payload size in bytes (128 MiB). +pub const MAX_PDF_DOCUMENT_BYTES: usize = 128 * 1024 * 1024; +/// Maximum single rasterized page edge length in pixels (4096 px). +pub const MAX_PDF_PAGE_DIMENSION_PX: u32 = 4096; +/// Maximum total pixels per rasterized page (4096 * 4096 = 16M pixels = 64 MiB RGBA8). +pub const MAX_PDF_PAGE_PIXELS: u64 = 16_777_216; +/// Number of leading bytes scanned for the `%PDF-` signature per ISO 32000-1. +const PDF_HEADER_SCAN_LIMIT: usize = 1024; + +/// C-ABI error codes shared between Rust validation and Swift `PdfRendererBridge`. +#[repr(u32)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffinePdfErrorCode { + #[default] + Ok = 0, + InvalidArgument = 1, + EmptyDocument = 2, + DocumentTooLarge = 3, + InvalidOrEncryptedPdf = 4, + PageOutOfRange = 5, + InvalidDimensions = 6, + PixelLimitExceeded = 7, + RenderFailed = 8, +} + +/// Original page box size in PDF points (`72 pt = 1 inch`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffinePdfPageSize { + pub width_pt: f32, + pub height_pt: f32, +} + +/// Validated RGBA8 rasterization plan returned to Swift `PdfRendererBridge`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AffinePdfRenderPlan { + pub target_width_px: u32, + pub target_height_px: u32, + pub byte_len: usize, + pub error: u32, +} + +/// Validate a raw PDF payload before passing it to `PDFKit`. +pub fn validate_pdf_bytes(bytes: &[u8]) -> Result<(), AffinePdfErrorCode> { + if bytes.is_empty() { + return Err(AffinePdfErrorCode::EmptyDocument); + } + if bytes.len() > MAX_PDF_DOCUMENT_BYTES { + return Err(AffinePdfErrorCode::DocumentTooLarge); + } + let scan_end = bytes.len().min(PDF_HEADER_SCAN_LIMIT); + let prefix = &bytes[..scan_end]; + if !prefix.windows(5).any(|w| w == b"%PDF-") { + return Err(AffinePdfErrorCode::InvalidOrEncryptedPdf); + } + Ok(()) +} + +/// Validate page bounds and pixel dimensions and compute the exact RGBA8 buffer length. +pub fn plan_pdf_page_render( + page_index: u32, + page_count: u32, + target_width_px: u32, + target_height_px: u32, +) -> AffinePdfRenderPlan { + if page_count == 0 || page_index >= page_count { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PageOutOfRange as u32, + }; + } + if target_width_px == 0 || target_height_px == 0 { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::InvalidDimensions as u32, + }; + } + if target_width_px > MAX_PDF_PAGE_DIMENSION_PX || target_height_px > MAX_PDF_PAGE_DIMENSION_PX { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + } + let pixels = u64::from(target_width_px) * u64::from(target_height_px); + if pixels > MAX_PDF_PAGE_PIXELS { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + } + let Some(byte_len) = (pixels as usize).checked_mul(4) else { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + }; + AffinePdfRenderPlan { + target_width_px, + target_height_px, + byte_len, + error: AffinePdfErrorCode::Ok as u32, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pdf_header_validation_table() { + let cases: [(&str, &[u8], Result<(), AffinePdfErrorCode>); 4] = [ + ("empty", b"", Err(AffinePdfErrorCode::EmptyDocument)), + ( + "not_pdf", + b"not a pdf", + Err(AffinePdfErrorCode::InvalidOrEncryptedPdf), + ), + ("valid_pdf_1_4", b"%PDF-1.4\n%%EOF\n", Ok(())), + ( + "valid_pdf_with_leading_junk", + b" \n%PDF-1.7\n%%EOF\n", + Ok(()), + ), + ]; + for (name, bytes, expected) in cases { + assert_eq!(validate_pdf_bytes(bytes), expected, "{name}"); + } + } + + #[test] + fn pdf_render_plan_table_enforces_page_bounds_and_oom_limits() { + struct Case { + name: &'static str, + page: u32, + count: u32, + w: u32, + h: u32, + expect_err: AffinePdfErrorCode, + expect_bytes: usize, + } + + let cases = [ + Case { + name: "valid_page_0", + page: 0, + count: 2, + w: 300, + h: 400, + expect_err: AffinePdfErrorCode::Ok, + expect_bytes: 300 * 400 * 4, + }, + Case { + name: "valid_max_4096_square", + page: 1, + count: 2, + w: 4096, + h: 4096, + expect_err: AffinePdfErrorCode::Ok, + expect_bytes: 4096 * 4096 * 4, + }, + Case { + name: "out_of_range_page", + page: 2, + count: 2, + w: 200, + h: 200, + expect_err: AffinePdfErrorCode::PageOutOfRange, + expect_bytes: 0, + }, + Case { + name: "zero_page_count", + page: 0, + count: 0, + w: 200, + h: 200, + expect_err: AffinePdfErrorCode::PageOutOfRange, + expect_bytes: 0, + }, + Case { + name: "zero_dimension", + page: 0, + count: 1, + w: 0, + h: 200, + expect_err: AffinePdfErrorCode::InvalidDimensions, + expect_bytes: 0, + }, + Case { + name: "exceeds_edge_cap", + page: 0, + count: 1, + w: 4097, + h: 100, + expect_err: AffinePdfErrorCode::PixelLimitExceeded, + expect_bytes: 0, + }, + ]; + + for c in cases { + let plan = plan_pdf_page_render(c.page, c.count, c.w, c.h); + assert_eq!(plan.error, c.expect_err as u32, "{}", c.name); + assert_eq!(plan.byte_len, c.expect_bytes, "{}", c.name); + } + } +} diff --git a/packages/frontend/hosts/ios/src/runtime_root.rs b/packages/frontend/hosts/ios/src/runtime_root.rs new file mode 100644 index 0000000000..c94058c0ed --- /dev/null +++ b/packages/frontend/hosts/ios/src/runtime_root.rs @@ -0,0 +1,92 @@ +//! Root view of the embedded window: a bare page editor or the mobile product shell. +//! +//! [`EditorView`] resolves the page editor that owns text input at call time, so +//! `UITextInput`, document positions, and selection actions reach the root editor, or the +//! shell's embedded editor while the shell shows a `Page` route. + +use std::rc::Rc; + +use affine_mobile::{InMemoryPlatformAccessibility, MobileRoute, MobileSheet, MobileShellView}; +use anyhow::Context as _; +use playground::PlaygroundView; +use ui::{AnyWindowHandle, App, AppContext, Context, Entity, Task, Window, WindowHandle}; + +use super::shell_workspace::ShellWorkspace; + +/// Root view type mounted in the embedded window. +#[derive(Clone, Copy)] +pub(crate) enum RuntimeRoot { + Editor(WindowHandle), + Shell(WindowHandle), +} + +impl RuntimeRoot { + pub(crate) fn window(self) -> AnyWindowHandle { + match self { + Self::Editor(handle) => handle.into(), + Self::Shell(handle) => handle.into(), + } + } + + pub(crate) fn shell(self) -> Option> { + match self { + Self::Editor(_) => None, + Self::Shell(handle) => Some(handle), + } + } + + /// The root editor, or the shell's embedded editor while the `Page` route is shown with + /// no sheet or drawer above it. + pub(crate) fn editor(self, cx: &App) -> Option> { + match self { + Self::Editor(handle) => handle.entity(cx).ok(), + Self::Shell(handle) => { + let shell = handle.read(cx).ok()?; + if !matches!(shell.state.route, MobileRoute::Page(_)) + || shell.state.active_sheet != MobileSheet::None + { + return None; + } + shell.page_editor().cloned() + } + } + } +} + +/// Handle to the page editor that owns text input, with the `WindowHandle` call shape. +#[derive(Clone, Copy)] +pub(crate) struct EditorView(pub(crate) RuntimeRoot); + +impl EditorView { + pub(crate) fn read_with( + self, + cx: &App, + read: impl FnOnce(&PlaygroundView, &App) -> R, + ) -> anyhow::Result { + let entity = self.0.editor(cx).context("no page editor is shown")?; + Ok(read(entity.read(cx), cx)) + } + + pub(crate) fn update( + self, + cx: &mut App, + update: impl FnOnce(&mut PlaygroundView, &mut Window, &mut Context) -> R, + ) -> anyhow::Result { + let entity = self.0.editor(cx).context("no page editor is shown")?; + cx.update_window(self.0.window(), |_, window, cx| { + entity.update(cx, |view, cx| update(view, window, cx)) + }) + } +} + +/// Host-side state of a mounted shell. +pub(crate) struct ShellHost { + pub(crate) a11y: InMemoryPlatformAccessibility, + pub(crate) workspace: Option, +} + +/// Local workspace behind the shell, and the task that commits its edits every second. +pub(crate) struct MountedWorkspace { + pub(crate) store: Rc, + pub(crate) _autosave: Task<()>, +} diff --git a/packages/frontend/hosts/ios/src/selection.rs b/packages/frontend/hosts/ios/src/selection.rs new file mode 100644 index 0000000000..843e84cad6 --- /dev/null +++ b/packages/frontend/hosts/ios/src/selection.rs @@ -0,0 +1,1252 @@ +use crate::{AffineUtf16Range, AffineWindowInsets}; + +/// C-ABI 2D point in logical points matching `AffinePoint` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffinePoint { + pub x: f32, + pub y: f32, +} + +/// C-ABI rectangle in logical points matching `AffineRect` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineRect { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +impl AffineRect { + pub fn sanitized(self) -> Self { + Self { + x: sanitize_f32(self.x), + y: sanitize_f32(self.y), + width: sanitize_f32(self.width).max(0.0), + height: sanitize_f32(self.height).max(0.0), + } + } + + pub fn right(self) -> f32 { + self.x + self.width + } + + pub fn bottom(self) -> f32 { + self.y + self.height + } +} + +/// Which teardrop handle is active or hit-tested (`0 = none, 1 = start, 2 = end`). +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffineSelectionHandleKind { + #[default] + None = 0, + Start = 1, + End = 2, +} + +impl AffineSelectionHandleKind { + pub fn from_u8(raw: u8) -> Self { + match raw { + 1 => Self::Start, + 2 => Self::End, + _ => Self::None, + } + } +} + +/// Writing direction for teardrop handle horizontal bias (`0 = LTR, 1 = RTL`). +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffineWritingDirection { + #[default] + Ltr = 0, + Rtl = 1, +} + +impl AffineWritingDirection { + pub fn from_u8(raw: u8) -> Self { + match raw { + 1 => Self::Rtl, + _ => Self::Ltr, + } + } +} + +/// Computed layout for one teardrop selection handle. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineTeardropHandleLayout { + pub visible: bool, + pub drop_above: bool, + pub stem_x: f32, + pub stem_top_y: f32, + pub stem_bottom_y: f32, + pub stem_width: f32, + pub drop_center_x: f32, + pub drop_center_y: f32, + pub drop_radius: f32, + pub drop_offset_x: f32, +} + +/// Computed layout for the circular magnifier loupe shown during handle drags. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineLoupeLayout { + pub visible: bool, + pub center_x: f32, + pub center_y: f32, + pub focus_x: f32, + pub focus_y: f32, + pub diameter: f32, + pub zoom_scale: f32, +} + +/// Full deterministic selection overlay snapshot consumed by Swift `SelectionOverlayView`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineSelectionOverlayState { + pub has_selection: bool, + pub is_collapsed: bool, + pub is_rtl: bool, + pub active_drag_handle: u8, + pub show_floating_menu: bool, + pub range: AffineUtf16Range, + pub drag_probe_point: AffinePoint, + pub start_handle: AffineTeardropHandleLayout, + pub end_handle: AffineTeardropHandleLayout, + pub loupe: AffineLoupeLayout, + pub menu_anchor_rect: AffineRect, +} + +/// Deterministic selection handle geometry and drag state machine. +#[derive(Debug, Clone, Default)] +pub struct SelectionOverlayController { + has_selection: bool, + range: AffineUtf16Range, + writing_direction: AffineWritingDirection, + start_caret: AffineRect, + end_caret: AffineRect, + active_drag: AffineSelectionHandleKind, + drag_anchor_utf16: Option, + drag_touch_point: AffinePoint, + grab_offset: AffinePoint, +} + +impl SelectionOverlayController { + pub const STEM_WIDTH_PT: f32 = 2.0; + pub const DROP_RADIUS_PT: f32 = 6.0; + pub const DROP_BIAS_PT: f32 = 3.0; + pub const LOUPE_DIAMETER_PT: f32 = 88.0; + pub const LOUPE_ZOOM_SCALE: f32 = 1.5; + pub const LOUPE_VERTICAL_OFFSET_PT: f32 = 68.0; + pub const MIN_TOUCH_HIT_RADIUS_PT: f32 = 22.0; + pub const VIEWPORT_MARGIN_PT: f32 = 4.0; + + pub fn set_selection( + &mut self, + start_caret: AffineRect, + end_caret: AffineRect, + range: AffineUtf16Range, + writing_direction: AffineWritingDirection, + ) { + self.has_selection = true; + self.range = range; + self.writing_direction = writing_direction; + self.start_caret = start_caret.sanitized(); + self.end_caret = end_caret.sanitized(); + if range.length == 0 { + self.active_drag = AffineSelectionHandleKind::None; + } + } + + pub fn clear(&mut self) { + self.has_selection = false; + self.range = AffineUtf16Range::default(); + self.start_caret = AffineRect::default(); + self.end_caret = AffineRect::default(); + self.active_drag = AffineSelectionHandleKind::None; + self.drag_anchor_utf16 = None; + self.drag_touch_point = AffinePoint::default(); + self.grab_offset = AffinePoint::default(); + } + + pub fn active_drag_handle(&self) -> AffineSelectionHandleKind { + self.active_drag + } + + pub fn drag_anchor_utf16(&self) -> Option { + self.drag_anchor_utf16 + } + + pub fn hit_test_handle( + &self, + point: AffinePoint, + hit_radius_pt: f32, + viewport_w: f32, + viewport_h: f32, + insets: AffineWindowInsets, + ) -> AffineSelectionHandleKind { + let state = self.layout(viewport_w, viewport_h, insets); + if !state.has_selection || state.is_collapsed { + return AffineSelectionHandleKind::None; + } + let radius = sanitize_f32(hit_radius_pt).max(Self::MIN_TOUCH_HIT_RADIUS_PT); + let px = sanitize_f32(point.x); + let py = sanitize_f32(point.y); + let d_start = distance_to_handle(px, py, state.start_handle); + let d_end = distance_to_handle(px, py, state.end_handle); + + match (d_start <= radius, d_end <= radius) { + (true, true) => { + if d_start <= d_end { + AffineSelectionHandleKind::Start + } else { + AffineSelectionHandleKind::End + } + } + (true, false) => AffineSelectionHandleKind::Start, + (false, true) => AffineSelectionHandleKind::End, + (false, false) => AffineSelectionHandleKind::None, + } + } + + pub fn begin_drag( + &mut self, + handle: AffineSelectionHandleKind, + touch_point: AffinePoint, + ) -> bool { + if !self.has_selection || self.range.length == 0 { + return false; + } + let active_caret = match handle { + AffineSelectionHandleKind::Start => self.start_caret, + AffineSelectionHandleKind::End => self.end_caret, + AffineSelectionHandleKind::None => return false, + }; + let tx = sanitize_f32(touch_point.x); + let ty = sanitize_f32(touch_point.y); + let caret_ref_x = active_caret.x + active_caret.width * 0.5; + let caret_ref_y = active_caret.y + active_caret.height * 0.5; + self.active_drag = handle; + self.drag_anchor_utf16 = Some(match handle { + AffineSelectionHandleKind::Start => { + self.range.location.saturating_add(self.range.length) + } + AffineSelectionHandleKind::End => self.range.location, + AffineSelectionHandleKind::None => return false, + }); + self.drag_touch_point = AffinePoint { x: tx, y: ty }; + self.grab_offset = AffinePoint { + x: caret_ref_x - tx, + y: caret_ref_y - ty, + }; + true + } + + /// Compute the caret-aligned probe point (`touch + grab_offset`) for an active drag, + /// ensuring a 0pt move on the teardrop center causes zero vertical or horizontal line jump. + pub fn drag_probe_point_for(&self, touch_point: AffinePoint) -> AffinePoint { + let tx = sanitize_f32(touch_point.x); + let ty = sanitize_f32(touch_point.y); + if self.active_drag == AffineSelectionHandleKind::None { + return AffinePoint { x: tx, y: ty }; + } + AffinePoint { + x: sanitize_f32(tx + self.grab_offset.x), + y: sanitize_f32(ty + self.grab_offset.y), + } + } + + /// Update an in-progress drag from authoritative UTF-16 anchor/target offsets and + /// caller-supplied shaped start/end caret rects, without guessing crossover from + /// 2D caret coordinates (safe for mixed BiDi runs and vertical finger drift). + pub fn apply_text_drag_endpoints( + &mut self, + touch_point: AffinePoint, + target_offset: u32, + start_caret: AffineRect, + end_caret: AffineRect, + ) -> bool { + if self.active_drag == AffineSelectionHandleKind::None { + return false; + } + let anchor = self + .drag_anchor_utf16 + .unwrap_or_else(|| match self.active_drag { + AffineSelectionHandleKind::Start => { + self.range.location.saturating_add(self.range.length) + } + AffineSelectionHandleKind::End => self.range.location, + AffineSelectionHandleKind::None => 0, + }); + self.drag_touch_point = AffinePoint { + x: sanitize_f32(touch_point.x), + y: sanitize_f32(touch_point.y), + }; + let new_start = anchor.min(target_offset); + let new_end = anchor.max(target_offset); + self.range = AffineUtf16Range { + location: new_start, + length: new_end.saturating_sub(new_start), + }; + self.start_caret = start_caret.sanitized(); + self.end_caret = end_caret.sanitized(); + if target_offset < anchor { + self.active_drag = AffineSelectionHandleKind::Start; + } else if target_offset > anchor { + self.active_drag = AffineSelectionHandleKind::End; + } + true + } + + pub fn end_drag(&mut self) -> bool { + if self.active_drag == AffineSelectionHandleKind::None { + return false; + } + self.active_drag = AffineSelectionHandleKind::None; + self.drag_anchor_utf16 = None; + self.grab_offset = AffinePoint::default(); + if self.range.length == 0 { + self.clear(); + } + true + } + + pub fn layout( + &self, + viewport_w: f32, + viewport_h: f32, + insets: AffineWindowInsets, + ) -> AffineSelectionOverlayState { + let vw = sanitize_f32(viewport_w).max(0.0); + let vh = sanitize_f32(viewport_h).max(0.0); + let safe_left = sanitize_f32(insets.safe_left).max(0.0).min(vw); + let safe_right = sanitize_f32(insets.safe_right).max(0.0).min(vw); + let safe_top = sanitize_f32(insets.safe_top).max(0.0).min(vh); + let bottom_inset = sanitize_f32(insets.safe_bottom) + .max(0.0) + .max(sanitize_f32(insets.ime_bottom).max(0.0)) + .min(vh); + + let min_x = safe_left; + let max_x = (vw - safe_right).max(min_x); + let min_y = safe_top; + let max_y = (vh - bottom_inset).max(min_y); + + let is_collapsed = !self.has_selection || self.range.length == 0; + let is_rtl = self.writing_direction == AffineWritingDirection::Rtl; + let drag_probe_point = if self.active_drag != AffineSelectionHandleKind::None { + self.drag_probe_point_for(self.drag_touch_point) + } else { + AffinePoint::default() + }; + let loupe = if self.active_drag != AffineSelectionHandleKind::None { + build_loupe(drag_probe_point, min_x, max_x, min_y, max_y) + } else { + AffineLoupeLayout::default() + }; + + if !self.has_selection || is_collapsed { + let start_handle = if self.has_selection + && self.active_drag == AffineSelectionHandleKind::Start + { + build_teardrop_handle(self.start_caret, true, is_rtl, min_x, max_x, min_y, max_y) + } else { + AffineTeardropHandleLayout::default() + }; + let end_handle = + if self.has_selection && self.active_drag == AffineSelectionHandleKind::End { + build_teardrop_handle(self.end_caret, false, is_rtl, min_x, max_x, min_y, max_y) + } else { + AffineTeardropHandleLayout::default() + }; + return AffineSelectionOverlayState { + has_selection: self.has_selection, + is_collapsed: true, + is_rtl, + active_drag_handle: self.active_drag as u8, + show_floating_menu: false, + range: self.range, + drag_probe_point, + start_handle, + end_handle, + loupe, + menu_anchor_rect: AffineRect::default(), + }; + } + + let start_handle = + build_teardrop_handle(self.start_caret, true, is_rtl, min_x, max_x, min_y, max_y); + let end_handle = + build_teardrop_handle(self.end_caret, false, is_rtl, min_x, max_x, min_y, max_y); + + let sel_top = self.start_caret.y.min(self.end_caret.y); + let sel_bottom = self + .start_caret + .bottom() + .max(self.end_caret.bottom()) + .max(sel_top + 1.0); + let selection_visible = sel_bottom > min_y && sel_top < max_y; + let show_floating_menu = self.active_drag == AffineSelectionHandleKind::None + && (start_handle.visible || end_handle.visible || selection_visible); + let menu_anchor_rect = if show_floating_menu { + build_menu_anchor_rect(self.start_caret, self.end_caret, min_x, max_x, min_y, max_y) + } else { + AffineRect::default() + }; + + AffineSelectionOverlayState { + has_selection: true, + is_collapsed: false, + is_rtl, + active_drag_handle: self.active_drag as u8, + show_floating_menu, + range: self.range, + drag_probe_point, + start_handle, + end_handle, + loupe, + menu_anchor_rect, + } + } +} + +fn build_teardrop_handle( + caret: AffineRect, + is_start: bool, + is_rtl: bool, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineTeardropHandleLayout { + let caret_bottom = caret.bottom().max(caret.y + 1.0); + let in_x = caret.x >= min_x && caret.x <= max_x; + let in_y = caret_bottom >= min_y && caret.y <= max_y; + if !in_x || !in_y { + return AffineTeardropHandleLayout::default(); + } + + let r = SelectionOverlayController::DROP_RADIUS_PT; + let bias = SelectionOverlayController::DROP_BIAS_PT; + let stem_x = clamp_safe(caret.x, min_x, max_x); + let stem_top_y = clamp_safe(caret.y, min_y, max_y); + let stem_bottom_y = clamp_safe(caret_bottom, stem_top_y, max_y); + + // Start handle: teardrop above stem, biased left in LTR and right in RTL. + // End handle: teardrop below stem, biased right in LTR and left in RTL. + let drop_offset_x = match (is_start, is_rtl) { + (true, false) | (false, true) => -bias, + (true, true) | (false, false) => bias, + }; + + let drop_x_min = min_x + r; + let drop_x_max = max_x - r; + let drop_center_x = if drop_x_min <= drop_x_max { + clamp_safe(stem_x + drop_offset_x, drop_x_min, drop_x_max) + } else { + (min_x + max_x) * 0.5 + }; + + let raw_drop_y = if is_start { + stem_top_y - r + } else { + stem_bottom_y + r + }; + let drop_y_min = min_y + r; + let drop_y_max = max_y - r; + let drop_center_y = if drop_y_min <= drop_y_max { + clamp_safe(raw_drop_y, drop_y_min, drop_y_max) + } else { + (min_y + max_y) * 0.5 + }; + + AffineTeardropHandleLayout { + visible: true, + drop_above: is_start, + stem_x, + stem_top_y, + stem_bottom_y, + stem_width: SelectionOverlayController::STEM_WIDTH_PT, + drop_center_x, + drop_center_y, + drop_radius: r, + drop_offset_x, + } +} + +fn build_loupe( + touch: AffinePoint, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineLoupeLayout { + let diameter = SelectionOverlayController::LOUPE_DIAMETER_PT; + let radius = diameter * 0.5; + let margin = SelectionOverlayController::VIEWPORT_MARGIN_PT; + let focus_x = clamp_safe(touch.x, min_x, max_x); + let focus_y = clamp_safe(touch.y, min_y, max_y); + + let cx_min = min_x + radius + margin; + let cx_max = max_x - radius - margin; + let center_x = if cx_min <= cx_max { + clamp_safe(focus_x, cx_min, cx_max) + } else { + (min_x + max_x) * 0.5 + }; + + let cy_min = min_y + radius + margin; + let cy_max = max_y - radius - margin; + let preferred_y = focus_y - SelectionOverlayController::LOUPE_VERTICAL_OFFSET_PT; + let center_y = if cy_min <= cy_max { + clamp_safe(preferred_y, cy_min, cy_max) + } else { + (min_y + max_y) * 0.5 + }; + + AffineLoupeLayout { + visible: true, + center_x, + center_y, + focus_x, + focus_y, + diameter, + zoom_scale: SelectionOverlayController::LOUPE_ZOOM_SCALE, + } +} + +fn build_menu_anchor_rect( + start_caret: AffineRect, + end_caret: AffineRect, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineRect { + let left = clamp_safe(start_caret.x.min(end_caret.x), min_x, max_x); + let right = clamp_safe(start_caret.right().max(end_caret.right()), left, max_x); + let top = clamp_safe(start_caret.y.min(end_caret.y), min_y, max_y); + let bottom = clamp_safe(start_caret.bottom().max(end_caret.bottom()), top, max_y); + AffineRect { + x: left, + y: top, + width: (right - left).max(1.0), + height: (bottom - top).max(1.0), + } +} + +fn distance_to_handle(px: f32, py: f32, handle: AffineTeardropHandleLayout) -> f32 { + if !handle.visible { + return f32::INFINITY; + } + let d_drop = hypot(px - handle.drop_center_x, py - handle.drop_center_y); + let clamped_y = clamp_safe(py, handle.stem_top_y, handle.stem_bottom_y); + let d_stem = hypot(px - handle.stem_x, py - clamped_y); + d_drop.min(d_stem) +} + +fn hypot(dx: f32, dy: f32) -> f32 { + (dx * dx + dy * dy).sqrt() +} + +fn clamp_safe(value: f32, min: f32, max: f32) -> f32 { + let v = sanitize_f32(value); + if min <= max { v.clamp(min, max) } else { min } +} + +fn sanitize_f32(v: f32) -> f32 { + if v.is_finite() { v } else { 0.0 } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn standard_insets() -> AffineWindowInsets { + AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 0.0, + } + } + + #[test] + fn teardrop_geometry_table_covers_ltr_rtl_collapsed_multiline_and_narrow_clamp() { + struct Case { + name: &'static str, + start: AffineRect, + end: AffineRect, + range: AffineUtf16Range, + dir: AffineWritingDirection, + vw: f32, + vh: f32, + expect_visible: bool, + expect_start_offset_sign: f32, + expect_end_offset_sign: f32, + } + + let cases = [ + Case { + name: "ltr_single_line", + start: AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 0, + length: 10, + }, + dir: AffineWritingDirection::Ltr, + vw: 390.0, + vh: 844.0, + expect_visible: true, + expect_start_offset_sign: -1.0, + expect_end_offset_sign: 1.0, + }, + Case { + name: "rtl_flips_teardrop_bias", + start: AffineRect { + x: 280.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 110.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 2, + length: 8, + }, + dir: AffineWritingDirection::Rtl, + vw: 390.0, + vh: 844.0, + expect_visible: true, + expect_start_offset_sign: 1.0, + expect_end_offset_sign: -1.0, + }, + Case { + name: "collapsed_caret_hides_handles", + start: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 4, + length: 0, + }, + dir: AffineWritingDirection::Ltr, + vw: 390.0, + vh: 844.0, + expect_visible: false, + expect_start_offset_sign: 0.0, + expect_end_offset_sign: 0.0, + }, + Case { + name: "multiline_and_narrow_viewport_clamps_handles_inside_bounds", + start: AffineRect { + x: 1.0, + y: 60.0, + width: 2.0, + height: 22.0, + }, + end: AffineRect { + x: 319.0, + y: 420.0, + width: 2.0, + height: 22.0, + }, + range: AffineUtf16Range { + location: 0, + length: 64, + }, + dir: AffineWritingDirection::Ltr, + vw: 320.0, + vh: 568.0, + expect_visible: true, + expect_start_offset_sign: -1.0, + expect_end_offset_sign: 1.0, + }, + ]; + + for c in cases { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection(c.start, c.end, c.range, c.dir); + let layout = ctrl.layout(c.vw, c.vh, standard_insets()); + assert_eq!(layout.start_handle.visible, c.expect_visible, "{}", c.name); + assert_eq!(layout.end_handle.visible, c.expect_visible, "{}", c.name); + assert_eq!(layout.show_floating_menu, c.expect_visible, "{}", c.name); + if c.expect_visible { + assert!(layout.start_handle.drop_above, "{}", c.name); + assert!(!layout.end_handle.drop_above, "{}", c.name); + assert_eq!( + layout.start_handle.drop_offset_x.signum(), + c.expect_start_offset_sign, + "{}", + c.name + ); + assert_eq!( + layout.end_handle.drop_offset_x.signum(), + c.expect_end_offset_sign, + "{}", + c.name + ); + assert!( + layout.start_handle.drop_center_x >= SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!( + layout.end_handle.drop_center_x + <= c.vw - SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!( + layout.start_handle.drop_center_y + >= 59.0 + SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!(layout.menu_anchor_rect.width >= 1.0, "{}", c.name); + assert!(layout.menu_anchor_rect.height >= 20.0, "{}", c.name); + } + } + } + + #[test] + fn drag_lifecycle_activates_clamped_loupe_swaps_crossed_handles_and_restores_menu() { + let mut ctrl = SelectionOverlayController::default(); + let insets = standard_insets(); + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 12, + }, + AffineWritingDirection::Ltr, + ); + + let hit = ctrl.hit_test_handle( + AffinePoint { x: 77.0, y: 114.0 }, + 22.0, + 390.0, + 844.0, + insets, + ); + assert_eq!(hit, AffineSelectionHandleKind::Start); + assert!(ctrl.begin_drag(hit, AffinePoint { x: 10.0, y: 70.0 })); + + let dragging = ctrl.layout(390.0, 844.0, insets); + assert!(dragging.loupe.visible); + assert!(!dragging.show_floating_menu); + assert_eq!( + dragging.loupe.zoom_scale, + SelectionOverlayController::LOUPE_ZOOM_SCALE + ); + // Loupe must clamp away from left and top safe edges. + let min_cx = SelectionOverlayController::LOUPE_DIAMETER_PT * 0.5 + + SelectionOverlayController::VIEWPORT_MARGIN_PT; + let min_cy = 59.0 + + SelectionOverlayController::LOUPE_DIAMETER_PT * 0.5 + + SelectionOverlayController::VIEWPORT_MARGIN_PT; + assert!(dragging.loupe.center_x >= min_cx); + assert!(dragging.loupe.center_y >= min_cy); + + // Drag start handle past end handle: authoritative UTF-16 anchor updates range and flips active drag to End. + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 260.0, y: 125.0 }, + 18, + AffineRect { + x: 200.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 260.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + + // Release handle: loupe closes and floating menu anchor appears. + assert!(ctrl.end_drag()); + let settled = ctrl.layout(390.0, 844.0, insets); + assert!(!settled.loupe.visible); + assert!(settled.show_floating_menu); + assert_eq!(settled.menu_anchor_rect.x, 200.0); + assert_eq!(settled.menu_anchor_rect.width, 62.0); + } + + #[test] + fn grab_offset_prevents_zero_pt_drag_line_jump_and_offscreen_handles_hide() { + let mut ctrl = SelectionOverlayController::default(); + let insets = standard_insets(); + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 12, + }, + AffineWritingDirection::Ltr, + ); + let initial = ctrl.layout(390.0, 844.0, insets); + let drop_center = AffinePoint { + x: initial.end_handle.drop_center_x, + y: initial.end_handle.drop_center_y, + }; + assert!(ctrl.begin_drag(AffineSelectionHandleKind::End, drop_center)); + // 0pt move on teardrop center must probe exact caret midpoint (201.0, 210.0), not drop_center_y (226.0). + let probe = ctrl.drag_probe_point_for(drop_center); + assert_eq!(probe.x, 201.0); + assert_eq!(probe.y, 210.0); + let state = ctrl.layout(390.0, 844.0, insets); + assert_eq!(state.drag_probe_point, probe); + + // Offscreen carets (above safe_top or below keyboard) must hide their handles. + let kb_insets = AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 302.0, + }; + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 10.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 620.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 20, + }, + AffineWritingDirection::Ltr, + ); + let offscreen = ctrl.layout(390.0, 844.0, kb_insets); + assert!(!offscreen.start_handle.visible); + assert!(!offscreen.end_handle.visible); + } + + #[test] + fn crossover_table_swaps_active_drag_and_preserves_anchor_for_ltr_rtl_and_multiline() { + struct Case { + name: &'static str, + dir: AffineWritingDirection, + start: AffineRect, + end: AffineRect, + drag: AffineSelectionHandleKind, + target: AffineRect, + expect_active_after: AffineSelectionHandleKind, + expect_start_x: f32, + expect_start_y: f32, + expect_end_x: f32, + expect_end_y: f32, + } + + let cases = [ + Case { + name: "ltr_same_line_start_crosses_end", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 180.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::Start, + target: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::End, + expect_start_x: 180.0, + expect_start_y: 200.0, + expect_end_x: 240.0, + expect_end_y: 200.0, + }, + Case { + name: "ltr_same_line_end_crosses_before_start", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 220.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 60.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 60.0, + expect_start_y: 200.0, + expect_end_x: 120.0, + expect_end_y: 200.0, + }, + Case { + name: "rtl_same_line_end_crosses_before_start", + dir: AffineWritingDirection::Rtl, + start: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 300.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 300.0, + expect_start_y: 200.0, + expect_end_x: 240.0, + expect_end_y: 200.0, + }, + Case { + name: "multiline_end_crosses_above_start", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 100.0, + y: 240.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 200.0, + y: 280.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 150.0, + y: 180.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 150.0, + expect_start_y: 180.0, + expect_end_x: 100.0, + expect_end_y: 240.0, + }, + ]; + + let insets = standard_insets(); + for c in cases { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection( + c.start, + c.end, + AffineUtf16Range { + location: 2, + length: 8, + }, + c.dir, + ); + assert!( + ctrl.begin_drag(c.drag, AffinePoint { x: 100.0, y: 200.0 }), + "{}", + c.name + ); + // Authoritative UTF-16 target offset crosses past the fixed anchor (2 or 10). + let target_offset = match c.expect_active_after { + AffineSelectionHandleKind::End => 12, + AffineSelectionHandleKind::Start => 1, + AffineSelectionHandleKind::None => 2, + }; + let new_start = AffineRect { + x: c.expect_start_x, + y: c.expect_start_y, + width: 2.0, + height: 20.0, + }; + let new_end = AffineRect { + x: c.expect_end_x, + y: c.expect_end_y, + width: 2.0, + height: 20.0, + }; + assert!( + ctrl.apply_text_drag_endpoints( + AffinePoint { + x: c.target.x, + y: c.target.y, + }, + target_offset, + new_start, + new_end, + ), + "{}", + c.name + ); + assert_eq!( + ctrl.active_drag_handle(), + c.expect_active_after, + "{}", + c.name + ); + let layout = ctrl.layout(390.0, 844.0, insets); + assert_eq!(layout.start_handle.stem_x, c.expect_start_x, "{}", c.name); + assert_eq!( + layout.start_handle.stem_top_y, c.expect_start_y, + "{}", + c.name + ); + assert_eq!(layout.end_handle.stem_x, c.expect_end_x, "{}", c.name); + assert_eq!(layout.end_handle.stem_top_y, c.expect_end_y, "{}", c.name); + } + } + + #[test] + fn keyboard_occlusion_hides_handles_and_menu_then_restores_on_dismiss() { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection( + AffineRect { + x: 40.0, + y: 710.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 180.0, + y: 710.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 10, + length: 8, + }, + AffineWritingDirection::Ltr, + ); + + let no_kb = standard_insets(); + let before = ctrl.layout(390.0, 844.0, no_kb); + assert!(before.start_handle.visible && before.end_handle.visible); + assert!(before.show_floating_menu); + + let with_kb = AffineWindowInsets { + ime_bottom: 302.0, + ..no_kb + }; + let occluded = ctrl.layout(390.0, 844.0, with_kb); + assert!(!occluded.start_handle.visible && !occluded.end_handle.visible); + assert!(!occluded.show_floating_menu); + assert!(occluded.has_selection); + assert_eq!(occluded.range.location, 10); + assert_eq!(occluded.range.length, 8); + + let restored = ctrl.layout(390.0, 844.0, no_kb); + assert!(restored.start_handle.visible && restored.end_handle.visible); + assert!(restored.show_floating_menu); + } + + #[test] + fn apply_text_drag_endpoints_handles_bidi_crossover_zero_length_and_vertical_drift() { + let mut ctrl = SelectionOverlayController::default(); + let start_c = AffineRect { + x: 180.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + let end_c = AffineRect { + x: 120.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + // Mixed BiDi: LTR doc with RTL substring where start_caret.x > end_caret.x. + ctrl.set_selection( + start_c, + end_c, + AffineUtf16Range { + location: 6, + length: 5, + }, + AffineWritingDirection::Ltr, + ); + assert!(ctrl.begin_drag( + AffineSelectionHandleKind::End, + AffinePoint { x: 120.0, y: 148.0 } + )); + assert_eq!(ctrl.drag_anchor_utf16(), Some(6)); + + // 1. Mixed BiDi coordinates (start.x > end.x under LTR) + +50pt vertical finger drift + // must NOT flip active_drag or swap start/end carets. + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 140.0, y: 198.0 }, + 9, + start_c, + AffineRect { + x: 140.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + let st = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st.range, + AffineUtf16Range { + location: 6, + length: 3 + } + ); + + // 2. Crossing through length == 0 (target == anchor == 6) keeps dragged handle visible, + // then crossing to 3 flips active_drag to Start, and dragging back to 8 flips back to End. + let at_anchor = AffineRect { + x: 180.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 180.0, y: 148.0 }, + 6, + at_anchor, + at_anchor, + )); + let st_zero = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_zero.active_drag_handle, + AffineSelectionHandleKind::End as u8 + ); + assert!( + st_zero.end_handle.visible, + "dragged handle stays visible at length == 0" + ); + + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 210.0, y: 148.0 }, + 3, + AffineRect { + x: 210.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + at_anchor, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::Start); + let st_cross = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_cross.range, + AffineUtf16Range { + location: 3, + length: 3 + } + ); + + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 150.0, y: 148.0 }, + 8, + at_anchor, + AffineRect { + x: 150.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + let st_back = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_back.range, + AffineUtf16Range { + location: 6, + length: 2 + } + ); + + assert!(ctrl.end_drag()); + assert_eq!(ctrl.drag_anchor_utf16(), None); + } +} diff --git a/packages/frontend/hosts/ios/src/share_ingest.rs b/packages/frontend/hosts/ios/src/share_ingest.rs new file mode 100644 index 0000000000..8cef2339d3 --- /dev/null +++ b/packages/frontend/hosts/ios/src/share_ingest.rs @@ -0,0 +1,435 @@ +//! Thin iOS adapter over [`affine_store::share_ingest`] for `ShareExtensionBridge`. +//! +//! Delegates all validation, SHA-256 content-addressed blob persistence, `0.27.5` +//! `affine:share-import-receipt-v1` & `hasValidSharePlan` idempotency, and `tagIds` / +//! `collectionId` root metadata updates to the single canonical store-domain implementation. + +pub use affine_store::share_ingest::{ + IOS_APP_GROUP_ID, MAX_SHARE_ATTACHMENT_BYTES, SHARE_IMPORT_RECEIPT_PROPERTY_ID, + ShareIngestAttachmentSpec, ShareIngestOutcome, ShareIngestRequest, SharePayloadKind, + ingest_share_item_into_sqlite, sha256_base64url, +}; + +use crate::workspace_store::{IosWorkspaceHandle, WorkspaceStoreError}; + +impl IosWorkspaceHandle { + /// Read a non-deleted attachment blob by key from the workspace SQLite `blobs` table. + pub fn read_blob(&self, key: &str) -> Result>, WorkspaceStoreError> { + let record = self.runtime.block_on(self.storage.get_blob(key))?; + Ok(record.map(|r| r.data)) + } + + /// Atomically ingest one ShareExtension item into SQLite (`blobs` + `updates` + `clocks` + + /// `db$docProperties` + `share_ingest_receipts`) inside a single `BEGIN IMMEDIATE ... COMMIT` + /// transaction via [`affine_store::share_ingest::ingest_share_item_into_sqlite`]. + pub fn ingest_share_item( + &self, + req: &ShareIngestRequest, + blob_bytes: &[u8], + ) -> Result { + if self.storage.is_closed() { + return Err(WorkspaceStoreError::Database( + "workspace storage is closed".into(), + )); + } + let db_path = self.db_path.clone(); + let workspace_id = self.space_id.clone(); + self.runtime + .block_on(ingest_share_item_into_sqlite( + &db_path, + &workspace_id, + req, + blob_bytes, + )) + .map_err(WorkspaceStoreError::from) + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use affine_store::workspace_db::{WorkspaceDb, WorkspaceDbTableName, WorkspaceRootDoc}; + use blocksuite_playground_doc::{ + read::BlockContent, schema::BlockSpec, session::PageDocSession, + }; + + use super::*; + + fn unique_temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "affine-ios-share-ingest-{label}-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn share_ingest_matches_0275_sha256_empty_title_pdf_style_image_size_tags_and_collections() { + let docs = unique_temp_dir("parity-0275"); + let allowlist = vec!["ws-share".to_string()]; + let ws = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist)) + .unwrap(); + + // Seed workspace root with tag "tag-rust" and collection "col-inbox" as 0.27.5 would. + { + let mut root = WorkspaceRootDoc::new("ws-share", 11); + if let Some(u) = root.initialize_meta().unwrap() { + ws.runtime + .block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_000)) + .unwrap(); + } + if let Some(u) = root + .define_tag("tag-rust", "Rust", "blue", 1_795_880_000_000) + .unwrap() + { + ws.runtime + .block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_001)) + .unwrap(); + } + if let Some(u) = root.define_collection("col-inbox", "Inbox").unwrap() { + ws.runtime + .block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_002)) + .unwrap(); + } + } + + // 1) PDF with tagIds + collectionId + SHA-256 content-addressed blob + style == "pdf". + let pdf_bytes = b"%PDF-1.4\n"; + let expected_pdf_key = sha256_base64url(pdf_bytes); + let pdf_req = ShareIngestRequest { + share_id: "item-pdf-1".into(), + import_attempt_id: "attempt-pdf-1".into(), + doc_id: "doc-pdf-1".into(), + kind: SharePayloadKind::Pdf, + title: "Spec PDF".into(), + text_or_url: String::new(), + secondary_text: String::new(), + tag_ids: vec!["tag-rust".into()], + collection_id: Some("col-inbox".into()), + attachments: vec![ShareIngestAttachmentSpec { + blob_key: String::new(), + file_name: "x.pdf".into(), + mime_type: "application/pdf".into(), + byte_offset: 0, + byte_len: pdf_bytes.len(), + }], + client_id: 0, + now_ms: 1_795_880_000_010, + }; + let pdf_out = ws.ingest_share_item(&pdf_req, pdf_bytes).unwrap(); + assert!(!pdf_out.already_committed); + assert_eq!(pdf_out.blob_keys, vec![expected_pdf_key.clone()]); + + // 2) Untitled URL share: empty title MUST remain `""` (never `doc-untitled-2`). + let url_req = ShareIngestRequest { + share_id: "item-url-2".into(), + import_attempt_id: "attempt-url-2".into(), + doc_id: "doc-untitled-2".into(), + kind: SharePayloadKind::Url, + title: String::new(), + text_or_url: "https://affine.pro".into(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: Vec::new(), + client_id: 0, + now_ms: 1_795_880_000_020, + }; + ws.ingest_share_item(&url_req, &[]).unwrap(); + + // 3) Image share: prop:size MUST equal exact byte count (12), not -1. + let img_bytes = b"\x89PNG\r\n\x1a\n1234"; + let expected_img_key = sha256_base64url(img_bytes); + let img_req = ShareIngestRequest { + share_id: "item-img-3".into(), + import_attempt_id: "attempt-img-3".into(), + doc_id: "doc-img-3".into(), + kind: SharePayloadKind::Image, + title: "Photo".into(), + text_or_url: String::new(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: vec![ShareIngestAttachmentSpec { + blob_key: String::new(), + file_name: "p.png".into(), + mime_type: "image/png".into(), + byte_offset: 0, + byte_len: img_bytes.len(), + }], + client_id: 0, + now_ms: 1_795_880_000_030, + }; + ws.ingest_share_item(&img_req, img_bytes).unwrap(); + + // Retry of item-pdf-1 hits share_ingest_receipts idempotently. + assert!( + ws.ingest_share_item(&pdf_req, pdf_bytes) + .unwrap() + .already_committed + ); + + ws.checkpoint().unwrap(); + ws.close(); + + // Reopen from disk and verify every invariant. + let reopened = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist)) + .unwrap(); + assert_eq!( + reopened.read_blob(&expected_pdf_key).unwrap().as_deref(), + Some(pdf_bytes.as_slice()) + ); + assert_eq!( + reopened.read_blob(&expected_img_key).unwrap().as_deref(), + Some(img_bytes.as_slice()) + ); + + let pdf_bin = reopened.read_doc_binary("doc-pdf-1").unwrap().unwrap(); + let pdf_json = { + let mut s = PageDocSession::new("doc-pdf-1", 42).unwrap(); + s.apply_remote_update_v1(&pdf_bin).unwrap(); + s.export_doc_json().unwrap() + }; + assert_eq!( + pdf_json["blocks"]["share-attempt-pdf-1-attachment"]["prop:style"], + "pdf" + ); + assert_eq!( + pdf_json["blocks"]["share-attempt-pdf-1-attachment"]["prop:embed"], + true + ); + + let img_bin = reopened.read_doc_binary("doc-img-3").unwrap().unwrap(); + let img_json = { + let mut s = PageDocSession::new("doc-img-3", 42).unwrap(); + s.apply_remote_update_v1(&img_bin).unwrap(); + s.export_doc_json().unwrap() + }; + assert_eq!( + img_json["blocks"]["share-attempt-img-3-image"]["prop:size"], + 12 + ); + + let untitled_bin = reopened.read_doc_binary("doc-untitled-2").unwrap().unwrap(); + let mut untitled_sess = PageDocSession::new("doc-untitled-2", 42).unwrap(); + untitled_sess.apply_remote_update_v1(&untitled_bin).unwrap(); + assert_eq!(untitled_sess.read_page_snapshot().unwrap().title(), ""); + + let root_bin = reopened.read_doc_binary("ws-share").unwrap().unwrap(); + let root = WorkspaceRootDoc::from_update_v1("ws-share", 99, &root_bin).unwrap(); + let pdf_meta = root.get_page("doc-pdf-1").unwrap().unwrap(); + assert_eq!(pdf_meta.tags, vec!["tag-rust".to_string()]); + assert_eq!( + root.collection_allow_list("col-inbox").unwrap(), + Some(vec!["doc-pdf-1".to_string()]) + ); + let untitled_meta = root.get_page("doc-untitled-2").unwrap().unwrap(); + assert_eq!(untitled_meta.title, ""); + + reopened.close(); + let _ = std::fs::remove_dir_all(&docs); + } + + #[test] + fn interrupted_0275_partial_blocks_are_reused_without_overwriting_or_duplicating_children() { + let docs = unique_temp_dir("interrupted-0275"); + let allowlist = vec!["ws-share".to_string()]; + let ws = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist)) + .unwrap(); + + // Simulate 0.27.5 having written `preparing` receipt + partial/full share blocks, + // plus a user/preview edit on the bookmark title, before crashing prior to `committed`. + { + let mut s = PageDocSession::new("doc-resume", 55).unwrap(); + s.add_block( + "share-att-resume-page", + BlockSpec::Page { + title: "Original".into(), + }, + None, + None, + 1, + ) + .unwrap(); + s.add_block( + "share-att-resume-surface", + BlockSpec::Surface, + Some("share-att-resume-page"), + None, + 2, + ) + .unwrap(); + s.add_block( + "share-att-resume-note", + BlockSpec::Note { + xywh: Some("[0,0,800,600]".into()), + }, + Some("share-att-resume-page"), + None, + 3, + ) + .unwrap(); + s.add_block( + "share-att-resume-bookmark", + BlockSpec::Bookmark { + url: "https://example.com/page".into(), + title: Some("Preview Fetched By 0.27.5".into()), + description: None, + }, + Some("share-att-resume-note"), + None, + 4, + ) + .unwrap(); + let bin = s.encode_update_v1().unwrap(); + ws.runtime + .block_on(ws.storage.push_update("doc-resume", bin, 1_795_880_000_000)) + .unwrap(); + + let mut db = WorkspaceDb::new("ws-share", "local", 55); + let mut row = serde_json::Map::new(); + row.insert("id".into(), "doc-resume".into()); + row.insert( + SHARE_IMPORT_RECEIPT_PROPERTY_ID.into(), + serde_json::json!({ + "version": 1, + "attemptId": "att-resume", + "state": "preparing" + }) + .to_string() + .into(), + ); + let dp_bin = db + .upsert_db_row(WorkspaceDbTableName::DocProperties, &row) + .unwrap(); + ws.runtime + .block_on(ws.storage.push_update( + &WorkspaceDbTableName::DocProperties.local_doc_id(), + dp_bin, + 1_795_880_000_001, + )) + .unwrap(); + } + + let req = ShareIngestRequest { + share_id: "share-resume-1".into(), + import_attempt_id: "att-resume".into(), + doc_id: "doc-resume".into(), + kind: SharePayloadKind::Url, + title: "Fallback Title".into(), + text_or_url: "https://example.com/page".into(), + secondary_text: "Missing quote leaf".into(), + tag_ids: Vec::new(), + collection_id: None, + attachments: Vec::new(), + client_id: 77, + now_ms: 1_795_880_000_100, + }; + let out = ws.ingest_share_item(&req, &[]).unwrap(); + assert!(!out.already_committed); + + let doc_bin = ws.read_doc_binary("doc-resume").unwrap().unwrap(); + let mut verify = PageDocSession::new("doc-resume", 88).unwrap(); + verify.apply_remote_update_v1(&doc_bin).unwrap(); + let snap = verify.read_page_snapshot().unwrap(); + let note = snap + .root + .as_ref() + .unwrap() + .children + .iter() + .find(|n| n.id == "share-att-resume-note") + .unwrap(); + let child_ids: Vec<&str> = note.children.iter().map(|c| c.id.as_str()).collect(); + assert_eq!( + child_ids, + vec![ + "share-att-resume-bookmark", + "share-att-resume-selected-text" + ], + "existing bookmark must not be duplicated in sys:children" + ); + match ¬e.children[0].content { + BlockContent::Bookmark { title, .. } => { + assert_eq!( + title.as_deref(), + Some("Preview Fetched By 0.27.5"), + "existing bookmark block must not be overwritten" + ); + } + other => panic!("expected Bookmark, got {other:?}"), + } + + // A different share item claiming a DIFFERENT attemptId on `doc-resume` must fail with conflict. + let conflict_req = ShareIngestRequest { + share_id: "share-conflict-2".into(), + import_attempt_id: "att-other".into(), + doc_id: "doc-resume".into(), + ..req + }; + assert!(ws.ingest_share_item(&conflict_req, &[]).is_err()); + + ws.close(); + let _ = std::fs::remove_dir_all(&docs); + } + + #[test] + fn corrupted_workspace_root_and_missing_destinations_abort_atomically() { + let docs = unique_temp_dir("corrupt-root"); + let allowlist = vec!["ws-share".to_string()]; + let ws = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist)) + .unwrap(); + + // Missing destination tag must fail before creating blob or doc. + let pdf_bytes = b"%PDF-1.4\n"; + let missing_tag_req = ShareIngestRequest { + share_id: "item-missing-tag".into(), + import_attempt_id: "att-missing-tag".into(), + doc_id: "doc-missing-tag".into(), + kind: SharePayloadKind::Pdf, + title: "Tagged".into(), + text_or_url: String::new(), + secondary_text: String::new(), + tag_ids: vec!["nonexistent-tag".into()], + collection_id: None, + attachments: vec![ShareIngestAttachmentSpec { + blob_key: String::new(), + file_name: "c.pdf".into(), + mime_type: "application/pdf".into(), + byte_offset: 0, + byte_len: pdf_bytes.len(), + }], + client_id: 7, + now_ms: 1_795_880_000_000, + }; + assert!(ws.ingest_share_item(&missing_tag_req, pdf_bytes).is_err()); + assert!( + ws.read_blob(&sha256_base64url(pdf_bytes)) + .unwrap() + .is_none() + ); + assert!(ws.read_doc_binary("doc-missing-tag").unwrap().is_none()); + + // Corrupted workspace root must also roll back atomically. + ws.runtime + .block_on( + ws.storage + .push_update("ws-share", [0xff_u8, 0xff, 0xff], 1_795_880_000_000), + ) + .unwrap(); + let mut plain_req = missing_tag_req; + plain_req.tag_ids.clear(); + assert!(ws.ingest_share_item(&plain_req, pdf_bytes).is_err()); + assert!(ws.read_doc_binary("doc-missing-tag").unwrap().is_none()); + + ws.close(); + let _ = std::fs::remove_dir_all(&docs); + } +} diff --git a/packages/frontend/hosts/ios/src/shell_runtime.rs b/packages/frontend/hosts/ios/src/shell_runtime.rs new file mode 100644 index 0000000000..83179f92e7 --- /dev/null +++ b/packages/frontend/hosts/ios/src/shell_runtime.rs @@ -0,0 +1,694 @@ +//! Mobile product shell mounted as the root view of [`IosEditorRuntime`]. +//! +//! The shell owns routes, sheets, Search input, and the embedded page editor. The runtime +//! routes text input to whichever of them has focus, runs the platform back action through +//! `MobileBackCoordinator`, and keeps one local SQLite workspace in step with the shell: it +//! loads each page when the shell opens it and commits edits every second. + +use std::{ + path::Path, + rc::Rc, + sync::{Arc, Mutex}, + time::Duration, +}; + +use affine_mobile::{ + BackOutcome, MobileBackCoordinator, MobileRoute, MobileSheet, MobileShellView, MobileTab, + NativeSelectionUi, ThemePreference, +}; +use playground::{FormFactor, PlaygroundTheme}; +use ui::AppContext; + +use super::{ + editor_runtime::IosEditorRuntime, + runtime_root::{MountedWorkspace, RuntimeRoot, ShellHost}, + shell_workspace::{ShellLaunch, ShellWorkspace}, +}; + +/// Interval between commits of the shell's edits to its SQLite workspace. +const AUTOSAVE_INTERVAL: Duration = Duration::from_secs(1); + +/// Route of the shell as a C-ABI code. +pub(crate) fn route_code(route: &MobileRoute) -> u8 { + match route { + MobileRoute::Home => 1, + MobileRoute::Explorer => 2, + MobileRoute::Journals => 3, + MobileRoute::Search => 4, + MobileRoute::Page(_) => 5, + MobileRoute::Settings => 6, + } +} + +impl IosEditorRuntime { + /// Mount the mobile shell with the showcase workspaces until a local workspace is mounted. + pub(crate) fn new_shell( + width_pt: f32, + height_pt: f32, + scale_factor: f32, + form_factor: FormFactor, + launch: &ShellLaunch, + ) -> Option { + let state = launch.showcase_state(); + let host = ShellHost { + a11y: affine_mobile::InMemoryPlatformAccessibility::new(), + workspace: None, + }; + let sink = host.a11y.clone(); + Self::open( + width_pt, + height_pt, + scale_factor, + form_factor, + Some(host), + move |_, cx| { + cx.new(|cx| { + let mut shell = + MobileShellView::with_a11y_sink(state, Arc::new(Mutex::new(sink)), cx); + // `UITextInteraction` draws the handles, the caret, and the selection. + shell.set_native_selection_ui(NativeSelectionUi { + native_selection_ui: true, + native_suppresses_gpu_caret_and_selection: true, + }); + shell + }) + }, + RuntimeRoot::Shell, + ) + } + + /// Shell route code (`0` when the root is a bare page editor). + pub(crate) fn shell_route(&self) -> u8 { + let Some(shell) = self.root.shell() else { + return 0; + }; + self.app + .update(|cx| shell.read_with(cx, |s, _| route_code(&s.state.route))) + .unwrap_or(0) + } + + /// Theme of the root view. + pub(crate) fn root_theme(&self) -> Option { + match self.root { + RuntimeRoot::Editor(_) => self + .app + .update(|cx| self.view().read_with(cx, |v, _| v.theme())) + .ok(), + RuntimeRoot::Shell(shell) => self + .app + .update(|cx| { + shell.read_with(cx, |s, _| match s.state.resolved_theme() { + ui_tokens::ThemeMode::Light => PlaygroundTheme::Light, + ui_tokens::ThemeMode::Dark => PlaygroundTheme::Dark, + }) + }) + .ok(), + } + } + + /// Follow the platform appearance: the shell resolves its `System` preference with it. + /// Returns `false` when the root is a bare page editor. + pub(crate) fn set_shell_system_dark(&mut self, dark: bool) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + let _ = self.app.update(|cx| { + shell.update(cx, |s, _, cx| { + if s.state.system_dark != dark { + s.state.system_dark = dark; + if s.state.settings.theme_preference == ThemePreference::System { + cx.notify(); + } + } + }) + }); + self.window.request_frame_now(); + true + } + + /// Close a sheet, the drawer, or the page, or step back through the route history. + /// Returns `false` at the root route, where the platform handles back. + pub(crate) fn shell_back(&mut self) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + let handled = self.app.update(|cx| { + shell.update(cx, |s, _, cx| { + let now_ms = s.clock_ms(cx); + let handled = match MobileBackCoordinator::handle_back(&mut s.state, now_ms) { + // Without history left, another tab steps back to Home before the app exits. + BackOutcome::YieldToHostExit if s.state.route != MobileRoute::Home => { + s.state.switch_tab(MobileTab::Home, now_ms); + true + } + BackOutcome::YieldToHostExit => false, + _ => true, + }; + if handled { + cx.notify(); + } + handled + }) + }); + let handled = matches!(handled, Ok(true)); + if handled { + self.window.request_frame_now(); + } + handled + } + + /// Whether a shell text field holds keyboard focus: Search with no sheet above it, or the + /// drawer filter. + pub(crate) fn shell_search_focused(&self) -> bool { + self.shell_text_focus() == Some(true) + } + + /// Whether a sheet covers the shell while no shell text field has focus. Text and + /// composition edits are then dropped instead of reaching the page editor under the sheet. + pub(crate) fn shell_blocks_text_input(&self) -> bool { + self.shell_text_focus() == Some(false) + } + + /// `Some(true)` when a shell text field has focus, `Some(false)` when a sheet covers the + /// shell without one, and `None` when the shell takes no part in text input. + fn shell_text_focus(&self) -> Option { + let shell = self.root.shell()?; + self.app + .update(|cx| { + shell.update(cx, |s, window, _| { + let focused = s.search_focus.is_focused(window); + match s.state.active_sheet { + MobileSheet::None => { + (s.state.route == MobileRoute::Search && focused).then_some(true) + } + MobileSheet::WorkspaceDrawer => Some(focused), + _ => Some(false), + } + }) + }) + .ok() + .flatten() + } + + /// Ask the platform for the software keyboard when a touch leaves a shell field focused. + pub(crate) fn request_keyboard_for_search_focus(&mut self) { + if self.shell_search_focused() { + self.window.state.borrow_mut().soft_keyboard_requested = true; + } + } + + /// Latest accessibility tree that the shell published, as JSON. + pub(crate) fn shell_accessibility_json(&self) -> Option { + let tree = self.shell.as_ref()?.a11y.latest_tree()?; + serde_json::to_string(&tree).ok() + } + + fn mounted_workspace(&self) -> Option> { + let mounted = self.shell.as_ref()?.workspace.as_ref()?; + Some(Rc::clone(&mounted.store)) + } + + /// Replace the showcase with the local workspace + /// `/workspaces///.db`. Only the root document and + /// `db$*` tables load now; pages load when the shell opens them. + pub(crate) fn mount_shell_workspace( + &mut self, + base_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, + name: &str, + now_ms: i64, + ) -> bool { + let Some(shell) = self.root.shell() else { + return false; + }; + if self.shell.as_ref().is_none_or(|h| h.workspace.is_some()) { + return false; + } + let now = self.app.update(|cx| cx.background_executor().now()); + let Ok((workspace, bridge)) = + ShellWorkspace::open(base_dir, space_type, peer, space_id, now_ms, now) + else { + return false; + }; + let store = Rc::new(workspace); + let autosave_store = Rc::clone(&store); + let mounted = self.app.update(|cx| { + let attached = shell.update(cx, |s, _, cx| { + let launch = ShellLaunch { + locale: s.state.locale(), + today: s.state.today_date.clone(), + dark: s.state.system_dark, + }; + *s.state_mut() = launch.local_workspace_state(space_id, name); + let attached = s.attach_workspace_bridge(bridge, now_ms).is_ok(); + cx.notify(); + attached + }); + let clock = cx.background_executor().clone(); + let autosave = cx.spawn(async move |cx| { + loop { + clock.timer(AUTOSAVE_INTERVAL).await; + let now_ms = autosave_store.now_ms(clock.now()); + let committed = shell.update(cx, |s, _, _| { + // A failed commit keeps the changes pending for the next tick. + let _ = autosave_store.commit(s, now_ms); + }); + if committed.is_err() { + break; + } + } + }); + (matches!(attached, Ok(true)), autosave) + }); + let (true, autosave) = mounted else { + return false; + }; + if let Some(host) = self.shell.as_mut() { + host.workspace = Some(MountedWorkspace { + store, + _autosave: autosave, + }); + } + self.window.request_frame_now(); + true + } + + /// Load the page that the shell shows from SQLite before it renders. A page loads once; a + /// page whose load failed loads again when the shell shows it the next time. + pub(crate) fn hydrate_shown_page(&mut self) { + let (Some(shell), Some(store)) = (self.root.shell(), self.mounted_workspace()) else { + return; + }; + let _ = self.app.update(|cx| { + let now_ms = store.now_ms(cx.background_executor().now()); + shell.update(cx, |s, _, cx| { + let shown = match &s.state.route { + MobileRoute::Page(doc_id) => Some(doc_id.clone()), + _ => None, + }; + if !store.needs_load(shown.as_deref()) { + return; + } + let Some(doc_id) = shown else { + return; + }; + let Some(Ok(mut bridge)) = s.take_workspace_bridge(now_ms) else { + return; + }; + let loaded = store.hydrate(&mut bridge, &doc_id, now_ms); + if s.attach_workspace_bridge(bridge, now_ms).is_ok() && loaded { + cx.notify(); + } + }) + }); + } + + /// Commit the shell's local changes to the mounted SQLite workspace now. + /// Returns the number of written rows, or `-1` when nothing is mounted or the commit fails. + pub(crate) fn flush_shell_workspace(&mut self) -> i64 { + let (Some(shell), Some(store)) = (self.root.shell(), self.mounted_workspace()) else { + return -1; + }; + self.app + .update(|cx| { + let now_ms = store.now_ms(cx.background_executor().now()); + shell.read_with(cx, |s, _| store.commit(s, now_ms)) + }) + .ok() + .and_then(Result::ok) + .map_or(-1, |n| n.min(i64::MAX as usize) as i64) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AffineUtf16Range, selection::AffinePoint}; + + fn node_center(rt: &IosEditorRuntime, prefix: &str) -> Option<(String, f32, f32)> { + let json = rt.shell_accessibility_json()?; + let tree: affine_client::AccessibilityTree = serde_json::from_str(&json).ok()?; + tree.nodes + .values() + .filter(|n| n.id.starts_with(prefix) && n.bounds.width > 0.0 && n.bounds.height > 0.0) + .min_by(|a, b| a.bounds.y.total_cmp(&b.bounds.y)) + .map(|n| { + ( + n.id.clone(), + n.bounds.x + n.bounds.width * 0.5, + n.bounds.y + n.bounds.height * 0.5, + ) + }) + } + + fn tap(rt: &mut IosEditorRuntime, id: u64, prefix: &str) -> String { + let (node, x, y) = node_center(rt, prefix).unwrap_or_else(|| panic!("node {prefix}")); + rt.dispatch_touch(id, 0, x, y); + rt.dispatch_touch(id, 2, x, y); + let _ = rt.render_frame(id as f64); + node + } + + fn focus_page_text(rt: &mut IosEditorRuntime) { + let _ = rt.app.update(|cx| { + rt.view() + .update(cx, |v, w, cx| v.focus_first_text_block(w, cx)) + }); + let _ = rt.render_frame(0.5); + } + + fn launch() -> ShellLaunch { + ShellLaunch::new("en-US", 1_764_000_000_000, 480, false) + } + + fn open_sheet(rt: &mut IosEditorRuntime, sheet: MobileSheet) { + if let Some(shell) = rt.root.shell() { + let _ = rt.app.update(|cx| { + shell.update(cx, |s, _, cx| { + s.state.open_sheet(sheet, 0.0); + cx.notify(); + }) + }); + } + let _ = rt.render_frame(0.7); + } + + fn active_sheet(rt: &IosEditorRuntime) -> Option { + let shell = rt.root.shell()?; + rt.app + .update(|cx| shell.read_with(cx, |s, _| s.state.active_sheet)) + .ok() + } + + /// Load page `doc_id` the way `hydrate_shown_page` does, without showing it. + fn load_page(rt: &mut IosEditorRuntime, doc_id: &str) -> bool { + let (Some(shell), Some(store)) = (rt.root.shell(), rt.mounted_workspace()) else { + return false; + }; + rt.app + .update(|cx| { + shell.update(cx, |s, _, _| { + let Some(Ok(mut bridge)) = s.take_workspace_bridge(10) else { + return false; + }; + let loaded = store.hydrate(&mut bridge, doc_id, 10); + s.attach_workspace_bridge(bridge, 10).is_ok() && loaded + }) + }) + .unwrap_or(false) + } + + /// Pages that the bridge's session holds in memory. + fn loaded_pages(rt: &IosEditorRuntime) -> usize { + let Some(shell) = rt.root.shell() else { + return 0; + }; + rt.app + .update(|cx| { + shell.read_with(cx, |s, _| { + s.workspace_bridge() + .map_or(0, |b| b.session().open_doc_revisions().count()) + }) + }) + .unwrap_or(0) + } + + fn back_to_home(rt: &mut IosEditorRuntime) { + for _ in 0..4 { + if rt.shell_route() == 1 { + return; + } + assert!(rt.handle_back()); + let _ = rt.render_frame(0.9); + } + assert_eq!(rt.shell_route(), 1, "back must reach Home"); + } + + #[test] + fn shell_routes_page_ime_search_ime_and_back_coordinator() { + let mut rt = IosEditorRuntime::new_shell(390.0, 844.0, 3.0, FormFactor::Phone, &launch()) + .expect("shell runtime"); + let _ = rt.render_frame(0.1); + assert_eq!(rt.shell_route(), 1, "launch shows Home"); + assert!(node_center(&rt, "mobile.tab.search").is_some()); + assert!(!rt.wants_software_keyboard() && rt.utf16_len() == 0); + + // Home row tap opens the Page route; the embedded editor owns text input. + let row = tap(&mut rt, 1, "mobile.home.doc."); + assert_eq!(rt.shell_route(), 5, "tapping {row} opens the page"); + focus_page_text(&mut rt); + let before = rt.utf16_len(); + rt.insert_text(&"Hi 世界".encode_utf16().collect::>()); + let text = String::from_utf16_lossy(&rt.utf16_text()); + assert!(text.contains("Hi 世界"), "page text {text:?}"); + assert_eq!(rt.utf16_len(), before + 5); + let sel = rt.selected_range(); + assert!(rt.caret_rect(sel.location).is_some()); + let (start, end) = rt.doc_document_bounds().expect("document bounds"); + assert!(start.valid && end.valid); + assert!(rt.doc_caret_rect_for_token(end.endpoint_token).is_some()); + let rect = rt.caret_rect(sel.location).expect("caret"); + assert!( + rt.closest_offset(AffinePoint { + x: rect.x, + y: rect.y + rect.height * 0.5, + }) + .is_some() + ); + + // A sheet or the drawer above the page owns touches and back: the page editor exposes + // no input, document positions, or selection until back closes it. + let page_text = rt.utf16_text(); + // An overlay sheet takes the focus from the editor, so the keyboard has no text; the + // drawer leaves the focus where it is. `(sheet, the editor keeps the focus)` + for (sheet, editor_focus) in [ + (MobileSheet::DocActions, false), + (MobileSheet::WorkspaceDrawer, true), + ] { + open_sheet(&mut rt, sheet); + // Text and composition edits under the sheet are dropped. + rt.insert_text(&"LEAK".encode_utf16().collect::>()); + rt.set_marked_text( + &"ni".encode_utf16().collect::>(), + AffineUtf16Range { + location: 2, + length: 0, + }, + ); + let _ = rt.render_frame(0.75); + let shown = if editor_focus { + page_text.clone() + } else { + Vec::new() + }; + assert_eq!(rt.utf16_text(), shown, "{sheet:?} input text"); + assert!( + rt.app.update(|cx| rt.root.editor(cx)).is_none(), + "{sheet:?}" + ); + assert!(rt.doc_document_bounds().is_none(), "{sheet:?}"); + assert!(rt.handle_back(), "back closes {sheet:?}"); + let _ = rt.render_frame(0.8); + assert_eq!(active_sheet(&rt), Some(MobileSheet::None)); + assert_eq!( + rt.shell_route(), + 5, + "back after {sheet:?} stays on the page" + ); + focus_page_text(&mut rt); + assert_eq!(rt.utf16_text(), page_text, "{sheet:?} keeps the page text"); + } + + // Back leaves the page; the page editor no longer owns input. + assert!(rt.handle_back()); + let _ = rt.render_frame(1.0); + assert_eq!(rt.shell_route(), 1); + assert_eq!(rt.utf16_len(), 0); + assert!(rt.doc_document_bounds().is_none()); + + // Search tab, then the field: one keyboard request, and IME text reaches the query. + let _ = rt.take_software_keyboard_request(); + let _ = tap(&mut rt, 2, "mobile.tab.search"); + assert_eq!(rt.shell_route(), 4); + let _ = tap(&mut rt, 3, "mobile.search.input"); + assert!(rt.take_software_keyboard_request() && rt.wants_software_keyboard()); + assert!(!rt.is_surface_readonly()); + assert_eq!(rt.utf16_len(), 0, "Search launches with an empty query"); + rt.set_marked_text( + &"tong".encode_utf16().collect::>(), + AffineUtf16Range { + location: 4, + length: 0, + }, + ); + assert_eq!(rt.marked_range().length, 4); + let marked = rt.marked_range(); + rt.replace_range(marked, &"同步".encode_utf16().collect::>()); + rt.unmark_text(); + assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), "同步"); + + // Back steps through the history to Home, then yields to the platform. + let mut steps = 0; + while rt.handle_back() { + steps += 1; + assert!(steps < 8, "back must reach the root route"); + } + assert_eq!(rt.shell_route(), 1); + assert!(!rt.handle_back()); + + // The drawer filter, once it holds focus, takes text: the runtime stops dropping edits + // and asks for the keyboard. + open_sheet(&mut rt, MobileSheet::WorkspaceDrawer); + if let Some(shell) = rt.root.shell() { + let _ = rt + .app + .update(|cx| shell.update(cx, |s, window, cx| window.focus(&s.search_focus, cx))); + } + assert!(rt.shell_search_focused() && !rt.shell_blocks_text_input()); + rt.insert_text(&"filter".encode_utf16().collect::>()); + assert!(rt.handle_back(), "back closes the drawer"); + let _ = rt.render_frame(0.85); + assert!(!rt.shell_search_focused() && !rt.shell_blocks_text_input()); + assert_eq!(rt.shell_route(), 1); + } + + #[test] + fn shell_local_workspace_loads_pages_on_open_and_autosaves_every_second() { + let base = + std::env::temp_dir().join(format!("affine-ios-shell-workspace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let texts = ["Durable 本地", "Second page"]; + let mut writer = + IosEditorRuntime::new_shell(390.0, 844.0, 3.0, FormFactor::Phone, &launch()) + .expect("shell runtime"); + assert!(writer.mount_shell_workspace(&base, "workspace", "local", "ws-local", "Local", 10)); + assert!(!writer.mount_shell_workspace( + &base, + "workspace", + "local", + "ws-local", + "Local", + 11 + )); + let _ = writer.render_frame(0.1); + assert!( + node_center(&writer, "mobile.home.doc.").is_none(), + "no showcase rows" + ); + for (id, text) in (1..).zip(texts) { + let _ = tap(&mut writer, id, "mobile.home.new_doc_btn"); + assert_eq!(writer.shell_route(), 5); + focus_page_text(&mut writer); + writer.insert_text(&text.encode_utf16().collect::>()); + // A commit while a sheet covers the page never reaches the stored page. + open_sheet(&mut writer, MobileSheet::DocActions); + writer.insert_text(&"LEAK".encode_utf16().collect::>()); + assert!(writer.handle_back(), "back closes the sheet"); + let _ = writer.render_frame(0.95); + back_to_home(&mut writer); + } + + // A page whose load fails is not retried while it stays shown, and is tried again once + // the shell shows it again. + let mut early = + IosEditorRuntime::new_shell(390.0, 844.0, 3.0, FormFactor::Phone, &launch()) + .expect("early shell"); + assert!(early.mount_shell_workspace(&base, "workspace", "local", "ws-local", "Local", 15)); + let early_store = early.mounted_workspace().expect("early workspace"); + for attempt in 0..2 { + assert!( + early_store.needs_load(Some("missing-page")), + "attempt {attempt}" + ); + assert!( + !load_page(&mut early, "missing-page"), + "a missing page fails to load" + ); + assert!( + !early_store.needs_load(Some("missing-page")), + "no retry while shown" + ); + assert!(!early_store.needs_load(None), "no page shows"); + } + drop(early); + + // One second of scheduler time commits both pages without an explicit flush. + writer + .dispatcher + .advance_test_clock(std::time::Duration::from_millis(1_100)); + let _ = writer.drain_tasks(); + + // A second runtime on the same database loads no page at mount and one page on open. + let mut reader = + IosEditorRuntime::new_shell(390.0, 844.0, 3.0, FormFactor::Phone, &launch()) + .expect("reader shell"); + assert!(reader.mount_shell_workspace(&base, "workspace", "local", "ws-local", "Local", 20)); + let _ = reader.render_frame(0.1); + assert_eq!(loaded_pages(&reader), 0, "mount decodes no page"); + let _ = tap(&mut reader, 30, "mobile.home.doc."); + assert_eq!(reader.shell_route(), 5); + assert_eq!( + loaded_pages(&reader), + 1, + "opening a page loads only that page" + ); + focus_page_text(&mut reader); + let shown = String::from_utf16_lossy(&reader.utf16_text()); + assert!(texts.contains(&shown.as_str()), "reader shows {shown:?}"); + + assert_eq!( + writer.flush_shell_workspace(), + 0, + "autosave left no pending change" + ); + drop((writer, reader)); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn scrolled_drawer_filter_maps_caret_rects_and_touches_to_the_same_offsets() { + const QUERY: &str = "offline-first collaborative workspace synchronization notes"; + let mut rt = IosEditorRuntime::new_shell(390.0, 844.0, 3.0, FormFactor::Phone, &launch()) + .expect("shell runtime"); + let _ = rt.render_frame(0.1); + open_sheet(&mut rt, MobileSheet::WorkspaceDrawer); + if let Some(shell) = rt.root.shell() { + let _ = rt + .app + .update(|cx| shell.update(cx, |s, window, cx| window.focus(&s.search_focus, cx))); + } + rt.insert_text(&QUERY.encode_utf16().collect::>()); + for frame in 0..3 { + let _ = rt.render_frame(1.0 + f64::from(frame)); + } + let len = QUERY.encode_utf16().count() as u32; + // The caret rect of each offset, given back as a touch, lands on the same offset: the + // end of the line, the start of `notes`, and the start of `synchronization`. + for offset in [len, len - 5, len - 21] { + let rect = rt.caret_rect(offset).expect("caret rect"); + let touched = rt.closest_offset(AffinePoint { + x: rect.x + rect.width / 2.0, + y: rect.y + rect.height / 2.0, + }); + assert_eq!(touched, Some(offset), "{rect:?}"); + } + let end = rt.caret_rect(len).expect("caret rect"); + let location = rt + .closest_offset(AffinePoint { + x: end.x + end.width / 2.0, + y: end.y + end.height / 2.0, + }) + .expect("offset"); + rt.set_selected_range(AffineUtf16Range { + location, + length: 0, + }); + rt.insert_text(&"!".encode_utf16().collect::>()); + assert_eq!( + String::from_utf16_lossy(&rt.utf16_text()), + format!("{QUERY}!") + ); + } +} diff --git a/packages/frontend/hosts/ios/src/shell_workspace.rs b/packages/frontend/hosts/ios/src/shell_workspace.rs new file mode 100644 index 0000000000..ebeb5eedc7 --- /dev/null +++ b/packages/frontend/hosts/ios/src/shell_workspace.rs @@ -0,0 +1,223 @@ +//! Local SQLite workspace behind the mobile shell, and the shell launch state. +//! +//! The host opens one allowlisted `//.db` workspace in place, loads +//! each page into the [`MobileWorkspaceBridge`] when the shell opens it, and commits shell edits +//! back through `SqliteWorkspaceStore::flush_session_mutations`. + +use std::{cell::RefCell, collections::HashSet, path::Path}; + +use affine_client::{ + ClientError, ClientResult, DirectKind, FolderForestCache, HostKind, LinkGraph, NavHistory, + NavTarget, Origin, Scope, SqliteWorkspaceStore, +}; +use affine_mobile::{ + MobileAppState, MobileLocale, MobileShellView, MobileWorkspaceBridge, ThemePreference, + seed_showcase_state, +}; +use ui::scheduler::Instant; +use ui_tokens::ThemeMode; + +/// Locale, date, and appearance that the platform gives the shell at launch. +#[derive(Clone, Debug)] +pub(crate) struct ShellLaunch { + pub(crate) locale: MobileLocale, + pub(crate) today: String, + pub(crate) dark: bool, +} + +impl ShellLaunch { + /// Resolve the launch values from a BCP 47 language tag, Unix epoch milliseconds, and the + /// local UTC offset in minutes. + pub(crate) fn new( + language_tag: &str, + now_ms: i64, + utc_offset_minutes: i32, + dark: bool, + ) -> Self { + let local_ms = now_ms.saturating_add(i64::from(utc_offset_minutes) * 60_000); + let today = chrono::DateTime::from_timestamp_millis(local_ms) + .map(|t| t.format("%Y-%m-%d").to_string()) + .unwrap_or_else(|| "1970-01-01".to_string()); + let code = language_tag.split(['-', '_']).next().unwrap_or("en"); + Self { + locale: MobileLocale::parse(&code.to_ascii_lowercase()), + today, + dark, + } + } + + /// Deterministic showcase workspaces, shown until the host mounts a local workspace. + pub(crate) fn showcase_state(&self) -> MobileAppState { + let mut state = seed_showcase_state(self.locale, self.theme(), &self.today); + state.settings.theme_preference = ThemePreference::System; + state.system_dark = self.dark; + state.search_query.clear(); + state + } + + /// One empty workspace with id `space_id`, which a mounted bridge fills. + pub(crate) fn local_workspace_state(&self, space_id: &str, name: &str) -> MobileAppState { + let mut state = self.showcase_state(); + state.workspace_store.truncate(1); + state.active_workspace_idx = 0; + state.settings.account_email.clear(); + state.settings.account_plan.clear(); + let scope = Scope::new("local", "", space_id); + let mut history = NavHistory::new(); + history.push( + scope.clone(), + NavTarget::Home, + Origin::Direct(DirectKind::Home), + None, + ); + let ws = &mut state.workspace_store[0]; + let stale: Vec = ws.doc_crdt_updates().keys().cloned().collect(); + for doc_id in stale { + ws.remove_doc_crdt_update(&doc_id); + } + ws.docs_mut().clear(); + ws.summary.id = space_id.to_string(); + ws.summary.name = name.to_string(); + ws.summary.doc_count = 0; + ws.summary.is_cloud = false; + ws.scope = scope; + ws.folder_rows.clear(); + ws.folder_revision = ws.folder_revision.saturating_add(1); + ws.folder_cache = FolderForestCache::new(); + ws.collections.clear(); + ws.tags.clear(); + ws.link_graph = LinkGraph::new(); + ws.history = history; + ws.collapsed_folders.clear(); + state + } + + fn theme(&self) -> ThemeMode { + if self.dark { + ThemeMode::Dark + } else { + ThemeMode::Light + } + } +} + +/// Open local SQLite workspace that the shell edits. +pub(crate) struct ShellWorkspace { + runtime: tokio::runtime::Runtime, + store: SqliteWorkspaceStore, + /// Unix epoch milliseconds and scheduler time when the workspace was mounted. + mounted: (i64, Instant), + /// Pages that loaded from SQLite into the session. + hydrated: RefCell>, + /// Shown page whose last load failed, so the shell does not retry it on every frame. + failed: RefCell>, +} + +impl ShellWorkspace { + /// Open `/workspaces///.db` and load its root + /// document and `db$*` tables into a bridge. Pages load on demand through [`Self::hydrate`]. + pub(crate) fn open( + base_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, + now_ms: i64, + now: Instant, + ) -> ClientResult<(Self, MobileWorkspaceBridge)> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| ClientError::Store(format!("starting the SQLite runtime: {e}")))?; + let client_id = blocksuite_playground_doc::try_random_client_id() + .map_err(|e| ClientError::Store(format!("making a client ID: {e}")))?; + let store = runtime.block_on(SqliteWorkspaceStore::open( + base_dir, space_type, peer, space_id, + ))?; + let session = runtime.block_on(store.load_workspace_session( + "local", + client_id, + HostKind::Native, + "", + "https://app.affine.pro", + now_ms, + ))?; + let workspace = Self { + runtime, + store, + mounted: (now_ms, now), + hydrated: RefCell::default(), + failed: RefCell::default(), + }; + Ok((workspace, MobileWorkspaceBridge::new(session))) + } + + /// Unix epoch milliseconds at scheduler time `now`. + pub(crate) fn now_ms(&self, now: Instant) -> i64 { + let (mounted_ms, mounted_at) = self.mounted; + let elapsed = now.saturating_duration_since(mounted_at).as_millis(); + mounted_ms.saturating_add(elapsed.min(i64::MAX as u128) as i64) + } + + /// Load page `doc_id` from SQLite into the bridge's session. Returns `true` when the page + /// was not in the session and now is. A failed load marks the page so that the shell tries + /// it again only after it leaves and reopens the page. + pub(crate) fn hydrate( + &self, + bridge: &mut MobileWorkspaceBridge, + doc_id: &str, + now_ms: i64, + ) -> bool { + if bridge.session().doc_revision(doc_id).is_some() { + self.hydrated.borrow_mut().insert(doc_id.to_string()); + return false; + } + let loaded = self + .runtime + .block_on( + self.store + .open_or_hydrate_document(bridge.session_mut(), doc_id, now_ms), + ) + .is_ok(); + if loaded { + self.hydrated.borrow_mut().insert(doc_id.to_string()); + } else { + *self.failed.borrow_mut() = Some(doc_id.to_string()); + } + loaded + } + + /// Whether the shown page `doc_id` still needs a load. `None` means that no page shows, + /// which allows another load of a page that failed before. + pub(crate) fn needs_load(&self, doc_id: Option<&str>) -> bool { + let mut failed = self.failed.borrow_mut(); + if failed.as_deref() != doc_id { + *failed = None; + } + doc_id.is_some_and(|id| failed.is_none() && !self.hydrated.borrow().contains(id)) + } + + /// Merge the shell's edits into its bridge and commit the pending local changes. Without + /// pending changes this returns `Ok(0)` before any SQLite access; the WAL checkpoint runs + /// only after rows were written. + pub(crate) fn commit(&self, shell: &MobileShellView, now_ms: i64) -> ClientResult { + let Some(mut bridge) = shell.workspace_bridge() else { + return Ok(0); + }; + bridge.sync_from_state(&shell.state, now_ms)?; + let written = self.runtime.block_on(self.store.flush_session_mutations( + bridge.session_mut(), + None, + now_ms, + ))?; + if written > 0 { + self.runtime.block_on(self.store.checkpoint())?; + } + Ok(written) + } +} + +impl Drop for ShellWorkspace { + fn drop(&mut self) { + self.runtime.block_on(self.store.close()); + } +} diff --git a/packages/frontend/hosts/ios/src/text_layout.rs b/packages/frontend/hosts/ios/src/text_layout.rs new file mode 100644 index 0000000000..e1a495a459 --- /dev/null +++ b/packages/frontend/hosts/ios/src/text_layout.rs @@ -0,0 +1,587 @@ +//! Deterministic pure-Rust fallback text layout (soft line-wrapping, +//! surrogate-safe caret/hit-testing, per-line selection rects, and software +//! loupe rasterization) used when no native CoreText `AffineTextProvider` is +//! attached (for example, headless Linux `cargo test`). + +use crate::{ + AffineUtf16Range, AffineWindowInsets, + selection::{AffinePoint, AffineRect, AffineWritingDirection}, +}; + +pub const CONTENT_INSET_PT: f32 = 16.0; +pub const LINE_HEIGHT_PT: f32 = 22.0; +const GLYPH_ADVANCE_ASCII_PT: f32 = 9.0; +const GLYPH_ADVANCE_SPACE_PT: f32 = 5.0; +const GLYPH_ADVANCE_WIDE_PT: f32 = 11.0; +const GLYPH_ADVANCE_NARROW_PT: f32 = 4.5; + +#[derive(Debug, Clone, Copy)] +struct VisualLine { + start: usize, + end: usize, + is_soft_wrapped: bool, + y: f32, +} + +/// One per-line selection rectangle matching `UITextSelectionRect`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineSelectionRect { + pub rect: AffineRect, + pub contains_start: bool, + pub contains_end: bool, +} + +/// Detect document base writing direction from the first strong directional UTF-16 unit. +pub fn detect_writing_direction(utf16: &[u16]) -> AffineWritingDirection { + for &unit in utf16 { + if (0x0590..=0x08FF).contains(&unit) + || (0xFB1D..=0xFDFF).contains(&unit) + || (0xFE70..=0xFEFC).contains(&unit) + { + return AffineWritingDirection::Rtl; + } + if (0x0041..=0x005A).contains(&unit) + || (0x0061..=0x007A).contains(&unit) + || (0x00C0..=0x024F).contains(&unit) + || (0x0370..=0x052F).contains(&unit) + || (0x4E00..=0x9FFF).contains(&unit) + { + return AffineWritingDirection::Ltr; + } + } + AffineWritingDirection::Ltr +} + +/// Detect paragraph base writing direction for the `\n`-delimited paragraph containing `utf16_offset`. +pub fn detect_paragraph_writing_direction( + utf16: &[u16], + utf16_offset: usize, +) -> AffineWritingDirection { + if utf16.is_empty() { + return AffineWritingDirection::Ltr; + } + let idx = utf16_offset.min(utf16.len()); + let mut para_start = idx; + while para_start > 0 && utf16[para_start - 1] != 0x000A { + para_start -= 1; + } + let mut para_end = idx; + while para_end < utf16.len() && utf16[para_end] != 0x000A { + para_end += 1; + } + detect_writing_direction(&utf16[para_start..para_end]) +} + +/// Snap a UTF-16 offset so it never splits a surrogate pair. +pub fn snap_utf16_boundary(utf16: &[u16], offset: usize) -> usize { + let clamped = offset.min(utf16.len()); + if clamped > 0 && clamped < utf16.len() { + let cur = utf16[clamped]; + let prev = utf16[clamped - 1]; + if (0xDC00..=0xDFFF).contains(&cur) && (0xD800..=0xDBFF).contains(&prev) { + return clamped - 1; + } + } + clamped +} + +fn next_cluster_end(utf16: &[u16], idx: usize) -> usize { + if idx >= utf16.len() { + return utf16.len(); + } + let cur = utf16[idx]; + if (0xD800..=0xDBFF).contains(&cur) + && idx + 1 < utf16.len() + && (0xDC00..=0xDFFF).contains(&utf16[idx + 1]) + { + return idx + 2; + } + idx + 1 +} + +fn default_cluster_advance_pt(cluster: &[u16]) -> f32 { + let Some(&u) = cluster.first() else { + return 0.0; + }; + if let Ok(ascii) = u8::try_from(u) { + return match ascii { + b'\n' | b'\r' => 0.0, + b' ' => GLYPH_ADVANCE_SPACE_PT, + b'.' | b',' | b'i' | b'l' | b'!' | b'|' => GLYPH_ADVANCE_NARROW_PT, + b'W' | b'M' => GLYPH_ADVANCE_WIDE_PT, + _ => GLYPH_ADVANCE_ASCII_PT, + }; + } + match u { + 0x0590..=0x08FF => GLYPH_ADVANCE_ASCII_PT, + 0xD800..=0xDBFF => 14.0, + _ => GLYPH_ADVANCE_ASCII_PT, + } +} + +fn content_box(viewport_w: f32, insets: AffineWindowInsets) -> (f32, f32, f32) { + let origin_x = insets.safe_left.max(0.0) + CONTENT_INSET_PT; + let origin_y = insets.safe_top.max(0.0) + CONTENT_INSET_PT; + let right_margin = insets.safe_right.max(0.0) + CONTENT_INSET_PT; + let width = (viewport_w.max(0.0) - origin_x - right_margin).max(40.0); + (origin_x, origin_y, width) +} + +fn layout_visual_lines( + utf16: &[u16], + viewport_w: f32, + insets: AffineWindowInsets, +) -> Vec { + let (_origin_x, origin_y, max_w) = content_box(viewport_w, insets); + let mut lines = Vec::new(); + let mut line_start = 0usize; + let mut cursor = 0usize; + let mut line_w = 0.0f32; + let mut last_space_end: Option = None; + let mut line_idx = 0usize; + + while cursor < utf16.len() { + if utf16[cursor] == 0x000A { + lines.push(VisualLine { + start: line_start, + end: cursor, + is_soft_wrapped: false, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + line_idx += 1; + cursor += 1; + line_start = cursor; + line_w = 0.0; + last_space_end = None; + continue; + } + let next = next_cluster_end(utf16, cursor); + let adv = default_cluster_advance_pt(&utf16[cursor..next]); + if line_w + adv > max_w && cursor > line_start { + let wrap_end = match last_space_end { + Some(sp) if sp > line_start => sp, + _ => cursor, + }; + lines.push(VisualLine { + start: line_start, + end: wrap_end, + is_soft_wrapped: true, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + line_idx += 1; + line_start = wrap_end; + cursor = wrap_end; + line_w = 0.0; + last_space_end = None; + continue; + } + line_w += adv; + if utf16[cursor] == 0x0020 { + last_space_end = Some(next); + } + cursor = next; + } + + lines.push(VisualLine { + start: line_start, + end: utf16.len(), + is_soft_wrapped: false, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + lines +} + +fn measure_range_width(utf16: &[u16], start: usize, end: usize) -> f32 { + let mut w = 0.0f32; + let mut i = start.min(utf16.len()); + let limit = end.min(utf16.len()); + while i < limit { + let next = next_cluster_end(utf16, i); + w += default_cluster_advance_pt(&utf16[i..next]); + i = next; + } + w +} + +/// Compute the fallback visual caret rect for `utf16_offset`. +/// Soft-wrap boundary offsets belong to the start of the wrapped next line; +/// hard `\n` boundary offsets stay at the end of the preceding line. +pub fn caret_rect_for_offset( + utf16: &[u16], + utf16_offset: u32, + viewport_w: f32, + insets: AffineWindowInsets, +) -> AffineRect { + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let offset = snap_utf16_boundary(utf16, utf16_offset as usize); + let lines = layout_visual_lines(utf16, viewport_w, insets); + + let line = lines + .iter() + .find(|l| { + if l.is_soft_wrapped { + offset >= l.start && offset < l.end + } else { + offset >= l.start && offset <= l.end + } + }) + .or_else(|| lines.last()) + .expect("layout_visual_lines always emits at least one line"); + + let prefix_w = measure_range_width(utf16, line.start, offset); + let x = match dir { + AffineWritingDirection::Ltr => origin_x + prefix_w, + AffineWritingDirection::Rtl => origin_x + max_w - prefix_w, + }; + + AffineRect { + x, + y: line.y, + width: 2.0, + height: LINE_HEIGHT_PT, + } +} + +/// Compute fallback per-line selection rectangles across soft-wrapped visual lines. +pub fn selection_rects_for_range( + utf16: &[u16], + range: AffineUtf16Range, + viewport_w: f32, + insets: AffineWindowInsets, +) -> Vec { + if range.length == 0 || utf16.is_empty() { + return Vec::new(); + } + let sel_start = snap_utf16_boundary(utf16, range.location as usize); + let sel_end = snap_utf16_boundary( + utf16, + (range.location as usize).saturating_add(range.length as usize), + ); + if sel_end <= sel_start { + return Vec::new(); + } + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + let mut rects = Vec::new(); + + for line in &lines { + if sel_end < line.start || sel_start > line.end { + continue; + } + let seg_start = line.start.max(sel_start); + let seg_end = line.end.min(sel_end); + let empty_hard_line_inside = line.start == line.end + && !line.is_soft_wrapped + && sel_start < line.start + && sel_end > line.end; + if seg_end <= seg_start && !empty_hard_line_inside { + continue; + } + + let contains_start = if line.is_soft_wrapped { + sel_start >= line.start && sel_start < line.end + } else { + sel_start >= line.start && sel_start <= line.end + }; + let contains_end = sel_end > line.start && sel_end <= line.end; + + let prefix_start = measure_range_width(utf16, line.start, seg_start); + let prefix_end = measure_range_width(utf16, line.start, seg_end); + let (x0, x1) = match dir { + AffineWritingDirection::Ltr => (origin_x + prefix_start, origin_x + prefix_end), + AffineWritingDirection::Rtl => ( + origin_x + max_w - prefix_end, + origin_x + max_w - prefix_start, + ), + }; + rects.push(AffineSelectionRect { + rect: AffineRect { + x: x0.min(x1), + y: line.y, + width: (x1 - x0).abs().max(2.0), + height: LINE_HEIGHT_PT, + }, + contains_start, + contains_end, + }); + } + rects +} + +/// Hit-test the closest surrogate-safe UTF-16 offset for a point in host view coordinates. +pub fn closest_offset_for_point( + utf16: &[u16], + point: AffinePoint, + viewport_w: f32, + insets: AffineWindowInsets, +) -> u32 { + if utf16.is_empty() { + return 0; + } + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + let px = if point.x.is_finite() { point.x } else { 0.0 }; + let py = if point.y.is_finite() { point.y } else { 0.0 }; + + let mut target_line = &lines[0]; + let mut best_dy = f32::INFINITY; + for line in &lines { + let mid_y = line.y + LINE_HEIGHT_PT * 0.5; + let dy = (py - mid_y).abs(); + if dy < best_dy { + best_dy = dy; + target_line = line; + } + } + + let boundary_x = |prefix_w: f32| match dir { + AffineWritingDirection::Ltr => origin_x + prefix_w, + AffineWritingDirection::Rtl => origin_x + max_w - prefix_w, + }; + + let mut best_offset = target_line.start; + let mut best_dx = (px - boundary_x(0.0)).abs(); + let mut acc_w = 0.0f32; + let mut idx = target_line.start; + while idx < target_line.end { + let next = next_cluster_end(utf16, idx); + acc_w += default_cluster_advance_pt(&utf16[idx..next]); + let dx = (px - boundary_x(acc_w)).abs(); + if dx < best_dx { + best_dx = dx; + best_offset = next; + } + idx = next; + } + + snap_utf16_boundary(utf16, best_offset).min(u32::MAX as usize) as u32 +} + +/// Software fallback RGBA8 loupe rasterizer used only when no native CoreText provider +/// is registered (e.g. headless Linux `cargo test`). +#[allow(clippy::too_many_arguments)] +pub fn render_loupe_rgba8( + utf16: &[u16], + selected_range: AffineUtf16Range, + viewport_w: f32, + insets: AffineWindowInsets, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, +) -> Vec { + let dim = diameter_px.clamp(16, 512) as usize; + let zoom = if zoom_scale.is_finite() && zoom_scale > 0.25 { + zoom_scale.min(12.0) + } else { + 1.75 + }; + let mut rgba = vec![255u8; dim * dim * 4]; + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + + let sel_start = selected_range.location as usize; + let sel_end = sel_start.saturating_add(selected_range.length as usize); + let half_dim = (dim as f32) * 0.5; + + let to_px = |wx: f32, wy: f32| -> (f32, f32) { + ( + (wx - focus_x) * zoom + half_dim, + (wy - focus_y) * zoom + half_dim, + ) + }; + + for line in &lines { + let mut acc_w = 0.0f32; + let mut idx = line.start; + while idx < line.end { + let next = next_cluster_end(utf16, idx); + let adv = default_cluster_advance_pt(&utf16[idx..next]); + let glyph_x = match dir { + AffineWritingDirection::Ltr => origin_x + acc_w, + AffineWritingDirection::Rtl => origin_x + max_w - acc_w - adv, + }; + + if idx >= sel_start && idx < sel_end { + let (px0, py0) = to_px(glyph_x, line.y); + let (px1, py1) = to_px(glyph_x + adv, line.y + LINE_HEIGHT_PT); + fill_rect(&mut rgba, dim, px0, py0, px1, py1, [206, 232, 255, 255]); + } + + if !matches!(utf16[idx], 0x0020 | 0x000A | 0x000D) { + let (gx0, gy0) = to_px(glyph_x + 1.0, line.y + 4.0); + let (gx1, gy1) = to_px( + glyph_x + (adv - 1.0).max(2.0), + line.y + LINE_HEIGHT_PT - 4.0, + ); + fill_rect(&mut rgba, dim, gx0, gy0, gx1, gy1, [24, 24, 28, 255]); + } + + acc_w += adv; + idx = next; + } + } + + let cx = half_dim; + fill_rect( + &mut rgba, + dim, + cx - 1.0, + half_dim - (LINE_HEIGHT_PT * 0.5) * zoom, + cx + 1.0, + half_dim + (LINE_HEIGHT_PT * 0.5) * zoom, + [30, 150, 235, 255], + ); + + rgba +} + +fn fill_rect(rgba: &mut [u8], dim: usize, x0: f32, y0: f32, x1: f32, y1: f32, color: [u8; 4]) { + let ix0 = (x0.floor() as isize).clamp(0, dim as isize) as usize; + let iy0 = (y0.floor() as isize).clamp(0, dim as isize) as usize; + let ix1 = (x1.ceil() as isize).clamp(0, dim as isize) as usize; + let iy1 = (y1.ceil() as isize).clamp(0, dim as isize) as usize; + for y in iy0..iy1 { + for x in ix0..ix1 { + let base = (y * dim + x) * 4; + rgba[base..base + 4].copy_from_slice(&color); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fallback_text_layout_handles_soft_wrap_boundary_selection_rects_and_surrogate() { + let insets = AffineWindowInsets::default(); + + // 1. Soft-wrap boundary offset belongs to the start of the wrapped next line, + // and selecting from that offset emits no trailing 2pt sliver on the prior line. + let narrow: Vec = "ABCDZ".encode_utf16().collect(); + let c0 = caret_rect_for_offset(&narrow, 0, 72.0, insets); + let c4 = caret_rect_for_offset(&narrow, 4, 72.0, insets); + assert!( + c4.y > c0.y + 10.0 && (c4.x - c0.x).abs() < 0.01, + "soft-wrap boundary offset 4 must start line 2 (c0={c0:?}, c4={c4:?})" + ); + let wrapped_tail = selection_rects_for_range( + &narrow, + AffineUtf16Range { + location: 4, + length: 1, + }, + 72.0, + insets, + ); + assert_eq!(wrapped_tail.len(), 1, "no 2pt sliver on line 1"); + assert!(wrapped_tail[0].rect.y > c0.y + 10.0); + assert!(wrapped_tail[0].contains_start && wrapped_tail[0].contains_end); + + // Hard newline boundary offset stays on line 1; offset after `\n` starts line 2. + let hard: Vec = "AB\nCD".encode_utf16().collect(); + let ch2 = caret_rect_for_offset(&hard, 2, 390.0, insets); + let ch3 = caret_rect_for_offset(&hard, 3, 390.0, insets); + assert!((ch2.y - c0.y).abs() < 0.01); + assert!(ch3.y > ch2.y + 10.0); + + // 2. Multi-line soft-wrap selection emits per-line rects with start/end flags. + let long: Vec = + "AFFiNE native iOS soft line wrapping verification across multiple visual lines" + .encode_utf16() + .collect(); + let cl0 = caret_rect_for_offset(&long, 0, 390.0, insets); + let cl60 = caret_rect_for_offset(&long, 60, 390.0, insets); + assert!(cl60.y > cl0.y + 10.0); + assert_eq!( + closest_offset_for_point( + &long, + AffinePoint { + x: cl60.x, + y: cl60.y + 10.0, + }, + 390.0, + insets, + ), + 60 + ); + let rects = selection_rects_for_range( + &long, + AffineUtf16Range { + location: 5, + length: 60, + }, + 390.0, + insets, + ); + assert!(rects.len() >= 2); + assert!(rects.first().unwrap().contains_start); + assert!(!rects.first().unwrap().contains_end); + assert!(!rects.last().unwrap().contains_start); + assert!(rects.last().unwrap().contains_end); + + // 3. Base & per-paragraph direction detection and surrogate pair boundary snap. + let hebrew: Vec = "שלום".encode_utf16().collect(); + assert_eq!( + detect_writing_direction(&hebrew), + AffineWritingDirection::Rtl + ); + let multi_para: Vec = "A\nשלום".encode_utf16().collect(); + assert_eq!( + detect_paragraph_writing_direction(&multi_para, 0), + AffineWritingDirection::Ltr + ); + assert_eq!( + detect_paragraph_writing_direction(&multi_para, 2), + AffineWritingDirection::Rtl + ); + let emoji: Vec = "A😀B".encode_utf16().collect(); + assert_eq!(snap_utf16_boundary(&emoji, 2), 1); + + // 4. Fallback loupe RGBA8 produces strictly more dark pixels over 'W' than spaces. + let sample: Vec = "WWWW ....".encode_utf16().collect(); + let cw = caret_rect_for_offset(&sample, 2, 390.0, insets); + let cs = caret_rect_for_offset(&sample, 9, 390.0, insets); + let count_dark = |buf: &[u8]| -> usize { + buf.chunks_exact(4) + .filter(|px| px[3] == 255 && px[0] < 80 && px[1] < 80 && px[2] < 80) + .count() + }; + let dark_w = count_dark(&render_loupe_rgba8( + &sample, + AffineUtf16Range { + location: 0, + length: 16, + }, + 390.0, + insets, + cw.x, + cw.y + 11.0, + 88, + 1.75, + )); + let dark_s = count_dark(&render_loupe_rgba8( + &sample, + AffineUtf16Range { + location: 0, + length: 16, + }, + 390.0, + insets, + cs.x, + cs.y + 11.0, + 88, + 1.75, + )); + assert!( + dark_w > 0 && dark_w > dark_s, + "dark_w={dark_w} dark_s={dark_s}" + ); + } +} diff --git a/packages/frontend/hosts/ios/src/workspace_store.rs b/packages/frontend/hosts/ios/src/workspace_store.rs new file mode 100644 index 0000000000..c8d62ae967 --- /dev/null +++ b/packages/frontend/hosts/ios/src/workspace_store.rs @@ -0,0 +1,563 @@ +use std::path::{Path, PathBuf}; + +use affine_store::{ + StoreError, + sqlite::{ + SqliteDocStorage, millis_to_naive_utc, naive_utc_to_millis, + resolve_allowlisted_workspace_paths, resolve_workspace_db_path, + }, + workspace_db::PendingDocUpdate, +}; +use blocksuite_playground_doc::{ + DocError, + read::{BlockContent, BlockNode, PageSnapshot}, + session::PageDocSession, +}; +use serde::Serialize; +use thiserror::Error; +use tokio::runtime::{Builder, Runtime}; + +/// Explicit SQLite busy timeout (milliseconds) configured on every opened iOS host connection. +pub const SQLITE_BUSY_TIMEOUT_MS: u64 = 5_000; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct PageSnapshotDto<'a> { + doc_id: &'a str, + title: &'a str, + block_count: usize, + blocks: Vec>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct BlockSummaryDto<'a> { + id: &'a str, + flavour: &'a str, + text: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + source_id: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + url: Option<&'a str>, + child_ids: Vec<&'a str>, +} + +fn block_plain_text(node: &BlockNode) -> Option<&str> { + match &node.content { + BlockContent::Page { title } => Some(title.plain.as_str()), + BlockContent::Paragraph { text, .. } => Some(text.plain.as_str()), + BlockContent::List { text, .. } => Some(text.plain.as_str()), + BlockContent::Code { text, .. } => Some(text.as_str()), + _ => None, + } +} + +fn block_source_id(node: &BlockNode) -> Option<&str> { + match &node.content { + BlockContent::Image { source_id, .. } | BlockContent::Attachment { source_id, .. } => { + Some(source_id.as_str()) + } + _ => None, + } +} + +fn block_url(node: &BlockNode) -> Option<&str> { + match &node.content { + BlockContent::Bookmark { url, .. } | BlockContent::ExternalEmbed { url, .. } => { + Some(url.as_str()) + } + _ => None, + } +} + +fn serialize_page_snapshot(snapshot: &PageSnapshot) -> Result { + let blocks: Vec> = snapshot + .root + .iter() + .chain(snapshot.detached.iter()) + .flat_map(BlockNode::walk) + .map(|node| BlockSummaryDto { + id: node.id.as_str(), + flavour: node.flavour.as_str(), + text: block_plain_text(node), + source_id: block_source_id(node), + url: block_url(node), + child_ids: node.children.iter().map(|c| c.id.as_str()).collect(), + }) + .collect(); + let dto = PageSnapshotDto { + doc_id: snapshot.doc_id.as_str(), + title: snapshot.title(), + block_count: snapshot.block_count(), + blocks, + }; + serde_json::to_string(&dto) +} + +#[derive(Debug, Error)] +pub enum WorkspaceStoreError { + #[error("storage error: {0}")] + Store(#[from] StoreError), + #[error("document CRDT error: {0}")] + Doc(#[from] DocError), + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), + #[error("JSON serialization error: {0}")] + Json(#[from] serde_json::Error), + #[error("local workspace {0:?} requires an explicit affine-local-workspace allowlist entry")] + WorkspaceNotAllowlisted(String), + #[error("invalid share ingest payload: {0}")] + InvalidSharePayload(String), + #[error("database error: {0}")] + Database(String), +} + +/// Persisted result of an offline paragraph edit on an in-place SQLite WAL database. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OfflineEditResult { + pub update_bytes: Vec, + pub state_vector: Vec, + pub timestamp_ms: i64, +} + +/// Exported document diff ready for outbound sync against a remote peer state vector. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExportedDocDiff { + pub doc_id: String, + pub missing: Vec, + pub state: Vec, + pub timestamp_ms: i64, +} + +/// Resolve the 0.27.5-compatible in-place SQLite path: +/// `/workspaces///.db`. +pub fn resolve_ios_space_db_path( + documents_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, +) -> Result { + Ok(resolve_workspace_db_path( + documents_dir, + space_type, + peer, + space_id, + )?) +} + +/// Resolve paths for an explicit `affine-local-workspace` allowlist without scanning disk. +/// +/// Enforces invariant F1: deleted workspaces whose `.db` files remain on disk are never +/// discovered or resurrected. +pub fn resolve_allowlisted_local_workspaces( + documents_dir: &Path, + allowlisted_ids: &[String], +) -> Result, WorkspaceStoreError> { + let refs: Vec<&str> = allowlisted_ids.iter().map(String::as_str).collect(); + Ok(resolve_allowlisted_workspace_paths( + documents_dir, + "workspace", + "local", + &refs, + )?) +} + +/// Handle to an opened 0.27.5-compatible in-place SQLite WAL workspace or userspace database. +pub struct IosWorkspaceHandle { + pub(crate) storage: SqliteDocStorage, + pub(crate) runtime: Runtime, + pub(crate) space_id: String, + pub(crate) db_path: PathBuf, +} + +impl IosWorkspaceHandle { + /// Open an existing or new SQLite WAL database in place under `/workspaces/...`. + /// + /// Fail-closed invariant F1: when `space_type == "workspace"` and `peer == "local"`, + /// `allowlisted_local_ids` MUST be `Some(ids)` containing `space_id` before any + /// directory creation or SQLite file open happens. + pub fn open( + documents_dir: &Path, + space_type: &str, + peer: &str, + space_id: &str, + allowlisted_local_ids: Option<&[String]>, + ) -> Result { + if space_type == "workspace" && peer == "local" { + let allowed = allowlisted_local_ids + .map(|allowlist| allowlist.iter().any(|id| id == space_id)) + .unwrap_or(false); + if !allowed { + return Err(WorkspaceStoreError::WorkspaceNotAllowlisted( + space_id.to_string(), + )); + } + } + + let db_path = resolve_ios_space_db_path(documents_dir, space_type, peer, space_id)?; + if let Some(parent) = db_path.parent() { + std::fs::create_dir_all(parent)?; + } + + let runtime = Builder::new_current_thread().enable_all().build()?; + let path_str = db_path.to_string_lossy().into_owned(); + let storage = runtime.block_on(async { + let storage = SqliteDocStorage::new(path_str); + storage.connect().await?; + storage.set_space_id(space_id).await?; + Ok::(storage) + })?; + + Ok(Self { + storage, + runtime, + space_id: space_id.to_string(), + db_path, + }) + } + + pub fn space_id(&self) -> &str { + &self.space_id + } + + pub fn db_path(&self) -> &Path { + &self.db_path + } + + /// Read and compact the stored Yjs V1 document binary for `doc_id`. + pub fn read_doc_binary(&self, doc_id: &str) -> Result>, WorkspaceStoreError> { + let record = self.runtime.block_on(self.storage.get_doc(doc_id))?; + Ok(record.map(|r| r.bin)) + } + + /// Decode `doc_id` through `PageDocSession` and serialize its typed `PageSnapshot` as JSON. + pub fn read_page_snapshot_json( + &self, + doc_id: &str, + client_id: u64, + ) -> Result, WorkspaceStoreError> { + let Some(bin) = self.read_doc_binary(doc_id)? else { + return Ok(None); + }; + let mut session = PageDocSession::new(doc_id, client_id)?; + session.apply_remote_update_v1(&bin)?; + let snapshot = session.read_page_snapshot()?; + Ok(Some(serialize_page_snapshot(&snapshot)?)) + } + + /// Edit a paragraph/block `prop:text` offline (single character or range replacement) + /// and persist the resulting CRDT delta atomically via `push_updates_batch` (`BEGIN IMMEDIATE`). + pub fn edit_paragraph_text( + &self, + doc_id: &str, + block_id: &str, + utf16_index: u64, + delete_len: u64, + insert_text: &str, + client_id: u64, + now_ms: i64, + ) -> Result { + let Some(existing) = self.read_doc_binary(doc_id)? else { + return Err(WorkspaceStoreError::Store( + affine_store::StoreError::DocNotFound(doc_id.to_string()), + )); + }; + let mut session = PageDocSession::new(doc_id, client_id)?; + let now_u64 = now_ms.max(0) as u64; + session.apply_remote_update_v1(&existing)?; + + let sv_before = session.encode_state_vector_v1()?; + if delete_len > 0 { + session.remove_text(block_id, "prop:text", utf16_index, delete_len, now_u64)?; + } + if !insert_text.is_empty() { + session.insert_text(block_id, "prop:text", utf16_index, insert_text, now_u64)?; + } + + let delta = session.encode_diff_v1(&sv_before)?; + let state_vector = session.encode_state_vector_v1()?; + let batch = [PendingDocUpdate { + doc_id: doc_id.to_string(), + update: delta.clone(), + }]; + let committed = self + .runtime + .block_on(self.storage.push_updates_batch(&batch, None, now_ms))?; + let timestamp_ms = committed + .first() + .map(|(_, ts)| naive_utc_to_millis(*ts)) + .unwrap_or(now_ms); + + Ok(OfflineEditResult { + update_bytes: delta, + state_vector, + timestamp_ms, + }) + } + + /// Compute the pending diff and state vector for `doc_id` against an optional remote state vector. + pub fn export_pending_diff( + &self, + doc_id: &str, + remote_state_vector: Option<&[u8]>, + ) -> Result, WorkspaceStoreError> { + let diff = self + .runtime + .block_on(self.storage.get_doc_diff(doc_id, remote_state_vector))?; + Ok(diff.map(|d| ExportedDocDiff { + doc_id: d.doc_id, + missing: d.missing, + state: d.state, + timestamp_ms: naive_utc_to_millis(d.timestamp), + })) + } + + /// Persist a remote V1 update atomically via `push_updates_batch` using `local_now_ms`, + /// advance `peer_clocks` using the authoritative server `remote_clock_ms`, and return + /// the compacted merged document binary. + pub fn apply_remote_update( + &self, + doc_id: &str, + update_bytes: &[u8], + peer: &str, + remote_clock_ms: i64, + local_now_ms: i64, + ) -> Result, WorkspaceStoreError> { + let batch = [PendingDocUpdate { + doc_id: doc_id.to_string(), + update: update_bytes.to_vec(), + }]; + let merged = self.runtime.block_on(async { + self.storage + .push_updates_batch(&batch, None, local_now_ms) + .await?; + let remote_clock = millis_to_naive_utc(remote_clock_ms); + self.storage + .set_peer_remote_clock(peer, doc_id, remote_clock) + .await?; + self.storage + .set_peer_pulled_remote_clock(peer, doc_id, remote_clock) + .await?; + let record = self.storage.get_doc(doc_id).await?; + Ok::>, StoreError>(record.map(|r| r.bin)) + })?; + Ok(merged.unwrap_or_default()) + } + + /// Run a non-blocking `PRAGMA wal_checkpoint(PASSIVE);` suitable for iOS background transitions. + pub fn checkpoint_passive(&self) -> Result<(), WorkspaceStoreError> { + let _ = self.runtime.block_on(self.storage.checkpoint_passive())?; + Ok(()) + } + + /// Flush the SQLite WAL journal into the main database file (`FULL`). + pub fn checkpoint(&self) -> Result<(), WorkspaceStoreError> { + self.runtime.block_on(self.storage.checkpoint())?; + Ok(()) + } + + /// Close the underlying SQLite connection pool cleanly. + pub fn close(self) { + let Self { + storage, runtime, .. + } = self; + runtime.block_on(storage.close()); + drop(storage); + drop(runtime); + } +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType}; + use sqlx::{Connection, sqlite::SqliteConnectOptions}; + + use super::*; + + fn unique_temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "affine-ios-s2-{label}-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn seed_page_with_paragraph(doc_id: &str, client_id: u64, text: &str) -> Vec { + let mut session = PageDocSession::new(doc_id, client_id).unwrap(); + session + .add_block( + "page-1", + BlockSpec::Page { + title: "iOS S2 Spec".into(), + }, + None, + None, + 1_000, + ) + .unwrap(); + session + .add_block( + "note-1", + BlockSpec::Note { + xywh: Some("[0,0,800,600]".into()), + }, + Some("page-1"), + None, + 1_001, + ) + .unwrap(); + session + .add_block( + "para-1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + }, + Some("note-1"), + None, + 1_002, + ) + .unwrap(); + session.encode_update_v1().unwrap() + } + + #[test] + fn f1_allowlist_fail_closed_blocks_missing_and_unlisted_local_workspaces() { + let docs = unique_temp_dir("f1"); + let alive_path = + resolve_ios_space_db_path(&docs, "workspace", "local", "ws-alive").unwrap(); + let deleted_path = + resolve_ios_space_db_path(&docs, "workspace", "local", "ws-deleted").unwrap(); + std::fs::create_dir_all(alive_path.parent().unwrap()).unwrap(); + std::fs::write(&alive_path, b"").unwrap(); + std::fs::write(&deleted_path, b"").unwrap(); + + let allowlist = vec!["ws-alive".to_string()]; + let mounted = resolve_allowlisted_local_workspaces(&docs, &allowlist).unwrap(); + assert_eq!(mounted, vec![("ws-alive".to_string(), alive_path)]); + + // Local workspace without allowlist (None) MUST fail closed before touching disk. + let err_none = IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-alive", None) + .err() + .unwrap(); + assert!(matches!( + err_none, + WorkspaceStoreError::WorkspaceNotAllowlisted(id) if id == "ws-alive" + )); + + // Attempting to open the deleted workspace DB must be rejected under allowlist enforcement. + let err = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-deleted", Some(&allowlist)) + .err() + .unwrap(); + assert!( + matches!(err, WorkspaceStoreError::WorkspaceNotAllowlisted(id) if id == "ws-deleted") + ); + + // Userspace and cloud SQLite DBs do not require local allowlist. + let userspace_ws = IosWorkspaceHandle::open( + &docs, + "userspace", + "https://app.affine.pro", + "user-42", + None, + ) + .unwrap(); + assert_eq!( + userspace_ws.db_path(), + docs.join("workspaces/userspace/https_app.affine.pro/user-42.db") + ); + userspace_ws.close(); + + let _ = std::fs::remove_dir_all(&docs); + } + + #[test] + fn offline_edit_split_remote_clock_and_passive_checkpoint_with_concurrent_reader() { + let docs = unique_temp_dir("offline-sync"); + let allowlist = vec!["ws-ios-1".to_string()]; + + let ws = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-ios-1", Some(&allowlist)) + .unwrap(); + let initial_bin = seed_page_with_paragraph("doc-1", 10, "Hello iOS"); + ws.apply_remote_update("doc-1", &initial_bin, "seed", 9_000, 10_000) + .unwrap(); + + let mut remote_peer = PageDocSession::new("doc-1", 20).unwrap(); + remote_peer.apply_remote_update_v1(&initial_bin).unwrap(); + let remote_sv_before = remote_peer.encode_state_vector_v1().unwrap(); + + let edit = ws + .edit_paragraph_text("doc-1", "para-1", 9, 0, "!", 11, 11_000) + .unwrap(); + assert!(!edit.update_bytes.is_empty()); + + let diff = ws + .export_pending_diff("doc-1", Some(&remote_sv_before)) + .unwrap() + .unwrap(); + assert!(!diff.missing.is_empty()); + remote_peer.apply_remote_update_v1(&diff.missing).unwrap(); + + let sv_remote = remote_peer.encode_state_vector_v1().unwrap(); + remote_peer + .insert_text("para-1", "prop:text", 10, " Sync", 12_000) + .unwrap(); + let remote_delta = remote_peer.encode_diff_v1(&sv_remote).unwrap(); + + // Device clock (99_000) is ahead of authoritative server remote clock (12_500). + let merged = ws + .apply_remote_update("doc-1", &remote_delta, "cloud", 12_500, 99_000) + .unwrap(); + assert!(!merged.is_empty()); + + // Verify peer_clocks recorded remote_clock_ms (12_500), not local_now_ms (99_000). + let recorded_remote = ws + .runtime + .block_on(ws.storage.get_peer_remote_clock("cloud", "doc-1")) + .unwrap() + .unwrap(); + assert_eq!(naive_utc_to_millis(recorded_remote.timestamp), 12_500); + + // Open an uncommitted concurrent read transaction and verify PASSIVE checkpoint does not block. + let mut reader = ws.runtime.block_on(async { + let mut conn = sqlx::SqliteConnection::connect_with( + &SqliteConnectOptions::new().filename(ws.db_path()), + ) + .await + .unwrap(); + sqlx::query("BEGIN;").execute(&mut conn).await.unwrap(); + let _ = sqlx::query("SELECT COUNT(*) FROM meta;") + .fetch_one(&mut conn) + .await + .unwrap(); + conn + }); + ws.checkpoint_passive().unwrap(); + ws.runtime.block_on(async { + sqlx::query("COMMIT;").execute(&mut reader).await.unwrap(); + reader.close().await.unwrap(); + }); + + ws.checkpoint().unwrap(); + ws.close(); + + let reopened = + IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-ios-1", Some(&allowlist)) + .unwrap(); + let snapshot_json = reopened + .read_page_snapshot_json("doc-1", 30) + .unwrap() + .unwrap(); + assert!( + snapshot_json.contains("Hello iOS! Sync"), + "snapshot_json={snapshot_json}" + ); + reopened.close(); + + let _ = std::fs::remove_dir_all(&docs); + } +} diff --git a/packages/frontend/hosts/ios/tests/IosHostS2SmokeTest.swift b/packages/frontend/hosts/ios/tests/IosHostS2SmokeTest.swift new file mode 100644 index 0000000000..b78d50076b --- /dev/null +++ b/packages/frontend/hosts/ios/tests/IosHostS2SmokeTest.swift @@ -0,0 +1,817 @@ +import Foundation + +final class InMemoryTokenPersistence: LegacyAuthTokenPersistence, @unchecked Sendable { + private let lock = NSLock() + private var storage: [String: Data] = [:] + + func readRawData(service: String, account: String) throws -> Data? { + lock.lock() + defer { lock.unlock() } + return storage["\(service)::\(account)"] + } + + func writeRawData(_ data: Data, service: String, account: String) throws { + lock.lock() + defer { lock.unlock() } + storage["\(service)::\(account)"] = data + } + + func deleteRawData(service: String, account: String) throws { + lock.lock() + defer { lock.unlock() } + storage.removeValue(forKey: "\(service)::\(account)") + } +} + +final class MockAuthURLProtocol: URLProtocol { + static let lock = NSLock() + static var requestCountByPath: [String: Int] = [:] + static var lastHeaders: [String: String] = [:] + static var handler: ((URLRequest) throws -> (Int, Data))? + + static func reset() { + lock.lock() + requestCountByPath = [:] + lastHeaders = [:] + handler = nil + lock.unlock() + } + + override class func canInit(with request: URLRequest) -> Bool { + true + } + + override class func canonicalRequest(for request: URLRequest) -> URLRequest { + request + } + + override func startLoading() { + let path = request.url?.path ?? "" + Self.lock.lock() + Self.requestCountByPath[path, default: 0] += 1 + Self.lastHeaders = request.allHTTPHeaderFields ?? [:] + let currentHandler = Self.handler + Self.lock.unlock() + + guard let currentHandler else { + client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) + return + } + DispatchQueue.global().async { + do { + let (status, data) = try currentHandler(self.request) + let response = HTTPURLResponse( + url: self.request.url!, + statusCode: status, + httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"] + )! + self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + self.client?.urlProtocol(self, didLoad: data) + self.client?.urlProtocolDidFinishLoading(self) + } catch { + self.client?.urlProtocol(self, didFailWithError: error) + } + } + } + + override func stopLoading() {} +} + +func require(_ condition: Bool, _ message: String) { + if !condition { + fputs("FAIL: \(message)\n", stderr) + exit(1) + } +} + +func makeMockSession() -> URLSession { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [MockAuthURLProtocol.self] + return URLSession(configuration: config) +} + +func makeTokenResponseJson(accessToken: String, refreshToken: String, expiresIn: Int = 3600) -> Data { + let json = """ + { + "tokenType": "Bearer", + "accessToken": "\(accessToken)", + "expiresIn": \(expiresIn), + "refreshToken": "\(refreshToken)", + "refreshExpiresAt": "2027-01-25T00:00:00.000Z", + "session": { + "id": "sess-1", + "absoluteExpiresAt": "2027-06-25T00:00:00.000Z" + } + } + """ + return Data(json.utf8) +} + +@main +struct IosHostS2SmokeTest { + static func main() async { + do { + try await testSingleFlightConcurrentRefreshCoalescesToOneRequest() + try await testRevokeDuringInFlightRefreshPreventsLateWriteBackAndClearsCookies() + try testFailClosedLocalWorkspaceAllowlist() + try await testSentinelMixedNoiseAndWriteBackWhitelistGuard() + try await testBackgroundPassiveCheckpointCoordinator() + testIdleFrameZeroDraw() + try await testAllowlistShrinkEvictsAndClosesWorkspaceAndPropagatesMountError() + try await testCorruptLocalWorkspacePreservesRawAndFullWhitelistRoundtrip() + try await testMultiBridgeInstancesShareSingleFlightAndMutationEpoch() + testDrawableUnavailablePreservesDirtyFlagForNextFrame() + try await testExplicitAllowlistDeletionSyncsRollbackWriteBackPlan() + try await testBatchMountContinuesValidWorkspacesAndPreservesPriorStateOnBadSnapshot() + try await testCloudLastWorkspacePreservedAcrossLocalAllowlistUpdate() + try await testPartialMountFailureGatesRollbackWriteBackUntilResolved() + print("ALL 14 SWIFT+RUST S2-IOS SMOKE TESTS PASSED") + } catch { + fputs("UNHANDLED ERROR: \(error)\n", stderr) + exit(1) + } + } + + /// 1. Three concurrent `validAccessToken` calls triggering refresh coalesce into 1 HTTP request. + static func testSingleFlightConcurrentRefreshCoalescesToOneRequest() async throws { + MockAuthURLProtocol.reset() + let persistence = InMemoryTokenPersistence() + let bridge = LegacyAuthBridge( + persistence: persistence, + clearWebKitCookies: false + ) + let endpoint = "https://app.affine.pro" + let expiredPair = LegacyStoredAuthTokenPair( + version: 1, + tokenType: "Bearer", + accessToken: "acc-old", + accessExpiresAt: Date(timeIntervalSinceNow: 10), + refreshToken: "ref-old", + refreshExpiresAt: "2027-01-25T00:00:00.000Z", + session: LegacyAuthSessionInfo(id: "sess-1", absoluteExpiresAt: "2027-06-25T00:00:00.000Z") + ) + try await bridge.writeTokenPair(expiredPair, for: endpoint) + + let releaseRefresh = DispatchSemaphore(value: 0) + let refreshEntered = DispatchSemaphore(value: 0) + MockAuthURLProtocol.handler = { req in + if req.url?.path == "/api/auth/session/refresh" { + refreshEntered.signal() + _ = releaseRefresh.wait(timeout: .now() + 2.0) + return (200, makeTokenResponseJson(accessToken: "acc-new-single-flight", refreshToken: "ref-new")) + } + return (404, Data()) + } + + let session = makeMockSession() + async let r1 = bridge.validAccessToken(for: endpoint, minValidity: 120, session: session) + async let r2 = bridge.validAccessToken(for: endpoint, minValidity: 120, session: session) + async let r3 = bridge.validAccessToken(for: endpoint, minValidity: 120, session: session) + + _ = refreshEntered.wait(timeout: .now() + 2.0) + try await Task.sleep(nanoseconds: 50_000_000) + releaseRefresh.signal() + + let results = try await [r1, r2, r3] + for item in results { + require(item?.accessToken == "acc-new-single-flight", "all 3 callers must receive rotated token") + } + MockAuthURLProtocol.lock.lock() + let refreshCalls = MockAuthURLProtocol.requestCountByPath["/api/auth/session/refresh", default: 0] + let clientKind = MockAuthURLProtocol.lastHeaders["x-affine-client-kind"] + let affineVersion = MockAuthURLProtocol.lastHeaders["x-affine-version"] + MockAuthURLProtocol.lock.unlock() + require(refreshCalls == 1, "expected exactly 1 refresh request, got \(refreshCalls)") + require(clientKind == "native", "expected x-affine-client-kind=native") + require(affineVersion == "0.27.5", "expected x-affine-version=0.27.5, got \(String(describing: affineVersion))") + print("PASS [1/14]: 3-way concurrent refresh coalesced to 1 HTTP call with native + 0.27.5 headers") + } + + /// 2. `revokeSession` while refresh is in flight prevents stale write-back and clears only matching cookies. + static func testRevokeDuringInFlightRefreshPreventsLateWriteBackAndClearsCookies() async throws { + MockAuthURLProtocol.reset() + let persistence = InMemoryTokenPersistence() + let cookies = HTTPCookieStorage.shared + let endpoint = "https://app.affine.pro" + if let authCookie = HTTPCookie(properties: [ + .domain: "app.affine.pro", + .path: "/", + .name: "affine_session", + .value: "s-123", + ]) { + cookies.setCookie(authCookie) + } + if let otherCookie = HTTPCookie(properties: [ + .domain: "other.example.com", + .path: "/", + .name: "affine_session", + .value: "keep-me", + ]) { + cookies.setCookie(otherCookie) + } + + let bridge = LegacyAuthBridge( + persistence: persistence, + cookieStorage: cookies, + clearWebKitCookies: false + ) + let expiredPair = LegacyStoredAuthTokenPair( + version: 1, + tokenType: "Bearer", + accessToken: "acc-old", + accessExpiresAt: Date(timeIntervalSinceNow: 10), + refreshToken: "ref-old", + refreshExpiresAt: "2027-01-25T00:00:00.000Z", + session: LegacyAuthSessionInfo(id: "sess-1", absoluteExpiresAt: "2027-06-25T00:00:00.000Z") + ) + try await bridge.writeTokenPair(expiredPair, for: endpoint) + + let refreshEntered = DispatchSemaphore(value: 0) + let releaseRefresh = DispatchSemaphore(value: 0) + MockAuthURLProtocol.handler = { req in + if req.url?.path == "/api/auth/session/refresh" { + refreshEntered.signal() + _ = releaseRefresh.wait(timeout: .now() + 2.0) + return (200, makeTokenResponseJson(accessToken: "acc-stale-late", refreshToken: "ref-stale")) + } + if req.url?.path == "/api/auth/session/revoke" { + return (200, Data("{\"ok\":true}".utf8)) + } + return (404, Data()) + } + + let session = makeMockSession() + let refreshTask = Task { + try await bridge.refreshSession(endpoint: endpoint, session: session) + } + _ = refreshEntered.wait(timeout: .now() + 2.0) + try await bridge.revokeSession(endpoint: endpoint, session: session) + releaseRefresh.signal() + + do { + _ = try await refreshTask.value + require(false, "late refresh must fail after revoke") + } catch { + // Expected cancellation / operationCancelled. + } + + let storedAfter = try await bridge.readTokenPair(for: endpoint) + require(storedAfter == nil, "late refresh must NOT resurrect Keychain token after revoke") + + let remainingAffine = cookies.cookies?.filter { $0.domain.contains("app.affine.pro") && $0.name == "affine_session" } ?? [] + let remainingOther = cookies.cookies?.filter { $0.domain.contains("other.example.com") && $0.name == "affine_session" } ?? [] + require(remainingAffine.isEmpty, "matching-domain auth cookie must be cleared") + require(remainingOther.count == 1, "unrelated-domain cookie must remain intact") + print("PASS [2/14]: revoke during in-flight refresh blocked stale Keychain write-back & cleared only matching cookies") + } + + /// 3. Local workspace open with nil allowlist or malformed JSON allowlist fails closed. + static func testFailClosedLocalWorkspaceAllowlist() throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-f1-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + do { + _ = try WorkspaceStorageBridge( + spaceType: "workspace", + peer: "local", + spaceId: "ws-deleted", + allowlistedLocalIds: nil, + documentsDirectory: tmpDir + ) + require(false, "nil allowlist must throw for local workspace") + } catch WorkspaceStorageBridgeError.localAllowlistRequired { + // Expected. + } + + let cNil = tmpDir.path.withCString { cDocs in + "workspace".withCString { cType in + "local".withCString { cPeer in + "ws-deleted".withCString { cSpace in + affine_ios_workspace_open(cDocs, cType, cPeer, cSpace, nil) + } + } + } + } + require(cNil == nil, "C-ABI nil allowlist must fail closed") + + let cBad = tmpDir.path.withCString { cDocs in + "workspace".withCString { cType in + "local".withCString { cPeer in + "ws-deleted".withCString { cSpace in + "{corrupt-json".withCString { cAllow in + affine_ios_workspace_open(cDocs, cType, cPeer, cSpace, cAllow) + } + } + } + } + } + require(cBad == nil, "C-ABI malformed allowlist JSON must fail closed") + print("PASS [3/14]: local workspace nil & malformed allowlist rejected fail-closed") + } + + /// 4. Unified sentinel accepts mixed whitelisted + noise keys and rejects non-whitelisted write-back/remove. + @MainActor + static func testSentinelMixedNoiseAndWriteBackWhitelistGuard() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-sentinel-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let mixed = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 2, + keys: ["__cap_init__", "affine-local-workspace"], + entries: ["affine-local-workspace": "[\"ws-1\"]"], + idbAccessCount: 0 + ) + let disp = try coordinator.applySnapshot(mixed) + require(disp.status == "existing_user", "mixed whitelisted + noise must classify as existing_user") + require(disp.state.localWorkspaceIds == ["ws-1"], "expected ws-1 imported") + coordinator.closeAll() + + let freshNoise = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 1, + keys: ["__cap_init__"], + entries: [:], + idbAccessCount: 0 + ) + let freshDisp = try coordinator.applySnapshot(freshNoise) + require(freshDisp.status == "fresh_install", "noise-only snapshot must classify as fresh_install") + + do { + try LegacyLocalStorageProbe.validateWriteBackKeys(set: [:], remove: ["unrelated.preference"]) + require(false, "non-whitelisted remove key must be rejected") + } catch LegacyLocalStorageProbeError.keyNotWhitelisted(let k) { + require(k == "unrelated.preference", "unexpected rejected key \(k)") + } + + do { + try LegacyLocalStorageProbe.validateWriteBackKeys(set: [:], remove: ["affine-local-workspace"]) + require(false, "removing affine-local-workspace must be rejected") + } catch LegacyLocalStorageProbeError.protectedKeyRemovalForbidden { + // Expected. + } + print("PASS [4/14]: unified sentinel handled mixed/noise snapshots and blocked non-whitelisted write-back/remove") + } + + /// 5. Background transition triggers non-blocking PASSIVE WAL checkpoint. + @MainActor + static func testBackgroundPassiveCheckpointCoordinator() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-bg-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let snap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 1, + keys: ["affine-local-workspace"], + entries: ["affine-local-workspace": "[\"ws-bg\"]"], + idbAccessCount: 0 + ) + _ = try coordinator.applySnapshot(snap) + require(coordinator.workspace(id: "ws-bg") != nil, "allowlisted workspace must mount") + require(coordinator.checkpointAllPassive(), "PASSIVE WAL checkpoint must succeed") + coordinator.closeAll() + print("PASS [5/14]: background PASSIVE WAL checkpoint succeeded across mounted workspace") + } + + /// 6. Idle second frame returns 0 (skip GPU draw) until invalidated. + static func testIdleFrameZeroDraw() { + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + require(host != nil, "host create failed") + defer { affine_ios_host_destroy(host) } + + let first = affine_ios_host_render_frame(host, 1.0) + require(first != 0, "first dirty frame must draw") + let second = affine_ios_host_render_frame(host, 1.016) + require(second == 0, "idle second frame must return 0 to skip Metal draw") + affine_ios_host_request_frame(host) + let third = affine_ios_host_render_frame(host, 1.033) + require(third != 0, "requested frame must draw again") + print("PASS [6/14]: idle second render_frame returned 0 (zero GPU submission)") + } + + /// 7. Shrinking/clearing allowlist ["A"] -> [] without closeAll() evicts & closes A; mount errors propagate. + @MainActor + static func testAllowlistShrinkEvictsAndClosesWorkspaceAndPropagatesMountError() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-evict-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + try coordinator.applyLocalWorkspaceAllowlist(["ws-a"]) + guard let heldBridge = coordinator.workspace(id: "ws-a") else { + require(false, "ws-a must be mounted") + return + } + require(heldBridge.checkpointPassive(), "ws-a should be active before shrink") + + // Apply empty allowlist WITHOUT calling closeAll(): ws-a must be closed and evicted. + try coordinator.applyLocalWorkspaceAllowlist([]) + require(coordinator.workspace(id: "ws-a") == nil, "ws-a must be evicted from activeWorkspaces") + require(!heldBridge.checkpointPassive(), "evicted bridge handle must be closed and reject calls") + let staleWrite = heldBridge.applyRemoteUpdate( + docId: "doc-1", + update: Data([0, 0]), + peer: "cloud", + remoteClockMs: 100, + localNowMs: 100 + ) + require(staleWrite == nil, "evicted bridge must reject writes") + + // Mount failure (invalid traversal spaceId) must throw upward instead of being swallowed by try?. + do { + try coordinator.applyLocalWorkspaceAllowlist(["../escape"]) + require(false, "invalid workspace ID mount failure must throw") + } catch { + // Expected propagated error. + } + print("PASS [7/14]: allowlist shrink evicted & closed old handle and mount failure propagated") + } + + /// 8. Corrupt affine-local-workspace preserves raw string as existing_user (0 local mounts) and full whitelist roundtrips. + @MainActor + static func testCorruptLocalWorkspacePreservesRawAndFullWhitelistRoundtrip() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-corrupt-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let corruptSnap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 6, + keys: [ + "affine-local-workspace", + "affine-settings", + "global-cache:i18n_lng", + "global-state:serverConfig:srv-1", + "last_workspace_id", + "theme", + ], + entries: [ + "affine-local-workspace": "{broken", + "affine-settings": "{broken-aux", + "global-cache:i18n_lng": "\"zh-Hans\"", + "global-state:serverConfig:srv-1": "{\"serverName\":\"Self\"}", + "last_workspace_id": "ws-prev", + "theme": "dark", + ], + idbAccessCount: 0 + ) + let disp = try coordinator.applySnapshot(corruptSnap) + require(disp.status == "existing_user", "corrupt affine-local-workspace must classify as existing_user") + require(disp.state.localWorkspaceIds.isEmpty, "corrupt affine-local-workspace must mount 0 workspaces") + require(coordinator.allowlistedLocalIds.isEmpty, "corrupt affine-local-workspace must keep allowlist empty") + + let plan = try coordinator.buildRollbackWriteBackPlan() + require(plan.set["affine-local-workspace"] == "{broken", "corrupt affine-local-workspace must be preserved verbatim") + require(plan.set["affine-settings"] == "{broken-aux", "corrupt auxiliary key must be preserved verbatim") + require(plan.set["global-state:serverConfig:srv-1"] == "{\"serverName\":\"Self\"}", "serverConfig must roundtrip") + require(plan.set["theme"] == "dark", "theme must roundtrip") + require(plan.set["last_workspace_id"] == "ws-prev", "last_workspace_id must roundtrip") + require(plan.set["global-cache:i18n_lng"] == "\"zh-Hans\"", "i18n_lng must roundtrip") + print("PASS [8/14]: corrupt affine-local-workspace preserved verbatim as existing_user & full whitelist roundtripped") + } + + /// 9. Two distinct LegacyAuthBridge instances sharing the same persistence share single-flight & mutationEpochs. + static func testMultiBridgeInstancesShareSingleFlightAndMutationEpoch() async throws { + MockAuthURLProtocol.reset() + let sharedStore = InMemoryTokenPersistence() + let bridgeA = LegacyAuthBridge(persistence: sharedStore, clearWebKitCookies: false) + let bridgeB = LegacyAuthBridge(persistence: sharedStore, clearWebKitCookies: false) + let endpoint = "https://app.affine.pro" + + let expiredPair = LegacyStoredAuthTokenPair( + version: 1, + tokenType: "Bearer", + accessToken: "acc-old", + accessExpiresAt: Date(timeIntervalSinceNow: 10), + refreshToken: "ref-old", + refreshExpiresAt: "2027-01-25T00:00:00.000Z", + session: LegacyAuthSessionInfo(id: "sess-1", absoluteExpiresAt: "2027-06-25T00:00:00.000Z") + ) + try await bridgeA.writeTokenPair(expiredPair, for: endpoint) + + let entered1 = DispatchSemaphore(value: 0) + let release1 = DispatchSemaphore(value: 0) + MockAuthURLProtocol.handler = { req in + if req.url?.path == "/api/auth/session/refresh" { + entered1.signal() + _ = release1.wait(timeout: .now() + 2.0) + return (200, makeTokenResponseJson(accessToken: "acc-shared-sf", refreshToken: "ref-shared-sf")) + } + return (404, Data()) + } + let session = makeMockSession() + async let ra = bridgeA.refreshSession(endpoint: endpoint, session: session) + async let rb = bridgeB.refreshSession(endpoint: endpoint, session: session) + _ = entered1.wait(timeout: .now() + 2.0) + try await Task.sleep(nanoseconds: 50_000_000) + release1.signal() + let (pa, pb) = try await (ra, rb) + require(pa.accessToken == "acc-shared-sf" && pb.accessToken == "acc-shared-sf", "both bridges must get rotated token") + MockAuthURLProtocol.lock.lock() + let sfCalls = MockAuthURLProtocol.requestCountByPath["/api/auth/session/refresh", default: 0] + MockAuthURLProtocol.lock.unlock() + require(sfCalls == 1, "two bridges sharing persistence must coalesce to 1 refresh, got \(sfCalls)") + + // Now bridgeA starts refresh while bridgeB calls clearSession -> late response must NOT resurrect token. + MockAuthURLProtocol.reset() + try await bridgeA.writeTokenPair(expiredPair, for: endpoint) + let entered2 = DispatchSemaphore(value: 0) + let release2 = DispatchSemaphore(value: 0) + MockAuthURLProtocol.handler = { req in + if req.url?.path == "/api/auth/session/refresh" { + entered2.signal() + _ = release2.wait(timeout: .now() + 2.0) + return (200, makeTokenResponseJson(accessToken: "acc-zombie", refreshToken: "ref-zombie")) + } + return (404, Data()) + } + let taskA = Task { + try await bridgeA.refreshSession(endpoint: endpoint, session: session) + } + _ = entered2.wait(timeout: .now() + 2.0) + try await bridgeB.clearSession(for: endpoint) + release2.signal() + do { + _ = try await taskA.value + require(false, "late refresh on bridgeA must be rejected after bridgeB.clearSession") + } catch { + // Expected cancellation. + } + let afterClear = try await bridgeA.readTokenPair(for: endpoint) + require(afterClear == nil, "credentials must stay cleared after cross-instance clearSession") + + // Historical 0.27.5 unbracketed IPv6 Keychain account ("https://::1:8443") must be read + // and refreshed over a valid bracketed HTTP URL ("https://[::1]:8443/api/auth/session/refresh"). + let ipv6Endpoint = "https://[::1]:8443" + let legacyAccountKey = "https://::1:8443" + let legacyData = try JSONEncoder().encode(expiredPair) + try sharedStore.writeRawData( + legacyData, + service: LegacyAuthBridge.keychainService, + account: legacyAccountKey + ) + let loadedLegacyIpv6 = try await bridgeA.readTokenPair(for: ipv6Endpoint) + require( + loadedLegacyIpv6?.refreshToken == expiredPair.refreshToken, + "historical unbracketed IPv6 Keychain entry must load for bracketed endpoint" + ) + var seenIpv6Url: String? + MockAuthURLProtocol.reset() + MockAuthURLProtocol.handler = { req in + seenIpv6Url = req.url?.absoluteString + let body = """ + {"tokenType":"Bearer","accessToken":"acc-ipv6-new","expiresIn":3600,"refreshToken":"ref-ipv6-new","refreshExpiresAt":"2026-12-25T10:00:00Z","session":{"id":"sess-ipv6","absoluteExpiresAt":"2027-05-25T10:00:00Z"}} + """ + return (200, Data(body.utf8)) + } + let refreshedIpv6 = try await bridgeA.refreshSession(endpoint: ipv6Endpoint, session: session) + require(refreshedIpv6.accessToken == "acc-ipv6-new", "IPv6 refresh must return new access token") + require( + seenIpv6Url == "https://[::1]:8443/api/auth/session/refresh", + "IPv6 refresh HTTP URL must stay bracketed, got \(String(describing: seenIpv6Url))" + ) + + // 0.27.5 compressed unbracketed IPv6 Keychain account ("https://2001:db8::1:8443") must also + // load when the caller passes expanded IPv6 form, and refresh over compressed bracketed HTTP URL. + let expandedIpv6Endpoint = "https://[2001:0db8:0000:0000:0000:0000:0000:0001]:8443" + let legacyCompressedAccountKey = "https://2001:db8::1:8443" + try sharedStore.writeRawData( + legacyData, + service: LegacyAuthBridge.keychainService, + account: legacyCompressedAccountKey + ) + let loadedExpandedIpv6 = try await bridgeA.readTokenPair(for: expandedIpv6Endpoint) + require( + loadedExpandedIpv6?.refreshToken == expiredPair.refreshToken, + "0.27.5 compressed unbracketed IPv6 Keychain entry must load for expanded IPv6 endpoint" + ) + var seenExpandedIpv6Url: String? + MockAuthURLProtocol.reset() + MockAuthURLProtocol.handler = { req in + seenExpandedIpv6Url = req.url?.absoluteString + let body = """ + {"tokenType":"Bearer","accessToken":"acc-ipv6-exp-new","expiresIn":3600,"refreshToken":"ref-ipv6-exp-new","refreshExpiresAt":"2026-12-25T10:00:00Z","session":{"id":"sess-ipv6-exp","absoluteExpiresAt":"2027-05-25T10:00:00Z"}} + """ + return (200, Data(body.utf8)) + } + let refreshedExpandedIpv6 = try await bridgeA.refreshSession( + endpoint: expandedIpv6Endpoint, + session: session + ) + require( + refreshedExpandedIpv6.accessToken == "acc-ipv6-exp-new", + "expanded IPv6 refresh must return new access token" + ) + require( + seenExpandedIpv6Url == "https://[2001:db8::1]:8443/api/auth/session/refresh", + "expanded IPv6 refresh HTTP URL must be compressed bracketed, got \(String(describing: seenExpandedIpv6Url))" + ) + print("PASS [9/14]: multi-instance LegacyAuthBridge shared single-flight, mutationEpochs & IPv6 legacy Keychain upgrade") + } + + /// 10. Frame 1 drawable unavailable preserves dirty=true; Frame 2 with no new input renders & clears dirty. + static func testDrawableUnavailablePreservesDirtyFlagForNextFrame() { + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + require(host != nil, "host create failed") + defer { affine_ios_host_destroy(host) } + + // Frame 1: host is dirty, but nextDrawable() returns nil -> do NOT consume dirty! + require(affine_ios_host_is_dirty(host), "fresh host must start dirty") + let drawableFrame1Available = false + if affine_ios_host_is_dirty(host) && drawableFrame1Available { + _ = affine_ios_host_render_frame(host, 1.0) + } + require(affine_ios_host_is_dirty(host), "dirty must remain true when drawable was unavailable") + + // Frame 2: no new input, drawable now available -> renders and consumes dirty. + let drawableFrame2Available = true + var frame2Rgba: UInt32 = 0 + if affine_ios_host_is_dirty(host) && drawableFrame2Available { + frame2Rgba = affine_ios_host_render_frame(host, 1.016) + } + require(frame2Rgba != 0, "Frame 2 must render once drawable becomes available") + require(!affine_ios_host_is_dirty(host), "dirty must be false after Frame 2 commits") + require(affine_ios_host_render_frame(host, 1.033) == 0, "Frame 3 idle must return 0") + print("PASS [10/14]: drawable unavailable preserved dirty for Frame 2 render") + } + + /// 11. Explicit allowlist deletion after import updates rollback write-back plan (F1 zero resurrection). + @MainActor + static func testExplicitAllowlistDeletionSyncsRollbackWriteBackPlan() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-r5-del-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let snap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 4, + keys: ["affine-local-workspace", "last_workspace_id", "last_workspace_flavour", "theme"], + entries: [ + "affine-local-workspace": "[\"ws-a\"]", + "last_workspace_id": "ws-a", + "last_workspace_flavour": "local", + "theme": "dark", + ], + idbAccessCount: 0 + ) + _ = try coordinator.applySnapshot(snap) + require(coordinator.workspace(id: "ws-a") != nil, "ws-a must mount on initial import") + + // Explicitly delete ws-a via allowlist update: rollback plan must emit "[]" (not stale ["ws-a"]). + try coordinator.applyLocalWorkspaceAllowlist([]) + require(coordinator.workspace(id: "ws-a") == nil, "ws-a must be evicted") + let plan = try coordinator.buildRollbackWriteBackPlan() + require(plan.set["affine-local-workspace"] == "[]", "rollback plan must write [] after explicit deletion, got \(String(describing: plan.set["affine-local-workspace"]))") + require(plan.set["theme"] == "dark", "other whitelisted keys must stay preserved") + require(plan.remove.contains("last_workspace_id"), "deleted last_workspace_id must be removed") + require(plan.remove.contains("last_workspace_flavour"), "deleted last_workspace_flavour must be removed") + print("PASS [11/14]: explicit allowlist deletion synced importedStateJson & rollback plan emitted []") + } + + /// 12. Batch mount with partial failure mounts all valid workspaces and throws summarized failures; + /// invalid snapshot never publishes half-baked importedStateJson. + @MainActor + static func testBatchMountContinuesValidWorkspacesAndPreservesPriorStateOnBadSnapshot() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-r5-batch-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + do { + try coordinator.applyLocalWorkspaceAllowlist(["ws-b", "../bad", "ws-c"]) + require(false, "batch with ../bad must throw mountFailures") + } catch HostBootstrapError.mountFailures(let failed) { + require(failed == ["../bad"], "expected failed=[\"../bad\"], got \(failed)") + } + require(coordinator.workspace(id: "ws-b") != nil, "ws-b must still mount despite ../bad failure") + require(coordinator.workspace(id: "ws-c") != nil, "ws-c must still mount despite ../bad failure") + + // Invalid sentinel snapshot must throw without clobbering state or publishing half-baked JSON. + let badSnap = LegacyLocalStorageSnapshot( + origin: "about:blank", + length: 0, + keys: [], + entries: [:], + idbAccessCount: 0 + ) + do { + _ = try coordinator.applySnapshot(badSnap) + require(false, "invalid snapshot must throw") + } catch HostBootstrapError.invalidSentinelSnapshot { + // Expected. + } + require(coordinator.importedStateJson == nil, "failed snapshot must not publish importedStateJson") + coordinator.closeAll() + print("PASS [12/14]: batch mount mounted valid B & C while reporting ../bad, and bad snapshot published no state") + } + + /// 13. Cloud last_workspace_id / last_workspace_flavour stay intact when updating local allowlist. + @MainActor + static func testCloudLastWorkspacePreservedAcrossLocalAllowlistUpdate() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-r6-cloud-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let snap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 3, + keys: ["affine-local-workspace", "last_workspace_id", "last_workspace_flavour"], + entries: [ + "affine-local-workspace": "[\"ws-a\"]", + "last_workspace_id": "cloud-C", + "last_workspace_flavour": "affine-cloud", + ], + idbAccessCount: 0 + ) + _ = try coordinator.applySnapshot(snap) + + // No-op allowlist refresh keeps cloud last_workspace_id & flavour intact. + try coordinator.applyLocalWorkspaceAllowlist(["ws-a"]) + let planSame = try coordinator.buildRollbackWriteBackPlan() + require(planSame.set["last_workspace_id"] == "cloud-C", "cloud last_workspace_id must stay in set on same allowlist") + require(planSame.set["last_workspace_flavour"] == "affine-cloud", "cloud last_workspace_flavour must stay in set on same allowlist") + require(!planSame.remove.contains("last_workspace_id"), "cloud last_workspace_id must not be removed") + require(!planSame.remove.contains("last_workspace_flavour"), "cloud last_workspace_flavour must not be removed") + + // Clearing local workspaces removes ws-a but must NOT clear cloud-C. + try coordinator.applyLocalWorkspaceAllowlist([]) + let planEmpty = try coordinator.buildRollbackWriteBackPlan() + require(planEmpty.set["affine-local-workspace"] == "[]", "local allowlist must write []") + require(planEmpty.set["last_workspace_id"] == "cloud-C", "cloud last_workspace_id must stay in set after clearing local allowlist") + require(planEmpty.set["last_workspace_flavour"] == "affine-cloud", "cloud last_workspace_flavour must stay in set after clearing local allowlist") + require(!planEmpty.remove.contains("last_workspace_id"), "cloud last_workspace_id must not be removed after clearing local allowlist") + require(!planEmpty.remove.contains("last_workspace_flavour"), "cloud last_workspace_flavour must not be removed after clearing local allowlist") + + // Same-ID workspace promoted from local ("ws-same") to affine-cloud ("ws-same" / "affine-cloud"): + // deleting the local copy must preserve the cloud last_workspace_id & flavour. + let sameIdSnap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 3, + keys: ["affine-local-workspace", "last_workspace_id", "last_workspace_flavour"], + entries: [ + "affine-local-workspace": "[\"ws-same\"]", + "last_workspace_id": "ws-same", + "last_workspace_flavour": "affine-cloud", + ], + idbAccessCount: 0 + ) + _ = try coordinator.applySnapshot(sameIdSnap) + try coordinator.applyLocalWorkspaceAllowlist([]) + let planSameId = try coordinator.buildRollbackWriteBackPlan() + require(planSameId.set["last_workspace_id"] == "ws-same", "same-ID affine-cloud workspace must survive local copy removal") + require(planSameId.set["last_workspace_flavour"] == "affine-cloud", "same-ID affine-cloud flavour must survive local copy removal") + coordinator.closeAll() + print("PASS [13/14]: cloud last_workspace_id & flavour preserved across local allowlist updates (including same-ID promotion)") + } + + /// 14. Partial mount failures block buildRollbackWriteBackPlan() until allowlist is reconciled cleanly. + @MainActor + static func testPartialMountFailureGatesRollbackWriteBackUntilResolved() async throws { + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s2-ios-swift-r6-gate-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDir) + let partialSnap = LegacyLocalStorageSnapshot( + origin: "capacitor://localhost", + length: 1, + keys: ["affine-local-workspace"], + entries: ["affine-local-workspace": "[\"ws-b\",\"../bad\",\"ws-c\"]"], + idbAccessCount: 0 + ) + do { + _ = try coordinator.applySnapshot(partialSnap) + require(false, "applySnapshot with ../bad must throw mountFailures") + } catch HostBootstrapError.mountFailures(let failed) { + require(failed == ["../bad"], "expected failed=[\"../bad\"], got \(failed)") + } + require(coordinator.workspace(id: "ws-b") != nil, "ws-b must be mounted") + require(coordinator.workspace(id: "ws-c") != nil, "ws-c must be mounted") + require(coordinator.lastFailedMountIds == ["../bad"], "lastFailedMountIds must record ../bad") + + // Rollback write-back must be blocked while mount failures remain unresolved. + do { + _ = try coordinator.buildRollbackWriteBackPlan() + require(false, "buildRollbackWriteBackPlan must throw while lastFailedMountIds is non-empty") + } catch HostBootstrapError.mountFailures(let failed) { + require(failed == ["../bad"], "expected rollback gate failed=[\"../bad\"], got \(failed)") + } + + // Reconciling allowlist to valid workspaces clears lastFailedMountIds and unblocks rollback planning. + try coordinator.applyLocalWorkspaceAllowlist(["ws-b", "ws-c"]) + require(coordinator.lastFailedMountIds.isEmpty, "lastFailedMountIds must clear after clean reconcile") + let plan = try coordinator.buildRollbackWriteBackPlan() + require(plan.set["affine-local-workspace"] == "[\"ws-b\",\"ws-c\"]", "reconciled rollback plan must emit [\"ws-b\",\"ws-c\"], got \(String(describing: plan.set["affine-local-workspace"]))") + coordinator.closeAll() + print("PASS [14/14]: partial mount failure gated rollback write-back until allowlist resolved") + } +} diff --git a/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift new file mode 100644 index 0000000000..d33876bba5 --- /dev/null +++ b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift @@ -0,0 +1,2038 @@ +import CoreFoundation +import CoreGraphics +import Foundation +import PDFKit +import SQLite3 +import UIKit +import WebKit + +/// Monotonic smoke clock. Each log line shows the time since the first line +/// and the time since the previous line, then flushes stdout. +nonisolated(unsafe) private var smokeClockStart: TimeInterval? +nonisolated(unsafe) private var smokeClockLast: TimeInterval = 0 + +func smokeLog(_ message: String) { + let now = ProcessInfo.processInfo.systemUptime + let start = smokeClockStart ?? now + if smokeClockStart == nil { + smokeClockStart = now + smokeClockLast = now + } + let sinceStartMs = Int(((now - start) * 1000).rounded()) + let elapsedMs = Int(((now - smokeClockLast) * 1000).rounded()) + smokeClockLast = now + print("[t=\(sinceStartMs)ms elapsed_ms=\(elapsedMs)] \(message)") + fflush(stdout) +} + +func requireS3(_ condition: Bool, _ message: String) { + if !condition { + fputs("FAIL: \(message)\n", stderr) + smokeLog("FAIL: \(message)") + fflush(stderr) + _exit(1) + } +} + +/// Build a valid 4-page PDF 1.4 document with exact quadrant colors: +/// - Page 0: Normal 200x300 MediaBox [0 0 200 300] +/// - Page 1: /Rotate 90 on 200x300 (displayed size 300x200) +/// - Page 2: Non-zero MediaBox origin [100 100 300 400] (size 200x300) +/// - Page 3: CropBox top-right quarter [100 150 200 300] (size 100x150, pure yellow) +func buildFourPageGeometryTestPdf() -> Data { + func quadrantStream(originX: Int, originY: Int) -> String { + let x0 = originX + let x1 = originX + 100 + let y0 = originY + let y1 = originY + 150 + // Bottom-left: Red, Bottom-right: Green, Top-left: Blue, Top-right: Yellow + return """ + 1 0 0 rg \(x0) \(y0) 100 150 re f + 0 1 0 rg \(x1) \(y0) 100 150 re f + 0 0 1 rg \(x0) \(y1) 100 150 re f + 1 1 0 rg \(x1) \(y1) 100 150 re f + """ + } + + let s0 = quadrantStream(originX: 0, originY: 0) + let s1 = quadrantStream(originX: 0, originY: 0) + let s2 = quadrantStream(originX: 100, originY: 100) + let s3 = quadrantStream(originX: 0, originY: 0) + + let objects: [String] = [ + "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", + "2 0 obj\n<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>\nendobj\n", + "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Contents 4 0 R >>\nendobj\n", + "4 0 obj\n<< /Length \(s0.utf8.count) >>\nstream\n\(s0)\nendstream\nendobj\n", + "5 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Rotate 90 /Contents 6 0 R >>\nendobj\n", + "6 0 obj\n<< /Length \(s1.utf8.count) >>\nstream\n\(s1)\nendstream\nendobj\n", + "7 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [100 100 300 400] /Contents 8 0 R >>\nendobj\n", + "8 0 obj\n<< /Length \(s2.utf8.count) >>\nstream\n\(s2)\nendstream\nendobj\n", + "9 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /CropBox [100 150 200 300] /Contents 10 0 R >>\nendobj\n", + "10 0 obj\n<< /Length \(s3.utf8.count) >>\nstream\n\(s3)\nendstream\nendobj\n", + ] + + var pdf = "%PDF-1.4\n" + var offsets: [Int] = [0] + for obj in objects { + offsets.append(pdf.utf8.count) + pdf += obj + } + let xrefStart = pdf.utf8.count + pdf += "xref\n0 \(objects.count + 1)\n" + pdf += "0000000000 65535 f \n" + for off in offsets.dropFirst() { + pdf += String(format: "%010d 00000 n \n", off) + } + pdf += "trailer\n<< /Size \(objects.count + 1) /Root 1 0 R >>\nstartxref\n\(xrefStart)\n%%EOF\n" + return Data(pdf.utf8) +} + +func pixelAt(_ rgba: Data, width: Int, x: Int, y: Int) -> (UInt8, UInt8, UInt8, UInt8) { + let base = (y * width + x) * 4 + return rgba.withUnsafeBytes { raw in + let bytes = raw.bindMemory(to: UInt8.self) + return (bytes[base], bytes[base + 1], bytes[base + 2], bytes[base + 3]) + } +} + +func assertColor(_ px: (UInt8, UInt8, UInt8, UInt8), r: Bool, g: Bool, b: Bool, _ label: String) { + let okR = r ? px.0 > 200 : px.0 < 55 + let okG = g ? px.1 > 200 : px.1 < 55 + let okB = b ? px.2 > 200 : px.2 < 55 + requireS3(okR && okG && okB && px.3 == 255, "\(label): unexpected RGBA \(px)") +} + +@main +struct IosHostS3SmokeTest { + @MainActor + static func main() { + DispatchQueue.main.async { + Task { @MainActor in + await runSmokeTests() + } + } + CFRunLoopRun() + requireS3(false, "The main run loop stopped before the smoke tests ended") + } + + @MainActor + private static func runSmokeTests() async { + do { + smokeLog("START [1/8]: PDFKit geometry and guards") + try testPdfKitFourPageGeometryAndGuards() + smokeLog("START [2/8]: touch ownership and readonly positions pid=\(getpid())") + testTouchOwnershipPartitionAndReadonlyDocPositions() + smokeLog("START [3/8]: keyboard avoidance") + testKeyboardAvoidancePerFrameSlideOverAndBackgroundResume() + smokeLog("START [4/8]: haptics bridge") + testHapticsBridgeDispatchAndBoundedHistory() + smokeLog("START [5/8]: MetalHostViewController end to end") + testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu() + smokeLog("START [6/8]: native GPU editor mount and IME") + try await testS6NativeEditorMountImeAndStageOneReadonly() + smokeLog("START [7/8]: WKWebView and SQLite upgrade drill") + try await test0275SameSignatureWebViewAndSqliteUpgradeRollbackDrill() + smokeLog("START [8/8]: mobile shell root routes, UITextInput, Search, back, and SQLite reopen") + try testMobileShellRootRoutesTextInputSearchBackAndSqliteReopen() + smokeLog("ALL 8 SWIFT+RUST IOS HOST SMOKE TESTS PASSED") + fflush(stderr) + _exit(0) + } catch { + fputs("UNHANDLED ERROR: \(error)\n", stderr) + smokeLog("UNHANDLED ERROR: \(error)") + fflush(stderr) + _exit(1) + } + } + + /// 1. Real PDFKit 4-page geometry (Normal, /Rotate 90, non-zero MediaBox, CropBox), + /// URL scheme guard, 64-bit overflow guard, and zero-copy C-ABI provider. + static func testPdfKitFourPageGeometryAndGuards() throws { + let pdfBytes = buildFourPageGeometryTestPdf() + let bridge = PdfRendererBridge() + + let handle = try bridge.open(data: pdfBytes) + requireS3(handle.pageCount == 4, "expected pageCount == 4, got \(handle.pageCount)") + + // Page 0: Normal 200x300 (top-left Blue, top-right Yellow, bottom-left Red, bottom-right Green). + let size0 = try bridge.pageSizePoints(of: handle, pageIndex: 0) + requireS3(abs(size0.width - 200) < 0.5 && abs(size0.height - 300) < 0.5, "page 0 size \(size0)") + let p0 = try bridge.renderPageRgba8(of: handle, pageIndex: 0, targetWidthPx: 100, targetHeightPx: 150) + assertColor(pixelAt(p0.rgba8, width: 100, x: 25, y: 37), r: false, g: false, b: true, "page0 top-left blue") + assertColor(pixelAt(p0.rgba8, width: 100, x: 75, y: 37), r: true, g: true, b: false, "page0 top-right yellow") + assertColor(pixelAt(p0.rgba8, width: 100, x: 25, y: 112), r: true, g: false, b: false, "page0 bottom-left red") + assertColor(pixelAt(p0.rgba8, width: 100, x: 75, y: 112), r: false, g: true, b: false, "page0 bottom-right green") + + // Page 1: /Rotate 90 -> displayed size 300x200; 90 deg CW: + // top-left=Red, top-right=Blue, bottom-left=Green, bottom-right=Yellow. + let size1 = try bridge.pageSizePoints(of: handle, pageIndex: 1) + requireS3(abs(size1.width - 300) < 0.5 && abs(size1.height - 200) < 0.5, "page 1 rotated size \(size1)") + let p1 = try bridge.renderPageRgba8(of: handle, pageIndex: 1, targetWidthPx: 150, targetHeightPx: 100) + assertColor(pixelAt(p1.rgba8, width: 150, x: 37, y: 25), r: true, g: false, b: false, "page1 rotated top-left red") + assertColor(pixelAt(p1.rgba8, width: 150, x: 112, y: 25), r: false, g: false, b: true, "page1 rotated top-right blue") + assertColor(pixelAt(p1.rgba8, width: 150, x: 37, y: 75), r: false, g: true, b: false, "page1 rotated bottom-left green") + assertColor(pixelAt(p1.rgba8, width: 150, x: 112, y: 75), r: true, g: true, b: false, "page1 rotated bottom-right yellow") + + // Page 2: Non-zero MediaBox origin (100, 100) -> all 4 quadrants must match Page 0 (not all-white!). + let size2 = try bridge.pageSizePoints(of: handle, pageIndex: 2) + requireS3(abs(size2.width - 200) < 0.5 && abs(size2.height - 300) < 0.5, "page 2 size \(size2)") + let p2 = try bridge.renderPageRgba8(of: handle, pageIndex: 2, targetWidthPx: 100, targetHeightPx: 150) + assertColor(pixelAt(p2.rgba8, width: 100, x: 25, y: 37), r: false, g: false, b: true, "page2 origin top-left blue") + assertColor(pixelAt(p2.rgba8, width: 100, x: 75, y: 37), r: true, g: true, b: false, "page2 origin top-right yellow") + assertColor(pixelAt(p2.rgba8, width: 100, x: 25, y: 112), r: true, g: false, b: false, "page2 origin bottom-left red") + assertColor(pixelAt(p2.rgba8, width: 100, x: 75, y: 112), r: false, g: true, b: false, "page2 origin bottom-right green") + + // Page 3: CropBox [100 150 200 300] -> size 100x150, entire page is yellow. + let size3 = try bridge.pageSizePoints(of: handle, pageIndex: 3) + requireS3(abs(size3.width - 100) < 0.5 && abs(size3.height - 150) < 0.5, "page 3 cropBox size \(size3)") + let p3 = try bridge.renderPageRgba8(of: handle, pageIndex: 3, targetWidthPx: 60, targetHeightPx: 90) + assertColor(pixelAt(p3.rgba8, width: 60, x: 15, y: 20), r: true, g: true, b: false, "page3 cropBox top-left yellow") + assertColor(pixelAt(p3.rgba8, width: 60, x: 45, y: 70), r: true, g: true, b: false, "page3 cropBox bottom-right yellow") + + // Controlled local file open + non-file URL scheme guard + path traversal guard. + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s3-ios-pdf-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + let fileURL = tmpDir.appendingPathComponent("sample.pdf") + try pdfBytes.write(to: fileURL) + let fileHandle = try bridge.open(fileURL: fileURL, allowedDirectory: tmpDir) + requireS3(fileHandle.pageCount == 4, "file-opened PDF must have pageCount == 4") + + do { + _ = try bridge.open(fileURL: URL(string: "https://example.com/a.pdf")!, allowedDirectory: tmpDir) + requireS3(false, "non-file URL must be rejected") + } catch PdfRendererError.invalidArgument {} + + do { + _ = try bridge.open(fileURL: tmpDir.appendingPathComponent("../escape.pdf"), allowedDirectory: tmpDir) + requireS3(false, "path outside allowed directory must be rejected") + } catch PdfRendererError.pathOutsideAllowedDirectory {} + + // Error guards: negative page index -> pageOutOfRange, >UInt32.max dimension -> pixelLimitExceeded. + do { + _ = try bridge.renderPageRgba8(of: handle, pageIndex: -1, targetWidthPx: 64, targetHeightPx: 64) + requireS3(false, "negative pageIndex must throw pageOutOfRange") + } catch PdfRendererError.pageOutOfRange {} + + do { + _ = try bridge.renderPageRgba8(of: handle, pageIndex: 0, targetWidthPx: Int(UInt32.max) + 10, targetHeightPx: 64) + requireS3(false, "64-bit overflow width must throw pixelLimitExceeded without trapping") + } catch PdfRendererError.pixelLimitExceeded {} + + do { + _ = try bridge.open(data: Data()) + requireS3(false, "empty PDF must fail") + } catch PdfRendererError.emptyDocument {} + + // Zero-copy C-ABI roundtrip via registered AffinePdfProvider. + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + requireS3(host != nil, "host create failed") + defer { + bridge.detach(from: host!) + affine_ios_host_destroy(host) + } + bridge.attach(to: host!) + var errCode: UInt32 = 99 + let cCount = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_page_count(host, raw.bindMemory(to: UInt8.self).baseAddress, pdfBytes.count, &errCode) + } + requireS3(errCode == 0 && cCount == 4, "C-ABI pdf_page_count expected 4, got \(cCount) (err \(errCode))") + + let cBuf = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_render_page_rgba8( + host, + raw.bindMemory(to: UInt8.self).baseAddress, + pdfBytes.count, + 1, + 150, + 100, + &errCode + ) + } + defer { affine_ios_bytes_free(cBuf) } + requireS3(errCode == 0 && cBuf.len == 150 * 100 * 4 && cBuf.ptr != nil, "C-ABI rotated render failed") + let cRgba = Data(bytes: cBuf.ptr!, count: cBuf.len) + assertColor(pixelAt(cRgba, width: 150, x: 37, y: 25), r: true, g: false, b: false, "C-ABI page1 rotated top-left red") + + // ABA / same-length, identical-header-and-tail, different-middle-stream cache isolation test. + func makeSingleColorPdf(colorOp: String) -> Data { + let padding = String(repeating: " ", count: 80) + let stream = "\(padding)\n\(colorOp) 0 0 100 100 re f\n\(padding)" + let objs = [ + "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", + "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n", + "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>\nendobj\n", + "4 0 obj\n<< /Length \(stream.utf8.count) >>\nstream\n\(stream)\nendstream\nendobj\n", + ] + var out = "%PDF-1.4\n" + var offs = [0] + for o in objs { + offs.append(out.utf8.count) + out += o + } + let xrefPos = out.utf8.count + out += "xref\n0 5\n0000000000 65535 f \n" + for off in offs.dropFirst() { + out += String(format: "%010d 00000 n \n", off) + } + out += "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n\(xrefPos)\n%%EOF\n" + return Data(out.utf8) + } + + let pdfRed = makeSingleColorPdf(colorOp: "1 0 0 rg") + let pdfBlue = makeSingleColorPdf(colorOp: "0 0 1 rg") + requireS3(pdfRed.count == pdfBlue.count, "ABA test PDFs must have identical byte length") + requireS3(pdfRed.prefix(64) == pdfBlue.prefix(64) && pdfRed.suffix(64) == pdfBlue.suffix(64), "ABA test PDFs must share identical first & last 64 bytes") + + // Explicit PDF handle lifecycle (open -> doc_page_count -> doc_page_size -> doc_render_page_rgba8 -> close). + let docId = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_open(host, raw.bindMemory(to: UInt8.self).baseAddress, pdfBytes.count, &errCode) + } + requireS3(errCode == 0 && docId != 0 && bridge.openDocumentCount == 1, "explicit pdf_open failed") + let docCount = affine_ios_host_pdf_doc_page_count(host, docId, &errCode) + requireS3(errCode == 0 && docCount == 4, "explicit doc_page_count expected 4, got \(docCount)") + var docPageSize = AffinePdfPageSize() + let gotSize = affine_ios_host_pdf_doc_page_size(host, docId, 1, &docPageSize, &errCode) + requireS3(gotSize && errCode == 0 && abs(docPageSize.width_pt - 300) < 0.5 && abs(docPageSize.height_pt - 200) < 0.5, "explicit doc_page_size rotated mismatch") + let docBuf = affine_ios_host_pdf_doc_render_page_rgba8(host, docId, 1, 150, 100, &errCode) + defer { affine_ios_bytes_free(docBuf) } + requireS3(errCode == 0 && docBuf.len == 150 * 100 * 4 && docBuf.ptr != nil, "explicit doc_render failed") + assertColor(pixelAt(Data(bytes: docBuf.ptr!, count: docBuf.len), width: 150, x: 37, y: 25), r: true, g: false, b: false, "explicit doc page1 rotated top-left red") + affine_ios_host_pdf_close(host, docId) + requireS3(bridge.openDocumentCount == 0, "pdf_close must release PDFDocument immediately") + + // Reuse the exact same mutable buffer address across both stateless C-ABI calls to prove zero UAF / ABA collision. + var sharedBuf = Array(pdfRed) + let bufRed = sharedBuf.withUnsafeBufferPointer { ptr in + affine_ios_host_pdf_render_page_rgba8(host, ptr.baseAddress, ptr.count, 0, 20, 20, &errCode) + } + defer { affine_ios_bytes_free(bufRed) } + requireS3(errCode == 0 && bufRed.len == 20 * 20 * 4 && bufRed.ptr != nil, "ABA red render failed") + assertColor(pixelAt(Data(bytes: bufRed.ptr!, count: bufRed.len), width: 20, x: 10, y: 10), r: true, g: false, b: false, "ABA PDF A red") + + sharedBuf.replaceSubrange(0.. 10.0 && firstFrameAfterResume.ime_bottom < 280.0, + "first frame after background resume must ease smoothly, got \(firstFrameAfterResume.ime_bottom)" + ) + smokeLog("PASS [3/8]: KeyboardAvoidanceCoordinator WindowInsets contract, slide-over overlap_w guard, and background resume timestamp passed") + } + + /// 4. HapticsBridge: all 7 patterns dispatch + bounded recordedPatterns ring buffer. + @MainActor + static func testHapticsBridgeDispatchAndBoundedHistory() { + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + requireS3(host != nil, "host create failed") + defer { affine_ios_host_destroy(host) } + + let bridge = HapticsBridge() + bridge.prepareAll() + bridge.attach(to: host!) + defer { bridge.detach(from: host!) } + + for pattern in AffineHapticPatternSwift.allCases { + requireS3(affine_ios_host_trigger_haptic(host, pattern.rawValue), "trigger \(pattern) failed") + requireS3(affine_ios_host_haptic_count(host, pattern.rawValue) == 1, "count mismatch for \(pattern)") + } + requireS3(!affine_ios_host_trigger_haptic(host, 99), "invalid pattern 99 must return false") + requireS3(affine_ios_host_haptic_total_count(host) == 7, "expected total == 7") + requireS3(bridge.dispatchedPatterns == AffineHapticPatternSwift.allCases, "recorded patterns mismatch") + + // Verify bounded history cap (never grows beyond maxRecordedPatterns = 64). + for _ in 0..<80 { + _ = affine_ios_host_trigger_haptic(host, AffineHapticPatternSwift.selectionChanged.rawValue) + } + requireS3( + bridge.dispatchedPatterns.count == HapticsBridge.maxRecordedPatterns, + "dispatchedPatterns must stay bounded at \(HapticsBridge.maxRecordedPatterns), got \(bridge.dispatchedPatterns.count)" + ) + smokeLog("PASS [4/8]: HapticsBridge dispatched all 7 patterns and enforced bounded history cap (64)") + } + + /// 5. End-to-end MetalHostViewController: system UITextInteraction mounted (zero SelectionOverlayView + /// subview), document-level GPU selection snapshot, cross-block drag, multi-MIME UIPasteboard + /// copy/cut/paste, readonly action_mask gating, BiDi RTL/mixed selectionRects, soft-wrap, and keyboard scroll. + @MainActor + static func testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu() { + func makeEmptyEditorVC(width: CGFloat = 390, height: CGFloat = 844) -> MetalHostViewController { + let controller = MetalHostViewController(root: .pageEditor) + controller.view.frame = CGRect(x: 0, y: 0, width: width, height: height) + controller.loadViewIfNeeded() + controller.view.layoutIfNeeded() + if let ptr = controller.hostPointer { + affine_ios_host_reset_empty_doc(ptr) + } + return controller + } + + let vc = makeEmptyEditorVC() + let hostView = vc.textHostView + guard let hostPtr = vc.hostPointer else { + requireS3(false, "MetalHostViewController hostPointer must be initialized") + return + } + + // Verify system UITextInteraction is mounted and zero legacy subviews exist on MetalHostView. + let hasTextInteraction = hostView.interactions.contains { $0 is UITextInteraction } + requireS3(hasTextInteraction, "MetalHostView must mount system UITextInteraction") + requireS3(hostView.subviews.isEmpty, "MetalHostView must mount zero custom overlay subviews") + + hostView.insertText("Hello world") + hostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 5)) + + let snapBefore = affine_ios_host_document_selection_snapshot(hostPtr) + requireS3(snapBefore.has_selection && !snapBefore.is_collapsed, "document snapshot must report active range selection") + requireS3(snapBefore.start_visible && snapBefore.end_visible, "start and end carets must be visible") + requireS3( + snapBefore.start_caret.x > 0 && snapBefore.end_caret.x > snapBefore.start_caret.x + 20.0, + "document carets must reflect real glyph advance (start=\(snapBefore.start_caret.x), end=\(snapBefore.end_caret.x))" + ) + requireS3(vc.presentedMenuAnchorRect != nil, "menu anchor rect must be published on range selection") + + // Drag end handle to offset 7 ("Hello w") via document-level drag API. + let targetCaret7 = hostView.caretRect(for: AffineTextPosition(utf16Offset: 7)) + requireS3(affine_ios_host_doc_selection_begin_drag(hostPtr, 2), "begin end-handle drag must succeed") + requireS3( + affine_ios_host_doc_selection_update_drag(hostPtr, Float(targetCaret7.midX), Float(targetCaret7.midY)), + "update end-handle drag must succeed" + ) + let snapDuring = affine_ios_host_document_selection_snapshot(hostPtr) + requireS3(snapDuring.menu_suppressed_for_motion && !snapDuring.menu_anchor_visible, "menu must hide during drag") + affine_ios_host_doc_selection_end_drag(hostPtr) + + let finalRange = (hostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3( + finalRange == NSRange(location: 0, length: 7), + "expected selectedTextRange [0, 7] ('Hello w'), got \(String(describing: finalRange))" + ) + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "copy action must be enabled") + hostView.copy(nil) + requireS3(hostView.lastCopiedText == "Hello w", "expected copied text 'Hello w', got \(String(describing: hostView.lastCopiedText))") + + // Cut active selection [0, 7] ("Hello w"): remaining text is "orld", copy/cut disabled on collapsed caret. + hostView.cut(nil) + let remainingText = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 4))) + requireS3(remainingText == "orld", "expected remaining text 'orld' after cut, got \(String(describing: remainingText))") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "copy must be disabled on collapsed caret") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.cut(_:)), withSender: nil), "cut must be disabled on collapsed caret") + + // External paste from system/host pasteboard inserts into editor. + MetalHostViewController.seedExternalPasteboard(["text/plain": "EXT"]) + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), "paste must be enabled when pasteboard has text") + hostView.paste(nil) + let afterPaste = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 7))) + requireS3(afterPaste == "EXTorld", "expected 'EXTorld' after external paste, got \(String(describing: afterPaste))") + + // Clearing system/host pasteboard must immediately disable Paste and never resurrect stale text. + MetalHostViewController.seedExternalPasteboard([:]) + requireS3( + !hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), + "paste must be disabled when system pasteboard is cleared" + ) + hostView.paste(nil) + let afterEmptyPaste = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 7))) + requireS3( + afterEmptyPaste == "EXTorld", + "paste() on cleared pasteboard must be a no-op (got \(String(describing: afterEmptyPaste)))" + ) + MetalHostViewController.seedExternalPasteboard(["text/plain": "EXT"]) + + // Read-only gating: COPY + SELECT_ALL allowed, CUT + PASTE strictly forbidden, + // and inputView suppresses the software keyboard while keeping firstResponder active. + hostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 3)) + affine_ios_host_set_page_readonly(hostPtr, true) + requireS3(hostView.inputView != nil, "readonly mode must return zero-size empty inputView to suppress software keyboard") + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "readonly must allow copy") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.cut(_:)), withSender: nil), "readonly must forbid cut") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), "readonly must forbid paste") + affine_ios_host_set_page_readonly(hostPtr, false) + requireS3(hostView.inputView == nil, "editable mode must restore default system keyboard (inputView == nil)") + + // 5b. BiDi RTL ("שלום 123 abc", "A אבג B") multi-line selectionRects and per-endpoint RTL. + let vcRtl = makeEmptyEditorVC() + let bidiMixed = "שלום 123 abc" + vcRtl.textHostView.insertText(bidiMixed) + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 4)) + let snapRtl = affine_ios_host_document_selection_snapshot(vcRtl.hostPointer!) + requireS3(snapRtl.start_is_rtl && snapRtl.end_is_rtl, "Hebrew text must report start_is_rtl & end_is_rtl") + let rHeb = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 0, length: 4))) + requireS3(rHeb.count == 1 && rHeb[0].rect.width > 20.0 && rHeb[0].writingDirection == .rightToLeft, "'שלום' rect must be >20pt wide and RTL") + + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 5, length: 3)) + let r123 = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 5, length: 3))) + requireS3(r123.count == 1 && r123[0].rect.width > 12.0, "'123' rect must be >12pt wide, got \(r123.map { $0.rect.width })") + + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 9, length: 3)) + let rAbc = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 9, length: 3))) + requireS3(rAbc.count == 1 && rAbc[0].rect.width > 12.0, "'abc' rect must be >12pt wide, got \(rAbc.map { $0.rect.width })") + + let vcMixed = makeEmptyEditorVC() + vcMixed.textHostView.insertText("A אבג B") + vcMixed.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 2, length: 3)) + let mixedRects = vcMixed.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 2, length: 3))) + requireS3(mixedRects.count == 1 && mixedRects[0].rect.width > 15.0 && mixedRects[0].containsStart && mixedRects[0].containsEnd, "mixed BiDi 'אבג' must emit 1 rect >15pt wide") + vcMixed.textHostView.copy(nil) + requireS3(vcMixed.textHostView.lastCopiedText == "אבג", "mixed BiDi copy must yield exact 'אבג'") + + // Monotonic BiDi caretRect (RTL Hebrew decreasing, embedded digits & Latin increasing) + NFD equivalence. + var prevHebX = CGFloat.greatestFiniteMagnitude + for offset in 0...3 { + let c = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: offset)) + requireS3(c.minX < prevHebX, "Hebrew caret x must decrease RTL at offset \(offset)") + prevHebX = c.minX + } + let d1 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 5)).minX + let d2 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 6)).minX + let d3 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 7)).minX + requireS3(d1 < d2 && d2 < d3, "embedded digits '123' must increase LTR (\(d1), \(d2), \(d3))") + + let vcNorm = makeEmptyEditorVC() + vcNorm.textHostView.insertText("\u{00E9}B") + _ = vcNorm.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 1, length: 1))) + vcNorm.textHostView.replace(AffineTextRange(utf16Range: NSRange(location: 0, length: 2)), withText: "e\u{0301}B") + let decompRects = vcNorm.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 2, length: 1))) + requireS3(decompRects.count == 1 && decompRects[0].rect.width > 5.0, "NFD 'e\\u{0301}B' [2,3) must yield valid rect") + + // UIKit single-handle cross-block drag (`textRange(from: selectedTextRange.start, to: closestPosition(to:))`) + // AND cross-block selection ending on an empty paragraph (`end <= endOfDocument`). + let vcCross = makeEmptyEditorVC() + vcCross.textHostView.insertText("First block\nSecond block\n") + if let crossPtr = vcCross.hostPointer { + _ = affine_ios_host_render_frame(crossPtr, 1.0) + let snapP3 = affine_ios_host_document_selection_snapshot(crossPtr) + let baseX = CGFloat(snapP3.start_caret.x) + let p3MidY = CGFloat(snapP3.start_caret.y + snapP3.start_caret.height * 0.5) + // Select "First" from offset 0 of paragraph 1 via two-point viewport selection, then drag ONLY the End handle into paragraph 2! + let p1Pt = CGPoint(x: baseX, y: p3MidY - 68.0) + let p1EndPt = CGPoint(x: baseX + 46.0, y: p3MidY - 68.0) + let p2Pt = CGPoint(x: baseX + 70.0, y: p3MidY - 34.0) + let p3EmptyPt = CGPoint(x: baseX + 4.0, y: p3MidY) + let initRange = vcCross.textHostView.textRange( + from: vcCross.textHostView.closestPosition(to: p1Pt)!, + to: vcCross.textHostView.closestPosition(to: p1EndPt)! + )! + vcCross.textHostView.selectedTextRange = initRange + let fixedStart = vcCross.textHostView.selectedTextRange!.start + let draggedToP2 = vcCross.textHostView.textRange( + from: fixedStart, + to: vcCross.textHostView.closestPosition(to: p2Pt)! + )! + vcCross.textHostView.selectedTextRange = draggedToP2 + vcCross.textHostView.copy(nil) + let crossCopied = vcCross.textHostView.lastCopiedText ?? "" + requireS3( + crossCopied.contains("First block") && crossCopied.contains("Second"), + "UIKit single-handle cross-block drag must preserve paragraph 1 start and extend into paragraph 2 (got '\(crossCopied)')" + ) + // Drag into empty paragraph 3 (`maxLen == 0`): `selectedTextRange.end` must NOT exceed `endOfDocument`. + let draggedToEmptyP3 = vcCross.textHostView.textRange( + from: fixedStart, + to: vcCross.textHostView.closestPosition(to: p3EmptyPt)! + )! + vcCross.textHostView.selectedTextRange = draggedToEmptyP3 + if let activeEmptySel = vcCross.textHostView.selectedTextRange { + let cmp = vcCross.textHostView.compare(activeEmptySel.end, to: vcCross.textHostView.endOfDocument) + requireS3( + cmp != .orderedDescending, + "cross-block selection ending on empty block must never exceed endOfDocument (cmp=\(cmp.rawValue))" + ) + } + } + + // Cross-anchor single-handle reversal on "Hello world": [6, 11) ("world") -> drag End handle to offset 3 -> "lo ". + let vcRev = makeEmptyEditorVC() + vcRev.textHostView.insertText("Hello world") + vcRev.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 6, length: 5)) + let c3 = vcRev.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 3)) + let fixedAnchor6 = vcRev.textHostView.selectedTextRange!.start + let reversedRange = vcRev.textHostView.textRange( + from: fixedAnchor6, + to: vcRev.textHostView.closestPosition(to: CGPoint(x: c3.midX, y: c3.midY))! + )! + vcRev.textHostView.selectedTextRange = reversedRange + vcRev.textHostView.copy(nil) + requireS3( + vcRev.textHostView.lastCopiedText == "lo ", + "single-handle cross-anchor reversal [6,11)->3 must select 'lo ', got '\(vcRev.textHostView.lastCopiedText ?? "")'" + ) + + // 5c. Soft-wrap multi-line selectionRects and rotation/resize recomputation. + let vcWrap = makeEmptyEditorVC() + let longLine = "AFFiNE native iOS GPU soft line wrapping verification across multiple wrapped visual lines" + vcWrap.textHostView.insertText(longLine) + vcWrap.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 10, length: 60)) + let wrapSelRects = vcWrap.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 10, length: 60))) + requireS3( + wrapSelRects.count >= 2 && wrapSelRects.first!.containsStart && wrapSelRects.last!.containsEnd, + "multi-line soft-wrap selectionRects must return >=2 per-line rects with start/end flags (got \(wrapSelRects.count))" + ) + let endYPortrait = affine_ios_host_document_selection_snapshot(vcWrap.hostPointer!).end_caret.y + vcWrap.view.frame = CGRect(x: 0, y: 0, width: 844, height: 390) + vcWrap.view.setNeedsLayout() + vcWrap.view.layoutIfNeeded() + let endYLandscape = affine_ios_host_document_selection_snapshot(vcWrap.hostPointer!).end_caret.y + requireS3( + endYLandscape < endYPortrait - 10.0, + "widening viewport 390->844 must move wrapped end caret up (portrait=\(endYPortrait), landscape=\(endYLandscape))" + ) + + // 5d. Keyboard auto-scroll keeps bottom selection visible and copyable. + let vcKb = makeEmptyEditorVC() + let fillerLines = String(repeating: "\n", count: 35) + let bottomWord = "BottomTarget" + vcKb.textHostView.insertText(fillerLines + bottomWord) + let kbLen = vcKb.textHostView.currentAuthoritativeUtf16Units.count + let kbStart = max(0, kbLen - bottomWord.utf16.count) + vcKb.textHostView.selectedTextRange = AffineTextRange( + utf16Range: NSRange(location: kbStart, length: bottomWord.utf16.count) + ) + let kbBefore = affine_ios_host_document_selection_snapshot(vcKb.hostPointer!) + requireS3(kbBefore.start_caret.y > 650.0, "bottom selection must sit below y=650 (got \(kbBefore.start_caret.y))") + _ = vcKb.keyboardCoordinator.applyKeyboardFrame( + windowBounds: CGRect(x: 0, y: 0, width: 390, height: 844), + keyboardFrameInView: CGRect(x: 0, y: 542, width: 390, height: 302), + safeAreaInsets: .zero, + isHidden: false, + durationSec: 0.0, + timestampSec: 1.0 + ) + vcKb.sampleInsets(timestamp: 1.0) + let kbRevealed = affine_ios_host_document_selection_snapshot(vcKb.hostPointer!) + requireS3( + kbRevealed.start_visible && kbRevealed.end_visible && kbRevealed.start_caret.y < kbBefore.start_caret.y, + "page must auto-scroll selection above keyboard (before=\(kbBefore.start_caret.y), after=\(kbRevealed.start_caret.y))" + ) + vcKb.textHostView.copy(nil) + requireS3(vcKb.textHostView.lastCopiedText == bottomWord, "selection and copy must stay intact while keyboard is open") + + // 5e. Unfocused CJK/Emoji `closestPosition` + dual `endpointToken` `selectedTextRange` read-write roundtrip + ordinary-scroll menu restore. + let vcCjk = makeEmptyEditorVC() + vcCjk.textHostView.insertText("甲乙丙丁🚀") + vcCjk.textHostView.insertText("\n") + vcCjk.textHostView.insertText("Second") + if let cjkPtr = vcCjk.hostPointer { + _ = affine_ios_host_render_frame(cjkPtr, 1.0) + let snapP2 = affine_ios_host_document_selection_snapshot(cjkPtr) + let baseX = CGFloat(snapP2.start_caret.x) + let p1Y = CGFloat(snapP2.start_caret.y + snapP2.start_caret.height * 0.5) - 34.0 + let p2Y = CGFloat(snapP2.start_caret.y + snapP2.start_caret.height * 0.5) + // Focus starts in paragraph 2 ("Second"); hit-testing unfocused CJK paragraph 1 must return identical UTF-16 offset on 1st and 2nd call. + let probeCjkPt = CGPoint(x: baseX + 48.0, y: p1Y) + let posFirst = vcCjk.textHostView.closestPosition(to: probeCjkPt) as? AffineTextPosition + let posSecond = vcCjk.textHostView.closestPosition(to: probeCjkPt) as? AffineTextPosition + requireS3( + posFirst != nil && posFirst?.utf16Offset == posSecond?.utf16Offset && (posFirst?.utf16Offset ?? 0) >= 2, + "unfocused CJK closestPosition must match focused UTF-16 offset on first query (first=\(String(describing: posFirst?.utf16Offset)), second=\(String(describing: posSecond?.utf16Offset)))" + ) + // Select cross-block "甲乙丙丁🚀\nSec", read `selectedTextRange` (two `.endpointToken`s), write it straight back, and verify text is preserved! + let crossStart = vcCjk.textHostView.position(from: posFirst!, offset: -(posFirst?.utf16Offset ?? 0))! + let crossEnd = vcCjk.textHostView.closestPosition(to: CGPoint(x: baseX, y: p2Y))! + vcCjk.textHostView.selectedTextRange = vcCjk.textHostView.textRange(from: crossStart, to: crossEnd) + vcCjk.textHostView.copy(nil) + let expectedCross = vcCjk.textHostView.lastCopiedText ?? "" + requireS3( + expectedCross.hasPrefix("甲乙丙丁🚀\nS"), + "cross-block CJK selection setup must span both paragraphs (got '\(expectedCross)')" + ) + let readBackRange = vcCjk.textHostView.selectedTextRange! + vcCjk.textHostView.selectedTextRange = readBackRange + vcCjk.textHostView.copy(nil) + let afterRoundtrip = vcCjk.textHostView.lastCopiedText ?? "" + requireS3( + afterRoundtrip == expectedCross, + "writing back dual-endpointToken selectedTextRange must preserve cross-block selection '\(expectedCross)', got '\(afterRoundtrip)'" + ) + } + + smokeLog("PASS [5/8]: MetalHostViewController E2E UITextInteraction, document drag, multi-MIME clipboard, readonly mask, BiDi, soft-wrap, and keyboard scroll passed") + } + + /// 6. S6 native GPU PlaygroundView mount: zero HostTextPreviewView, live CAMetalLayer, + /// H-S1 zero backingText copy (Markdown `# ` + `[[` -> `@`), H-S2 inputDelegate notifications, + /// newline block split & block-start deleteBackward merge, and T1 Stage-1 touch readonly. + @MainActor + static func testS6NativeEditorMountImeAndStageOneReadonly() async throws { + let vc = MetalHostViewController(root: .pageEditor) + vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vc.loadViewIfNeeded() + vc.view.layoutIfNeeded() + guard let handle = vc.hostPointer else { + requireS3(false, "MetalHostViewController must initialize hostHandle") + return + } + + // Verify Metal GPU layer is attached directly to hostView (zero HostTextPreviewView class exists). + let hasMetalSublayer = (vc.textHostView.layer.sublayers ?? []).contains { $0 is CAMetalLayer } + requireS3(hasMetalSublayer, "MetalRenderer CAMetalLayer must be attached to MetalHostView") + + // Live MetalRenderer CAMetalLayer attached as sublayer on iOS. + let rawMetal = affine_ios_host_metal_layer(handle) + requireS3(rawMetal != nil, "affine_ios_host_metal_layer must return MetalRenderer CAMetalLayer") + + // Stage-1 touch defaults: Phone & Tablet default to edgeless_readonly + database_readonly. + requireS3(affine_ios_host_edgeless_readonly(handle), "iOS touch host must default edgeless_readonly = true") + requireS3(affine_ios_host_database_readonly(handle), "iOS touch host must default database_readonly = true") + + // Reset to empty doc for authoritative H-S1 / H-S2 IME verification. + affine_ios_host_reset_empty_doc(handle) + let seqBefore = affine_ios_host_text_input_change_seq(handle) + vc.textHostView.insertText("# Heading") + let seqAfter = affine_ios_host_text_input_change_seq(handle) + requireS3(seqAfter > seqBefore, "H-S2: editor text mutation must advance text_input_change_seq") + let fullRange = vc.textHostView.textRange( + from: vc.textHostView.beginningOfDocument, + to: vc.textHostView.endOfDocument + ) + let readBack = fullRange.flatMap { vc.textHostView.text(in: $0) } ?? "" + requireS3(readBack.contains("Heading"), "H-S1: UITextInput must read authoritative editor text, got '\(readBack)'") + + // Block split on newline + block-start deleteBackward merge. + vc.textHostView.insertText("\n") + requireS3( + vc.textHostView.currentAuthoritativeUtf16Units.isEmpty, + "insertText(\"\\n\") must split into an empty focused next block" + ) + let afterSplitRange = vc.textHostView.textRange( + from: vc.textHostView.beginningOfDocument, + to: vc.textHostView.endOfDocument + ) + let afterSplit = afterSplitRange.flatMap { vc.textHostView.text(in: $0) } ?? "" + requireS3( + afterSplit.contains("Heading"), + "full-document beginningOfDocument..endOfDocument must span all blocks after split, got '\(afterSplit)'" + ) + // Value equality & hashing on AffineTextPosition / AffineTextRange (NSObject equivalence contract). + let pA = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 42) + let pB = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 42) + let pSameTokMovedBlock = AffineTextPosition(utf16Offset: 3, blockOrder: 2, endpointToken: 42) + let pDiffTokSameCoords = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 99) + let pZeroTok = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 0) + let pC = AffineTextPosition(utf16Offset: 4, blockOrder: 1, endpointToken: 43) + requireS3(pA.isEqual(pB) && pA.hash == pB.hash && !pA.isEqual(pC), "AffineTextPosition must implement value isEqual/hash") + requireS3( + pA.isEqual(pSameTokMovedBlock) && pA.hash == pSameTokMovedBlock.hash, + "AffineTextPosition with identical non-zero endpointToken must stay equal with equal hash across blockOrder changes" + ) + requireS3( + !pA.isEqual(pDiffTokSameCoords) && !pA.isEqual(pZeroTok), + "AffineTextPosition with distinct endpointTokens must never compare equal even at same coordinates" + ) + let rA = AffineTextRange(startPos: pA, endPos: pC) + let rB = AffineTextRange(startPos: pB, endPos: pC) + requireS3(rA.isEqual(rB) && rA.hash == rB.hash, "AffineTextRange must implement value isEqual/hash") + + // Surrogate pair / grapheme cluster characterUnitRange & characterRange(at:) must not split 🚀. + affine_ios_host_reset_empty_doc(handle) + vc.textHostView.insertText("甲🚀乙") + _ = affine_ios_host_render_frame(handle, 1.0) + if let caretEnd = vc.textHostView.selectedTextRange?.start, + let emojiPos = vc.textHostView.position(from: caretEnd, offset: -3) as? AffineTextPosition, + let unitRange = vc.textHostView.characterUnitRange(at: emojiPos) + { + let unitText = vc.textHostView.text(in: unitRange) ?? "" + requireS3( + unitText == "🚀" && unitRange.utf16Range.length == 2, + "characterUnitRange at 🚀 must return full 2-UTF16 surrogate pair, got '\(unitText)' len=\(unitRange.utf16Range.length)" + ) + } else { + requireS3(false, "characterUnitRange must resolve 🚀 surrogate pair position") + } + + // Code block focus must switch autocorrectionType to .no (wantsCodeInput regression guard). + affine_ios_host_reset_empty_doc(handle) + requireS3(vc.textHostView.autocorrectionType == .default, "Prose block must default autocorrectionType to .default") + vc.textHostView.insertText("``` ") + requireS3( + vc.textHostView.autocorrectionType == .no && vc.textHostView.autocapitalizationType == .none, + "Code block focus must set autocorrectionType == .no and autocapitalizationType == .none" + ) + affine_ios_host_reset_empty_doc(handle) + vc.textHostView.insertText("# Heading") + vc.textHostView.insertText("\n") + + vc.textHostView.deleteBackward() + let afterMergeRange = vc.textHostView.textRange( + from: vc.textHostView.beginningOfDocument, + to: vc.textHostView.endOfDocument + ) + let afterMerge = afterMergeRange.flatMap { vc.textHostView.text(in: $0) } ?? "" + requireS3(afterMerge.contains("Heading"), "deleteBackward at block start must merge back, got '\(afterMerge)'") + + // Verify non-zero safe-area insets (top=59pt, bottom=34pt) keep hostView, + // selectionOverlayView, and caretRect in one shared (0, 0) safe-area frame. + let safeWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let vcSafe = MetalHostViewController(root: .pageEditor) + vcSafe.additionalSafeAreaInsets = UIEdgeInsets(top: 59, left: 0, bottom: 34, right: 0) + safeWindow.rootViewController = vcSafe + safeWindow.isHidden = false + safeWindow.layoutIfNeeded() + vcSafe.view.layoutIfNeeded() + requireS3( + abs(vcSafe.textHostView.frame.origin.y - vcSafe.view.safeAreaInsets.top) < 0.5 + && vcSafe.view.safeAreaInsets.top >= 59.0 + && abs( + vcSafe.textHostView.frame.height + - (vcSafe.view.bounds.height - vcSafe.view.safeAreaInsets.top - vcSafe.view.safeAreaInsets.bottom) + ) < 0.5, + "hostView must be framed inside safeAreaInsets (insets=\(vcSafe.view.safeAreaInsets), got \(vcSafe.textHostView.frame))" + ) + if let safeHandle = vcSafe.hostPointer { + affine_ios_host_reset_empty_doc(safeHandle) + vcSafe.textHostView.insertText("SafeArea") + let c0 = vcSafe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0)) + let c8 = vcSafe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 8)) + requireS3(c8.minX > c0.minX, "caretRect in safe-area hostView must advance horizontally") + + // UIKit IME contract: Pinyin/Kana setMarkedText -> setMarkedText -> insertText + // must NOT echo textWillChange/textDidChange back to UITextInputDelegate, whereas + // editor-initiated/external mutations MUST notify it. + final class CountingInputDelegate: NSObject, UITextInputDelegate { + var textWillChangeCount = 0 + var textDidChangeCount = 0 + var selectionWillChangeCount = 0 + var selectionDidChangeCount = 0 + func selectionWillChange(_ textInput: UITextInput?) { selectionWillChangeCount += 1 } + func selectionDidChange(_ textInput: UITextInput?) { selectionDidChangeCount += 1 } + func textWillChange(_ textInput: UITextInput?) { textWillChangeCount += 1 } + func textDidChange(_ textInput: UITextInput?) { textDidChangeCount += 1 } + @available(iOS 18.4, *) + func conversationContext(_ context: UIConversationContext?, didChange textInput: (any UITextInput)?) {} + } + affine_ios_host_reset_empty_doc(safeHandle) + let countingDelegate = CountingInputDelegate() + vcSafe.textHostView.inputDelegate = countingDelegate + vcSafe.textHostView.setMarkedText("ni", selectedRange: NSRange(location: 2, length: 0)) + vcSafe.textHostView.setMarkedText("nihao", selectedRange: NSRange(location: 5, length: 0)) + vcSafe.textHostView.insertText("你好") + requireS3( + countingDelegate.textWillChangeCount == 0 && countingDelegate.textDidChangeCount == 0, + "IME-originated Pinyin sequence must trigger 0 textWillChange/textDidChange callbacks (got will=\(countingDelegate.textWillChangeCount), did=\(countingDelegate.textDidChangeCount))" + ) + // Single-Writer contract: UIKit calling setSelectedTextRange must NOT synchronously echo + // selectionWillChange/selectionDidChange back into inputDelegate. + let selWillBefore = countingDelegate.selectionWillChangeCount + let selDidBefore = countingDelegate.selectionDidChangeCount + vcSafe.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 2)) + requireS3( + countingDelegate.selectionWillChangeCount == selWillBefore + && countingDelegate.selectionDidChangeCount == selDidBefore, + "setSelectedTextRange must not synchronously echo selectionWillChange/selectionDidChange" + ) + // External editor mutation (reset / shortcut) MUST notify inputDelegate. + affine_ios_host_reset_empty_doc(safeHandle) + requireS3( + countingDelegate.textWillChangeCount > 0 || countingDelegate.selectionDidChangeCount > 0, + "External editor mutation must notify UITextInputDelegate" + ) + vcSafe.textHostView.inputDelegate = nil + // Code input mode disables autocorrection, autocapitalization, smart quotes, and smart dashes. + affine_ios_host_reset_empty_doc(safeHandle) + requireS3( + !affine_ios_host_wants_code_input(safeHandle) + && vcSafe.textHostView.autocorrectionType == .default + && vcSafe.textHostView.autocapitalizationType == .sentences, + "prose paragraph must use default autocorrection and sentence capitalization" + ) + vcSafe.textHostView.insertText("``` ") + requireS3( + affine_ios_host_wants_code_input(safeHandle) + && vcSafe.textHostView.autocorrectionType == .no + && vcSafe.textHostView.autocapitalizationType == .none + && vcSafe.textHostView.smartQuotesType == .no + && vcSafe.textHostView.smartDashesType == .no, + "code block must disable autocorrection, autocapitalization, smart quotes, and smart dashes" + ) + + // Forwarded empty-tail tap regression guard (5 consecutive rounds): + // tapping below the last block must route to Rust (shouldLetTextInteractionOwnTouch == false), + // append/focus the trailing paragraph, and raise software keyboard (isFirstResponder == true). + safeWindow.makeKeyAndVisible() + for round in 1...5 { + affine_ios_host_reset_empty_doc(safeHandle) + vcSafe.textHostView.insertText("First paragraph \(round)") + _ = affine_ios_host_render_frame(safeHandle, Double(round)) + _ = vcSafe.textHostView.resignFirstResponder() + requireS3(!vcSafe.textHostView.isFirstResponder, "round \(round): must resign before empty-tail tap") + let tailPoint = CGPoint(x: 195.0, y: 620.0) + requireS3( + !vcSafe.shouldLetTextInteractionOwnTouch(at: tailPoint), + "round \(round): empty page tail tap must forward immediately to Rust" + ) + affine_ios_host_touch_event(safeHandle, UInt64(900 + round), 0, Float(tailPoint.x), Float(tailPoint.y)) + affine_ios_host_touch_event(safeHandle, UInt64(900 + round), 2, Float(tailPoint.x), Float(tailPoint.y)) + vcSafe.textHostView.handleForwardedTouchCompletion(endedEditableTap: true) + requireS3( + affine_ios_host_wants_software_keyboard(safeHandle) + && vcSafe.textHostView.isFirstResponder + && vcSafe.textHostView.inputView == nil, + "round \(round): empty-tail tap must raise software keyboard (wantsKb=\(affine_ios_host_wants_software_keyboard(safeHandle)), isFR=\(vcSafe.textHostView.isFirstResponder))" + ) + vcSafe.textHostView.insertText("Tail line \(round)") + let docRange = vcSafe.textHostView.textRange( + from: vcSafe.textHostView.beginningOfDocument, + to: vcSafe.textHostView.endOfDocument + ) + let fullText = docRange.flatMap { vcSafe.textHostView.text(in: $0) } ?? "" + requireS3( + fullText.contains("Tail line \(round)"), + "round \(round): typing after empty-tail tap must write into newly focused paragraph, got '\(fullText)'" + ) + } + } + + // Verify all 3 zero-CocoaPods iOS Native Islands (Atomic SQLite ShareExtension, Paywall, Onboarding/SignIn). + requireS3( + ShareExtensionBridge.appGroupIdentifier == "group.app.affine.pro" + && ShareExtensionBridge.inboxDirectoryName == "ShareInbox" + && ShareExtensionBridge.attachmentsDirectoryName == "Attachments" + && ShareExtensionBridge.invalidDirectoryName == "Invalid", + "ShareExtension must align 1:1 with group.app.affine.pro/ShareInbox/{Attachments,Invalid}" + ) + let tempInbox = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-s6-share-\(UUID().uuidString)", isDirectory: true) + .appendingPathComponent("ShareInbox", isDirectory: true) + let tempShareDocs = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-s6-share-docs-\(UUID().uuidString)", isDirectory: true) + defer { + try? FileManager.default.removeItem(at: tempInbox.deletingLastPathComponent()) + try? FileManager.default.removeItem(at: tempShareDocs) + } + try! FileManager.default.createDirectory(at: tempShareDocs, withIntermediateDirectories: true) + let shareBridge = ShareExtensionBridge(inboxDirectory: tempInbox) + + // Cold-start regression guards: + // (a) Single-tap on prose at cold start (`wants_software_keyboard == false`): UIKit calls + // `becomeFirstResponder()` (which initially queries `inputView` -> `emptyInputView`), + // immediately followed by `setSelectedTextRange:` placing a collapsed caret on prose -> + // `reloadInputViews()` must promote `inputView` to `nil` (real system keyboard!). + let coldEditWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let vcColdEdit = MetalHostViewController(root: .pageEditor) + coldEditWindow.rootViewController = vcColdEdit + coldEditWindow.makeKeyAndVisible() + coldEditWindow.layoutIfNeeded() + vcColdEdit.view.layoutIfNeeded() + if let coldEditPtr = vcColdEdit.hostPointer { + _ = affine_ios_host_render_frame(coldEditPtr, 1.0) + requireS3( + !affine_ios_host_wants_software_keyboard(coldEditPtr) && !vcColdEdit.textHostView.isFirstResponder, + "cold-start showcase must start with wants_software_keyboard == false and isFirstResponder == false" + ) + requireS3(vcColdEdit.textHostView.becomeFirstResponder(), "cold-start hostView must becomeFirstResponder on tap") + let prosePt = CGPoint(x: 120.0, y: 210.0) + if let hitCaretPos = vcColdEdit.textHostView.closestPosition(to: prosePt), + let collapsedTapRange = vcColdEdit.textHostView.textRange(from: hitCaretPos, to: hitCaretPos) + { + vcColdEdit.textHostView.selectedTextRange = collapsedTapRange + } else { + requireS3(false, "closestPosition must hit showcase prose at \(prosePt)") + } + requireS3( + vcColdEdit.textHostView.isFirstResponder + && affine_ios_host_wants_software_keyboard(coldEditPtr) + && vcColdEdit.textHostView.inputView == nil, + "cold-start single-tap on prose must reload inputView to nil so system keyboard appears" + ) + _ = vcColdEdit.textHostView.resignFirstResponder() + } + + // (b) Cold-start `affine_ios_host_set_page_readonly(true)` with zero display-link ticks: + // `textInteraction` must switch to `.nonEditable` synchronously BEFORE the first touch + // (never tearing down `.editable` mid-gesture on the first double-tap!), and selecting + // the word at `(x, y)` via `UITextInputTokenizer` + `selectedTextRange` must succeed. + let coldRoWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let vcColdRo = MetalHostViewController(root: .pageEditor) + coldRoWindow.rootViewController = vcColdRo + coldRoWindow.makeKeyAndVisible() + coldRoWindow.layoutIfNeeded() + vcColdRo.view.layoutIfNeeded() + if let coldRoPtr = vcColdRo.hostPointer { + _ = affine_ios_host_render_frame(coldRoPtr, 1.0) + requireS3( + !affine_ios_host_document_selection_snapshot(coldRoPtr).has_selection, + "cold-start readonly test must start with has_selection == false" + ) + affine_ios_host_set_page_readonly(coldRoPtr, true) + requireS3( + vcColdRo.isTextInteractionReadonlyForTesting, + "affine_ios_host_set_page_readonly(true) must synchronously switch UITextInteraction to .nonEditable before any touch" + ) + let roWordPt = CGPoint(x: 120.0, y: 210.0) + _ = vcColdRo.textHostView.becomeFirstResponder() + if let roPos = vcColdRo.textHostView.closestPosition(to: roWordPt), + let wordRange = vcColdRo.textHostView.tokenizer.rangeEnclosingPosition( + roPos, + with: .word, + inDirection: UITextDirection(rawValue: UITextStorageDirection.forward.rawValue) + ) + { + vcColdRo.textHostView.selectedTextRange = wordRange + let roSnap = affine_ios_host_document_selection_snapshot(coldRoPtr) + let roSelectedText = vcColdRo.textHostView.selectedTextRange.flatMap { vcColdRo.textHostView.text(in: $0) } ?? "" + requireS3( + roSnap.has_selection && !roSnap.is_collapsed && !roSelectedText.isEmpty && vcColdRo.textHostView.inputView != nil, + "cold-start readonly first double-tap word selection must select non-empty word with suppressed keyboard (got '\(roSelectedText)')" + ) + } else { + requireS3(false, "cold-start readonly tokenizer must resolve word range at \(roWordPt)") + } + _ = vcColdRo.textHostView.resignFirstResponder() + } + + // 1) Real ShareInboxStore layout: ShareInbox/.json + ShareInbox/Attachments//x.pdf (9 bytes) + // + schemaVersion 1 legacy envelope (no importAttemptId) + schemaVersion 99 future envelope (preserved). + let pdf9Bytes = Data("%PDF-1.4\n".utf8) + requireS3(pdf9Bytes.count == 9, "test PDF fixture must be 9 bytes") + let shareItem = ShareInboxItem( + id: "ios-share-1", + documentId: "share-doc-url", + title: "AFFiNE", + content: ShareInboxContent(kind: .url, url: "https://affine.pro", text: nil), + target: ShareInboxTarget( + workspaceId: "ws-share-1", + workspaceFlavour: "local", + tagIds: [], + collectionId: nil + ) + ) + let pdfShareItem = ShareInboxItem( + id: "ios-share-pdf-1", + documentId: "share-doc-pdf", + title: "Spec", + content: ShareInboxContent(kind: .pdf, url: nil, text: nil), + attachments: [ + ShareInboxAttachment( + fileName: "x.pdf", + mimeType: "application/pdf", + relativePath: "ios-share-pdf-1/x.pdf" + ), + ] + ) + let staged = try! shareBridge.stageItem(shareItem) + let stagedPdf = try! shareBridge.stageItem( + pdfShareItem, + attachmentBlobs: ["ios-share-pdf-1/x.pdf": pdf9Bytes] + ) + let pdfAttDir = tempInbox.appendingPathComponent("Attachments/ios-share-pdf-1", isDirectory: true) + let pdfAttPath = pdfAttDir.appendingPathComponent("x.pdf") + + // Legacy v1 manifest (omits schemaVersion & importAttemptId). + let v1ManifestUrl = tempInbox.appendingPathComponent("ios-share-v1.json") + let v1Json = """ + { + "id": "ios-share-v1", + "documentId": "share-doc-v1", + "createdAt": "2026-11-28T10:00:00Z", + "title": "Legacy v1", + "content": { "kind": "text", "text": "Legacy v1 shared note" } + } + """ + try! Data(v1Json.utf8).write(to: v1ManifestUrl, options: .atomic) + + // Future schemaVersion 99 manifest: MUST be skipped and preserved untouched. + let v99ManifestUrl = tempInbox.appendingPathComponent("ios-share-v99.json") + let v99Json = """ + { + "schemaVersion": 99, + "importAttemptId": "future-attempt", + "id": "ios-share-v99", + "documentId": "share-doc", + "createdAt": "2026-11-28T11:00:00Z", + "title": "Future", + "content": { "kind": "text", "text": "Future format" } + } + """ + try! Data(v99Json.utf8).write(to: v99ManifestUrl, options: .atomic) + + requireS3( + FileManager.default.fileExists(atPath: staged.path) + && FileManager.default.fileExists(atPath: stagedPdf.path) + && FileManager.default.fileExists(atPath: pdfAttPath.path) + && FileManager.default.fileExists(atPath: v1ManifestUrl.path) + && FileManager.default.fileExists(atPath: v99ManifestUrl.path), + "ShareExtension fixtures must exist under ShareInbox/.json and ShareInbox/Attachments//x.pdf" + ) + + // Precondition gate: unmounted workspace (workspace == nil) MUST consume 0 and leave every file untouched. + let unmountedCount = shareBridge.drainAndIngestIntoHost(handle, workspace: nil) + requireS3( + unmountedCount == 0 + && FileManager.default.fileExists(atPath: staged.path) + && FileManager.default.fileExists(atPath: stagedPdf.path) + && FileManager.default.fileExists(atPath: pdfAttPath.path) + && FileManager.default.fileExists(atPath: v1ManifestUrl.path) + && FileManager.default.fileExists(atPath: v99ManifestUrl.path), + "Unmounted workspace must consume 0 items and never touch ShareInbox files" + ) + + // Mount workspace and consume atomically into SQLite (blobs + updates + share_ingest_receipts). + let shareCoord1 = HostBootstrapCoordinator(documentsDirectory: tempShareDocs) + try! shareCoord1.applyLocalWorkspaceAllowlist(["ws-share-1"]) + let shareWs1 = shareCoord1.workspace(id: "ws-share-1")! + affine_ios_host_reset_empty_doc(handle) + let ingestedCount = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs1) + requireS3( + ingestedCount == 3, + "ShareExtension must atomically ingest 3 items (URL + 9-byte PDF + v1 text), got \(ingestedCount)" + ) + requireS3( + !FileManager.default.fileExists(atPath: staged.path) + && !FileManager.default.fileExists(atPath: stagedPdf.path) + && !FileManager.default.fileExists(atPath: pdfAttDir.path) + && !FileManager.default.fileExists(atPath: v1ManifestUrl.path) + && FileManager.default.fileExists(atPath: v99ManifestUrl.path), + "ShareExtension cleanup must remove consumed JSON + Attachments// dir while preserving schemaVersion 99" + ) + shareCoord1.closeAll() + + // Reopen SQLite workspace: verify exact 9-byte SHA-256 content-addressed blob in `blobs` table AND all 3 blocks in `share-doc`. + let shareCoord2 = HostBootstrapCoordinator(documentsDirectory: tempShareDocs) + try! shareCoord2.applyLocalWorkspaceAllowlist(["ws-share-1"]) + let shareWs2 = shareCoord2.workspace(id: "ws-share-1")! + let expectedPdfBlobKey = ShareExtensionBridge.sha256Base64Url(pdf9Bytes) + requireS3( + expectedPdfBlobKey.count == 44, + "0.27.5 blob key must be 44-char unpadded base64url SHA-256, got \(expectedPdfBlobKey)" + ) + let readBackBlob = shareWs2.readBlob(key: expectedPdfBlobKey) + requireS3( + readBackBlob == pdf9Bytes, + "Reopened SQLite blobs table must contain exact 9-byte PDF attachment under SHA-256 key, got \(String(describing: readBackBlob?.count))" + ) + let persistedUrlSnap = shareWs2.readPageSnapshotJson(docId: "share-doc-url", clientId: 1) ?? "" + let persistedPdfSnap = shareWs2.readPageSnapshotJson(docId: "share-doc-pdf", clientId: 1) ?? "" + let persistedV1Snap = shareWs2.readPageSnapshotJson(docId: "share-doc-v1", clientId: 1) ?? "" + requireS3( + persistedUrlSnap.contains("https://affine.pro") + && persistedUrlSnap.contains("affine:bookmark") + && persistedPdfSnap.contains(expectedPdfBlobKey) + && persistedPdfSnap.contains("affine:attachment") + && persistedV1Snap.contains("Legacy v1 shared note"), + "Reopened SQLite docs must contain Bookmark URL, SHA-256 Attachment blob reference, and v1 text" + ) + // Active PlaygroundView text must NOT be polluted by unrelated background ShareInbox ingests. + let activeEditorRange = vc.textHostView.textRange( + from: vc.textHostView.beginningOfDocument, + to: vc.textHostView.endOfDocument + ) + let activeEditorText = activeEditorRange.flatMap { vc.textHostView.text(in: $0) } ?? "" + requireS3( + !activeEditorText.contains("Legacy v1 shared note"), + "ShareInbox SQLite ingest must never dual-write into an unrelated open PlaygroundView buffer" + ) + + // Cloud-targeted or other-workspace share manifests must stay untouched when only ws-share-1 is mounted. + let cloudTargetedUrl = try! shareBridge.stageItem(ShareInboxItem( + id: "ios-share-cloud-1", + documentId: "cloud-doc-1", + title: "Cloud Target", + content: ShareInboxContent(kind: .text, url: nil, text: "Keep for cloud sync"), + target: ShareInboxTarget( + workspaceId: "ws-cloud-9", + workspaceFlavour: "affine-cloud", + tagIds: [], + collectionId: nil + ) + )) + let skippedCloud = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2) + requireS3( + skippedCloud == 0 && FileManager.default.fileExists(atPath: cloudTargetedUrl.path), + "Cloud-targeted ShareInbox manifest must remain untouched when draining local workspace" + ) + try? FileManager.default.removeItem(at: cloudTargetedUrl) + + // Corrupt JSON and invalid URL scheme must be moved into ShareInbox/Invalid/ (zero rescan loop). + let corruptUrl = tempInbox.appendingPathComponent("999-corrupt.json") + try! "{not-valid-json".data(using: .utf8)!.write(to: corruptUrl) + let rejectedUrl = try! shareBridge.stageItem(ShareInboxItem( + id: "ios-share-bad", + documentId: "share-doc-bad", + title: "Bad", + content: ShareInboxContent(kind: .url, url: "javascript:alert(1)", text: nil) + )) + _ = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2) + requireS3(!FileManager.default.fileExists(atPath: corruptUrl.path), "Corrupt JSON must be moved out of ShareInbox/") + requireS3(!FileManager.default.fileExists(atPath: rejectedUrl.path), "Invalid scheme manifest must be moved out of ShareInbox/") + requireS3( + FileManager.default.fileExists(atPath: shareBridge.invalidDirectory.appendingPathComponent("999-corrupt.json").path), + "Corrupt JSON must reside in ShareInbox/Invalid/" + ) + + // 2) SQLite COMMIT succeeded + first checkpoint_passive failed + retry -> idempotent receipt hit, + // target doc contains text EXACTLY ONCE (zero duplicate paragraphs). + let idempItem = ShareInboxItem( + id: "ios-share-idemp-1", + documentId: "share-doc-idemp", + title: "Idempotent", + content: ShareInboxContent(kind: .text, url: nil, text: "UNIQUE_IDEMPOTENT_MARKER_42") + ) + let idempFile = try! shareBridge.stageItem(idempItem) + var checkpointCalls = 0 + shareBridge.checkpointHook = { ws in + checkpointCalls += 1 + if checkpointCalls == 1 { + return false // Inject first checkpoint_passive failure AFTER SQLite COMMIT succeeded. + } + return ws.checkpointPassive() + } + let firstAttempt = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2) + requireS3(firstAttempt == 1, "First attempt commits SQLite tx before checkpoint failure (got \(firstAttempt))") + requireS3( + FileManager.default.fileExists(atPath: idempFile.path), + "Failed checkpoint_passive must leave manifest intact for idempotent retry" + ) + let retryAttempt = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2) + shareBridge.checkpointHook = nil + requireS3(retryAttempt == 0, "Retry must hit share_ingest_receipts idempotently (0 newly inserted), got \(retryAttempt)") + requireS3(!FileManager.default.fileExists(atPath: idempFile.path), "Successful retry checkpoint must clean up manifest") + let snapAfterRetry = shareWs2.readPageSnapshotJson(docId: "share-doc-idemp", clientId: 1) ?? "" + let markerOccurrences = snapAfterRetry.components(separatedBy: "UNIQUE_IDEMPOTENT_MARKER_42").count - 1 + requireS3( + markerOccurrences == 1, + "Idempotent retry after checkpoint failure must insert text EXACTLY once, got \(markerOccurrences) in \(snapAfterRetry)" + ) + if Bundle.main.bundleIdentifier == nil { + let defaultManifest = try! ShareExtensionBridge().stageItem( + ShareInboxItem( + id: "ios-share-default-1", + documentId: "share-doc-default", + title: "Default share inbox", + content: ShareInboxContent(kind: .text, url: nil, text: "Default share inbox") + ) + ) + let count = ShareExtensionBridge().drainAndIngestIntoHost(handle, workspace: shareWs2) + requireS3( + count == 1 && !FileManager.default.fileExists(atPath: defaultManifest.path), + "A new default bridge must consume the staged share" + ) + } + shareCoord2.closeAll() + + // 3) StoreKit 2 expiration & revocation reconciliation (`0.27.5` `PricingConfiguration` IDs): + // purchase -> persisted Verified -> restart -> currentEntitlements=[] clears disk & Rust -> + // re-purchase -> revocationDate != nil revokes immediately & deletes disk cache. + let tempEntitlementFile = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-s6-paywall-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: tempEntitlementFile) } + let fixedNow = Date(timeIntervalSince1970: 1_800_000_000) + let futureExp = Date(timeIntervalSince1970: 1_800_086_400) + let paywall1 = AffinePaywallBridge(entitlementFileUrl: tempEntitlementFile) + paywall1.attach(host: handle, now: fixedNow) + requireS3( + paywall1.syncProductsPayload(host: handle, payload: [[ + "product_id": "app.affine.pro.Monthly", + "display_name": "AFFiNE Pro", + "display_price": "$9.99", + ]]), + "AffinePaywall must accept allowlisted 0.27.5 StoreKit 2 product" + ) + requireS3(paywall1.beginPurchase(host: handle, productId: "app.affine.pro.Monthly"), "beginPurchase") + let activeSnap = PaywallEntitlementSnapshot( + transactionId: "tx-ios-1", + productId: "app.affine.pro.Monthly", + jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", + expirationDate: futureExp, + revocationDate: nil + ) + requireS3( + paywall1.applyVerifiedTransactionUpdate(activeSnap, host: handle, now: fixedNow), + "AffinePaywall must verify active JWS entitlement and persist to disk" + ) + requireS3(paywall1.stateJson(host: handle).contains("verified"), "Paywall state must be verified") + requireS3(FileManager.default.fileExists(atPath: tempEntitlementFile.path), "Entitlement cache must exist on disk") + + // Restart fresh host: restore persisted entitlement, then reconcile against empty currentEntitlements = []. + let vcFreshPaywall = MetalHostViewController(root: .pageEditor) + vcFreshPaywall.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcFreshPaywall.loadViewIfNeeded() + let paywall2 = AffinePaywallBridge(entitlementFileUrl: tempEntitlementFile) + paywall2.attach(host: vcFreshPaywall.hostPointer!, now: fixedNow) + let restoredPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!) + requireS3( + restoredPaywallJson.contains("verified") + && restoredPaywallJson.contains("tx-ios-1") + && restoredPaywallJson.contains("app.affine.pro.Monthly"), + "Restarted host must restore active persisted StoreKit 2 entitlement + product_id (got \(restoredPaywallJson))" + ) + requireS3( + paywall2.reconcileCurrentEntitlements([], host: vcFreshPaywall.hostPointer!, now: fixedNow), + "Reconciling empty currentEntitlements must succeed" + ) + let clearedPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!) + requireS3( + !clearedPaywallJson.contains("\"phase\":\"verified\"") + && clearedPaywallJson.contains("\"verified_transaction_id\":null") + && !FileManager.default.fileExists(atPath: tempEntitlementFile.path), + "Empty currentEntitlements must revoke Rust state and delete stale disk cache (got \(clearedPaywallJson))" + ) + + // Re-purchase and receive a verified transaction update with revocationDate != nil -> immediate revoke. + requireS3( + paywall2.applyVerifiedTransactionUpdate(activeSnap, host: vcFreshPaywall.hostPointer!, now: fixedNow), + "Re-applying active entitlement must succeed" + ) + let revokedSnap = PaywallEntitlementSnapshot( + transactionId: "tx-ios-1", + productId: "app.affine.pro.Monthly", + jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", + expirationDate: futureExp, + revocationDate: fixedNow + ) + requireS3( + paywall2.applyVerifiedTransactionUpdate(revokedSnap, host: vcFreshPaywall.hostPointer!, now: fixedNow), + "Applying revoked transaction update must succeed" + ) + let revokedPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!) + requireS3( + !revokedPaywallJson.contains("\"phase\":\"verified\"") + && revokedPaywallJson.contains("\"verified_transaction_id\":null") + && paywall2.activeEntitlements.isEmpty + && !FileManager.default.fileExists(atPath: tempEntitlementFile.path), + "Revoked transaction update must immediately clear Rust state and disk cache (got \(revokedPaywallJson))" + ) + + // Unknown product with lexically earlier transactionId ("000-unknown") alongside valid Monthly ("tx-ios-1") + // must be filtered out BEFORE persistence and primary selection (never masking valid subscription). + let unknownSnap = PaywallEntitlementSnapshot( + transactionId: "000-unknown", + productId: "com.unknown.unlisted.item", + jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", + expirationDate: futureExp, + revocationDate: nil + ) + requireS3( + paywall2.reconcileCurrentEntitlements([unknownSnap, activeSnap], host: vcFreshPaywall.hostPointer!, now: fixedNow), + "reconcileCurrentEntitlements must succeed when unknown product coexists with valid Monthly" + ) + let coexistingJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!) + requireS3( + coexistingJson.contains("\"phase\":\"verified\"") + && coexistingJson.contains("tx-ios-1") + && !coexistingJson.contains("000-unknown") + && paywall2.activeEntitlements.keys.sorted() == ["tx-ios-1"], + "Unknown product must never mask valid subscription or enter activeEntitlements (got \(coexistingJson))" + ) + + if Bundle.main.bundleIdentifier == nil { + let defaultPaywall = AffinePaywallBridge() + requireS3( + defaultPaywall.applyVerifiedTransactionUpdate(activeSnap, host: handle, now: fixedNow), + "The default paywall must persist the entitlement" + ) + let restartedPaywall = AffinePaywallBridge() + restartedPaywall.attach(host: vcFreshPaywall.hostPointer!, now: fixedNow) + requireS3( + restartedPaywall.activeEntitlements.keys.sorted() == ["tx-ios-1"], + "A new default paywall must restore the entitlement" + ) + try! FileManager.default.removeItem(at: ShareExtensionBridge.unbundledStorageDirectory) + } + + // Disk persistence failure rollback: pointing entitlementFileUrl at an existing directory causes atomic write + // to fail and MUST leave both Swift memory and Rust paywall state untouched. + let unwritableDirUrl = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-paywall-unwritable-\(UUID().uuidString)", isDirectory: true) + try! FileManager.default.createDirectory(at: unwritableDirUrl, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: unwritableDirUrl) } + let paywallUnwritable = AffinePaywallBridge(entitlementFileUrl: unwritableDirUrl) + requireS3( + !paywallUnwritable.applyVerifiedTransactionUpdate(activeSnap, host: handle, now: fixedNow), + "Disk write failure must fail applyVerifiedTransactionUpdate" + ) + requireS3( + paywallUnwritable.activeEntitlements.isEmpty, + "Disk write failure must roll back in-memory activeEntitlements" + ) + + requireS3( + vc.handleIncomingUrl(URL(string: "affine://share-inbox")!), + "MetalHostViewController.handleIncomingUrl must route affine://share-inbox deep links" + ) + + // Verify WorkspaceStorageBridge lock safety under concurrent background FFI + main-actor close(). + do { + let raceDir = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-ws-lock-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: raceDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: raceDir) } + let raceBridge = try WorkspaceStorageBridge( + spaceType: "workspace", + peer: "local", + spaceId: "ws-lock-drill", + allowlistedLocalIds: ["ws-lock-drill"], + documentsDirectory: raceDir + ) + let bgTask = Task.detached(priority: .utility) { + for i in 0..<24 { + _ = raceBridge.checkpointPassive() + _ = raceBridge.readDoc(docId: "doc-\(i)") + } + } + raceBridge.close() + await bgTask.value + requireS3(raceBridge.readDoc(docId: "doc-0") == nil, "closed WorkspaceStorageBridge must return nil safely") + } + + // Narrow-bridge OnboardingSignInBridge two-stage state machine via MetalHostViewController.handleIncomingUrl: + requireS3(vc.onboardingSignIn.beginOAuth(host: handle, csrfState: "state-token-999"), "beginOAuth") + requireS3( + !vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c1&state=bad")!), + "OAuth callback via MetalHostViewController.handleIncomingUrl must reject CSRF mismatch" + ) + requireS3( + vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c1&state=state-token-999")!), + "OAuth callback via MetalHostViewController.handleIncomingUrl must accept matching CSRF state" + ) + let pendingOAuthJson = vc.onboardingSignIn.stateJson(host: handle) + requireS3( + pendingOAuthJson.contains("pending_exchange") + && pendingOAuthJson.contains("\"authenticated_subject\":null"), + "OAuth callback must enter pending_exchange before session confirmation (got \(pendingOAuthJson))" + ) + requireS3( + vc.onboardingSignIn.failSessionExchange(host: handle, reason: "simulated exchange error"), + "failSessionExchange must reset onboarding state" + ) + requireS3( + vc.onboardingSignIn.stateJson(host: handle).contains("sign_in_choice"), + "Failed session exchange must reset onboarding state to sign_in_choice" + ) + requireS3(vc.onboardingSignIn.beginOAuth(host: handle, csrfState: "state-token-retry"), "retry beginOAuth") + requireS3( + vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c2&state=state-token-retry")!), + "Retry OAuth callback URL must be accepted" + ) + requireS3( + vc.onboardingSignIn.confirmSessionExchange(host: handle, subject: "usr-verified-1"), + "confirmSessionExchange must succeed" + ) + let confirmedOAuthJson = vc.onboardingSignIn.stateJson(host: handle) + requireS3( + confirmedOAuthJson.contains("\"stage\":\"completed\"") + && confirmedOAuthJson.contains("usr-verified-1"), + "Onboarding must reach completed with confirmed subject (got \(confirmedOAuthJson))" + ) + requireS3( + vc.onboardingSignIn.completeAppleCredential( + host: handle, + userIdentifier: "apple-user-1", + identityTokenJws: "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1MSJ9.c2ln" + ), + "completeAppleCredential must accept compact 3-segment JWS into pending_exchange" + ) + requireS3( + vc.onboardingSignIn.stateJson(host: handle).contains("pending_exchange"), + "Apple credential must enter pending_exchange before confirmation" + ) + requireS3( + vc.onboardingSignIn.confirmSessionExchange(host: handle, subject: "usr-apple-1") + && vc.onboardingSignIn.stateJson(host: handle).contains("usr-apple-1"), + "Apple sign-in must confirm verified subject" + ) + + // Reload showcase document, trigger light & dark GPU frames, and verify iOS dark chrome sync. + affine_ios_host_load_showcase_doc(handle) + let lightClear = vc.renderFrameNow(timestamp: 1.0) + requireS3( + lightClear != 0 && !affine_ios_host_is_dark_theme(handle) + && vc.overrideUserInterfaceStyle == .light + && vc.preferredStatusBarStyle == .darkContent, + "Light theme frame must sync light clearColor and light UIUserInterfaceStyle (clear=\(String(format: "0x%08X", lightClear)))" + ) + affine_ios_host_set_dark_theme(handle, true) + let darkClear = vc.renderFrameNow(timestamp: 1.1) + let darkR = Double((darkClear >> 24) & 0xFF) / 255.0 + let darkG = Double((darkClear >> 16) & 0xFF) / 255.0 + let darkB = Double((darkClear >> 8) & 0xFF) / 255.0 + let darkLuma = 0.2126 * darkR + 0.7152 * darkG + 0.0722 * darkB + requireS3( + darkClear != 0 + && darkClear != 0xFAFA_FCFF + && darkLuma < 0.35 + && affine_ios_host_is_dark_theme(handle) + && vc.overrideUserInterfaceStyle == .dark + && vc.preferredStatusBarStyle == .lightContent + && vc.textHostView.keyboardAppearance == .dark, + "Dark theme must sync dark clearColor (got \(String(format: "0x%08X", darkClear)), luma=\(darkLuma)), .dark overrideUserInterfaceStyle, .lightContent status bar, and .dark keyboard" + ) + affine_ios_host_set_dark_theme(handle, false) + let restoredLight = vc.renderFrameNow(timestamp: 1.2) + requireS3( + restoredLight != 0 + && !affine_ios_host_is_dark_theme(handle) + && vc.overrideUserInterfaceStyle == .light + && vc.preferredStatusBarStyle == .darkContent, + "Restoring light theme must flip overrideUserInterfaceStyle back to .light" + ) + + smokeLog("PASS [6/8]: iOS native GPU editor mount, safe-area alignment, H-S1/H-S2 IME, block split/merge, UITextInteraction selection, empty-tail tap keyboard raise, native islands, and T1 readonly passed") + } + + /// 7. Real WKWebView + real `/workspaces/workspace/local/.db` 0.27.5 + /// same-signature upgrade -> in-place edit -> rollback write-back -> old-shell readback drill. + @MainActor + static func test0275SameSignatureWebViewAndSqliteUpgradeRollbackDrill() async throws { + let tmpDocs = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-0275-drill-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: tmpDocs, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDocs) } + + // 1) Seed 0.27.5 SQLite workspace (`/workspaces/workspace/local/ws-0275-drill.db`) + // directly via raw `SQLite3` + genuine JavaScript `Yjs` (`yjs-npm-13.6.21`) V1 binary updates + // (zero new-host `WorkspaceStorageBridge` touched before upgrade!) AND 0.27.5 Capacitor + // WKWebView localStorage on `capacitor://localhost` (zero IDB). + let dbDir = tmpDocs + .appendingPathComponent("workspaces/workspace/local", isDirectory: true) + try FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true) + let dbFile = dbDir.appendingPathComponent("ws-0275-drill.db") + do { + var rawDb: OpaquePointer? + let openRc = sqlite3_open_v2( + dbFile.path, + &rawDb, + SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, + nil + ) + requireS3(openRc == SQLITE_OK && rawDb != nil, "raw SQLite3 open for 0.27.5 seed must succeed") + defer { sqlite3_close(rawDb) } + let ddl = """ + PRAGMA journal_mode = WAL; + CREATE TABLE _sqlx_migrations ( + version BIGINT PRIMARY KEY, + description TEXT NOT NULL, + installed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + success BOOLEAN NOT NULL, + checksum BLOB NOT NULL, + execution_time BIGINT NOT NULL + ); + INSERT INTO _sqlx_migrations VALUES + (1, 'init_v2', '2026-11-28 12:00:00', 1, X'a1f0a1496ba1d1ff1689fc234514b13e7501ce5a3891b5943a75300b20e68444444ae71a1a80f40e46ccee2fc9e2af1a', 1), + (2, 'add_blob_sync', '2026-11-28 12:00:00', 1, X'c40244fec04822d74db419bead8486db435bb52d1f0214e4ddcc8928f4444475c7be8f96cee4c4383fd21b866fffd630', 1), + (3, 'add_idx_snapshots', '2026-11-28 12:00:00', 1, X'c13e51745e6f2d3e49f01fc82df68e88e91feabfa0a28507d658bb85b4c5cb81354ac8b23eb1038b175b1ae66311980a', 1), + (4, 'add_indexer_sync', '2026-11-28 12:00:00', 1, X'eeb9b2d07c3827f326feaed6651f587f177c2312c701d72f321c2d1a132bcd962fc914b39b12a34694003033bf29882b', 1), + (5, 'workspace_inventory', '2026-11-28 12:00:00', 1, X'c47dc6bc54f25ad6395edbf231a84399c64d0b497aabcb4ab65d9f6a2f0fd8100c423e13524b8cd3b7c6b960192601b8', 1); + CREATE TABLE "meta" (space_id VARCHAR PRIMARY KEY NOT NULL); + CREATE TABLE "snapshots" ( + doc_id VARCHAR PRIMARY KEY NOT NULL, + data BLOB NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL + ); + CREATE TABLE "updates" ( + doc_id VARCHAR NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + data BLOB NOT NULL, + PRIMARY KEY (doc_id, created_at) + ); + CREATE TABLE "clocks" ( + doc_id VARCHAR PRIMARY KEY NOT NULL, + timestamp TIMESTAMP NOT NULL + ); + CREATE TABLE "blobs" ( + key VARCHAR PRIMARY KEY NOT NULL, + data BLOB NOT NULL, + mime VARCHAR NOT NULL, + size INTEGER NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + deleted_at TIMESTAMP + ); + CREATE TABLE "peer_clocks" ( + peer VARCHAR NOT NULL, + doc_id VARCHAR NOT NULL, + remote_clock TIMESTAMP NOT NULL DEFAULT 0, + pulled_remote_clock TIMESTAMP NOT NULL DEFAULT 0, + pushed_clock TIMESTAMP NOT NULL DEFAULT 0, + inventory_kind TEXT, + lifecycle TEXT, + lifecycle_changed_at INTEGER, + pending_create BOOLEAN NOT NULL DEFAULT FALSE, + inventory_ready BOOLEAN NOT NULL DEFAULT FALSE, + cache_token INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (peer, doc_id) + ); + CREATE INDEX peer_clocks_doc_id ON peer_clocks (doc_id); + CREATE TABLE "peer_blob_sync" ( + peer VARCHAR NOT NULL, + blob_id VARCHAR NOT NULL, + uploaded_at TIMESTAMP, + PRIMARY KEY (peer, blob_id) + ); + CREATE INDEX peer_blob_sync_peer ON peer_blob_sync (peer); + CREATE TABLE idx_snapshots ( + index_name TEXT PRIMARY KEY NOT NULL, + data BLOB NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL + ); + CREATE TABLE "indexer_sync" ( + doc_id VARCHAR PRIMARY KEY NOT NULL, + indexed_clock TIMESTAMP NOT NULL DEFAULT 0, + indexer_version INTEGER NOT NULL DEFAULT 0 + ); + INSERT INTO meta (space_id) VALUES ('ws-0275-drill'); + """ + requireS3(sqlite3_exec(rawDb, ddl, nil, nil, nil) == SQLITE_OK, "0.27.5 schema DDL must succeed") + + // Genuine JavaScript Yjs (13.6.x) V1 updates for root workspace `ws-0275-drill` & page `doc-0275` (`para-0275-1` = "Seeded in 0.27.5"): + let yjsRootV1 = Data( + base64Encoded: "AQcFACcBBG1ldGEFcGFnZXMABwAFAAEoAAUBAmlkAXcIZG9jLTAyNzUoAAUBBXRpdGxlAXcUMC4yNy41IEV4aXN0aW5nIE5vdGUoAAUBCmNyZWF0ZURhdGUBe0J6IiMYOAAAJwAFAQR0YWdzACkBBnNwYWNlcwhkb2MtMDI3NQhkb2MtMDI3NXYAAA==" + )! + let yjsPageV1 = Data( + base64Encoded: "AR8FACcBBmJsb2NrcwlwYWdlLTAyNzUBKAAFAAZzeXM6aWQBdwlwYWdlLTAyNzUoAAUAC3N5czpmbGF2b3VyAXcLYWZmaW5lOnBhZ2UoAAUAC3N5czp2ZXJzaW9uAX0CJwAFAApwcm9wOnRpdGxlAgQABQQUMC4yNy41IEV4aXN0aW5nIE5vdGUnAAUADHN5czpjaGlsZHJlbgAIAAUZAncMc3VyZmFjZS0wMjc1dwlub3RlLTAyNzUnAQZibG9ja3MMc3VyZmFjZS0wMjc1ASgABRwGc3lzOmlkAXcMc3VyZmFjZS0wMjc1KAAFHAtzeXM6Zmxhdm91cgF3DmFmZmluZTpzdXJmYWNlKAAFHAtzeXM6dmVyc2lvbgF9BScABRwMc3lzOmNoaWxkcmVuACcABRwNcHJvcDplbGVtZW50cwEnAQZibG9ja3MJbm90ZS0wMjc1ASgABSIGc3lzOmlkAXcJbm90ZS0wMjc1KAAFIgtzeXM6Zmxhdm91cgF3C2FmZmluZTpub3RlKAAFIgtzeXM6dmVyc2lvbgF9ASgABSIJcHJvcDp4eXdoAXcNWzAsMCw4MDAsNDAwXSgABSIKcHJvcDppbmRleAF3AmEwKAAFIhBwcm9wOmRpc3BsYXlNb2RlAXcEYm90aCcABSIMc3lzOmNoaWxkcmVuAAgABSkBdwtwYXJhLTAyNzUtMScBBmJsb2NrcwtwYXJhLTAyNzUtMQEoAAUrBnN5czppZAF3C3BhcmEtMDI3NS0xKAAFKwtzeXM6Zmxhdm91cgF3EGFmZmluZTpwYXJhZ3JhcGgoAAUrC3N5czp2ZXJzaW9uAX0BKAAFKwlwcm9wOnR5cGUBdwR0ZXh0JwAFKwlwcm9wOnRleHQCBAAFMBBTZWVkZWQgaW4gMC4yNy41JwAFKwxzeXM6Y2hpbGRyZW4AAA==" + )! + let seedRows: [(String, String, Data)] = [ + ("ws-0275-drill", "2026-11-28 12:00:01.000", yjsRootV1), + ("doc-0275", "2026-11-28 12:00:02.000", yjsPageV1), + ] + let sqlTransient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + for (docId, tsText, bin) in seedRows { + var stmt: OpaquePointer? + requireS3( + sqlite3_prepare_v2(rawDb, "INSERT INTO updates (doc_id, created_at, data) VALUES (?1, ?2, ?3);", -1, &stmt, nil) == SQLITE_OK, + "prepare INSERT INTO updates" + ) + _ = docId.withCString { sqlite3_bind_text(stmt, 1, $0, -1, sqlTransient) } + _ = tsText.withCString { sqlite3_bind_text(stmt, 2, $0, -1, sqlTransient) } + _ = bin.withUnsafeBytes { raw in + sqlite3_bind_blob(stmt, 3, raw.baseAddress, Int32(bin.count), sqlTransient) + } + requireS3(sqlite3_step(stmt) == SQLITE_DONE, "step INSERT INTO updates for \(docId)") + sqlite3_finalize(stmt) + + var clkStmt: OpaquePointer? + requireS3( + sqlite3_prepare_v2(rawDb, "INSERT INTO clocks (doc_id, timestamp) VALUES (?1, ?2);", -1, &clkStmt, nil) == SQLITE_OK, + "prepare INSERT INTO clocks" + ) + _ = docId.withCString { sqlite3_bind_text(clkStmt, 1, $0, -1, sqlTransient) } + _ = tsText.withCString { sqlite3_bind_text(clkStmt, 2, $0, -1, sqlTransient) } + requireS3(sqlite3_step(clkStmt) == SQLITE_DONE, "step INSERT INTO clocks for \(docId)") + sqlite3_finalize(clkStmt) + } + requireS3(sqlite3_exec(rawDb, "PRAGMA wal_checkpoint(FULL);", nil, nil, nil) == SQLITE_OK, "0.27.5 seed WAL checkpoint") + } + + // Keep an unmigrated copy of the 0.27.5 seed for the fail-closed timeout check in step 2b. + let failClosedDocs = FileManager.default.temporaryDirectory + .appendingPathComponent("affine-ios-0275-fail-closed-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: failClosedDocs, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: failClosedDocs) } + try FileManager.default.copyItem( + at: tmpDocs.appendingPathComponent("workspaces", isDirectory: true), + to: failClosedDocs.appendingPathComponent("workspaces", isDirectory: true) + ) + let failClosedDbFile = failClosedDocs + .appendingPathComponent("workspaces/workspace/local/ws-0275-drill.db") + let failClosedSeedBytes = try Data(contentsOf: failClosedDbFile) + + let probeHostWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + probeHostWindow.rootViewController = UIViewController() + probeHostWindow.makeKeyAndVisible() + defer { probeHostWindow.isHidden = true } + + func reportWebViewStep(_ step: String) { + smokeLog("iOS smoke [7/8]: \(step)") + } + + reportWebViewStep("write the legacy localStorage fixture") + let probe = LegacyLocalStorageProbe(hostWindowProvider: { probeHostWindow }) + let seeded = try await probe.writeBackLegacyLocalStorage( + set: [ + "affine-local-workspace": "[\"ws-0275-drill\"]", + "theme": "light", + "last_workspace_id": "ws-0275-drill", + ], + remove: [] + ) + requireS3(seeded.origin == "capacitor://localhost" && seeded.idbAccessCount == 0, "0.27.5 seed must run on capacitor://localhost with 0 IDB") + requireS3( + probeHostWindow.subviews.allSatisfy { !($0 is WKWebView) }, + "LegacyLocalStorageProbe.finish() must detach hidden WKWebView from host window after writeBack" + ) + + // 2) New host captures real WKWebView sentinel, mounts `/workspaces/workspace/local/ws-0275-drill.db` in place, edits existing doc & checkpoints WAL. + let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDocs, probe: probe) + reportWebViewStep("read the legacy fixture and open the SQLite workspace") + let disp = try await coordinator.bootstrapFromLegacyStorage() + requireS3( + coordinator.imported && !coordinator.canCreateDefaultWorkspace, + "Bootstrapped existing user must set imported=true and canCreateDefaultWorkspace=false" + ) + requireS3(disp.status == "existing_user" && disp.state.localWorkspaceIds == ["ws-0275-drill"], "new host must import ws-0275-drill from real WKWebView") + guard let ws = coordinator.workspace(id: "ws-0275-drill") else { + requireS3(false, "ws-0275-drill must mount in place") + return + } + let missingEdit = ws.editParagraphText( + docId: "non-existent-doc", + blockId: "p-1", + utf16Index: 0, + deleteLen: 0, + insertText: "must fail", + clientId: 7, + nowMs: 1_795_880_000_000 + ) + requireS3(missingEdit == nil, "editParagraphText must fail on non-existent document instead of auto-creating") + let editBytes = ws.editParagraphText( + docId: "doc-0275", + blockId: "para-0275-1", + utf16Index: 0, + deleteLen: 16, + insertText: "Edited in native 0.28", + clientId: 7, + nowMs: 1_795_880_000_000 + ) + requireS3(editBytes != nil && !editBytes!.isEmpty, "in-place SQLite edit on seeded 0.27.5 block must emit CRDT update") + requireS3(coordinator.checkpointAllPassive(), "PASSIVE WAL checkpoint must succeed") + + // 2b) Deterministic fail-closed probe timeout test (0ms wall-clock via injected timeoutScheduler): + // when LegacyLocalStorageProbe fails/times out, HostBootstrapCoordinator MUST fail closed + // (`imported == false`, `canCreateDefaultWorkspace == false`, zero SQLite mounts or deletions) + // and remain retryable on next launch. It runs after the real probe so that the first + // `WKWebView` of the process completes the cold WebContent handshake without a teardown, + // and it uses its own unmigrated Documents copy. + do { + let failingProbe = LegacyLocalStorageProbe( + timeoutScheduler: { _, onTimeout in + onTimeout() + return {} + }, + hostWindowProvider: { probeHostWindow } + ) + let failClosedCoord = HostBootstrapCoordinator(documentsDirectory: failClosedDocs, probe: failingProbe) + var sawTimeout = false + do { + _ = try await failClosedCoord.bootstrapFromLegacyStorage() + } catch let err as LegacyLocalStorageProbeError where err == .timedOut { + sawTimeout = true + } + requireS3(sawTimeout, "Deterministic probe timeout must throw LegacyLocalStorageProbeError.timedOut") + requireS3( + !failClosedCoord.imported + && !failClosedCoord.canCreateDefaultWorkspace + && failClosedCoord.mountedWorkspacesSnapshot().isEmpty + && failClosedCoord.allowlistedLocalIds.isEmpty + && failClosedCoord.lastSnapshot == nil + && (try? Data(contentsOf: failClosedDbFile)) == failClosedSeedBytes, + "Timed-out LegacyLocalStorageProbe must fail closed with imported=false, canCreateDefaultWorkspace=false, zero mounts, and untouched legacy DB" + ) + requireS3( + probeHostWindow.subviews.allSatisfy { !($0 is WKWebView) }, + "LegacyLocalStorageProbe.finish() must detach hidden WKWebView from host window even on timeout" + ) + } + + // 3) Add a new local workspace & plan rollback write-back -> write back to real WKWebView. + try coordinator.applyLocalWorkspaceAllowlist(["ws-0275-drill", "ws-0275-added"]) + let plan = try coordinator.buildRollbackWriteBackPlan() + requireS3( + (plan.set["affine-local-workspace"] ?? "").contains("ws-0275-added"), + "rollback writeback plan must include ws-0275-added" + ) + reportWebViewStep("write back the rollback plan") + let writtenBack = try await probe.writeBackLegacyLocalStorage(set: plan.set, remove: plan.remove) + requireS3(writtenBack.idbAccessCount == 0, "rollback writeback must keep idbAccessCount == 0") + coordinator.closeAll() + + // 4) Simulated old 0.27.5 shell reads back from real WKWebView + re-opens in-place SQLite DB. + reportWebViewStep("read back the old shell localStorage") + let oldShellReadback = try await probe.capture() + requireS3( + (oldShellReadback.entries["affine-local-workspace"] ?? "").contains("ws-0275-drill") + && (oldShellReadback.entries["affine-local-workspace"] ?? "").contains("ws-0275-added"), + "old 0.27.5 WKWebView must read back both original and added workspaces" + ) + let verifyCoord = HostBootstrapCoordinator(documentsDirectory: tmpDocs) + try verifyCoord.applyLocalWorkspaceAllowlist(["ws-0275-drill"]) + let reopenedWs = verifyCoord.workspace(id: "ws-0275-drill") + let reopenedDiff = reopenedWs?.exportPendingDiff(docId: "doc-0275", remoteStateVector: nil) + let reopenedSnap = reopenedWs?.readPageSnapshotJson(docId: "doc-0275", clientId: 7) ?? "" + requireS3( + reopenedDiff != nil && !reopenedDiff!.isEmpty && reopenedSnap.contains("Edited in native 0.28"), + "old 0.27.5 SQLite workspace must preserve native-edited doc content intact (snap=\(reopenedSnap))" + ) + verifyCoord.closeAll() + + smokeLog("PASS [7/8]: 0.27.5 real WKWebView + in-place SQLite same-signature upgrade & rollback readback drill passed") + } + + /// Center of the first (topmost) shell accessibility node whose ID starts with `prefix`. + static func shellNodeCenter(_ host: OpaquePointer, _ prefix: String) -> CGPoint? { + guard let raw = affine_ios_host_shell_accessibility_json(host) else { + return nil + } + defer { affine_ios_string_free(raw) } + guard + let data = String(cString: raw).data(using: .utf8), + let tree = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let nodes = tree["nodes"] as? [String: [String: Any]] + else { + return nil + } + var best: CGRect? + for (id, node) in nodes where id.hasPrefix(prefix) { + guard let b = node["bounds"] as? [String: Double] else { continue } + let rect = CGRect(x: b["x"] ?? 0, y: b["y"] ?? 0, width: b["width"] ?? 0, height: b["height"] ?? 0) + if rect.width > 0, rect.height > 0, best.map({ rect.minY < $0.minY }) ?? true { + best = rect + } + } + return best.map { CGPoint(x: $0.midX, y: $0.midY) } + } + + /// Taps the shell node `prefix` through the C ABI touch path that `MetalHostView` forwards. + static func shellTap(_ host: OpaquePointer, _ view: MetalHostView, _ id: UInt64, _ prefix: String) { + guard let point = shellNodeCenter(host, prefix) else { + requireS3(false, "shell node \(prefix) must be published with bounds") + return + } + // Page text taps belong to `UITextInteraction`; shell chrome taps go straight to Rust. + let ownedByText = prefix.hasPrefix("mobile.page.block.") + requireS3( + affine_ios_host_should_forward_touch_immediately(host, Float(point.x), Float(point.y)) != ownedByText, + "shell tap on \(prefix) must go to \(ownedByText ? "UITextInteraction" : "Rust") first" + ) + affine_ios_host_touch_event(host, id, 0, Float(point.x), Float(point.y)) + affine_ios_host_touch_event(host, id, 2, Float(point.x), Float(point.y)) + view.handleForwardedTouchCompletion() + _ = affine_ios_host_render_frame(host, Double(id)) + } + + static func shellText(_ host: OpaquePointer) -> String { + let len = affine_ios_host_utf16_len(host) + var units = [UInt16](repeating: 0, count: len) + let copied = units.withUnsafeMutableBufferPointer { buf in + affine_ios_host_copy_utf16(host, buf.baseAddress, len) + } + return String(decoding: units.prefix(copied), as: UTF16.self) + } + + /// 8. Mobile shell root: launch on the 4-TabBar `Home`, open a document into the `Page` route, + /// type CJK and Latin text through `UITextInput` into the embedded editor, query caret + /// geometry, return with back, type into `Search` through the same `UITextInput`, unwind + /// the route history with `MobileBackCoordinator`, and reopen a flushed SQLite workspace. + @MainActor + static func testMobileShellRootRoutesTextInputSearchBackAndSqliteReopen() throws { + let vc = MetalHostViewController(root: .shell) + vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vc.loadViewIfNeeded() + vc.view.layoutIfNeeded() + guard let host = vc.hostPointer else { + requireS3(false, "shell MetalHostViewController must initialize hostHandle") + return + } + let view = vc.textHostView + _ = affine_ios_host_render_frame(host, 0.1) + requireS3(affine_ios_host_shell_route(host) == 1, "shell must launch on Home") + requireS3(shellNodeCenter(host, "mobile.tab.search") != nil, "Home must show the 4-TabBar") + requireS3(affine_ios_host_utf16_len(host) == 0, "Home must expose no editor text") + + shellTap(host, view, 1, "mobile.home.doc.") + requireS3(affine_ios_host_shell_route(host) == 5, "Home row tap must open the Page route") + shellTap(host, view, 2, "mobile.page.block.") + requireS3(affine_ios_host_wants_software_keyboard(host), "page block tap must want the keyboard") + let before = affine_ios_host_utf16_len(host) + view.insertText("Hi 世界") + requireS3( + affine_ios_host_utf16_len(host) == before + 5 && shellText(host).contains("Hi 世界"), + "UITextInput must write into the embedded page editor, got '\(shellText(host))'" + ) + if let selected = view.selectedTextRange { + let caret = view.caretRect(for: selected.end) + requireS3(caret.height > 0 && caret.minY > 0, "page caret rect must be live, got \(caret)") + } else { + requireS3(false, "page editor must expose a selected AffineTextRange") + } + + requireS3(affine_ios_host_handle_back(host), "back must leave the page") + _ = affine_ios_host_render_frame(host, 3.0) + requireS3(affine_ios_host_shell_route(host) == 1, "back must return to Home") + requireS3(affine_ios_host_utf16_len(host) == 0, "Home must release the page editor input") + + shellTap(host, view, 4, "mobile.tab.search") + requireS3(affine_ios_host_shell_route(host) == 4, "Search tab tap must open Search") + shellTap(host, view, 5, "mobile.search.input") + requireS3( + affine_ios_host_wants_software_keyboard(host) && !affine_ios_host_is_surface_readonly(host), + "Search field focus must want the keyboard" + ) + requireS3(affine_ios_host_utf16_len(host) == 0, "Search must launch with an empty query") + view.insertText("同步") + requireS3(shellText(host) == "同步", "UITextInput must write the Search query, got '\(shellText(host))'") + + var steps = 0 + while affine_ios_host_handle_back(host) { + steps += 1 + requireS3(steps < 8, "back must reach the root route") + } + requireS3(affine_ios_host_shell_route(host) == 1, "back must unwind to Home") + + let base = FileManager.default.temporaryDirectory.appendingPathComponent("shell-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: base) } + func openShell() -> OpaquePointer? { + let shell = "en-US".withCString { tag in + affine_ios_host_create_shell(nil, 390, 844, 3, tag, 1_764_000_000_000, 480, false) + } + guard let shell else { return nil } + let mounted = base.path.withCString { dir in + affine_ios_host_shell_mount_workspace(shell, dir, "workspace", "local", "ws-local", "Local", 1_764_000_000_000) + } + requireS3(mounted, "shell must mount the local SQLite workspace") + _ = affine_ios_host_render_frame(shell, 0.1) + return shell + } + guard let first = openShell() else { + requireS3(false, "shell host create failed") + return + } + requireS3(shellNodeCenter(first, "mobile.home.doc.") == nil, "local workspace must hide showcase rows") + shellTap(first, view, 10, "mobile.home.new_doc_btn") + requireS3(affine_ios_host_shell_route(first) == 5, "new document must open the Page route") + shellTap(first, view, 11, "mobile.page.block.") + let saved = Array("Saved 本地".utf16) + saved.withUnsafeBufferPointer { buf in + affine_ios_host_insert_text(first, buf.baseAddress, buf.count) + } + let savedText = shellText(first) + requireS3(savedText.contains("Saved 本地"), "shell page must hold typed text, got '\(savedText)'") + requireS3(affine_ios_host_shell_flush_workspace(first) >= 0, "flush must commit the shell edits") + affine_ios_host_destroy(first) + + guard let reopened = openShell() else { + requireS3(false, "reopened shell host create failed") + return + } + defer { affine_ios_host_destroy(reopened) } + shellTap(reopened, view, 12, "mobile.home.doc.") + requireS3(affine_ios_host_shell_route(reopened) == 5, "reopened Home row must open the page") + shellTap(reopened, view, 13, "mobile.page.block.") + requireS3(shellText(reopened) == savedText, "cold reopen must show '\(savedText)', got '\(shellText(reopened))'") + + smokeLog("PASS [8/8]: mobile shell root Home -> Page UITextInput CJK + caret, back, Search UITextInput, back unwind, and SQLite cold reopen passed") + } +} diff --git a/packages/frontend/hosts/web/AGENTS.md b/packages/frontend/hosts/web/AGENTS.md new file mode 100644 index 0000000000..cb0150c1cc --- /dev/null +++ b/packages/frontend/hosts/web/AGENTS.md @@ -0,0 +1,50 @@ +# Working in `packages/frontend/hosts/web/` (for agents) + +This directory holds the zero-build Web Mobile host and the `desktop/` Workbench entry for AFFiNE. +It uses plain HTML and standard ES modules with JSDoc types. +`desktop/start.js` keeps each Workbench workspace in the same IndexedDB v3 store as the Web Mobile host (`src/idb-storage.js`), passes the stored update frames to `wasm_desktop_main`, and calls `flush_web_desktop` when the page is hidden or unloaded. + +## Hard boundaries + +- Keep zero `package.json` files and zero `yarn.lock` files in `packages/frontend/hosts/`. +- Keep zero third-party npm imports in `src/*.js`. Use relative ES module imports only. +- Keep `index.html` Content Security Policy free of third-party script domains. +- Keep permanent visual DOM in `index.html` limited to `` and ` + +
+
+
+ + +

Loading AFFiNE...

+
+ + + + diff --git a/packages/frontend/hosts/web/scripts/chromium-harness.mjs b/packages/frontend/hosts/web/scripts/chromium-harness.mjs new file mode 100644 index 0000000000..3974ac0718 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/chromium-harness.mjs @@ -0,0 +1,685 @@ +// @ts-check + +/** + * Lifecycle owner for the real-browser verification scripts. + * + * One harness owns one temporary work directory and each process group that + * the script starts. The Chromium profile is in the work directory. Chromium + * also uses the work directory as its temporary directory, so the harness + * removes the files that Chromium leaves there. + * + * Each process starts detached, as the leader of its own process group, so + * one signal reaches the process and all its descendants. The harness does + * not own a server behind a URL that the caller passes in, and never signals + * that server. + * + * A normal end, a failed assertion, `SIGINT`, and `SIGTERM` all go through + * `close()`. `close()` waits a limited time for each process group, and + * removes the work directory only after each process group is gone. A forced + * `process.exit()` cannot wait, so the `exit` handler kills each process group + * and then removes the work directory. + * + * When the harness cannot signal a process group, or the group stays alive, + * the work directory stays and its path goes to stderr. + * + * Uses a preinstalled Chromium and never runs `playwright install`. + */ + +import { execFileSync, spawn } from 'node:child_process'; +import { + closeSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readSync, + rmSync, +} from 'node:fs'; +import { constants, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +const DEFAULT_LIMITS = { + /** How long a process group has to end after `SIGTERM`. */ + termGraceMs: 2000, + /** How long a process group has to be gone after `SIGKILL`. */ + groupGoneTimeoutMs: 2000, + /** How long a server has to answer its health check. */ + serverHealthTimeoutMs: 20000, +}; +const GROUP_PROBE_INTERVAL_MS = 20; +const SERVER_HEALTH_INTERVAL_MS = 100; +const DEVTOOLS_TIMEOUT_MS = 15000; + +const CHROMIUM_ARGS = [ + '--headless=new', + '--no-sandbox', + '--enable-unsafe-swiftshader', + '--disable-dev-shm-usage', + '--disable-background-networking', + '--no-first-run', + '--no-default-browser-check', + '--password-store=basic', + '--use-mock-keychain', + '--disable-sync', + '--disable-extensions', + '--disable-component-update', + '--disable-dbus', + '--metrics-recording-only', + '--remote-debugging-port=0', +]; + +// Allow 45 seconds for a single cold SwiftShader DevTools handshake. +export const SWIFTSHADER_OPTIONS = { + timeoutMs: 45000, + args: [ + '--use-gl=angle', + '--use-angle=swiftshader', + '--enable-webgl', + '--ignore-gpu-blocklist', + '--disable-gpu-sandbox', + '--window-size=1280,800', + ], +}; + +/** @param {string} debugPort */ +export async function openPageTarget(debugPort, url = 'about:blank') { + const response = await fetch( + `http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(url)}`, + { method: 'PUT' } + ); + if (!response.ok) { + throw new Error(`Cannot open a Chromium page (HTTP ${response.status})`); + } + const target = await response.json(); + if ( + typeof target?.webSocketDebuggerUrl !== 'string' || + !target.webSocketDebuggerUrl + ) { + throw new Error('Chromium returned a page without a debugger URL'); + } + return target; +} + +/** @param {string} debugPort */ +export async function connectBrowserTarget(debugPort) { + const signal = AbortSignal.timeout(DEVTOOLS_TIMEOUT_MS); + const response = await fetch(`http://127.0.0.1:${debugPort}/json/version`, { + signal, + }); + if (!response.ok) { + throw new Error( + `Cannot find the Chromium debugger (HTTP ${response.status})` + ); + } + const { webSocketDebuggerUrl } = await response.json(); + signal.throwIfAborted(); + const ws = new WebSocket(webSocketDebuggerUrl); + try { + await new Promise((resolve, reject) => { + ws.addEventListener('open', resolve, { once: true, signal }); + ws.addEventListener('error', reject, { once: true, signal }); + signal.addEventListener('abort', () => reject(signal.reason), { + once: true, + }); + }); + } catch (error) { + ws.close(); + throw error; + } + + let nextId = 0; + /** + * @param {string} method + * @returns {Promise} + */ + function send(method, params = {}) { + const id = ++nextId; + const listeners = new AbortController(); + return new Promise((resolve, reject) => { + const options = { signal: listeners.signal }; + const closed = () => + reject(new Error('Chromium browser debugger closed')); + ws.addEventListener('close', closed, options); + ws.addEventListener('error', closed, options); + ws.addEventListener( + 'message', + event => { + const reply = JSON.parse(event.data); + if (reply.id !== id) return; + if (reply.error) reject(new Error(reply.error.message)); + else resolve(reply.result); + }, + options + ); + const timer = setTimeout( + () => + reject(new Error(`Chromium browser debugger timed out on ${method}`)), + DEVTOOLS_TIMEOUT_MS + ); + listeners.signal.addEventListener('abort', () => clearTimeout(timer)); + if (ws.readyState !== WebSocket.OPEN) closed(); + else ws.send(JSON.stringify({ id, method, params })); + }).finally(() => listeners.abort()); + } + + return { + send, + /** @param {string} targetId */ + pageDebuggerUrl: targetId => + new URL(`/devtools/page/${targetId}`, webSocketDebuggerUrl).href, + close: () => ws.close(), + }; +} + +/** + * Runs one callback in a new browser context. Close the page before the context. + * @template {{ close: () => void }} Page + * @param {Awaited>} browser + * @param {(url: string) => Promise} connectPage + * @param {(page: Page) => Promise} run + */ +export async function withIsolatedPage(browser, connectPage, run) { + const { browserContextId } = await browser.send( + 'Target.createBrowserContext', + { + disposeOnDetach: true, + } + ); + try { + const { targetId } = await browser.send('Target.createTarget', { + url: 'about:blank', + browserContextId, + }); + try { + const page = await connectPage(browser.pageDebuggerUrl(targetId)); + try { + await run(page); + } finally { + page.close(); + } + } finally { + await browser.send('Target.closeTarget', { targetId }); + } + } finally { + await browser.send('Target.disposeBrowserContext', { browserContextId }); + } +} + +/** @param {string} prefix */ +function createWorkDirectory(prefix) { + // sockaddr_un.sun_path includes the terminating NUL (sys/un.h). + const limit = process.platform === 'darwin' ? 104 : 108; + let rejectedPath = ''; + for (const root of new Set([tmpdir(), '/tmp'])) { + const dir = join(root, prefix + 'XXXXXX'); + // The macOS socket directory name is longer than the Linux name. + const socket = join( + dir, + '.org.chromium.Chromium.scoped_dir.XXXXXX', + 'SingletonSocket' + ); + const bytes = Buffer.byteLength(socket) + 1; + if (bytes <= limit) { + const workDir = mkdtempSync(join(root, prefix)); + if (rejectedPath) console.warn(`${rejectedPath}. Using ${workDir}`); + return workDir; + } + rejectedPath = `Chromium socket path needs ${bytes} bytes (limit ${limit}): ${socket}`; + if (root === '/tmp') throw new Error(rejectedPath); + } + throw new Error('Cannot select a Chromium socket directory'); +} + +/** + * Close all resources even if one close fails. + * @param {{ close: () => Promise } | undefined} harness + * @param {{ close: () => void } | null | undefined} connection + * @param {import('node:http').Server | undefined} [server] + */ +export async function closeBrowserResources(harness, connection, server) { + const results = await Promise.allSettled([ + Promise.resolve().then(() => connection?.close()), + Promise.resolve().then(() => harness?.close()), + server?.listening + ? new Promise((resolve, reject) => { + server.close(err => (err ? reject(err) : resolve(undefined))); + }) + : undefined, + ]); + const failures = results.filter(result => result.status === 'rejected'); + if (failures.length) { + throw new AggregateError( + failures.map(f => f.reason), + 'Browser cleanup failed' + ); + } +} + +/** + * @typedef {object} OwnedGroup + * @property {string} label + * @property {number} pgid + * @property {import('node:child_process').ChildProcess} child + * @property {Promise} exited Resolves when Node has reaped the direct child. + * @property {boolean} gone + */ + +/** + * Sends `signal` to a process group and reports the answer of the kernel. + * + * @param {number} pgid + * @param {NodeJS.Signals | 0} signal + * @returns {'alive' | 'gone' | 'denied'} + */ +function signalGroup(pgid, signal) { + try { + process.kill(-pgid, signal); + return 'alive'; + } catch (err) { + const code = /** @type {NodeJS.ErrnoException} */ (err).code; + if (code === 'ESRCH') { + return 'gone'; + } + if (code === 'EPERM') { + return 'denied'; + } + throw err; + } +} + +/** @param {string} bin */ +function isShellScriptWrapper(bin) { + try { + const fd = openSync(bin, 'r'); + try { + const buf = Buffer.alloc(2); + return readSync(fd, buf, 0, 2, 0) === 2 && buf.toString() === '#!'; + } finally { + closeSync(fd); + } + } catch { + return false; + } +} + +/** + * Uses the path from `CHROME_PATH` or `CHROME_BIN` as given. Without one, it + * prefers a real browser binary. A launcher script (a snap or a distribution + * wrapper) is used only when no binary is found. + */ +function findChromiumBinary() { + const explicit = process.env.CHROME_PATH || process.env.CHROME_BIN; + if (explicit) { + if (!existsSync(explicit)) { + throw new Error( + `The browser path from CHROME_PATH or CHROME_BIN does not exist: ${explicit}` + ); + } + return explicit; + } + const candidates = [ + ...(process.platform === 'darwin' + ? [ + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + ] + : []), + '/usr/bin/google-chrome-stable', + '/usr/bin/google-chrome', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + ]; + let wrapperFallback = null; + for (const bin of candidates) { + if (!existsSync(bin)) { + continue; + } + if (isShellScriptWrapper(bin)) { + wrapperFallback ??= bin; + continue; + } + return bin; + } + const pwDir = join(process.env.HOME || '', '.cache/ms-playwright'); + if (existsSync(pwDir)) { + const found = execFileSync( + 'find', + [pwDir, '-name', 'chrome', '-type', 'f'], + { encoding: 'utf8' } + ) + .split('\n') + .map(line => line.trim()) + .find(Boolean); + if (found) { + return found; + } + } + if (wrapperFallback) { + return wrapperFallback; + } + throw new Error('No preinstalled Chromium binary found on this machine'); +} + +/** + * @param {{ tmpPrefix: string, limits?: Partial }} options + * `tmpPrefix` names the work directory under the system temporary directory. + * `limits` replaces time limits. Only the lifecycle tests pass it. + */ +export function createChromiumHarness({ tmpPrefix, limits: limitOverrides }) { + const limits = { ...DEFAULT_LIMITS, ...limitOverrides }; + const workTmp = createWorkDirectory(tmpPrefix); + const profileDir = join(workTmp, 'chrome-profile'); + try { + mkdirSync(profileDir); + } catch (err) { + rmSync(workTmp, { recursive: true, force: true }); + throw err; + } + + /** @type {OwnedGroup[]} */ + const groups = []; + /** `close()` aborts this controller. Then the teardown is in progress. */ + const teardown = new AbortController(); + /** @type {Promise | null} */ + let closing = null; + + /** + * Removes the work directory, or keeps it and prints why. + * + * @param {string[]} problems + */ + const releaseWorkTmp = problems => { + if (problems.length === 0) { + try { + rmSync(workTmp, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 100, + }); + return; + } catch (err) { + problems = [`removal failed: ${String(err)}`]; + } + } + console.error(`[chromium-harness] kept ${workTmp}: ${problems.join('; ')}`); + }; + + /** + * @param {OwnedGroup} group + * @param {boolean} denied + */ + const describeSurvivor = (group, denied) => + `${group.label} process group ${group.pgid} ${ + denied ? 'cannot be signalled (EPERM)' : 'is still alive' + }`; + + /** + * Stops one process group and waits until it is gone. + * + * @param {OwnedGroup} group + * @returns {Promise} The reason the group survives, or `null`. + */ + const reapGroup = async group => { + if (group.gone) { + return null; + } + let answer = signalGroup(group.pgid, 'SIGTERM'); + if (answer === 'alive') { + /** @type {NodeJS.Timeout | undefined} */ + let grace; + await Promise.race([ + group.exited, + new Promise(resolve => { + grace = setTimeout(resolve, limits.termGraceMs); + }), + ]); + clearTimeout(grace); + } + if (!group.gone && answer !== 'gone') { + // Kill the members that ignore `SIGTERM` or outlive the direct child. + // Then probe. A zombie still answers signal 0. On macOS, a group that + // holds only zombies answers `EPERM` until the system reaps them. Thus + // only `ESRCH` means that every member is reaped. + answer = signalGroup(group.pgid, 'SIGKILL'); + const deadline = Date.now() + limits.groupGoneTimeoutMs; + while (answer !== 'gone' && Date.now() < deadline) { + await delay(GROUP_PROBE_INTERVAL_MS); + answer = signalGroup(group.pgid, 0); + } + } + if (answer === 'gone') { + group.gone = true; + } + if (group.gone) { + return null; + } + // Let the script end although this child cannot be reaped. + group.child.unref(); + group.child.stdout?.destroy(); + group.child.stderr?.destroy(); + return describeSurvivor(group, answer === 'denied'); + }; + + const close = () => { + teardown.abort(); + closing ??= (async () => { + const survivors = await Promise.all(groups.map(reapGroup)); + process.off('exit', onExit); + process.off('SIGINT', onSignal); + process.off('SIGTERM', onSignal); + releaseWorkTmp(survivors.filter(reason => reason !== null)); + })(); + return closing; + }; + + // The event loop has stopped: no child can be awaited, and a zombie still + // answers signal 0. Kill each group without a probe. + const onExit = () => { + const problems = []; + for (const group of groups) { + if (!group.gone && signalGroup(group.pgid, 'SIGKILL') === 'denied') { + problems.push(describeSurvivor(group, true)); + } + } + releaseWorkTmp(problems); + }; + + /** @param {NodeJS.Signals} signal */ + const onSignal = signal => { + void close().then(() => process.exit(128 + constants.signals[signal])); + }; + + process.on('exit', onExit); + process.on('SIGINT', onSignal); + process.on('SIGTERM', onSignal); + + /** @param {string} label */ + const refuseDuringTeardown = label => { + if (teardown.signal.aborted) { + throw new Error(`Refused ${label}: teardown is in progress`); + } + }; + + /** + * Starts a detached process and registers its process group. + * + * @param {string} label + * @param {string} bin + * @param {string[]} args + * @param {import('node:child_process').SpawnOptions} options + */ + const spawnOwned = (label, bin, args, options) => { + refuseDuringTeardown(`start of ${label}`); + const child = spawn(bin, args, { ...options, detached: true }); + const pgid = child.pid; + /** @type {Promise} */ + const exited = new Promise(resolve => { + child.once('exit', () => resolve()); + child.once('error', () => resolve()); + }); + if (pgid === undefined) { + throw new Error(`Failed to start ${label}: ${bin}`); + } + const group = { label, pgid, child, exited, gone: false }; + // The group can be empty when its leader exits. Record that now. Later, + // the system can give the same ID to a process group of a different owner. + child.once('exit', () => { + group.gone = signalGroup(pgid, 0) === 'gone'; + }); + groups.push(group); + return child; + }; + + /** + * Starts a server and waits until `/healthz` answers. + * + * A server that binds to an assigned port can publish its URL after start. + * + * @param {{ bin: string, args: string[], baseUrl: string | (() => string | undefined) }} options + */ + const startServer = async ({ bin, args, baseUrl }) => { + const server = spawnOwned('server', bin, args, { + stdio: ['ignore', 'pipe', 'pipe'], + }); + let logs = ''; + for (const stream of [server.stdout, server.stderr]) { + stream?.on('data', chunk => { + logs += String(chunk); + }); + } + const deadline = Date.now() + limits.serverHealthTimeoutMs; + let healthy = false; + let url = typeof baseUrl === 'string' ? baseUrl : undefined; + while ( + !healthy && + !teardown.signal.aborted && + server.exitCode === null && + server.signalCode === null && + Date.now() < deadline + ) { + if (typeof baseUrl === 'function') url ??= baseUrl(); + if (!url) { + await delay(SERVER_HEALTH_INTERVAL_MS); + continue; + } + try { + // The time limit and the teardown each stop a request in flight. + const res = await fetch(`${url}/healthz`, { + signal: AbortSignal.any([ + teardown.signal, + AbortSignal.timeout(Math.max(1, deadline - Date.now())), + ]), + }); + healthy = res.ok && Date.now() <= deadline; + } catch { + // Server still booting, or the request stopped. + } + if (!healthy) { + await delay(SERVER_HEALTH_INTERVAL_MS); + } + } + // A signal can start the teardown while the health request is in flight. + const address = url ?? 'an unpublished URL'; + refuseDuringTeardown(`use of the server at ${address}`); + if (!healthy) { + throw new Error( + `Server at ${address} did not become healthy\nServer logs:\n${logs}` + ); + } + }; + + /** + * Starts headless Chromium on the harness profile. + * + * @param {{args?: string[], timeoutMs?: number}} [options] + * @returns {Promise} The DevTools HTTP port. + */ + const launchChromium = async ({ + args = [], + timeoutMs = DEVTOOLS_TIMEOUT_MS, + } = {}) => { + for (const arg of args) { + if ( + !arg.startsWith('--') || + /^--(?:remote-debugging[^=]*|user-data-dir)(?:=|$)/.test(arg) + ) { + throw new Error(`Invalid extra Chromium argument: ${arg}`); + } + } + if (groups.some(group => group.label === 'Chromium' && !group.gone)) { + throw new Error('The Chromium profile is already in use'); + } + const startedAt = Date.now(); + const chrome = spawnOwned( + 'Chromium', + findChromiumBinary(), + [ + ...CHROMIUM_ARGS, + ...args, + `--user-data-dir=${profileDir}`, + 'about:blank', + ], + { + stdio: ['ignore', 'ignore', 'pipe'], + env: { + ...process.env, + TMPDIR: workTmp, + // Chromium on macOS reads this name and not `TMPDIR`. + MAC_CHROMIUM_TMPDIR: workTmp, + DBUS_SESSION_BUS_ADDRESS: 'disabled:', + DBUS_SYSTEM_BUS_ADDRESS: 'disabled:', + }, + } + ); + const stderr = /** @type {import('node:stream').Readable} */ ( + chrome.stderr + ); + /** @type {string} */ + const browserWsUrl = await new Promise((resolveWs, rejectWs) => { + let stderrBuf = ''; + let waiting = true; + /** @param {string} reason */ + const fail = reason => { + if (!waiting) return; + waiting = false; + clearTimeout(timer); + // Drain buffered stderr. A descendant can keep the pipe open after exit. + setImmediate(() => { + const status = chrome.signalCode ?? chrome.exitCode ?? 'running'; + const elapsedMs = Date.now() - startedAt; + const stderrTail = stderrBuf.slice(-2000).replace(/\n+$/, ''); + void close().then(() => { + const detail = stderrTail ? `${stderrTail} ` : ''; + rejectWs( + new Error( + `Chromium ${reason} (${status}): ${detail}[${elapsedMs}ms]` + ) + ); + }, rejectWs); + }); + }; + const timer = setTimeout(() => fail('DevTools timeout'), timeoutMs); + /** @param {unknown} chunk */ + const onData = chunk => { + stderrBuf += String(chunk); + const m = stderrBuf.match(/DevTools listening on (ws:\/\/\S+)\s/); + if (m && waiting) { + waiting = false; + clearTimeout(timer); + stderr.off('data', onData); + stderr.resume(); + resolveWs(m[1]); + } + }; + stderr.on('data', onData); + chrome.once('exit', () => fail('exited early')); + chrome.once('close', () => fail('exited early')); + }); + refuseDuringTeardown('use of Chromium'); + return new URL(browserWsUrl).port; + }; + + return { workTmp, profileDir, startServer, launchChromium, close }; +} diff --git a/packages/frontend/hosts/web/scripts/legacy-workspace-readiness.mjs b/packages/frontend/hosts/web/scripts/legacy-workspace-readiness.mjs new file mode 100644 index 0000000000..91261d0c44 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/legacy-workspace-readiness.mjs @@ -0,0 +1,882 @@ +// @ts-check + +/** + * Legacy shell workspace readiness and IndexedDB persistence verifier. + * + * DOM selectors in this module are bound to the frozen legacy shell version + * `@affine/mobile 0.27.5`: + * - Editor container: `[data-affine-editor-container][data-testid="editor-"]` + * - Mounted BlockSuite host inside container: `editor-host` + * - IndexedDB workspace database: `local:workspace:` (`snapshots`, `updates`) + */ + +import assert from 'node:assert/strict'; + +/** @type {Promise | null} */ +let defaultYjsPromise = null; + +/** + * Loads `yjs` on demand so static module imports (for example from Node unit + * tests running without `node_modules`) never fail at load time. + * + * @param {string} [yjsModuleUrl] + * @returns {Promise} + */ +async function loadYjs(yjsModuleUrl) { + if (yjsModuleUrl) { + return import(yjsModuleUrl); + } + defaultYjsPromise ??= import('yjs'); + return defaultYjsPromise; +} + +const RESERVED_DOC_SEGMENTS = new Set([ + 'home', + 'all', + 'trash', + 'shared', + 'journals', + 'collections', + 'tags', + 'settings', + 'search', + 'collection', + 'tag', + '404', + 'workspace', + 'sign-in', + 'magic-link', + 'oauth', +]); + +/** + * Validates that a workspace or document ID segment is non-empty and not a + * reserved route word or path traversal token. + * + * @param {unknown} value + * @returns {value is string} + */ +export function isValidLegacyDocId(value) { + if (typeof value !== 'string') return false; + const trimmed = value.trim(); + if (!trimmed || trimmed !== value) return false; + if (trimmed === '.' || trimmed === '..' || trimmed.includes('/')) + return false; + return !RESERVED_DOC_SEGMENTS.has(trimmed.toLowerCase()); +} + +/** + * Parses a legacy shell pathname into a workspace route descriptor. + * + * @param {string} pathname + * @returns {{ kind: 'doc', wsId: string, docId: string } | { kind: 'home', wsId: string } | { kind: 'other', pathname: string }} + */ +export function parseLegacyWorkspaceRoute(pathname) { + const match = /^\/workspace\/([^/]+)\/([^/]+)\/?$/.exec(pathname); + if (!match) { + return { kind: 'other', pathname }; + } + let wsId; + let segment; + try { + wsId = decodeURIComponent(match[1]); + segment = decodeURIComponent(match[2]); + } catch { + return { kind: 'other', pathname }; + } + if (!wsId || wsId === '.' || wsId === '..' || wsId.includes('/')) { + return { kind: 'other', pathname }; + } + if (segment === 'home') { + return { kind: 'home', wsId }; + } + if (!isValidLegacyDocId(segment)) { + return { kind: 'other', pathname }; + } + return { kind: 'doc', wsId, docId: segment }; +} + +/** + * Runs inside the browser page to read `snapshots` and `updates` for the given + * `docIds` from an already-existing `local:workspace:` database. + * + * Rows must match the `@affine/nbstore` IndexedDB schema: `snapshots` rows + * carry a non-empty `Uint8Array` `bin`, `updates` rows carry a non-empty + * `Uint8Array` `bin` and a `Date` `createdAt`, and `updates` has a `docId` + * index. Any other shape is reported as an error. + * + * Single no-create mechanism: `onupgradeneeded` aborts its transaction + * immediately so a missing database is never created. No `indexedDB.databases()` + * pre-check is performed. + * + * @param {string} wsId + * @param {string[]} docIds + */ +function readExistingWorkspaceRecordsInPage(wsId, docIds) { + const dbName = 'local:workspace:' + wsId; + + const isBin = value => value instanceof Uint8Array && value.length > 0; + + const toBase64 = bytes => { + let binary = ''; + const chunkSize = 0x8000; + for (let i = 0; i < bytes.length; i += chunkSize) { + binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize)); + } + return btoa(binary); + }; + + const requestToPromise = req => + new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => + reject(req.error || new Error('IndexedDB request failed')); + }); + + return new Promise((resolve, reject) => { + let abortedMissing = false; + const openReq = indexedDB.open(dbName); + openReq.onupgradeneeded = event => { + abortedMissing = true; + event.target.transaction.abort(); + }; + openReq.onblocked = () => { + reject(new Error(`IndexedDB open blocked: ${dbName}`)); + }; + openReq.onerror = () => { + if (abortedMissing) { + resolve({ + exists: false, + dbName, + error: `IndexedDB database does not exist: ${dbName}`, + }); + return; + } + reject(openReq.error || new Error(`Failed to open IndexedDB: ${dbName}`)); + }; + openReq.onsuccess = async () => { + const db = openReq.result; + const fail = error => resolve({ exists: true, dbName, error }); + try { + const names = db.objectStoreNames; + if (!names.contains('snapshots') || !names.contains('updates')) { + fail( + `IndexedDB database ${dbName} is missing snapshots or updates object store` + ); + return; + } + const tx = db.transaction(['snapshots', 'updates'], 'readonly'); + const snapshotsStore = tx.objectStore('snapshots'); + const updatesStore = tx.objectStore('updates'); + if (!updatesStore.indexNames.contains('docId')) { + fail( + `IndexedDB database ${dbName} is missing the updates.docId index` + ); + return; + } + const updatesIndex = updatesStore.index('docId'); + + const perDoc = await Promise.all( + docIds.map(async id => { + const [snapshotRow, updateRows] = await Promise.all([ + requestToPromise(snapshotsStore.get(id)), + requestToPromise(updatesIndex.getAll(id)), + ]); + return { id, snapshotRow, updateRows }; + }) + ); + + /** @type {Record} */ + const docs = {}; + for (const { id, snapshotRow, updateRows } of perDoc) { + const entry = { snapshots: [], updates: [] }; + if (snapshotRow) { + if (!isBin(snapshotRow.bin)) { + fail( + `${dbName} snapshots row "${id}" has no non-empty Uint8Array bin` + ); + return; + } + entry.snapshots.push(toBase64(snapshotRow.bin)); + } + for (const row of updateRows) { + if (!isBin(row.bin) || !(row.createdAt instanceof Date)) { + fail( + `${dbName} updates row of "${id}" needs a non-empty Uint8Array bin and a Date createdAt` + ); + return; + } + entry.updates.push(toBase64(row.bin)); + } + docs[id] = entry; + } + + resolve({ + exists: true, + dbName, + docs, + }); + } catch (err) { + reject(err); + } finally { + db.close(); + } + }; + }); +} + +/** + * Merges `snapshots` followed by `updates` in `createdAt` order into a fresh + * `Y.Doc`. + * + * @param {any} Y + * @param {{ snapshots: string[], updates: string[] } | undefined} record + * @returns {{ doc: any, payloadCount: number }} + */ +function mergeYjsRecord(Y, record) { + const doc = new Y.Doc(); + let payloadCount = 0; + if (!record) return { doc, payloadCount }; + for (const snap of record.snapshots) { + Y.applyUpdate(doc, Buffer.from(snap, 'base64')); + payloadCount += 1; + } + for (const upd of record.updates) { + Y.applyUpdate(doc, Buffer.from(upd, 'base64')); + payloadCount += 1; + } + return { doc, payloadCount }; +} + +/** + * Extracts valid document IDs from a root workspace Y.Doc's `meta.pages`. + * + * @param {any} rootDoc + * @returns {string[]} + */ +export function extractCatalogDocIds(rootDoc) { + const meta = rootDoc.getMap('meta').toJSON(); + const pages = Array.isArray(meta?.pages) ? meta.pages : []; + /** @type {string[]} */ + const ids = []; + for (const page of pages) { + if (page && isValidLegacyDocId(page.id)) { + ids.push(page.id); + } + } + return ids; +} + +/** + * Verifies semantic Yjs persistence for `` (root catalog) and `` + * (page document containing `sys:flavour === "affine:page"`). + * + * @param {any} tab + * @param {string} wsId + * @param {string} docId + * @param {{ yjsModuleUrl?: string }} [options] + * @returns {Promise<{ ok: true, catalogDocIds: string[] } | { ok: false, reason: string }>} + */ +export async function inspectLegacyWorkspacePersistence( + tab, + wsId, + docId, + options = {} +) { + const Y = await loadYjs(options.yjsModuleUrl); + const raw = await tab.evalJs( + `(${readExistingWorkspaceRecordsInPage})(${JSON.stringify(wsId)}, ${JSON.stringify([wsId, docId])})` + ); + if (!raw || raw.error) { + return { + ok: false, + reason: raw?.error || `Failed to read local:workspace:${wsId}`, + }; + } + + const rootMerged = mergeYjsRecord(Y, raw.docs?.[wsId]); + if (rootMerged.payloadCount === 0) { + return { + ok: false, + reason: `IndexedDB local:workspace:${wsId} has no Yjs records for root document "${wsId}"`, + }; + } + const catalogDocIds = extractCatalogDocIds(rootMerged.doc); + if (!catalogDocIds.includes(docId)) { + return { + ok: false, + reason: `Root document "${wsId}" meta.pages does not contain "${docId}" (found: [${catalogDocIds.join(', ')}])`, + }; + } + + const pageMerged = mergeYjsRecord(Y, raw.docs?.[docId]); + if (pageMerged.payloadCount === 0) { + return { + ok: false, + reason: `IndexedDB local:workspace:${wsId} has no Yjs records for page document "${docId}"`, + }; + } + const blocks = pageMerged.doc.getMap('blocks').toJSON(); + const hasAffinePage = + blocks && + typeof blocks === 'object' && + Object.values(blocks).some( + block => + block && + typeof block === 'object' && + block['sys:flavour'] === 'affine:page' + ); + if (!hasAffinePage) { + return { + ok: false, + reason: `Page document "${docId}" in local:workspace:${wsId} has no block with sys:flavour === "affine:page"`, + }; + } + + return { ok: true, catalogDocIds }; +} + +/** + * Counts `local:workspace:*` IndexedDB databases in the current origin. + * Used only for the same-origin reopen count invariant (never as an open pre-check). + * + * @param {any} tab + * @returns {Promise} + */ +export async function listLegacyWorkspaceDatabases(tab) { + const names = await tab.evalJs(`(async () => { + const dbs = await indexedDB.databases(); + return dbs + .map(entry => entry && entry.name) + .filter(name => typeof name === 'string' && name.startsWith('local:workspace:')) + .sort(); + })()`); + return Array.isArray(names) ? names : []; +} + +/** + * Runs inside the page and synchronously reports whether the live page shows + * the expected legacy shell state: + * - A valid `/workspace//` route renders visible + * `[data-affine-editor-container][data-testid="editor-"]` containing + * `editor-host`, carries the `affine_shell=legacy` cookie when required, + * and exposes no synthetic `__AFFINE_LEGACY_SHELL__`, or + * - (When `allowHome` is true) the route is `/workspace//home`. + * Both states require `document.readyState === 'complete'`. + * + * @param {typeof parseLegacyWorkspaceRoute} parseRoute + * @param {{ allowHome: boolean, wsId: string | null, docId: string | null, requireLegacyCookie: boolean }} expected + */ +function inspectLegacyPageInPage(parseRoute, expected) { + function isVisible(el) { + if (!el) return false; + const rects = Array.from(el.getClientRects()); + if (!rects.some(r => r.width > 0 && r.height > 0)) return false; + if (typeof el.checkVisibility === 'function') { + return el.checkVisibility({ + visibilityProperty: true, + opacityProperty: true, + }); + } + return true; + } + + const pathname = window.location.pathname; + const route = parseRoute(pathname); + if (document.readyState !== 'complete') { + return { + ready: false, + diagnostic: `document.readyState=${document.readyState} on "${pathname}"`, + }; + } + if (route.kind === 'home') { + if ( + expected.allowHome && + (!expected.wsId || route.wsId === expected.wsId) + ) { + return { ready: true, kind: 'home', wsId: route.wsId, pathname }; + } + return { + ready: false, + diagnostic: `Legacy shell is on "${pathname}" instead of a document route`, + }; + } + if (route.kind !== 'doc') { + return { + ready: false, + diagnostic: `Legacy shell route "${pathname}" is not a valid /workspace// path`, + }; + } + if (expected.wsId && route.wsId !== expected.wsId) { + return { + ready: false, + diagnostic: `Legacy shell workspace "${route.wsId}" does not match expected "${expected.wsId}"`, + }; + } + if (expected.docId && route.docId !== expected.docId) { + return { + ready: false, + diagnostic: `Legacy shell doc "${route.docId}" does not match expected "${expected.docId}"`, + }; + } + const selector = + '[data-affine-editor-container][data-testid="editor-' + + CSS.escape(route.docId) + + '"]'; + const container = document.querySelector(selector); + if (!container || !isVisible(container)) { + return { + ready: false, + diagnostic: `Missing visible ${selector} on "${pathname}"`, + }; + } + if (!container.querySelector('editor-host')) { + return { + ready: false, + diagnostic: `Missing editor-host inside ${selector} on "${pathname}"`, + }; + } + if ( + expected.requireLegacyCookie && + !document.cookie.split('; ').includes('affine_shell=legacy') + ) { + return { + ready: false, + diagnostic: `Missing affine_shell=legacy cookie on "${pathname}"`, + }; + } + if (/** @type {any} */ (window).__AFFINE_LEGACY_SHELL__) { + return { + ready: false, + diagnostic: `Synthetic __AFFINE_LEGACY_SHELL__ is exposed on "${pathname}"`, + }; + } + return { + ready: true, + kind: 'doc', + wsId: route.wsId, + docId: route.docId, + pathname, + }; +} + +/** + * Page expression for `inspectLegacyPageInPage` bound to the same route parser + * and reserved route words that Node uses. + */ +const PAGE_INSPECT = `(${inspectLegacyPageInPage}).bind(null, (() => { + const RESERVED_DOC_SEGMENTS = new Set(${JSON.stringify([...RESERVED_DOC_SEGMENTS])}); + ${isValidLegacyDocId} + return ${parseLegacyWorkspaceRoute}; +})())`; + +/** + * Runs inside the page and re-evaluates `inspect(expected)` on DOM mutations, + * history changes and animation frames until it reports a ready state. + * + * @param {(expected: Parameters[1]) => any} inspect + * @param {Parameters[1]} expected + * @param {number} remainingMs + */ +function waitForLegacyPageInPage(inspect, expected, remainingMs) { + return new Promise((resolve, reject) => { + let done = false; + let rafId = 0; + let lastDiagnostic = `Timed out on "${window.location.pathname}"`; + + const cleanup = () => { + done = true; + clearTimeout(timer); + if (rafId) cancelAnimationFrame(rafId); + observer.disconnect(); + window.removeEventListener('popstate', scheduleCheck); + window.removeEventListener('load', scheduleCheck); + }; + + const check = () => { + if (done) return; + rafId = 0; + const status = inspect(expected); + if (status.ready) { + cleanup(); + resolve(status); + return; + } + lastDiagnostic = status.diagnostic; + rafId = requestAnimationFrame(check); + }; + + const scheduleCheck = () => { + if (done || rafId) return; + rafId = requestAnimationFrame(check); + }; + + const observer = new MutationObserver(scheduleCheck); + observer.observe(document.documentElement || document, { + childList: true, + subtree: true, + attributes: true, + }); + window.addEventListener('popstate', scheduleCheck); + window.addEventListener('load', scheduleCheck); + + const timer = setTimeout( + () => { + cleanup(); + reject( + new Error(`Legacy shell did not mount editor: ${lastDiagnostic}`) + ); + }, + Math.max(1, remainingMs) + ); + + check(); + }); +} + +/** + * Reads the live legacy page state once, without waiting. + * + * @param {any} tab + * @param {Parameters[1]} expected + * @returns {Promise<{ ready: true, kind: 'doc' | 'home', wsId: string, docId?: string, pathname: string } | { ready: false, diagnostic: string }>} + */ +function inspectLegacyPage(tab, expected) { + return tab.evalJs(`${PAGE_INSPECT}(${JSON.stringify(expected)})`); +} + +/** + * Waits one animation frame in the page (event-driven, no fixed sleep). + * + * @param {any} tab + */ +async function nextAnimationFrame(tab) { + await tab.evalJs( + 'new Promise(resolve => requestAnimationFrame(() => resolve(true)))' + ); +} + +/** + * Attaches strict CDP error and critical-network monitors before navigation and + * verifies that the legacy `@affine/mobile 0.27.5` shell reaches a real + * `/workspace//` document with a mounted `editor-host` and + * semantically valid IndexedDB Yjs state. + * + * @param {any} tab + * @param {string} baseUrl + * @param {{ + * timeoutMs?: number, + * navigationTimeoutMs?: number, + * mode?: 'fresh' | 'reopen', + * expectedWsId?: string, + * expectedDocId?: string, + * expectedWorkspaceDbCount?: number, + * requireLegacyCookie?: boolean, + * entryPath?: string, + * yjsModuleUrl?: string, + * }} [options] + */ +export async function verifyLegacyWorkspaceReadiness( + tab, + baseUrl, + options = {} +) { + const timeoutMs = + options.timeoutMs ?? + Number(process.env.AFFINE_LEGACY_CONTROL_TIMEOUT_MS ?? 15000); + assert.ok( + Number.isSafeInteger(timeoutMs) && timeoutMs > 0, + 'Legacy readiness timeout must be a positive integer' + ); + const navigationTimeoutMs = options.navigationTimeoutMs ?? 15000; + assert.ok( + Number.isSafeInteger(navigationTimeoutMs) && + navigationTimeoutMs > 0 && + navigationTimeoutMs <= 2 ** 31 - 1, + 'Legacy initial navigation timeout must be a positive timer interval' + ); + const mode = options.mode ?? 'fresh'; + const expectedWsId = options.expectedWsId ?? null; + const expectedDocId = options.expectedDocId ?? null; + const requireLegacyCookie = options.requireLegacyCookie ?? true; + + if (mode === 'reopen') { + assert.ok( + expectedWsId && isValidLegacyDocId(expectedDocId), + 'Reopen mode requires valid expectedWsId and expectedDocId' + ); + } + + const failure = Promise.withResolvers(); + const critical = new Map(); + const workers = new Set(); + let idle = Promise.withResolvers(); + + const pendingUrls = () => + critical.size ? `: ${Array.from(critical.values()).join(', ')}` : ''; + + function finishRequest(id) { + if (critical.delete(id) && !critical.size) { + idle.resolve(); + idle = Promise.withResolvers(); + } + } + + const onMessage = event => { + const { method, params } = JSON.parse(event.data); + if (method === 'Runtime.exceptionThrown') { + const details = params.exceptionDetails; + failure.reject(new Error(details.exception?.description || details.text)); + } else if (method === 'Network.requestWillBeSent') { + const url = params.request.url; + if ( + ['Document', 'Script', 'Stylesheet'].includes(params.type) || + /\.(?:wasm|m?js|css|html?)(?:[?#]|$)/i.test(url) + ) { + critical.set(params.requestId, url); + if (!params.loaderId) workers.add(params.requestId); + } + } else if (method === 'Network.responseReceived') { + const res = params.response; + if (res.mimeType === 'application/wasm') { + critical.set(params.requestId, res.url); + } + if (critical.has(params.requestId) && res.status >= 400) { + failure.reject( + new Error(`Legacy shell HTTP ${res.status}: ${res.url}`) + ); + } + } else if ( + method === 'Network.loadingFailed' && + critical.has(params.requestId) + ) { + failure.reject( + new Error(`${params.errorText}: ${critical.get(params.requestId)}`) + ); + } else if ( + method === 'Network.responseReceivedExtraInfo' && + workers.delete(params.requestId) + ) { + if (params.statusCode >= 400) { + failure.reject( + new Error( + `Legacy worker HTTP ${params.statusCode}: ${critical.get(params.requestId)}` + ) + ); + } + finishRequest(params.requestId); + } else if (method === 'Network.loadingFinished') { + finishRequest(params.requestId); + } else if (method === 'Log.entryAdded') { + const entry = params.entry; + if ( + entry.level === 'error' && + (entry.source !== 'network' || critical.has(entry.networkRequestId)) + ) { + failure.reject(new Error(`${entry.text} ${entry.url || ''}`)); + } + } + }; + + tab.ws.addEventListener('message', onMessage); + + const navigateAndWaitIdle = async targetUrl => { + const nav = await tab.send('Page.navigate', { url: targetUrl }); + if (nav.errorText) { + throw new Error(nav.errorText); + } + if (critical.size) { + await idle.promise; + } + }; + + const entryUrl = + mode === 'reopen' + ? `${baseUrl}/workspace/${encodeURIComponent(/** @type {string} */ (expectedWsId))}/${encodeURIComponent(/** @type {string} */ (expectedDocId))}` + : `${baseUrl}${options.entryPath ?? '/?shell=legacy'}`; + let deadlineTimer = setTimeout(() => { + failure.reject( + new Error( + `Legacy shell initial navigation timed out after ${navigationTimeoutMs}ms${pendingUrls()}` + ) + ); + }, navigationTimeoutMs); + + try { + await Promise.race([failure.promise, navigateAndWaitIdle(entryUrl)]); + const deadlineAt = Date.now() + timeoutMs; + const remainingMs = () => deadlineAt - Date.now(); + clearTimeout(deadlineTimer); + + // Bound operations that cannot check the readiness deadline themselves. + const backstopMs = timeoutMs + 2000; + deadlineTimer = setTimeout(() => { + failure.reject( + new Error( + `Legacy shell startup timed out after ${backstopMs}ms${pendingUrls()}` + ) + ); + }, backstopMs); + + return await Promise.race([ + failure.promise, + (async () => { + let navigatedFromHome = false; + let lockedWsId = expectedWsId; + let lockedDocId = expectedDocId; + /** @type {{ wsId: string, docId: string, pathname: string }} */ + let mounted; + + while (true) { + const left = remainingMs(); + if (left <= 0) { + throw new Error( + `Legacy shell readiness timed out after ${timeoutMs}ms` + ); + } + + const expected = { + allowHome: mode === 'fresh' && !navigatedFromHome, + wsId: lockedWsId, + docId: lockedDocId, + requireLegacyCookie, + }; + let state; + do { + if (critical.size) await idle.promise; + state = await tab.evalJs( + `(${waitForLegacyPageInPage})(${PAGE_INSPECT}, ${JSON.stringify(expected)}, ${Math.max(1, remainingMs())})` + ); + } while (critical.size); + + if (state.kind === 'doc') { + mounted = { + wsId: state.wsId, + docId: state.docId, + pathname: state.pathname, + }; + break; + } + + // Fresh launch landed on `/workspace//home`: lock the workspace, + // read root `meta.pages` from existing IndexedDB without creating a + // DB, then lock the selected document and navigate once. + lockedWsId = state.wsId; + const Y = await loadYjs(options.yjsModuleUrl); + let resolvedDocId = null; + let lastHomeError = `Workspace "${state.wsId}" root document has no catalog docId`; + while (remainingMs() > 0) { + const rawRoot = await tab.evalJs( + `(${readExistingWorkspaceRecordsInPage})(${JSON.stringify(state.wsId)}, ${JSON.stringify([state.wsId])})` + ); + if (rawRoot && !rawRoot.error) { + const merged = mergeYjsRecord(Y, rawRoot.docs?.[state.wsId]); + if (merged.payloadCount > 0) { + const catalog = extractCatalogDocIds(merged.doc); + if (catalog.length > 0) { + resolvedDocId = catalog[0]; + break; + } + lastHomeError = `Root document "${state.wsId}" meta.pages contains no valid docId`; + } else { + lastHomeError = `IndexedDB local:workspace:${state.wsId} has no root document records`; + } + } else if (rawRoot?.error) { + lastHomeError = rawRoot.error; + } + + // Check if the shell already navigated away from /home on its own. + const currentPath = await tab.evalJs('window.location.pathname'); + if (parseLegacyWorkspaceRoute(currentPath).kind === 'doc') { + break; + } + await nextAnimationFrame(tab); + } + + if (resolvedDocId) { + navigatedFromHome = true; + lockedDocId = resolvedDocId; + const deepLink = `${baseUrl}/workspace/${encodeURIComponent(state.wsId)}/${encodeURIComponent(resolvedDocId)}`; + await navigateAndWaitIdle(deepLink); + continue; + } + + const currentPath = await tab.evalJs('window.location.pathname'); + if (parseLegacyWorkspaceRoute(currentPath).kind === 'doc') { + continue; + } + throw new Error( + `Legacy shell stopped on ${state.pathname} without a readable document catalog: ${lastHomeError}` + ); + } + + // Every persistence result counts only while the live page still shows + // the mounted document, so a shell that falls back to another route or + // unmounts the editor before IndexedDB settles never passes. + const mountedExpectation = { + allowHome: false, + wsId: mounted.wsId, + docId: mounted.docId, + requireLegacyCookie, + }; + const lostMount = diagnostic => + `Legacy shell lost the mounted document ${mounted.pathname}: ${diagnostic}`; + let verifiedCatalog = null; + while (true) { + const idbCheck = await inspectLegacyWorkspacePersistence( + tab, + mounted.wsId, + mounted.docId, + { yjsModuleUrl: options.yjsModuleUrl } + ); + const live = await inspectLegacyPage(tab, mountedExpectation); + let notReady; + if (!live.ready) { + notReady = lostMount(live.diagnostic); + } else if (!idbCheck.ok) { + notReady = `Legacy shell IndexedDB persistence check failed: ${idbCheck.reason}`; + } else { + verifiedCatalog = idbCheck.catalogDocIds; + break; + } + if (remainingMs() <= 0) { + throw new Error(notReady); + } + await nextAnimationFrame(tab); + } + + let workspaceDbNames = null; + if ( + mode === 'reopen' || + options.expectedWorkspaceDbCount !== undefined + ) { + workspaceDbNames = await listLegacyWorkspaceDatabases(tab); + if (options.expectedWorkspaceDbCount !== undefined) { + assert.equal( + workspaceDbNames.length, + options.expectedWorkspaceDbCount, + `Expected ${options.expectedWorkspaceDbCount} local:workspace:* databases after reopen, found ${workspaceDbNames.length}: [${workspaceDbNames.join(', ')}]` + ); + } + } + + const final = await inspectLegacyPage(tab, mountedExpectation); + if (!final.ready) { + throw new Error(lostMount(final.diagnostic)); + } + + return { + wsId: mounted.wsId, + docId: mounted.docId, + pathname: mounted.pathname, + navigatedFromHome, + catalogDocIds: verifiedCatalog, + workspaceDbNames, + }; + })(), + ]); + } finally { + clearTimeout(deadlineTimer); + tab.ws.removeEventListener('message', onMessage); + } +} diff --git a/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs b/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs new file mode 100644 index 0000000000..a55f986683 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs @@ -0,0 +1,1597 @@ +#!/usr/bin/env node +// @ts-check + +/** + * Assembles a hosted `canary` dual-shell static release bundle for `affine-server` + * (`--role front --deployment-mode cloud --channel canary --static-dir `). + * + * Output layout under `/`: + * - `index.html`, `assets/desktop.js` (desktop fallback shell unless `--desktop-dir` is given) + * - `mobile/index.html`, `mobile/sign-in.html` (cookie-immune `/mobile/...` asset URLs) + * - `mobile/src/**` (zero-build ES module thin host) + * - `mobile/wasm/{mermaid,math,typst,pdf}-worker..wasm` + * - `mobile/pkg/{playground.js,playground_bg.wasm}` + * - `mobile/assets/fonts/{inter-latin,ibm-plex-mono}..ttf` + * - `mobile/release-manifest.json` (immutable content-hash manifest) + * - `mobile-legacy/{index.html,app.js,idb-storage.js,yjs.mjs,assets-manifest.json}` (fallback shell using real `yjs` and shared v3 IDB schema) + */ + +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + copyFileSync, + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const FRONTEND_ROOT = resolve(WEB_ROOT, '../..'); +const REPO_ROOT = resolve(FRONTEND_ROOT, '../..'); +const WORKER_KINDS = ['mermaid', 'math', 'typst', 'pdf']; +const MIN_REAL_WASM_BYTES = 10 * 1024; +const PREVIEW_WORKER_REQUIRED_EXPORTS = [ + 'memory', + 'prepare', + 'invoke', + 'output_ptr', +]; +const PLAYGROUND_REQUIRED_EXPORTS = ['merge_updates_v1', 'extract_subdoc_ids']; + +const FONT_SPECS = [ + { + key: 'latin', + prefix: 'inter-latin', + src: join( + FRONTEND_ROOT, + 'component/src/fonts/inter/Inter-VariableFont_slnt,wght.ttf' + ), + }, + { + key: 'mono', + prefix: 'ibm-plex-mono', + src: join( + FRONTEND_ROOT, + 'component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf' + ), + }, +]; + +/** + * Validates that a staged `.wasm` binary is a real compiled module (not a tiny + * test stub) and exports every required function symbol. + * + * @param {string} label + * @param {Buffer} bytes + * @param {string[]} requiredExports + */ +export function validateRealWasmBinary(label, bytes, requiredExports) { + if (!bytes || bytes.byteLength < MIN_REAL_WASM_BYTES) { + throw new Error( + `Invalid ${label}: expected real compiled Wasm (>= ${MIN_REAL_WASM_BYTES} bytes), got ${bytes ? bytes.byteLength : 0} bytes.` + ); + } + let mod; + try { + mod = new WebAssembly.Module(bytes); + } catch (err) { + throw new Error( + `Invalid ${label}: failed to compile Wasm module (${err instanceof Error ? err.message : String(err)}).` + ); + } + const moduleExports = WebAssembly.Module.exports(mod); + const hasExport = name => + moduleExports.some( + exp => + exp.name === name || + (exp.kind === 'function' && exp.name.startsWith(`${name}_`)) + ); + const missing = requiredExports.filter(name => !hasExport(name)); + if (missing.length > 0) { + throw new Error( + `Invalid ${label}: missing required Wasm exports: ${missing.join(', ')}.` + ); + } +} + +/** + * Recursively collects sorted file paths inside `dir`. + * + * @param {string} dir + * @returns {string[]} + */ +function listFilesSorted(dir) { + /** @type {string[]} */ + const out = []; + if (!existsSync(dir)) { + return out; + } + /** @param {string} current */ + function visit(current) { + const entries = readdirSync(current, { withFileTypes: true }).sort( + (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) + ); + for (const entry of entries) { + const full = join(current, entry.name); + if (entry.isDirectory()) { + visit(full); + } else if (entry.isFile()) { + out.push(full); + } + } + } + visit(dir); + return out; +} + +/** + * @param {Buffer} buf + * @returns {string} + */ +function sha256Hex(buf) { + return createHash('sha256').update(buf).digest('hex'); +} + +/** + * Resolves a built preview worker wasm binary from `wasmDir` or staged `assets/`. + * + * @param {string | null} wasmDir + * @param {string} kind + * @returns {string | null} + */ +function findWorkerWasm(wasmDir, kind) { + const candidates = []; + if (wasmDir) { + candidates.push(join(wasmDir, `${kind}.wasm`)); + candidates.push(join(wasmDir, `${kind}-worker.wasm`)); + if (existsSync(wasmDir)) { + for (const entry of readdirSync(wasmDir)) { + if (entry.startsWith(`${kind}-worker.`) && entry.endsWith('.wasm')) { + candidates.push(join(wasmDir, entry)); + } + } + } + } + const stagedAssets = join(WEB_ROOT, 'assets'); + if (existsSync(stagedAssets)) { + candidates.push(join(stagedAssets, `${kind}-worker.dev-local.wasm`)); + for (const entry of readdirSync(stagedAssets)) { + if (entry.startsWith(`${kind}-worker.`) && entry.endsWith('.wasm')) { + candidates.push(join(stagedAssets, entry)); + } + } + } + for (const candidate of candidates) { + if (existsSync(candidate)) { + return candidate; + } + } + return null; +} + +/** + * Resolves the main `playground` wasm-bindgen directory. + * + * @param {string | null} wasmDir + * @returns {string | null} + */ +function findMainPkgDir(wasmDir) { + const candidates = [ + wasmDir ? join(wasmDir, 'pkg') : null, + join(WEB_ROOT, 'assets/pkg'), + ].filter(Boolean); + for (const dir of candidates) { + if ( + dir && + existsSync(join(dir, 'playground.js')) && + existsSync(join(dir, 'playground_bg.wasm')) + ) { + return dir; + } + } + return null; +} + +/** + * Computes a deterministic content-derived `shell_build_id` (12 hex chars). + * + * @param {Array<{ name: string, bytes: Buffer }>} inputs + * @returns {string} + */ +function computeShellBuildId(inputs) { + const hash = createHash('sha256'); + const sorted = [...inputs].sort((a, b) => + a.name < b.name ? -1 : a.name > b.name ? 1 : 0 + ); + for (const item of sorted) { + hash.update(item.name); + hash.update('\0'); + hash.update(item.bytes); + hash.update('\0'); + } + return hash.digest('hex').slice(0, 12); +} + +/** + * Stages a real, self-contained browser ESM `yjs.mjs` bundle into `legacyDir`. + * + * @param {string} legacyDir + * @param {string | null} yjsBundlePath + */ +function stageLegacyYjsBundle(legacyDir, yjsBundlePath) { + const dest = join(legacyDir, 'yjs.mjs'); + if (yjsBundlePath) { + if (!existsSync(yjsBundlePath)) { + throw new Error(`Missing --yjs-bundle file: ${yjsBundlePath}`); + } + copyFileSync(yjsBundlePath, dest); + return; + } + + const yjsEntry = join(REPO_ROOT, 'node_modules/yjs/dist/yjs.mjs'); + const esbuildBin = join(REPO_ROOT, 'node_modules/.bin/esbuild'); + if (existsSync(yjsEntry) && existsSync(esbuildBin)) { + execFileSync( + esbuildBin, + [ + yjsEntry, + '--bundle', + '--format=esm', + '--platform=browser', + `--outfile=${dest}`, + ], + { stdio: 'pipe' } + ); + return; + } + + throw new Error( + 'Missing real yjs bundle for mobile-legacy. Pass --legacy-dir , --yjs-bundle , or install repo node_modules (yjs + esbuild).' + ); +} + +/** + * Builds the fallback `mobile-legacy/index.html` and `mobile-legacy/app.js` + * powered by real `yjs` (`Y.Doc` + `Y.applyUpdate` + `Y.encodeStateAsUpdate`) + * when no external `--legacy-dir` bundle is supplied. + * + * @param {string} legacyDir + * @param {string} shellBuildId + * @param {string | null} yjsBundlePath + */ +export function writeDefaultLegacyShell( + legacyDir, + shellBuildId, + yjsBundlePath +) { + mkdirSync(legacyDir, { recursive: true }); + stageLegacyYjsBundle(legacyDir, yjsBundlePath); + copyFileSync( + join(WEB_ROOT, 'src/idb-storage.js'), + join(legacyDir, 'idb-storage.js') + ); + + const legacyHtml = ` + + + + + + AFFiNE Mobile Legacy + + + +
+
+ Legacy Fallback Shell +

AFFiNE Mobile Legacy

+

Ready (shell=legacy)

+

+
Checking same-origin IndexedDB...
+
+ + + + + +

+
+ Return to Native Shell +
+
+ + + +`; + + const legacyAppJs = `(async () => { +const Y = await import('/mobile-legacy/yjs.mjs'); +const { + IDB_SCHEMA_VERSION, + LOCAL_WORKSPACE_CHANGED_CHANNEL, + addLocalWorkspaceId, + upgradeIdbSchema, +} = await import('/mobile-legacy/idb-storage.js'); + +function ensureLegacyShellDom() { + if (document.getElementById('legacy-shell-root')) return; + const style = document.createElement('style'); + style.textContent = + 'html,body{margin:0;padding:0;min-height:100%;background:#f8fafc;color:#0f172a;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}' + + '#legacy-shell-root{max-width:420px;margin:0 auto;padding:20px 16px 32px}' + + '.legacy-card{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:18px;box-shadow:0 4px 16px rgba(15,23,42,.06)}' + + '.legacy-badge{display:inline-block;padding:4px 10px;border-radius:999px;background:#fef3c7;color:#92400e;font-size:12px;font-weight:600}' + + 'h1{margin:12px 0 6px;font-size:20px;line-height:1.3}p{margin:6px 0;font-size:14px;line-height:1.5;color:#475569}' + + 'pre{margin:12px 0 0;padding:12px;border-radius:10px;background:#0f172a;color:#f8fafc;font-size:12px;line-height:1.45;overflow-x:auto;white-space:pre-wrap;word-break:break-word}' + + '.legacy-editor{margin-top:14px;display:flex;flex-direction:column;gap:8px}' + + '.legacy-editor label{font-size:13px;font-weight:600;color:#1e293b}' + + '.legacy-editor select,.legacy-editor textarea{width:100%;box-sizing:border-box;padding:8px 10px;border:1px solid #cbd5e1;border-radius:10px;font-family:inherit;font-size:13px;color:#0f172a;background:#f8fafc}' + + '.legacy-editor button{min-height:44px;padding:10px 14px;border:none;border-radius:10px;background:#1e6efb;color:#fff;font-size:14px;font-weight:600;cursor:pointer}' + + '.legacy-editor button:disabled{opacity:.6;cursor:not-allowed}' + + '#legacy-editor-status{margin:0;font-size:12px;color:#0f766e}' + + 'a.switch-link{display:inline-block;margin-top:14px;color:#1e6efb;font-size:13px;font-weight:600;text-decoration:none}'; + document.head.append(style); + const main = document.createElement('main'); + main.id = 'legacy-shell-root'; + main.dataset.shell = 'legacy'; + main.dataset.buildId = ${JSON.stringify(shellBuildId)}; + const card = document.createElement('section'); + card.className = 'legacy-card'; + const badge = document.createElement('span'); + badge.className = 'legacy-badge'; + badge.textContent = 'Legacy Fallback Shell'; + const h1 = document.createElement('h1'); + h1.textContent = 'AFFiNE Mobile Legacy'; + const statusP = document.createElement('p'); + statusP.id = 'legacy-status'; + statusP.textContent = 'Ready (shell=legacy)'; + const reasonP = document.createElement('p'); + reasonP.id = 'legacy-fallback-reason'; + const pre = document.createElement('pre'); + pre.id = 'legacy-recovered-doc'; + pre.textContent = 'Checking same-origin IndexedDB...'; + const editorDiv = document.createElement('div'); + editorDiv.className = 'legacy-editor'; + const selLabel = document.createElement('label'); + selLabel.htmlFor = 'legacy-target-doc'; + selLabel.textContent = 'Target document'; + const sel = document.createElement('select'); + sel.id = 'legacy-target-doc'; + const txtLabel = document.createElement('label'); + txtLabel.htmlFor = 'legacy-editor-input'; + txtLabel.textContent = 'Append paragraph'; + const textarea = document.createElement('textarea'); + textarea.id = 'legacy-editor-input'; + textarea.rows = 2; + textarea.placeholder = 'Write a paragraph to append...'; + const btn = document.createElement('button'); + btn.id = 'legacy-append-btn'; + btn.type = 'button'; + btn.textContent = 'Append Paragraph'; + const edStatus = document.createElement('p'); + edStatus.id = 'legacy-editor-status'; + edStatus.setAttribute('aria-live', 'polite'); + editorDiv.append(selLabel, sel, txtLabel, textarea, btn, edStatus); + const link = document.createElement('a'); + link.className = 'switch-link'; + link.href = '/?shell=native'; + link.textContent = 'Return to Native Shell'; + card.append(badge, h1, statusP, reasonP, pre, editorDiv, link); + main.append(card); + document.body.append(main); +} + +const state = { + shell: 'legacy', + buildId: ${JSON.stringify(shellBuildId)}, + ready: false, + fallbackReason: null, + routeTarget: null, + selectedTarget: null, + recoveredDocs: [], +}; + +function resolveRouteTarget() { + const params = new URLSearchParams(window.location.search); + const explicitDb = (params.get('idb') || '').trim() || null; + let pathWorkspaceId = null; + let pathDocId = null; + const pathMatch = window.location.pathname.match( + /^\\/workspace\\/([^/]+)(?:\\/([^/]+))?\\/?$/ + ); + if (pathMatch) { + try { + pathWorkspaceId = decodeURIComponent(pathMatch[1] || '').trim() || null; + pathDocId = pathMatch[2] + ? decodeURIComponent(pathMatch[2]).trim() || null + : null; + } catch { + pathWorkspaceId = (pathMatch[1] || '').trim() || null; + pathDocId = (pathMatch[2] || '').trim() || null; + } + } + const workspaceId = + (params.get('workspace') || '').trim() || pathWorkspaceId || null; + const docId = + (params.get('doc') || params.get('docId') || '').trim() || + pathDocId || + null; + const dbName = + explicitDb || (workspaceId ? 'local:workspace:' + workspaceId : null); + return { dbName, workspaceId, docId }; +} + +function encodeTargetKey(dbName, docId) { + return JSON.stringify({ dbName, docId }); +} + +function decodeTargetKey(raw) { + if (!raw) return null; + try { + const parsed = JSON.parse(raw); + if ( + parsed && + typeof parsed.dbName === 'string' && + parsed.dbName && + typeof parsed.docId === 'string' && + parsed.docId + ) { + return { dbName: parsed.dbName, docId: parsed.docId }; + } + } catch { + // Ignore invalid option keys. + } + return null; +} + +function readFallbackReason() { + try { + return ( + window.localStorage.getItem('affine:web-pref:shellFallbackReason') || + window.localStorage.getItem('shellFallbackReason') || + null + ); + } catch { + return null; + } +} + +function toBytes(raw) { + if (raw instanceof Uint8Array) return raw; + if (raw instanceof ArrayBuffer) return new Uint8Array(raw); + if (ArrayBuffer.isView(raw)) { + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + } + return new Uint8Array(0); +} + +function openDb(name, allowCreate = false) { + return new Promise((resolve, reject) => { + const req = allowCreate + ? indexedDB.open(name, IDB_SCHEMA_VERSION) + : indexedDB.open(name); + req.onupgradeneeded = event => { + if (!allowCreate) { + const tx = event.target?.transaction || req.transaction; + if (tx) { + tx.abort(); + } + return; + } + const oldVersion = + typeof event.oldVersion === 'number' ? event.oldVersion : 0; + upgradeIdbSchema(req.result, oldVersion); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error || new Error('IndexedDB open failed')); + req.onblocked = () => reject(new Error('IndexedDB open blocked')); + }); +} + +function readAllFromStore(db, storeName) { + return new Promise((resolve, reject) => { + if (!db.objectStoreNames.contains(storeName)) { + resolve([]); + return; + } + const tx = db.transaction(storeName, 'readonly'); + const req = tx.objectStore(storeName).getAll(); + req.onsuccess = () => resolve(req.result || []); + req.onerror = () => reject(req.error || new Error('IndexedDB read failed')); + }); +} + +function isPageVisibleNote(block) { + if (!(block instanceof Y.Map)) return false; + if (block.get('sys:flavour') !== 'affine:note') return false; + if (block.get('prop:hidden') === true) return false; + if (block.get('prop:displayMode') === 'edgeless') return false; + return true; +} + +function walkBlockSuiteTree(doc) { + const blocks = doc.getMap('blocks'); + const pageIds = []; + const noteIds = []; + const flavours = new Set(); + const paragraphs = []; + const paragraphNodes = []; + const childIds = []; + + blocks.forEach((block, id) => { + if (!(block instanceof Y.Map)) return; + const flavour = block.get('sys:flavour'); + if (typeof flavour === 'string') { + flavours.add(flavour); + if (flavour === 'affine:page') { + pageIds.push(id); + } + } + }); + pageIds.sort(); + + const visited = new Set(); + function walkChildren(parentId, depth) { + if (depth > 64 || visited.has(parentId)) return; + visited.add(parentId); + const parent = blocks.get(parentId); + const children = parent instanceof Y.Map ? parent.get('sys:children') : null; + if (!(children instanceof Y.Array)) return; + for (const cid of children.toArray()) { + if (typeof cid !== 'string' || visited.has(cid)) continue; + childIds.push(cid); + const block = blocks.get(cid); + if (block instanceof Y.Map) { + const text = block.get('prop:text'); + if (text instanceof Y.Text) { + const str = text.toString(); + paragraphs.push(str); + paragraphNodes.push({ id: cid, depth, text: str }); + } + walkChildren(cid, depth + 1); + } + } + } + + for (const pid of pageIds) { + const page = blocks.get(pid); + const pageChildren = page instanceof Y.Map ? page.get('sys:children') : null; + if (pageChildren instanceof Y.Array) { + for (const cid of pageChildren.toArray()) { + if (typeof cid !== 'string' || visited.has(cid)) continue; + const candidate = blocks.get(cid); + if (isPageVisibleNote(candidate)) { + noteIds.push(cid); + walkChildren(cid, 0); + } + } + } + } + + return { + pageId: pageIds[0] || null, + pageIds, + noteId: noteIds[0] || null, + noteIds, + childIds, + flavours: [...flavours], + paragraphs, + paragraphNodes, + }; +} + +async function inspectRecoveredIdb() { + const routeTarget = resolveRouteTarget(); + state.routeTarget = routeTarget; + const dbNames = []; + if (routeTarget.dbName) { + dbNames.push(routeTarget.dbName); + } else if (typeof indexedDB.databases === 'function') { + try { + const list = await indexedDB.databases(); + for (const item of list) { + if ( + item && + typeof item.name === 'string' && + (item.name.startsWith('local:workspace:') || + item.name.startsWith('affine_')) + ) { + dbNames.push(item.name); + } + } + } catch { + // Ignore browsers without indexedDB.databases(). + } + } + + const recovered = []; + for (const dbName of dbNames) { + let db = null; + try { + db = await openDb(dbName); + const updates = await readAllFromStore(db, 'updates'); + const snapshots = await readAllFromStore(db, 'snapshots'); + const byDoc = new Map(); + for (const row of snapshots) { + const docId = row.id || row.docId || 'unknown'; + if (!byDoc.has(docId)) byDoc.set(docId, []); + byDoc.get(docId).push(toBytes(row.bin ?? row.data)); + } + for (const row of updates) { + const docId = row.docId || row.id || 'unknown'; + if (!byDoc.has(docId)) byDoc.set(docId, []); + byDoc.get(docId).push(toBytes(row.bin ?? row.data)); + } + const wsIdForDb = extractWorkspaceIdFromDbName(dbName); + for (const [docId, docUpdates] of byDoc.entries()) { + if (wsIdForDb && docId === wsIdForDb) { + continue; + } + const doc = new Y.Doc(); + let totalBytes = 0; + for (const bytes of docUpdates) { + if (bytes.byteLength > 0) { + Y.applyUpdate(doc, bytes); + totalBytes += bytes.byteLength; + } + } + const tree = walkBlockSuiteTree(doc); + recovered.push({ + dbName, + docId, + clientID: doc.clientID, + updateCount: docUpdates.length, + totalBytes, + pageId: tree.pageId, + noteId: tree.noteId, + noteIds: tree.noteIds, + childIds: tree.childIds, + flavours: tree.flavours, + paragraphs: tree.paragraphs, + paragraphNodes: tree.paragraphNodes, + text: tree.paragraphs.join(' | '), + }); + } + } catch { + // Skip unreadable databases. + } finally { + if (db) { + db.close(); + } + } + } + return recovered; +} + +function renderLegacyDom() { + const statusEl = document.getElementById('legacy-status'); + if (statusEl) { + statusEl.textContent = 'Active shell: mobile-legacy (' + state.buildId + ')'; + } + const reasonEl = document.getElementById('legacy-fallback-reason'); + if (reasonEl && state.fallbackReason) { + reasonEl.textContent = 'Fallback reason: ' + state.fallbackReason; + } + const docEl = document.getElementById('legacy-recovered-doc'); + if (docEl) { + docEl.textContent = + state.recoveredDocs.length > 0 + ? state.recoveredDocs + .map( + d => + '[' + + d.dbName + + '/' + + d.docId + + '] (' + + d.updateCount + + ' Yjs updates, ' + + d.flavours.join(', ') + + ')\\n' + + d.paragraphNodes + .map( + (node, i) => + ' ' + + ' '.repeat(node.depth) + + (i + 1) + + '. ' + + node.text + ) + .join('\\n') + ) + .join('\\n') + : 'No pending local documents in IndexedDB.'; + } +} + +function extractWorkspaceIdFromDbName(dbName) { + if (typeof dbName === 'string' && dbName.startsWith('local:workspace:')) { + const wsId = dbName.slice('local:workspace:'.length).trim(); + return wsId || null; + } + return null; +} + +function navigateUrlToTarget(target) { + const url = new URL(window.location.href); + if (target) { + const wsId = extractWorkspaceIdFromDbName(target.dbName); + if (wsId) { + url.searchParams.set('workspace', wsId); + } + url.searchParams.set('doc', target.docId); + url.searchParams.delete('docId'); + if (/^\\/workspace\\/[^/]+(?:\\/[^/]+)?\\/?$/.test(url.pathname) && wsId) { + url.pathname = + '/workspace/' + + encodeURIComponent(wsId) + + '/' + + encodeURIComponent(target.docId); + } + } else { + url.searchParams.delete('doc'); + url.searchParams.delete('docId'); + if (/^\\/workspace\\/([^/]+)\\/[^/]+\\/?$/.test(url.pathname)) { + url.pathname = url.pathname.replace( + /^(\\/workspace\\/[^/]+)\\/[^/]+\\/?$/, + '$1' + ); + } + } + if (typeof window.history?.replaceState === 'function') { + window.history.replaceState(null, '', url.pathname + url.search + url.hash); + } + state.routeTarget = resolveRouteTarget(); +} + +function syncReturnToNativeLink(activeTarget) { + const linkEl = document.querySelector('a.switch-link'); + if (!linkEl) return; + const route = resolveRouteTarget(); + const wsId = + (activeTarget ? extractWorkspaceIdFromDbName(activeTarget.dbName) : null) || + route.workspaceId || + null; + const docId = activeTarget?.docId || route.docId || null; + const params = new URLSearchParams(); + params.set('shell', 'native'); + if (wsId) { + params.set('workspace', wsId); + } + if (docId) { + params.set('doc', docId); + } + linkEl.setAttribute('href', '/?' + params.toString()); +} + +function materializeDoc(reads) { + const doc = new Y.Doc(); + for (const row of [reads.snapshot.result, ...reads.updates.result]) { + if (!row) continue; + const bytes = toBytes(row.bin ?? row.data); + if (bytes.byteLength) Y.applyUpdate(doc, bytes); + } + return doc; +} + +function buildWorkspaceCatalogDelta(rootDoc, docId) { + const meta = rootDoc.getMap('meta'); + const existingPages = meta.get('pages'); + const hasDoc = + existingPages instanceof Y.Array && + existingPages.toArray().some(entry => { + if (entry instanceof Y.Map) return entry.get('id') === docId; + return entry && typeof entry === 'object' && entry.id === docId; + }); + if (hasDoc) return null; + const prevRootSv = Y.encodeStateVector(rootDoc); + rootDoc.transact(() => { + let pages = meta.get('pages'); + if (!(pages instanceof Y.Array)) { + pages = new Y.Array(); + meta.set('pages', pages); + } + const pageMeta = new Y.Map(); + pageMeta.set('id', docId); + pageMeta.set('title', ''); + pageMeta.set('createDate', Date.now()); + pageMeta.set('tags', new Y.Array()); + pages.push([pageMeta]); + }); + return Y.encodeStateAsUpdate(rootDoc, prevRootSv); +} + +function registerLocalWorkspaceId(wsId) { + if (!wsId) return; + let notifyChannel = null; + try { + if (typeof BroadcastChannel === 'function') { + notifyChannel = new BroadcastChannel(LOCAL_WORKSPACE_CHANGED_CHANNEL); + } + addLocalWorkspaceId(wsId, window.localStorage, notifyChannel); + } catch { + // Never fail document persistence if localStorage is unavailable. + } finally { + notifyChannel?.close(); + } +} + +function deriveActiveTargetFromUrl(candidates) { + const route = resolveRouteTarget(); + state.routeTarget = route; + if (route.docId) { + if (route.dbName) { + return ( + candidates.find( + c => c.dbName === route.dbName && c.docId === route.docId + ) || null + ); + } + const matches = candidates.filter(c => c.docId === route.docId); + return matches.length === 1 ? matches[0] : null; + } + if (candidates.length === 1) { + return candidates[0]; + } + return null; +} + +function syncTargetSelector() { + const selectEl = document.getElementById('legacy-target-doc'); + const btnEl = document.getElementById('legacy-append-btn'); + const route = resolveRouteTarget(); + state.routeTarget = route; + const candidates = state.recoveredDocs.map(d => ({ + dbName: d.dbName, + docId: d.docId, + label: d.dbName + ' / ' + d.docId, + })); + + if ( + route.dbName && + route.docId && + !candidates.some( + c => c.dbName === route.dbName && c.docId === route.docId + ) + ) { + candidates.push({ + dbName: route.dbName, + docId: route.docId, + label: route.dbName + ' / ' + route.docId + ' (new)', + }); + } + + const resolved = deriveActiveTargetFromUrl(candidates); + state.selectedTarget = resolved + ? { dbName: resolved.dbName, docId: resolved.docId } + : null; + + if (selectEl) { + selectEl.textContent = ''; + const placeholder = document.createElement('option'); + placeholder.value = ''; + placeholder.textContent = '-- Select target document --'; + selectEl.append(placeholder); + for (const c of candidates) { + const opt = document.createElement('option'); + opt.value = encodeTargetKey(c.dbName, c.docId); + opt.textContent = c.label; + selectEl.append(opt); + } + selectEl.value = state.selectedTarget + ? encodeTargetKey(state.selectedTarget.dbName, state.selectedTarget.docId) + : ''; + } + if (btnEl) { + btnEl.disabled = !state.selectedTarget; + } + syncReturnToNativeLink(state.selectedTarget); +} + +function appendParagraph(doc, docId, text) { + const prevSv = Y.encodeStateVector(doc); + const tree = walkBlockSuiteTree(doc); + const blocks = doc.getMap('blocks'); + const allocateBlockId = prefix => { + let seq = 0; + let candidate = prefix + '-' + doc.clientID + '-' + Date.now(); + while (blocks.has(candidate)) { + seq += 1; + candidate = + prefix + '-' + doc.clientID + '-' + Date.now() + '-' + seq; + } + return candidate; + }; + const paragraphId = allocateBlockId('para-legacy'); + doc.transact(() => { + let targetNoteId = + tree.noteIds.length > 0 + ? tree.noteIds[tree.noteIds.length - 1] + : null; + if (!targetNoteId) { + const deterministicPageId = 'page:' + docId; + const pageId = + tree.pageId || + (!blocks.has(deterministicPageId) + ? deterministicPageId + : allocateBlockId('page-legacy')); + let page = blocks.get(pageId); + if (!(page instanceof Y.Map)) { + page = new Y.Map(); + page.set('sys:id', pageId); + page.set('sys:flavour', 'affine:page'); + page.set('sys:children', new Y.Array()); + blocks.set(pageId, page); + } + let pageChildren = page.get('sys:children'); + if (!(pageChildren instanceof Y.Array)) { + pageChildren = new Y.Array(); + page.set('sys:children', pageChildren); + } + const deterministicNoteId = 'note:' + docId; + targetNoteId = !blocks.has(deterministicNoteId) + ? deterministicNoteId + : allocateBlockId('note-legacy'); + const note = new Y.Map(); + note.set('sys:id', targetNoteId); + note.set('sys:flavour', 'affine:note'); + note.set('sys:children', new Y.Array()); + blocks.set(targetNoteId, note); + pageChildren.push([targetNoteId]); + } + const note = blocks.get(targetNoteId); + const noteChildren = + note instanceof Y.Map ? note.get('sys:children') : null; + if (!(noteChildren instanceof Y.Array)) { + throw new Error( + 'Cannot append paragraph: missing note sys:children Y.Array' + ); + } + const para = new Y.Map(); + para.set('sys:id', paragraphId); + para.set('sys:flavour', 'affine:paragraph'); + para.set('prop:type', 'text'); + const yText = new Y.Text(); + yText.insert(0, text); + para.set('prop:text', yText); + blocks.set(paragraphId, para); + noteChildren.push([paragraphId]); + }); + const docDelta = Y.encodeStateAsUpdate(doc, prevSv); + return { paragraphId, docDelta, clientID: doc.clientID }; +} + +function saveParagraph(db, wsId, docId, text) { + return new Promise((resolve, reject) => { + const tx = db.transaction(['snapshots', 'updates', 'clocks'], 'readwrite'); + const snapshots = tx.objectStore('snapshots'); + const updates = tx.objectStore('updates'); + const clocks = tx.objectStore('clocks'); + const byDoc = updates.index('docId'); + const reads = new Map(); + let lastRead; + let result; + let failure; + tx.oncomplete = () => resolve(result); + tx.onabort = () => reject(failure || tx.error || new Error('Save aborted')); + + function putDelta(id, delta) { + const storedTime = reads.get(id).clock.result?.timestamp; + const prev = new Date(storedTime ?? 0).getTime(); + const createdAt = new Date(Math.max(Date.now(), (prev || 0) + 1)); + updates.add({ docId: id, createdAt, bin: delta }); + clocks.put({ docId: id, timestamp: createdAt }); + } + + try { + for (const id of wsId && wsId !== docId ? [docId, wsId] : [docId]) { + const snapshot = snapshots.get(id); + const rows = byDoc.getAll(id); + lastRead = clocks.get(id); + reads.set(id, { snapshot, updates: rows, clock: lastRead }); + } + // IndexedDB completes these requests in order with the write lock held. + lastRead.onsuccess = () => { + try { + const doc = materializeDoc(reads.get(docId)); + const { paragraphId, docDelta, clientID } = + appendParagraph(doc, docId, text); + putDelta(docId, docDelta); + if (wsId && wsId !== docId) { + const root = materializeDoc(reads.get(wsId)); + const delta = buildWorkspaceCatalogDelta(root, docId); + if (delta) putDelta(wsId, delta); + } + result = { + ok: true, paragraphId, clientID, byteLength: docDelta.byteLength, + }; + } catch (err) { + failure = err; + tx.abort(); + } + }; + } catch (err) { + failure = err; + tx.abort(); + } + }); +} + +state.appendParagraphEdit = async (dbName, docId, text) => { + const wsId = extractWorkspaceIdFromDbName(dbName); + const db = await openDb(dbName, true); + let result; + try { + result = await saveParagraph(db, wsId, docId, text); + } finally { + db.close(); + } + registerLocalWorkspaceId(wsId); + state.lastEditClientID = result.clientID; + state.recoveredDocs = await inspectRecoveredIdb(); + renderLegacyDom(); + syncTargetSelector(); + return result; +}; + +function bindLegacyEditorUi() { + const selectEl = document.getElementById('legacy-target-doc'); + const inputEl = document.getElementById('legacy-editor-input'); + const btnEl = document.getElementById('legacy-append-btn'); + const statusEl = document.getElementById('legacy-editor-status'); + if (!inputEl || !btnEl) return; + + selectEl?.addEventListener('change', () => { + const nextTarget = decodeTargetKey(selectEl.value); + navigateUrlToTarget(nextTarget); + syncTargetSelector(); + if (statusEl) { + statusEl.textContent = state.selectedTarget + ? 'Target: ' + state.selectedTarget.docId + : 'Please select a target document first.'; + } + }); + + btnEl.addEventListener('click', async () => { + const target = state.selectedTarget; + if (!target) { + if (statusEl) { + statusEl.textContent = 'Please select a target document first.'; + } + return; + } + const text = String(inputEl.value || '').trim(); + if (!text) { + if (statusEl) statusEl.textContent = 'Enter text before appending.'; + return; + } + btnEl.disabled = true; + try { + const res = await state.appendParagraphEdit( + target.dbName, + target.docId, + text + ); + inputEl.value = ''; + if (statusEl) { + statusEl.textContent = + 'Saved to ' + + target.docId + + ' (' + + res.byteLength + + ' B, client ' + + res.clientID + + ')'; + } + } catch (err) { + if (statusEl) { + statusEl.textContent = + 'Save failed: ' + (err instanceof Error ? err.message : String(err)); + } + } finally { + btnEl.disabled = !state.selectedTarget; + } + }); +} + +async function bootLegacyShell() { + ensureLegacyShellDom(); + state.fallbackReason = readFallbackReason(); + state.recoveredDocs = await inspectRecoveredIdb(); + state.ready = true; + window.__AFFINE_LEGACY_SHELL__ = state; + renderLegacyDom(); + syncTargetSelector(); + bindLegacyEditorUi(); +} + +window.__AFFINE_LEGACY_SHELL__ = state; +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', () => void bootLegacyShell(), { + once: true, + }); +} else { + void bootLegacyShell(); +} +})(); +`; + + const assetsManifest = { + publicPath: '/mobile-legacy/', + css: [], + js: ['app.js'], + gitHash: shellBuildId, + description: 'AFFiNE Mobile Legacy Fallback Shell', + }; + + writeFileSync(join(legacyDir, 'index.html'), legacyHtml); + writeFileSync(join(legacyDir, 'app.js'), legacyAppJs); + writeFileSync( + join(legacyDir, 'assets-manifest.json'), + JSON.stringify(assetsManifest, null, 2) + '\n' + ); +} + +/** + * Assembles the full hosted canary dual-shell `/` directory. + * Strictly requires real compiled Wasm binaries for all 4 preview workers and + * the main `playground` package. + * + * @param {Object} options + * @param {string} options.outDir + * @param {string | null} [options.wasmDir] + * @param {string | null} [options.buildId] + * @param {string | null} [options.legacyDir] + * @param {boolean} [options.allowSyntheticLegacy] + * @param {string | null} [options.yjsBundle] + * @param {string | null} [options.desktopDir] + */ +export function stageCanaryDualShell(options) { + const outDir = resolve(options.outDir); + const wasmDir = options.wasmDir ? resolve(options.wasmDir) : null; + const legacySrcDir = options.legacyDir ? resolve(options.legacyDir) : null; + const yjsBundlePath = options.yjsBundle ? resolve(options.yjsBundle) : null; + const desktopSrcDir = options.desktopDir ? resolve(options.desktopDir) : null; + + const mobileDir = join(outDir, 'mobile'); + const mobileSrcDir = join(mobileDir, 'src'); + const mobileWasmDir = join(mobileDir, 'wasm'); + const mobilePkgDir = join(mobileDir, 'pkg'); + const mobileFontsDir = join(mobileDir, 'assets/fonts'); + const mobileLegacyDir = join(outDir, 'mobile-legacy'); + + // Collect source files & binary inputs for deterministic shell_build_id hashing. + const srcFiles = listFilesSorted(join(WEB_ROOT, 'src')); + /** @type {Array<{ name: string, bytes: Buffer }>} */ + const hashInputs = srcFiles.map(file => ({ + name: `src/${relative(join(WEB_ROOT, 'src'), file)}`, + bytes: readFileSync(file), + })); + + /** @type {Record} */ + const workerBins = {}; + for (const kind of WORKER_KINDS) { + const found = findWorkerWasm(wasmDir, kind); + if (!found) { + throw new Error( + `Missing real compiled preview worker wasm for "${kind}". Build blocksuite-preview and pass --wasm-dir .` + ); + } + const bytes = readFileSync(found); + validateRealWasmBinary( + `${kind}-worker.wasm`, + bytes, + PREVIEW_WORKER_REQUIRED_EXPORTS + ); + workerBins[kind] = { src: found, bytes }; + hashInputs.push({ name: `wasm/${kind}.wasm`, bytes }); + } + + const mainPkgSrc = findMainPkgDir(wasmDir); + if (!mainPkgSrc) { + throw new Error( + 'Missing real compiled playground wasm-bindgen package (pkg/playground.js + pkg/playground_bg.wasm). Build playground and pass --wasm-dir .' + ); + } + const mainPkgJsBytes = readFileSync(join(mainPkgSrc, 'playground.js')); + const mainPkgWasmBytes = readFileSync(join(mainPkgSrc, 'playground_bg.wasm')); + const mainPkgJsText = mainPkgJsBytes.toString('utf8'); + for (const sym of PLAYGROUND_REQUIRED_EXPORTS) { + if (!mainPkgJsText.includes(sym)) { + throw new Error( + `Invalid pkg/playground.js: missing required export "${sym}".` + ); + } + } + validateRealWasmBinary( + 'pkg/playground_bg.wasm', + mainPkgWasmBytes, + PLAYGROUND_REQUIRED_EXPORTS + ); + hashInputs.push({ name: 'pkg/playground.js', bytes: mainPkgJsBytes }); + hashInputs.push({ name: 'pkg/playground_bg.wasm', bytes: mainPkgWasmBytes }); + + /** @type {Array<{ key: string, prefix: string, src: string, bytes: Buffer }>} */ + const fontBins = []; + for (const spec of FONT_SPECS) { + if (!existsSync(spec.src)) { + throw new Error(`Missing tracked font source: ${spec.src}`); + } + const bytes = readFileSync(spec.src); + fontBins.push({ ...spec, bytes }); + hashInputs.push({ name: `fonts/${spec.prefix}.ttf`, bytes }); + } + + const shellBuildId = + (options.buildId && options.buildId.trim()) || + computeShellBuildId(hashInputs); + + // Prepare clean mobile & mobile-legacy output directories. + rmSync(mobileDir, { recursive: true, force: true }); + rmSync(mobileLegacyDir, { recursive: true, force: true }); + mkdirSync(mobileSrcDir, { recursive: true }); + mkdirSync(mobileWasmDir, { recursive: true }); + mkdirSync(mobilePkgDir, { recursive: true }); + mkdirSync(mobileFontsDir, { recursive: true }); + + // 1. Copy desktop shell or create a minimal desktop placeholder. + if (desktopSrcDir && existsSync(desktopSrcDir)) { + cpSync(desktopSrcDir, outDir, { recursive: true }); + } else if (!existsSync(join(outDir, 'index.html'))) { + mkdirSync(join(outDir, 'assets'), { recursive: true }); + writeFileSync( + join(outDir, 'index.html'), + `AFFiNE Desktop
\n` + ); + writeFileSync( + join(outDir, 'assets/desktop.js'), + 'window.__AFFINE_DESKTOP_SHELL__ = true;\n' + ); + } + + // 2. Stage mobile/src/**. + cpSync(join(WEB_ROOT, 'src'), mobileSrcDir, { recursive: true }); + + // 3. Stage content-hash-locked worker wasm binaries under mobile/wasm/. + /** @type {Record} */ + const manifestWorkers = {}; + /** @type {Record} */ + const htmlWorkers = {}; + for (const kind of WORKER_KINDS) { + const fileName = `${kind}-worker.${shellBuildId}.wasm`; + const dst = join(mobileWasmDir, fileName); + writeFileSync(dst, workerBins[kind].bytes); + htmlWorkers[kind] = { + script: `/src/workers/${kind}-worker.js`, + wasm: `/wasm/${fileName}`, + }; + manifestWorkers[kind] = { + script: `/mobile/src/workers/${kind}-worker.js`, + wasm: `/mobile/wasm/${fileName}`, + sha256: sha256Hex(workerBins[kind].bytes), + bytes: workerBins[kind].bytes.byteLength, + }; + } + + // 4. Stage main playground wasm-bindgen bundle under mobile/pkg/. + writeFileSync(join(mobilePkgDir, 'playground.js'), mainPkgJsBytes); + writeFileSync(join(mobilePkgDir, 'playground_bg.wasm'), mainPkgWasmBytes); + if (existsSync(join(mainPkgSrc, 'snippets'))) { + cpSync(join(mainPkgSrc, 'snippets'), join(mobilePkgDir, 'snippets'), { + recursive: true, + }); + } + + // 5. Stage content-hash-locked fonts under mobile/assets/fonts/. + /** @type {Record} */ + const htmlFonts = {}; + /** @type {Record} */ + const manifestFonts = {}; + for (const font of fontBins) { + const fileName = `${font.prefix}.${shellBuildId}.ttf`; + copyFileSync(font.src, join(mobileFontsDir, fileName)); + htmlFonts[font.key] = `/assets/fonts/${fileName}`; + manifestFonts[font.key] = { + url: `/mobile/assets/fonts/${fileName}`, + sha256: sha256Hex(font.bytes), + bytes: font.bytes.byteLength, + }; + } + + // 6. Rewrite mobile/index.html with locked shell_build_id and cookie-immune /mobile/ assetBaseUrl. + const rawIndexHtml = readFileSync(join(WEB_ROOT, 'index.html'), 'utf8'); + const embeddedManifest = { + shellVersion: 'mobile-v1', + shell_build_id: shellBuildId, + buildId: shellBuildId, + buildHash: shellBuildId, + assetBaseUrl: '/mobile/', + appEntryJs: '/src/default-app-entry.js', + mainWasmJs: '/pkg/playground.js', + workers: htmlWorkers, + fonts: htmlFonts, + }; + const stagedIndexHtml = rawIndexHtml + .replace( + /` + ) + .replace( + '', + '' + ); + writeFileSync(join(mobileDir, 'index.html'), stagedIndexHtml); + + // 7. Rewrite mobile/sign-in.html with cookie-immune /mobile/src/sign-in.js. + const rawSignInHtml = readFileSync(join(WEB_ROOT, 'sign-in.html'), 'utf8'); + const stagedSignInHtml = rawSignInHtml.replace( + '', + '' + ); + writeFileSync(join(mobileDir, 'sign-in.html'), stagedSignInHtml); + + // 8. Stage mobile-legacy/ fallback shell. + if (legacySrcDir) { + if ( + !statSync(legacySrcDir, { throwIfNoEntry: false })?.isDirectory() || + !statSync(join(legacySrcDir, 'index.html'), { + throwIfNoEntry: false, + })?.isFile() + ) { + throw new Error( + `Invalid --legacy-dir "${legacySrcDir}": directory must exist and contain index.html (build @affine/mobile first).` + ); + } + cpSync(legacySrcDir, mobileLegacyDir, { recursive: true }); + } else if (options.allowSyntheticLegacy) { + writeDefaultLegacyShell(mobileLegacyDir, shellBuildId, yjsBundlePath); + } else { + throw new Error( + 'Missing required --legacy-dir (pass --synthetic-legacy-fixture only in isolated test harnesses).' + ); + } + + // 9. Write structured release manifest. + const releaseManifest = { + schemaVersion: 1, + shellVersion: 'mobile-v1', + shell_build_id: shellBuildId, + assetBaseUrl: '/mobile/', + legacyBaseUrl: '/mobile-legacy/', + pkg: { + js: '/mobile/pkg/playground.js', + wasm: '/mobile/pkg/playground_bg.wasm', + jsSha256: sha256Hex(mainPkgJsBytes), + wasmSha256: sha256Hex(mainPkgWasmBytes), + }, + workers: manifestWorkers, + fonts: manifestFonts, + }; + writeFileSync( + join(mobileDir, 'release-manifest.json'), + JSON.stringify(releaseManifest, null, 2) + '\n' + ); + + return { + outDir, + shellBuildId, + mobileDir, + mobileLegacyDir, + releaseManifest, + }; +} + +function parseCliArgs(argv) { + /** @type {Record} */ + const args = {}; + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i]; + if (token === '--synthetic-legacy-fixture') { + args['synthetic-legacy-fixture'] = true; + } else if ( + token === '--out' || + token === '--wasm-dir' || + token === '--build-id' || + token === '--legacy-dir' || + token === '--yjs-bundle' || + token === '--desktop-dir' + ) { + const next = argv[i + 1]; + if (!next || next.startsWith('--')) { + throw new Error(`Missing value for ${token}`); + } + args[token.slice(2)] = next; + i += 1; + } else { + throw new Error(`Unknown argument: ${token}`); + } + } + return args; +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const cli = parseCliArgs(process.argv.slice(2)); + if (typeof cli.out !== 'string' || !cli.out.trim()) { + console.error( + 'Usage: node stage-canary-dual-shell.mjs --out --wasm-dir --legacy-dir [--build-id ] [--desktop-dir ] [--synthetic-legacy-fixture]' + ); + process.exit(1); + } + const result = stageCanaryDualShell({ + outDir: cli.out, + wasmDir: typeof cli['wasm-dir'] === 'string' ? cli['wasm-dir'] : null, + buildId: typeof cli['build-id'] === 'string' ? cli['build-id'] : null, + legacyDir: typeof cli['legacy-dir'] === 'string' ? cli['legacy-dir'] : null, + allowSyntheticLegacy: Boolean(cli['synthetic-legacy-fixture']), + yjsBundle: typeof cli['yjs-bundle'] === 'string' ? cli['yjs-bundle'] : null, + desktopDir: + typeof cli['desktop-dir'] === 'string' ? cli['desktop-dir'] : null, + }); + console.log( + JSON.stringify( + { + ok: true, + outDir: result.outDir, + shell_build_id: result.shellBuildId, + workers: Object.keys(result.releaseManifest.workers), + fonts: Object.keys(result.releaseManifest.fonts), + }, + null, + 2 + ) + ); +} diff --git a/packages/frontend/hosts/web/scripts/stage-preview-workers.mjs b/packages/frontend/hosts/web/scripts/stage-preview-workers.mjs new file mode 100644 index 0000000000..7e21d64bbe --- /dev/null +++ b/packages/frontend/hosts/web/scripts/stage-preview-workers.mjs @@ -0,0 +1,79 @@ +#!/usr/bin/env node +// @ts-check + +import { copyFileSync, cpSync, existsSync, mkdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const FRONTEND_ROOT = resolve(WEB_ROOT, '../..'); +const ASSETS_DIR = join(WEB_ROOT, 'assets'); +const FONTS_OUT_DIR = join(ASSETS_DIR, 'fonts'); +const SOURCE_DIR = process.argv[2] + ? resolve(process.argv[2]) + : '/tmp/preview-wasm'; +const BUILD_HASH = process.argv[3] || 'dev-local'; + +const KINDS = ['mermaid', 'math', 'typst', 'pdf']; +const FONT_SPECS = [ + { + src: join( + FRONTEND_ROOT, + 'component/src/fonts/inter/Inter-VariableFont_slnt,wght.ttf' + ), + outName: `inter-latin.${BUILD_HASH}.ttf`, + }, + { + src: join( + FRONTEND_ROOT, + 'component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf' + ), + outName: `ibm-plex-mono.${BUILD_HASH}.ttf`, + }, +]; + +mkdirSync(ASSETS_DIR, { recursive: true }); +mkdirSync(FONTS_OUT_DIR, { recursive: true }); + +for (const kind of KINDS) { + const src = join(SOURCE_DIR, `${kind}.wasm`); + if (!existsSync(src)) { + throw new Error(`Missing built preview wasm binary: ${src}`); + } + const dst = join(ASSETS_DIR, `${kind}-worker.${BUILD_HASH}.wasm`); + copyFileSync(src, dst); +} + +const PKG_OUT_DIR = join(ASSETS_DIR, 'pkg'); +const pkgSrcDir = join(SOURCE_DIR, 'pkg'); +if ( + existsSync(join(pkgSrcDir, 'playground.js')) && + existsSync(join(pkgSrcDir, 'playground_bg.wasm')) +) { + mkdirSync(PKG_OUT_DIR, { recursive: true }); + copyFileSync( + join(pkgSrcDir, 'playground.js'), + join(PKG_OUT_DIR, 'playground.js') + ); + copyFileSync( + join(pkgSrcDir, 'playground_bg.wasm'), + join(PKG_OUT_DIR, 'playground_bg.wasm') + ); + const snippetsSrc = join(pkgSrcDir, 'snippets'); + if (existsSync(snippetsSrc)) { + cpSync(snippetsSrc, join(PKG_OUT_DIR, 'snippets'), { recursive: true }); + } +} else { + throw new Error(`Missing main wasm-bindgen package under: ${pkgSrcDir}`); +} + +for (const font of FONT_SPECS) { + if (!existsSync(font.src)) { + throw new Error(`Missing tracked font source: ${font.src}`); + } + copyFileSync(font.src, join(FONTS_OUT_DIR, font.outName)); +} + +console.log( + `Staged 4 preview Wasm workers, main playground Wasm bundle, and ${FONT_SPECS.length} static fonts into ${ASSETS_DIR}` +); diff --git a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs new file mode 100644 index 0000000000..8dc90204be --- /dev/null +++ b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs @@ -0,0 +1,744 @@ +#!/usr/bin/env node +// @ts-check + +/** + * Real-browser Headless Chromium CI gate for Canary Dual-Shell routing, + * `@affine/mobile`-shaped legacy shell staging (`assets-manifest.json`), + * zero-empty-IndexedDB guard on unknown/cloud workspace URLs, and same-origin + * IndexedDB v3 CRDT persistence across WebGPU crash fallback (`native` <-> `legacy`). + * + * Uses the prebuilt `/tmp/preview-wasm` bundle (`playground_bg.wasm` + 4 preview + * `.wasm` workers). `chromium-harness.mjs` owns the Chromium process group and + * the temporary work directory. + */ + +import assert from 'node:assert/strict'; +import { + existsSync, + mkdirSync, + readFileSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { createServer } from 'node:http'; +import { extname, join, normalize, resolve } from 'node:path'; + +import { createChromiumHarness, openPageTarget } from './chromium-harness.mjs'; +import { stageCanaryDualShell } from './stage-canary-dual-shell.mjs'; +import { verifyZeroThirdPartyJs } from './verify-zero-third-party-js.mjs'; + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.ttf': 'font/ttf', +}; + +function parseShellCookie(cookieHeader) { + const raw = String(cookieHeader || ''); + for (const part of raw.split(';')) { + const [k, v] = part.trim().split('='); + if ( + k === 'affine_shell' && + (v === 'native' || v === 'legacy' || v === 'desktop') + ) { + return v; + } + } + return null; +} + +const wasmDirArg = process.argv[2] || '/tmp/preview-wasm'; +const harness = createChromiumHarness({ tmpPrefix: 'affine-dual-ci-' }); +const legacyDistDir = join(harness.workTmp, 'legacy-mobile-dist'); +const stagedRoot = join(harness.workTmp, 'static-root'); +mkdirSync(join(legacyDistDir, 'js'), { recursive: true }); + +// Build an `@affine/mobile`-shaped dist directory (`assets-manifest.json` + `index.html` + `js/mobile-legacy.js`) +// that opens same-origin `local:workspace:` IndexedDB v3 directly without Web Locks and verifies/appends CRDT updates. +writeFileSync( + join(legacyDistDir, 'assets-manifest.json'), + JSON.stringify( + { + publicPath: '/mobile-legacy/', + css: [], + js: ['js/mobile-legacy.js'], + gitHash: 'ci-dual-shell', + description: 'AFFiNE Mobile Legacy Shell', + }, + null, + 2 + ) + '\n' +); +writeFileSync( + join(legacyDistDir, 'index.html'), + ` + + + + + AFFiNE Mobile Legacy + + +
+ Return to Native Shell + + + +` +); +writeFileSync( + join(legacyDistDir, 'js/mobile-legacy.js'), + `import initWasm, { + WasmLocalDocSession, +} from '/pkg/playground.js'; +import { + addLocalWorkspaceId, + createIdbWorkspaceStorage, +} from '/mobile/src/idb-storage.js'; + +let wasmReady = null; +function ensureWasm() { + if (!wasmReady) { + wasmReady = initWasm('/pkg/playground_bg.wasm'); + } + return wasmReady; +} + +async function readParagraphs(wsId, docId) { + await ensureWasm(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: wsId, + }); + try { + const raw = await storage.getDocRaw(docId); + if (!raw) return null; + const session = new WasmLocalDocSession(docId, 777); + try { + if (raw.snapshot && raw.snapshot.byteLength > 0) { + session.apply_update_v1(raw.snapshot); + } + for (const frame of raw.updates || []) { + if (frame && frame.byteLength > 0) { + session.apply_update_v1(frame); + } + } + return JSON.parse(session.read_snapshot_json()); + } finally { + session.free(); + } + } finally { + storage.close(); + } +} + +async function seedWorkspaceDoc(wsId, docId, title, firstParagraph) { + await ensureWasm(); + const initSession = new WasmLocalDocSession(docId, 101); + let snapshotBytes; + try { + snapshotBytes = initSession.initialize_page(title, firstParagraph, Date.now()); + } finally { + initSession.free(); + } + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: wsId, + }); + try { + await storage.pushDocUpdate({ docId, bin: snapshotBytes }); + addLocalWorkspaceId(wsId, window.localStorage); + } finally { + storage.close(); + } +} + +async function appendLegacyParagraph(wsId, docId, text) { + await ensureWasm(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: wsId, + }); + try { + const raw = await storage.getDocRaw(docId); + if (!raw) throw new Error('Missing doc in legacy shell: ' + docId); + const session = new WasmLocalDocSession(docId, 888); + try { + if (raw.snapshot && raw.snapshot.byteLength > 0) { + session.apply_update_v1(raw.snapshot); + } + for (const frame of raw.updates || []) { + if (frame && frame.byteLength > 0) { + session.apply_update_v1(frame); + } + } + const delta = session.append_paragraph(text, Date.now()); + await storage.pushDocUpdate({ docId, bin: delta }); + return JSON.parse(session.read_snapshot_json()); + } finally { + session.free(); + } + } finally { + storage.close(); + } +} + +const u = new URL(window.location.href); +const m = u.pathname.match(/^\\/workspace\\/([^/]+)\\/([^/]+)/); +const wsId = u.searchParams.get('workspace') || (m ? m[1] : ''); +const docId = u.searchParams.get('doc') || (m ? m[2] : ''); +const link = document.getElementById('return-native-link'); +if (link && wsId && docId) { + link.setAttribute( + 'href', + '/workspace/' + encodeURIComponent(wsId) + '/' + encodeURIComponent(docId) + '?shell=native' + ); +} + +window.__AFFINE_LEGACY_SHELL__ = { + ready: true, + shell: 'legacy', + readParagraphs, + seedWorkspaceDoc, + appendLegacyParagraph, +}; +` +); + +const staged = stageCanaryDualShell({ + outDir: stagedRoot, + wasmDir: wasmDirArg, + legacyDir: legacyDistDir, +}); +const zeroCheck = verifyZeroThirdPartyJs({ stageDir: staged.mobileDir }); +assert.equal(zeroCheck.ok, true, zeroCheck.violations.join('; ')); + +function tryServeFile(rootDir, relPath, res, extraHeaders = {}) { + const cleanRel = normalize(relPath).replace(/^\/+/, ''); + const full = resolve(rootDir, cleanRel); + if ( + (full !== rootDir && !full.startsWith(rootDir + '/')) || + !existsSync(full) || + !statSync(full).isFile() + ) { + return false; + } + res.writeHead(200, { + 'content-type': MIME_TYPES[extname(full)] || 'application/octet-stream', + ...extraHeaders, + }); + res.end(readFileSync(full)); + return true; +} + +const server = createServer((req, res) => { + const url = new URL(req.url || '/', 'http://127.0.0.1'); + const pathname = url.pathname; + const prefixMap = [ + ['/wasm/', join(stagedRoot, 'mobile/wasm')], + ['/pkg/', join(stagedRoot, 'mobile/pkg')], + ['/mobile/', join(stagedRoot, 'mobile')], + ['/mobile-legacy/', join(stagedRoot, 'mobile-legacy')], + ]; + for (const [prefix, dir] of prefixMap) { + if (pathname.startsWith(prefix)) { + const rel = pathname.slice(prefix.length); + if (!tryServeFile(dir, rel, res)) { + res.writeHead(404); + res.end('not found'); + } + return; + } + } + + const qShell = url.searchParams.get('shell'); + const explicitShell = + qShell === 'native' || qShell === 'legacy' || qShell === 'desktop' + ? qShell + : null; + const cookieShell = parseShellCookie(req.headers.cookie); + const shell = explicitShell || cookieShell || 'native'; + const shellRoot = + shell === 'legacy' + ? join(stagedRoot, 'mobile-legacy') + : shell === 'desktop' + ? stagedRoot + : join(stagedRoot, 'mobile'); + /** @type {Record} */ + const headers = { + 'cache-control': 'no-store', + vary: 'User-Agent, Cookie', + }; + if (explicitShell) { + headers['set-cookie'] = + `affine_shell=${explicitShell}; Path=/; Max-Age=2592000; SameSite=Lax`; + } + if (pathname !== '/' && tryServeFile(shellRoot, pathname, res, headers)) { + return; + } + if (!tryServeFile(shellRoot, 'index.html', res, headers)) { + res.writeHead(404); + res.end('not found'); + } +}); + +await new Promise(resolveListen => + server.listen(0, '127.0.0.1', resolveListen) +); +const addr = server.address(); +const port = typeof addr === 'object' && addr ? addr.port : 0; +const baseUrl = `http://127.0.0.1:${port}`; + +/** @type {WebSocket[]} */ +const openSockets = []; + +async function connectTab(wsDebuggerUrl, label = 'tab') { + const ws = new WebSocket(wsDebuggerUrl); + openSockets.push(ws); + await new Promise((ok, fail) => { + const timer = setTimeout( + () => fail(new Error(`CDP WebSocket open timed out (${label})`)), + 10000 + ); + ws.addEventListener( + 'open', + () => { + clearTimeout(timer); + ok(); + }, + { once: true } + ); + ws.addEventListener( + 'error', + err => { + clearTimeout(timer); + fail( + new Error( + `CDP WebSocket error (${label}): ${String(err?.message || err)}` + ) + ); + }, + { once: true } + ); + }); + let nextId = 1; + const pending = new Map(); + /** @type {Array<{ url: string, status: number }>} */ + const responses = []; + ws.addEventListener('close', () => { + for (const [id, entry] of pending.entries()) { + pending.delete(id); + entry.fail(new Error(`CDP WebSocket closed during ${entry.stage}`)); + } + }); + ws.addEventListener('message', ev => { + const msg = JSON.parse(String(ev.data)); + if (msg.id && pending.has(msg.id)) { + const { ok, fail } = pending.get(msg.id); + pending.delete(msg.id); + if (msg.error) fail(new Error(msg.error.message)); + else ok(msg.result); + } else if (msg.method === 'Network.responseReceived') { + responses.push({ + url: msg.params.response.url, + status: msg.params.response.status, + }); + } + }); + const send = (method, params = {}, stage = method, timeoutMs = 15000) => + new Promise((ok, fail) => { + const id = nextId++; + const timer = setTimeout(() => { + if (pending.has(id)) { + pending.delete(id); + fail( + new Error(`CDP [${stage}] ${method} timed out after ${timeoutMs}ms`) + ); + } + }, timeoutMs); + pending.set(id, { + stage, + ok: val => { + clearTimeout(timer); + ok(val); + }, + fail: err => { + clearTimeout(timer); + fail(err); + }, + }); + ws.send(JSON.stringify({ id, method, params })); + }); + await send('Page.enable', {}, `${label}:Page.enable`); + await send('Runtime.enable', {}, `${label}:Runtime.enable`); + await send('Network.enable', {}, `${label}:Network.enable`); + const evalJs = async (expression, stage = `${label}:evalJs`) => { + const res = await send( + 'Runtime.evaluate', + { + expression, + awaitPromise: true, + returnByValue: true, + }, + stage + ); + if (res.exceptionDetails) { + throw new Error( + `Browser eval [${stage}] failed: ${JSON.stringify(res.exceptionDetails)}` + ); + } + return res.result?.value; + }; + return { send, evalJs, responses }; +} + +async function waitFor(evalJs, expr, timeoutMs = 15000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await evalJs(expr)) return; + await new Promise(r => setTimeout(r, 40)); + } + throw new Error(`Timed out waiting for: ${expr}`); +} + +try { + const debugPort = await harness.launchChromium(); + const tabAInfo = await openPageTarget(debugPort); + const tabA = await connectTab(tabAInfo.webSocketDebuggerUrl); + + // 1. Navigating to an unknown/cloud workspace URL on Native Shell MUST NOT create an empty IndexedDB. + console.log( + '[phase 1/4] verify unknown/cloud workspace URL creates zero empty IndexedDBs' + ); + await tabA.send( + 'Page.navigate', + { + url: `${baseUrl}/workspace/cloud-unregistered-ws/doc-404?shell=native`, + }, + 'phase1:navigate-unregistered' + ); + await waitFor( + expr => tabA.evalJs(expr, 'phase1:wait-host-boot'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.selectionOverlay && !document.getElementById("boot"))' + ); + const missingWsCheck = await tabA.evalJs( + `(async () => { + const dbs = await indexedDB.databases(); + return { + dbNames: dbs.map(d => d.name), + hasSession: Boolean(window.__AFFINE_WEB_HOST__.activeDocSession), + }; + })()`, + 'phase1:check-idb' + ); + assert.deepEqual( + missingWsCheck.dbNames, + [], + `Unregistered cloud workspace URL must create 0 IndexedDB databases, got ${JSON.stringify(missingWsCheck.dbNames)}` + ); + assert.equal(missingWsCheck.hasSession, false); + + // 2. Open Tab B on `?shell=legacy`, seed an initialized BlockSuite v3 workspace & document, + // and verify Tab A's cookie-immune `/wasm/*` and `/pkg/*` lazy fetches stay 200 OK while `affine_shell=legacy` is set! + console.log( + '[phase 2/4] seed legacy IndexedDB v3 workspace & verify cookie-immune /wasm + /pkg fetches' + ); + const newTarget = await openPageTarget(debugPort, `${baseUrl}/?shell=legacy`); + const tabB = await connectTab(newTarget.webSocketDebuggerUrl); + await waitFor( + tabB.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)' + ); + await tabB.evalJs( + `window.__AFFINE_LEGACY_SHELL__.seedWorkspaceDoc('ws-ci-dual', 'doc-1', 'Dual Shell CI', 'Para 1: Seeded')` + ); + + const lazyUnderLegacyCookie = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + const pdfWasm = h.workerLoader.resolveWorkerAssets('pdf').wasm; + const r1 = await fetch(pdfWasm, { credentials: 'same-origin' }); + const r2 = await fetch('/pkg/playground_bg.wasm', { credentials: 'same-origin' }); + return { + cookie: document.cookie, + pdfStatus: r1.status, + pdfBytes: (await r1.arrayBuffer()).byteLength, + pkgStatus: r2.status, + pkgBytes: (await r2.arrayBuffer()).byteLength, + }; + })()`); + assert.ok(lazyUnderLegacyCookie.cookie.includes('affine_shell=legacy')); + assert.equal(lazyUnderLegacyCookie.pdfStatus, 200); + assert.ok(lazyUnderLegacyCookie.pdfBytes > 10 * 1024); + assert.equal(lazyUnderLegacyCookie.pkgStatus, 200); + assert.ok(lazyUnderLegacyCookie.pkgBytes > 10 * 1024); + + // 3. Open `/workspace/ws-ci-dual/doc-1?shell=native`, edit in WasmLocalDocSession, + // inject 2 WebGPU `uncapturederror` crashes -> flushBeforeNavigation -> `?shell=legacy` + // -> append in legacy -> Return to Native Shell -> verify all 3 paragraphs! + console.log( + '[phase 3/4] native edit -> 2x WebGPU loss fallback -> legacy append' + ); + await tabA.send( + 'Page.navigate', + { + url: `${baseUrl}/workspace/ws-ci-dual/doc-1?shell=native`, + }, + 'phase3:navigate-native' + ); + await waitFor( + expr => tabA.evalJs(expr, 'phase3:wait-native-session'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))' + ); + const initialParagraphs = await tabA.evalJs( + 'window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs', + 'phase3:read-seeded-snapshot' + ); + assert.deepEqual(initialParagraphs, ['Para 1: Seeded']); + + await tabA.evalJs( + `(async () => { + const h = window.__AFFINE_WEB_HOST__; + await h.activeDocSession.appendParagraph('Para 2: Native Before Crash'); + const listeners = []; + let recoverOnce = true; + const makeFakeDevice = () => ({ + addEventListener(type, fn) { + if (type === 'uncapturederror') listeners.push(fn); + }, + }); + const recoveryOpts = { + tryRebuildWebGpu: () => { + if (recoverOnce) { + recoverOnce = false; + h.bindWebGpuDevice(makeFakeDevice(), recoveryOpts); + return true; + } + return false; + }, + tryWebGl2Fallback: () => false, + }; + h.bindWebGpuDevice(makeFakeDevice(), recoveryOpts); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + unsub(); + reject( + new Error( + 'Timed out waiting for first WebGPU rebuild subscription: ' + + JSON.stringify({ + state: h.gpuRecovery.getState(), + listeners: listeners.length, + }) + ) + ); + }, 5000); + const unsub = h.gpuRecovery.subscribe(st => { + if (st.restoreCount >= 1 && st.status === 'ready' && listeners.length >= 2) { + clearTimeout(timer); + unsub(); + resolve(); + } + }); + listeners[0]({ error: new Error('gpu-loss-1') }); + }); + listeners[1]({ error: new Error('gpu-loss-2') }); + })()`, + 'phase3:trigger-2x-webgpu-loss' + ); + + await waitFor( + expr => tabA.evalJs(expr, 'phase3:wait-legacy-fallback'), + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)' + ); + const afterFallbackSnap = await tabA.evalJs( + `window.__AFFINE_LEGACY_SHELL__.appendLegacyParagraph('ws-ci-dual', 'doc-1', 'Para 3: Appended In Legacy')`, + 'phase3:append-in-legacy' + ); + assert.deepEqual(afterFallbackSnap.paragraphs, [ + 'Para 1: Seeded', + 'Para 2: Native Before Crash', + 'Para 3: Appended In Legacy', + ]); + + console.log( + '[phase 4/4] return to native shell & verify CRDT round-trip + createIfMissing' + ); + await tabA.evalJs( + `document.getElementById('return-native-link').click()`, + 'phase4:click-return-native' + ); + await waitFor( + expr => tabA.evalJs(expr, 'phase4:wait-native-return'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))' + ); + const mainParas = await tabA.evalJs( + `window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs`, + 'phase4:read-main-paras' + ); + assert.deepEqual(mainParas, [ + 'Para 1: Seeded', + 'Para 2: Native Before Crash', + 'Para 3: Appended In Legacy', + ]); + + await tabA.send( + 'Page.navigate', + { + url: `${baseUrl}/workspace/ws-ci-dual/doc-2-created-in-native?shell=native&create=1&title=Native%20Created&firstParagraph=Para%20A%3A%20Created%20Via%20Route`, + }, + 'phase4:navigate-create-route' + ); + await waitFor( + expr => tabA.evalJs(expr, 'phase4:wait-created-route-session'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocId === "doc-2-created-in-native" && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))' + ); + const createdRouteParas = await tabA.evalJs( + `window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs`, + 'phase4:read-created-route-paras' + ); + assert.deepEqual(createdRouteParas, ['Para A: Created Via Route']); + + // Dual-tab real-Chromium IndexedDB race: both `tabA` and `tabB` read `doc-race-browser` + // as missing (`null`) before either writes, then concurrently invoke `createIfMissing` + // with distinct initial content. Verify only ONE update is persisted, both tabs load + // the winning content, and a fresh reload preserves the same content. + await tabB.send( + 'Page.navigate', + { + url: `${baseUrl}/workspace/ws-ci-dual/doc-1?shell=native`, + }, + 'phase4:tabB-navigate-native' + ); + await waitFor( + expr => tabB.evalJs(expr, 'phase4:wait-tabB-native-session'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))' + ); + + const armRaceScript = (title, para) => `(() => { + const h = window.__AFFINE_WEB_HOST__; + const origGetRaw = h.workspaceStorage.getDocRaw.bind(h.workspaceStorage); + window.__raceEnteredGetRaw = false; + window.__releaseRaceGetRaw = null; + h.workspaceStorage.getDocRaw = async docId => { + const res = await origGetRaw(docId); + if (docId === 'doc-race-browser' && !window.__raceEnteredGetRaw) { + window.__raceEnteredGetRaw = true; + await new Promise(r => { + window.__releaseRaceGetRaw = r; + }); + } + return res; + }; + window.__raceOpenPromise = h.openDoc('doc-race-browser', { + createIfMissing: { + title: ${JSON.stringify(title)}, + firstParagraph: ${JSON.stringify(para)}, + }, + }); + return true; + })()`; + + await Promise.all([ + tabA.evalJs( + armRaceScript('Browser Title A', 'Para Browser A'), + 'phase4:arm-tabA-race' + ), + tabB.evalJs( + armRaceScript('Browser Title B', 'Para Browser B'), + 'phase4:arm-tabB-race' + ), + ]); + await waitFor( + expr => tabA.evalJs(expr, 'phase4:wait-tabA-getraw'), + 'Boolean(window.__raceEnteredGetRaw && typeof window.__releaseRaceGetRaw === "function")' + ); + await waitFor( + expr => tabB.evalJs(expr, 'phase4:wait-tabB-getraw'), + 'Boolean(window.__raceEnteredGetRaw && typeof window.__releaseRaceGetRaw === "function")' + ); + + const [tabARaceRes, tabBRaceRes] = await Promise.all([ + tabA.evalJs( + `(async () => { + window.__releaseRaceGetRaw(); + const s = await window.__raceOpenPromise; + const raw = await window.__AFFINE_WEB_HOST__.workspaceStorage.getDocRaw('doc-race-browser'); + return { + paragraphs: s.getSnapshot().paragraphs, + updateCount: raw ? raw.updates.length : 0, + }; + })()`, + 'phase4:finish-tabA-race' + ), + tabB.evalJs( + `(async () => { + window.__releaseRaceGetRaw(); + const s = await window.__raceOpenPromise; + const raw = await window.__AFFINE_WEB_HOST__.workspaceStorage.getDocRaw('doc-race-browser'); + return { + paragraphs: s.getSnapshot().paragraphs, + updateCount: raw ? raw.updates.length : 0, + }; + })()`, + 'phase4:finish-tabB-race' + ), + ]); + assert.equal(tabARaceRes.updateCount, 1); + assert.equal(tabBRaceRes.updateCount, 1); + assert.deepEqual(tabARaceRes.paragraphs, tabBRaceRes.paragraphs); + assert.ok( + tabARaceRes.paragraphs[0] === 'Para Browser A' || + tabARaceRes.paragraphs[0] === 'Para Browser B' + ); + + await tabA.send( + 'Page.navigate', + { + url: `${baseUrl}/workspace/ws-ci-dual/doc-race-browser?shell=native`, + }, + 'phase4:reload-race-doc' + ); + await waitFor( + expr => tabA.evalJs(expr, 'phase4:wait-reloaded-race-doc'), + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocId === "doc-race-browser" && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))' + ); + const reloadedRaceParas = await tabA.evalJs( + `window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs`, + 'phase4:read-reloaded-race-doc' + ); + assert.deepEqual(reloadedRaceParas, tabARaceRes.paragraphs); + + const finalNativeParagraphs = { + mainParas, + createdParas: createdRouteParas, + }; + + const badResponses = tabA.responses.filter( + r => r.status >= 400 && !r.url.endsWith('/favicon.ico') + ); + assert.deepEqual(badResponses, []); + + console.log( + 'ALL CANARY DUAL-SHELL REAL-BROWSER CI CHECKS PASSED:', + JSON.stringify({ + shellBuildId: staged.shellBuildId, + zeroEmptyIdbOnUnknownWorkspace: true, + paragraphs: finalNativeParagraphs.mainParas, + }) + ); +} finally { + for (const s of openSockets) { + try { + s.close(); + } catch { + // ignore + } + } + server.close(); + await harness.close(); +} diff --git a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs new file mode 100644 index 0000000000..318ac2b91d --- /dev/null +++ b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs @@ -0,0 +1,2167 @@ +#!/usr/bin/env node +// @ts-check + +/** + * End-to-end verification for hosted `canary` dual-shell static routing + + * pure-Rust `server-http` (`affine-server`) + real Headless Chromium: + * + * 1. Stages `/{mobile,mobile-legacy}` via `stage-canary-dual-shell.mjs` + * and verifies zero third-party JS in the staged mobile shell. + * 2. Starts a real `affine-server` (`--role front --deployment-mode cloud --channel canary`) + * or connects to `--base-url `. + * 3. Opens two same-origin tabs in real Headless Chromium (`390x844 @ 2x DPR`): + * - Tab A: `native` mobile shell + * - Tab B: `mobile-legacy` fallback shell (`?shell=legacy`, sets `affine_shell=legacy`) + * Verifies Tab A lazily loads `/mobile/*`, `/wasm/*`, `/pkg/*` after Tab B sets + * the `legacy` cookie with 0 404s, 0 CSP violations, and 0 cross-shell asset leaks. + * 4. Verifies `/sign-in`, `/magic-link`, `/oauth/callback` auth route & strict CSP boundary. + * 5. Verifies SSR OpenGraph (`og:title`, `og:description`, `og:image`) & `X-Robots-Tag: noindex` + * on `/workspace//` for both crawler UA and mobile UA. + * 6. Injects 2 consecutive WebGPU crashes (`device.lost` + `uncapturederror`) in real Chromium: + * - Crash #1 recovers in-place on `native` shell without navigation. + * - Verifies flush-failure aborts redirect (`fallback-blocked`) without silent data loss. + * - Crash #2 trips `webgpu-crash-threshold`, flushes pending Yjs edits via + * `flushPendingBeforeRedirect` into same-origin IndexedDB, writes fallback marker, + * navigates to `?shell=legacy`, and confirms `mobile-legacy` reads back the exact edit. + * + * `chromium-harness.mjs` owns the `affine-server` and Chromium process groups and the + * temporary work directory. A server behind `--base-url` is not owned. + */ + +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { createChromiumHarness, openPageTarget } from './chromium-harness.mjs'; +import { + listLegacyWorkspaceDatabases, + verifyLegacyWorkspaceReadiness, +} from './legacy-workspace-readiness.mjs'; +import { stageCanaryDualShell } from './stage-canary-dual-shell.mjs'; +import { verifyZeroThirdPartyJs } from './verify-zero-third-party-js.mjs'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const REPO_ROOT = resolve(WEB_ROOT, '../../../..'); +const MOBILE_UA = + 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36'; +const CRAWLER_UA = 'Twitterbot/1.0'; + +function parseCliArgs(argv) { + /** @type {Record} */ + const args = {}; + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i]; + if ( + token === '--out-dir' || + token === '--wasm-dir' || + token === '--legacy-dir' || + token === '--yjs-bundle' || + token === '--server-bin' || + token === '--database-url' || + token === '--base-url' || + token === '--public-doc-path' || + token === '--private-doc-path' || + token === '--expected-og-title' + ) { + const next = argv[i + 1]; + if (!next || next.startsWith('--')) { + throw new Error(`Missing value for ${token}`); + } + args[token.slice(2)] = next; + i += 1; + } else { + throw new Error(`Unknown argument: ${token}`); + } + } + return args; +} + +async function allocateFreePort() { + return new Promise((resolvePort, rejectPort) => { + const srv = createServer(); + srv.unref(); + srv.on('error', rejectPort); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + srv.close(err => { + if (err) rejectPort(err); + else resolvePort(port); + }); + }); + }); +} + +function resolveServerBin(explicitBin) { + const candidates = [ + explicitBin, + process.env.AFFINE_SERVER_BIN, + join(REPO_ROOT, 'packages/backend/target/debug/affine-server'), + join(REPO_ROOT, 'packages/backend/target/release/affine-server'), + ].filter(Boolean); + for (const bin of candidates) { + if (bin && existsSync(bin)) { + return resolve(bin); + } + } + throw new Error( + 'Missing affine-server binary. Build it in packages/backend or pass --server-bin .' + ); +} + +/** + * Connects to one CDP page target and returns helpers + network/CSP monitors. + * + * @param {string} wsUrl + */ +export async function connectCdpTarget(wsUrl) { + const ws = new WebSocket(wsUrl); + await new Promise((ok, fail) => { + ws.addEventListener('open', ok, { once: true }); + ws.addEventListener('error', fail, { once: true }); + }); + + let nextId = 1; + const pending = new Map(); + /** @type {Array<{ url: string, status: number, type: string }>} */ + const responses = []; + /** @type {Array<{ url: string, errorText: string }>} */ + const failedRequests = []; + /** @type {Array} */ + const consoleErrors = []; + /** @type {Map} */ + const requestUrls = new Map(); + + ws.addEventListener('message', ev => { + const msg = JSON.parse(String(ev.data)); + if (msg.id && pending.has(msg.id)) { + const { ok, fail } = pending.get(msg.id); + pending.delete(msg.id); + if (msg.error) fail(new Error(msg.error.message)); + else ok(msg.result); + return; + } + if (msg.method === 'Network.requestWillBeSent') { + requestUrls.set(msg.params.requestId, msg.params.request.url); + } else if (msg.method === 'Network.responseReceived') { + responses.push({ + url: msg.params.response.url, + status: msg.params.response.status, + type: msg.params.type || 'Other', + }); + } else if (msg.method === 'Network.loadingFailed') { + const url = requestUrls.get(msg.params.requestId) || 'unknown'; + if (!msg.params.canceled) { + failedRequests.push({ + url, + errorText: msg.params.errorText || 'loadingFailed', + }); + } + } else if ( + msg.method === 'Runtime.consoleAPICalled' && + msg.params.type === 'error' + ) { + const text = (msg.params.args || []) + .map(a => a.value ?? a.description ?? '') + .join(' '); + consoleErrors.push(text); + } else if ( + msg.method === 'Log.entryAdded' && + msg.params.entry?.level === 'error' + ) { + consoleErrors.push(msg.params.entry.text || 'log-error'); + } + }); + + ws.addEventListener('close', () => { + for (const entry of pending.values()) + entry.fail(new Error('CDP target closed')); + pending.clear(); + }); + + const send = (method, params = {}) => + new Promise((ok, fail) => { + const id = nextId++; + const timer = setTimeout(() => { + pending.delete(id); + fail(new Error(`CDP timeout after 25s for ${method}`)); + }, 25000); + pending.set(id, { + ok: val => { + clearTimeout(timer); + ok(val); + }, + fail: err => { + clearTimeout(timer); + fail(err); + }, + }); + ws.send(JSON.stringify({ id, method, params })); + }); + + const evalJs = async expression => { + const r = await send('Runtime.evaluate', { + expression, + awaitPromise: true, + returnByValue: true, + }); + if (r.exceptionDetails) { + throw new Error( + r.exceptionDetails.exception?.description || r.exceptionDetails.text + ); + } + return r.result?.value; + }; + + await send('Page.enable'); + await send('Network.enable'); + await send('Runtime.enable'); + await send('Log.enable'); + await send('Network.setUserAgentOverride', { userAgent: MOBILE_UA }); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, + height: 844, + deviceScaleFactor: 2, + mobile: true, + }); + await send('Page.addScriptToEvaluateOnNewDocument', { + source: ` + window.__S5_CSP_VIOLATIONS__ = []; + window.addEventListener('securitypolicyviolation', ev => { + window.__S5_CSP_VIOLATIONS__.push({ + blockedURI: ev.blockedURI, + violatedDirective: ev.violatedDirective, + effectiveDirective: ev.effectiveDirective, + }); + }); + `, + }); + + return { + ws, + send, + evalJs, + responses, + failedRequests, + consoleErrors, + close() { + try { + ws.close(); + } catch { + // Ignore close errors. + } + }, + }; +} + +export async function waitForCondition(evalJs, expr, timeoutMs = 15000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const val = await evalJs(expr); + if (val) { + return val; + } + } catch { + // Page may be mid-navigation. + } + await new Promise(r => setTimeout(r, 80)); + } + throw new Error(`Timed out waiting for condition: ${expr}`); +} + +// Hold the open success callback before the caller can request a transaction. +export function gateSaveConnections(count) { + const open = indexedDB.open.bind(indexedDB); + const resume = []; + let ready; + window.connectionsReady = new Promise(resolve => { + ready = resolve; + }); + window.releaseConnections = () => resume.forEach(release => release()); + indexedDB.open = (...args) => { + const req = open(...args); + req.addEventListener( + 'success', + event => { + event.stopImmediatePropagation(); + resume.push(() => req.onsuccess(event)); + if (resume.length === count) { + delete indexedDB.open; + ready(); + } + }, + { once: true } + ); + return req; + }; +} + +// Inspect one committed view before a native reader can compact the updates. +export async function readSavedWorkspace(wsId) { + const request = req => + new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const db = await request(indexedDB.open('local:workspace:' + wsId)); + try { + const tx = db.transaction(['updates', 'clocks', 'snapshots']); + const [updates, clocks, snapshots] = await Promise.all( + ['updates', 'clocks', 'snapshots'].map(name => + request(tx.objectStore(name).getAll()) + ) + ); + const Y = await import('/mobile-legacy/yjs.mjs'); + const root = new Y.Doc(); + for (const row of [...snapshots, ...updates]) { + if (row.docId === wsId) Y.applyUpdate(root, row.bin); + } + const meta = root.getMap('meta').toJSON(); + return { + catalog: (meta.pages || []).map(page => page.id), + meta, + updates: updates.map(row => [row.docId, row.createdAt.getTime()]), + clocks: clocks.map(row => [row.docId, row.timestamp.getTime()]), + }; + } finally { + db.close(); + } +} + +export function assertSaveClocks(saved, expectedCounts) { + assert.deepEqual( + saved.clocks.map(([id]) => id).sort(), + Object.keys(expectedCounts).sort() + ); + for (const [id, timestamp] of saved.clocks) { + const times = saved.updates + .filter(([key]) => key === id) + .map(row => row[1]); + assert.equal(times.length, expectedCounts[id]); + assert.ok(times.every((time, i) => time > (times[i - 1] || 0))); + assert.equal(timestamp, times.at(-1)); + } +} + +export function stageVerificationBundle(cli, outDir) { + const legacyDir = cli['legacy-dir']; + return stageCanaryDualShell({ + outDir, + wasmDir: cli['wasm-dir'], + legacyDir, + allowSyntheticLegacy: !legacyDir, + yjsBundle: cli['yjs-bundle'], + }); +} + +async function verify(cli, outDir, harness, openTabs) { + const staticRoot = join(harness.workTmp, 'static-root'); + const staged = stageVerificationBundle(cli, staticRoot); + const zeroThirdParty = verifyZeroThirdPartyJs({ stageDir: staged.mobileDir }); + assert.equal( + zeroThirdParty.ok, + true, + `Staged mobile shell failed zero-third-party-JS gate: ${zeroThirdParty.violations.join('; ')}` + ); + + // 2. Start real affine-server (--role front --deployment-mode cloud --channel canary) unless --base-url is given. + let baseUrl = typeof cli['base-url'] === 'string' ? cli['base-url'] : ''; + if (!baseUrl) { + const serverBin = resolveServerBin( + typeof cli['server-bin'] === 'string' ? cli['server-bin'] : null + ); + const databaseUrl = + (typeof cli['database-url'] === 'string' && cli['database-url']) || + process.env.DATABASE_URL || + process.env.AFFINE_TEST_PG_URL; + if (!databaseUrl) { + throw new Error( + 'Missing --database-url (or DATABASE_URL / AFFINE_TEST_PG_URL) for affine-server' + ); + } + const port = await allocateFreePort(); + baseUrl = `http://127.0.0.1:${port}`; + await harness.startServer({ + bin: serverBin, + args: [ + '--role', + 'front', + '--deployment-mode', + 'cloud', + '--channel', + 'canary', + '--host', + '127.0.0.1', + '--port', + String(port), + '--external-url', + baseUrl, + '--static-dir', + staticRoot, + '--database-url', + databaseUrl, + ], + baseUrl, + }); + } + + // 3. Launch real Headless Chromium (existing binary, never playwright install). + const debugPort = await harness.launchChromium(); + const openNewTab = async () => { + const target = await openPageTarget(debugPort); + const tab = await connectCdpTarget(target.webSocketDebuggerUrl); + openTabs.push(tab); + return tab; + }; + + if (cli['legacy-dir']) { + const tab = await openNewTab(); + const yjsModuleUrl = + typeof cli['yjs-bundle'] === 'string' + ? pathToFileURL(resolve(cli['yjs-bundle'])).href + : undefined; + const mounted = await verifyLegacyWorkspaceReadiness(tab, baseUrl, { + yjsModuleUrl, + }); + const initialDbs = await listLegacyWorkspaceDatabases(tab); + assert.ok( + initialDbs.length > 0, + 'Legacy shell mounted without any local:workspace:* database' + ); + + // Reopen the document deep link in a new tab of the same profile. The + // welcome template stays blocked, so the shell must load the workspace + // from the IndexedDB that the first launch wrote. + const reopenTab = await openNewTab(); + await reopenTab.send('Network.setBlockedURLs', { + urls: ['*onboarding*.zip*', '*welcome-template*'], + }); + const reopened = await verifyLegacyWorkspaceReadiness(reopenTab, baseUrl, { + mode: 'reopen', + expectedWsId: mounted.wsId, + expectedDocId: mounted.docId, + expectedWorkspaceDbCount: initialDbs.length, + yjsModuleUrl, + }); + if (outDir) { + const shot = await reopenTab.send('Page.captureScreenshot', { + format: 'png', + }); + writeFileSync( + join(outDir, 'legacy-shell.png'), + Buffer.from(shot.data, 'base64') + ); + } + console.log( + 'The supplied mobile bundle mounted on the legacy route:', + JSON.stringify({ + wsId: mounted.wsId, + docId: mounted.docId, + pathname: mounted.pathname, + navigatedFromHome: mounted.navigatedFromHome, + reopened: { + pathname: reopened.pathname, + workspaceDbNames: reopened.workspaceDbNames, + }, + }) + ); + return; + } + const Y = await import( + pathToFileURL(join(staged.mobileLegacyDir, 'yjs.mjs')).href + ); + + // --- Scenario A: Same-origin Dual-Tab (Tab A = native, Tab B = mobile-legacy) --- + const tabA = await openNewTab(); + await tabA.send('Page.navigate', { url: `${baseUrl}/` }); + await waitForCondition( + tabA.evalJs, + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.selectionOverlay && !document.getElementById("boot"))' + ); + const tabAInfo = await tabA.evalJs(`(() => { + const h = window.__AFFINE_WEB_HOST__; + return { + shellBuildId: h.workerLoader.manifest.shell_build_id, + assetBaseUrl: h.workerLoader.assetBaseUrl, + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + }; + })()`); + assert.equal(tabAInfo.shellBuildId, staged.shellBuildId); + assert.equal(tabAInfo.assetBaseUrl, '/mobile/'); + assert.equal(tabAInfo.cspViolationCount, 0); + + // Paint a clear status card onto Tab A canvas for visual evidence. + await tabA.evalJs(`(() => { + const h = window.__AFFINE_WEB_HOST__; + h.selectionOverlay.setScene({ + theme: 'light', + selection: null, + paint(ctx, vw, vh) { + ctx.fillStyle = '#f8fafc'; + ctx.fillRect(0, 0, vw, vh); + ctx.fillStyle = '#0f172a'; + ctx.fillRect(0, 0, vw, 88); + ctx.fillStyle = '#ffffff'; + ctx.font = '700 18px -apple-system, sans-serif'; + ctx.fillText('AFFiNE Canary Native Shell', 20, 56); + ctx.fillStyle = '#ffffff'; + ctx.beginPath(); + ctx.roundRect(18, 112, vw - 36, 180, 14); + ctx.fill(); + ctx.fillStyle = '#0f172a'; + ctx.font = '600 15px -apple-system, sans-serif'; + ctx.fillText('Tab A: Native Mobile Host', 34, 148); + ctx.fillStyle = '#475569'; + ctx.font = '400 13px -apple-system, sans-serif'; + ctx.fillText('shell_build_id: ' + h.workerLoader.manifest.shell_build_id, 34, 182); + ctx.fillText('assetBaseUrl: ' + h.workerLoader.assetBaseUrl, 34, 208); + ctx.fillText('Status: 0 404s, 0 CSP violations', 34, 234); + }, + }); + })()`); + if (outDir) { + const shot = await tabA.send('Page.captureScreenshot', { format: 'png' }); + writeFileSync( + join(outDir, 'canary-tab-a-native.png'), + Buffer.from(shot.data, 'base64') + ); + } + + // Open Tab B on the SAME ORIGIN with ?shell=legacy (flips affine_shell=legacy cookie!). + const tabB = await openNewTab(); + await tabB.send('Page.navigate', { url: `${baseUrl}/?shell=legacy` }); + await waitForCondition( + tabB.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)' + ); + const tabBInfo = await tabB.evalJs(`({ + shell: window.__AFFINE_LEGACY_SHELL__.shell, + buildId: window.__AFFINE_LEGACY_SHELL__.buildId, + cookie: document.cookie, + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + })`); + assert.equal(tabBInfo.shell, 'legacy'); + assert.ok( + tabBInfo.cookie.includes('affine_shell=legacy'), + `Expected affine_shell=legacy cookie, got: ${tabBInfo.cookie}` + ); + assert.equal(tabBInfo.cspViolationCount, 0); + if (outDir) { + const shot = await tabB.send('Page.captureScreenshot', { format: 'png' }); + writeFileSync( + join(outDir, 'canary-tab-b-legacy.png'), + Buffer.from(shot.data, 'base64') + ); + } + + // Now with affine_shell=legacy active in the shared cookie jar, Tab A lazily fetches + // its pinned font, worker wasm, and main pkg wasm — MUST all return 200 with real compiled Wasm bytes (> 10 KB) and zero cross-shell leakage! + const tabALazyFetch = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + const cookieSeenByTabA = document.cookie; + const fontBuf = await h.workerLoader.loadFont('latin'); + const pdfAssets = h.workerLoader.resolveWorkerAssets('pdf'); + const wasmResp = await fetch(pdfAssets.wasm, { credentials: 'same-origin' }); + const wasmBytes = (await wasmResp.arrayBuffer()).byteLength; + const directWasmResp = await fetch('/wasm/pdf-worker.' + h.workerLoader.manifest.shell_build_id + '.wasm', { credentials: 'same-origin' }); + const directWasmBytes = (await directWasmResp.arrayBuffer()).byteLength; + const pkgResp = await fetch('/pkg/playground_bg.wasm', { credentials: 'same-origin' }); + const pkgBytes = (await pkgResp.arrayBuffer()).byteLength; + return { + cookieSeenByTabA, + fontBytes: fontBuf.byteLength, + wasmUrl: pdfAssets.wasm, + wasmStatus: wasmResp.status, + wasmBytes, + wasmContentType: wasmResp.headers.get('content-type'), + directWasmStatus: directWasmResp.status, + directWasmBytes, + pkgStatus: pkgResp.status, + pkgBytes, + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + }; + })()`); + assert.ok( + tabALazyFetch.cookieSeenByTabA.includes('affine_shell=legacy'), + 'Tab A must share the same-origin cookie jar with Tab B' + ); + assert.ok(tabALazyFetch.fontBytes > 1000, 'Lazy font fetch must succeed'); + assert.equal(tabALazyFetch.wasmStatus, 200); + assert.ok( + tabALazyFetch.wasmBytes > 10 * 1024, + `Expected real compiled pdf-worker wasm (> 10 KB), got ${tabALazyFetch.wasmBytes}` + ); + assert.equal(tabALazyFetch.wasmContentType, 'application/wasm'); + assert.equal(tabALazyFetch.directWasmStatus, 200); + assert.ok(tabALazyFetch.directWasmBytes > 10 * 1024); + assert.equal(tabALazyFetch.pkgStatus, 200); + assert.ok( + tabALazyFetch.pkgBytes > 10 * 1024, + `Expected real compiled playground_bg.wasm (> 10 KB), got ${tabALazyFetch.pkgBytes}` + ); + assert.equal(tabALazyFetch.cspViolationCount, 0); + + const tabA404s = tabA.responses.filter(r => r.status >= 400); + const tabB404s = tabB.responses.filter(r => r.status >= 400); + assert.deepEqual( + tabA404s, + [], + `Tab A had HTTP >=400 responses: ${JSON.stringify(tabA404s)}` + ); + assert.deepEqual( + tabB404s, + [], + `Tab B had HTTP >=400 responses: ${JSON.stringify(tabB404s)}` + ); + assert.deepEqual(tabA.failedRequests, []); + assert.deepEqual(tabB.failedRequests, []); + + // Verify zero cross-shell asset leakage: Tab A never loaded /mobile-legacy/*, Tab B never loaded /mobile/*. + assert.equal( + tabA.responses.some(r => + new URL(r.url).pathname.startsWith('/mobile-legacy/') + ), + false, + 'Tab A (native) must never receive /mobile-legacy/* assets' + ); + assert.equal( + tabB.responses.some(r => new URL(r.url).pathname.startsWith('/mobile/')), + false, + 'Tab B (legacy) must never receive /mobile/* assets' + ); + + // --- Scenario B: Auth routes (/sign-in, /magic-link, /oauth/callback) & strict CSP --- + for (const authPath of ['/sign-in', '/magic-link', '/oauth/callback']) { + const authRes = await fetch(`${baseUrl}${authPath}`, { + headers: { + 'user-agent': MOBILE_UA, + cookie: 'affine_shell=native', + }, + }); + assert.equal(authRes.status, 200, `${authPath} must return 200`); + const html = await authRes.text(); + assert.ok( + html.includes('id="auth-card"'), + `${authPath} must serve mobile sign-in.html` + ); + assert.ok( + html.includes('/mobile/src/sign-in.js'), + `${authPath} must load cookie-immune /mobile/src/sign-in.js` + ); + assert.ok( + html.includes('https://challenges.cloudflare.com'), + `${authPath} CSP allows Turnstile isolation` + ); + } + const mainIndexRes = await fetch(`${baseUrl}/?shell=native`, { + headers: { 'user-agent': MOBILE_UA }, + }); + const mainIndexHtml = await mainIndexRes.text(); + assert.equal( + mainIndexHtml.includes('challenges.cloudflare.com'), + false, + 'Main mobile shell CSP must never include Turnstile domain' + ); + + // --- Scenario C: Public share / crawler SSR OpenGraph verification --- + const publicDocPath = + typeof cli['public-doc-path'] === 'string' + ? cli['public-doc-path'] + : '/workspace/ws-og/doc-public'; + const privateDocPath = + typeof cli['private-doc-path'] === 'string' + ? cli['private-doc-path'] + : '/workspace/ws-og/doc-private'; + const expectedOgTitle = + typeof cli['expected-og-title'] === 'string' + ? cli['expected-og-title'] + : ''; + + const crawlerResp = await fetch(`${baseUrl}${publicDocPath}`, { + headers: { 'user-agent': CRAWLER_UA, accept: 'text/html' }, + }); + assert.equal(crawlerResp.status, 200); + const crawlerHtml = await crawlerResp.text(); + assert.ok(crawlerHtml.includes('property="og:title"'), 'Missing og:title'); + assert.ok( + crawlerHtml.includes('property="og:description"'), + 'Missing og:description' + ); + assert.ok(crawlerHtml.includes('property="og:image"'), 'Missing og:image'); + if (expectedOgTitle) { + assert.ok( + crawlerHtml.includes(expectedOgTitle), + `Expected crawler OG HTML to contain "${expectedOgTitle}"` + ); + assert.equal( + crawlerResp.headers.get('x-robots-tag'), + null, + 'Public doc must be indexable (no x-robots-tag: noindex)' + ); + } + + const mobileDocResp = await fetch(`${baseUrl}${publicDocPath}`, { + headers: { 'user-agent': MOBILE_UA, accept: 'text/html' }, + }); + assert.equal(mobileDocResp.status, 200); + const mobileDocHtml = await mobileDocResp.text(); + assert.ok( + mobileDocHtml.includes('property="og:title"'), + 'Mobile SSR doc response must retain og:title' + ); + assert.ok( + mobileDocHtml.includes('id="app-canvas"'), + 'Mobile SSR doc response must retain native shell #app-canvas' + ); + assert.ok( + mobileDocHtml.includes('/mobile/src/host.js'), + 'Mobile SSR doc response must retain cookie-immune /mobile/src/host.js' + ); + if (expectedOgTitle) { + assert.ok( + mobileDocHtml.includes(expectedOgTitle), + `Mobile SSR doc response must contain "${expectedOgTitle}"` + ); + } + + const privResp = await fetch(`${baseUrl}${privateDocPath}`, { + headers: { 'user-agent': CRAWLER_UA, accept: 'text/html' }, + }); + assert.equal(privResp.status, 200); + assert.equal(privResp.headers.get('x-robots-tag'), 'noindex'); + const privHtml = await privResp.text(); + assert.ok(privHtml.includes('noindex, nofollow')); + + // --- Scenario D: Double WebGPU Crash Circuit Breaker + IDB Flush Barrier + Legacy Takeover --- + const gpuTab = await openNewTab(); + await gpuTab.send('Page.navigate', { + url: `${baseUrl}/?shell=native&workspace=canary-gpu-ws`, + }); + await waitForCondition( + gpuTab.evalJs, + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.selectionOverlay && !document.getElementById("boot"))' + ); + + // Set up workspace IDB + enqueue a REAL Yjs V1 CRDT update created by real `yjs`: + // Page -> [Note 1 (Para A -> Nested Child Para B), Hidden Edgeless Note (excluded), Note 2 (Para C)] + // + verify flush-failure abort + inject crash #1 in-place recovery. + const note1ParaA = 'CANARY-NOTE1-PARA-A'; + const nestedChildB = 'CANARY-NESTED-CHILD-B'; + const hiddenEdgelessText = 'EDGELESS-ONLY-HIDDEN'; + const note2ParaC = 'CANARY-NOTE2-PARA-C'; + const legacyEdit2Text = 'CANARY-CRDT-EDIT-2-LEGACY-UI'; + const legacyEdit3Text = 'CANARY-CRDT-EDIT-3-AFTER-RELOAD-UI'; + const nativeDoc = new Y.Doc(); + nativeDoc.transact(() => { + const blocks = nativeDoc.getMap('blocks'); + const makePara = (id, text, children = []) => { + const para = new Y.Map(); + para.set('sys:id', id); + para.set('sys:flavour', 'affine:paragraph'); + para.set('prop:type', 'text'); + const yText = new Y.Text(); + yText.insert(0, text); + para.set('prop:text', yText); + if (children.length > 0) { + const ch = new Y.Array(); + ch.push(children); + para.set('sys:children', ch); + } + blocks.set(id, para); + }; + + const page = new Y.Map(); + page.set('sys:id', 'page-s5'); + page.set('sys:flavour', 'affine:page'); + const pageChildren = new Y.Array(); + pageChildren.push(['note-1', 'note-hidden', 'note-2']); + page.set('sys:children', pageChildren); + blocks.set('page-s5', page); + + const note1 = new Y.Map(); + note1.set('sys:id', 'note-1'); + note1.set('sys:flavour', 'affine:note'); + const note1Children = new Y.Array(); + note1Children.push(['para-a']); + note1.set('sys:children', note1Children); + blocks.set('note-1', note1); + makePara('para-a', note1ParaA, ['para-b']); + makePara('para-b', nestedChildB); + + const hiddenNote = new Y.Map(); + hiddenNote.set('sys:id', 'note-hidden'); + hiddenNote.set('sys:flavour', 'affine:note'); + hiddenNote.set('prop:hidden', true); + const hiddenChildren = new Y.Array(); + hiddenChildren.push(['para-hidden']); + hiddenNote.set('sys:children', hiddenChildren); + blocks.set('note-hidden', hiddenNote); + makePara('para-hidden', hiddenEdgelessText); + + const note2 = new Y.Map(); + note2.set('sys:id', 'note-2'); + note2.set('sys:flavour', 'affine:note'); + const note2Children = new Y.Array(); + note2Children.push(['para-c']); + note2.set('sys:children', note2Children); + blocks.set('note-2', note2); + makePara('para-c', note2ParaC); + }); + const realYjsV1Edit1 = Array.from(Y.encodeStateAsUpdate(nativeDoc)); + const crash1Result = await gpuTab.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ flavour: 'local', type: 'workspace', id: 'canary-gpu-ws' }); + const yjsV1Update = new Uint8Array(${JSON.stringify(realYjsV1Edit1)}); + h.pendingWrites.enqueue({ + docId: 'doc-canary-crash', + bin: yjsV1Update, + }); + + // Verify flushPendingBeforeRedirect aborts on flush failure without losing pending writes. + const { flushPendingBeforeRedirect } = await import('/mobile/src/host.js'); + let abortedNavCalled = false; + const abortCheck = await flushPendingBeforeRedirect({ + pauseInput: () => {}, + flushPendingWrites: async () => { + throw new Error('simulated-idb-lock'); + }, + navigate: () => { + abortedNavCalled = true; + }, + resumeInput: () => {}, + targetUrl: '/?shell=legacy', + }); + + // Wire controllable WebGPU devices (device1 -> crash #1 rebuilds device2 -> crash #2 trips circuit breaker). + const makeFakeDevice = name => { + let resolveLost; + const lost = new Promise(r => { resolveLost = r; }); + const listeners = new Map(); + return { + name, + lost, + addEventListener(type, fn) { + if (!listeners.has(type)) listeners.set(type, []); + listeners.get(type).push(fn); + }, + triggerLost(reason) { + resolveLost({ reason }); + }, + triggerUncapturedError(message) { + for (const fn of listeners.get('uncapturederror') || []) { + fn({ error: { message } }); + } + }, + }; + }; + + const dev1 = makeFakeDevice('gpu-dev-1'); + const dev2 = makeFakeDevice('gpu-dev-2'); + window.__S5_GPU_DEV2__ = dev2; + let rebuildCount = 0; + + const deviceOpts = { + tryRebuildWebGpu: async () => { + rebuildCount += 1; + h.bindWebGpuDevice(dev2, deviceOpts); + h.selectionOverlay.setScene({ + theme: 'light', + selection: null, + paint(ctx, vw, vh) { + ctx.fillStyle = '#ecfdf5'; + ctx.fillRect(0, 0, vw, vh); + ctx.fillStyle = '#065f46'; + ctx.fillRect(0, 0, vw, 88); + ctx.fillStyle = '#ffffff'; + ctx.font = '700 18px -apple-system, sans-serif'; + ctx.fillText('WebGPU Crash #1 Recovered', 20, 56); + ctx.fillStyle = '#064e3b'; + ctx.font = '600 15px -apple-system, sans-serif'; + ctx.fillText('In-place GPU rebuild succeeded', 24, 140); + ctx.font = '400 13px -apple-system, sans-serif'; + ctx.fillText('shell_build_id: ' + h.workerLoader.manifest.shell_build_id, 24, 170); + ctx.fillText('Pending Yjs V1 CRDT edit buffered: ' + h.pendingWrites.pendingCount(), 24, 198); + ctx.fillText('Next crash trips flush + legacy takeover', 24, 226); + }, + }); + return true; + }, + }; + h.bindWebGpuDevice(dev1, deviceOpts); + + // Inject WebGPU crash #1 (device.lost). + dev1.triggerLost('destroyed'); + await new Promise(r => setTimeout(r, 80)); + + return { + abortCheck, + abortedNavCalled, + rebuildCount, + pendingAfterCrash1: h.pendingWrites.pendingCount(), + stateAfterCrash1: h.gpuRecovery.getState(), + hrefAfterCrash1: window.location.href, + }; + })()`); + + assert.equal(crash1Result.abortCheck.navigated, false); + assert.equal(crash1Result.abortedNavCalled, false); + assert.equal(crash1Result.rebuildCount, 1); + assert.equal(crash1Result.pendingAfterCrash1, 1); + assert.equal(crash1Result.stateAfterCrash1.status, 'ready'); + assert.equal(crash1Result.stateAfterCrash1.webGpuLossCount, 1); + assert.equal(crash1Result.stateAfterCrash1.restoreCount, 1); + assert.ok( + crash1Result.hrefAfterCrash1.includes('shell=native'), + 'Crash #1 must recover in-place on native shell' + ); + + if (outDir) { + const shot = await gpuTab.send('Page.captureScreenshot', { format: 'png' }); + writeFileSync( + join(outDir, 'canary-gpu-crash1-recovered.png'), + Buffer.from(shot.data, 'base64') + ); + } + + // Inject WebGPU crash #2 (uncapturederror on rebuilt device2) -> flushes IDB -> navigates to ?shell=legacy! + await gpuTab.evalJs(`(() => { + window.__S5_GPU_DEV2__.triggerUncapturedError('gpu-device-fatal-crash-2'); + return true; + })()`); + + await waitForCondition( + gpuTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const crash2Takeover = await gpuTab.evalJs(`({ + href: window.location.href, + cookie: document.cookie, + legacyState: window.__AFFINE_LEGACY_SHELL__, + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + })`); + + assert.ok( + crash2Takeover.href.includes('shell=legacy'), + `Expected redirect to ?shell=legacy, got ${crash2Takeover.href}` + ); + assert.ok( + crash2Takeover.cookie.includes('affine_shell=legacy'), + 'Expected affine_shell=legacy cookie after takeover' + ); + assert.equal( + crash2Takeover.legacyState.fallbackReason, + 'webgpu-crash-threshold' + ); + assert.equal(crash2Takeover.cspViolationCount, 0); + const initialRecoveredDoc = crash2Takeover.legacyState.recoveredDocs.find( + d => d.docId === 'doc-canary-crash' + ); + assert.ok( + initialRecoveredDoc && + initialRecoveredDoc.flavours.includes('affine:page') && + initialRecoveredDoc.flavours.includes('affine:note') && + initialRecoveredDoc.flavours.includes('affine:paragraph'), + `Expected mobile-legacy to decode real Yjs V1 BlockSuite blocks from IndexedDB, got: ${JSON.stringify(crash2Takeover.legacyState.recoveredDocs)}` + ); + assert.deepEqual( + initialRecoveredDoc.paragraphs, + [note1ParaA, nestedChildB, note2ParaC], + 'Legacy shell must walk all visible Notes and nested sys:children while excluding hidden edgeless Notes' + ); + const initialDomText = await gpuTab.evalJs( + `document.getElementById('legacy-recovered-doc')?.textContent || ''` + ); + assert.ok(initialDomText.includes(note1ParaA)); + assert.ok(initialDomText.includes(nestedChildB)); + assert.ok(initialDomText.includes(note2ParaC)); + assert.equal(initialDomText.includes(hiddenEdgelessText), false); + + /** + * Drives the real visible legacy UI controls (`#legacy-editor-input` + + * `#legacy-append-btn`) via real Chromium CDP keyboard input and mouse click. + * + * @param {string} text + */ + const appendViaRealLegacyUi = async text => { + const inputCenter = await gpuTab.evalJs(`(() => { + const input = document.getElementById('legacy-editor-input'); + if (!input) throw new Error('Missing #legacy-editor-input'); + input.scrollIntoView({ block: 'center' }); + input.focus(); + input.value = ''; + const r = input.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await gpuTab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: inputCenter.x, + y: inputCenter.y, + button: 'left', + clickCount: 1, + }); + await gpuTab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: inputCenter.x, + y: inputCenter.y, + button: 'left', + clickCount: 1, + }); + await gpuTab.send('Input.insertText', { text }); + + const btnCenter = await gpuTab.evalJs(`(() => { + const btn = document.getElementById('legacy-append-btn'); + if (!btn) throw new Error('Missing #legacy-append-btn'); + btn.scrollIntoView({ block: 'center' }); + const r = btn.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await gpuTab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: btnCenter.x, + y: btnCenter.y, + button: 'left', + clickCount: 1, + }); + await gpuTab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: btnCenter.x, + y: btnCenter.y, + button: 'left', + clickCount: 1, + }); + + await waitForCondition( + gpuTab.evalJs, + `(document.getElementById('legacy-recovered-doc')?.textContent || '').includes(${JSON.stringify(text)})`, + 15000 + ); + return gpuTab.evalJs(`({ + clientID: window.__AFFINE_LEGACY_SHELL__?.lastEditClientID ?? null, + domText: document.getElementById('legacy-recovered-doc')?.textContent || '', + editorStatus: document.getElementById('legacy-editor-status')?.textContent || '', + })`); + }; + + // Edit #2 via real UI input + click -> reload page -> Edit #3 via real UI input + click -> reload again! + const legacyEdit2Ui = await appendViaRealLegacyUi(legacyEdit2Text); + assert.ok(legacyEdit2Ui.clientID !== null); + assert.ok(legacyEdit2Ui.domText.includes(legacyEdit2Text)); + + await gpuTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + gpuTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const afterReload1 = await gpuTab.evalJs(`({ + legacyState: window.__AFFINE_LEGACY_SHELL__, + domText: document.getElementById('legacy-recovered-doc')?.textContent || '', + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + })`); + assert.equal(afterReload1.cspViolationCount, 0); + const docAfterReload1 = afterReload1.legacyState.recoveredDocs.find( + d => d.docId === 'doc-canary-crash' + ); + assert.deepEqual(docAfterReload1?.paragraphs, [ + note1ParaA, + nestedChildB, + note2ParaC, + legacyEdit2Text, + ]); + assert.ok(afterReload1.domText.includes(legacyEdit2Text)); + + // Edit #3 after reload via real UI input + click (must allocate a fresh random Y.Doc clientID!). + const legacyEdit3Ui = await appendViaRealLegacyUi(legacyEdit3Text); + assert.ok(legacyEdit3Ui.clientID !== null); + assert.notEqual( + legacyEdit3Ui.clientID, + legacyEdit2Ui.clientID, + 'Reloaded legacy Y.Doc must allocate a fresh random clientID (no clock=0 collision)' + ); + assert.ok(legacyEdit3Ui.domText.includes(legacyEdit3Text)); + + await gpuTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + gpuTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const afterReloadTakeover = await gpuTab.evalJs(`({ + legacyState: window.__AFFINE_LEGACY_SHELL__, + domText: document.getElementById('legacy-recovered-doc')?.textContent || '', + cspViolationCount: (window.__S5_CSP_VIOLATIONS__ || []).length, + })`); + assert.equal(afterReloadTakeover.cspViolationCount, 0); + const persistedDoc = afterReloadTakeover.legacyState.recoveredDocs.find( + d => d.docId === 'doc-canary-crash' + ); + assert.ok( + persistedDoc && persistedDoc.updateCount >= 3, + `Expected >= 3 Yjs updates persisted across reloads, got: ${JSON.stringify(afterReloadTakeover.legacyState.recoveredDocs)}` + ); + const expectedAllParagraphs = [ + note1ParaA, + nestedChildB, + note2ParaC, + legacyEdit2Text, + legacyEdit3Text, + ]; + assert.deepEqual(persistedDoc.paragraphs, expectedAllParagraphs); + for (const line of expectedAllParagraphs) { + assert.ok( + afterReloadTakeover.domText.includes(line), + `Visible #legacy-recovered-doc must include "${line}" after reload` + ); + } + assert.equal(afterReloadTakeover.domText.includes(hiddenEdgelessText), false); + + // Verify the REAL compiled playground Wasm (`merge_updates_v1`) in Tab A merges ALL 3 Yjs V1 updates cleanly, + // then load the Wasm-merged binary into an independent Node `Y.Doc` and recursively walk + // `Page -> visible Notes -> sys:children -> nested Paragraphs` to confirm all 5 paragraphs survive in order! + const wasmMergeCheck = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ flavour: 'local', type: 'workspace', id: 'canary-gpu-ws' }); + const raw = await h.workspaceStorage.getDocRaw('doc-canary-crash'); + const merged = await h.workspaceStorage.getDoc('doc-canary-crash'); + return { + rawUpdatesCount: raw ? raw.updates.length : 0, + mergedBytes: merged && merged.bin ? Array.from(merged.bin) : [], + }; + })()`); + assert.equal(wasmMergeCheck.rawUpdatesCount, 3); + assert.ok( + wasmMergeCheck.mergedBytes.length > 80, + `Expected real playground Wasm merge_updates_v1 to produce a valid merged Yjs V1 snapshot` + ); + const verifyDoc = new Y.Doc(); + Y.applyUpdate(verifyDoc, new Uint8Array(wasmMergeCheck.mergedBytes)); + const vBlocks = verifyDoc.getMap('blocks'); + const vPage = vBlocks.get('page-s5'); + assert.equal(vPage?.get('sys:flavour'), 'affine:page'); + const vPageChildren = vPage?.get('sys:children')?.toArray() || []; + assert.deepEqual(vPageChildren, ['note-1', 'note-hidden', 'note-2']); + /** @type {string[]} */ + const vParagraphs = []; + const walkVerify = parentId => { + const parent = vBlocks.get(parentId); + const children = parent?.get('sys:children')?.toArray() || []; + for (const cid of children) { + const child = vBlocks.get(cid); + const text = child?.get('prop:text'); + if (text) { + vParagraphs.push(text.toString()); + } + walkVerify(cid); + } + }; + const visibleNoteIds = []; + for (const nid of vPageChildren) { + const note = vBlocks.get(nid); + if ( + note?.get('sys:flavour') === 'affine:note' && + note?.get('prop:hidden') !== true + ) { + visibleNoteIds.push(nid); + walkVerify(nid); + } + } + assert.deepEqual(visibleNoteIds, ['note-1', 'note-2']); + assert.deepEqual(vParagraphs, expectedAllParagraphs); + const mergedByteLength = wasmMergeCheck.mergedBytes.length; + + const gpuTab404s = gpuTab.responses.filter(r => r.status >= 400); + assert.deepEqual( + gpuTab404s, + [], + `GPU crash tab had HTTP >=400 responses: ${JSON.stringify(gpuTab404s)}` + ); + + if (outDir) { + const shot = await gpuTab.send('Page.captureScreenshot', { format: 'png' }); + writeFileSync( + join(outDir, 'canary-gpu-crash2-legacy-takeover.png'), + Buffer.from(shot.data, 'base64') + ); + } + + // --- Scenario E: Multi-doc route targeting (/workspace/local/z-active) + at placeholder and disable append button. + const multiDocTab = await openNewTab(); + await multiDocTab.send('Page.navigate', { + url: `${baseUrl}/?shell=legacy&workspace=local`, + }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const ambiguousState = await multiDocTab.evalJs(`({ + selectValue: document.getElementById('legacy-target-doc')?.value ?? null, + btnDisabled: document.getElementById('legacy-append-btn')?.disabled ?? null, + selectedTarget: window.__AFFINE_LEGACY_SHELL__?.selectedTarget ?? null, + })`); + assert.equal(ambiguousState.selectValue, ''); + assert.equal(ambiguousState.btnDisabled, true); + assert.equal(ambiguousState.selectedTarget, null); + + // 2. Explicit route `/workspace/local/z-active?shell=legacy&workspace=local` must target `z-active` + // and leave `a-other` untouched across real UI input + button click + reload! + await multiDocTab.send('Page.navigate', { + url: `${baseUrl}/workspace/local/z-active?shell=legacy&workspace=local`, + }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const targetedState = await multiDocTab.evalJs(`({ + selectedTarget: window.__AFFINE_LEGACY_SHELL__?.selectedTarget ?? null, + btnDisabled: document.getElementById('legacy-append-btn')?.disabled ?? null, + })`); + assert.deepEqual(targetedState.selectedTarget, { + dbName: 'local:workspace:local', + docId: 'z-active', + }); + assert.equal(targetedState.btnDisabled, false); + + const appendViaLegacyTab = async (tab, text) => { + const inputCenter = await tab.evalJs(`(() => { + const input = document.getElementById('legacy-editor-input'); + input.scrollIntoView({ block: 'center' }); + input.focus(); + input.value = ''; + const r = input.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await tab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: inputCenter.x, + y: inputCenter.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: inputCenter.x, + y: inputCenter.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.insertText', { text }); + + const btnCenter = await tab.evalJs(`(() => { + const btn = document.getElementById('legacy-append-btn'); + btn.scrollIntoView({ block: 'center' }); + const r = btn.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await tab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: btnCenter.x, + y: btnCenter.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: btnCenter.x, + y: btnCenter.y, + button: 'left', + clickCount: 1, + }); + await waitForCondition( + tab.evalJs, + `(document.getElementById('legacy-recovered-doc')?.textContent || '').includes(${JSON.stringify(text)})`, + 15000 + ); + }; + + await appendViaLegacyTab(multiDocTab, 'MARK-FOR-ACTIVE'); + + await multiDocTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const multiDocAfterReload = await multiDocTab.evalJs( + 'window.__AFFINE_LEGACY_SHELL__.recoveredDocs' + ); + const docAOther = multiDocAfterReload.find(d => d.docId === 'a-other'); + const docZActive = multiDocAfterReload.find(d => d.docId === 'z-active'); + assert.deepEqual(docAOther?.paragraphs, ['A-OTHER-ORIGINAL']); + assert.deepEqual(docZActive?.paragraphs, [ + 'Z-ACTIVE-ORIGINAL', + 'MARK-FOR-ACTIVE', + ]); + + // --- Scenario F: Brand-new workspace created in mobile-legacy -> real click on "Return to Native Shell" --- + const freshWsId = 'canary-fresh-legacy-ws'; + const freshDocId = 'doc-fresh-first'; + const freshParaText = 'FRESH-WORKSPACE-FIRST-PARA'; + const freshTab = await openNewTab(); + await freshTab.send('Page.navigate', { + url: `${baseUrl}/workspace/${freshWsId}/${freshDocId}?shell=legacy&workspace=${freshWsId}`, + }); + await waitForCondition( + freshTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const freshTarget = await freshTab.evalJs(`({ + selectedTarget: window.__AFFINE_LEGACY_SHELL__?.selectedTarget ?? null, + btnDisabled: document.getElementById('legacy-append-btn')?.disabled ?? null, + })`); + assert.deepEqual(freshTarget.selectedTarget, { + dbName: `local:workspace:${freshWsId}`, + docId: freshDocId, + }); + assert.equal(freshTarget.btnDisabled, false); + await appendViaLegacyTab(freshTab, freshParaText); + + // Verify cold workspace registration in localStorage['affine-local-workspace'] and dynamic Return link href. + const freshPreReturn = await freshTab.evalJs(`({ + localWorkspaces: JSON.parse(window.localStorage.getItem('affine-local-workspace') || '[]'), + returnHref: document.querySelector('a.switch-link')?.getAttribute('href') || '', + })`); + assert.ok( + Array.isArray(freshPreReturn.localWorkspaces) && + freshPreReturn.localWorkspaces.includes(freshWsId), + `Expected affine-local-workspace to register ${freshWsId}, got ${JSON.stringify(freshPreReturn.localWorkspaces)}` + ); + assert.ok( + freshPreReturn.returnHref.includes('shell=native') && + freshPreReturn.returnHref.includes(`workspace=${freshWsId}`) && + freshPreReturn.returnHref.includes(`doc=${freshDocId}`), + `Expected Return to Native Shell link to carry workspace & doc params, got ${freshPreReturn.returnHref}` + ); + + // Real user click on the visible "Return to Native Shell" link (no manual URL navigate or attachWorkspace cheating!). + const returnLinkCenter = await freshTab.evalJs(`(() => { + const link = document.querySelector('a.switch-link'); + if (!link) throw new Error('Missing a.switch-link'); + link.scrollIntoView({ block: 'center' }); + const r = link.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await freshTab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: returnLinkCenter.x, + y: returnLinkCenter.y, + button: 'left', + clickCount: 1, + }); + await freshTab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: returnLinkCenter.x, + y: returnLinkCenter.y, + button: 'left', + clickCount: 1, + }); + + await waitForCondition( + freshTab.evalJs, + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.selectionOverlay && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))', + 15000 + ); + const doc1Shot = await freshTab.send('Page.captureScreenshot', { + format: 'png', + }); + const freshNativeVerify = await freshTab.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + const { IDB_SCHEMA_VERSION, IDB_STORE_NAMES, openWorkspaceIdb } = + await import('/mobile/src/idb-storage.js'); + const db = await openWorkspaceIdb({ + flavour: 'local', + type: 'workspace', + id: ${JSON.stringify(freshWsId)}, + }); + const storeNames = Array.from(db.objectStoreNames).sort(); + const expectedStores = [...IDB_STORE_NAMES].sort(); + const version = db.version; + // Exercise a readwrite transaction spanning all 12 stores (catches any NotFoundError). + await new Promise((resolve, reject) => { + const tx = db.transaction(expectedStores, 'readwrite'); + tx.objectStore('indexerMetadata').put({ key: 'schema-probe', value: 1 }); + tx.objectStore('snapshots').get(${JSON.stringify(freshDocId)}); + tx.oncomplete = resolve; + tx.onerror = () => reject(tx.error || new Error('12-store tx failed')); + tx.onabort = () => reject(tx.error || new Error('12-store tx aborted')); + }); + const probeVal = await new Promise((resolve, reject) => { + const tx = db.transaction(['indexerMetadata'], 'readonly'); + const req = tx.objectStore('indexerMetadata').get('schema-probe'); + req.onsuccess = () => resolve(req.result?.value ?? null); + req.onerror = () => reject(req.error || new Error('probe read failed')); + }); + db.close(); + + const initialSnap = h.activeDocSession.getSnapshot(); + await h.activeDocSession.appendParagraph('NATIVE-CONTINUED-EDIT-PARA'); + const rootDocData = await h.workspaceStorage.getDoc(${JSON.stringify(freshWsId)}); + return { + href: window.location.href, + autoWorkspaceId: h.activeWorkspace?.id ?? null, + autoDocId: h.activeDocId ?? null, + registeredLocalWorkspaces: h.getLocalWorkspaceIds(), + version, + expectedVersion: IDB_SCHEMA_VERSION, + storeNames, + expectedStores, + probeVal, + initialParagraphs: initialSnap.paragraphs, + rootCatalogBytes: + rootDocData && rootDocData.bin ? Array.from(rootDocData.bin) : [], + }; + })()`); + assert.equal(freshNativeVerify.autoWorkspaceId, freshWsId); + assert.equal(freshNativeVerify.autoDocId, freshDocId); + assert.ok(freshNativeVerify.registeredLocalWorkspaces.includes(freshWsId)); + assert.equal(freshNativeVerify.version, freshNativeVerify.expectedVersion); + assert.deepEqual( + freshNativeVerify.storeNames, + freshNativeVerify.expectedStores, + 'Legacy-created workspace IDB must contain all 12 v3 object stores' + ); + assert.equal(freshNativeVerify.probeVal, 1); + assert.deepEqual(freshNativeVerify.initialParagraphs, [freshParaText]); + assert.ok(freshNativeVerify.rootCatalogBytes.length > 0); + const freshRootDoc = new Y.Doc(); + Y.applyUpdate( + freshRootDoc, + new Uint8Array(freshNativeVerify.rootCatalogBytes) + ); + const rootMetaPages = + freshRootDoc.getMap('meta').get('pages')?.toArray() || []; + assert.ok( + rootMetaPages.some(p => (p?.get ? p.get('id') : p?.id) === freshDocId), + `Expected workspace root doc meta.pages to include ${freshDocId}` + ); + + // Reload Native Shell and verify continued native edit persisted to same-origin IDB. + await freshTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + freshTab.evalJs, + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))', + 15000 + ); + const nativeAfterReload = await freshTab.evalJs( + 'window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs' + ); + assert.deepEqual(nativeAfterReload, [ + freshParaText, + 'NATIVE-CONTINUED-EDIT-PARA', + ]); + + // Save a second distinct doc in mobile-legacy, click Return to Native Shell, and verify canvas pixels differ! + const freshDoc2Id = 'doc-fresh-second'; + const freshPara2Text = 'SECOND-DOC-DISTINCT-CANVAS-BODY'; + await freshTab.send('Page.navigate', { + url: `${baseUrl}/workspace/${freshWsId}/${freshDoc2Id}?shell=legacy&workspace=${freshWsId}`, + }); + await waitForCondition( + freshTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + await appendViaLegacyTab(freshTab, freshPara2Text); + const returnLink2 = await freshTab.evalJs(`(() => { + const link = document.querySelector('a.switch-link'); + link.scrollIntoView({ block: 'center' }); + const r = link.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await freshTab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: returnLink2.x, + y: returnLink2.y, + button: 'left', + clickCount: 1, + }); + await freshTab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: returnLink2.x, + y: returnLink2.y, + button: 'left', + clickCount: 1, + }); + await waitForCondition( + freshTab.evalJs, + 'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.activeDocSession && !document.getElementById("boot"))', + 15000 + ); + const doc2NativeParagraphs = await freshTab.evalJs( + 'window.__AFFINE_WEB_HOST__.activeDocSession.getSnapshot().paragraphs' + ); + assert.deepEqual(doc2NativeParagraphs, [freshPara2Text]); + const doc2Shot = await freshTab.send('Page.captureScreenshot', { + format: 'png', + }); + assert.ok(doc1Shot.data.length > 500 && doc2Shot.data.length > 500); + assert.notEqual( + doc1Shot.data, + doc2Shot.data, + 'Two distinct local documents must render visibly distinct Native Shell canvas pixels' + ); + const freshDecodedTexts = nativeAfterReload; + + // --- Scenario G: Hidden edgeless Note with ID 'note-root' must not be overwritten --- + const edgelessCollisionDocId = 'doc-edgeless-collision'; + const edgelessChildText = 'EDGELESS-NOTE-ROOT-INTACT'; + const newVisiblePageText = 'NEW-VISIBLE-PAGE-PARA'; + const edgelessSeedDoc = new Y.Doc(); + edgelessSeedDoc.transact(() => { + const b = edgelessSeedDoc.getMap('blocks'); + const p = new Y.Map(); + p.set('sys:id', 'page-edgeless'); + p.set('sys:flavour', 'affine:page'); + const pc = new Y.Array(); + pc.push(['note-root']); + p.set('sys:children', pc); + b.set('page-edgeless', p); + + const n = new Y.Map(); + n.set('sys:id', 'note-root'); + n.set('sys:flavour', 'affine:note'); + n.set('prop:displayMode', 'edgeless'); + const nc = new Y.Array(); + nc.push(['para-edgeless-child']); + n.set('sys:children', nc); + b.set('note-root', n); + + const para = new Y.Map(); + para.set('sys:id', 'para-edgeless-child'); + para.set('sys:flavour', 'affine:paragraph'); + para.set('prop:type', 'text'); + const yt = new Y.Text(); + yt.insert(0, edgelessChildText); + para.set('prop:text', yt); + b.set('para-edgeless-child', para); + }); + const edgelessSeedBin = Array.from(Y.encodeStateAsUpdate(edgelessSeedDoc)); + await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ flavour: 'local', type: 'workspace', id: 'local' }); + await h.workspaceStorage.pushDocUpdate({ + docId: ${JSON.stringify(edgelessCollisionDocId)}, + bin: new Uint8Array(${JSON.stringify(edgelessSeedBin)}), + }); + return true; + })()`); + + await multiDocTab.send('Page.navigate', { + url: `${baseUrl}/workspace/local/${edgelessCollisionDocId}?shell=legacy&workspace=local`, + }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + await appendViaLegacyTab(multiDocTab, newVisiblePageText); + + const edgelessMergedBytes = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ flavour: 'local', type: 'workspace', id: 'local' }); + const merged = await h.workspaceStorage.getDoc(${JSON.stringify(edgelessCollisionDocId)}); + return merged && merged.bin ? Array.from(merged.bin) : []; + })()`); + const edgelessVerifyDoc = new Y.Doc(); + Y.applyUpdate(edgelessVerifyDoc, new Uint8Array(edgelessMergedBytes)); + const eBlocks = edgelessVerifyDoc.getMap('blocks'); + const ePage = eBlocks.get('page-edgeless'); + const ePageChildren = ePage?.get('sys:children')?.toArray() || []; + assert.equal( + ePageChildren.length, + 2, + `Expected original edgeless note-root + newly allocated visible note, got ${JSON.stringify(ePageChildren)}` + ); + assert.equal(ePageChildren[0], 'note-root'); + assert.notEqual( + ePageChildren[1], + 'note-root', + 'New visible Note must use a unique non-colliding ID instead of overwriting note-root' + ); + const preservedNoteRoot = eBlocks.get('note-root'); + assert.equal(preservedNoteRoot?.get('sys:flavour'), 'affine:note'); + assert.equal(preservedNoteRoot?.get('prop:displayMode'), 'edgeless'); + assert.deepEqual(preservedNoteRoot?.get('sys:children')?.toArray(), [ + 'para-edgeless-child', + ]); + assert.equal( + eBlocks.get('para-edgeless-child')?.get('prop:text')?.toString(), + edgelessChildText + ); + const newVisibleNote = eBlocks.get(ePageChildren[1]); + assert.equal(newVisibleNote?.get('sys:flavour'), 'affine:note'); + assert.notEqual(newVisibleNote?.get('prop:displayMode'), 'edgeless'); + assert.notEqual(newVisibleNote?.get('prop:hidden'), true); + const newVisibleChildIds = + newVisibleNote?.get('sys:children')?.toArray() || []; + assert.equal(newVisibleChildIds.length, 1); + assert.equal( + eBlocks.get(newVisibleChildIds[0])?.get('prop:text')?.toString(), + newVisiblePageText + ); + + // --- Scenario H: Dual-tab concurrent first-save of the same cold document --- + const raceWsId = 'canary-concurrent-ws'; + const raceDocId = 'doc-cold-race'; + const raceText1 = 'CONCURRENT-TAB-1-PARA'; + const raceText2 = 'CONCURRENT-TAB-2-PARA'; + const raceUrl = `${baseUrl}/workspace/${raceWsId}/${raceDocId}?shell=legacy&workspace=${raceWsId}`; + const raceTab1 = await openNewTab(); + const raceTab2 = await openNewTab(); + await Promise.all([ + raceTab1.send('Page.navigate', { url: raceUrl }), + raceTab2.send('Page.navigate', { url: raceUrl }), + ]); + await Promise.all([ + waitForCondition( + raceTab1.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ), + waitForCondition( + raceTab2.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ), + ]); + + // Pre-fill both tabs via real CDP input, then click Append Paragraph concurrently! + const prepareTabInput = async (tab, text) => { + const center = await tab.evalJs(`(() => { + const input = document.getElementById('legacy-editor-input'); + input.scrollIntoView({ block: 'center' }); + input.focus(); + input.value = ''; + const r = input.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + await tab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: center.x, + y: center.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: center.x, + y: center.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.insertText', { text }); + return tab.evalJs(`(() => { + const btn = document.getElementById('legacy-append-btn'); + btn.scrollIntoView({ block: 'center' }); + const r = btn.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + })()`); + }; + const [raceBtn1, raceBtn2] = await Promise.all([ + prepareTabInput(raceTab1, raceText1), + prepareTabInput(raceTab2, raceText2), + ]); + const clickButton = async (tab, center) => { + await tab.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: center.x, + y: center.y, + button: 'left', + clickCount: 1, + }); + await tab.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: center.x, + y: center.y, + button: 'left', + clickCount: 1, + }); + }; + const clickBoth = async pairs => { + await Promise.all( + pairs.map(([tab]) => tab.evalJs(`(${gateSaveConnections})(1)`)) + ); + await Promise.all(pairs.map(([tab, button]) => clickButton(tab, button))); + await Promise.all( + pairs.map(([tab]) => tab.evalJs('window.connectionsReady')) + ); + await Promise.all( + pairs.map(([tab]) => tab.evalJs('window.releaseConnections()')) + ); + }; + await clickBoth([ + [raceTab1, raceBtn1], + [raceTab2, raceBtn2], + ]); + await Promise.all([ + waitForCondition( + raceTab1.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').includes('Saved to ${raceDocId}')`, + 15000 + ), + waitForCondition( + raceTab2.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').includes('Saved to ${raceDocId}')`, + 15000 + ), + ]); + + // Reload and assert both paragraphs survive in a single affine:page root! + await raceTab1.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + raceTab1.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const raceAfterReload = await raceTab1.evalJs(`({ + domText: document.getElementById('legacy-recovered-doc')?.textContent || '', + recoveredDocs: window.__AFFINE_LEGACY_SHELL__?.recoveredDocs || [], + })`); + const raceDocState = raceAfterReload.recoveredDocs.find( + d => d.docId === raceDocId + ); + assert.ok( + raceDocState, + 'Expected concurrent cold doc to persist across reload' + ); + assert.ok( + raceDocState.paragraphs.includes(raceText1) && + raceDocState.paragraphs.includes(raceText2), + `Expected both concurrent paragraphs after reload, got ${JSON.stringify(raceDocState.paragraphs)}` + ); + assert.ok( + raceAfterReload.domText.includes(raceText1) && + raceAfterReload.domText.includes(raceText2), + 'Visible #legacy-recovered-doc must show both concurrent paragraphs' + ); + + const savedWorkspace = (tab, id) => + tab.evalJs(`(${readSavedWorkspace})(${JSON.stringify(id)})`); + const sameDoc = await savedWorkspace(raceTab1, raceWsId); + assert.deepEqual(sameDoc.catalog, [raceDocId]); + assert.deepEqual([...raceDocState.paragraphs].sort(), [raceText1, raceText2]); + assertSaveClocks(sameDoc, { [raceDocId]: 2, [raceWsId]: 1 }); + + // Merge via real playground Wasm in Tab A and verify strictly 1 affine:page root in the Y.Doc! + const raceMergedBytes = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ + flavour: 'local', + type: 'workspace', + id: ${JSON.stringify(raceWsId)}, + }); + const merged = await h.workspaceStorage.getDoc(${JSON.stringify(raceDocId)}); + return merged && merged.bin ? Array.from(merged.bin) : []; + })()`); + const raceVerifyDoc = new Y.Doc(); + Y.applyUpdate(raceVerifyDoc, new Uint8Array(raceMergedBytes)); + const raceBlocks = raceVerifyDoc.getMap('blocks'); + /** @type {string[]} */ + const racePageRoots = []; + raceBlocks.forEach((block, id) => { + if (block?.get?.('sys:flavour') === 'affine:page') { + racePageRoots.push(id); + } + }); + assert.deepEqual( + racePageRoots, + [`page:${raceDocId}`], + `Expected strictly 1 deterministic affine:page root, got ${JSON.stringify(racePageRoots)}` + ); + + // --- Scenario I: Two tabs concurrently first-save DIFFERENT docs A & B in same cold workspace --- + const multiColdWs = 'canary-multi-cold-ws'; + const alphaTab = await openNewTab(); + const betaTab = await openNewTab(); + await Promise.all([ + alphaTab.send('Page.navigate', { + url: `${baseUrl}/workspace/${multiColdWs}/doc-alpha?shell=legacy&workspace=${multiColdWs}`, + }), + betaTab.send('Page.navigate', { + url: `${baseUrl}/workspace/${multiColdWs}/doc-beta?shell=legacy&workspace=${multiColdWs}`, + }), + ]); + await Promise.all([ + waitForCondition( + alphaTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ), + waitForCondition( + betaTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ), + ]); + const [alphaBtn, betaBtn] = await Promise.all([ + prepareTabInput(alphaTab, 'ALPHA-FIRST-SAVE'), + prepareTabInput(betaTab, 'BETA-FIRST-SAVE'), + ]); + await clickBoth([ + [alphaTab, alphaBtn], + [betaTab, betaBtn], + ]); + await Promise.all([ + waitForCondition( + alphaTab.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').includes('Saved to doc-alpha')`, + 15000 + ), + waitForCondition( + betaTab.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').includes('Saved to doc-beta')`, + 15000 + ), + ]); + const differentDocs = await savedWorkspace(alphaTab, multiColdWs); + assert.deepEqual(differentDocs.catalog.sort(), ['doc-alpha', 'doc-beta']); + assertSaveClocks(differentDocs, { + 'doc-alpha': 1, + 'doc-beta': 1, + [multiColdWs]: 2, + }); + for (const [tab, docId, text] of [ + [alphaTab, 'doc-alpha', 'ALPHA-FIRST-SAVE'], + [betaTab, 'doc-beta', 'BETA-FIRST-SAVE'], + ]) { + const docs = await tab.evalJs( + 'window.__AFFINE_LEGACY_SHELL__.recoveredDocs' + ); + assert.deepEqual(docs.find(doc => doc.docId === docId)?.paragraphs, [text]); + } + const multiColdRootBytes = await tabA.evalJs(`(async () => { + const h = window.__AFFINE_WEB_HOST__; + h.attachWorkspace({ + flavour: 'local', + type: 'workspace', + id: ${JSON.stringify(multiColdWs)}, + }); + const root = await h.workspaceStorage.getDoc(${JSON.stringify(multiColdWs)}); + return root && root.bin ? Array.from(root.bin) : []; + })()`); + const multiColdRootDoc = new Y.Doc(); + Y.applyUpdate(multiColdRootDoc, new Uint8Array(multiColdRootBytes)); + const multiColdCatalogIds = ( + multiColdRootDoc.getMap('meta').get('pages')?.toArray() || [] + ).map(p => (p?.get ? p.get('id') : p?.id)); + assert.ok( + multiColdCatalogIds.includes('doc-alpha') && + multiColdCatalogIds.includes('doc-beta'), + `Expected workspace catalog to include both doc-alpha and doc-beta, got ${JSON.stringify(multiColdCatalogIds)}` + ); + + // --- Scenario J: Injected atomic transaction abort + retry yields strictly 1 paragraph --- + const abortWs = 'canary-abort-ws'; + const abortDocId = 'doc-abort-retry'; + const abortText = 'ABORT-RETRY-SINGLE-PARA'; + const abortTab = await openNewTab(); + await abortTab.send('Page.navigate', { + url: `${baseUrl}/workspace/${abortWs}/${abortDocId}?shell=legacy&workspace=${abortWs}`, + }); + await waitForCondition( + abortTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + await abortTab.evalJs(`(() => { + const origTx = IDBDatabase.prototype.transaction; + let tripped = false; + IDBDatabase.prototype.transaction = function (stores, mode, ...rest) { + const tx = origTx.call(this, stores, mode, ...rest); + if (!tripped && mode === 'readwrite') { + tripped = true; + queueMicrotask(() => { + try { + tx.abort(); + } catch { + // Already finished. + } + }); + } + return tx; + }; + return true; + })()`); + const abortBtnCenter = await prepareTabInput(abortTab, abortText); + await clickButton(abortTab, abortBtnCenter); + await waitForCondition( + abortTab.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').startsWith('Save failed:')`, + 15000 + ); + // Click the same Append Paragraph button again to retry (text must still be intact!). + await clickButton(abortTab, abortBtnCenter); + await waitForCondition( + abortTab.evalJs, + `(document.getElementById('legacy-editor-status')?.textContent || '').includes('Saved to ${abortDocId}')`, + 15000 + ); + await abortTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + abortTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const abortAfterReload = await abortTab.evalJs( + 'window.__AFFINE_LEGACY_SHELL__.recoveredDocs' + ); + const abortDocState = abortAfterReload.find(d => d.docId === abortDocId); + assert.deepEqual( + abortDocState?.paragraphs, + [abortText], + `Expected strictly 1 paragraph after atomic abort + retry, got ${JSON.stringify(abortDocState?.paragraphs)}` + ); + + // --- Scenario K: From ?doc=a-other manually select z-active, save twice without jumping back --- + await multiDocTab.send('Page.navigate', { + url: `${baseUrl}/?shell=legacy&workspace=local&doc=a-other`, + }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const switchedState = await multiDocTab.evalJs(`(() => { + const sel = document.getElementById('legacy-target-doc'); + sel.value = JSON.stringify({ + dbName: 'local:workspace:local', + docId: 'z-active', + }); + sel.dispatchEvent(new Event('change', { bubbles: true })); + return { + search: window.location.search, + returnHref: document.querySelector('a.switch-link')?.getAttribute('href') || '', + selectedDocId: window.__AFFINE_LEGACY_SHELL__?.selectedTarget?.docId ?? null, + }; + })()`); + assert.ok(switchedState.search.includes('doc=z-active')); + assert.ok(switchedState.returnHref.includes('doc=z-active')); + assert.equal(switchedState.selectedDocId, 'z-active'); + + await appendViaLegacyTab(multiDocTab, 'MANUAL-SWITCH-EDIT-1'); + const midSwitchState = await multiDocTab.evalJs(`({ + search: window.location.search, + returnHref: document.querySelector('a.switch-link')?.getAttribute('href') || '', + selectedDocId: window.__AFFINE_LEGACY_SHELL__?.selectedTarget?.docId ?? null, + })`); + assert.equal(midSwitchState.selectedDocId, 'z-active'); + assert.ok(midSwitchState.returnHref.includes('doc=z-active')); + + await appendViaLegacyTab(multiDocTab, 'MANUAL-SWITCH-EDIT-2'); + await multiDocTab.send('Page.reload', { ignoreCache: false }); + await waitForCondition( + multiDocTab.evalJs, + 'Boolean(window.__AFFINE_LEGACY_SHELL__ && window.__AFFINE_LEGACY_SHELL__.ready)', + 15000 + ); + const afterSwitchReload = await multiDocTab.evalJs( + 'window.__AFFINE_LEGACY_SHELL__.recoveredDocs' + ); + const switchAOther = afterSwitchReload.find(d => d.docId === 'a-other'); + const switchZActive = afterSwitchReload.find(d => d.docId === 'z-active'); + assert.deepEqual(switchAOther?.paragraphs, ['A-OTHER-ORIGINAL']); + assert.deepEqual(switchZActive?.paragraphs, [ + 'Z-ACTIVE-ORIGINAL', + 'MARK-FOR-ACTIVE', + 'MANUAL-SWITCH-EDIT-1', + 'MANUAL-SWITCH-EDIT-2', + ]); + + const report = { + ok: true, + shell_build_id: staged.shellBuildId, + baseUrl, + realWasm: { + playgroundWasmBytes: staged.releaseManifest.pkg.wasmSha256 + ? tabALazyFetch.pkgBytes + : 0, + workerWasmBytes: Object.fromEntries( + Object.entries(staged.releaseManifest.workers).map(([k, v]) => [ + k, + v.bytes, + ]) + ), + yjsV1WasmMergeBytes: mergedByteLength, + }, + dualTab: { + tabAStatus400Plus: tabA404s.length, + tabBStatus400Plus: tabB404s.length, + tabALazyFontBytes: tabALazyFetch.fontBytes, + tabALazyWasmStatus: tabALazyFetch.wasmStatus, + tabADirectWasmStatus: tabALazyFetch.directWasmStatus, + tabAPkgStatus: tabALazyFetch.pkgStatus, + cspViolations: 0, + crossShellLeaks: 0, + }, + authRoutes: { + verified: ['/sign-in', '/magic-link', '/oauth/callback'], + mainShellTurnstileIsolated: true, + }, + ssrOpenGraph: { + publicDocPath, + privateDocPath, + crawlerHasOgTags: true, + mobileHasOgTagsAndNativeShell: true, + privateDocNoindex: true, + }, + gpuDoubleCrashTakeover: { + flushFailureAbortedNavigation: true, + crash1RecoveredInPlace: true, + crash2FallbackReason: crash2Takeover.legacyState.fallbackReason, + recoveredDocsCount: afterReloadTakeover.legacyState.recoveredDocs.length, + yjsV1BlocksFlavours: persistedDoc.flavours, + yjsV1VisibleNoteIds: visibleNoteIds, + yjsV1HiddenNoteExcluded: true, + yjsV1ParagraphsVerifiedByTreeWalk: vParagraphs, + yjsV1EditedViaRealLegacyUi: true, + yjsV1WasmMergedBytes: mergedByteLength, + zeroDataLoss: true, + }, + multiDocRouteTargeting: { + ambiguousMultiDocBlocksWrite: true, + routeTargetedDocId: 'z-active', + zActiveParagraphsAfterReload: docZActive?.paragraphs || [], + aOtherUntouchedParagraphs: docAOther?.paragraphs || [], + }, + freshLegacyWorkspaceNativeReopen: { + workspaceId: freshWsId, + docId: freshDocId, + clickedVisibleReturnLink: true, + autoAttachedWorkspaceId: freshNativeVerify.autoWorkspaceId, + autoOpenedDocId: freshNativeVerify.autoDocId, + registeredInLocalWorkspaceList: true, + rootCatalogIncludesDoc: true, + idbVersion: freshNativeVerify.version, + objectStoreCount: freshNativeVerify.storeNames.length, + all12StoresReadableWritable: true, + nativeWasmSnapshotParagraphs: freshDecodedTexts, + distinctCanvasPixelsAcrossTwoDocs: true, + }, + edgelessNoteRootCollisionGuard: { + docId: edgelessCollisionDocId, + pageChildren: ePageChildren, + preservedEdgelessNoteId: 'note-root', + preservedEdgelessDisplayMode: preservedNoteRoot?.get('prop:displayMode'), + preservedEdgelessChildText: edgelessChildText, + allocatedVisibleNoteId: ePageChildren[1], + newVisibleParagraphText: newVisiblePageText, + }, + concurrentColdDocFirstSave: { + workspaceId: raceWsId, + docId: raceDocId, + clocks: sameDoc.clocks, + catalog: sameDoc.catalog, + pageRoots: racePageRoots, + paragraphsAfterReload: raceDocState.paragraphs, + }, + concurrentMultiDocWorkspaceCatalog: { + workspaceId: multiColdWs, + clocks: differentDocs.clocks, + catalogDocIds: multiColdCatalogIds, + }, + atomicAbortRetryNoDuplicate: { + workspaceId: abortWs, + docId: abortDocId, + paragraphsAfterReload: abortDocState?.paragraphs || [], + }, + manualSelectUrlSourceOfTruth: { + switchedToDocId: 'z-active', + zActiveParagraphs: switchZActive?.paragraphs || [], + aOtherUntouchedParagraphs: switchAOther?.paragraphs || [], + }, + }; + + if (outDir) { + writeFileSync( + join(outDir, 'canary-dual-shell-report.json'), + JSON.stringify(report, null, 2) + '\n' + ); + } + console.log(JSON.stringify(report, null, 2)); +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + const cli = parseCliArgs(process.argv.slice(2)); + const outDir = + typeof cli['out-dir'] === 'string' ? resolve(cli['out-dir']) : null; + if (outDir) { + mkdirSync(outDir, { recursive: true }); + } + + const harness = createChromiumHarness({ + tmpPrefix: 'affine-canary-dual-shell-e2e-', + }); + + const openTabs = []; + try { + await verify(cli, outDir, harness, openTabs); + } finally { + for (const tab of openTabs) tab.close(); + await harness.close(); + } +} diff --git a/packages/frontend/hosts/web/scripts/verify-desktop-persistence.mjs b/packages/frontend/hosts/web/scripts/verify-desktop-persistence.mjs new file mode 100644 index 0000000000..eeb1cf6177 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/verify-desktop-persistence.mjs @@ -0,0 +1,1003 @@ +#!/usr/bin/env node +// @ts-check + +/** + * Real-browser gate for the Web Desktop workspace store. + * + * Serves `desktop/`, `src/`, the playground preview bridge, the tracked fonts, and a built + * `affine_desktop` wasm-bindgen package (`--pkg ` with `affine_desktop.js` and + * `affine_desktop_bg.wasm`). Then, in headless Chromium: + * 1. The first load seeds the showcase workspace into IndexedDB. + * 2. `Edgeless` and `New Page` create two documents. The page gets a new title and body. + * 3. After `Page.reload`, the URL keeps the open document, IndexedDB holds the typed text, + * and the frame matches the frame before the reload, not the seeded first frame. + * 4. The second workspace (`?workspace=ws-local-scratch`) keeps a new page the same way. + * Text typed right before a reload is in IndexedDB after it: the page flushes when it + * goes away, with no wait for the next timed save. + * 5. A page without `indexedDB` starts the showcase in memory with zero errors. + * 6. On an origin of its own, two tabs open the empty store at the same time. Without + * `navigator.locks`, a barrier holds each tab after it read the empty store until both + * did, so both seed the workspace. With `navigator.locks`, the second tab reads the + * store that the first tab seeded. In both cases a third tab that opens after them + * shows the sidebar (document, collection, and tag counts) and the page of one seed. + * 7. A click activates a sandboxed HTML preview. A wheel event over the preview + * reaches the canvas and returns pointer hits to it under the desktop CSP. + * + * Use `--cpu-rate` to slow the browser tab that creates and reloads the documents. + * + * Writes `first-load.png`, `before-reload.png`, `after-reload.png`, + * `scratch-first-reload.png`, `scratch-second-reload.png`, `no-indexeddb.png`, + * `two-tabs--first.png`, and `two-tabs--third.png` to + * `--out `. + */ + +import assert from 'node:assert/strict'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + writeFileSync, +} from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { basename, extname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { inflateSync } from 'node:zlib'; + +import { + closeBrowserResources, + createChromiumHarness, + openPageTarget, + SWIFTSHADER_OPTIONS, +} from './chromium-harness.mjs'; +import { inspectV1 } from './yjs-v1-inspect.mjs'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const REPO_ROOT = resolve(WEB_ROOT, '../../../..'); +const PREVIEW_BRIDGE = join( + REPO_ROOT, + 'blocksuite/crates/playground/web/preview-workers.js' +); +const FONTS_DIR = join(REPO_ROOT, 'packages/ui/tokens/fonts'); +const WIDTH = 1280; +const HEIGHT = 800; +/** @type {Record} */ +const CLICKS = JSON.parse(`{ + "desktop.sidebar.new_page": [206, 64], + "desktop.sidebar.new_doc_options": [230, 64], + "desktop.sidebar.new_edgeless": [252, 130], + "desktop.topbar.title": [345, 26] +}`); +const MAIN_WORKSPACE = 'ws-affine-desktop'; +const SCRATCH_WORKSPACE = 'ws-local-scratch'; +const DOC_PROPERTIES = 'db$docProperties'; +const TITLE = 'Persisted Title'; +const BODY = 'Body survives reload'; +const SCRATCH_TITLE = 'Scratch Title'; +const LAST_WORDS = 'typed right before reload'; + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'application/javascript; charset=utf-8', + '.wasm': 'application/wasm', + '.ttf': 'font/ttf', +}; + +function parseArgs(argv) { + const args = { pkg: '', out: '', cpuRate: 1 }; + for (let i = 2; i < argv.length; i += 1) { + if (argv[i] === '--pkg') args.pkg = resolve(argv[++i]); + else if (argv[i] === '--out') args.out = resolve(argv[++i]); + else if (argv[i] === '--cpu-rate') args.cpuRate = Number(argv[++i]); + else throw new Error(`Unknown option ${argv[i]}`); + } + if ( + !args.pkg || + !args.out || + !Number.isFinite(args.cpuRate) || + args.cpuRate < 1 + ) { + throw new Error( + 'Usage: verify-desktop-persistence.mjs --pkg --out [--cpu-rate ]' + ); + } + return args; +} + +/** @param {string} pkgDir */ +function staticFile(pkgDir, urlPath) { + const fonts = new Map( + readdirSync(FONTS_DIR, { recursive: true }) + .map(String) + .filter(rel => rel.endsWith('.ttf')) + .map(rel => [basename(rel), join(FONTS_DIR, rel)]) + ); + const serifDir = join( + REPO_ROOT, + 'packages/frontend/component/src/fonts/source-serif-4' + ); + for (const name of readdirSync(serifDir).filter(name => + name.endsWith('.ttf') + )) { + fonts.set(name, join(serifDir, name)); + } + if (urlPath === '/desktop' || urlPath === '/desktop/') + return join(WEB_ROOT, 'desktop/index.html'); + if (urlPath === '/preview-workers.js') return PREVIEW_BRIDGE; + if (urlPath.startsWith('/assets/fonts/')) + return fonts.get(decodeURIComponent(basename(urlPath))); + for (const [prefix, dir] of [ + ['/desktop/', join(WEB_ROOT, 'desktop')], + ['/src/', join(WEB_ROOT, 'src')], + ['/pkg/', pkgDir], + ]) { + if (urlPath.startsWith(prefix)) { + const file = resolve(dir, urlPath.slice(prefix.length)); + return file.startsWith(dir) ? file : undefined; + } + } + return undefined; +} + +function decodePng(buf) { + let offset = 8; + let width = 0; + let height = 0; + let colorType = 0; + const idat = []; + while (offset < buf.length) { + const len = buf.readUInt32BE(offset); + const type = buf.subarray(offset + 4, offset + 8).toString('ascii'); + const data = buf.subarray(offset + 8, offset + 8 + len); + offset += 12 + len; + if (type === 'IHDR') { + width = data.readUInt32BE(0); + height = data.readUInt32BE(4); + colorType = data[9]; + } else if (type === 'IDAT') idat.push(data); + } + const bpp = colorType === 6 ? 4 : 3; + const raw = inflateSync(Buffer.concat(idat)); + const stride = width * bpp; + const rgb = new Uint8Array(width * height * 3); + let prev = new Uint8Array(stride); + for (let y = 0; y < height; y += 1) { + const filter = raw[y * (stride + 1)]; + const row = new Uint8Array(stride); + for (let i = 0; i < stride; i += 1) { + const x = raw[y * (stride + 1) + 1 + i]; + const a = i >= bpp ? row[i - bpp] : 0; + const b = prev[i]; + const c = i >= bpp ? prev[i - bpp] : 0; + const p = a + b - c; + const paeth = + Math.abs(p - a) <= Math.abs(p - b) && Math.abs(p - a) <= Math.abs(p - c) + ? a + : Math.abs(p - b) <= Math.abs(p - c) + ? b + : c; + row[i] = (x + [0, a, b, (a + b) >> 1, paeth][filter]) & 0xff; + } + for (let px = 0; px < width; px += 1) { + rgb.set(row.subarray(px * bpp, px * bpp + 3), (y * width + px) * 3); + } + prev = row; + } + return { width, height, rgb }; +} + +/** Pixels of `img` inside the box where `test(r, g, b)` holds. */ +function matching(img, [x0, y0, x1, y1], test) { + const out = []; + for (let y = y0; y < y1; y += 1) { + for (let x = x0; x < x1; x += 1) { + const i = (y * img.width + x) * 3; + if (test(img.rgb[i], img.rgb[i + 1], img.rgb[i + 2])) out.push([x, y]); + } + } + return out; +} + +function bounds(points) { + const xs = points.map(p => p[0]); + const ys = points.map(p => p[1]); + return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; +} + +/** Share of the pixels inside the box (the whole frame by default) that differ. */ +function differentPixelRatio( + a, + b, + [x0, y0, x1, y1] = [0, 0, a.width, a.height] +) { + let diff = 0; + for (let y = y0; y < y1; y += 1) { + for (let x = x0; x < x1; x += 1) { + const i = (y * a.width + x) * 3; + if ( + Math.abs(a.rgb[i] - b.rgb[i]) + + Math.abs(a.rgb[i + 1] - b.rgb[i + 1]) + + Math.abs(a.rgb[i + 2] - b.rgb[i + 2]) > + 48 + ) + diff += 1; + } + } + return diff / ((x1 - x0) * (y1 - y0)); +} + +/** The sidebar: document counts, favorites, folders, collections, and tags. */ +const SIDEBAR = [0, 0, 258, HEIGHT]; + +const isDark = (r, g, b) => r < 110 && g < 110 && b < 110; + +async function connect(debugPort) { + const target = await openPageTarget(debugPort); + const ws = new WebSocket(target.webSocketDebuggerUrl); + await new Promise((ok, fail) => { + ws.addEventListener('open', ok, { once: true }); + ws.addEventListener('error', fail, { once: true }); + }); + let nextId = 1; + const pending = new Map(); + const errors = []; + const cspIssues = []; + /** @type {(() => void) | null} */ + let onLoad = null; + ws.addEventListener('message', ev => { + const msg = JSON.parse(String(ev.data)); + if (msg.method === 'Page.loadEventFired') { + onLoad?.(); + } else if (msg.id && pending.has(msg.id)) { + const { ok, fail } = pending.get(msg.id); + pending.delete(msg.id); + if (msg.error) fail(new Error(msg.error.message)); + else ok(msg.result); + } else if (msg.method === 'Runtime.exceptionThrown') { + errors.push( + msg.params.exceptionDetails?.exception?.description ?? 'exception' + ); + } else if (msg.method === 'Runtime.consoleAPICalled') { + const text = msg.params.args.map(a => a.value ?? a.description).join(' '); + if (msg.params.type === 'error') errors.push(text); + else console.log(`[page console.${msg.params.type}] ${text}`); + } else if (msg.method === 'Audits.issueAdded') { + const details = + msg.params.issue.details.contentSecurityPolicyIssueDetails; + if (details) cspIssues.push(details); + } + }); + const send = (method, params = {}) => + new Promise((ok, fail) => { + const id = nextId++; + pending.set(id, { ok, fail }); + ws.send(JSON.stringify({ id, method, params })); + }); + const evaluate = async expression => { + const r = await send('Runtime.evaluate', { + expression, + awaitPromise: true, + returnByValue: true, + }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.text); + return r.result?.value; + }; + const shot = async () => + Buffer.from( + (await send('Page.captureScreenshot', { format: 'png' })).data, + 'base64' + ); + const click = async ([x, y]) => { + await send('Input.dispatchMouseEvent', { + type: 'mouseMoved', + x, + y, + button: 'none', + }); + for (const type of ['mousePressed', 'mouseReleased']) { + await send('Input.dispatchMouseEvent', { + type, + x, + y, + button: 'left', + buttons: type === 'mousePressed' ? 1 : 0, + clickCount: 1, + }); + } + }; + const key = async (key, code, keyCode) => { + for (const type of ['rawKeyDown', 'keyUp']) { + await send('Input.dispatchKeyEvent', { + type, + key, + code, + windowsVirtualKeyCode: keyCode, + nativeVirtualKeyCode: keyCode, + }); + } + }; + await send('Page.enable'); + await send('Runtime.enable'); + await send('Audits.enable'); + await send('Emulation.setDeviceMetricsOverride', { + width: WIDTH, + height: HEIGHT, + deviceScaleFactor: 1, + mobile: false, + }); + await send('Emulation.setFocusEmulationEnabled', { enabled: true }); + /** Navigates with `method` and waits for the load event of the new page. */ + const load = async (method, params = {}) => { + const loaded = new Promise(ok => { + onLoad = ok; + }); + await send(method, params); + await loaded; + }; + return { ws, send, load, evaluate, shot, click, key, errors, cspIssues }; +} + +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +/** Waits until the sidebar and the page show ink in two equal frames in a row. */ +async function settledFrame(page) { + let last = null; + for (let i = 0; i < 120; i += 1) { + await sleep(500); + const png = await page.shot(); + const img = decodePng(png); + const ink = matching(img, [0, 0, WIDTH, HEIGHT], isDark).length; + if (ink > 500 && last && differentPixelRatio(last.img, img) < 0.001) { + return { png, img }; + } + last = { png, img }; + } + if (last) + writeFileSync(join(tmpdir(), 'desktop-unstable-frame.png'), last.png); + throw new Error( + `The desktop did not render a stable frame (last frame in ${tmpdir()}). Errors: ${page.errors.join('; ')}` + ); +} + +/** End of the first line of large dark text right of the sidebar: the page title. */ +function titleEnd(img, sidebarRight) { + let band = null; + for (let y = 100; y < 400 && !band; y += 1) { + const row = matching( + img, + [sidebarRight + 40, y, WIDTH - 40, y + 1], + isDark + ); + if (row.length > 20) band = y; + } + assert.ok(band !== null, 'the page shows a title'); + const ink = matching( + img, + [sidebarRight + 40, band, WIDTH - 40, band + 28], + isDark + ); + const [, y0, x1, y1] = bounds(ink); + return [x1 - 2, (y0 + y1) >> 1]; +} + +/** Waits for an observable browser state. */ +async function waitFor(description, read) { + const deadline = performance.now() + 15000; + do { + const result = await read(); + if (result) return result; + await sleep(50); + } while (performance.now() < deadline); + throw new Error(`Timed out waiting for ${description}`); +} + +/** Reads snapshots and updates together in one read-only transaction. */ +async function readStore(page, workspaceId, docId) { + const rows = await page.evaluate(`(async () => { + const read = req => new Promise((ok, fail) => { + req.onsuccess = () => ok(req.result); + req.onerror = () => fail(req.error); + }); + const open = indexedDB.open(${JSON.stringify('local:workspace:' + workspaceId)}); + open.onupgradeneeded = () => open.transaction.abort(); + const db = await read(open); + try { + const tx = db.transaction(['snapshots', 'updates'], 'readonly'); + const id = ${JSON.stringify(docId ?? null)}; + const snapshots = tx.objectStore('snapshots'); + const updates = tx.objectStore('updates'); + return await Promise.all(id === null + ? [read(snapshots.getAllKeys()), read(updates.getAllKeys())] + : [read(snapshots.get(id)), read(updates.index('docId').getAll(id))]) + .then(([snapshot, pending]) => id === null + ? [...new Set([...snapshot, ...pending.map(key => key[0])])] + : [snapshot, ...pending].filter(row => row?.bin?.byteLength) + .map(row => Array.from(new Uint8Array(row.bin)))); + } finally { + db.close(); + } + })()`); + return docId === undefined + ? rows + : inspectV1(rows.map(row => Uint8Array.from(row))); +} + +async function routeDoc(page, workspaceId, previous) { + return waitFor('the new document route', async () => { + const query = new URLSearchParams(await page.evaluate('location.search')); + const id = query.get('doc'); + return query.get('workspace') === workspaceId && id && id !== previous + ? id + : null; + }); +} + +async function documentText(page, workspaceId, docId) { + const doc = await readStore(page, workspaceId, docId); + const blocks = [...doc.map('blocks').values()].filter( + block => block instanceof Map + ); + return { + title: blocks + .find(block => block.get('sys:flavour') === 'affine:page') + ?.get('prop:title'), + paragraphs: blocks + .filter(block => block.get('sys:flavour') === 'affine:paragraph') + .map(block => block.get('prop:text')) + .filter(text => text !== ''), + }; +} + +const IME_STATE = `(() => { + const input = document.activeElement; + return input instanceof HTMLTextAreaElement + ? { value: input.value, start: input.selectionStart, end: input.selectionEnd } + : null; +})()`; + +function hasTitleBorder(img) { + const [x, y] = CLICKS['desktop.topbar.title']; + const accent = (r, g, b) => b > 185 && g - r > 30 && b - g > 20; + for (let row = y - 16; row <= y + 16; row++) { + if (matching(img, [x, row, x + 150, row + 1], accent).length > 100) + return true; + } + return false; +} + +async function renamePage(page, title) { + const initial = await page.evaluate(IME_STATE); + await page.click(CLICKS['desktop.topbar.title']); + await waitFor('the focused topbar title', async () => { + if (!hasTitleBorder(decodePng(await page.shot()))) return false; + const input = await page.evaluate(IME_STATE); + // The newly created page has an empty title. The mirror must show that field. + return input?.value === '' && input.start === 0 && input.end === 0; + }); + assert.notEqual( + initial?.value, + title, + 'the textarea does not already hold the target title' + ); + await page.send('Input.insertText', { text: title }); + await waitFor( + 'the typed topbar title', + async () => (await page.evaluate(IME_STATE))?.value === title + ); + await page.key('Enter', 'Enter', 13); + await waitFor( + 'the closed topbar title input', + async () => !hasTitleBorder(decodePng(await page.shot())) + ); +} + +async function createPage(page, workspaceId, title, body) { + const previous = new URLSearchParams( + await page.evaluate('location.search') + ).get('doc'); + await page.click(CLICKS['desktop.sidebar.new_page']); + const docId = await routeDoc(page, workspaceId, previous); + await settledFrame(page); + await renamePage(page, title); + const frame = await settledFrame(page); + await page.click(titleEnd(frame.img, SIDEBAR[2])); + await waitFor( + 'the editor title input', + async () => (await page.evaluate(IME_STATE))?.value === title + ); + await page.key('End', 'End', 35); + await page.key('Enter', 'Enter', 13); + await waitFor( + 'the empty paragraph input', + async () => (await page.evaluate(IME_STATE))?.value === '' + ); + await page.send('Input.insertText', { text: body }); + return docId; +} + +/** @param {Awaited>} page */ +async function checkHtmlPreviewWheel(page) { + const x = 920; + const y = 440; + await page.evaluate(`(() => { + const canvas = document.querySelector('canvas'); + const state = window.previewWheelTest = { loaded: false, wheels: [], violations: [] }; + document.addEventListener('securitypolicyviolation', event => { + state.violations.push(event.violatedDirective); + }); + canvas.addEventListener('wheel', event => { + state.wheels.push({ + deltaY: event.deltaY, x: event.clientX, y: event.clientY, + isTrusted: event.isTrusted, + }); + }); + window.__playgroundPreview.mountHtmlEmbed( + 'wheel-test', '

Static HTML preview

', + { x: ${x - 100}, y: ${y - 60}, w: 200, h: 120 } + ); + document.querySelector('#embed-layer iframe').addEventListener('load', () => { + state.loaded = true; + }, { once: true }); + })()`); + await waitFor('the HTML preview to load', () => + page.evaluate('window.previewWheelTest.loaded') + ); + const hit = `document.elementFromPoint(${x}, ${y})`; + const iframe = "document.querySelector('#embed-layer iframe')"; + assert.equal(await page.evaluate(`${hit}?.tagName`), 'CANVAS'); + await page.click([x, y]); + assert.equal(await page.evaluate(`${iframe}?.style.pointerEvents`), 'auto'); + assert.equal(await page.evaluate(`${hit} === ${iframe}`), true); + await page.click([x, y]); + assert.equal( + await page.evaluate(`document.activeElement === ${iframe}`), + true + ); + + await page.send('Input.dispatchMouseEvent', { + type: 'mouseWheel', + x, + y, + deltaX: 0, + deltaY: 90, + }); + let wheels; + try { + wheels = await waitFor('the wheel event on the canvas', async () => { + assert.deepEqual(page.cspIssues, [], 'Chromium reports no CSP issues'); + const state = await page.evaluate('window.previewWheelTest'); + assert.deepEqual(state.violations, [], 'the page has no CSP violations'); + return state.wheels.length && state.wheels; + }); + } catch (error) { + return failWithWheelDiagnostics(page, error, { x, y, iframe, hit }); + } + assert.deepEqual(wheels, [{ deltaY: 90, x, y, isTrusted: false }]); + assert.equal(await page.evaluate(`${iframe}?.style.pointerEvents`), 'none'); + assert.equal(await page.evaluate(`${hit}?.tagName`), 'CANVAS'); + console.log( + 'HTML preview wheel passed: +90 reached the canvas, pointer hits returned to it, and Chromium reported zero CSP violations' + ); +} + +/** + * @param {Pick>, 'ws' | 'send' | 'evaluate'>} page + * @param {unknown} error + * @param {{x: number, y: number, iframe: string, hit: string}} target + */ +export async function failWithWheelDiagnostics( + page, + error, + { x, y, iframe, hit } +) { + if (page.ws.readyState !== WebSocket.OPEN) throw error; + const listeners = new AbortController(); + /** @type {ReturnType | undefined} */ + let timer; + let message; + try { + const interrupted = new Promise((_, reject) => { + const onDisconnect = () => reject(error); + const options = { once: true, signal: listeners.signal }; + page.ws.addEventListener('close', onDisconnect, options); + page.ws.addEventListener('error', onDisconnect, options); + timer = setTimeout(() => reject(error), 1_000); + }); + // Promise.all observes both CDP requests even after the race ends. + const [version, snapshot] = await Promise.race([ + Promise.all([ + page.send('Browser.getVersion'), + page.evaluate(`(() => { + const describe = element => element && { + tagName: element.tagName, + id: element.id, + className: element.getAttribute('class') ?? '', + }; + const frame = ${iframe}; + const state = window.previewWheelTest; + return { + activeElement: describe(document.activeElement), + iframe: frame && { + bounds: frame.getBoundingClientRect().toJSON(), + pointerEvents: frame.style.pointerEvents, + sandbox: frame.getAttribute('sandbox'), + }, + hitElement: describe(${hit}), + wheelCount: state?.wheels.length ?? null, + lastWheel: state?.wheels.at(-1) ?? null, + }; + })()`), + ]), + interrupted, + ]); + const diagnostics = { product: version.product, x, y, ...snapshot }; + message = `${String(error)}\nHTML preview wheel diagnostics\n${JSON.stringify(diagnostics)}`; + } catch { + throw error; + } finally { + clearTimeout(timer); + listeners.abort(); + } + throw new Error(message, { cause: error }); +} + +async function main() { + const args = parseArgs(process.argv); + assert.ok( + existsSync(join(args.pkg, 'affine_desktop.js')), + 'the package has affine_desktop.js' + ); + mkdirSync(args.out, { recursive: true }); + const save = (name, png) => writeFileSync(join(args.out, name), png); + + const harness = createChromiumHarness({ + tmpPrefix: 'affine-desktop-persist-', + }); + const server = createServer(serveDesktop(args.pkg)); + let page; + try { + await new Promise((ok, fail) => { + server.once('error', fail); + server.listen(0, '127.0.0.1', ok); + }); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + server.address() + ); + const url = `http://127.0.0.1:${port}/desktop?theme=light`; + const debugPort = await harness.launchChromium(SWIFTSHADER_OPTIONS); + + page = await connect(debugPort); + if (args.cpuRate !== 1) { + await page.send('Emulation.setCPUThrottlingRate', { rate: args.cpuRate }); + } + await checkPersistence(page, url, save); + await checkHtmlPreviewWheel(page); + page.ws.close(); + + page = await connect(debugPort); + await page.send('Page.addScriptToEvaluateOnNewDocument', { + source: + "Object.defineProperty(window, 'indexedDB', { value: undefined });", + }); + await page.load('Page.navigate', { url }); + const memory = await settledFrame(page); + save('no-indexeddb.png', memory.png); + assert.deepEqual(page.errors, []); + page.ws.close(); + page = undefined; + + for (const locks of [false, true]) { + await checkTwoFirstOpens(debugPort, args.pkg, locks, save); + } + console.log( + 'Web Desktop persistence passed: reload kept the created documents, and two first opens show the content of one seed' + ); + } finally { + await closeBrowserResources(harness, page?.ws, server); + } +} + +/** + * Request handler that serves the desktop page, its modules, the fonts, and the package + * `pkgDir`. With `reads`, `desktop/start.js` reports to `/read-store?empty=` whether the + * showcase store it read was empty, and waits for the answer. With `reads.barrier`, the + * answer to an empty read waits until two tabs read an empty store. + * + * @param {string} pkgDir + * @param {{ empty: number, barrier: boolean, held: import('node:http').ServerResponse[] }} [reads] + */ +function serveDesktop(pkgDir, reads) { + return (req, res) => { + const reqUrl = new URL(req.url ?? '/', 'http://localhost'); + if (reads && reqUrl.pathname === '/read-store') { + if (reqUrl.searchParams.get('empty') !== 'true') { + res.end(); + return; + } + reads.empty += 1; + reads.held.push(res); + if (!reads.barrier || reads.empty >= 2) { + for (const held of reads.held.splice(0)) held.end(); + } + return; + } + const urlPath = reqUrl.pathname; + const file = staticFile(pkgDir, urlPath); + if (!file || !existsSync(file)) { + res.writeHead(404); + res.end(); + return; + } + res.writeHead(200, { + 'Content-Type': MIME_TYPES[extname(file)] ?? 'application/octet-stream', + 'Cache-Control': 'no-store', + }); + if (reads && urlPath === '/desktop/start.js') { + const source = readFileSync(file, 'utf8'); + const read = + 'const store = await openStore(wasm.web_desktop_workspace_ids());'; + assert.ok(source.includes(read), 'start.js opens the store'); + res.end( + source.replace( + read, + read + + " await fetch('/read-store?empty=' + Boolean(store && !store.docIds('ws-affine-desktop').length));" + ) + ); + return; + } + res.end(readFileSync(file)); + }; +} + +/** + * Steps 1 to 4: create, edit, and reload documents of both workspaces at `url`. + * + * @param {Awaited>} page + * @param {string} url + * @param {(name: string, png: Buffer) => void} save + */ +async function checkPersistence(page, url, save) { + { + await page.load('Page.navigate', { url }); + assert.equal( + await page.evaluate('location.pathname'), + new URL(url).pathname + ); + const first = await settledFrame(page); + save('first-load.png', first.png); + const seeded = await waitFor( + 'the seeded workspace in IndexedDB', + async () => { + const docs = await readStore(page, MAIN_WORKSPACE); + return docs.length > 0 && docs; + } + ); + const seedId = await routeDoc(page, MAIN_WORKSPACE); + await page.click(CLICKS['desktop.sidebar.new_doc_options']); + const menuPoint = CLICKS['desktop.sidebar.new_edgeless']; + const menuBox = [ + menuPoint[0] - 18, + menuPoint[1] - 8, + menuPoint[0] + 100, + menuPoint[1] + 8, + ]; + await waitFor( + 'the new document menu', + async () => + differentPixelRatio(first.img, decodePng(await page.shot()), menuBox) > + 0.02 + ); + await page.click(menuPoint); + const boardId = await routeDoc(page, MAIN_WORKSPACE, seedId); + await waitFor('the new board in IndexedDB', async () => + (await readStore(page, MAIN_WORKSPACE)).includes(boardId) + ); + const boardMode = (await readStore(page, MAIN_WORKSPACE, DOC_PROPERTIES)) + .map(boardId) + .get('primaryMode'); + assert.equal( + boardMode, + 'edgeless', + 'the first new document has primaryMode edgeless' + ); + assert.match( + (await documentText(page, MAIN_WORKSPACE, boardId)).title, + /^Untitled Board \d+$/, + 'IndexedDB holds the title of the new board' + ); + + const docId = await createPage(page, MAIN_WORKSPACE, TITLE, BODY); + assert.ok( + !seeded.includes(boardId) && !seeded.includes(docId), + 'both documents are new' + ); + const before = await settledFrame(page); + save('before-reload.png', before.png); + const route = await page.evaluate('location.search'); + + await page.load('Page.reload'); + const after = await settledFrame(page); + save('after-reload.png', after.png); + assert.deepEqual( + await documentText(page, MAIN_WORKSPACE, docId), + { + title: TITLE, + paragraphs: [BODY], + }, + 'IndexedDB holds the title and paragraph of the open page' + ); + assert.equal(await page.evaluate('location.search'), route); + assert.deepEqual( + new Set(await readStore(page, MAIN_WORKSPACE)), + new Set([...seeded, boardId, docId]), + 'the workspace contains exactly the two new documents' + ); + const changed = differentPixelRatio(before.img, after.img); + const fromSeed = differentPixelRatio(first.img, after.img); + console.log( + `Frame difference after reload: ${(changed * 100).toFixed(3)}% to before, ${(fromSeed * 100).toFixed(3)}% to the first load` + ); + assert.ok( + changed < 0.005, + 'the reloaded frame matches the frame before the reload' + ); + assert.equal( + differentPixelRatio(before.img, after.img, SIDEBAR), + 0, + 'the reloaded sidebar, with its collection and tag counts, matches the sidebar before the reload' + ); + assert.ok( + fromSeed > 0.01, + 'the reloaded frame is not the seeded first frame' + ); + + await page.load('Page.navigate', { + url: url + '&workspace=ws-local-scratch', + }); + await settledFrame(page); + const scratchId = await createPage( + page, + SCRATCH_WORKSPACE, + SCRATCH_TITLE, + LAST_WORDS + ); + await page.load('Page.reload'); + const scratchAfterFlush = await settledFrame(page); + assert.deepEqual( + await documentText(page, SCRATCH_WORKSPACE, scratchId), + { + title: SCRATCH_TITLE, + paragraphs: [LAST_WORDS], + }, + 'the pagehide flush keeps the scratch title and paragraph' + ); + save('scratch-first-reload.png', scratchAfterFlush.png); + const scratchRoute = await page.evaluate('location.search'); + assert.match(scratchRoute, /[?&]workspace=ws-local-scratch&doc=/); + await page.load('Page.reload'); + const scratchAfter = await settledFrame(page); + save('scratch-second-reload.png', scratchAfter.png); + assert.equal(await page.evaluate('location.search'), scratchRoute); + const scratchChanged = differentPixelRatio( + scratchAfterFlush.img, + scratchAfter.img + ); + console.log( + `Second workspace frame difference after reload: ${(scratchChanged * 100).toFixed(3)}%` + ); + assert.ok( + scratchChanged < 0.005, + 'the second workspace reloads to the same frame' + ); + assert.deepEqual(page.errors, []); + } +} + +/** + * Step 6: two tabs open the empty store of a new origin at the same time, then a third tab + * opens it. Without `locks`, the tabs have no `navigator.locks` and both read the empty store. + * + * @param {number} debugPort + * @param {string} pkgDir + * @param {boolean} locks + * @param {(name: string, png: Buffer) => void} save + */ +async function checkTwoFirstOpens(debugPort, pkgDir, locks, save) { + const reads = { empty: 0, barrier: !locks, held: [] }; + const server = createServer(serveDesktop(pkgDir, reads)); + const tabs = []; + try { + await new Promise((ok, fail) => { + server.once('error', fail); + server.listen(0, '127.0.0.1', ok); + }); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + server.address() + ); + const url = `http://127.0.0.1:${port}/desktop/?theme=light`; + for (let i = 0; i < 3; i += 1) { + const tab = await connect(debugPort); + tabs.push(tab); + if (!locks) { + await tab.send('Page.addScriptToEvaluateOnNewDocument', { + source: + "Object.defineProperty(Navigator.prototype, 'locks', { get: () => undefined });", + }); + } + } + const [a, b, third] = tabs; + await Promise.all([a, b].map(tab => tab.load('Page.navigate', { url }))); + await a.send('Page.bringToFront'); + await settledFrame(a); + await b.send('Page.bringToFront'); + const first = await settledFrame(b); + const route = await b.evaluate('location.href'); + await third.send('Page.bringToFront'); + await third.load('Page.navigate', { url: route }); + const cold = await settledFrame(third); + const name = locks ? 'locks' : 'no-locks'; + save(`two-tabs-${name}-first.png`, first.png); + save(`two-tabs-${name}-third.png`, cold.png); + const sidebar = differentPixelRatio(first.img, cold.img, SIDEBAR); + const content = differentPixelRatio(first.img, cold.img, [ + SIDEBAR[2] + 22, + 100, + WIDTH, + HEIGHT, + ]); + console.log( + `Two first opens (${name}): ${reads.empty} empty reads, sidebar difference ${sidebar}, page difference ${content}` + ); + assert.equal( + reads.empty, + locks ? 1 : 2, + `${name}: tabs that read an empty store` + ); + assert.equal( + sidebar, + 0, + `${name}: the third tab shows the sidebar of one seed` + ); + assert.equal( + content, + 0, + `${name}: the third tab shows the page of one seed` + ); + // Without the lock, both tabs write the seed at the same time. A write + // that the other tab made first at the same time fails and is written + // again; any other error fails the check. + const rewrites = tabs.flatMap(tab => + tab.errors.filter(error => + error.startsWith('IndexedDB write failed and is written again') + ) + ); + console.log( + `Two first opens (${name}): ${rewrites.length} writes written again` + ); + if (locks) assert.deepEqual(rewrites, [], name); + for (const tab of tabs) { + assert.deepEqual( + tab.errors.filter(error => !rewrites.includes(error)), + [], + name + ); + } + } finally { + for (const held of reads.held.splice(0)) held.end(); + for (const tab of tabs) { + void tab.send('Page.close').catch(() => {}); + tab.ws.close(); + } + server.closeAllConnections(); + await new Promise(ok => server.close(ok)); + } +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + await main(); +} diff --git a/packages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs b/packages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs new file mode 100644 index 0000000000..11d826ffae --- /dev/null +++ b/packages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs @@ -0,0 +1,353 @@ +#!/usr/bin/env node +// @ts-check + +/** + * Real-browser Headless Chromium E2E gate for `src/idb-storage.js`. + * + * Uses a preinstalled Chromium binary (never runs `playwright install`) and + * stops the Chromium process group in `finally`, cleaning + * up its temporary profile directory. + * + * Verifies in real Chromium `indexedDB` + `BroadcastChannel`: + * 1. Overlapping `flush()` + concurrent `enqueue('c')` persists all 3 items + * exactly once with zero duplicates and zero drops. + * 2. `pushDocUpdatesBatch` encountering a mid-batch `DataError` calls + * `tx.abort()` so zero partial rows persist. + * 3. Cold-start `Promise.all` concurrent reads share a single `openPromise`, + * so `close()` -> `indexedDB.deleteDatabase(...)` completes immediately + * with zero `blocked` events. + * 4. Legacy V1 `affine-local` database enumeration with built-in Yjs v1 + * `ContentDoc` extractor discovers top-level subdocs and reads docs + * without mutating or creating empty V1 databases. + */ + +import assert from 'node:assert/strict'; +import { existsSync, readFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { extname, normalize, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + closeBrowserResources, + createChromiumHarness, + openPageTarget, +} from './chromium-harness.mjs'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.wasm': 'application/wasm', +}; + +const PROBE_HTML = ` + + + + + +`; + +let harness; +let server; +let ws; +try { + harness = createChromiumHarness({ tmpPrefix: 'affine-idb-e2e-' }); + server = createServer((req, res) => { + const url = new URL(req.url || '/', 'http://127.0.0.1'); + if (url.pathname === '/probe.html') { + res.writeHead(200, { 'content-type': MIME_TYPES['.html'] }); + res.end(PROBE_HTML); + return; + } + const rel = normalize(url.pathname).replace(/^\/+/, ''); + const full = resolve(WEB_ROOT, rel); + if (!full.startsWith(WEB_ROOT) || !existsSync(full)) { + res.writeHead(404); + res.end('not found'); + return; + } + res.writeHead(200, { + 'content-type': MIME_TYPES[extname(full)] || 'application/octet-stream', + }); + res.end(readFileSync(full)); + }); + await new Promise((ok, fail) => { + server.once('error', fail); + server.listen(0, '127.0.0.1', ok); + }); + const { port } = server.address(); + const debugPort = await harness.launchChromium({ args: ['--disable-gpu'] }); + const pageTarget = await openPageTarget(debugPort); + ws = new WebSocket(pageTarget.webSocketDebuggerUrl); + await new Promise((ok, fail) => { + ws.addEventListener('open', ok, { once: true }); + ws.addEventListener('error', fail, { once: true }); + }); + + let nextId = 1; + const pending = new Map(); + ws.addEventListener('message', ev => { + const msg = JSON.parse(String(ev.data)); + if (msg.id && pending.has(msg.id)) { + const { ok, fail } = pending.get(msg.id); + pending.delete(msg.id); + if (msg.error) fail(new Error(msg.error.message)); + else ok(msg.result); + } + }); + const send = (method, params = {}) => + new Promise((ok, fail) => { + const id = nextId++; + pending.set(id, { ok, fail }); + ws.send(JSON.stringify({ id, method, params })); + }); + const evalJs = async expression => { + const r = await send('Runtime.evaluate', { + expression, + awaitPromise: true, + returnByValue: true, + }); + if (r.exceptionDetails) { + throw new Error(r.exceptionDetails.text); + } + return r.result?.value; + }; + + await send('Page.enable'); + await send('Page.navigate', { url: `http://127.0.0.1:${port}/probe.html` }); + + let probeResult = null; + for (let i = 0; i < 100; i += 1) { + const err = await evalJs('window.__IDB_E2E_ERROR__ || null'); + if (err) { + throw new Error(`Browser probe error: ${err}`); + } + const res = await evalJs('window.__IDB_E2E_RESULT__ || null'); + if (res) { + probeResult = res; + break; + } + await new Promise(r => setTimeout(r, 50)); + } + assert.ok(probeResult, 'IDB real-browser probe did not complete in time'); + + assert.deepEqual(probeResult.overlappingFlush, { + ok1: true, + ok2: true, + pendingAfter: 0, + rowsA: 1, + rowsB: 1, + rowsC: 1, + }); + assert.equal(probeResult.batchAtomicity.firstPersisted, false); + assert.ok(probeResult.batchAtomicity.errorName); + assert.deepEqual(probeResult.concurrentOpenDelete, { + deleted: true, + blocked: false, + }); + assert.equal(probeResult.v1.missingDoc, null); + assert.equal(probeResult.v1.createdEmpty, false); + assert.deepEqual(probeResult.v1.listed, [ + 'ws-v1-e2e', + 'live-guid', + 'userdata$u1$ws-v1-e2e', + 'userdata$u1$ws-v1-e2e$fav', + ]); + assert.ok( + probeResult.v1.mergedRootBytes > 0, + 'getV1Doc must merge REAL_YJS_V1_UPDATES via real Wasm codec' + ); + assert.deepEqual(probeResult.v1.roundtrippedSubdocs, ['live-guid']); + assert.equal(probeResult.v1.subdocBytes, 11); + + console.log(`Real-browser IDB E2E passed:`, JSON.stringify(probeResult)); +} finally { + await closeBrowserResources(harness, ws, server); +} diff --git a/packages/frontend/hosts/web/scripts/verify-preview-workers-e2e.mjs b/packages/frontend/hosts/web/scripts/verify-preview-workers-e2e.mjs new file mode 100644 index 0000000000..7bc2ff09a7 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/verify-preview-workers-e2e.mjs @@ -0,0 +1,657 @@ +#!/usr/bin/env node +// @ts-check + +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { Worker as NodeWorker } from 'node:worker_threads'; + +import { createWorkerLoader } from '../src/worker-loader.js'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const ASSETS_DIR = join(WEB_ROOT, 'assets'); + +/** + * Builds a PDF with one 300x200 page per fill operator. `padBytes` adds an + * unreferenced stream object of that size, so large inputs make the worker + * grow its linear memory. + * + * @param {string[]} pageFills + * @param {number} [padBytes=0] + * @returns {Uint8Array} + */ +function buildPdf(pageFills, padBytes = 0) { + const bodies = [ + '<< /Type /Catalog /Pages 2 0 R >>', + `<< /Type /Pages /Kids [${pageFills.map((_, i) => `${3 + i * 2} 0 R`).join(' ')}] /Count ${pageFills.length} >>`, + ]; + for (const [i, fill] of pageFills.entries()) { + const stream = `${fill} 0 0 300 200 re f\n`; + bodies.push( + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents ${4 + i * 2} 0 R >>`, + `<< /Length ${stream.length} >>\nstream\n${stream}endstream` + ); + } + const chunks = [Buffer.from('%PDF-1.4\n', 'ascii')]; + let length = chunks[0].length; + const offsets = []; + const push = buf => { + chunks.push(buf); + length += buf.length; + }; + for (const [i, body] of bodies.entries()) { + offsets.push(length); + push(Buffer.from(`${i + 1} 0 obj\n${body}\nendobj\n`, 'ascii')); + } + if (padBytes > 0) { + offsets.push(length); + push( + Buffer.from( + `${bodies.length + 1} 0 obj\n<< /Length ${padBytes} >>\nstream\n`, + 'ascii' + ) + ); + push(Buffer.alloc(padBytes, 0x20)); + push(Buffer.from('\nendstream\nendobj\n', 'ascii')); + } + const xrefAt = length; + const size = offsets.length + 1; + push( + Buffer.from( + `xref\n0 ${size}\n0000000000 65535 f \n` + + offsets.map(o => `${String(o).padStart(10, '0')} 00000 n \n`).join('') + + `trailer\n<< /Size ${size} /Root 1 0 R >>\nstartxref\n${xrefAt}\n%%EOF\n`, + 'ascii' + ) + ); + return new Uint8Array(Buffer.concat(chunks)); +} + +/** + * Serves only staged static files under `hosts/web/assets/`. + * + * @param {string | URL} url + */ +async function staticAssetsFetch(url) { + const parsed = new URL(String(url)); + if (!parsed.pathname.startsWith('/assets/')) { + return { + ok: false, + status: 404, + arrayBuffer: async () => new ArrayBuffer(0), + }; + } + const relPath = parsed.pathname.slice('/assets/'.length); + const filePath = join(ASSETS_DIR, relPath); + const buf = readFileSync(filePath); + return { + ok: true, + status: 200, + arrayBuffer: async () => + buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength), + }; +} + +const indexHtml = readFileSync(join(WEB_ROOT, 'index.html'), 'utf8'); +const manifestMatch = indexHtml.match( + / + + diff --git a/packages/frontend/hosts/web/src/a11y.js b/packages/frontend/hosts/web/src/a11y.js new file mode 100644 index 0000000000..c70e38bc72 --- /dev/null +++ b/packages/frontend/hosts/web/src/a11y.js @@ -0,0 +1,404 @@ +// @ts-check + +/** + * First-frame discoverable write-only accessibility semantic subtree for the + * Web Mobile thin host (`#a11y-tree`). + * + * - Exposes a discoverable initial semantic entry on frame 1 without waiting + * for screen-reader detection heuristics. + * - Incrementally patches `role`, `aria-label`, `aria-selected`, and `tabindex` + * on non-visual DOM nodes inside `#a11y-tree`. + * - Enforces strict focus mutual exclusion across `#a11y-tree`, `#ime`, and + * `#embed-layer` to prevent screen-reader double announcements. + */ + +/** + * @typedef {'none' | 'a11y' | 'ime' | 'embed'} FocusOwner + */ + +/** + * @typedef {Object} A11yNodeDescriptor + * @property {string} id + * @property {string} role + * @property {string} label + * @property {boolean} [selected] + * @property {number} [tabIndex] + * @property {string | null} [parentId] + * @property {boolean} [expanded] + * @property {boolean} [disabled] + */ + +/** + * @typedef {Object} A11yPatchOp + * @property {'upsert' | 'remove'} op + * @property {string} id + * @property {A11yNodeDescriptor} [node] + */ + +const DEFAULT_ENTRY_ID = 'workspace-entry'; + +/** + * @param {HTMLElement | null | undefined} el + * @param {string} name + * @param {string | null} value + */ +function setOrRemoveAttr(el, name, value) { + if (!el) { + return; + } + if (value === null || value === undefined) { + el.removeAttribute?.(name); + } else { + el.setAttribute?.(name, value); + } +} + +/** + * Creates the write-only ARIA semantic subtree controller bound to `#a11y-tree`, + * `#ime`, and `#embed-layer`. + * + * @param {Object} options + * @param {Document} options.doc + * @param {HTMLElement} options.root + * @param {HTMLTextAreaElement | null} [options.ime] + * @param {HTMLElement | null} [options.embedLayer] + * @param {string} [options.workspaceLabel='AFFiNE workspace'] + */ +export function createA11yTree(options) { + const { doc, root } = options; + const ime = options.ime || null; + const embedLayer = options.embedLayer || null; + const workspaceLabel = options.workspaceLabel || 'AFFiNE workspace'; + + /** @type {Map} */ + const nodes = new Map(); + /** @type {FocusOwner} */ + let focusOwner = 'a11y'; + /** @type {string | null} */ + let activeNodeId = null; + + /** + * Applies incremental attribute updates to a single semantic node. + * + * @param {HTMLElement} el + * @param {A11yNodeDescriptor} prev + * @param {A11yNodeDescriptor} next + */ + function patchAttributes(el, prev, next) { + if (prev.role !== next.role) { + setOrRemoveAttr(el, 'role', next.role); + } + if (prev.label !== next.label) { + setOrRemoveAttr(el, 'aria-label', next.label); + } + if (prev.selected !== next.selected) { + setOrRemoveAttr( + el, + 'aria-selected', + next.selected === undefined ? null : String(Boolean(next.selected)) + ); + } + if (prev.expanded !== next.expanded) { + setOrRemoveAttr( + el, + 'aria-expanded', + next.expanded === undefined ? null : String(Boolean(next.expanded)) + ); + } + if (prev.disabled !== next.disabled) { + setOrRemoveAttr( + el, + 'aria-disabled', + next.disabled === undefined ? null : String(Boolean(next.disabled)) + ); + } + const nextTabIndex = + typeof next.tabIndex === 'number' ? next.tabIndex : undefined; + const prevTabIndex = + typeof prev.tabIndex === 'number' ? prev.tabIndex : undefined; + const a11yActive = focusOwner === 'a11y' || focusOwner === 'none'; + if (!a11yActive) { + setOrRemoveAttr(el, 'tabindex', '-1'); + } else if (prevTabIndex !== nextTabIndex) { + setOrRemoveAttr( + el, + 'tabindex', + nextTabIndex === undefined ? null : String(nextTabIndex) + ); + } + } + + /** + * Upserts a semantic node by ID using incremental attribute diffing. + * + * @param {A11yNodeDescriptor} descriptor + */ + function upsertNode(descriptor) { + const existing = nodes.get(descriptor.id); + if (existing) { + patchAttributes(existing.el, existing.state, descriptor); + if (existing.state.parentId !== descriptor.parentId) { + const nextParent = + (descriptor.parentId && nodes.get(descriptor.parentId)?.el) || root; + nextParent.append(existing.el); + } + existing.state = { ...descriptor }; + return existing.el; + } + + const el = doc.createElement('div'); + setOrRemoveAttr(el, 'data-a11y-id', descriptor.id); + setOrRemoveAttr(el, 'role', descriptor.role); + setOrRemoveAttr(el, 'aria-label', descriptor.label); + if (descriptor.selected !== undefined) { + setOrRemoveAttr( + el, + 'aria-selected', + String(Boolean(descriptor.selected)) + ); + } + if (descriptor.expanded !== undefined) { + setOrRemoveAttr( + el, + 'aria-expanded', + String(Boolean(descriptor.expanded)) + ); + } + if (descriptor.disabled !== undefined) { + setOrRemoveAttr( + el, + 'aria-disabled', + String(Boolean(descriptor.disabled)) + ); + } + const a11yActive = focusOwner === 'a11y' || focusOwner === 'none'; + if (!a11yActive) { + setOrRemoveAttr(el, 'tabindex', '-1'); + } else if (typeof descriptor.tabIndex === 'number') { + setOrRemoveAttr(el, 'tabindex', String(descriptor.tabIndex)); + } + + const parent = + (descriptor.parentId && nodes.get(descriptor.parentId)?.el) || root; + parent.append(el); + nodes.set(descriptor.id, { el, state: { ...descriptor } }); + return el; + } + + /** + * Removes a semantic node by ID. + * + * @param {string} id + */ + function removeNode(id) { + const entry = nodes.get(id); + if (!entry) { + return false; + } + entry.el.remove?.(); + const toRemove = new Set([id]); + let grew = true; + while (grew) { + grew = false; + for (const [childId, childEntry] of nodes.entries()) { + if ( + !toRemove.has(childId) && + childEntry.state.parentId && + toRemove.has(childEntry.state.parentId) + ) { + toRemove.add(childId); + grew = true; + } + } + } + for (const removedId of toRemove) { + nodes.delete(removedId); + if (activeNodeId === removedId) { + activeNodeId = null; + } + } + return true; + } + + /** + * Applies an ordered batch of incremental upsert/remove patch operations. + * + * @param {A11yPatchOp[]} ops + */ + function patch(ops) { + for (const item of ops) { + if (item.op === 'upsert' && item.node) { + upsertNode(item.node); + } else if (item.op === 'remove') { + removeNode(item.id); + } + } + } + + /** + * Synchronizes `tabindex` on semantic child nodes when `#a11y-tree` enters or + * leaves exclusive focus ownership so real keyboard `Tab`/`Shift+Tab` never + * reaches hidden semantic nodes. + * + * @param {boolean} active + */ + function syncChildTabIndexes(active) { + for (const entry of nodes.values()) { + if (active) { + setOrRemoveAttr( + entry.el, + 'tabindex', + typeof entry.state.tabIndex === 'number' + ? String(entry.state.tabIndex) + : null + ); + } else { + setOrRemoveAttr(entry.el, 'tabindex', '-1'); + } + } + } + + /** + * Synchronizes `inert` and iframe `tabindex` on `#embed-layer` so inactive + * embeds are unreachable by keyboard Tab order. + * + * @param {boolean} active + */ + function syncEmbedInteractivity(active) { + if (!embedLayer) { + return; + } + embedLayer.inert = !active; + const children = embedLayer.children ? Array.from(embedLayer.children) : []; + for (const child of children) { + if (child && typeof child.setAttribute === 'function') { + if (active) { + child.removeAttribute?.('tabindex'); + } else { + child.setAttribute('tabindex', '-1'); + } + } + } + } + + /** + * Switches exclusive focus ownership among `'a11y'`, `'ime'`, `'embed'`, and + * `'none'` so screen readers and keyboard Tab order never expose two surfaces + * simultaneously. + * + * @param {FocusOwner} nextOwner + */ + function setFocusOwner(nextOwner) { + focusOwner = nextOwner; + + if (nextOwner === 'ime') { + root.inert = true; + setOrRemoveAttr(root, 'aria-hidden', 'true'); + syncChildTabIndexes(false); + setOrRemoveAttr(embedLayer, 'aria-hidden', 'true'); + syncEmbedInteractivity(false); + setOrRemoveAttr(ime, 'aria-hidden', null); + if (ime) { + ime.tabIndex = 0; + ime.readOnly = false; + } + return; + } + + if (nextOwner === 'embed') { + root.inert = true; + setOrRemoveAttr(root, 'aria-hidden', 'true'); + syncChildTabIndexes(false); + setOrRemoveAttr(ime, 'aria-hidden', 'true'); + setOrRemoveAttr(embedLayer, 'aria-hidden', null); + syncEmbedInteractivity(true); + if (ime) { + ime.tabIndex = -1; + ime.readOnly = true; + ime.blur?.(); + } + return; + } + + if (nextOwner === 'a11y') { + root.inert = false; + setOrRemoveAttr(root, 'aria-hidden', null); + syncChildTabIndexes(true); + setOrRemoveAttr(ime, 'aria-hidden', 'true'); + setOrRemoveAttr(embedLayer, 'aria-hidden', 'true'); + syncEmbedInteractivity(false); + if (ime) { + ime.tabIndex = -1; + ime.blur?.(); + } + return; + } + + root.inert = false; + setOrRemoveAttr(root, 'aria-hidden', null); + syncChildTabIndexes(true); + setOrRemoveAttr(ime, 'aria-hidden', null); + setOrRemoveAttr(embedLayer, 'aria-hidden', null); + syncEmbedInteractivity(true); + if (ime) { + ime.tabIndex = 0; + ime.readOnly = false; + } + } + + /** + * Keyboard-reachable entry point that returns exclusive focus to the + * workspace semantic entry node (`DEFAULT_ENTRY_ID`). + */ + function activateA11yEntry() { + return focusNode(DEFAULT_ENTRY_ID); + } + + /** + * Moves exclusive focus to a specific semantic node inside `#a11y-tree`. + * + * @param {string} id + * @returns {boolean} + */ + function focusNode(id) { + const entry = nodes.get(id); + if (!entry) { + return false; + } + setFocusOwner('a11y'); + activeNodeId = id; + if (entry.state.tabIndex === undefined) { + setOrRemoveAttr(entry.el, 'tabindex', '0'); + entry.state.tabIndex = 0; + } + entry.el.focus?.({ preventScroll: true }); + return true; + } + + // Mount the first-frame discoverable semantic entry immediately without + // relying on screen-reader detection heuristics. + setOrRemoveAttr(root, 'role', 'application'); + setOrRemoveAttr(root, 'aria-label', workspaceLabel); + upsertNode({ + id: DEFAULT_ENTRY_ID, + role: 'main', + label: workspaceLabel, + tabIndex: 0, + }); + setFocusOwner('a11y'); + + return { + root, + defaultEntryId: DEFAULT_ENTRY_ID, + patch, + upsertNode, + removeNode, + setFocusOwner, + focusNode, + activateA11yEntry, + getFocusOwner: () => focusOwner, + getActiveNodeId: () => activeNodeId, + getNode: id => nodes.get(id)?.el || null, + nodeCount: () => nodes.size, + }; +} diff --git a/packages/frontend/hosts/web/src/default-app-entry.js b/packages/frontend/hosts/web/src/default-app-entry.js new file mode 100644 index 0000000000..5ff4aba956 --- /dev/null +++ b/packages/frontend/hosts/web/src/default-app-entry.js @@ -0,0 +1,884 @@ +// @ts-check + +import { + createSelectionOverlayController, + drawSelectionOverlay, + SELECTION_MENU_FONT, +} from './selection-overlay.js'; + +/** + * Default thin-host entry module referenced by `index.html`. + * Presents a first-frame clear on `#app-canvas` (WebGPU, then WebGL2, then 2D) + * before calling `host.markFirstFrameReady()` to remove `#boot`. + * Wires `webglcontextrestored`, WebGPU-to-WebGL2 replacement-canvas downgrade, + * and canvas-drawn selection overlay pointer/clipboard handling directly on + * `#app-canvas`. + */ + +const VERT_SRC = `#version 300 es +in vec2 a_pos; +out vec2 v_uv; +void main() { + v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5); + gl_Position = vec4(a_pos, 0.0, 1.0); +}`; + +const FRAG_SRC = `#version 300 es +precision mediump float; +in vec2 v_uv; +uniform sampler2D u_tex; +out vec4 outColor; +void main() { + outColor = texture(u_tex, v_uv); +}`; + +/** + * Uploads a 2D offscreen canvas onto a WebGL2 `#app-canvas` via a full-screen + * textured quad. Falls back to `gl.clear(...)` when minimal mock contexts omit + * shader methods. + * + * @param {WebGL2RenderingContext} gl + * @param {HTMLCanvasElement | OffscreenCanvas | null} sourceCanvas + * @returns {boolean} + */ +function presentWebGl2Frame(gl, sourceCanvas) { + if (!sourceCanvas) { + gl.clearColor?.(0.078, 0.078, 0.078, 1); + gl.clear?.(gl.COLOR_BUFFER_BIT ?? 0x4000); + return true; + } + if ( + typeof gl.createShader !== 'function' || + typeof gl.createProgram !== 'function' || + typeof gl.createTexture !== 'function' || + typeof gl.texImage2D !== 'function' || + typeof gl.drawArrays !== 'function' + ) { + return false; + } + + /** @type {any} */ + const cache = gl; + let state = cache.__affineQuadState; + if (!state || gl.isContextLost?.()) { + const vs = gl.createShader(gl.VERTEX_SHADER); + const fs = gl.createShader(gl.FRAGMENT_SHADER); + const prog = gl.createProgram(); + const buf = gl.createBuffer(); + const tex = gl.createTexture(); + if (!vs || !fs || !prog || !buf || !tex) { + return false; + } + gl.shaderSource(vs, VERT_SRC); + gl.compileShader(vs); + gl.shaderSource(fs, FRAG_SRC); + gl.compileShader(fs); + gl.attachShader(prog, vs); + gl.attachShader(prog, fs); + gl.linkProgram(prog); + gl.bindBuffer(gl.ARRAY_BUFFER, buf); + gl.bufferData( + gl.ARRAY_BUFFER, + new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), + gl.STATIC_DRAW + ); + state = { + prog, + buf, + tex, + posLoc: gl.getAttribLocation(prog, 'a_pos'), + }; + cache.__affineQuadState = state; + } + + gl.viewport?.(0, 0, gl.drawingBufferWidth || 1, gl.drawingBufferHeight || 1); + gl.useProgram(state.prog); + gl.bindBuffer(gl.ARRAY_BUFFER, state.buf); + gl.enableVertexAttribArray(state.posLoc); + gl.vertexAttribPointer(state.posLoc, 2, gl.FLOAT, false, 0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, state.tex); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D( + gl.TEXTURE_2D, + 0, + gl.RGBA, + gl.RGBA, + gl.UNSIGNED_BYTE, + /** @type {TexImageSource} */ (sourceCanvas) + ); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + return true; +} + +/** + * Clears or composites `#app-canvas` with WebGL2 or 2D fallback. + * + * @param {HTMLCanvasElement} canvas + * @param {HTMLCanvasElement | OffscreenCanvas | null} [sourceCanvas] + * @returns {boolean} + */ +function paintWebGl2Or2d(canvas, sourceCanvas = null) { + if (typeof canvas.getContext !== 'function') { + return false; + } + const gl = /** @type {WebGL2RenderingContext | null} */ ( + canvas.getContext('webgl2') + ); + if (gl) { + return presentWebGl2Frame(gl, sourceCanvas); + } + + const ctx2d = canvas.getContext('2d'); + if (ctx2d) { + if (sourceCanvas) { + if (typeof ctx2d.drawImage !== 'function') { + return false; + } + ctx2d.clearRect?.(0, 0, canvas.width || 1, canvas.height || 1); + ctx2d.drawImage( + /** @type {CanvasImageSource} */ (sourceCanvas), + 0, + 0, + canvas.width || 1, + canvas.height || 1 + ); + return true; + } + ctx2d.fillStyle = '#141414'; + ctx2d.fillRect(0, 0, canvas.width || 1, canvas.height || 1); + return true; + } + return false; +} + +/** + * Replaces a WebGPU-locked `` with a fresh DOM canvas + * so WebGL2 context creation succeeds after WebGPU `device.lost`. + * + * @param {HTMLCanvasElement} oldCanvas + * @param {any} host + * @returns {HTMLCanvasElement} + */ +function replaceCanvasForWebGl2Fallback(oldCanvas, host) { + const doc = globalThis.document; + if (!doc || typeof doc.createElement !== 'function') { + return oldCanvas; + } + const fresh = doc.createElement('canvas'); + fresh.id = oldCanvas.id || 'app-canvas'; + fresh.setAttribute?.('aria-hidden', 'true'); + const dpr = Math.max(1, globalThis.window?.devicePixelRatio || 1); + const hasExplicitSize = + oldCanvas.width > 0 && + oldCanvas.height > 0 && + !(oldCanvas.width === 300 && oldCanvas.height === 150); + if (hasExplicitSize) { + fresh.width = oldCanvas.width; + fresh.height = oldCanvas.height; + } else if (globalThis.window?.innerWidth && globalThis.window?.innerHeight) { + fresh.width = Math.max(1, Math.round(globalThis.window.innerWidth * dpr)); + fresh.height = Math.max(1, Math.round(globalThis.window.innerHeight * dpr)); + } else { + fresh.width = oldCanvas.width || 300; + fresh.height = oldCanvas.height || 150; + } + if (typeof oldCanvas.replaceWith === 'function') { + oldCanvas.replaceWith(fresh); + } + host.bindCanvas?.(fresh); + return fresh; +} + +/** + * Presents a 2D surface or clear frame on a configured WebGPU canvas. + * + * @param {{ device: any, context: any, canvas: HTMLCanvasElement }} webGpuState + * @param {HTMLCanvasElement | OffscreenCanvas | null} sourceCanvas + * @returns {boolean} + */ +function presentWebGpuFrame(webGpuState, sourceCanvas) { + const { device, context } = webGpuState; + const texture = context.getCurrentTexture?.(); + if (!texture) { + return false; + } + if (sourceCanvas) { + if ( + typeof device.queue?.copyExternalImageToTexture !== 'function' || + typeof device.createCommandEncoder !== 'function' || + typeof device.queue?.submit !== 'function' + ) { + return false; + } + device.queue.copyExternalImageToTexture( + { source: sourceCanvas }, + { texture }, + { + width: sourceCanvas.width || webGpuState.canvas.width || 1, + height: sourceCanvas.height || webGpuState.canvas.height || 1, + } + ); + const encoder = device.createCommandEncoder(); + if (!encoder) { + return false; + } + device.queue.submit([encoder.finish()]); + return true; + } + const encoder = device.createCommandEncoder?.(); + if (encoder && typeof device.queue?.submit === 'function') { + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: texture.createView(), + loadOp: 'clear', + storeOp: 'store', + clearValue: { r: 0.078, g: 0.078, b: 0.078, a: 1 }, + }, + ], + }); + pass.end(); + device.queue.submit([encoder.finish()]); + return true; + } + return false; +} + +/** + * Creates an offscreen 2D staging canvas never mounted in the DOM. + * + * @param {number} width + * @param {number} height + * @returns {HTMLCanvasElement | OffscreenCanvas | null} + */ +function createOffscreenSurface(width, height) { + if (typeof OffscreenCanvas === 'function') { + return new OffscreenCanvas(width, height); + } + const doc = globalThis.document; + if (doc && typeof doc.createElement === 'function') { + const c = doc.createElement('canvas'); + c.width = width; + c.height = height; + return c; + } + return null; +} + +/** + * @param {HTMLCanvasElement} canvas + * @param {any} host + * @param {() => HTMLCanvasElement | OffscreenCanvas | null} getSourceCanvas + * @param {(nextCanvas: HTMLCanvasElement) => void} onCanvasReplaced + * @param {(state: { device: any, context: any, canvas: HTMLCanvasElement } | null) => void} setWebGpuState + * @returns {Promise} + */ +async function presentFirstFrameClear( + canvas, + host, + getSourceCanvas, + onCanvasReplaced, + setWebGpuState +) { + const gpu = + /** @type {{ requestAdapter?: () => Promise, getPreferredCanvasFormat?: () => string } | undefined} */ ( + globalThis.navigator?.gpu + ); + async function attachWebGpu(targetCanvas) { + if (!gpu || typeof gpu.requestAdapter !== 'function') { + return false; + } + const adapter = await gpu.requestAdapter(); + const device = adapter ? await adapter.requestDevice() : null; + const context = device ? targetCanvas.getContext('webgpu') : null; + if (!device || !context || typeof context.configure !== 'function') { + return false; + } + host.bindWebGpuDevice?.(device, { + tryRebuildWebGpu: async () => { + setWebGpuState(null); + return attachWebGpu(host.canvas || targetCanvas); + }, + tryWebGl2Fallback: () => { + setWebGpuState(null); + const nextCanvas = replaceCanvasForWebGl2Fallback( + host.canvas || targetCanvas, + host + ); + onCanvasReplaced(nextCanvas); + return paintWebGl2Or2d(nextCanvas, getSourceCanvas()); + }, + }); + const renderAttachment = + globalThis.GPUTextureUsage?.RENDER_ATTACHMENT ?? 0x10; + const copyDst = globalThis.GPUTextureUsage?.COPY_DST ?? 0x02; + context.configure({ + device, + format: gpu.getPreferredCanvasFormat?.() || 'bgra8unorm', + usage: renderAttachment | copyDst, + }); + const gpuState = { device, context, canvas: targetCanvas }; + if (presentWebGpuFrame(gpuState, getSourceCanvas())) { + setWebGpuState(gpuState); + return true; + } + return false; + } + + if (gpu && typeof gpu.requestAdapter === 'function') { + try { + if (await attachWebGpu(canvas)) { + return true; + } + } catch { + setWebGpuState(null); + // Fall through to WebGL2 or 2D clear. + } + } + + return paintWebGl2Or2d(canvas, getSourceCanvas()); +} + +/** + * Attaches the canvas-drawn selection overlay controller and pointer listeners + * directly to `#app-canvas` for production `index.html`. + * + * @param {any} host + */ +function attachSelectionOverlayRuntime(host) { + /** @type {HTMLCanvasElement | OffscreenCanvas | null} */ + let stageSurface = null; + /** @type {{ device: any, context: any, canvas: HTMLCanvasElement } | null} */ + let webGpuState = null; + /** @type {((ctx: CanvasRenderingContext2D, vw: number, vh: number) => void) | null} */ + let scenePainter = null; + /** @type {any} */ + let selectionInput = null; + /** @type {'light' | 'dark'} */ + let overlayTheme = 'light'; + /** @type {{ getSelectedText?: () => string, getSelectionToken?: () => unknown, deleteSelection?: (captured?: unknown) => void, insertText?: (t: string) => void, selectAll?: () => void, onDragHandle?: (h: 'start' | 'end', x: number, y: number) => void, onActionResult?: (r: any) => void, clipboard?: any, isSecureContext?: boolean } | null} */ + let selectionCallbacks = null; + /** @type {HTMLCanvasElement | null} */ + let pointerCanvas = null; + let sceneEpoch = 0; + + /** + * Presents `surface` to `activeCanvas` via WebGPU (with automatic + * replacement-canvas fallback to WebGL2/2D when needed) or WebGL2/2D. + * + * @param {HTMLCanvasElement} activeCanvas + * @param {HTMLCanvasElement | OffscreenCanvas | null} surface + * @returns {boolean} + */ + function presentSurface(activeCanvas, surface) { + if (webGpuState && webGpuState.canvas === activeCanvas) { + try { + if (presentWebGpuFrame(webGpuState, surface)) { + return true; + } + } catch { + // Fall back to a fresh WebGL2/2D canvas below. + } + webGpuState = null; + const nextCanvas = replaceCanvasForWebGl2Fallback(activeCanvas, host); + bindPointerCanvas(nextCanvas); + return paintWebGl2Or2d(nextCanvas, surface); + } + return paintWebGl2Or2d(activeCanvas, surface); + } + + function renderCompositeFrame() { + const activeCanvas = host.canvas; + if (!activeCanvas) { + return false; + } + if (!scenePainter && !selectionInput) { + return presentSurface(activeCanvas, null); + } + const dpr = Math.max(1, globalThis.window?.devicePixelRatio || 1); + const vw = + globalThis.window?.innerWidth || + Math.max(1, Math.round((activeCanvas.width || 390) / dpr)); + const vh = + globalThis.window?.innerHeight || + Math.max(1, Math.round((activeCanvas.height || 844) / dpr)); + const pixelW = Math.max(1, Math.round(vw * dpr)); + const pixelH = Math.max(1, Math.round(vh * dpr)); + if (activeCanvas.width !== pixelW || activeCanvas.height !== pixelH) { + activeCanvas.width = pixelW; + activeCanvas.height = pixelH; + } + if ( + !stageSurface || + stageSurface.width !== pixelW || + stageSurface.height !== pixelH + ) { + stageSurface = createOffscreenSurface(pixelW, pixelH); + } + if (!stageSurface) { + return false; + } + const ctx = /** @type {CanvasRenderingContext2D | null} */ ( + stageSurface.getContext('2d') + ); + if (!ctx) { + return false; + } + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + if (scenePainter) { + scenePainter(ctx, vw, vh); + } else { + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, vw, vh); + } + const layout = selectionController.getLayout(); + if (layout) { + drawSelectionOverlay(ctx, layout, { + theme: overlayTheme, + activeActionId: selectionController.getActiveActionId(), + }); + } + return presentSurface(activeCanvas, stageSurface); + } + + /** @param {string} label */ + function measureMenuLabel(label) { + const ctx = /** @type {CanvasRenderingContext2D | null} */ ( + stageSurface?.getContext?.('2d') ?? null + ); + if (!ctx || typeof ctx.measureText !== 'function') { + return Number.NaN; + } + ctx.save?.(); + ctx.font = SELECTION_MENU_FONT; + const width = ctx.measureText(label)?.width ?? Number.NaN; + ctx.restore?.(); + return width; + } + + const selectionController = createSelectionOverlayController({ + getInput: () => { + if (!selectionInput) { + return null; + } + const explicitLocale = + typeof selectionInput.locale === 'string' + ? selectionInput.locale.trim() + : ''; + let resolvedLocale = explicitLocale; + if (!resolvedLocale) { + resolvedLocale = host?.getPreferredLocale?.() || ''; + } + if (!resolvedLocale) { + try { + resolvedLocale = globalThis.navigator?.language || ''; + } catch { + resolvedLocale = ''; + } + } + return { + ...selectionInput, + locale: resolvedLocale || undefined, + }; + }, + measureText: measureMenuLabel, + onDragHandle: (handle, x, y) => { + selectionCallbacks?.onDragHandle?.(handle, x, y); + }, + onAction: async action => { + const activeCallbacks = selectionCallbacks; + if (!activeCallbacks) { + return null; + } + const actionEpoch = sceneEpoch; + const isActiveScene = () => + sceneEpoch === actionEpoch && selectionCallbacks === activeCallbacks; + const res = await host.executeClipboardAction({ + action, + getSelectedText: () => + isActiveScene() && activeCallbacks.getSelectedText + ? activeCallbacks.getSelectedText() + : '', + getSelectionToken: + typeof activeCallbacks.getSelectionToken === 'function' + ? () => + isActiveScene() + ? activeCallbacks.getSelectionToken() + : Symbol('stale-scene') + : undefined, + deleteSelection: + typeof activeCallbacks.deleteSelection === 'function' + ? arg => { + if (isActiveScene()) { + activeCallbacks.deleteSelection(arg); + } + } + : undefined, + insertText: + typeof activeCallbacks.insertText === 'function' + ? text => { + if (isActiveScene()) { + activeCallbacks.insertText(text); + } + } + : undefined, + selectAll: + typeof activeCallbacks.selectAll === 'function' + ? () => { + if (isActiveScene()) { + activeCallbacks.selectAll(); + } + } + : undefined, + clipboard: activeCallbacks.clipboard, + isSecureContext: activeCallbacks.isSecureContext, + }); + if (!isActiveScene()) { + return res; + } + activeCallbacks.onActionResult?.(res); + renderCompositeFrame(); + return res; + }, + onLayoutChange: () => { + renderCompositeFrame(); + }, + }); + + /** @param {PointerEvent} event */ + function toCanvasCoords(event) { + const rect = pointerCanvas?.getBoundingClientRect?.(); + return { + x: event.clientX - (rect?.left ?? 0), + y: event.clientY - (rect?.top ?? 0), + }; + } + + /** @param {PointerEvent} event */ + function handlePointerDown(event) { + const { x, y } = toCanvasCoords(event); + const res = selectionController.onPointerDown(x, y); + if (res.handled) { + if ( + selectionController.isDragging?.() && + typeof event.pointerId === 'number' + ) { + try { + pointerCanvas?.setPointerCapture?.(event.pointerId); + } catch { + // Ignore synthetic events without active pointer id. + } + } + event.preventDefault?.(); + } + } + + /** @param {PointerEvent} event */ + function handlePointerMove(event) { + const { x, y } = toCanvasCoords(event); + if (selectionController.onPointerMove(x, y)) { + event.preventDefault?.(); + } + } + + /** @param {PointerEvent} event */ + function handlePointerUp(event) { + if (typeof event.pointerId === 'number') { + try { + pointerCanvas?.releasePointerCapture?.(event.pointerId); + } catch { + // Ignore when pointer was not captured. + } + } + const { x, y } = toCanvasCoords(event); + const res = selectionController.onPointerUp(x, y); + if (res.handled) { + event.preventDefault?.(); + } + } + + function handlePointerCancel() { + selectionController.onPointerCancel(); + } + + function handleViewportResize() { + renderCompositeFrame(); + } + + globalThis.window?.addEventListener?.('resize', handleViewportResize); + globalThis.window?.addEventListener?.( + 'orientationchange', + handleViewportResize + ); + globalThis.window?.visualViewport?.addEventListener?.( + 'resize', + handleViewportResize + ); + + /** @param {HTMLCanvasElement | null} nextCanvas */ + function bindPointerCanvas(nextCanvas) { + if (pointerCanvas === nextCanvas) { + return; + } + if ( + pointerCanvas && + typeof pointerCanvas.removeEventListener === 'function' + ) { + pointerCanvas.removeEventListener('pointerdown', handlePointerDown); + pointerCanvas.removeEventListener('pointermove', handlePointerMove); + pointerCanvas.removeEventListener('pointerup', handlePointerUp); + pointerCanvas.removeEventListener('pointercancel', handlePointerCancel); + pointerCanvas.removeEventListener( + 'lostpointercapture', + handlePointerCancel + ); + } + pointerCanvas = nextCanvas; + if (pointerCanvas && typeof pointerCanvas.addEventListener === 'function') { + pointerCanvas.addEventListener('pointerdown', handlePointerDown); + pointerCanvas.addEventListener('pointermove', handlePointerMove); + pointerCanvas.addEventListener('pointerup', handlePointerUp); + pointerCanvas.addEventListener('pointercancel', handlePointerCancel); + pointerCanvas.addEventListener('lostpointercapture', handlePointerCancel); + } + } + + host.selectionOverlay = { + controller: selectionController, + /** + * Configures the canvas scene painter and optional selection overlay input, + * then composites the frame onto `#app-canvas`. Clears interactive + * selection state if presenting fails so invisible buttons cannot be hit. + * + * @param {{ paint?: ((ctx: CanvasRenderingContext2D, vw: number, vh: number) => void) | null, selection?: any, theme?: 'light' | 'dark', callbacks?: any }} config + */ + setScene(config) { + sceneEpoch += 1; + scenePainter = config.paint ?? null; + selectionInput = config.selection ?? null; + overlayTheme = config.theme || 'light'; + selectionCallbacks = config.callbacks ?? null; + const presented = renderCompositeFrame(); + if (!presented) { + selectionInput = null; + selectionCallbacks = null; + host.setSelectionOverlayActive?.(false); + return false; + } + host.setSelectionOverlayActive?.(Boolean(selectionInput)); + return true; + }, + renderFrame: renderCompositeFrame, + getLayout: () => selectionController.getLayout(), + }; + + return { + bindPointerCanvas, + renderCompositeFrame, + getSourceCanvas: () => stageSurface, + setWebGpuState: state => { + webGpuState = state; + }, + dispose() { + bindPointerCanvas(null); + globalThis.window?.removeEventListener?.('resize', handleViewportResize); + globalThis.window?.removeEventListener?.( + 'orientationchange', + handleViewportResize + ); + globalThis.window?.visualViewport?.removeEventListener?.( + 'resize', + handleViewportResize + ); + }, + }; +} + +/** + * Renders a live Wasm `PageSnapshot` onto `#app-canvas` through the standard + * `selectionOverlay.setScene(...)` pipeline so local documents hydrated from + * IndexedDB paint real title and paragraph content on Frame 1. + * + * @param {any} host + * @param {{ docId: string, getSnapshot: () => { docId: string, title: string, blocks: Array<{ text: string, depth: number }> } }} docSession + * @returns {boolean} + */ +function renderLocalDocScene(host, docSession, preloadedSnapshot = null) { + if (!host?.selectionOverlay?.setScene || !docSession) { + return false; + } + const snap = preloadedSnapshot ?? docSession.getSnapshot(); + const title = snap.title || snap.docId || 'Untitled'; + const blocks = Array.isArray(snap.blocks) ? snap.blocks : []; + return host.selectionOverlay.setScene({ + theme: 'light', + selection: null, + paint(ctx, vw, vh) { + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, vw, vh); + ctx.fillStyle = '#0f172a'; + ctx.fillRect(0, 0, vw, 64); + ctx.fillStyle = '#ffffff'; + ctx.font = '700 16px -apple-system, sans-serif'; + ctx.fillText(title, 20, 40); + ctx.fillStyle = '#334155'; + ctx.font = '400 14px -apple-system, sans-serif'; + let y = 96; + const maxWidth = Math.max(120, vw - 48); + for (const blk of blocks) { + const indent = Math.min(blk.depth || 0, 6) * 18; + const text = String(blk.text || ''); + if (!text) continue; + const words = text.split(/\s+/); + let line = ''; + for (const word of words) { + const probe = line ? `${line} ${word}` : word; + if (ctx.measureText(probe).width > maxWidth - indent && line) { + ctx.fillText(line, 24 + indent, y); + y += 22; + line = word; + } else { + line = probe; + } + } + if (line) { + ctx.fillText(line, 24 + indent, y); + y += 26; + } + if (y > vh - 24) break; + } + }, + }); +} + +/** + * Resolves `host.openDoc(...)` options for the current location search string. + * Navigating to `/workspace/:wsId/:docId?create=1` (with optional `&title=...` + * and `&firstParagraph=...`) initializes a brand-new BlockSuite v3 page via + * `WasmLocalDocSession.initialize_page(...)` when the target document has no + * persisted IndexedDB frames yet. + * + * @param {string} search + * @returns {{ createIfMissing: { title: string, firstParagraph: string } } | undefined} + */ +export function resolveInitialOpenDocOptions(search) { + if (!search) { + return undefined; + } + const params = new URLSearchParams(search); + const flag = params.get('create'); + if (flag !== '1' && flag !== 'true') { + return undefined; + } + return { + createIfMissing: { + title: params.get('title') ?? 'Untitled', + firstParagraph: params.get('firstParagraph') ?? '', + }, + }; +} + +/** + * Renders a visible canvas error state when durable `host.openDoc(...)` fails, + * keeping permanent DOM strictly limited to `#app-canvas`. + * + * @param {any} host + * @param {string} docId + * @param {Error} err + * @returns {boolean} + */ +function renderLocalDocErrorScene(host, docId, err) { + if (!host?.selectionOverlay?.setScene) { + return false; + } + const detail = err?.message || String(err) || 'Failed to load document'; + return host.selectionOverlay.setScene({ + theme: 'light', + selection: null, + paint(ctx, vw, vh) { + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, vw, vh); + ctx.fillStyle = '#991b1b'; + ctx.fillRect(0, 0, vw, 64); + ctx.fillStyle = '#ffffff'; + ctx.font = '700 16px -apple-system, sans-serif'; + ctx.fillText(`Unable to open ${docId || 'document'}`, 20, 40); + ctx.fillStyle = '#7f1d1d'; + ctx.font = '400 14px -apple-system, sans-serif'; + ctx.fillText(detail.slice(0, 160), 20, 96); + }, + }); +} + +const host = /** @type {any} */ ( + globalThis.window?.__AFFINE_WEB_HOST__ ?? globalThis.__AFFINE_WEB_HOST__ +); + +let firstFrameCleared = false; +let initialDocLoaded = false; +/** @type {Error | null} */ +let initialDocError = null; +if (host) { + const overlayRuntime = attachSelectionOverlayRuntime(host); + host.onDispose?.(() => overlayRuntime.dispose()); + host.bindCanvas?.(host.canvas ?? null); + overlayRuntime.bindPointerCanvas(host.canvas ?? null); + host.setGraphicsRecoveryHooks?.({ + onContextRestored: activeCanvas => { + if (!activeCanvas) { + return false; + } + const gl = activeCanvas.getContext?.('webgl2'); + if (gl && /** @type {any} */ (gl).__affineQuadState) { + delete (/** @type {any} */ (gl).__affineQuadState); + } + return overlayRuntime.renderCompositeFrame(); + }, + }); + host.setDocumentRenderHook?.((docSession, snapshot) => { + renderLocalDocScene(host, docSession, snapshot ?? null); + }); + if (host.canvas) { + firstFrameCleared = await presentFirstFrameClear( + host.canvas, + host, + overlayRuntime.getSourceCanvas, + nextCanvas => overlayRuntime.bindPointerCanvas(nextCanvas), + state => overlayRuntime.setWebGpuState(state) + ); + } + if (firstFrameCleared && host.workspaceBound && host.activeDocId) { + if (typeof host.openDoc === 'function') { + try { + const initialOpenOpts = resolveInitialOpenDocOptions( + String(globalThis.window?.location?.search ?? '') + ); + const docSession = await host.openDoc( + host.activeDocId, + initialOpenOpts + ); + initialDocLoaded = docSession !== null && docSession !== undefined; + } catch (err) { + initialDocError = err instanceof Error ? err : new Error(String(err)); + renderLocalDocErrorScene(host, host.activeDocId, initialDocError); + } + } else { + initialDocLoaded = true; + } + } else if (firstFrameCleared) { + initialDocLoaded = true; + } + if (firstFrameCleared) { + host.markFirstFrameReady?.(); + } else { + await host.handleRuntimeGpuLoss?.(); + } +} + +export const defaultAppEntryCanvasReady = firstFrameCleared; +export const defaultAppEntryDocError = initialDocError; +export const defaultAppEntryReady = firstFrameCleared && initialDocLoaded; diff --git a/packages/frontend/hosts/web/src/host.js b/packages/frontend/hosts/web/src/host.js new file mode 100644 index 0000000000..e643d042a8 --- /dev/null +++ b/packages/frontend/hosts/web/src/host.js @@ -0,0 +1,2280 @@ +// @ts-check + +import { createA11yTree } from './a11y.js'; +import { + createIdbV1ReadonlyReader, + createIdbWorkspaceStorage, + createPendingWriteFlusher, + getLocalWorkspaceIds, + getWebPreference, + LOCAL_WORKSPACE_CHANGED_CHANNEL, + setLocalWorkspaceIds, + setWebPreference, +} from './idb-storage.js'; +import { createPdfPreviewClient } from './pdf-client.js'; +import { + attachImeSelectionGuard, + executeClipboardAction, +} from './selection-overlay.js'; +import { createWorkerLoader, readEmbeddedManifest } from './worker-loader.js'; + +/** + * @typedef {Object} SafeAreaInsets + * @property {number} top + * @property {number} right + * @property {number} bottom + * @property {number} left + */ + +/** + * @typedef {Object} GraphicsSupport + * @property {boolean} webgpu + * @property {boolean} webgl2 + * @property {boolean} supported + */ + +/** + * @typedef {Object} FlushNavigationOptions + * @property {() => void} pauseInput + * @property {() => Promise} flushPendingWrites + * @property {(url: string) => void} navigate + * @property {string} targetUrl + * @property {() => void} [resumeInput] + */ + +const SINGLE_USE_OAUTH_PARAMS = ['code', 'state']; +const ALLOWED_SANDBOX_TOKENS = new Set([ + 'allow-scripts', + 'allow-forms', + 'allow-popups', +]); + +/** + * Parses a computed CSS pixel value into a finite non-negative number. + * + * @param {string | null | undefined} value + * @returns {number} + */ +function parseCssPx(value) { + if (!value) { + return 0; + } + const num = Number.parseFloat(String(value).replace(/px$/i, '').trim()); + return Number.isFinite(num) && num >= 0 ? num : 0; +} + +/** + * Probes WebGPU and WebGL2 availability using a disposable offscreen canvas so + * the primary `#app-canvas` is never locked to a WebGL2 context before WebGPU + * initialization. + * + * @param {Document | null | undefined} doc + * @param {{ gpu?: unknown } | undefined} nav + * @returns {GraphicsSupport} + */ +export function detectGraphicsSupport(doc, nav = globalThis.navigator) { + const webgpu = Boolean(nav && nav.gpu); + let webgl2 = false; + if (doc && typeof doc.createElement === 'function') { + try { + const probeCanvas = doc.createElement('canvas'); + if (probeCanvas && typeof probeCanvas.getContext === 'function') { + probeCanvas.width = 1; + probeCanvas.height = 1; + const gl = probeCanvas.getContext('webgl2'); + if (gl) { + webgl2 = true; + gl.getExtension?.('WEBGL_lose_context')?.loseContext?.(); + } + } + } catch { + webgl2 = false; + } + } + return { + webgpu, + webgl2, + supported: webgpu || webgl2, + }; +} + +/** + * Returns true when the URL already targets the legacy shell (`?shell=legacy`). + * + * @param {string} currentHref + * @returns {boolean} + */ +export function isLegacyShellUrl(currentHref) { + try { + return new URL(currentHref).searchParams.get('shell') === 'legacy'; + } catch { + return false; + } +} + +/** + * Builds the `?shell=legacy` fallback URL while preserving query parameters + * and hash. By default (`codeConsumed = false`), single-use OAuth `code` is + * preserved untouched so the legacy shell consumes it once; when `codeConsumed` + * is `true`, `code` is stripped to prevent double consumption. + * + * @param {string} currentHref + * @param {{ codeConsumed?: boolean }} [options] + * @returns {{ url: string, oauthCodeStripped: boolean }} + */ +export function buildLegacyFallbackUrl(currentHref, options = {}) { + const codeConsumed = Boolean(options.codeConsumed); + const target = new URL(currentHref); + let oauthCodeStripped = false; + if (codeConsumed) { + for (const param of SINGLE_USE_OAUTH_PARAMS) { + if (target.searchParams.has(param)) { + target.searchParams.delete(param); + oauthCodeStripped = true; + } + } + } + target.searchParams.set('shell', 'legacy'); + return { + url: target.toString(), + oauthCodeStripped, + }; +} + +/** + * Tracks per-side safe-area insets with exact four-edge comparison. + * + * @param {(insets: SafeAreaInsets) => void} onChange + */ +export function createSafeAreaTracker(onChange) { + /** @type {SafeAreaInsets | null} */ + let last = null; + + /** + * @param {SafeAreaInsets} next + * @returns {boolean} + */ + function update(next) { + const normalized = { + top: Number.isFinite(next.top) && next.top >= 0 ? next.top : 0, + right: Number.isFinite(next.right) && next.right >= 0 ? next.right : 0, + bottom: + Number.isFinite(next.bottom) && next.bottom >= 0 ? next.bottom : 0, + left: Number.isFinite(next.left) && next.left >= 0 ? next.left : 0, + }; + const changed = + last === null || + !Object.is(last.top, normalized.top) || + !Object.is(last.right, normalized.right) || + !Object.is(last.bottom, normalized.bottom) || + !Object.is(last.left, normalized.left); + if (!changed) { + return false; + } + last = normalized; + onChange(normalized); + return true; + } + + return { + update, + /** @returns {SafeAreaInsets | null} */ + current: () => (last ? { ...last } : null), + }; +} + +/** + * Reads `[top, right, bottom, left]` safe-area CSS pixels from the single + * hidden probe element. + * + * @param {Window} win + * @param {HTMLElement} probe + * @returns {SafeAreaInsets} + */ +export function readSafeAreaProbe(win, probe) { + const computed = win.getComputedStyle(probe); + return { + top: parseCssPx(computed.getPropertyValue('padding-top')), + right: parseCssPx(computed.getPropertyValue('padding-right')), + bottom: parseCssPx(computed.getPropertyValue('padding-bottom')), + left: parseCssPx(computed.getPropertyValue('padding-left')), + }; +} + +/** + * Attaches listeners to the single `aria-hidden="true"` zero-size safe-area + * probe and notifies `onChange` whenever any individual side changes. + * + * @param {Window} win + * @param {HTMLElement} probe + * @param {(insets: SafeAreaInsets) => void} onChange + */ +export function observeSafeAreaProbe(win, probe, onChange) { + const tracker = createSafeAreaTracker(onChange); + const sample = () => tracker.update(readSafeAreaProbe(win, probe)); + + probe.addEventListener('transitionrun', sample); + probe.addEventListener('transitionend', sample); + win.addEventListener('resize', sample); + win.addEventListener('orientationchange', sample); + if (win.visualViewport) { + win.visualViewport.addEventListener('resize', sample); + win.visualViewport.addEventListener('scroll', sample); + } + + sample(); + + return { + sample, + dispose() { + probe.removeEventListener('transitionrun', sample); + probe.removeEventListener('transitionend', sample); + win.removeEventListener('resize', sample); + win.removeEventListener('orientationchange', sample); + if (win.visualViewport) { + win.visualViewport.removeEventListener('resize', sample); + win.visualViewport.removeEventListener('scroll', sample); + } + }, + }; +} + +/** + * Focuses `#ime` synchronously inside the user gesture call stack so iOS + * Safari and Android Chrome raise the software keyboard without auto-zoom. + * + * @param {HTMLTextAreaElement} imeEl + * @param {{ inputMode?: string, enterKeyHint?: string }} [options] + * @returns {boolean} + */ +export function focusImeInGesture(imeEl, options = {}) { + if (!imeEl) { + return false; + } + if (imeEl.style) { + imeEl.style.fontSize = '16px'; + } + if (options.inputMode) { + imeEl.inputMode = options.inputMode; + } + if (options.enterKeyHint) { + imeEl.enterKeyHint = options.enterKeyHint; + } + imeEl.readOnly = false; + imeEl.focus({ preventScroll: true }); + return true; +} + +/** + * Filters user HTML embed sandbox tokens through a strict allowlist + * (`allow-scripts`, `allow-forms`, `allow-popups`), defaulting to + * `allow-scripts` and unconditionally blocking `allow-same-origin` and + * `allow-top-navigation`. + * + * @param {string | undefined} rawSandbox + * @returns {string} + */ +export function sanitizeEmbedSandbox(rawSandbox) { + const requested = + rawSandbox === undefined || rawSandbox === null + ? ['allow-scripts'] + : String(rawSandbox).split(/\s+/); + const allowed = requested + .map(token => token.trim().toLowerCase()) + .filter(token => ALLOWED_SANDBOX_TOKENS.has(token)); + return [...new Set(allowed)].join(' '); +} + +/** + * Validates that an embed iframe URL matches `index.html` CSP `frame-src` + * (`blob:` or `about:blank` only). + * + * @param {string} rawSrc + * @returns {string} + */ +export function validateEmbedSrc(rawSrc) { + const trimmed = String(rawSrc || '').trim(); + if (!trimmed) { + throw new Error('Embed iframe src must be a non-empty URL'); + } + if (trimmed.toLowerCase() === 'about:blank') { + return 'about:blank'; + } + let parsed; + try { + parsed = new URL(trimmed); + } catch { + throw new Error(`Invalid embed iframe URL: ${trimmed}`); + } + if (parsed.protocol !== 'blob:') { + throw new Error(`Disallowed embed iframe protocol: ${parsed.protocol}`); + } + return trimmed; +} + +/** + * Mounts a sandboxed user HTML iframe inside `#embed-layer` with strict + * sandbox token allowlisting and `blob:`/`about:blank`-only URL validation. + * + * @param {Document} doc + * @param {HTMLElement} embedLayer + * @param {{ src: string, title?: string, sandbox?: string }} options + * @returns {HTMLIFrameElement} + */ +export function createSandboxedEmbedIframe(doc, embedLayer, options) { + const safeSrc = validateEmbedSrc(options.src); + const iframe = doc.createElement('iframe'); + iframe.setAttribute('sandbox', sanitizeEmbedSandbox(options.sandbox)); + iframe.setAttribute('referrerpolicy', 'no-referrer'); + iframe.setAttribute('title', options.title || 'Embedded content'); + iframe.src = safeSrc; + embedLayer.append(iframe); + return iframe; +} + +/** + * CRDT flush barrier executed before navigating away to login or legacy shell. + * Pauses input synchronously, awaits local persistence, and aborts navigation + * if persistence fails so pending local writes are never discarded. + * + * @param {FlushNavigationOptions} options + * @returns {Promise<{ navigated: boolean, reason?: string }>} + */ +const DEFAULT_FLUSH_TIMEOUT_MS = 8000; + +/** + * Navigates via `location.replace` (falling back to `location.assign` when a + * test mock omits `replace`) so automatic shell fallbacks do not pollute + * browser history and trap Back navigation in a redirect loop. + * + * @param {{ location?: { replace?: (url: string) => void, assign?: (url: string) => void } } | null | undefined} win + * @param {string} url + */ +function replaceLocation(win, url) { + if (typeof win?.location?.replace === 'function') { + win.location.replace(url); + } else if (typeof win?.location?.assign === 'function') { + win.location.assign(url); + } +} + +export async function flushBeforeNavigation(options) { + options.pauseInput(); + const timeoutMs = + typeof options.flushTimeoutMs === 'number' + ? options.flushTimeoutMs + : DEFAULT_FLUSH_TIMEOUT_MS; + /** @type {ReturnType | null} */ + let timeoutHandle = null; + try { + const flushPromise = options.flushPendingWrites(); + const result = + timeoutMs > 0 + ? await Promise.race([ + flushPromise, + new Promise((_resolve, reject) => { + timeoutHandle = setTimeout(() => { + reject(new Error('flush-timeout')); + }, timeoutMs); + }), + ]) + : await flushPromise; + const ok = + typeof result === 'boolean' + ? result + : Boolean( + result && + result.ok && + (result.pendingCount === undefined || result.pendingCount === 0) + ); + if (!ok) { + options.resumeInput?.(); + return { navigated: false, reason: 'flush-rejected' }; + } + } catch (error) { + options.resumeInput?.(); + const message = error instanceof Error ? error.message : String(error); + if (message === 'flush-timeout') { + return { navigated: false, reason: 'flush-timeout' }; + } + return { navigated: false, reason: `flush-error:${message}` }; + } finally { + if (timeoutHandle !== null) { + clearTimeout(timeoutHandle); + } + } + options.navigate(options.targetUrl); + return { navigated: true }; +} + +/** + * Alias for the CRDT IndexedDB flush barrier executed before shell redirect. + */ +export const flushPendingBeforeRedirect = flushBeforeNavigation; + +/** + * Removes `#boot` once the first canvas frame is ready and deduplicates any + * pre-mounted `#app-canvas` or `#ime` if the Wasm UI platform mounted its own. + * + * @param {Document} doc + */ +export function removeBootSkeleton(doc) { + const boot = doc.getElementById('boot'); + if (boot) { + boot.remove(); + } + if (typeof doc.querySelectorAll === 'function') { + const canvases = doc.querySelectorAll('canvas'); + if (canvases.length > 1) { + const hostCanvas = doc.getElementById('app-canvas'); + if (hostCanvas) { + hostCanvas.remove(); + } + } + const textareas = doc.querySelectorAll('textarea'); + if (textareas.length > 1) { + const hostIme = doc.getElementById('ime'); + if (hostIme) { + hostIme.remove(); + } + } + } +} + +/** + * Creates a deterministic graphics context recovery and legacy-fallback + * controller for `#app-canvas` WebGL2 and WebGPU devices. + * + * @param {Object} options + * @param {() => string} options.getHref + * @param {() => boolean} options.isOAuthCodeConsumed + * @param {() => HTMLCanvasElement | null} [options.getActiveCanvas] + * @param {() => void} options.pauseInput + * @param {() => void} options.resumeInput + * @param {() => void} [options.freezeFrameLoop] + * @param {() => void} [options.unfreezeFrameLoop] + * @param {() => Promise} options.flushPendingWrites + * @param {(url: string) => void} options.navigate + * @param {(message: string, opts?: { retryable?: boolean }) => void} [options.showFatal] + * @param {() => void} [options.hideFatal] + * @param {() => boolean} [options.isDocumentHidden] + * @param {(canvas: HTMLCanvasElement | null) => boolean | Promise} [options.onContextRestored] + * @param {(info: unknown) => boolean | Promise} [options.tryRebuildWebGpu] + * @param {(info: unknown) => boolean | Promise} [options.tryWebGl2Fallback] + * @param {(reason: string, targetUrl: string) => void} [options.onFallbackMarker] + * @param {number} [options.restoreTimeoutMs=4000] + * @param {number} [options.maxContextLosses=3] + * @param {number} [options.maxWebGpuLosses=2] + * @param {number} [options.lossWindowMs=30000] + * @param {() => number} [options.now] + * @param {(fn: () => void, ms: number) => unknown} [options.setTimer] + * @param {(handle: unknown) => void} [options.clearTimer] + */ +export function createGpuRecoveryController(options) { + const restoreTimeoutMs = Math.max(1, options.restoreTimeoutMs ?? 4000); + const maxContextLosses = Math.max(1, options.maxContextLosses ?? 3); + const maxWebGpuLosses = Math.max(1, options.maxWebGpuLosses ?? 2); + const lossWindowMs = Math.max(1, options.lossWindowMs ?? 30_000); + const now = options.now || (() => Date.now()); + const setTimer = options.setTimer || ((fn, ms) => setTimeout(fn, ms)); + const clearTimer = + options.clearTimer || (handle => clearTimeout(/** @type {any} */ (handle))); + + /** @type {'ready' | 'context-lost' | 'fallback-pending' | 'fallback-blocked' | 'fallback-navigated' | 'fatal'} */ + let status = 'ready'; + let inputPaused = false; + let frameLoopFrozen = false; + let totalLossCount = 0; + let webGpuLossCount = 0; + let restoreCount = 0; + let recoveryEpoch = 0; + /** @type {number[]} */ + let lossTimestamps = []; + /** @type {number[]} */ + let webGpuLossTimestamps = []; + /** @type {unknown} */ + let restoreTimer = null; + let restoreTimerPausedByVisibility = false; + /** @type {Promise<{ navigated: boolean, retryable?: boolean, reason?: string }> | null} */ + let fallbackInFlight = null; + /** @type {string | null} */ + let lastError = null; + /** @type {string | null} */ + let lastFallbackReason = null; + /** @type {string | null} */ + let pendingFallbackUrl = null; + /** @type {((canvas: HTMLCanvasElement | null) => boolean | Promise) | null} */ + let onContextRestoredHook = options.onContextRestored || null; + /** @type {((info: unknown) => boolean | Promise) | null} */ + let tryRebuildWebGpuHook = options.tryRebuildWebGpu || null; + /** @type {((info: unknown) => boolean | Promise) | null} */ + let tryWebGl2FallbackHook = options.tryWebGl2Fallback || null; + /** @type {Set<(state: ReturnType) => void>} */ + const stateListeners = new Set(); + + function getState() { + return { + status, + inputPaused, + frameLoopFrozen, + totalLossCount, + webGpuLossCount, + restoreCount, + lossCountInWindow: lossTimestamps.length, + webGpuLossCountInWindow: webGpuLossTimestamps.length, + retryable: status === 'fallback-blocked', + lastError, + lastFallbackReason, + pendingFallbackUrl, + }; + } + + function notifyState() { + if (stateListeners.size === 0) { + return; + } + const snap = getState(); + for (const listener of stateListeners) { + listener(snap); + } + } + + function clearRestoreTimer() { + restoreTimerPausedByVisibility = false; + if (restoreTimer !== null) { + clearTimer(restoreTimer); + restoreTimer = null; + } + } + + function scheduleRestoreTimeout() { + clearRestoreTimer(); + if (options.isDocumentHidden?.()) { + restoreTimerPausedByVisibility = true; + return; + } + restoreTimer = setTimer(() => { + restoreTimer = null; + void triggerFallback('context-restore-timeout'); + }, restoreTimeoutMs); + } + + function pauseAll() { + if (!inputPaused) { + inputPaused = true; + options.pauseInput(); + } + if (!frameLoopFrozen) { + frameLoopFrozen = true; + options.freezeFrameLoop?.(); + } + } + + function resumeAll() { + if (frameLoopFrozen) { + frameLoopFrozen = false; + options.unfreezeFrameLoop?.(); + } + if (inputPaused) { + inputPaused = false; + options.resumeInput(); + } + } + + /** + * Flushes pending IndexedDB writes and navigates to `?shell=legacy` only + * after persistence succeeds. Single-flight mutex prevents overlapping + * flushes or duplicate navigations. Aborts navigation and exposes a + * retryable error state if persistence fails. + * + * @param {string} [reason='runtime-gpu-loss'] + * @returns {Promise<{ navigated: boolean, retryable?: boolean, reason?: string }>} + */ + function triggerFallback(reason = 'runtime-gpu-loss') { + if (fallbackInFlight) { + return fallbackInFlight; + } + if (status === 'fallback-navigated' || status === 'fatal') { + return Promise.resolve({ + navigated: false, + retryable: false, + reason: status, + }); + } + + clearRestoreTimer(); + pauseAll(); + recoveryEpoch += 1; + lastFallbackReason = reason; + + if (isLegacyShellUrl(options.getHref())) { + status = 'fatal'; + lastError = 'already-legacy'; + options.showFatal?.('Graphics context was lost.', { retryable: false }); + notifyState(); + return Promise.resolve({ + navigated: false, + retryable: false, + reason: 'already-legacy', + }); + } + + const fallback = buildLegacyFallbackUrl(options.getHref(), { + codeConsumed: options.isOAuthCodeConsumed(), + }); + status = 'fallback-pending'; + pendingFallbackUrl = fallback.url; + notifyState(); + + const run = (async () => { + try { + const result = await flushPendingBeforeRedirect({ + pauseInput: () => pauseAll(), + flushPendingWrites: options.flushPendingWrites, + navigate: url => { + options.onFallbackMarker?.(reason, url); + options.navigate(url); + }, + targetUrl: fallback.url, + }); + + if (result.navigated) { + status = 'fallback-navigated'; + lastError = null; + pendingFallbackUrl = null; + notifyState(); + return { navigated: true }; + } + + status = 'fallback-blocked'; + lastError = result.reason || 'flush-rejected'; + options.showFatal?.( + 'Unable to save pending edits. Tap Retry to try again.', + { retryable: true } + ); + notifyState(); + return { + navigated: false, + retryable: true, + reason: lastError, + }; + } finally { + fallbackInFlight = null; + } + })(); + + fallbackInFlight = run; + return run; + } + + /** + * Handles `#app-canvas` `webglcontextlost`. Calls `preventDefault()`, pauses + * input, freezes the frame loop, and starts the visibility-aware restore + * timeout. Ignores duplicate losses once fallback is pending or terminal. + * + * @param {Event | null | undefined} event + * @returns {{ tripped: boolean, lossCountInWindow: number }} + */ + function handleWebGlContextLost(event) { + if (event && typeof event.preventDefault === 'function') { + event.preventDefault(); + } + if ( + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { tripped: false, lossCountInWindow: lossTimestamps.length }; + } + + pauseAll(); + recoveryEpoch += 1; + const t = now(); + totalLossCount += 1; + lossTimestamps = lossTimestamps.filter(ts => t - ts <= lossWindowMs); + lossTimestamps.push(t); + + if (lossTimestamps.length >= maxContextLosses) { + void triggerFallback('context-loss-threshold'); + return { tripped: true, lossCountInWindow: lossTimestamps.length }; + } + + status = 'context-lost'; + scheduleRestoreTimeout(); + notifyState(); + + return { tripped: false, lossCountInWindow: lossTimestamps.length }; + } + + /** + * Pauses or resumes the restore timeout when page visibility changes. + * + * @param {boolean} hidden + */ + function handleVisibilityChange(hidden) { + if (status !== 'context-lost') { + return; + } + if (hidden) { + if (restoreTimer !== null) { + clearTimer(restoreTimer); + restoreTimer = null; + } + restoreTimerPausedByVisibility = true; + } else if (restoreTimerPausedByVisibility) { + scheduleRestoreTimeout(); + } + } + + /** + * Handles `#app-canvas` `webglcontextrestored`. Rebuilds render targets and + * redraws immediately, then resumes the frame loop and input delivery. + * Strictly blocked once fallback is pending, navigated, or fatal, or when a + * newer loss epoch superseded this async restore. + * + * @returns {Promise<{ recovered: boolean, reason?: string }>} + */ + async function handleWebGlContextRestored() { + clearRestoreTimer(); + if ( + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, reason: status }; + } + const epoch = recoveryEpoch; + try { + const rebuilt = onContextRestoredHook + ? await onContextRestoredHook(options.getActiveCanvas?.() ?? null) + : true; + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, reason: status }; + } + if (!rebuilt) { + await triggerFallback('context-restore-failed'); + return { recovered: false, reason: 'context-restore-failed' }; + } + restoreCount += 1; + status = 'ready'; + lastError = null; + pendingFallbackUrl = null; + options.hideFatal?.(); + resumeAll(); + notifyState(); + return { recovered: true }; + } catch { + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, reason: status }; + } + await triggerFallback('context-restore-failed'); + return { recovered: false, reason: 'context-restore-failed' }; + } + } + + /** + * Handles WebGPU `device.lost` and `uncapturederror`. Attempts in-place + * WebGPU rebuild (or WebGL2 downgrade) on the first failure; trips the + * IDB-flushed legacy circuit breaker once `maxWebGpuLosses` (default 2) + * consecutive failures occur inside `lossWindowMs`. + * + * @param {unknown} info + * @param {{ tryRebuildWebGpu?: (info: unknown) => boolean | Promise, tryWebGl2Fallback?: (info: unknown) => boolean | Promise }} [override] + * @returns {Promise<{ recovered: boolean, mode?: string, navigated?: boolean, retryable?: boolean, reason?: string }>} + */ + async function handleWebGpuDeviceLost(info, override = {}) { + if ( + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + if (fallbackInFlight) { + const res = await fallbackInFlight; + return { recovered: false, ...res }; + } + return { recovered: false, navigated: false, reason: status }; + } + clearRestoreTimer(); + pauseAll(); + recoveryEpoch += 1; + const epoch = recoveryEpoch; + const t = now(); + totalLossCount += 1; + webGpuLossCount += 1; + webGpuLossTimestamps = webGpuLossTimestamps.filter( + ts => t - ts <= lossWindowMs + ); + webGpuLossTimestamps.push(t); + + if (webGpuLossTimestamps.length >= maxWebGpuLosses) { + const res = await triggerFallback('webgpu-crash-threshold'); + return { recovered: false, ...res }; + } + + const rebuildFn = override.tryRebuildWebGpu || tryRebuildWebGpuHook; + if (typeof rebuildFn === 'function') { + try { + const ok = await rebuildFn(info); + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, navigated: false, reason: status }; + } + if (ok) { + restoreCount += 1; + status = 'ready'; + lastError = null; + pendingFallbackUrl = null; + options.hideFatal?.(); + resumeAll(); + notifyState(); + return { recovered: true, mode: 'webgpu' }; + } + } catch { + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, navigated: false, reason: status }; + } + // Fall through to WebGL2 downgrade or legacy circuit breaker. + } + } + + const fallbackFn = override.tryWebGl2Fallback || tryWebGl2FallbackHook; + if (typeof fallbackFn === 'function') { + try { + const ok = await fallbackFn(info); + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, navigated: false, reason: status }; + } + if (ok) { + restoreCount += 1; + status = 'ready'; + lastError = null; + pendingFallbackUrl = null; + options.hideFatal?.(); + resumeAll(); + notifyState(); + return { recovered: true, mode: 'webgl2' }; + } + } catch { + if ( + epoch !== recoveryEpoch || + fallbackInFlight !== null || + status === 'fallback-pending' || + status === 'fallback-navigated' || + status === 'fatal' + ) { + return { recovered: false, navigated: false, reason: status }; + } + // Fall through to unrecoverable circuit breaker. + } + } + const res = await triggerFallback('webgpu-device-lost'); + return { recovered: false, ...res }; + } + + /** + * Retries a blocked legacy fallback after an IndexedDB flush error. + * Only starts a new single-flight flush when currently `fallback-blocked`. + */ + function retryFallback() { + if (fallbackInFlight) { + return fallbackInFlight; + } + if (status !== 'fallback-blocked') { + return Promise.resolve({ + navigated: false, + retryable: false, + reason: status, + }); + } + return triggerFallback(lastFallbackReason || 'retry-fallback'); + } + + /** + * Updates recovery hooks after app entry boot. + * + * @param {{ onContextRestored?: (canvas: HTMLCanvasElement | null) => boolean | Promise, tryWebGl2Fallback?: (info: unknown) => boolean | Promise }} hooks + */ + function setHooks(hooks) { + if (hooks.onContextRestored !== undefined) { + onContextRestoredHook = hooks.onContextRestored; + } + if (hooks.tryRebuildWebGpu !== undefined) { + tryRebuildWebGpuHook = hooks.tryRebuildWebGpu; + } + if (hooks.tryWebGl2Fallback !== undefined) { + tryWebGl2FallbackHook = hooks.tryWebGl2Fallback; + } + } + + function dispose() { + clearRestoreTimer(); + stateListeners.clear(); + } + + return { + handleWebGlContextLost, + handleWebGlContextRestored, + handleWebGpuDeviceLost, + handleVisibilityChange, + triggerFallback, + retryFallback, + setHooks, + dispose, + subscribe: listener => { + if (typeof listener !== 'function') { + return () => {}; + } + stateListeners.add(listener); + return () => { + stateListeners.delete(listener); + }; + }, + getState, + }; +} + +/** + * Displays a fatal or retryable error overlay inside `#boot`. + * Recreates `#boot` on `doc.body` if the boot skeleton was already removed + * after the first canvas frame, keeping zero extra DOM during normal steady + * state. + * + * @param {Document} doc + * @param {string} message + * @param {{ retryable?: boolean, onRetry?: () => void }} [options] + */ +export function showBootFatal(doc, message, options = {}) { + let boot = doc.getElementById('boot'); + let msgEl = doc.getElementById('boot-message'); + + if (!boot && doc.body && typeof doc.createElement === 'function') { + boot = doc.createElement('div'); + boot.id = 'boot'; + boot.setAttribute?.('role', 'alert'); + boot.setAttribute?.('aria-live', 'assertive'); + if (boot.style) { + boot.style.position = 'fixed'; + boot.style.inset = '0'; + boot.style.zIndex = '20'; + boot.style.display = 'flex'; + boot.style.flexDirection = 'column'; + boot.style.alignItems = 'center'; + boot.style.justifyContent = 'center'; + boot.style.gap = '12px'; + boot.style.padding = '24px'; + boot.style.background = 'rgba(20, 20, 24, 0.92)'; + boot.style.color = '#ffffff'; + } + msgEl = doc.createElement('div'); + msgEl.id = 'boot-message'; + if (msgEl.style) { + msgEl.style.fontSize = '15px'; + msgEl.style.lineHeight = '1.5'; + msgEl.style.textAlign = 'center'; + msgEl.style.maxWidth = '320px'; + } + boot.append?.(msgEl); + doc.body.append?.(boot); + } + + if (!boot) { + return; + } + if (boot.dataset) { + boot.dataset.state = 'fatal'; + } + if (msgEl) { + msgEl.textContent = message; + } + + let retryBtn = doc.getElementById('gpu-fallback-retry'); + if (options.retryable) { + if (!retryBtn && typeof doc.createElement === 'function') { + retryBtn = doc.createElement('button'); + retryBtn.id = 'gpu-fallback-retry'; + retryBtn.setAttribute?.('type', 'button'); + retryBtn.textContent = 'Retry'; + if (retryBtn.style) { + retryBtn.style.padding = '10px 20px'; + retryBtn.style.borderRadius = '8px'; + retryBtn.style.border = '0'; + retryBtn.style.background = '#1e6efb'; + retryBtn.style.color = '#ffffff'; + retryBtn.style.fontSize = '14px'; + retryBtn.style.fontWeight = '600'; + retryBtn.style.cursor = 'pointer'; + } + boot.append?.(retryBtn); + } + if (retryBtn && options.onRetry) { + const btn = /** @type {HTMLButtonElement} */ (retryBtn); + btn.disabled = false; + btn.onclick = () => { + btn.disabled = true; + void Promise.resolve(options.onRetry?.()).finally(() => { + btn.disabled = false; + }); + }; + } + } else if (retryBtn) { + retryBtn.remove?.(); + } +} + +/** + * Removes any runtime `#boot` error banner once recovery or navigation settles. + * + * @param {Document} doc + */ +export function hideRuntimeFatal(doc) { + const boot = doc.getElementById('boot'); + if (boot) { + boot.remove?.(); + } +} + +/** + * Initializes the Web Mobile thin host in a browser document. + * + * @param {Object} [env] + * @param {Window} [env.win] + * @param {Document} [env.doc] + * @param {() => Promise} [env.flushPendingWrites] + * @param {(insets: SafeAreaInsets) => void} [env.onSafeAreaChange] + * @param {(specifier: string) => Promise} [env.importModule] + * @param {{ flavour: string, type: 'workspace' | 'userspace', id: string }} [env.space] + * @param {IDBFactory} [env.indexedDB] + * @param {typeof BroadcastChannel} [env.BroadcastChannelImpl] + * @param {ReturnType} [env.workspaceStorage] + * @param {(updates: Uint8Array[]) => Uint8Array | Promise} [env.mergeUpdates] + * @param {(rootUpdates: Uint8Array[]) => Iterable | Promise>} [env.extractSubdocIds] + * @param {() => number} [env.now] + * @param {(fn: () => void, ms: number) => unknown} [env.setTimer] + * @param {(handle: unknown) => void} [env.clearTimer] + * @param {number} [env.restoreTimeoutMs] + * @param {number} [env.maxContextLosses] + * @param {number} [env.lossWindowMs] + * @param {() => void} [env.onFreezeFrameLoop] + * @param {() => void} [env.onUnfreezeFrameLoop] + * @param {(canvas: HTMLCanvasElement | null) => boolean | Promise} [env.onContextRestored] + * @param {(info: unknown) => boolean | Promise} [env.tryWebGl2Fallback] + * @param {string | null} [env.assetBaseUrl] + * @param {string} [env.buildId] + * @param {number} [env.pdfCacheMaxBytes] + */ +export async function bootWebHost(env = {}) { + const win = env.win || globalThis.window; + const doc = env.doc || globalThis.document; + if (!win || !doc) { + return null; + } + + const canvas = /** @type {HTMLCanvasElement | null} */ ( + doc.getElementById('app-canvas') + ); + const ime = /** @type {HTMLTextAreaElement | null} */ ( + doc.getElementById('ime') + ); + const probe = doc.getElementById('safe-area-probe'); + const embedLayer = doc.getElementById('embed-layer'); + const a11yRoot = doc.getElementById('a11y-tree'); + + /** @type {(updates: Uint8Array[]) => Uint8Array | Promise} */ + let activeMergeUpdates = + typeof env.mergeUpdates === 'function' ? env.mergeUpdates : null; + /** @type {(rootUpdates: Uint8Array[]) => Iterable | Promise>} */ + let activeExtractSubdocIds = + typeof env.extractSubdocIds === 'function' ? env.extractSubdocIds : null; + + /** + * @param {{ flavour: string, type: 'workspace' | 'userspace', id: string }} space + */ + function createWorkspaceBindings(space) { + const nextStorage = createIdbWorkspaceStorage({ + ...space, + indexedDB: env.indexedDB || win.indexedDB, + BroadcastChannelImpl: env.BroadcastChannelImpl || win.BroadcastChannel, + now: env.now, + mergeUpdates: activeMergeUpdates || undefined, + }); + const nextPending = createPendingWriteFlusher(nextStorage); + const nextV1Reader = createIdbV1ReadonlyReader({ + workspaceId: space.id, + indexedDB: env.indexedDB || win.indexedDB, + mergeUpdates: activeMergeUpdates || undefined, + extractSubdocIds: activeExtractSubdocIds || undefined, + }); + return { + workspaceStorage: nextStorage, + pendingWrites: nextPending, + v1Reader: nextV1Reader, + }; + } + + /** + * Resolves initial workspace and document IDs from the current URL + * (`/workspace/:wsId(/:docId)` or `?workspace=...&doc=...`) or the first + * registered local workspace in `localStorage['affine-local-workspace']`. + * + * @param {string | undefined} href + * @param {Storage | null} storage + * @returns {{ workspaceId: string | null, docId: string | null }} + */ + function resolveInitialWorkspaceRoute(href, storage) { + let workspaceId = null; + let docId = null; + if (typeof href === 'string' && href) { + try { + const parsed = new URL(href, 'http://localhost'); + const match = parsed.pathname.match( + /^\/workspace\/([^/]+)(?:\/([^/]+))?\/?$/ + ); + if (match) { + try { + workspaceId = decodeURIComponent(match[1] || '').trim() || null; + docId = match[2] + ? decodeURIComponent(match[2]).trim() || null + : null; + } catch { + workspaceId = (match[1] || '').trim() || null; + docId = (match[2] || '').trim() || null; + } + } + workspaceId = + (parsed.searchParams.get('workspace') || '').trim() || workspaceId; + docId = + ( + parsed.searchParams.get('doc') || + parsed.searchParams.get('docId') || + '' + ).trim() || docId; + } catch { + // Ignore malformed URLs in minimal test harnesses. + } + } + if (!workspaceId) { + const registered = getLocalWorkspaceIds(storage); + if (registered.length > 0) { + workspaceId = registered[0]; + } + } + return { workspaceId, docId }; + } + + const initialRoute = resolveInitialWorkspaceRoute( + win?.location?.href, + safeGetLocalStorage(win) + ); + const hasIdbFactory = Boolean( + (env.indexedDB || win.indexedDB) && + typeof (env.indexedDB || win.indexedDB).open === 'function' + ); + + /** @type {{ flavour: string, type: 'workspace' | 'userspace', id: string } | null} */ + let currentSpace = env.space + ? { ...env.space } + : !env.workspaceStorage && initialRoute.workspaceId && hasIdbFactory + ? { flavour: 'local', type: 'workspace', id: initialRoute.workspaceId } + : null; + /** @type {string | null} */ + let activeDocId = initialRoute.docId; + /** @type {{ docId: string, getSnapshot: () => any, appendParagraph: (text: string) => Promise<{ snapshot: any, delta: Uint8Array }>, dispose: () => void } | null} */ + let activeDocSession = null; + /** @type {((docSession: any) => void) | null} */ + let documentRenderHook = null; + /** @type {Set<() => void>} */ + const disposeCallbacks = new Set(); + let hostDisposed = false; + let workspaceGeneration = 0; + let openDocRequestSeq = 0; + let workspaceStorage = + env.workspaceStorage || + (currentSpace + ? createIdbWorkspaceStorage({ + ...currentSpace, + indexedDB: env.indexedDB || win.indexedDB, + BroadcastChannelImpl: + env.BroadcastChannelImpl || win.BroadcastChannel, + now: env.now, + mergeUpdates: activeMergeUpdates || undefined, + }) + : null); + let pendingWrites = workspaceStorage + ? createPendingWriteFlusher(workspaceStorage) + : null; + let v1Reader = currentSpace + ? createIdbV1ReadonlyReader({ + workspaceId: currentSpace.id, + indexedDB: env.indexedDB || win.indexedDB, + mergeUpdates: activeMergeUpdates || undefined, + extractSubdocIds: activeExtractSubdocIds || undefined, + }) + : null; + const resolveFlush = () => { + if (env.flushPendingWrites) { + return env.flushPendingWrites(); + } + if (pendingWrites) { + return pendingWrites.flush(); + } + return Promise.resolve({ + ok: true, + unbound: true, + flushedCount: 0, + pendingCount: 0, + }); + }; + + const graphics = detectGraphicsSupport(doc, win.navigator); + if (!graphics.supported) { + if (isLegacyShellUrl(win.location.href)) { + showBootFatal(doc, 'WebGPU and WebGL2 are unavailable in this browser.'); + return { fallback: false, fatal: true, graphics }; + } + const fallback = buildLegacyFallbackUrl(win.location.href, { + codeConsumed: false, + }); + showBootFatal(doc, 'WebGPU and WebGL2 are unavailable. Switching shell...'); + const runBootFallback = async () => { + const res = await flushBeforeNavigation({ + pauseInput() { + if (ime) { + ime.readOnly = true; + } + }, + flushPendingWrites: resolveFlush, + flushTimeoutMs: env.flushTimeoutMs, + navigate: url => replaceLocation(win, url), + targetUrl: fallback.url, + resumeInput() { + if (ime) { + ime.readOnly = false; + } + }, + }); + if (!res.navigated) { + showBootFatal( + doc, + 'Unable to save pending edits. Tap Retry to try again.', + { + retryable: true, + onRetry: () => runBootFallback(), + } + ); + } + return res; + }; + const fallbackResult = await runBootFallback(); + return { + fallback: fallbackResult.navigated, + fatal: !fallbackResult.navigated, + retryable: !fallbackResult.navigated, + graphics, + }; + } + + const manifest = readEmbeddedManifest(doc); + const workerLoader = createWorkerLoader(manifest, { + baseUrl: win.location.href, + assetBaseUrl: env.assetBaseUrl, + buildId: env.buildId, + }); + win.__AFFINE_WEB_HOST__ = true; + const mainWasmJsUrl = workerLoader.resolveMainWasmJsUrl(); + /** @type {Promise<{ merge_updates_v1: Function, extract_subdoc_ids: Function }> | null} */ + let mainWasmModPromise = null; + function loadMainWasmExports() { + if (!mainWasmJsUrl) { + return Promise.reject( + new Error('Main Wasm JS module URL is not configured') + ); + } + if (!mainWasmModPromise) { + const moduleImporter = env.importModule || (spec => import(spec)); + mainWasmModPromise = (async () => { + const mod = await moduleImporter(mainWasmJsUrl); + if (typeof mod.default === 'function') { + await mod.default(); + } + return mod; + })().catch(err => { + mainWasmModPromise = null; + throw err; + }); + } + return mainWasmModPromise; + } + if (mainWasmJsUrl) { + if (!activeMergeUpdates) { + activeMergeUpdates = async updates => { + const mod = await loadMainWasmExports(); + return mod.merge_updates_v1(updates); + }; + } + if (!activeExtractSubdocIds) { + activeExtractSubdocIds = async rootUpdates => { + const mod = await loadMainWasmExports(); + return mod.extract_subdoc_ids(rootUpdates); + }; + } + workspaceStorage?.setCrdtCodecs?.({ mergeUpdates: activeMergeUpdates }); + v1Reader?.setCrdtCodecs?.({ + mergeUpdates: activeMergeUpdates, + extractSubdocIds: activeExtractSubdocIds, + }); + } + const pdfClient = createPdfPreviewClient({ + workerLoader, + maxCacheBytes: env.pdfCacheMaxBytes, + }); + + const safeAreaObserver = probe + ? observeSafeAreaProbe( + win, + probe, + env.onSafeAreaChange || (() => undefined) + ) + : null; + + const a11yTree = a11yRoot + ? createA11yTree({ + doc, + root: a11yRoot, + ime, + embedLayer, + }) + : null; + + let selectionOverlayActive = false; + const imeSelectionGuard = ime + ? attachImeSelectionGuard(ime, () => selectionOverlayActive) + : null; + + let oauthCodeConsumed = false; + let inputPaused = false; + /** @type {HTMLCanvasElement | null} */ + let boundCanvas = null; + + /** @param {Event} event */ + function blockPausedCanvasInput(event) { + if (!inputPaused) { + return; + } + event.preventDefault?.(); + event.stopImmediatePropagation?.(); + } + + /** @param {string} targetUrl */ + async function navigateWithFlush(targetUrl) { + const res = await flushBeforeNavigation({ + pauseInput() { + inputPaused = true; + if (ime) { + ime.readOnly = true; + } + }, + flushPendingWrites: resolveFlush, + flushTimeoutMs: env.flushTimeoutMs, + navigate: url => win.location.assign(url), + targetUrl, + resumeInput() { + inputPaused = false; + if (ime) { + ime.readOnly = false; + } + }, + }); + if (!res.navigated) { + showBootFatal( + doc, + 'Unable to save pending edits. Tap Retry to try again.', + { + retryable: true, + onRetry: () => navigateWithFlush(targetUrl), + } + ); + } else { + hideRuntimeFatal(doc); + } + return res; + } + + const gpuRecovery = createGpuRecoveryController({ + getHref: () => win.location.href, + isOAuthCodeConsumed: () => oauthCodeConsumed, + getActiveCanvas: () => boundCanvas, + isDocumentHidden: () => doc.visibilityState === 'hidden', + pauseInput() { + inputPaused = true; + if (ime) { + ime.readOnly = true; + } + }, + resumeInput() { + inputPaused = false; + if (ime) { + ime.readOnly = false; + } + }, + freezeFrameLoop: env.onFreezeFrameLoop, + unfreezeFrameLoop: env.onUnfreezeFrameLoop, + flushPendingWrites: resolveFlush, + navigate: url => replaceLocation(win, url), + showFatal: (message, opts) => + showBootFatal(doc, message, { + retryable: Boolean(opts?.retryable), + onRetry: opts?.retryable + ? () => gpuRecovery.retryFallback() + : undefined, + }), + hideFatal: () => hideRuntimeFatal(doc), + onContextRestored: env.onContextRestored, + tryRebuildWebGpu: env.tryRebuildWebGpu, + tryWebGl2Fallback: env.tryWebGl2Fallback, + onFallbackMarker: (reason, targetUrl) => { + const storage = safeGetLocalStorage(win); + if (!storage || typeof storage.setItem !== 'function') { + return; + } + try { + setWebPreference('shellFallbackReason', reason, storage); + setWebPreference('shellFallbackTarget', targetUrl, storage); + } catch { + // Never block legacy fallback navigation on storage quota errors. + } + }, + restoreTimeoutMs: env.restoreTimeoutMs, + maxContextLosses: env.maxContextLosses, + maxWebGpuLosses: env.maxWebGpuLosses, + lossWindowMs: env.lossWindowMs, + now: env.now, + setTimer: env.setTimer, + clearTimer: env.clearTimer, + }); + + function onVisibilityChange() { + gpuRecovery.handleVisibilityChange(doc.visibilityState === 'hidden'); + } + doc.addEventListener?.('visibilitychange', onVisibilityChange); + + async function handleRuntimeGpuLoss() { + return gpuRecovery.triggerFallback('runtime-gpu-loss'); + } + + /** @param {Event} event */ + function onContextLost(event) { + gpuRecovery.handleWebGlContextLost(event); + } + + function onContextRestored() { + void gpuRecovery.handleWebGlContextRestored(); + } + + /** @param {HTMLCanvasElement | null} activeCanvas */ + function bindCanvas(activeCanvas) { + if (boundCanvas === activeCanvas) { + return; + } + if (boundCanvas && typeof boundCanvas.removeEventListener === 'function') { + boundCanvas.removeEventListener('webglcontextlost', onContextLost); + boundCanvas.removeEventListener( + 'webglcontextrestored', + onContextRestored + ); + boundCanvas.removeEventListener( + 'pointerdown', + blockPausedCanvasInput, + true + ); + boundCanvas.removeEventListener( + 'pointermove', + blockPausedCanvasInput, + true + ); + boundCanvas.removeEventListener( + 'pointerup', + blockPausedCanvasInput, + true + ); + } + boundCanvas = activeCanvas || null; + if (boundCanvas && typeof boundCanvas.addEventListener === 'function') { + boundCanvas.addEventListener('webglcontextlost', onContextLost); + boundCanvas.addEventListener('webglcontextrestored', onContextRestored); + boundCanvas.addEventListener('pointerdown', blockPausedCanvasInput, true); + boundCanvas.addEventListener('pointermove', blockPausedCanvasInput, true); + boundCanvas.addEventListener('pointerup', blockPausedCanvasInput, true); + } + } + + /** + * @param {{ lost?: Promise, addEventListener?: Function } | null | undefined} device + * @param {{ tryRebuildWebGpu?: (info: unknown) => boolean | Promise, tryWebGl2Fallback?: (info: unknown) => boolean | Promise }} [deviceOpts] + */ + function bindWebGpuDevice(device, deviceOpts = {}) { + if (!device) { + return; + } + let reportedForDevice = false; + const reportOnce = info => { + if (reportedForDevice) { + return; + } + reportedForDevice = true; + void gpuRecovery.handleWebGpuDeviceLost(info, deviceOpts); + }; + if (device.lost && typeof device.lost.then === 'function') { + void device.lost.then(info => { + reportOnce(info); + }); + } + if (typeof device.addEventListener === 'function') { + device.addEventListener('uncapturederror', event => { + reportOnce({ + reason: 'uncapturederror', + error: event?.error ?? event, + }); + }); + } + } + + const BroadcastChannelCtor = env.BroadcastChannelImpl || win.BroadcastChannel; + const localWorkspaceChannel = + typeof BroadcastChannelCtor === 'function' + ? new BroadcastChannelCtor(LOCAL_WORKSPACE_CHANGED_CHANNEL) + : null; + /** @type {Set<(ids: string[], changedId: string | null) => void>} */ + const localWorkspaceListeners = new Set(); + /** @param {MessageEvent} event */ + function handleLocalWorkspaceChanged(event) { + const ids = getLocalWorkspaceIds(safeGetLocalStorage(win)); + const changedId = typeof event?.data === 'string' ? event.data : null; + for (const listener of localWorkspaceListeners) { + listener(ids, changedId); + } + } + localWorkspaceChannel?.addEventListener( + 'message', + handleLocalWorkspaceChanged + ); + + bindCanvas(canvas); + + /** @type {Set>} */ + const inFlightSessionWrites = new Set(); + + const hostHandle = { + fallback: false, + fatal: false, + graphics, + get canvas() { + return boundCanvas || canvas; + }, + ime, + embedLayer, + a11yTree, + isInputPaused: () => inputPaused, + get workspaceStorage() { + return workspaceStorage; + }, + get pendingWrites() { + return pendingWrites; + }, + get v1Reader() { + return v1Reader; + }, + get workspaceBound() { + return Boolean(workspaceStorage); + }, + get activeWorkspace() { + return currentSpace ? { ...currentSpace } : null; + }, + get activeDocId() { + return activeDocId; + }, + get activeDocSession() { + return activeDocSession; + }, + setDocumentRenderHook: hook => { + documentRenderHook = typeof hook === 'function' ? hook : null; + if (documentRenderHook && activeDocSession) { + documentRenderHook(activeDocSession); + } + }, + openDoc: async (docId, options = {}) => { + if (hostDisposed || !workspaceStorage || !docId) { + return null; + } + const expectedWsGen = workspaceGeneration; + const reqSeq = ++openDocRequestSeq; + const sessionStorage = workspaceStorage; + const sessionPendingWrites = pendingWrites; + while ( + inFlightSessionWrites.size > 0 || + (sessionPendingWrites && + (sessionPendingWrites.pendingCount() > 0 || + sessionPendingWrites.isFlushing?.())) + ) { + if (inFlightSessionWrites.size > 0) { + const writesSnapshot = Array.from(inFlightSessionWrites); + await Promise.allSettled(writesSnapshot); + } + if ( + sessionPendingWrites && + (sessionPendingWrites.pendingCount() > 0 || + sessionPendingWrites.isFlushing?.()) + ) { + const flushRes = await sessionPendingWrites.flush(); + if (!flushRes.ok) { + throw new Error( + flushRes.error || + 'Failed to flush pending writes before opening document' + ); + } + } + if ( + hostDisposed || + workspaceGeneration !== expectedWsGen || + openDocRequestSeq !== reqSeq + ) { + return null; + } + } + // Seal the previous session synchronously right after all prior writes have drained, + // before reading the document snapshot so no concurrent edit can commit behind our back. + const prevSession = activeDocSession; + prevSession?.sealForReopen?.(reqSeq); + let wasmSession = null; + let handedOff = false; + try { + const mod = await loadMainWasmExports(); + if ( + hostDisposed || + workspaceGeneration !== expectedWsGen || + openDocRequestSeq !== reqSeq || + typeof mod.WasmLocalDocSession !== 'function' + ) { + prevSession?.unsealIfCurrent?.(reqSeq); + return null; + } + const cryptoObj = win?.crypto || globalThis.crypto; + if (!cryptoObj || typeof cryptoObj.getRandomValues !== 'function') { + throw new Error( + 'Web Crypto getRandomValues is required to allocate document clientId' + ); + } + const allocClientId = () => { + const randBuf = new Uint32Array(1); + cryptoObj.getRandomValues(randBuf); + return randBuf[0] >>> 0 || 1; + }; + const applyRawFrames = (targetSession, rawDoc) => { + if (rawDoc?.snapshot && rawDoc.snapshot.byteLength > 0) { + targetSession.apply_update_v1(rawDoc.snapshot); + } + for (const frame of rawDoc?.updates || []) { + if (frame && frame.byteLength > 0) { + targetSession.apply_update_v1(frame); + } + } + }; + wasmSession = new mod.WasmLocalDocSession(docId, allocClientId()); + const raw = await sessionStorage.getDocRaw(docId); + if ( + hostDisposed || + workspaceGeneration !== expectedWsGen || + openDocRequestSeq !== reqSeq + ) { + return null; + } + const hasSnapshot = Boolean( + raw?.snapshot && raw.snapshot.byteLength > 0 + ); + const hasUpdates = Boolean( + Array.isArray(raw?.updates) && + raw.updates.some(frame => frame && frame.byteLength > 0) + ); + if (!hasSnapshot && !hasUpdates) { + if (options?.createIfMissing) { + if (typeof wasmSession.initialize_page !== 'function') { + throw new Error( + 'WasmLocalDocSession.initialize_page is required for createIfMissing' + ); + } + const initTitle = String(options.createIfMissing.title ?? ''); + const initParagraph = String( + options.createIfMissing.firstParagraph ?? '' + ); + const initDelta = wasmSession.initialize_page( + initTitle, + initParagraph, + Date.now() + ); + const initWriteOp = (async () => { + if (typeof sessionStorage.createDocIfMissing === 'function') { + if ( + sessionPendingWrites && + (sessionPendingWrites.pendingCount() > 0 || + sessionPendingWrites.isFlushing?.()) + ) { + const preFlush = await sessionPendingWrites.flush(); + if (!preFlush.ok) { + throw new Error( + preFlush.error || + 'Failed to flush pending writes before creating page' + ); + } + } + return sessionStorage.createDocIfMissing({ + docId, + bin: initDelta, + }); + } + if (sessionPendingWrites) { + sessionPendingWrites.enqueue({ docId, bin: initDelta }); + const flushRes = await sessionPendingWrites.flush(); + if (!flushRes.ok) { + throw new Error( + flushRes.error || 'Failed to persist initialized page' + ); + } + } else { + await sessionStorage.pushDocUpdate({ docId, bin: initDelta }); + } + return { created: true, raw: null }; + })(); + inFlightSessionWrites.add(initWriteOp); + let createOutcome; + try { + createOutcome = await initWriteOp; + } finally { + inFlightSessionWrites.delete(initWriteOp); + } + if ( + hostDisposed || + workspaceGeneration !== expectedWsGen || + openDocRequestSeq !== reqSeq + ) { + prevSession?.unsealIfCurrent?.(reqSeq); + return null; + } + if (createOutcome && createOutcome.created === false) { + const staleSession = wasmSession; + wasmSession = null; + staleSession.free?.(); + wasmSession = new mod.WasmLocalDocSession(docId, allocClientId()); + applyRawFrames(wasmSession, createOutcome.raw); + } + } else { + if (activeDocId === docId) { + activeDocSession?.dispose(); + activeDocSession = null; + activeDocId = null; + } else { + prevSession?.unsealIfCurrent?.(reqSeq); + } + return null; + } + } else { + applyRawFrames(wasmSession, raw); + } + activeDocSession?.dispose(); + activeDocId = docId; + let sessionDisposed = false; + let sealedByOpenSeq = 0; + let snapshotProjectionSeq = 0; + /** @type {any} */ + let cachedSnapshot = null; + const wrapped = { + docId, + sealForReopen(seq) { + if (!sessionDisposed) { + sealedByOpenSeq = seq; + } + }, + unsealIfCurrent(seq) { + if (!sessionDisposed && sealedByOpenSeq === seq) { + sealedByOpenSeq = 0; + } + }, + getSnapshot() { + if (sessionDisposed) { + throw new Error('Document session is disposed'); + } + if (cachedSnapshot === null) { + cachedSnapshot = JSON.parse(wasmSession.read_snapshot_json()); + } + return structuredClone(cachedSnapshot); + }, + async appendParagraph(text) { + if ( + sessionDisposed || + sealedByOpenSeq !== 0 || + hostDisposed || + activeDocSession !== wrapped + ) { + throw new Error('Document session is disposed'); + } + const appended = wasmSession.append_paragraph_with_snapshot( + String(text), + Date.now() + ); + const delta = appended.delta; + const snapshot = JSON.parse(appended.snapshotJson); + snapshotProjectionSeq += 1; + const myProjectionSeq = snapshotProjectionSeq; + cachedSnapshot = snapshot; + const writeOp = (async () => { + if (sessionPendingWrites) { + sessionPendingWrites.enqueue({ docId, bin: delta }); + const flushRes = await sessionPendingWrites.flush(); + if (!flushRes.ok) { + throw new Error( + flushRes.error || 'Failed to persist document update' + ); + } + } else { + await sessionStorage.pushDocUpdate({ docId, bin: delta }); + } + })(); + inFlightSessionWrites.add(writeOp); + try { + await writeOp; + } finally { + inFlightSessionWrites.delete(writeOp); + } + if ( + !sessionDisposed && + activeDocSession === wrapped && + snapshotProjectionSeq === myProjectionSeq + ) { + documentRenderHook?.(wrapped, structuredClone(snapshot)); + } + return { snapshot: structuredClone(snapshot), delta }; + }, + dispose() { + if (sessionDisposed) { + return; + } + sessionDisposed = true; + cachedSnapshot = null; + wasmSession.free?.(); + }, + }; + handedOff = true; + activeDocSession = wrapped; + documentRenderHook?.(wrapped, wrapped.getSnapshot()); + return wrapped; + } catch (err) { + if ( + !hostDisposed && + workspaceGeneration === expectedWsGen && + openDocRequestSeq === reqSeq + ) { + prevSession?.unsealIfCurrent?.(reqSeq); + } + throw err; + } finally { + if (!handedOff) { + wasmSession?.free?.(); + } + } + }, + attachWorkspace: space => { + if ( + pendingWrites && + (pendingWrites.pendingCount() > 0 || pendingWrites.isFlushing?.()) + ) { + throw new Error( + 'Cannot switch workspace while pending writes are unflushed; flush pendingWrites first' + ); + } + const normalized = { + flavour: space.flavour || space.peer || 'local', + type: space.type || space.spaceType || 'workspace', + id: space.id || space.spaceId, + }; + workspaceGeneration += 1; + workspaceStorage?.close(); + activeDocSession?.dispose(); + activeDocSession = null; + activeDocId = null; + currentSpace = normalized; + ({ workspaceStorage, pendingWrites, v1Reader } = + createWorkspaceBindings(normalized)); + return { workspaceStorage, pendingWrites, v1Reader }; + }, + switchWorkspace: async space => { + if ( + pendingWrites && + (pendingWrites.pendingCount() > 0 || pendingWrites.isFlushing?.()) + ) { + const flushResult = await pendingWrites.flush(); + if (!flushResult.ok) { + throw new Error( + flushResult.error || + 'Failed to flush pending writes before switching workspace' + ); + } + } + const normalized = { + flavour: space.flavour || space.peer || 'local', + type: space.type || space.spaceType || 'workspace', + id: space.id || space.spaceId, + }; + workspaceGeneration += 1; + workspaceStorage?.close(); + activeDocSession?.dispose(); + activeDocSession = null; + activeDocId = null; + currentSpace = normalized; + ({ workspaceStorage, pendingWrites, v1Reader } = + createWorkspaceBindings(normalized)); + return { workspaceStorage, pendingWrites, v1Reader }; + }, + setCrdtCodecs: codecs => { + if (codecs && 'mergeUpdates' in codecs) { + activeMergeUpdates = + typeof codecs.mergeUpdates === 'function' + ? codecs.mergeUpdates + : null; + } + if (codecs && 'extractSubdocIds' in codecs) { + activeExtractSubdocIds = + typeof codecs.extractSubdocIds === 'function' + ? codecs.extractSubdocIds + : null; + } + workspaceStorage?.setCrdtCodecs?.({ mergeUpdates: activeMergeUpdates }); + v1Reader?.setCrdtCodecs?.({ + mergeUpdates: activeMergeUpdates, + extractSubdocIds: activeExtractSubdocIds, + }); + }, + workerLoader, + pdfClient, + gpuRecovery, + safeAreaObserver, + navigateWithFlush, + flushPendingBeforeRedirect: navigateWithFlush, + handleRuntimeGpuLoss, + retryGpuFallback: () => gpuRecovery.retryFallback(), + setGraphicsRecoveryHooks: hooks => gpuRecovery.setHooks(hooks), + setSelectionOverlayActive: active => { + selectionOverlayActive = Boolean(active); + }, + executeClipboardAction: params => + executeClipboardAction({ + ...params, + clipboard: params.clipboard ?? win.navigator?.clipboard ?? null, + isSecureContext: params.isSecureContext ?? win.isSecureContext ?? true, + imeEl: ime, + doc, + }), + markOAuthCodeConsumed: () => { + oauthCodeConsumed = true; + }, + bindCanvas, + bindWebGpuDevice, + focusImeInGesture: options => { + if (!ime) { + return false; + } + a11yTree?.setFocusOwner('ime'); + return focusImeInGesture(ime, options); + }, + mountSandboxedEmbed: options => { + if (!embedLayer) { + return null; + } + const iframe = createSandboxedEmbedIframe(doc, embedLayer, options); + if (a11yTree && a11yTree.getFocusOwner() !== 'embed') { + iframe.setAttribute('tabindex', '-1'); + } + /** @type {'none' | 'a11y' | 'ime' | 'embed'} */ + let previousOwner = 'a11y'; + let activating = false; + const activate = (fromFocusEvent = false) => { + if (activating || !a11yTree) { + return; + } + activating = true; + try { + const current = a11yTree.getFocusOwner(); + if (current !== 'embed') { + previousOwner = current; + } + a11yTree.setFocusOwner('embed'); + iframe.removeAttribute?.('tabindex'); + if (!fromFocusEvent) { + iframe.focus?.(); + } + } finally { + activating = false; + } + }; + const onIframeFocus = () => activate(true); + const unmount = () => { + iframe.removeEventListener?.('focus', onIframeFocus); + iframe.remove?.(); + if (a11yTree && a11yTree.getFocusOwner() === 'embed') { + a11yTree.setFocusOwner(previousOwner); + } + }; + iframe.addEventListener?.('focus', onIframeFocus); + return { iframe, activate: () => activate(false), unmount }; + }, + getLocalWorkspaceIds: () => getLocalWorkspaceIds(safeGetLocalStorage(win)), + setLocalWorkspaceIds: (ids, changedId = null) => + setLocalWorkspaceIds( + ids, + win?.localStorage ?? null, + localWorkspaceChannel, + changedId + ), + subscribeLocalWorkspaceIds: listener => { + localWorkspaceListeners.add(listener); + return () => { + localWorkspaceListeners.delete(listener); + }; + }, + getWebPreference: key => getWebPreference(key, safeGetLocalStorage(win)), + setWebPreference: (key, value) => + setWebPreference(key, value, win?.localStorage ?? null), + getPreferredLocale: () => resolvePreferredLocale(win), + markFirstFrameReady: () => removeBootSkeleton(doc), + onDispose: cb => { + if (typeof cb === 'function') { + disposeCallbacks.add(cb); + } + return () => { + disposeCallbacks.delete(cb); + }; + }, + dispose: () => { + hostDisposed = true; + workspaceGeneration += 1; + for (const cb of disposeCallbacks) { + try { + cb(); + } catch { + // Never abort teardown if one listener throws. + } + } + disposeCallbacks.clear(); + doc.removeEventListener?.('visibilitychange', onVisibilityChange); + localWorkspaceChannel?.removeEventListener( + 'message', + handleLocalWorkspaceChanged + ); + localWorkspaceChannel?.close(); + localWorkspaceListeners.clear(); + workspaceStorage?.close(); + activeDocSession?.dispose(); + activeDocSession = null; + activeDocId = null; + safeAreaObserver?.dispose(); + imeSelectionGuard?.dispose(); + gpuRecovery.dispose(); + pdfClient.dispose(); + workerLoader.dispose(); + bindCanvas(null); + }, + }; + + /** @type {{ __AFFINE_WEB_HOST__?: unknown }} */ ( + /** @type {unknown} */ (win) + ).__AFFINE_WEB_HOST__ = hostHandle; + + const entryUrl = workerLoader.resolveAppEntryUrl(); + if (entryUrl) { + const importer = env.importModule || (spec => import(spec)); + try { + await importer(entryUrl); + } catch { + const fb = await gpuRecovery.triggerFallback('wasm-boot-failed'); + const isRetryableFlush = Boolean( + fb.retryable || gpuRecovery.getState().retryable + ); + if (!fb.navigated && !isRetryableFlush) { + const retryReloadWithFlush = async () => { + const res = await flushBeforeNavigation({ + pauseInput() { + if (ime) { + ime.readOnly = true; + } + }, + flushPendingWrites: resolveFlush, + flushTimeoutMs: env.flushTimeoutMs, + navigate: url => replaceLocation(win, url), + targetUrl: win.location.href, + resumeInput() { + if (ime) { + ime.readOnly = false; + } + }, + }); + if (!res.navigated) { + showBootFatal( + doc, + 'Unable to save pending edits. Tap Retry to try again.', + { + retryable: true, + onRetry: () => retryReloadWithFlush(), + } + ); + } + return res; + }; + showBootFatal( + doc, + 'Failed to initialize AFFiNE. Tap Retry to try again.', + { + retryable: true, + onRetry: () => retryReloadWithFlush(), + } + ); + } + return { + ...hostHandle, + fallback: Boolean(fb.navigated), + fatal: !fb.navigated, + retryable: isRetryableFlush, + }; + } + } + + return hostHandle; +} + +/** + * Safely reads `win.localStorage` without throwing when browser privacy settings + * or sandboxed iframes reject the property getter with `SecurityError`. + * + * @param {{ localStorage?: Storage } | null | undefined} win + * @returns {Storage | null} + */ +function safeGetLocalStorage(win) { + try { + return win?.localStorage ?? null; + } catch { + return null; + } +} + +/** + * Decodes a stored language value from either 0.27.5 `GlobalCache` + * (`JSON.stringify(lang)` under `global-cache:i18n_lng`) or a plain string + * preference, treating `'system'`, malformed JSON, and empty/non-BCP-47 + * sentinels as unset. + * + * @param {string | null | undefined} raw + * @returns {string} + */ +function decodeStoredLocale(raw) { + if (typeof raw !== 'string') { + return ''; + } + let trimmed = raw.trim(); + if (!trimmed) { + return ''; + } + if ( + trimmed.startsWith('"') || + trimmed.startsWith('{') || + trimmed.startsWith('[') + ) { + try { + const parsed = JSON.parse(trimmed); + trimmed = typeof parsed === 'string' ? parsed.trim() : ''; + } catch { + return ''; + } + } else if (trimmed === 'null' || trimmed === 'undefined') { + return ''; + } + if (!trimmed || trimmed.toLowerCase() === 'system') { + return ''; + } + if (!/^[a-zA-Z]{2,3}(?:[-_][a-zA-Z0-9]{1,8})*$/.test(trimmed)) { + return ''; + } + return trimmed; +} + +/** + * Resolves the user's preferred locale from host `language` preference, + * existing 0.27.5 `global-cache:i18n_lng`, or `navigator.language`. + * + * @param {{ localStorage?: Storage, navigator?: { language?: string } } | null | undefined} win + * @returns {string} + */ +function resolvePreferredLocale(win) { + const storage = safeGetLocalStorage(win); + const hostPref = decodeStoredLocale(getWebPreference('language', storage)); + if (hostPref) { + return hostPref; + } + const legacyGlobalCache = decodeStoredLocale( + getWebPreference('global-cache:i18n_lng', storage) + ); + if (legacyGlobalCache) { + return legacyGlobalCache; + } + try { + const navLang = win?.navigator?.language; + return typeof navLang === 'string' ? navLang.trim() : ''; + } catch { + return ''; + } +} + +if ( + globalThis.window !== undefined && + globalThis.document !== undefined && + !globalThis.__AFFINE_WEB_HOST_TEST__ +) { + void bootWebHost().catch(() => { + showBootFatal( + globalThis.document, + 'Failed to initialize AFFiNE. Tap Retry to try again.', + { + retryable: true, + onRetry: () => + replaceLocation(globalThis.window, globalThis.window.location.href), + } + ); + }); +} diff --git a/packages/frontend/hosts/web/src/idb-storage.js b/packages/frontend/hosts/web/src/idb-storage.js new file mode 100644 index 0000000000..aa922c6531 --- /dev/null +++ b/packages/frontend/hosts/web/src/idb-storage.js @@ -0,0 +1,2557 @@ +// @ts-check + +/** + * Same-origin IndexedDB v3 (12-store) + V1 read-only fallback + BroadcastChannel + * bridge for the zero-build Web Mobile thin host. + * + * Schema layout, store names, key paths, indexes, database naming + * (`${flavour}:${type}:${id}`), channel naming (`idb:${dbName}`), and + * `localStorage['affine-local-workspace']` semantics match AFFiNE 0.27.5 + * (`packages/common/nbstore/src/impls/idb/**` and + * `packages/frontend/core/src/modules/workspace-engine/impls/local.ts`). + */ + +export const IDB_SCHEMA_VERSION = 3; + +export const IDB_STORE_NAMES = Object.freeze([ + 'snapshots', + 'updates', + 'clocks', + 'peerClocks', + 'blobs', + 'blobData', + 'locks', + 'blobSync', + 'indexerMetadata', + 'indexerRecords', + 'invertedIndex', + 'indexerSync', +]); + +export const LOCAL_WORKSPACE_LOCAL_STORAGE_KEY = 'affine-local-workspace'; +export const LOCAL_WORKSPACE_CHANGED_CHANNEL = 'affine-local-workspace-changed'; +export const V1_DOC_DB_NAME = 'affine-local'; +export const V1_CONST_TIMESTAMP = new Date(1893456000000); + +/** + * @typedef {Object} IdbSpaceOptions + * @property {string} flavour + * @property {'workspace' | 'userspace'} type + * @property {string} id + */ + +/** + * @typedef {Object} PendingDocWrite + * @property {string} docId + * @property {Uint8Array} bin + * @property {string} [editor] + * @property {'create' | 'update'} [intent] + * @property {string} [createForPeer] + * @property {string} [origin] + */ + +/** + * Raw stored frames of a document, as `getDocRaw` reads them. + * + * @typedef {Object} RawDoc + * @property {string} docId + * @property {Uint8Array | null} snapshot + * @property {Date | null} snapshotUpdatedAt + * @property {Uint8Array[]} updates + * @property {Array} updateTimes + * @property {Date} timestamp + */ + +/** + * Formats the canonical 0.27.5 IndexedDB database name. + * + * @param {IdbSpaceOptions} opts + * @returns {string} + */ +export function formatIdbName(opts) { + if (!opts || !opts.flavour || !opts.type || !opts.id) { + throw new TypeError('flavour, type, and id are required for IDB name'); + } + return `${opts.flavour}:${opts.type}:${opts.id}`; +} + +/** + * Formats the canonical 0.27.5 BroadcastChannel name for an IndexedDB database. + * + * @param {string} dbName + * @returns {string} + */ +export function formatIdbChannelName(dbName) { + return `idb:${dbName}`; +} + +/** + * Normalizes a parsed workspace ID list to an ordered array of strings. + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeWorkspaceIds(raw) { + if (!Array.isArray(raw)) { + return []; + } + return raw.filter(item => typeof item === 'string' && item.length > 0); +} + +/** + * Deduplicates workspace IDs while preserving first-seen order. + * + * @param {string[]} ids + * @returns {string[]} + */ +export function dedupeWorkspaceIds(ids) { + return [...new Set(ids)]; +} + +function defaultLocalStorage() { + try { + return globalThis.localStorage ?? null; + } catch { + return null; + } +} + +/** + * Reads the ordered local workspace ID list strictly from same-origin + * `localStorage['affine-local-workspace']`. Never scans `indexedDB.databases()`, + * preventing deleted workspaces with leftover IDB files from resurrecting. + * + * @param {Pick | null | undefined} [storage] + * @returns {string[]} + */ +export function getLocalWorkspaceIds(storage) { + const resolved = storage === undefined ? defaultLocalStorage() : storage; + if (!resolved || typeof resolved.getItem !== 'function') { + return []; + } + try { + const raw = resolved.getItem(LOCAL_WORKSPACE_LOCAL_STORAGE_KEY); + if (!raw) { + return []; + } + return dedupeWorkspaceIds(normalizeWorkspaceIds(JSON.parse(raw))); + } catch { + return []; + } +} + +/** + * Persists the ordered local workspace ID list to same-origin + * `localStorage['affine-local-workspace']` and optionally notifies peer tabs. + * + * @param {string[] | ((ids: string[]) => string[])} idsOrUpdater + * @param {Pick | null | undefined} [storage] + * @param {Pick | null} [notifyChannel] + * @param {string | null} [changedId] + * @returns {string[]} + */ +export function setLocalWorkspaceIds( + idsOrUpdater, + storage = globalThis.localStorage, + notifyChannel = null, + changedId = null +) { + if (!storage || typeof storage.setItem !== 'function') { + throw new Error('localStorage.setItem is unavailable for persistence'); + } + const next = + typeof idsOrUpdater === 'function' + ? idsOrUpdater(getLocalWorkspaceIds(storage)) + : idsOrUpdater; + const deduplicated = dedupeWorkspaceIds(normalizeWorkspaceIds(next)); + storage.setItem( + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY, + JSON.stringify(deduplicated) + ); + if (notifyChannel && typeof notifyChannel.postMessage === 'function') { + notifyChannel.postMessage(changedId); + } + return deduplicated; +} + +/** + * Appends a local workspace ID if not already present. + * + * @param {string} workspaceId + * @param {Pick | null | undefined} [storage] + * @param {Pick | null} [notifyChannel] + * @returns {string[]} + */ +export function addLocalWorkspaceId( + workspaceId, + storage = globalThis.localStorage, + notifyChannel = null +) { + return setLocalWorkspaceIds( + ids => [...ids, workspaceId], + storage, + notifyChannel, + workspaceId + ); +} + +/** + * Removes a local workspace ID from `localStorage['affine-local-workspace']`. + * + * @param {string} workspaceId + * @param {Pick | null | undefined} [storage] + * @param {Pick | null} [notifyChannel] + * @returns {string[]} + */ +export function removeLocalWorkspaceId( + workspaceId, + storage = globalThis.localStorage, + notifyChannel = null +) { + return setLocalWorkspaceIds( + ids => ids.filter(id => id !== workspaceId), + storage, + notifyChannel, + workspaceId + ); +} + +/** + * Reads a same-origin preference value from `localStorage`. + * + * @param {string} key + * @param {Pick | null | undefined} [storage] + * @returns {string | null} + */ +export function getWebPreference(key, storage) { + const resolved = storage === undefined ? defaultLocalStorage() : storage; + if (!resolved || typeof resolved.getItem !== 'function') { + return null; + } + try { + return resolved.getItem(key); + } catch { + return null; + } +} + +/** + * Writes or removes a same-origin preference value in `localStorage`. + * + * @param {string} key + * @param {string | null | undefined} value + * @param {Pick | null | undefined} [storage] + */ +export function setWebPreference( + key, + value, + storage = globalThis.localStorage +) { + if (value === null || value === undefined) { + if (!storage || typeof storage.removeItem !== 'function') { + throw new Error('localStorage.removeItem is unavailable for persistence'); + } + storage.removeItem(key); + } else { + if (!storage || typeof storage.setItem !== 'function') { + throw new Error('localStorage.setItem is unavailable for persistence'); + } + storage.setItem(key, String(value)); + } +} + +/** + * Creates a default `peerClocks` record matching 0.27.5 `createPeerClock`. + * + * @param {string} peer + * @param {string} docId + */ +export function createPeerClock(peer, docId) { + return { + peer, + docId, + clock: new Date(0), + pulledClock: new Date(0), + pushedClock: new Date(0), + }; +} + +/** + * Applies the frozen 0.27.5 v1 -> v2 -> v3 schema migrations creating all 12 + * object stores and their indexes. + * + * @param {IDBDatabase} db + * @param {number} oldVersion + */ +export function upgradeIdbSchema(db, oldVersion) { + const fromVersion = Number.isFinite(oldVersion) ? oldVersion : 0; + + if (fromVersion < 1) { + const snapshots = db.createObjectStore('snapshots', { + keyPath: 'docId', + autoIncrement: false, + }); + snapshots.createIndex('updatedAt', 'updatedAt', { unique: false }); + + const updates = db.createObjectStore('updates', { + keyPath: ['docId', 'createdAt'], + autoIncrement: false, + }); + updates.createIndex('docId', 'docId', { unique: false }); + + const clocks = db.createObjectStore('clocks', { + keyPath: 'docId', + autoIncrement: false, + }); + clocks.createIndex('timestamp', 'timestamp', { unique: false }); + + const peerClocks = db.createObjectStore('peerClocks', { + keyPath: ['peer', 'docId'], + autoIncrement: false, + }); + peerClocks.createIndex('peer', 'peer', { unique: false }); + + db.createObjectStore('blobs', { + keyPath: 'key', + autoIncrement: false, + }); + + db.createObjectStore('blobData', { + keyPath: 'key', + autoIncrement: false, + }); + + db.createObjectStore('locks', { + keyPath: 'key', + autoIncrement: false, + }); + } + + if (fromVersion < 2) { + const blobSync = db.createObjectStore('blobSync', { + keyPath: ['peer', 'key'], + autoIncrement: false, + }); + blobSync.createIndex('peer', 'peer', { unique: false }); + } + + if (fromVersion < 3) { + db.createObjectStore('indexerMetadata', { + keyPath: 'key', + }); + + const indexRecordsStore = db.createObjectStore('indexerRecords', { + autoIncrement: true, + }); + indexRecordsStore.createIndex('table', 'table', { unique: false }); + indexRecordsStore.createIndex('id', ['table', 'id'], { unique: true }); + + const invertedIndexStore = db.createObjectStore('invertedIndex', { + autoIncrement: true, + }); + invertedIndexStore.createIndex('key', ['table', 'key'], { unique: false }); + invertedIndexStore.createIndex('nid', 'nid', { unique: false }); + + db.createObjectStore('indexerSync', { + keyPath: 'docId', + autoIncrement: false, + }); + } +} + +/** + * Wraps a W3C `IDBRequest` into a Promise. + * + * @template T + * @param {IDBRequest} request + * @returns {Promise} + */ +function requestToPromise(request) { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => + reject(request.error || new Error('IndexedDB request failed')); + }); +} + +/** Delay between attempts of a `writeDocOpsNow` write that failed twice in a row. */ +const WRITE_RETRY_MS = 250; + +/** + * Newest time (ms) of each document that the storage objects of this page + * read or wrote, by database name. Connections of one page see each write at + * once, before a `BroadcastChannel` message could arrive. + * @type {Map>} + */ +const knownClocksByDb = new Map(); + +/** + * Key range of every `updates` key `[docId, createdAt]` of `docId`. Key order + * is number < Date < string < Array, so `[docId, []]` is above all of them. + * + * @param {string} docId + */ +function docKeys(docId) { + return globalThis.IDBKeyRange.bound([docId], [docId, []]); +} + +/** + * Resolves when an IndexedDB transaction commits, or rejects when it aborts. + * + * @param {IDBTransaction} tx + * @returns {Promise} + */ +function transactionDone(tx) { + return new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(); + tx.onabort = () => + reject(tx.error || new Error('IndexedDB transaction aborted')); + }); +} + +/** + * Opens an AFFiNE v3 workspace IndexedDB database at frozen version 3. + * + * @param {IdbSpaceOptions} space + * @param {{ indexedDB?: IDBFactory, createIfMissing?: boolean }} [env] + * @returns {Promise} + */ +export function openWorkspaceIdb(space, env = {}) { + const factory = env.indexedDB || globalThis.indexedDB; + if (!factory || typeof factory.open !== 'function') { + return Promise.reject(new Error('IndexedDB is unavailable')); + } + const createIfMissing = env.createIfMissing !== false; + const dbName = formatIdbName(space); + return new Promise((resolve, reject) => { + const req = factory.open(dbName, IDB_SCHEMA_VERSION); + let abortedMissing = false; + let rejected = false; + req.onupgradeneeded = event => { + const target = /** @type {IDBOpenDBRequest} */ (event.target || req); + const oldVersion = + typeof event.oldVersion === 'number' ? event.oldVersion : 0; + if (!createIfMissing && oldVersion === 0) { + abortedMissing = true; + target.transaction?.abort(); + return; + } + upgradeIdbSchema(target.result, oldVersion); + }; + req.onsuccess = () => { + // A blocked request can still succeed after the old connection closes. + if (rejected) { + req.result?.close?.(); + return; + } + resolve(req.result); + }; + req.onerror = () => { + rejected = true; + if (abortedMissing) { + const notFound = /** @type {Error & { code?: string }} */ ( + new Error(`IndexedDB ${dbName} does not exist`) + ); + notFound.code = 'IDB_NOT_FOUND'; + reject(notFound); + return; + } + reject(req.error || new Error(`Failed to open IndexedDB ${dbName}`)); + }; + req.onblocked = () => { + rejected = true; + reject(new Error(`IndexedDB open blocked for ${dbName}`)); + }; + }); +} + +/** + * Normalizes a Date or numeric timestamp into a Date instance. + * + * @param {Date | number | string | null | undefined} value + * @returns {Date} + */ +function toDate(value, fallbackMs = 0) { + let d; + if (value instanceof Date) { + d = value; + } else if (typeof value === 'number' || typeof value === 'string') { + d = new Date(value); + } else { + return new Date(fallbackMs); + } + return Number.isFinite(d.getTime()) ? d : new Date(fallbackMs); +} + +/** + * Byte-for-byte equality check for two optional `Uint8Array` buffers. + * + * @param {Uint8Array | null | undefined} a + * @param {Uint8Array | null | undefined} b + * @returns {boolean} + */ +function bytesEqual(a, b) { + if (a === b) { + return true; + } + if (!a || !b || a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} + +/** + * Creates a same-origin IndexedDB v3 + `BroadcastChannel` storage bridge for a + * workspace, matching AFFiNE 0.27.5 `IndexedDBDocStorage`, + * `IndexedDBDocSyncStorage`, `IndexedDBBlobStorage`, `IndexedDBBlobSyncStorage`, + * and `IndexedDBIndexerSyncStorage`. + * + * @param {IdbSpaceOptions & { + * indexedDB?: IDBFactory, + * BroadcastChannelImpl?: typeof BroadcastChannel, + * now?: () => number, + * mergeUpdates?: (updates: Uint8Array[]) => Uint8Array | Promise, + * readonlyMode?: boolean, + * setTimeout?: typeof globalThis.setTimeout, + * clearTimeout?: typeof globalThis.clearTimeout, + * onDocWriteFailure?: (error: Error) => void, + * }} options + */ +export function createIdbWorkspaceStorage(options) { + const dbName = formatIdbName(options); + const channelName = formatIdbChannelName(dbName); + const now = options.now || (() => Date.now()); + let configuredMergeUpdates = + typeof options.mergeUpdates === 'function' ? options.mergeUpdates : null; + const readonlyMode = Boolean(options.readonlyMode); + const BroadcastChannelCtor = + options.BroadcastChannelImpl || globalThis.BroadcastChannel; + + /** @type {IDBDatabase | null} */ + let db = null; + /** @type {Promise | null} */ + let openPromise = null; + let openGen = 0; + /** @type {BroadcastChannel | null} */ + let channel = null; + /** @type {Error | null} */ + let versionError = null; + let closed = false; + /** @type {Set<(update: any, origin?: string) => void>} */ + const updateListeners = new Set(); + /** @type {Set<(docId: string) => void>} */ + const deleteListeners = new Set(); + /** + * Newest time (ms) that a connection of this page read or wrote for each + * document of the database, shared by every storage object of `dbName`. + */ + let knownClockMs = knownClocksByDb.get(dbName); + if (!knownClockMs) { + knownClockMs = new Map(); + knownClocksByDb.set(dbName, knownClockMs); + } + /** @param {string} docId @param {number} ms */ + const noteClock = (docId, ms) => + knownClockMs.set(docId, Math.max(knownClockMs.get(docId) ?? 0, ms)); + const setTimer = options.setTimeout ?? globalThis.setTimeout; + const clearTimer = options.clearTimeout ?? globalThis.clearTimeout; + /** @typedef {{ docId: string, bin: Uint8Array } | { docId: string, delete: true } | { blobKey: string, data: Uint8Array }} DocOp */ + /** + * `writeDocOpsNow` transactions from the oldest one that has not settled, + * in issue order. + * @typedef {{ resolve: () => void, reject: (error: Error) => void }} WriteResult + * @typedef {{ ops: DocOp[], state: 'queued' | 'pending' | 'committed' | 'failed', results: WriteResult[] }} DocWrite + * @type {DocWrite[]} + */ + const docWrites = []; + /** Timer of the next attempt of the failed writes, or `null`. */ + let retryTimer = null; + /** @type {'idle' | 'waiting' | 'due' | 'reading' | 'ready' | 'paused'} */ + let retryState = 'idle'; + let delayRetry = false; + /** @type {Error | null} */ + let quotaError = null; + + /** @param {MessageEvent} event */ + function handleChannelMessage(event) { + const data = event?.data; + if (!data || typeof data !== 'object') { + return; + } + if (data.type === 'update' && data.update) { + for (const listener of updateListeners) { + listener(data.update, data.origin); + } + } else if (data.type === 'delete' && typeof data.docId === 'string') { + for (const listener of deleteListeners) { + listener(data.docId); + } + } else if (data.type === 'clocks' && Array.isArray(data.clocks)) { + for (const [docId, ms] of data.clocks) { + if (typeof docId === 'string' && Number.isFinite(ms)) { + noteClock(docId, ms); + } + } + } + } + + /** @param {IDBVersionChangeEvent} event */ + function handleVersionChange(event) { + if (event.newVersion !== IDB_SCHEMA_VERSION) { + versionError = new Error( + `Database version mismatch, expected ${IDB_SCHEMA_VERSION} but got ${event.newVersion}` + ); + close(); + } + } + + async function open() { + if (versionError) { + throw versionError; + } + closed = false; + if (!db) { + if (!openPromise) { + const gen = openGen; + const attempt = openWorkspaceIdb(options, { + indexedDB: options.indexedDB, + }) + .then(conn => { + if (gen !== openGen || versionError) { + conn.close(); + if (openPromise === attempt) { + openPromise = null; + } + throw versionError || new Error('IndexedDB storage was closed'); + } + db = conn; + if (typeof db.addEventListener === 'function') { + db.addEventListener('versionchange', handleVersionChange); + } + return db; + }) + .catch(err => { + if (openPromise === attempt) { + openPromise = null; + } + throw err; + }); + openPromise = attempt; + } + await openPromise; + } + if (!channel && typeof BroadcastChannelCtor === 'function') { + channel = new BroadcastChannelCtor(channelName); + channel.addEventListener('message', handleChannelMessage); + } + return /** @type {IDBDatabase} */ (db); + } + + /** + * Opens the workspace IndexedDB only if it already exists (`oldVersion > 0`), + * returning `null` without creating an empty database when missing. + * + * @returns {Promise} + */ + async function openIfExists() { + if (versionError) { + throw versionError; + } + if (db) { + return db; + } + if (openPromise) { + return openPromise; + } + const gen = openGen; + try { + const conn = await openWorkspaceIdb(options, { + indexedDB: options.indexedDB, + createIfMissing: false, + }); + if (gen !== openGen || versionError) { + conn.close(); + throw versionError || new Error('IndexedDB storage was closed'); + } + if (!db) { + db = conn; + if (typeof db.addEventListener === 'function') { + db.addEventListener('versionchange', handleVersionChange); + } + if (!channel && typeof BroadcastChannelCtor === 'function') { + channel = new BroadcastChannelCtor(channelName); + channel.addEventListener('message', handleChannelMessage); + } + } else if (db !== conn) { + conn.close(); + } + return db; + } catch (err) { + if (err && typeof err === 'object' && err.code === 'IDB_NOT_FOUND') { + return null; + } + throw err; + } + } + + function close() { + closed = true; + openGen += 1; + if (retryTimer !== null) { + clearTimer(retryTimer); + retryTimer = null; + } + retryState = 'idle'; + delayRetry = false; + quotaError = null; + const error = versionError || new Error('IndexedDB storage was closed'); + for (const write of docWrites.splice(0)) { + for (const { reject } of write.results) reject(error); + } + openPromise = null; + if (channel) { + channel.removeEventListener('message', handleChannelMessage); + channel.close(); + channel = null; + } + if (db) { + if (typeof db.removeEventListener === 'function') { + db.removeEventListener('versionchange', handleVersionChange); + } + db.close(); + db = null; + } + } + + /** + * Commits one or more CRDT updates atomically inside a single `readwrite` + * IndexedDB transaction and broadcasts them after `tx.oncomplete`. + * + * @param {PendingDocWrite[]} batch + * @returns {Promise>} + */ + async function pushDocUpdatesBatch(batch) { + if (readonlyMode) { + throw new Error('Cannot write to readonly IDB storage'); + } + if (!batch.length) { + return []; + } + const conn = await open(); + const tx = conn.transaction( + ['updates', 'clocks', 'peerClocks'], + 'readwrite' + ); + const done = transactionDone(tx); + const updatesStore = tx.objectStore('updates'); + const clocksStore = tx.objectStore('clocks'); + const peerClocksStore = tx.objectStore('peerClocks'); + + /** @type {Array<{ update: PendingDocWrite, timestamp: Date }>} */ + const committed = []; + + try { + for (const item of batch) { + const prev = await requestToPromise(clocksStore.get(item.docId)); + const rawPrevMs = prev ? toDate(prev.timestamp, 0).getTime() : 0; + const prevMs = Number.isFinite(rawPrevMs) ? rawPrevMs : 0; + const rawNow = now(); + const safeNow = Number.isFinite(rawNow) ? rawNow : Date.now(); + const timestamp = new Date(Math.max(safeNow, prevMs + 1)); + + /** @type {Record} */ + const updateRecord = { + docId: item.docId, + bin: item.bin, + createdAt: timestamp, + }; + if (item.editor !== undefined) { + updateRecord.editor = item.editor; + } + if (item.intent !== undefined) { + updateRecord.intent = item.intent; + } + if (item.createForPeer !== undefined) { + updateRecord.createForPeer = item.createForPeer; + } + + await requestToPromise(updatesStore.add(updateRecord)); + await requestToPromise( + clocksStore.put({ docId: item.docId, timestamp }) + ); + + if (item.createForPeer) { + const existing = + (await requestToPromise( + peerClocksStore.get([item.createForPeer, item.docId]) + )) || createPeerClock(item.createForPeer, item.docId); + await requestToPromise( + peerClocksStore.put({ ...existing, pendingCreate: true }) + ); + const root = + (await requestToPromise( + peerClocksStore.get([item.createForPeer, options.id]) + )) || createPeerClock(item.createForPeer, options.id); + await requestToPromise( + peerClocksStore.put({ + ...root, + cacheToken: (root.cacheToken || 0) + 1, + }) + ); + } + + committed.push({ update: item, timestamp }); + } + for (const { update, timestamp } of committed) { + noteClock(update.docId, timestamp.getTime()); + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } catch (error) { + try { + tx.abort(); + } catch { + // Ignore if transaction already aborted or finished. + } + await done.catch(() => {}); + throw error; + } + + for (const { update, timestamp } of committed) { + const payload = { + docId: update.docId, + bin: update.bin, + timestamp, + editor: update.editor, + createForPeer: update.createForPeer, + }; + for (const listener of updateListeners) { + try { + listener(payload, update.origin); + } catch { + // Post-commit listener errors must not cause committed batches to be retried. + } + } + if (channel) { + try { + channel.postMessage({ + type: 'update', + update: payload, + origin: update.origin, + }); + } catch { + // Broadcast errors must not cause committed batches to be retried. + } + } + } + + return committed.map(({ update, timestamp }) => ({ + docId: update.docId, + timestamp, + })); + } + + /** + * Applies `ops` in order in one `readwrite` transaction over `updates`, + * `snapshots`, and `clocks` (and `blobs` and `blobData` when `ops` put a + * blob) that issues every request and commits within + * this call, so the write completes even when the page unloads right after + * it. A request issued from a request callback does not run once the page + * unloads, and a transaction that waits for one holds back every later + * transaction of the database, so the transaction reads nothing. The + * connection must be open (`open()` resolved). + * + * Each update gets the time after the newest time that this object knows + * for its document: the times it read (`getDocRaw`, `getDocTimestamps`, the + * reads before a write again), the times it wrote, and the times that + * other connections post to the `BroadcastChannel` after their writes + * commit. The clock of the document moves to that time, and the object + * posts it. A delete removes the stored updates, snapshot, and clock of its + * document. A blob op stores the blob record and its bytes, so a blob and + * the document updates that refer to it commit or roll back together. + * + * When the transaction fails (for example, another connection wrote the + * same time for a document first), the object waits until its later + * `writeDocOpsNow` transactions settle, reads the newest stored time of + * each document again, and writes the ops again. A committed delete + * supersedes older failed ops for that document, and a later blob op + * supersedes older failed ops for that blob. A failed delete retries + * with the updates that committed after it. After a second failure in a + * row the object waits `WRITE_RETRY_MS` before each new attempt. It + * stops after `close()` or a version change. When the quota is exceeded, + * it keeps the ops and the ops of each later call in call order, and + * starts no transaction until a call with a delete or an explicit retry + * (`retryPausedWrites`) writes all of them in one transaction. + * + * @param {DocOp[]} ops + * @returns {Promise} Resolves when each op or its replacement commits. + * Rejects if storage runs out of space, at once while the + * object keeps ops after a quota failure, or if the connection closes + * before it can confirm the write. + */ + function writeDocOpsNow(ops) { + if (readonlyMode) { + throw new Error('Cannot write to readonly IDB storage'); + } + if (!db || closed) { + throw new Error('IndexedDB storage is not open'); + } + return new Promise((resolve, reject) => { + const results = [{ resolve, reject }]; + if (retryState === 'paused') { + if (ops.length && !ops.some(op => 'delete' in op)) { + docWrites.push({ ops, state: 'failed', results: [] }); + if (ops.some(op => 'blobKey' in op)) dropStaleBlobs(); + reject(quotaError); + return; + } + docWrites.push({ ops, state: 'queued', results }); + if (ops.some(op => 'blobKey' in op)) dropStaleBlobs(); + settleDocWrites(); + } else { + issueDocWrite(ops, results); + } + }); + } + + /** Starts a paused replay even if the caller has no new ops. */ + function retryPausedWrites() { + return retryState === 'paused' ? writeDocOpsNow([]) : null; + } + + /** + * @param {DocOp[]} ops + * @param {WriteResult[]} results + */ + function issueDocWrite(ops, results) { + const gen = openGen; + /** @type {DocWrite} */ + const write = { ops, state: 'pending', results }; + docWrites.push(write); + if (ops.some(op => 'blobKey' in op)) dropStaleBlobs(); + /** @type {Map} */ + const written = new Map(); + /** @type {Promise} */ + let committed; + try { + committed = transactionDone(beginDocWrite(ops, written)); + } catch (error) { + committed = Promise.reject(error); + } + committed.then( + () => { + if (gen !== openGen) return; + write.state = 'committed'; + supersedeDocWrites(write); + if (written.size) { + try { + channel?.postMessage({ type: 'clocks', clocks: [...written] }); + } catch { + // Broadcast errors must not cause committed writes to be retried. + } + } + for (const { resolve } of results) resolve(); + settleDocWrites(); + }, + error => { + if (gen !== openGen) return; + write.state = 'failed'; + if (error?.name === 'QuotaExceededError') { + if (retryTimer !== null) { + clearTimer(retryTimer); + retryTimer = null; + } + retryState = 'paused'; + if (quotaError === null) { + console.warn( + 'IndexedDB could not save the changes because storage is full', + error + ); + } + quotaError = error; + for (const failed of docWrites) { + if (failed.state !== 'failed') continue; + for (const { reject } of failed.results.splice(0)) reject(error); + } + } else { + console.error('IndexedDB write failed and is written again', error); + if (retryState === 'paused') { + for (const { reject } of write.results.splice(0)) reject(error); + } + } + if (ops.some(op => 'blobKey' in op)) dropStaleBlobs(); + options.onDocWriteFailure?.(error); + settleDocWrites(); + } + ); + } + + /** + * Removes from each failed write the blob ops that a later write puts + * again. Release the old bytes at once and wait for the replacements to + * commit before confirming the write. + */ + function dropStaleBlobs() { + /** @type {Map} */ + const later = new Map(); + for (let i = docWrites.length - 1; i >= 0; i -= 1) { + const write = docWrites[i]; + if (write.state === 'failed' && later.size) { + /** @type {Set} */ + const owners = new Set(); + const ops = write.ops.filter(op => { + const owner = 'blobKey' in op ? later.get(op.blobKey) : undefined; + if (!owner) return true; + if (owner.state !== 'committed') owners.add(owner); + return false; + }); + if (ops.length < write.ops.length) { + write.ops = ops; + // A partial replacement still needs the ops that remain here. + if (ops.length) owners.add(write); + else write.state = 'committed'; + followBlobReplacements(write.results.splice(0), owners); + } + } + for (const op of write.ops) { + if ('blobKey' in op && !later.has(op.blobKey)) { + later.set(op.blobKey, write); + } + } + } + } + + /** + * @param {WriteResult[]} results + * @param {Set} owners + */ + function followBlobReplacements(results, owners) { + if (!results.length) return; + if (!owners.size) { + for (const { resolve } of results) resolve(); + return; + } + if (retryState === 'paused' && quotaError) { + for (const owner of owners) { + if (owner.state !== 'failed') continue; + for (const { reject } of results) reject(quotaError); + return; + } + } + if (owners.size === 1) { + for (const owner of owners) owner.results.push(...results); + return; + } + let remaining = owners.size; + const result = { + resolve() { + if (remaining <= 0) return; + remaining -= 1; + if (remaining === 0) { + for (const { resolve } of results) resolve(); + } + }, + /** @param {Error} error */ + reject(error) { + if (remaining <= 0) return; + remaining = 0; + for (const { reject } of results) reject(error); + }, + }; + for (const owner of owners) owner.results.push(result); + } + + /** @param {DocWrite} committed */ + function supersedeDocWrites(committed) { + const index = docWrites.indexOf(committed); + if (index <= 0) return; + const deleted = new Set( + committed.ops.filter(op => 'delete' in op).map(op => op.docId) + ); + if (!deleted.size) return; + for (let i = 0; i < index; i += 1) { + const write = docWrites[i]; + if (write.state !== 'failed') continue; + write.ops = write.ops.filter( + op => 'blobKey' in op || !deleted.has(op.docId) + ); + if (!write.ops.length) { + write.state = 'committed'; + for (const { resolve } of write.results) resolve(); + } + } + } + + /** + * @param {DocOp[]} ops + * @param {Map} written The time of each written document. + * @returns {IDBTransaction} + */ + function beginDocWrite(ops, written) { + if (!db) { + throw new Error('IndexedDB storage is not open'); + } + const stores = ['updates', 'snapshots', 'clocks']; + if (ops.some(op => 'blobKey' in op)) stores.push('blobs', 'blobData'); + const tx = db.transaction(stores, 'readwrite'); + const updatesStore = tx.objectStore('updates'); + const snapshotsStore = tx.objectStore('snapshots'); + const clocksStore = tx.objectStore('clocks'); + for (const op of ops) { + if ('blobKey' in op) { + tx.objectStore('blobs').put({ + key: op.blobKey, + mime: 'application/octet-stream', + size: op.data.byteLength, + createdAt: new Date(now()), + deletedAt: null, + }); + tx.objectStore('blobData').put({ key: op.blobKey, data: op.data }); + continue; + } + if ('delete' in op) { + updatesStore.delete(docKeys(op.docId)); + snapshotsStore.delete(op.docId); + clocksStore.delete(op.docId); + written.delete(op.docId); + continue; + } + const timestamp = new Date( + Math.max(now(), (knownClockMs.get(op.docId) ?? 0) + 1) + ); + noteClock(op.docId, timestamp.getTime()); + written.set(op.docId, timestamp.getTime()); + updatesStore.add({ docId: op.docId, bin: op.bin, createdAt: timestamp }); + clocksStore.put({ docId: op.docId, timestamp }); + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + return tx; + } + + /** + * Notes the newest stored time of each of `docIds`: its clock, its snapshot + * time, and its newest update key. The read transaction commits within this + * call, so it never waits for the page. + * + * @param {Iterable} docIds + * @returns {Promise} + */ + async function readStoredTimes(docIds) { + if (!db) { + throw new Error('IndexedDB storage is not open'); + } + const tx = db.transaction(['updates', 'snapshots', 'clocks'], 'readonly'); + const done = transactionDone(tx); + /** @param {string} docId @param {unknown} value */ + const note = (docId, value) => { + if (value !== undefined && value !== null) { + const ms = toDate(/** @type {Date | number} */ (value)).getTime(); + if (Number.isFinite(ms)) noteClock(docId, ms); + } + }; + for (const docId of docIds) { + const clock = tx.objectStore('clocks').get(docId); + clock.onsuccess = () => note(docId, clock.result?.timestamp); + const snapshot = tx.objectStore('snapshots').get(docId); + snapshot.onsuccess = () => note(docId, snapshot.result?.updatedAt); + const newest = tx + .objectStore('updates') + .openKeyCursor(docKeys(docId), 'prev'); + newest.onsuccess = () => { + const key = newest.result?.primaryKey; + note(docId, Array.isArray(key) ? key[1] : undefined); + }; + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + return done; + } + + function settleDocWrites() { + if (closed || versionError) { + return; + } + while (docWrites[0]?.state === 'committed') { + docWrites.shift(); + if (retryState === 'idle') delayRetry = false; + } + if (retryState === 'reading') return; + if (!docWrites.length) { + if (retryTimer !== null) { + clearTimer(retryTimer); + retryTimer = null; + } + retryState = 'idle'; + delayRetry = false; + quotaError = null; + return; + } + if ( + retryState === 'waiting' || + docWrites.some(write => write.state === 'pending') + ) { + return; + } + if (retryState === 'paused') { + if (docWrites.some(write => write.state === 'queued')) { + retryState = 'idle'; + delayRetry = false; + rewrite(); + } + return; + } + if (retryState === 'ready') { + retryState = 'idle'; + delayRetry = true; + rewrite(); + return; + } + const gen = openGen; + if (retryState === 'idle' && delayRetry) { + retryState = 'waiting'; + retryTimer = setTimer(() => { + if (gen !== openGen || retryState !== 'waiting') return; + retryTimer = null; + retryState = 'due'; + settleDocWrites(); + }, WRITE_RETRY_MS); + return; + } + retryState = 'reading'; + const newest = docWrites.at(-1); + const docIds = new Set( + docWrites + .filter(write => write.state === 'failed') + .flatMap(write => + write.ops.flatMap(op => ('docId' in op ? [op.docId] : [])) + ) + ); + void readStoredTimes(docIds).then( + () => { + if (gen !== openGen || retryState !== 'reading') return; + // A write that arrived during the read can fail with a stale clock. + retryState = docWrites.at(-1) === newest ? 'ready' : 'due'; + settleDocWrites(); + }, + () => { + if (gen !== openGen || retryState !== 'reading') return; + retryState = 'idle'; + delayRetry = true; + settleDocWrites(); + } + ); + } + + /** + * Writes the failed ops again, with the updates after each failed delete + * and only the newest op of each blob. + */ + function rewrite() { + /** @type {Map} */ + const lastQueuedDelete = new Map(); + for (const [index, write] of docWrites.entries()) { + if (write.state !== 'queued') continue; + for (const op of write.ops) { + if ('delete' in op) lastQueuedDelete.set(op.docId, index); + } + } + const deleted = new Set(); + const ops = []; + const results = []; + for (const [index, write] of docWrites.splice(0).entries()) { + if (write.state !== 'committed') { + results.push(...write.results); + for (const op of write.ops) { + if ( + write.state === 'failed' && + 'docId' in op && + index < (lastQueuedDelete.get(op.docId) ?? -1) + ) { + continue; + } + if ('delete' in op) deleted.add(op.docId); + ops.push(op); + } + } else { + ops.push( + ...write.ops.filter(op => 'bin' in op && deleted.has(op.docId)) + ); + } + } + /** @type {Map} */ + const newest = new Map(); + ops.forEach((op, index) => { + if ('blobKey' in op) newest.set(op.blobKey, index); + }); + issueDocWrite( + ops.filter( + (op, index) => !('blobKey' in op) || newest.get(op.blobKey) === index + ), + results + ); + } + + /** + * @param {PendingDocWrite} update + * @param {string} [origin] + */ + async function pushDocUpdate(update, origin) { + const [res] = await pushDocUpdatesBatch([ + { ...update, origin: origin ?? update.origin }, + ]); + return res; + } + + /** + * Atomically initializes a document only if both `snapshots` and `updates` + * have zero non-empty frames for `update.docId` at commit time. + * Serializes across same-origin tabs via a single `readwrite` IndexedDB + * transaction over `['snapshots', 'updates', 'clocks']`, returning + * `{ created: false, raw }` with the winner's persisted frames when another + * tab initialized the document first. + * + * @param {{ docId: string, bin: Uint8Array, origin?: string }} update + * @param {string} [origin] + * @returns {Promise<{ created: boolean, raw: { docId: string, snapshot: Uint8Array | null, updates: Uint8Array[], timestamp: Date } | null, timestamp: Date }>} + */ + async function createDocIfMissing(update, origin) { + if (readonlyMode) { + throw new Error('Cannot write to readonly IDB storage'); + } + const conn = await open(); + const tx = conn.transaction( + ['snapshots', 'updates', 'clocks'], + 'readwrite' + ); + const done = transactionDone(tx); + const snapshotsStore = tx.objectStore('snapshots'); + const updatesStore = tx.objectStore('updates'); + const clocksStore = tx.objectStore('clocks'); + + /** @type {{ created: boolean, raw: { docId: string, snapshot: Uint8Array | null, updates: Uint8Array[], timestamp: Date } | null, timestamp: Date } | null} */ + let outcome = null; + const effectiveOrigin = origin ?? update.origin; + + try { + const [snapshot, existingUpdates] = await Promise.all([ + requestToPromise(snapshotsStore.get(update.docId)), + requestToPromise(updatesStore.index('docId').getAll(update.docId)), + ]); + const hasExistingSnapshot = Boolean( + snapshot?.bin && snapshot.bin.byteLength > 0 + ); + const nonEmptyUpdates = existingUpdates.filter( + entry => entry?.bin && entry.bin.byteLength > 0 + ); + + if (hasExistingSnapshot || nonEmptyUpdates.length > 0) { + nonEmptyUpdates.sort( + (a, b) => + toDate(a.createdAt).getTime() - toDate(b.createdAt).getTime() + ); + const existingTs = new Date( + Math.max( + hasExistingSnapshot ? toDate(snapshot.updatedAt).getTime() : 0, + nonEmptyUpdates.length + ? toDate( + nonEmptyUpdates[nonEmptyUpdates.length - 1].createdAt + ).getTime() + : 0 + ) + ); + outcome = { + created: false, + raw: { + docId: update.docId, + snapshot: hasExistingSnapshot ? snapshot.bin : null, + updates: nonEmptyUpdates.map(entry => entry.bin), + timestamp: existingTs, + }, + timestamp: existingTs, + }; + } else { + const prev = await requestToPromise(clocksStore.get(update.docId)); + const rawPrevMs = prev ? toDate(prev.timestamp, 0).getTime() : 0; + const prevMs = Number.isFinite(rawPrevMs) ? rawPrevMs : 0; + const rawNow = now(); + const safeNow = Number.isFinite(rawNow) ? rawNow : Date.now(); + const timestamp = new Date(Math.max(safeNow, prevMs + 1)); + + await requestToPromise( + updatesStore.add({ + docId: update.docId, + bin: update.bin, + createdAt: timestamp, + }) + ); + await requestToPromise( + clocksStore.put({ docId: update.docId, timestamp }) + ); + outcome = { created: true, raw: null, timestamp }; + } + + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } catch (error) { + try { + tx.abort(); + } catch { + // Ignore if transaction already aborted or finished. + } + await done.catch(() => {}); + throw error; + } + + if (outcome.created) { + const payload = { + docId: update.docId, + bin: update.bin, + timestamp: outcome.timestamp, + }; + for (const listener of updateListeners) { + try { + listener(payload, effectiveOrigin); + } catch { + // Post-commit listener errors must not fail committed initialization. + } + } + if (channel) { + try { + channel.postMessage({ + type: 'update', + update: payload, + origin: effectiveOrigin, + }); + } catch { + // Broadcast errors must not fail committed initialization. + } + } + } + return outcome; + } + + /** + * Reads raw unmerged snapshot + ordered update frames for a document so a + * native CRDT engine (for example Rust `y-octo`) can apply them in order + * without requiring a JS `mergeUpdates` callback. + * + * `snapshotUpdatedAt` and `updateTimes` (the `createdAt` of each update, + * in the order of `updates`) identify the frames for + * `compactDocWithMerged`. + * + * @param {string} docId + * @returns {Promise} + */ + async function getDocRaw(docId) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const readTx = conn.transaction(['snapshots', 'updates'], 'readonly'); + const readDone = transactionDone(readTx); + const [snapshot, updates] = await Promise.all([ + requestToPromise(readTx.objectStore('snapshots').get(docId)), + requestToPromise( + readTx.objectStore('updates').index('docId').getAll(docId) + ), + ]); + await readDone; + + if (!snapshot && !updates.length) { + return null; + } + + updates.sort( + (a, b) => toDate(a.createdAt).getTime() - toDate(b.createdAt).getTime() + ); + const timestamp = new Date( + Math.max( + snapshot ? toDate(snapshot.updatedAt).getTime() : 0, + updates.length + ? toDate(updates[updates.length - 1].createdAt).getTime() + : 0 + ) + ); + noteClock(docId, timestamp.getTime()); + return { + docId, + snapshot: snapshot ? snapshot.bin : null, + snapshotUpdatedAt: snapshot ? toDate(snapshot.updatedAt) : null, + updates: updates.map(entry => entry.bin), + updateTimes: updates.map(entry => entry.createdAt), + timestamp, + }; + } + + /** + * Reads non-empty frames for documents with a positive timestamp. + * + * @returns {Promise>} + */ + async function getAllDocsRaw() { + const conn = await openIfExists(); + const docs = new Map(); + if (!conn) return docs; + + const tx = conn.transaction(['clocks', 'snapshots', 'updates'], 'readonly'); + const [clocks, snapshots, updates] = await Promise.all([ + requestToPromise(tx.objectStore('clocks').getAll()), + requestToPromise(tx.objectStore('snapshots').getAll()), + requestToPromise(tx.objectStore('updates').getAll()), + transactionDone(tx), + ]); + + /** @param {string} docId @param {ArrayBuffer | ArrayBufferView | null} bin */ + function appendFrame(docId, bin) { + if (!bin?.byteLength) return; + const frame = + bin instanceof Uint8Array + ? bin + : ArrayBuffer.isView(bin) + ? new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength) + : new Uint8Array(bin); + const frames = docs.get(docId); + if (frames) frames.push(frame); + else docs.set(docId, [frame]); + } + + const positiveDocs = new Set(); + /** @param {string} docId @param {number} ms */ + function noteTime(docId, ms) { + noteClock(docId, ms); + if (typeof docId === 'string' && Number.isFinite(ms) && ms > 0) { + positiveDocs.add(docId); + } + } + + for (const clock of clocks) { + noteTime(clock.docId, toDate(clock.timestamp).getTime()); + } + for (const snapshot of snapshots) { + noteTime(snapshot.docId, toDate(snapshot.updatedAt).getTime()); + appendFrame(snapshot.docId, snapshot.bin); + } + const updatesByDoc = new Map(); + for (const update of updates) { + const ms = toDate(update.createdAt).getTime(); + noteTime(update.docId, ms); + if (!update.bin?.byteLength) continue; + const frames = updatesByDoc.get(update.docId); + const entry = { ms, bin: update.bin }; + if (frames) frames.push(entry); + else updatesByDoc.set(update.docId, [entry]); + } + // Both reads start in primary key order. A stable sort keeps that order + // when a numeric key and a Date key have the same time in milliseconds. + for (const [docId, frames] of updatesByDoc) { + frames.sort((a, b) => a.ms - b.ms); + for (const { bin } of frames) appendFrame(docId, bin); + } + for (const docId of docs.keys()) { + if (!positiveDocs.has(docId)) docs.delete(docId); + } + return docs; + } + + /** + * Reads a document snapshot + pending updates from same-origin IDB v3. + * When multiple CRDT frames exist, requires a `mergeUpdates` callback (never + * raw-concatenates Yjs/y-octo V1 frames). When `opts.compact` is true, + * re-verifies snapshot and updates inside the `readwrite` transaction before + * compacting so concurrent writes are never lost. + * + * @param {string} docId + * @param {{ compact?: boolean, mergeUpdates?: (updates: Uint8Array[]) => Uint8Array | Promise }} [opts] + */ + async function getDoc(docId, opts = {}) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const readTx = conn.transaction(['snapshots', 'updates'], 'readonly'); + const readDone = transactionDone(readTx); + const [snapshot, updates] = await Promise.all([ + requestToPromise(readTx.objectStore('snapshots').get(docId)), + requestToPromise( + readTx.objectStore('updates').index('docId').getAll(docId) + ), + ]); + await readDone; + + if (!updates.length) { + return snapshot + ? { + docId, + bin: snapshot.bin, + timestamp: toDate(snapshot.updatedAt), + } + : null; + } + + updates.sort( + (a, b) => toDate(a.createdAt).getTime() - toDate(b.createdAt).getTime() + ); + const sources = [ + ...(snapshot ? [snapshot.bin] : []), + ...updates.map(entry => entry.bin), + ]; + const merger = + typeof opts.mergeUpdates === 'function' + ? opts.mergeUpdates + : configuredMergeUpdates; + if (sources.length > 1 && !merger) { + throw new TypeError( + 'mergeUpdates callback is required to merge multiple CRDT updates; use getDocRaw() for raw frames' + ); + } + const mergedBin = sources.length === 1 ? sources[0] : await merger(sources); + const timestamp = new Date( + Math.max( + snapshot ? toDate(snapshot.updatedAt).getTime() : 0, + toDate(updates[updates.length - 1].createdAt).getTime() + ) + ); + + if (opts.compact && !readonlyMode) { + const writeTx = conn.transaction(['snapshots', 'updates'], 'readwrite'); + const writeDone = transactionDone(writeTx); + const snapshotsStore = writeTx.objectStore('snapshots'); + const updatesStore = writeTx.objectStore('updates'); + const [currentSnapshot, currentUpdates] = await Promise.all([ + requestToPromise(snapshotsStore.get(docId)), + Promise.all( + updates.map(entry => + requestToPromise(updatesStore.get([docId, entry.createdAt])) + ) + ), + ]); + const snapshotUnchanged = + (currentSnapshot + ? toDate(currentSnapshot.updatedAt).getTime() + : null) === + (snapshot ? toDate(snapshot.updatedAt).getTime() : null) && + bytesEqual(currentSnapshot?.bin, snapshot?.bin); + const updatesUnchanged = updates.every((entry, idx) => + bytesEqual(currentUpdates[idx]?.bin, entry.bin) + ); + if (snapshotUnchanged && updatesUnchanged) { + await requestToPromise( + snapshotsStore.put({ + docId, + bin: mergedBin, + createdAt: currentSnapshot + ? toDate(currentSnapshot.createdAt) + : timestamp, + updatedAt: timestamp, + }) + ); + for (const entry of updates) { + await requestToPromise(updatesStore.delete([docId, entry.createdAt])); + } + } + if (typeof writeTx.commit === 'function') { + writeTx.commit(); + } + await writeDone; + } + + return { docId, bin: mergedBin, timestamp }; + } + + /** + * Replaces the frames that `source` (a `getDocRaw` result) read with + * `mergedBin`, a CRDT snapshot merged outside IndexedDB. One transaction + * checks the snapshot and every source update before it writes the merged + * snapshot, advances the clock, and deletes those exact update keys. + * + * @param {{ docId: string, mergedBin: Uint8Array, source: RawDoc | null }} params + * @returns {Promise<{ compacted: boolean }>} + */ + async function compactDocWithMerged({ docId, mergedBin, source }) { + if (readonlyMode) { + throw new Error('Cannot compact readonly IDB storage'); + } + if (!source || (source.snapshot == null && !source.updates?.length)) { + return { compacted: false }; + } + const conn = await open(); + const tx = conn.transaction( + ['snapshots', 'updates', 'clocks'], + 'readwrite' + ); + const done = transactionDone(tx); + const snapshotsStore = tx.objectStore('snapshots'); + const updatesStore = tx.objectStore('updates'); + const clocksStore = tx.objectStore('clocks'); + let compacted = false; + try { + const [currentSnapshot, currentUpdates, clock] = await Promise.all([ + requestToPromise(snapshotsStore.get(docId)), + Promise.all( + source.updateTimes.map(createdAt => + requestToPromise(updatesStore.get([docId, createdAt])) + ) + ), + requestToPromise(clocksStore.get(docId)), + ]); + const snapshotMs = currentSnapshot + ? toDate(currentSnapshot.updatedAt).getTime() + : null; + const updatesUnchanged = + currentUpdates.length === source.updates.length && + currentUpdates.every( + (entry, i) => entry && bytesEqual(entry.bin, source.updates[i]) + ); + if ( + snapshotMs === (source.snapshotUpdatedAt?.getTime() ?? null) && + bytesEqual(currentSnapshot?.bin, source.snapshot ?? undefined) && + updatesUnchanged + ) { + let updatedAtMs = snapshotMs ?? 0; + for (const createdAt of source.updateTimes) { + updatedAtMs = Math.max(updatedAtMs, toDate(createdAt).getTime()); + } + const updatedAt = new Date(updatedAtMs); + await requestToPromise( + snapshotsStore.put({ + docId, + bin: mergedBin, + createdAt: currentSnapshot + ? toDate(currentSnapshot.createdAt) + : updatedAt, + updatedAt, + }) + ); + if (!clock || toDate(clock.timestamp) < updatedAt) { + await requestToPromise( + clocksStore.put({ ...clock, docId, timestamp: updatedAt }) + ); + } + for (const createdAt of source.updateTimes) { + await requestToPromise(updatesStore.delete([docId, createdAt])); + } + compacted = true; + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } catch (error) { + try { + tx.abort(); + } catch { + // Ignore if already finished. + } + await done.catch(() => {}); + throw error; + } + return { compacted }; + } + + /** + * @param {string} docId + */ + async function deleteDoc(docId) { + if (readonlyMode) { + throw new Error('Cannot delete from readonly IDB storage'); + } + const conn = await open(); + const tx = conn.transaction( + ['snapshots', 'updates', 'clocks', 'peerClocks'], + 'readwrite' + ); + const done = transactionDone(tx); + const updates = await requestToPromise( + tx.objectStore('updates').index('docId').getAll(docId) + ); + for (const entry of updates) { + await requestToPromise( + tx.objectStore('updates').delete([entry.docId, entry.createdAt]) + ); + } + await requestToPromise(tx.objectStore('snapshots').delete(docId)); + await requestToPromise(tx.objectStore('clocks').delete(docId)); + const peersStore = tx.objectStore('peerClocks'); + const allPeers = await requestToPromise(peersStore.getAll()); + for (const record of allPeers) { + if (record.docId !== docId || !record.pendingCreate) { + continue; + } + await requestToPromise( + peersStore.put({ ...record, pendingCreate: false }) + ); + const root = + (await requestToPromise(peersStore.get([record.peer, options.id]))) || + createPeerClock(record.peer, options.id); + await requestToPromise( + peersStore.put({ ...root, cacheToken: (root.cacheToken || 0) + 1 }) + ); + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + + for (const listener of deleteListeners) { + listener(docId); + } + channel?.postMessage({ type: 'delete', docId }); + } + + /** + * The time of each stored document that is later than `after`: the newest + * of its clock, its snapshot time, and its update keys. A clock that a + * concurrent write of another page put lower than a stored update does not + * hide that update. + * + * @param {Date} [after] + * @returns {Promise>} + */ + async function getDocTimestamps(after = new Date(0)) { + const conn = await openIfExists(); + if (!conn) { + return {}; + } + const tx = conn.transaction(['clocks', 'snapshots', 'updates'], 'readonly'); + const done = transactionDone(tx); + const [clocks, snapshots, updateKeys] = await Promise.all([ + requestToPromise(tx.objectStore('clocks').getAll()), + requestToPromise(tx.objectStore('snapshots').getAll()), + requestToPromise(tx.objectStore('updates').getAllKeys()), + ]); + await done; + /** @type {Map} */ + const newest = new Map(); + /** @param {unknown} docId @param {unknown} value */ + const note = (docId, value) => { + const ms = toDate(/** @type {Date | number} */ (value)).getTime(); + if (typeof docId === 'string' && Number.isFinite(ms)) { + newest.set(docId, Math.max(newest.get(docId) ?? -Infinity, ms)); + } + }; + for (const cur of clocks) note(cur.docId, cur.timestamp); + for (const cur of snapshots) note(cur.docId, cur.updatedAt); + for (const key of updateKeys) { + if (Array.isArray(key)) note(key[0], key[1]); + } + /** @type {Record} */ + const out = {}; + for (const [docId, ms] of newest) { + noteClock(docId, ms); + if (ms > after.getTime()) { + out[docId] = new Date(ms); + } + } + return out; + } + + /** + * @param {string} docId + */ + async function getDocTimestamp(docId) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const tx = conn.transaction('clocks', 'readonly'); + const done = transactionDone(tx); + const record = await requestToPromise(tx.objectStore('clocks').get(docId)); + await done; + return record + ? { docId: record.docId, timestamp: toDate(record.timestamp) } + : null; + } + + /** + * @param {string} peer + * @param {string} docId + * @param {'clock' | 'pulledClock' | 'pushedClock'} field + */ + async function getPeerField(peer, docId, field) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const tx = conn.transaction('peerClocks', 'readonly'); + const done = transactionDone(tx); + const record = await requestToPromise( + tx.objectStore('peerClocks').get([peer, docId]) + ); + await done; + return record + ? { docId: record.docId, timestamp: toDate(record[field]) } + : null; + } + + /** + * @param {string} peer + * @param {'clock' | 'pulledClock' | 'pushedClock'} field + */ + async function getPeerFieldMap(peer, field) { + const conn = await openIfExists(); + if (!conn) { + return {}; + } + const tx = conn.transaction('peerClocks', 'readonly'); + const done = transactionDone(tx); + const records = await requestToPromise( + tx.objectStore('peerClocks').index('peer').getAll(peer) + ); + await done; + /** @type {Record} */ + const out = {}; + for (const record of records) { + out[record.docId] = toDate(record[field]); + } + return out; + } + + /** + * @param {string} peer + * @param {{ docId: string, timestamp: Date }} clock + * @param {'clock' | 'pulledClock' | 'pushedClock'} field + */ + async function setPeerField(peer, clock, field) { + const conn = await open(); + const tx = conn.transaction('peerClocks', 'readwrite'); + const done = transactionDone(tx); + const store = tx.objectStore('peerClocks'); + const record = await requestToPromise(store.get([peer, clock.docId])); + const nextTs = toDate(clock.timestamp); + if (!record || toDate(record[field]) < nextTs) { + const base = record || createPeerClock(peer, clock.docId); + await requestToPromise(store.put({ ...base, [field]: nextTs })); + } + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } + + /** + * @param {string} key + */ + async function getBlob(key) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const tx = conn.transaction(['blobs', 'blobData'], 'readonly'); + const done = transactionDone(tx); + const [meta, payload] = await Promise.all([ + requestToPromise(tx.objectStore('blobs').get(key)), + requestToPromise(tx.objectStore('blobData').get(key)), + ]); + await done; + if (!meta || meta.deletedAt || !payload) { + return null; + } + return { ...meta, data: payload.data }; + } + + /** + * Reads the bytes of every blob that is not deleted in one transaction. + * + * @returns {Promise>} + */ + async function getAllBlobsRaw() { + const conn = await openIfExists(); + const blobs = new Map(); + if (!conn) return blobs; + const tx = conn.transaction(['blobs', 'blobData'], 'readonly'); + const [metas, payloads] = await Promise.all([ + requestToPromise(tx.objectStore('blobs').getAll()), + requestToPromise(tx.objectStore('blobData').getAll()), + transactionDone(tx), + ]); + const live = new Set( + metas.filter(meta => !meta.deletedAt).map(meta => meta.key) + ); + for (const { key, data } of payloads) { + if (live.has(key) && data) blobs.set(key, data); + } + return blobs; + } + + /** + * @param {{ key: string, mime: string, data: Uint8Array }} blob + */ + async function setBlob(blob) { + const conn = db ?? (await open()); + const tx = conn.transaction(['blobs', 'blobData'], 'readwrite'); + const metadata = tx.objectStore('blobs').put({ + key: blob.key, + mime: blob.mime, + size: blob.data.byteLength, + createdAt: new Date(now()), + deletedAt: null, + }); + const payload = tx.objectStore('blobData').put({ + key: blob.key, + data: blob.data, + }); + const written = Promise.all([ + transactionDone(tx), + requestToPromise(metadata), + requestToPromise(payload), + ]); + if (typeof tx.commit === 'function') { + tx.commit(); + } + await written; + } + + /** + * @param {string} peer + * @param {string} key + * @param {Date | null} uploadedAt + */ + async function setBlobUploadedAt(peer, key, uploadedAt) { + const conn = await open(); + const tx = conn.transaction('blobSync', 'readwrite'); + const done = transactionDone(tx); + await requestToPromise( + tx.objectStore('blobSync').put({ peer, key, uploadedAt }) + ); + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } + + /** + * @param {string} peer + * @param {string} key + * @returns {Promise} + */ + async function getBlobUploadedAt(peer, key) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const tx = conn.transaction('blobSync', 'readonly'); + const done = transactionDone(tx); + const record = await requestToPromise( + tx.objectStore('blobSync').get([peer, key]) + ); + await done; + return record?.uploadedAt ? toDate(record.uploadedAt) : null; + } + + /** + * @param {string} docId + */ + async function getDocIndexedClock(docId) { + const conn = await openIfExists(); + if (!conn) { + return null; + } + const tx = conn.transaction('indexerSync', 'readonly'); + const done = transactionDone(tx); + const record = await requestToPromise( + tx.objectStore('indexerSync').get(docId) + ); + await done; + return record + ? { + docId: record.docId, + timestamp: toDate(record.indexedClock), + indexerVersion: record.indexerVersion ?? 0, + } + : null; + } + + /** + * @param {{ docId: string, timestamp: Date, indexerVersion?: number }} clock + */ + async function setDocIndexedClock(clock) { + const conn = await open(); + const tx = conn.transaction('indexerSync', 'readwrite'); + const done = transactionDone(tx); + await requestToPromise( + tx.objectStore('indexerSync').put({ + docId: clock.docId, + indexedClock: toDate(clock.timestamp), + indexerVersion: clock.indexerVersion ?? 0, + }) + ); + if (typeof tx.commit === 'function') { + tx.commit(); + } + await done; + } + + /** + * @param {(update: any, origin?: string) => void} callback + */ + function subscribeDocUpdate(callback) { + updateListeners.add(callback); + return () => { + updateListeners.delete(callback); + }; + } + + /** + * @param {(docId: string) => void} callback + */ + function subscribeDocDelete(callback) { + deleteListeners.add(callback); + return () => { + deleteListeners.delete(callback); + }; + } + + /** + * Updates the CRDT `mergeUpdates` callback after Wasm initialization. + * + * @param {{ mergeUpdates?: ((updates: Uint8Array[]) => Uint8Array | Promise) | null }} codecs + */ + function setCrdtCodecs(codecs) { + if (codecs && 'mergeUpdates' in codecs) { + configuredMergeUpdates = + typeof codecs.mergeUpdates === 'function' ? codecs.mergeUpdates : null; + } + } + + return { + dbName, + channelName, + version: IDB_SCHEMA_VERSION, + open, + close, + setCrdtCodecs, + createDocIfMissing, + pushDocUpdate, + pushDocUpdatesBatch, + writeDocOpsNow, + retryPausedWrites, + getDoc, + getDocRaw, + getAllDocsRaw, + compactDocWithMerged, + deleteDoc, + getDocTimestamps, + getDocTimestamp, + getPeerRemoteClock: (peer, docId) => getPeerField(peer, docId, 'clock'), + getPeerRemoteClocks: peer => getPeerFieldMap(peer, 'clock'), + setPeerRemoteClock: (peer, clock) => setPeerField(peer, clock, 'clock'), + getPeerPulledRemoteClock: (peer, docId) => + getPeerField(peer, docId, 'pulledClock'), + getPeerPulledRemoteClocks: peer => getPeerFieldMap(peer, 'pulledClock'), + setPeerPulledRemoteClock: (peer, clock) => + setPeerField(peer, clock, 'pulledClock'), + getPeerPushedClock: (peer, docId) => + getPeerField(peer, docId, 'pushedClock'), + getPeerPushedClocks: peer => getPeerFieldMap(peer, 'pushedClock'), + setPeerPushedClock: (peer, clock) => + setPeerField(peer, clock, 'pushedClock'), + getBlob, + getAllBlobsRaw, + setBlob, + getBlobUploadedAt, + setBlobUploadedAt, + getDocIndexedClock, + setDocIndexedClock, + subscribeDocUpdate, + subscribeDocDelete, + }; +} + +/** + * Creates a strictly read-only fallback reader for legacy Web IndexedDB V1 + * databases (`affine-local` for docs and `${workspaceId}_blob` for blobs), + * aligned with `local.ts:197-210` and `nbstore/src/impls/idb/v1/*`. + * + * Never creates an empty V1 database when none exists, and never mutates V1 + * data. Listing subdocs of a non-empty V1 root requires an `extractSubdocIds` + * callback (wired to the main `playground` Wasm bundle in `host.js`) or explicit `opts.subdocIds`. + * + * @param {{ + * workspaceId: string, + * indexedDB?: IDBFactory, + * mergeUpdates?: (updates: Uint8Array[]) => Uint8Array | Promise, + * extractSubdocIds?: (rootUpdates: Uint8Array[]) => Iterable | Promise>, + * }} options + */ +export function createIdbV1ReadonlyReader(options) { + const workspaceId = options.workspaceId; + const factory = options.indexedDB || globalThis.indexedDB; + let configuredMergeUpdates = + typeof options.mergeUpdates === 'function' ? options.mergeUpdates : null; + let configuredExtractSubdocIds = + typeof options.extractSubdocIds === 'function' + ? options.extractSubdocIds + : null; + const blobDbName = `${workspaceId}_blob`; + + /** + * Opens an existing V1 database strictly read-only. Never creates an object + * store or empty database when the database does not already exist (even on + * runtimes without `indexedDB.databases()`). + * + * @param {string} dbName + * @param {string} storeName + * @returns {Promise} + */ + async function openExistingV1(dbName, storeName) { + if (!factory || typeof factory.open !== 'function') { + return null; + } + if (typeof factory.databases === 'function') { + const list = await factory.databases(); + if (!list.some(entry => entry.name === dbName)) { + return null; + } + } + return new Promise((resolve, reject) => { + let abortedMissing = false; + const req = factory.open(dbName, 1); + req.onupgradeneeded = event => { + const target = /** @type {IDBOpenDBRequest} */ (event.target || req); + const oldVersion = + typeof event.oldVersion === 'number' ? event.oldVersion : 0; + if ( + oldVersion === 0 || + !target.result?.objectStoreNames?.contains(storeName) + ) { + abortedMissing = true; + target.transaction?.abort?.(); + } + }; + req.onsuccess = () => { + const db = req.result; + if (abortedMissing || !db || !db.objectStoreNames.contains(storeName)) { + db?.close?.(); + resolve(null); + return; + } + resolve(db); + }; + req.onerror = () => { + if (abortedMissing) { + resolve(null); + return; + } + reject(req.error || new Error(`Failed to open V1 DB ${dbName}`)); + }; + }); + } + + /** + * Reads raw unmerged update frames for one document from V1 `affine-local` + * (`workspace` store). + * + * @param {string} docId + * @returns {Promise<{ docId: string, updates: Uint8Array[], timestamp: Date } | null>} + */ + async function getV1DocRaw(docId) { + const db = await openExistingV1(V1_DOC_DB_NAME, 'workspace'); + if (!db) { + return null; + } + try { + const tx = db.transaction('workspace', 'readonly'); + const done = transactionDone(tx); + const record = await requestToPromise( + tx.objectStore('workspace').get(docId) + ); + await done; + if (!record || !Array.isArray(record.updates) || !record.updates.length) { + return null; + } + return { + docId, + updates: record.updates.map(entry => entry.update), + timestamp: V1_CONST_TIMESTAMP, + }; + } finally { + db.close(); + } + } + + /** + * Reads one document from V1 `affine-local` (`workspace` store). + * Requires `mergeUpdates` when more than one CRDT update exists. + * + * @param {string} docId + * @param {{ mergeUpdates?: (updates: Uint8Array[]) => Uint8Array | Promise }} [opts] + */ + async function getV1Doc(docId, opts = {}) { + const raw = await getV1DocRaw(docId); + if (!raw) { + return null; + } + const merger = + typeof opts.mergeUpdates === 'function' + ? opts.mergeUpdates + : configuredMergeUpdates; + if (raw.updates.length > 1 && !merger) { + throw new TypeError( + 'mergeUpdates callback is required to merge multiple V1 CRDT updates; use getV1DocRaw() for raw frames' + ); + } + const bin = + raw.updates.length === 1 ? raw.updates[0] : await merger(raw.updates); + return { + docId, + bin, + timestamp: raw.timestamp, + }; + } + + /** + * Lists V1 document keys belonging to `workspaceId` in `affine-local`. + * Matches root doc, top-level page `subdoc.guid` keys extracted from root + * doc (or supplied via `opts.subdocIds`) that exist in `workspace`, + * `db$$...`, and 3- or 4-segment + * `userdata$$[$]` keys. + * + * @param {{ + * subdocIds?: Iterable, + * extractSubdocIds?: (rootUpdates: Uint8Array[]) => Iterable | Promise>, + * }} [opts] + * @returns {Promise} + */ + async function listV1DocIds(opts = {}) { + const db = await openExistingV1(V1_DOC_DB_NAME, 'workspace'); + if (!db) { + return []; + } + try { + const tx = db.transaction('workspace', 'readonly'); + const done = transactionDone(tx); + const store = tx.objectStore('workspace'); + const extractor = + typeof opts.extractSubdocIds === 'function' + ? opts.extractSubdocIds + : configuredExtractSubdocIds; + const [rawKeys, rootRecord] = await Promise.all([ + requestToPromise(store.getAllKeys()), + requestToPromise(store.get(workspaceId)), + ]); + await done; + const keys = rawKeys.map(String); + const keySet = new Set(keys); + /** @type {Uint8Array[]} */ + const rootUpdates = + rootRecord && Array.isArray(rootRecord.updates) + ? rootRecord.updates.map(entry => entry.update) + : []; + + /** @type {Set} */ + const matched = new Set(); + if (keySet.has(workspaceId)) { + matched.add(workspaceId); + } + if (opts.subdocIds) { + for (const subId of opts.subdocIds) { + if (typeof subId === 'string' && subId && keySet.has(subId)) { + matched.add(subId); + } + } + } + if (rootUpdates.length && !opts.subdocIds) { + if (!extractor) { + throw new TypeError( + 'extractSubdocIds callback is required to inspect non-empty V1 root CRDT updates' + ); + } + const extracted = await extractor(rootUpdates); + if (extracted) { + for (const subId of extracted) { + if (typeof subId === 'string' && subId && keySet.has(subId)) { + matched.add(subId); + } + } + } + } + + const escaped = workspaceId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const userDataRe = new RegExp( + `^userdata\\$[\\w-]+\\$${escaped}(?:\\$[^$]+)?$` + ); + for (const key of keys) { + if (key.startsWith(`db$${workspaceId}$`) || userDataRe.test(key)) { + matched.add(key); + } + } + return [...matched]; + } finally { + db.close(); + } + } + + /** + * Reads one blob from V1 `${workspaceId}_blob` (`blob` store). + * + * @param {string} key + */ + async function getV1Blob(key) { + const db = await openExistingV1(blobDbName, 'blob'); + if (!db) { + return null; + } + try { + const tx = db.transaction('blob', 'readonly'); + const done = transactionDone(tx); + const raw = await requestToPromise(tx.objectStore('blob').get(key)); + await done; + if (!raw) { + return null; + } + const data = raw instanceof Uint8Array ? raw : new Uint8Array(raw); + return { + key, + mime: '', + data, + createdAt: V1_CONST_TIMESTAMP, + }; + } finally { + db.close(); + } + } + + /** + * Updates CRDT merge/extraction callbacks after Wasm initialization. + * + * @param {{ mergeUpdates?: ((updates: Uint8Array[]) => Uint8Array | Promise) | null, extractSubdocIds?: ((rootUpdates: Uint8Array[]) => Iterable | Promise>) | null }} codecs + */ + function setCrdtCodecs(codecs) { + if (codecs && 'mergeUpdates' in codecs) { + configuredMergeUpdates = + typeof codecs.mergeUpdates === 'function' ? codecs.mergeUpdates : null; + } + if (codecs && 'extractSubdocIds' in codecs) { + configuredExtractSubdocIds = + typeof codecs.extractSubdocIds === 'function' + ? codecs.extractSubdocIds + : null; + } + } + + return Object.freeze({ + readonly: true, + workspaceId, + getV1Doc, + getV1DocRaw, + listV1DocIds, + getV1Blob, + setCrdtCodecs, + }); +} + +/** + * Buffers pending CRDT updates and commits them in a real same-origin IDB + * transaction (`oncomplete`). If the IDB transaction fails or aborts, all + * pending writes stay intact in the buffer so navigation/handoff can abort + * without losing user edits. + * + * @param {ReturnType} storage + */ +export function createPendingWriteFlusher(storage) { + /** @type {PendingDocWrite[]} */ + let queue = []; + /** @type {Promise<{ ok: boolean, flushedCount: number, pendingCount: number, error?: string }> | null} */ + let activeFlush = null; + + /** @param {PendingDocWrite} write */ + function enqueue(write) { + queue.push(write); + } + + /** + * Drains all buffered writes sequentially in a single-flight loop so + * overlapping `flush()` calls never duplicate commits or drop items enqueued + * while a batch transaction is in flight. + * + * @returns {Promise<{ ok: boolean, flushedCount: number, pendingCount: number, error?: string }>} + */ + async function drainLoop() { + let totalFlushed = 0; + while (queue.length > 0) { + const batch = queue.slice(); + try { + await storage.pushDocUpdatesBatch(batch); + queue = queue.slice(batch.length); + totalFlushed += batch.length; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + ok: false, + flushedCount: totalFlushed, + pendingCount: queue.length, + error: message, + }; + } + } + return { + ok: true, + flushedCount: totalFlushed, + pendingCount: queue.length, + }; + } + + /** + * Flushes all buffered writes into real IDB transactions with single-flight + * serialization. Loops until both `queue` and any in-flight drain finish so + * items enqueued right as an earlier flush settles are always persisted + * before this promise resolves. Retains uncommitted writes if commit fails. + * + * @returns {Promise<{ ok: boolean, flushedCount: number, pendingCount: number, error?: string }>} + */ + async function flush() { + let totalFlushed = 0; + while (queue.length > 0 || activeFlush) { + if (!activeFlush) { + const p = drainLoop(); + activeFlush = p; + try { + const r = await p; + totalFlushed += r.flushedCount; + if (!r.ok) { + return { + ok: false, + flushedCount: totalFlushed, + pendingCount: queue.length, + error: r.error, + }; + } + } finally { + if (activeFlush === p) { + activeFlush = null; + } + } + } else { + const r = await activeFlush; + if (!r.ok) { + return r; + } + } + } + return { + ok: true, + flushedCount: totalFlushed, + pendingCount: queue.length, + }; + } + + return { + enqueue, + flush, + pendingCount: () => queue.length, + isFlushing: () => activeFlush !== null, + peekPending: () => queue.slice(), + }; +} diff --git a/packages/frontend/hosts/web/src/pdf-client.js b/packages/frontend/hosts/web/src/pdf-client.js new file mode 100644 index 0000000000..07caadea5c --- /dev/null +++ b/packages/frontend/hosts/web/src/pdf-client.js @@ -0,0 +1,760 @@ +// @ts-check + +/** + * Lazy on-demand client for the pure-Rust `hayro` PDF Web Worker. + * Spawns zero workers and fetches zero `.wasm` bytes until a caller requests + * a PDF page count or page render. + */ + +/** + * @typedef {Object} PdfRenderedPage + * @property {number} pageCount + * @property {number} widthPx + * @property {number} heightPx + * @property {Uint8Array} rgba + * @property {number} scale + * @property {boolean} fromCache + */ + +/** + * @typedef {Object} PdfWorkerLike + * @property {(message: unknown, transfer?: Transferable[]) => void} postMessage + * @property {(type: string, listener: (event: MessageEvent) => void) => void} addEventListener + * @property {(type: string, listener: (event: MessageEvent) => void) => void} removeEventListener + * @property {() => void} [terminate] + */ + +/** + * @typedef {Object} PdfWorkerLoaderLike + * @property {(kind: 'pdf') => PdfWorkerLike} loadWorker + * @property {(kind: 'pdf') => boolean} [hasLoadedWorker] + * @property {(kind: 'pdf') => boolean} [terminateWorker] + */ + +const DEFAULT_MAX_CACHE_BYTES = 16 * 1024 * 1024; +const MIN_RENDER_SCALE = 0.25; +const MAX_RENDER_SCALE = 4; + +/** + * Clamps and normalizes a numeric render scale to match worker rasterization + * bounds (`[0.25, 4.0]`). + * + * @param {number | undefined} scale + * @returns {number} + */ +function normalizeScale(scale) { + if (typeof scale !== 'number' || !Number.isFinite(scale) || scale <= 0) { + return 1; + } + const clamped = Math.min(MAX_RENDER_SCALE, Math.max(MIN_RENDER_SCALE, scale)); + return Math.round(clamped * 100) / 100; +} + +/** + * Builds the deterministic cache and deduplication key for a PDF page render. + * + * @param {string} docKey + * @param {number} pageIndex + * @param {number} scale + * @returns {string} + */ +export function buildPdfPageCacheKey(docKey, pageIndex, scale) { + return `${docKey}:${pageIndex}:${normalizeScale(scale)}`; +} + +/** + * One `docKey` and the PDF bytes it was last opened with. + * + * @typedef {Object} PdfDocEntry + * @property {WeakRef} bytes The caller's bytes. Only identity is kept, never a copy. + * @property {number} byteLength + * @property {number | null} docId Handle in the current worker, or `null` when not open there. + * @property {number | undefined} pageCount + * @property {Promise | null} opened Answer to the last `pdf_open`, with the page count. + * @property {number} inFlight Worker requests not answered yet. + * @property {number} waiters Callers waiting for room in the open budget. + */ + +const MAX_OPEN_DOCS = 8; +const MAX_OPEN_DOC_BYTES = 256 * 1024 * 1024; +const MAX_KNOWN_DOCS = 64; +const MAX_DOC_ID = 0xffffffff; + +/** + * Tells whether `next` holds the same PDF as the bytes an entry was opened + * with. The same object is the same PDF. Another object is compared byte for + * byte while the first one is still alive, and is a different PDF otherwise. + * + * @param {PdfDocEntry} entry + * @param {Uint8Array} next + */ +function holdsSameBytes(entry, next) { + const prev = entry.bytes.deref(); + if (prev === next) { + return true; + } + if (!prev || prev.byteLength !== next.byteLength) { + return false; + } + for (let i = 0; i < next.byteLength; i += 1) { + if (prev[i] !== next[i]) { + return false; + } + } + entry.bytes = new WeakRef(next); + return true; +} + +/** + * Creates a lazy PDF preview client with request multiplexing, in-flight + * deduplication, Transferable zero-copy RGBA delivery, and byte-bounded LRU + * eviction for offscreen pages. + * + * The worker keeps each opened PDF parsed under a `docId` that this client + * assigns. The bytes cross to the worker once per open. At most + * `MAX_OPEN_DOCS` documents and `MAX_OPEN_DOC_BYTES` are open at any time. + * An open closes least recently used documents with no unanswered request, + * and only when that makes room. Otherwise it waits until a request is + * answered or a document closes. Empty documents and documents larger than + * `MAX_OPEN_DOC_BYTES` never go to the worker. + * + * @param {Object} options + * @param {PdfWorkerLoaderLike} options.workerLoader + * @param {number} [options.maxCacheBytes] + */ +export function createPdfPreviewClient(options) { + const workerLoader = options.workerLoader; + const maxCacheBytes = Math.max( + 1, + options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES + ); + + /** @type {PdfWorkerLike | null} */ + let worker = null; + /** @type {(() => void) | null} */ + let detachWorker = null; + let disposed = false; + let nextRequestId = 1; + let nextDocId = 1; + let totalCacheBytes = 0; + let evictions = 0; + let dedupHits = 0; + let cacheHits = 0; + + /** @type {Map void, reject: (error: Error) => void }>} */ + const pendingRpc = new Map(); + + /** @type {Map>} */ + const inFlightRenders = new Map(); + + /** Known documents by `docKey`, least recently used first. @type {Map} */ + const docs = new Map(); + + /** @type {Map} */ + const lruCache = new Map(); + + /** @type {Set} */ + let visibleKeys = new Set(); + + /** Opens that wait for room in the open budget. @type {(() => void)[]} */ + let openWaiters = []; + + function wakeOpenWaiters() { + const waiters = openWaiters; + openWaiters = []; + for (const wake of waiters) { + wake(); + } + } + + /** + * Stops listening to the current worker, terminates it, and fails every + * unanswered request. Every document then counts as closed. + * + * @param {Error} err + */ + function dropWorker(err) { + const rpcs = Array.from(pendingRpc.values()); + pendingRpc.clear(); + if (worker) { + const deadWorker = worker; + worker = null; + detachWorker?.(); + detachWorker = null; + if (typeof workerLoader.terminateWorker === 'function') { + workerLoader.terminateWorker('pdf'); + } else { + deadWorker.terminate?.(); + } + } + for (const entry of docs.values()) { + entry.docId = null; + } + nextDocId = 1; + for (const rpc of rpcs) { + rpc.reject(err); + } + wakeOpenWaiters(); + } + + function ensureWorker() { + if (disposed) { + throw new Error('PDF preview client is disposed'); + } + if (!worker) { + const ownWorker = workerLoader.loadWorker('pdf'); + /** @param {MessageEvent} event */ + const onMessage = event => { + if (ownWorker !== worker) { + return; + } + const msg = event?.data; + if (!msg || typeof msg !== 'object') { + return; + } + const entry = pendingRpc.get(msg.id); + if (!entry) { + return; + } + pendingRpc.delete(msg.id); + if (msg.ok) { + entry.resolve(msg.result); + } else { + entry.reject(new Error(msg.error || 'PDF worker request failed')); + } + }; + /** @param {Event} event */ + const onError = event => { + if (ownWorker !== worker) { + return; + } + const message = + /** @type {{ message?: string }} */ ( + /** @type {unknown} */ (event) + )?.message || `PDF worker ${event?.type || 'error'}`; + dropWorker(new Error(message)); + }; + ownWorker.addEventListener('message', onMessage); + ownWorker.addEventListener('error', onError); + ownWorker.addEventListener('messageerror', onError); + detachWorker = () => { + ownWorker.removeEventListener('message', onMessage); + ownWorker.removeEventListener('error', onError); + ownWorker.removeEventListener('messageerror', onError); + }; + worker = ownWorker; + } + return worker; + } + + /** + * Sends one RPC message over the lazily spawned PDF worker. + * + * @param {Record} payload + * @returns {Promise} + */ + function sendRpc(payload) { + const activeWorker = ensureWorker(); + const id = nextRequestId++; + return new Promise((resolve, reject) => { + pendingRpc.set(id, { resolve, reject }); + activeWorker.postMessage({ ...payload, id }); + }); + } + + /** + * Sends one RPC for a document and keeps it open while the RPC is unanswered. + * + * @param {PdfDocEntry} entry + * @param {Record} payload + */ + function sendDocRpc(entry, payload) { + entry.inFlight += 1; + return sendRpc(payload).finally(() => { + entry.inFlight -= 1; + if (entry.inFlight === 0) { + pruneKnownDocs(); + wakeOpenWaiters(); + } + }); + } + + /** @param {string} docKey */ + function dropCachedPages(docKey) { + const prefix = `${docKey}:`; + for (const [key, item] of lruCache) { + if (key.startsWith(prefix)) { + lruCache.delete(key); + totalCacheBytes -= item.byteLength; + } + } + for (const key of inFlightRenders.keys()) { + if (key.startsWith(prefix)) { + inFlightRenders.delete(key); + } + } + } + + /** + * Trims idle known document entries down to `MAX_KNOWN_DOCS`, keeping + * open, in-flight, waiting, and `keepEntry` entries intact. + * + * @param {PdfDocEntry} [keepEntry] + */ + function pruneKnownDocs(keepEntry) { + if (docs.size <= MAX_KNOWN_DOCS) { + return; + } + for (const [key, known] of docs) { + if (docs.size <= MAX_KNOWN_DOCS) { + break; + } + if ( + known !== keepEntry && + known.docId === null && + known.inFlight === 0 && + known.waiters === 0 + ) { + docs.delete(key); + dropCachedPages(key); + } + } + } + + /** + * @param {PdfDocEntry} entry + * @param {PdfDocEntry} [keepEntry] + */ + function closeDoc(entry, keepEntry) { + if (entry.docId === null) { + return; + } + const docId = entry.docId; + entry.docId = null; + sendRpc({ op: 'pdf_close', docId }).catch(() => {}); + pruneKnownDocs(keepEntry); + wakeOpenWaiters(); + } + + /** + * Makes room for `entry` in the open budget. Closes least recently used + * open documents with no unanswered request, but only when closing them + * makes `entry` fit. Returns whether `entry` fits. + * + * @param {PdfDocEntry} entry + */ + function admitOpen(entry) { + let openDocs = 0; + let openBytes = 0; + /** @type {PdfDocEntry[]} */ + const idle = []; + for (const known of docs.values()) { + if (known.docId !== null) { + openDocs += 1; + openBytes += known.byteLength; + if (known.inFlight === 0) { + idle.push(known); + } + } + } + const fits = () => + openDocs < MAX_OPEN_DOCS && + openBytes + entry.byteLength <= MAX_OPEN_DOC_BYTES; + const victims = []; + for (const known of idle) { + if (fits()) { + break; + } + victims.push(known); + openDocs -= 1; + openBytes -= known.byteLength; + } + if (!fits()) { + return false; + } + for (const victim of victims) { + closeDoc(victim, entry); + } + return true; + } + + /** + * Returns the entry of `docKey` for `pdfBytes`. New bytes for a known + * `docKey` replace its entry and drop its page count, cached pages and + * shared in-flight renders. + * + * @param {string} docKey + * @param {Uint8Array} pdfBytes + * @returns {PdfDocEntry} + */ + function resolveDoc(docKey, pdfBytes) { + let entry = docs.get(docKey); + if (entry && !holdsSameBytes(entry, pdfBytes)) { + const hadWaiters = entry.waiters > 0; + docs.delete(docKey); + dropCachedPages(docKey); + closeDoc(entry); + if (hadWaiters) { + wakeOpenWaiters(); + } + entry = undefined; + } + if (entry) { + docs.delete(docKey); + } else { + entry = { + bytes: new WeakRef(pdfBytes), + byteLength: pdfBytes.byteLength, + docId: null, + pageCount: undefined, + opened: null, + inFlight: 0, + waiters: 0, + }; + } + docs.set(docKey, entry); + pruneKnownDocs(entry); + return entry; + } + + /** + * Opens `entry` in the current worker unless it is open there, and returns + * its `docId`, or `null` when the open budget has no room now. The open + * message goes out before any render of the same document, so renders + * follow at once without waiting for its answer. + * + * @param {string} docKey + * @param {PdfDocEntry} entry + * @param {Uint8Array} pdfBytes + * @returns {number | null} + */ + function openDoc(docKey, entry, pdfBytes) { + ensureWorker(); + if (entry.docId !== null) { + return entry.docId; + } + if (nextDocId > MAX_DOC_ID) { + dropWorker(new Error('PDF worker restarted after its last document id')); + ensureWorker(); + } + if (!admitOpen(entry)) { + return null; + } + const docId = nextDocId++; + entry.docId = docId; + const opened = sendDocRpc(entry, { op: 'pdf_open', docId, pdfBytes }).then( + result => { + const count = Number(result.pageCount ?? 0); + if (docs.get(docKey) === entry) { + entry.pageCount = count; + } + return count; + }, + err => { + // The worker holds no document for a failed open. + if (entry.docId === docId) { + entry.docId = null; + pruneKnownDocs(); + wakeOpenWaiters(); + } + throw err; + } + ); + // Callers that need the page count read `entry.opened`; nobody else must see a rejection. + opened.catch(() => {}); + entry.opened = opened; + return docId; + } + + /** + * Opens `entry` and calls `send` with its `docId`: at once when the open + * budget has room, or after a request is answered or a document closes. + * + * @template T + * @param {string} docKey + * @param {PdfDocEntry} entry + * @param {Uint8Array} pdfBytes + * @param {(docId: number) => Promise} send + * @returns {Promise} + */ + function withOpenDoc(docKey, entry, pdfBytes, send) { + const docId = openDoc(docKey, entry, pdfBytes); + if (docId !== null) { + return send(docId); + } + entry.waiters += 1; + return new Promise(resolve => openWaiters.push(resolve)).then(() => { + entry.waiters -= 1; + if (disposed) { + throw new Error('PDF preview client is disposed'); + } + if (docs.get(docKey) !== entry) { + throw new Error('PDF bytes changed before the document opened'); + } + return withOpenDoc(docKey, entry, pdfBytes, send); + }); + } + + /** + * @param {Uint8Array} pdfBytes + * @returns {Error | null} + */ + function rejectSize(pdfBytes) { + const size = pdfBytes?.byteLength ?? 0; + if (size > 0 && size <= MAX_OPEN_DOC_BYTES) { + return null; + } + return new Error( + `PDF of ${size} B is outside the 1..${MAX_OPEN_DOC_BYTES} B worker limit` + ); + } + + /** + * Evicts least-recently-used entries until `totalCacheBytes <= maxCacheBytes`. + * Prefers evicting offscreen keys before visible keys. + * + * @param {string} [protectedKey] + */ + function enforceCacheBudget(protectedKey) { + if (totalCacheBytes <= maxCacheBytes) { + return; + } + // Pass 1: evict offscreen entries from oldest to newest. + for (const [key, item] of lruCache.entries()) { + if (totalCacheBytes <= maxCacheBytes) { + return; + } + if (key === protectedKey || visibleKeys.has(key)) { + continue; + } + lruCache.delete(key); + totalCacheBytes -= item.byteLength; + evictions += 1; + } + // Pass 2: if still over budget, evict oldest entries except the just-inserted key. + for (const [key, item] of lruCache.entries()) { + if (totalCacheBytes <= maxCacheBytes) { + return; + } + if (key === protectedKey) { + continue; + } + lruCache.delete(key); + totalCacheBytes -= item.byteLength; + evictions += 1; + } + } + + /** + * Updates the set of currently visible page cache keys so offscreen pages + * are evicted first under memory pressure. + * + * @param {Iterable} keys + */ + function setVisibleKeys(keys) { + visibleKeys = new Set(keys); + } + + /** + * Returns the page count for a PDF document, lazily spawning `pdf-worker` + * on the first uncached request. + * + * @param {{ docKey: string, pdfBytes: Uint8Array }} params + * @returns {Promise} + */ + function getPageCount(params) { + if (disposed) { + return Promise.reject(new Error('PDF preview client is disposed')); + } + const sizeError = rejectSize(params.pdfBytes); + if (sizeError) { + return Promise.reject(sizeError); + } + const entry = resolveDoc(params.docKey, params.pdfBytes); + if (entry.pageCount !== undefined) { + cacheHits += 1; + return Promise.resolve(entry.pageCount); + } + if (entry.docId !== null && entry.opened) { + dedupHits += 1; + return entry.opened; + } + return withOpenDoc( + params.docKey, + entry, + params.pdfBytes, + () => /** @type {Promise} */ (entry.opened) + ); + } + + /** + * Renders one PDF page to RGBA pixels, deduplicating concurrent requests for + * the same `(docKey, pageIndex, scale)` and caching results under the byte + * budget. + * + * @param {{ docKey: string, pdfBytes: Uint8Array, pageIndex: number, scale?: number }} params + * @returns {Promise} + */ + function renderPage(params) { + if (disposed) { + return Promise.reject(new Error('PDF preview client is disposed')); + } + const sizeError = rejectSize(params.pdfBytes); + if (sizeError) { + return Promise.reject(sizeError); + } + const entry = resolveDoc(params.docKey, params.pdfBytes); + const scale = normalizeScale(params.scale); + const cacheKey = buildPdfPageCacheKey( + params.docKey, + params.pageIndex, + scale + ); + + const cached = lruCache.get(cacheKey); + if (cached) { + if (cached.rgba.byteLength === 0) { + lruCache.delete(cacheKey); + totalCacheBytes = Math.max(0, totalCacheBytes - cached.byteLength); + } else { + // Refresh LRU recency and return an owned copy so caller transfers cannot empty cache. + lruCache.delete(cacheKey); + lruCache.set(cacheKey, cached); + cacheHits += 1; + return Promise.resolve({ + pageCount: cached.pageCount, + widthPx: cached.widthPx, + heightPx: cached.heightPx, + rgba: cached.rgba.slice(), + scale: cached.scale, + fromCache: true, + }); + } + } + + const wrapPrivateResult = shared => + shared.then(res => ({ + pageCount: res.pageCount, + widthPx: res.widthPx, + heightPx: res.heightPx, + rgba: res.rgba.slice(), + scale: res.scale, + fromCache: false, + })); + + const inFlight = inFlightRenders.get(cacheKey); + if (inFlight) { + dedupHits += 1; + return wrapPrivateResult(inFlight); + } + + const sharedPromise = withOpenDoc( + params.docKey, + entry, + params.pdfBytes, + docId => { + const opened = entry.opened; + return sendDocRpc(entry, { + op: 'pdf_render', + docId, + pageIndex: params.pageIndex, + scale, + }).catch(async err => { + // A failed open reports its parse error instead of the unknown docId error. + await opened; + throw err; + }); + } + ) + .then(result => { + const rgba = + result.rgba instanceof Uint8Array + ? result.rgba + : new Uint8Array(result.rgba); + const pageCount = Number(result.pageCount); + const widthPx = Number(result.widthPx); + const heightPx = Number(result.heightPx); + + const byteLength = rgba.byteLength; + if (docs.get(params.docKey) === entry) { + entry.pageCount = pageCount; + if (byteLength <= maxCacheBytes) { + const prev = lruCache.get(cacheKey); + if (prev) { + totalCacheBytes -= prev.byteLength; + lruCache.delete(cacheKey); + } + lruCache.set(cacheKey, { + pageCount, + widthPx, + heightPx, + rgba, + scale, + byteLength, + }); + totalCacheBytes += byteLength; + enforceCacheBudget(cacheKey); + } + } + + return { + pageCount, + widthPx, + heightPx, + rgba, + scale, + fromCache: false, + }; + }) + .finally(() => { + if (inFlightRenders.get(cacheKey) === sharedPromise) { + inFlightRenders.delete(cacheKey); + } + }); + + inFlightRenders.set(cacheKey, sharedPromise); + return wrapPrivateResult(sharedPromise); + } + + /** + * Terminates the PDF worker, clears cached pixel buffers, and rejects any + * remaining pending RPCs. + */ + function dispose() { + if (disposed) { + return; + } + disposed = true; + dropWorker(new Error('PDF preview client disposed')); + inFlightRenders.clear(); + docs.clear(); + lruCache.clear(); + visibleKeys.clear(); + totalCacheBytes = 0; + } + + return Object.freeze({ + getPageCount, + renderPage, + setVisibleKeys, + dispose, + getStats: () => { + let openDocs = 0; + for (const entry of docs.values()) { + if (entry.docId !== null) openDocs += 1; + } + return { + workerSpawned: worker !== null, + disposed, + activeRequests: pendingRpc.size, + openDocs, + cacheEntries: lruCache.size, + cacheBytes: totalCacheBytes, + maxCacheBytes, + evictions, + dedupHits, + cacheHits, + }; + }, + }); +} diff --git a/packages/frontend/hosts/web/src/selection-overlay.js b/packages/frontend/hosts/web/src/selection-overlay.js new file mode 100644 index 0000000000..493f70fde0 --- /dev/null +++ b/packages/frontend/hosts/web/src/selection-overlay.js @@ -0,0 +1,1181 @@ +// @ts-check + +/** + * Canvas-drawn text selection overlay, teardrop handles, and mobile clipboard + * gesture bridge. Draws all selection visuals on `#app-canvas` with zero + * floating DOM nodes. + */ + +/** + * @typedef {Object} Rect + * @property {number} x + * @property {number} y + * @property {number} width + * @property {number} height + */ + +/** + * @typedef {Object} CaretAnchor + * @property {number} x + * @property {number} y + * @property {number} height + * @property {'ltr' | 'rtl'} [dir] + */ + +/** + * @typedef {Object} SafeAreaInsets + * @property {number} top + * @property {number} right + * @property {number} bottom + * @property {number} left + */ + +/** + * @typedef {'copy' | 'cut' | 'paste' | 'select-all'} SelectionActionId + */ + +/** + * @typedef {Object} SelectionHandleLayout + * @property {'start' | 'end'} kind + * @property {'left' | 'right'} flare + * @property {number} stemX + * @property {number} stemTop + * @property {number} stemBottom + * @property {number} headCx + * @property {number} headCy + * @property {number} radius + * @property {Rect} hitRect + */ + +/** + * @typedef {Object} SelectionMenuItemLayout + * @property {SelectionActionId} id + * @property {string} label + * @property {number} x + * @property {number} y + * @property {number} width + * @property {number} height + */ + +/** + * @typedef {Object} SelectionMenuLayout + * @property {boolean} visible + * @property {'above' | 'below'} placement + * @property {'ltr' | 'rtl'} dir + * @property {string} locale + * @property {number} x + * @property {number} y + * @property {number} width + * @property {number} height + * @property {number} arrowX + * @property {SelectionMenuItemLayout[]} items + */ + +/** + * @typedef {Object} SelectionLoupeLayout + * @property {boolean} visible + * @property {'start' | 'end' | null} handle + * @property {number} cx + * @property {number} cy + * @property {number} radius + */ + +/** + * @typedef {Object} SelectionOverlayLayout + * @property {Rect[]} rects + * @property {SelectionHandleLayout} startHandle + * @property {SelectionHandleLayout} endHandle + * @property {SelectionMenuLayout} menu + * @property {SelectionLoupeLayout} loupe + * @property {boolean} dragging + */ + +/** + * @typedef {Object} SelectionOverlayInput + * @property {{ width: number, height: number, safeArea?: Partial }} viewport + * @property {Rect[]} rects + * @property {CaretAnchor} caretStart + * @property {CaretAnchor} caretEnd + * @property {boolean} [dragging] + * @property {'start' | 'end' | null} [activeHandle] + * @property {SelectionActionId[]} [actions] + * @property {boolean} [readOnly] + * @property {boolean} [canPaste] + * @property {number} [edgeMargin] + * @property {string} [locale] + * @property {'ltr' | 'rtl'} [dir] + * @property {Partial>} [labels] + * @property {(label: string) => number} [measureText] + */ + +/** @type {Readonly>>>} */ +const LOCALIZED_ACTION_LABELS = Object.freeze({ + en: Object.freeze({ + copy: 'Copy', + cut: 'Cut', + paste: 'Paste', + 'select-all': 'Select All', + }), + 'zh-hans': Object.freeze({ + copy: '复制', + cut: '剪切', + paste: '粘贴', + 'select-all': '全选', + }), + 'zh-hant': Object.freeze({ + copy: '複製', + cut: '剪下', + paste: '貼上', + 'select-all': '全選', + }), + ar: Object.freeze({ + copy: 'نسخ', + cut: 'قص', + paste: 'لصق', + 'select-all': 'تحديد الكل', + }), +}); + +const DEFAULT_ACTIONS = /** @type {const} */ ([ + 'copy', + 'cut', + 'paste', + 'select-all', +]); + +export const SELECTION_MENU_FONT = + '600 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'; +const MIN_ACTION_WIDTH_PX = 44; +const ACTION_HORIZONTAL_PADDING_PX = 28; +const MIN_EDGE_MARGIN_PX = 12; +const HANDLE_RADIUS_PX = 7.5; +const HANDLE_HIT_HALF_SIZE_PX = 22; +const MENU_HEIGHT_PX = 40; +const MENU_GAP_PX = 12; +const LOUPE_RADIUS_PX = 28; + +/** + * Normalizes a BCP-47 language tag to a built-in selection menu locale key, + * inspecting primary language, script, and region subtags before singleton + * extensions (`-u-`, `-t-`, `-x-`). + * + * @param {string | null | undefined} rawLocale + * @returns {'en' | 'zh-hans' | 'zh-hant' | 'ar'} + */ +export function resolveSelectionLocale(rawLocale) { + const candidate = + (typeof rawLocale === 'string' && rawLocale.trim()) || + globalThis.document?.documentElement?.lang?.trim() || + globalThis.navigator?.language?.trim() || + 'en'; + const parts = candidate.toLowerCase().replace(/_/g, '-').split('-'); + const lang = parts[0] || 'en'; + let script = ''; + let region = ''; + for (let i = 1; i < parts.length; i += 1) { + const sub = parts[i]; + if (sub.length === 1) { + break; + } + if (!script && /^[a-z]{4}$/.test(sub)) { + script = sub; + } else if (!region && (/^[a-z]{2}$/.test(sub) || /^\d{3}$/.test(sub))) { + region = sub; + } + } + if (lang === 'zh') { + if (script === 'hans') { + return 'zh-hans'; + } + if (script === 'hant') { + return 'zh-hant'; + } + if (region === 'tw' || region === 'hk' || region === 'mo') { + return 'zh-hant'; + } + return 'zh-hans'; + } + if (lang === 'ar') { + return 'ar'; + } + return 'en'; +} + +/** + * Resolves localized labels for selection menu actions with optional overrides. + * + * @param {string | null | undefined} locale + * @param {Partial> | null | undefined} [customLabels] + * @returns {Record} + */ +export function resolveSelectionActionLabels(locale, customLabels) { + const base = LOCALIZED_ACTION_LABELS[resolveSelectionLocale(locale)]; + /** @type {Record} */ + const resolved = { ...base }; + if (customLabels) { + for (const id of DEFAULT_ACTIONS) { + const override = customLabels[id]; + if (typeof override === 'string' && override.trim().length > 0) { + resolved[id] = override; + } + } + } + return resolved; +} + +/** + * Resolves horizontal layout direction (`ltr` or `rtl`) for the selection menu, + * inferring `rtl` when the resolved menu locale is Arabic and neither explicit + * `dir` nor `document.documentElement.dir` is set. + * + * @param {'ltr' | 'rtl' | string | null | undefined} rawDir + * @param {'en' | 'zh-hans' | 'zh-hant' | 'ar'} resolvedLocale + * @returns {'ltr' | 'rtl'} + */ +function resolveSelectionDirection(rawDir, resolvedLocale) { + if (rawDir === 'rtl' || rawDir === 'ltr') { + return rawDir; + } + const docDir = globalThis.document?.documentElement?.dir + ?.trim() + .toLowerCase(); + if (docDir === 'rtl' || docDir === 'ltr') { + return docDir; + } + return resolvedLocale === 'ar' ? 'rtl' : 'ltr'; +} + +/** + * Estimates rendered text width in CSS pixels for `MENU_FONT` when no Canvas 2D + * `measureText` callback is supplied. + * + * @param {string} label + * @returns {number} + */ +function estimateLabelWidthPx(label) { + let width = 0; + for (const ch of label) { + const code = ch.codePointAt(0) ?? 0; + if ( + (code >= 0x2e80 && code <= 0x9fff) || + (code >= 0xf900 && code <= 0xfaff) || + (code >= 0xfe30 && code <= 0xfe4f) || + (code >= 0xff00 && code <= 0xffef) + ) { + width += 13.5; + } else if ( + (code >= 0x0590 && code <= 0x08ff) || + (code >= 0xfb50 && code <= 0xfdff) || + (code >= 0xfe70 && code <= 0xfeff) + ) { + width += 7.8; + } else if (ch === ' ') { + width += 4.5; + } else if (ch >= 'A' && ch <= 'Z') { + width += 8.8; + } else { + width += 7.4; + } + } + return width; +} + +/** + * Computes the dynamic touch-safe button width for a menu label. + * + * @param {string} label + * @param {((label: string) => number) | undefined} measureText + * @returns {number} + */ +function computeActionWidthPx(label, measureText) { + let measured = Number.NaN; + if (typeof measureText === 'function') { + const candidate = measureText(label); + if ( + typeof candidate === 'number' && + Number.isFinite(candidate) && + candidate > 0 + ) { + measured = candidate; + } + } + const textWidth = Number.isFinite(measured) + ? measured + : estimateLabelWidthPx(label); + return Math.max( + MIN_ACTION_WIDTH_PX, + Math.ceil(textWidth) + ACTION_HORIZONTAL_PADDING_PX + ); +} + +/** + * Clamps a numeric value to `[min, max]`. + * + * @param {number} value + * @param {number} min + * @param {number} max + * @returns {number} + */ +function clamp(value, min, max) { + if (max < min) { + return min; + } + return Math.max(min, Math.min(max, value)); +} + +/** + * Returns true when `(x, y)` lies inside `rect`. + * + * @param {Rect} rect + * @param {number} x + * @param {number} y + * @returns {boolean} + */ +export function pointInRect(rect, x, y) { + return ( + x >= rect.x && + x <= rect.x + rect.width && + y >= rect.y && + y <= rect.y + rect.height + ); +} + +/** + * Builds one teardrop handle layout with an outward circular head. + * + * @param {'start' | 'end'} kind + * @param {CaretAnchor} caret + * @param {'left' | 'right'} flare + * @param {number} headCx + * @returns {SelectionHandleLayout} + */ +function buildHandleLayout(kind, caret, flare, headCx) { + const stemTop = caret.y; + const stemBottom = caret.y + Math.max(12, caret.height); + const headCy = stemBottom + HANDLE_RADIUS_PX + 2; + const hitLeft = Math.min(caret.x, headCx) - HANDLE_HIT_HALF_SIZE_PX; + const hitRight = Math.max(caret.x, headCx) + HANDLE_HIT_HALF_SIZE_PX; + const hitTop = stemTop - 8; + const hitBottom = headCy + HANDLE_HIT_HALF_SIZE_PX; + return { + kind, + flare, + stemX: caret.x, + stemTop, + stemBottom, + headCx, + headCy, + radius: HANDLE_RADIUS_PX, + hitRect: { + x: hitLeft, + y: hitTop, + width: hitRight - hitLeft, + height: hitBottom - hitTop, + }, + }; +} + +/** + * Computes pure layout geometry for selection highlights, outward-flared + * teardrop handles, and the floating action menu. + * + * @param {SelectionOverlayInput} input + * @returns {SelectionOverlayLayout} + */ +export function computeSelectionOverlayLayout(input) { + const safeTop = Math.max(0, input.viewport.safeArea?.top ?? 0); + const safeRight = Math.max(0, input.viewport.safeArea?.right ?? 0); + const safeBottom = Math.max(0, input.viewport.safeArea?.bottom ?? 0); + const safeLeft = Math.max(0, input.viewport.safeArea?.left ?? 0); + const edgeMargin = Math.max( + MIN_EDGE_MARGIN_PX, + input.edgeMargin ?? MIN_EDGE_MARGIN_PX + ); + + const rects = (input.rects || []).map(r => ({ + x: r.x, + y: r.y, + width: Math.max(0, r.width), + height: Math.max(0, r.height), + })); + + const start = input.caretStart; + const end = input.caretEnd; + const startIsVisualLeft = + start.x < end.x || (start.x === end.x && start.dir !== 'rtl'); + /** @type {'left' | 'right'} */ + const startFlare = startIsVisualLeft ? 'left' : 'right'; + /** @type {'left' | 'right'} */ + const endFlare = startIsVisualLeft ? 'right' : 'left'; + + const flareOffset = HANDLE_RADIUS_PX * 0.9; + let startHeadCx = + start.x + (startFlare === 'left' ? -flareOffset : flareOffset); + let endHeadCx = end.x + (endFlare === 'left' ? -flareOffset : flareOffset); + + const startHeadCy = + start.y + Math.max(12, start.height) + HANDLE_RADIUS_PX + 2; + const endHeadCy = end.y + Math.max(12, end.height) + HANDLE_RADIUS_PX + 2; + const minCenterGap = HANDLE_RADIUS_PX * 2 + 4; + if (Math.abs(startHeadCy - endHeadCy) < HANDLE_RADIUS_PX * 2 + 2) { + const gap = Math.abs(endHeadCx - startHeadCx); + if (gap < minCenterGap) { + const push = (minCenterGap - gap) / 2; + startHeadCx += startFlare === 'left' ? -push : push; + endHeadCx += endFlare === 'left' ? -push : push; + } + } + + const startHandle = buildHandleLayout( + 'start', + start, + startFlare, + startHeadCx + ); + const endHandle = buildHandleLayout('end', end, endFlare, endHeadCx); + + const locale = resolveSelectionLocale(input.locale); + const actionLabels = resolveSelectionActionLabels(locale, input.labels); + const dir = resolveSelectionDirection(input.dir, locale); + + const requestedActions = input.actions + ? [...input.actions] + : [...DEFAULT_ACTIONS]; + const filteredActions = requestedActions.filter(id => { + if (input.readOnly && (id === 'cut' || id === 'paste')) { + return false; + } + if (input.canPaste === false && id === 'paste') { + return false; + } + return Boolean(actionLabels[id]); + }); + + const actionSpecs = filteredActions.map(id => { + const label = actionLabels[id]; + return { + id, + label, + width: computeActionWidthPx(label, input.measureText), + }; + }); + + const maxBarWidth = Math.max( + 120, + input.viewport.width - safeLeft - safeRight - edgeMargin * 2 + ); + const rawWidth = actionSpecs.reduce((sum, spec) => sum + spec.width, 0); + const floorTotal = actionSpecs.length * MIN_ACTION_WIDTH_PX; + /** @type {number[]} */ + let allocatedWidths; + if (rawWidth <= maxBarWidth) { + allocatedWidths = actionSpecs.map(spec => spec.width); + } else if (maxBarWidth <= floorTotal) { + const each = actionSpecs.length > 0 ? maxBarWidth / actionSpecs.length : 0; + allocatedWidths = actionSpecs.map(() => each); + } else { + const extraBudget = maxBarWidth - floorTotal; + const excesses = actionSpecs.map(spec => + Math.max(0, spec.width - MIN_ACTION_WIDTH_PX) + ); + const totalExcess = excesses.reduce((sum, excess) => sum + excess, 0); + allocatedWidths = excesses.map(excess => + totalExcess > 0 + ? MIN_ACTION_WIDTH_PX + (excess / totalExcess) * extraBudget + : MIN_ACTION_WIDTH_PX + ); + } + const barWidth = Math.min(rawWidth, maxBarWidth); + + const bounds = rects.reduce( + (acc, r) => ({ + minX: Math.min(acc.minX, r.x), + minY: Math.min(acc.minY, r.y), + maxX: Math.max(acc.maxX, r.x + r.width), + maxY: Math.max(acc.maxY, r.y + r.height), + }), + { + minX: Math.min(start.x, end.x), + minY: Math.min(start.y, end.y), + maxX: Math.max(start.x, end.x), + maxY: Math.max(start.y + start.height, end.y + end.height), + } + ); + + const anchorMidX = (bounds.minX + bounds.maxX) / 2; + const minX = safeLeft + edgeMargin; + const maxX = Math.max( + minX, + input.viewport.width - safeRight - edgeMargin - barWidth + ); + const menuX = clamp(anchorMidX - barWidth / 2, minX, maxX); + + const aboveY = bounds.minY - MENU_GAP_PX - MENU_HEIGHT_PX; + const belowY = + Math.max(bounds.maxY, startHandle.headCy, endHandle.headCy) + + HANDLE_RADIUS_PX + + MENU_GAP_PX; + const fitsAbove = aboveY >= safeTop + 8; + /** @type {'above' | 'below'} */ + const placement = fitsAbove ? 'above' : 'below'; + const menuY = fitsAbove + ? aboveY + : clamp( + belowY, + safeTop + 8, + Math.max( + safeTop + 8, + input.viewport.height - safeBottom - MENU_HEIGHT_PX - 8 + ) + ); + + let cursorX = dir === 'rtl' ? menuX + barWidth : menuX; + const items = actionSpecs.map((spec, index) => { + const itemWidth = allocatedWidths[index]; + const x = dir === 'rtl' ? cursorX - itemWidth : cursorX; + cursorX = dir === 'rtl' ? x : cursorX + itemWidth; + return { + id: spec.id, + label: spec.label, + x, + y: menuY, + width: itemWidth, + height: MENU_HEIGHT_PX, + }; + }); + + const dragging = Boolean(input.dragging); + const activeHandle = dragging ? input.activeHandle || 'end' : null; + const loupeAnchor = activeHandle === 'start' ? start : end; + const loupeCx = clamp( + loupeAnchor.x, + safeLeft + LOUPE_RADIUS_PX + 8, + input.viewport.width - safeRight - LOUPE_RADIUS_PX - 8 + ); + const loupeCy = Math.max( + safeTop + LOUPE_RADIUS_PX + 8, + loupeAnchor.y - LOUPE_RADIUS_PX - 14 + ); + + const hasCaretAnchor = + Boolean(start && end) && + Number.isFinite(start.x) && + Number.isFinite(start.y) && + Number.isFinite(end.x) && + Number.isFinite(end.y); + + return { + rects, + startHandle, + endHandle, + menu: { + visible: + !dragging && items.length > 0 && (rects.length > 0 || hasCaretAnchor), + placement, + dir, + locale, + x: menuX, + y: menuY, + width: barWidth, + height: MENU_HEIGHT_PX, + arrowX: clamp(anchorMidX, menuX + 16, menuX + barWidth - 16), + items, + }, + loupe: { + visible: dragging, + handle: activeHandle, + cx: loupeCx, + cy: loupeCy, + radius: LOUPE_RADIUS_PX, + }, + dragging, + }; +} + +/** + * Traces a rounded rectangle path on a Canvas 2D context. + * + * @param {CanvasRenderingContext2D} ctx + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + * @param {number} radius + */ +function traceRoundedRect(ctx, x, y, width, height, radius) { + const r = Math.min(radius, width / 2, height / 2); + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.lineTo(x + width - r, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + r); + ctx.lineTo(x + width, y + height - r); + ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height); + ctx.lineTo(x + r, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - r); + ctx.lineTo(x, y + r); + ctx.quadraticCurveTo(x, y, x + r, y); + ctx.closePath(); +} + +/** + * Draws a single teardrop handle on a Canvas 2D context. + * + * @param {CanvasRenderingContext2D} ctx + * @param {SelectionHandleLayout} handle + * @param {string} accentColor + * @param {string} ringColor + */ +function drawTeardropHandle(ctx, handle, accentColor, ringColor) { + ctx.save(); + ctx.strokeStyle = accentColor; + ctx.lineWidth = 2.2; + ctx.lineCap = 'round'; + ctx.beginPath(); + ctx.moveTo(handle.stemX, handle.stemTop); + ctx.lineTo(handle.stemX, handle.stemBottom); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(handle.stemX, handle.stemBottom - 1); + ctx.lineTo(handle.headCx, handle.headCy); + ctx.stroke(); + + ctx.fillStyle = accentColor; + ctx.beginPath(); + ctx.arc(handle.headCx, handle.headCy, handle.radius, 0, Math.PI * 2); + ctx.fill(); + + ctx.strokeStyle = ringColor; + ctx.lineWidth = 1.6; + ctx.stroke(); + ctx.restore(); +} + +/** + * Draws the selection highlight, dual teardrop handles, optional magnifier + * loupe, and floating action bar directly on a 2D canvas context. + * + * @param {CanvasRenderingContext2D} ctx + * @param {SelectionOverlayLayout} layout + * @param {{ theme?: 'light' | 'dark', activeActionId?: SelectionActionId | null }} [options] + */ +export function drawSelectionOverlay(ctx, layout, options = {}) { + const dark = options.theme === 'dark'; + const accent = dark ? '#4c9aff' : '#1e6efb'; + const selectionFill = dark + ? 'rgba(76, 154, 255, 0.28)' + : 'rgba(30, 110, 251, 0.2)'; + const menuBg = dark ? '#242731' : '#181a20'; + const menuBorder = dark + ? 'rgba(255, 255, 255, 0.14)' + : 'rgba(255, 255, 255, 0.1)'; + const menuDivider = 'rgba(255, 255, 255, 0.16)'; + const menuText = '#ffffff'; + const activeBg = 'rgba(255, 255, 255, 0.14)'; + const ringColor = dark ? '#141414' : '#ffffff'; + + ctx.save(); + ctx.fillStyle = selectionFill; + for (const r of layout.rects) { + traceRoundedRect(ctx, r.x, r.y, r.width, r.height, 4); + ctx.fill(); + } + + drawTeardropHandle(ctx, layout.startHandle, accent, ringColor); + drawTeardropHandle(ctx, layout.endHandle, accent, ringColor); + + if (layout.loupe.visible) { + ctx.save(); + ctx.shadowColor = 'rgba(0, 0, 0, 0.26)'; + ctx.shadowBlur = 14; + ctx.shadowOffsetY = 4; + ctx.fillStyle = dark ? '#22252e' : '#ffffff'; + ctx.beginPath(); + ctx.arc( + layout.loupe.cx, + layout.loupe.cy, + layout.loupe.radius, + 0, + Math.PI * 2 + ); + ctx.fill(); + ctx.restore(); + + ctx.save(); + ctx.strokeStyle = accent; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.arc( + layout.loupe.cx, + layout.loupe.cy, + layout.loupe.radius, + 0, + Math.PI * 2 + ); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(layout.loupe.cx, layout.loupe.cy - 10); + ctx.lineTo(layout.loupe.cx, layout.loupe.cy + 10); + ctx.stroke(); + ctx.restore(); + } + + if (layout.menu.visible) { + const { x, y, width, height, arrowX, placement, items } = layout.menu; + ctx.save(); + ctx.shadowColor = 'rgba(0, 0, 0, 0.28)'; + ctx.shadowBlur = 16; + ctx.shadowOffsetY = 6; + ctx.fillStyle = menuBg; + traceRoundedRect(ctx, x, y, width, height, 10); + ctx.fill(); + + // Pointer beak + ctx.beginPath(); + if (placement === 'above') { + ctx.moveTo(arrowX - 6, y + height); + ctx.lineTo(arrowX + 6, y + height); + ctx.lineTo(arrowX, y + height + 6); + } else { + ctx.moveTo(arrowX - 6, y); + ctx.lineTo(arrowX + 6, y); + ctx.lineTo(arrowX, y - 6); + } + ctx.closePath(); + ctx.fill(); + ctx.restore(); + + ctx.save(); + ctx.strokeStyle = menuBorder; + ctx.lineWidth = 1; + traceRoundedRect(ctx, x + 0.5, y + 0.5, width - 1, height - 1, 10); + ctx.stroke(); + + ctx.font = SELECTION_MENU_FONT; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + const isRtl = layout.menu.dir === 'rtl'; + if ('direction' in ctx) { + ctx.direction = isRtl ? 'rtl' : 'ltr'; + } + + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (options.activeActionId === item.id) { + ctx.fillStyle = activeBg; + traceRoundedRect( + ctx, + item.x + 2, + item.y + 2, + item.width - 4, + item.height - 4, + 8 + ); + ctx.fill(); + } + ctx.fillStyle = menuText; + ctx.fillText( + item.label, + item.x + item.width / 2, + item.y + item.height / 2, + Math.max(8, item.width - 8) + ); + + if (i < items.length - 1) { + const dividerX = isRtl ? item.x : item.x + item.width; + ctx.strokeStyle = menuDivider; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(dividerX, item.y + 9); + ctx.lineTo(dividerX, item.y + item.height - 9); + ctx.stroke(); + } + } + ctx.restore(); + } + + ctx.restore(); +} + +/** + * Executes a clipboard action synchronously inside the user gesture stack. + * Uses `navigator.clipboard` in secure contexts and falls back to `#ime` + * transient copy on non-HTTPS origins. Never deletes text on Cut if the + * clipboard write fails. + * + * @param {Object} params + * @param {SelectionActionId} params.action + * @param {() => string} params.getSelectedText + * @param {() => unknown} [params.getSelectionToken] + * @param {(captured?: { token: unknown, text: string }) => void} [params.deleteSelection] + * @param {(text: string) => void} [params.insertText] + * @param {() => void} [params.selectAll] + * @param {{ writeText?: (text: string) => Promise, readText?: () => Promise } | null} [params.clipboard] + * @param {boolean} [params.isSecureContext] + * @param {HTMLTextAreaElement | null} [params.imeEl] + * @param {Document | null} [params.doc] + * @returns {Promise<{ ok: boolean, action: SelectionActionId, method?: string, text?: string, reason?: string }>} + */ +export async function executeClipboardAction(params) { + const { + action, + getSelectedText, + getSelectionToken, + deleteSelection, + insertText, + selectAll, + clipboard = globalThis.navigator?.clipboard ?? null, + isSecureContext = globalThis.isSecureContext ?? true, + imeEl = null, + doc = globalThis.document ?? null, + } = params; + + if (action === 'select-all') { + selectAll?.(); + return { ok: true, action, method: 'editor' }; + } + + /** @param {string} text */ + async function writeTextInGesture(text) { + let asyncErrorReason = null; + if ( + isSecureContext && + clipboard && + typeof clipboard.writeText === 'function' + ) { + try { + await clipboard.writeText(text); + return { ok: true, method: 'async-clipboard' }; + } catch (error) { + asyncErrorReason = + error instanceof Error ? error.message : String(error); + } + } + if (imeEl && doc && typeof doc.execCommand === 'function') { + const prevReadOnly = imeEl.readOnly; + try { + imeEl.readOnly = false; + imeEl.value = text; + imeEl.focus?.({ preventScroll: true }); + imeEl.setSelectionRange?.(0, text.length); + const copied = Boolean(doc.execCommand('copy')); + imeEl.value = ''; + imeEl.setSelectionRange?.(0, 0); + imeEl.readOnly = prevReadOnly; + return copied + ? { ok: true, method: 'exec-command-fallback' } + : { + ok: false, + reason: asyncErrorReason || 'exec-command-copy-rejected', + }; + } catch (error) { + imeEl.value = ''; + imeEl.readOnly = prevReadOnly; + return { + ok: false, + reason: + asyncErrorReason || + (error instanceof Error ? error.message : String(error)), + }; + } + } + return { ok: false, reason: asyncErrorReason || 'clipboard-unavailable' }; + } + + if (action === 'copy' || action === 'cut') { + const selectedText = getSelectedText(); + const hasTokenFn = typeof getSelectionToken === 'function'; + const initialToken = hasTokenFn ? getSelectionToken() : undefined; + if ( + action === 'cut' && + typeof deleteSelection === 'function' && + (!hasTokenFn || initialToken === null || initialToken === undefined) + ) { + return { ok: false, action, reason: 'missing-selection-token' }; + } + const writeRes = await writeTextInGesture(selectedText); + if (!writeRes.ok) { + return { ok: false, action, reason: writeRes.reason }; + } + if (action === 'cut') { + const currentText = getSelectedText(); + const tokenChanged = + hasTokenFn && !Object.is(getSelectionToken(), initialToken); + if (tokenChanged || currentText !== selectedText) { + return { + ok: false, + action, + reason: 'selection-changed-during-cut', + }; + } + deleteSelection?.({ token: initialToken, text: selectedText }); + } + return { + ok: true, + action, + method: writeRes.method, + text: selectedText, + }; + } + + if (action === 'paste') { + if ( + isSecureContext && + clipboard && + typeof clipboard.readText === 'function' + ) { + try { + const text = await clipboard.readText(); + insertText?.(text); + return { ok: true, action, method: 'async-clipboard', text }; + } catch (error) { + return { + ok: false, + action, + reason: error instanceof Error ? error.message : String(error), + }; + } + } + return { ok: false, action, reason: 'clipboard-read-unavailable' }; + } + + return { ok: false, action, reason: 'unknown-action' }; +} + +/** + * Suppresses native `#ime` context menus and residual text selection while + * the canvas selection overlay owns the active selection. + * + * @param {HTMLTextAreaElement} imeEl + * @param {() => boolean} isOverlayActive + */ +export function attachImeSelectionGuard(imeEl, isOverlayActive) { + /** @param {Event} event */ + function preventNativeMenu(event) { + if (isOverlayActive()) { + event.preventDefault?.(); + } + } + + imeEl.addEventListener?.('contextmenu', preventNativeMenu); + imeEl.addEventListener?.('selectstart', preventNativeMenu); + + return { + dispose() { + imeEl.removeEventListener?.('contextmenu', preventNativeMenu); + imeEl.removeEventListener?.('selectstart', preventNativeMenu); + }, + }; +} + +/** + * Creates a pointer hit-testing and drag state machine for the canvas + * selection overlay. + * + * @param {Object} options + * @param {() => SelectionOverlayInput | null} options.getInput + * @param {(handle: 'start' | 'end', x: number, y: number) => void} [options.onDragHandle] + * @param {(action: SelectionActionId) => Promise | unknown} [options.onAction] + * @param {(layout: SelectionOverlayLayout | null) => void} [options.onLayoutChange] + * @param {string} [options.locale] + * @param {'ltr' | 'rtl'} [options.dir] + * @param {Partial>} [options.labels] + * @param {(label: string) => number} [options.measureText] + */ +export function createSelectionOverlayController(options) { + /** @type {'start' | 'end' | null} */ + let draggingHandle = null; + /** @type {SelectionActionId | null} */ + let pressedMenuAction = null; + /** @type {SelectionActionId | null} */ + let activeActionId = null; + + /** @returns {SelectionOverlayLayout | null} */ + function getLayout() { + const raw = options.getInput(); + if (!raw) { + return null; + } + return computeSelectionOverlayLayout({ + ...raw, + locale: raw.locale ?? options.locale, + dir: raw.dir ?? options.dir, + labels: raw.labels ?? options.labels, + measureText: raw.measureText ?? options.measureText, + dragging: draggingHandle !== null, + activeHandle: draggingHandle, + }); + } + + function notify() { + options.onLayoutChange?.(getLayout()); + } + + /** + * Hit-tests the floating menu items first, then the two teardrop handles. + * + * @param {number} x + * @param {number} y + * @returns {{ kind: 'menu', action: SelectionActionId } | { kind: 'handle', handle: 'start' | 'end' } | null} + */ + function hitTest(x, y) { + const layout = getLayout(); + if (!layout) { + return null; + } + if (layout.menu.visible) { + for (const item of layout.menu.items) { + if (pointInRect(item, x, y)) { + return { kind: 'menu', action: item.id }; + } + } + } + if (pointInRect(layout.endHandle.hitRect, x, y)) { + return { kind: 'handle', handle: 'end' }; + } + if (pointInRect(layout.startHandle.hitRect, x, y)) { + return { kind: 'handle', handle: 'start' }; + } + return null; + } + + /** + * Captures a menu press or teardrop handle drag on pointer down. + * Menu actions wait until pointer up so touch events carry browser user + * activation and users can cancel by sliding off the button. + * + * @param {number} x + * @param {number} y + */ + function onPointerDown(x, y) { + const hit = hitTest(x, y); + if (!hit) { + pressedMenuAction = null; + activeActionId = null; + return { handled: false, hit: null, actionPromise: null }; + } + if (hit.kind === 'menu') { + pressedMenuAction = hit.action; + activeActionId = hit.action; + notify(); + return { handled: true, hit, actionPromise: null }; + } + draggingHandle = hit.handle; + pressedMenuAction = null; + activeActionId = null; + notify(); + return { handled: true, hit, actionPromise: null }; + } + + /** + * @param {number} x + * @param {number} y + */ + function onPointerMove(x, y) { + if (draggingHandle) { + options.onDragHandle?.(draggingHandle, x, y); + notify(); + return true; + } + if (pressedMenuAction) { + const hit = hitTest(x, y); + const nextActive = + hit && hit.kind === 'menu' && hit.action === pressedMenuAction + ? pressedMenuAction + : null; + if (nextActive !== activeActionId) { + activeActionId = nextActive; + notify(); + } + return true; + } + return false; + } + + /** + * Finishes a handle drag or invokes a menu action on pointer up when the + * release point remains on the pressed button. Runs synchronously inside the + * `pointerup` user-activation stack. + * + * @param {number} [x] + * @param {number} [y] + */ + function onPointerUp(x, y) { + const wasDragging = draggingHandle !== null; + const pendingAction = pressedMenuAction; + draggingHandle = null; + pressedMenuAction = null; + activeActionId = null; + + if (pendingAction) { + const hit = + typeof x === 'number' && typeof y === 'number' ? hitTest(x, y) : null; + const confirmed = + hit !== null && hit.kind === 'menu' && hit.action === pendingAction; + notify(); + if (confirmed) { + const actionPromise = Promise.resolve( + options.onAction?.(pendingAction) + ); + return { + handled: true, + action: pendingAction, + cancelled: false, + actionPromise, + }; + } + return { + handled: true, + action: null, + cancelled: true, + actionPromise: null, + }; + } + + if (wasDragging) { + notify(); + return { + handled: true, + action: null, + cancelled: false, + actionPromise: null, + }; + } + return { + handled: false, + action: null, + cancelled: false, + actionPromise: null, + }; + } + + /** + * Clears active handle drag and pressed menu state on pointer cancel. + */ + function onPointerCancel() { + const hadState = + draggingHandle !== null || + pressedMenuAction !== null || + activeActionId !== null; + draggingHandle = null; + pressedMenuAction = null; + activeActionId = null; + if (hadState) { + notify(); + return true; + } + return false; + } + + return { + getLayout, + hitTest, + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel, + isDragging: () => draggingHandle !== null, + getActiveActionId: () => activeActionId, + getPressedMenuAction: () => pressedMenuAction, + }; +} diff --git a/packages/frontend/hosts/web/src/sign-in.js b/packages/frontend/hosts/web/src/sign-in.js new file mode 100644 index 0000000000..b72f395541 --- /dev/null +++ b/packages/frontend/hosts/web/src/sign-in.js @@ -0,0 +1,2407 @@ +// @ts-check + +export const TURNSTILE_SCRIPT_URL = + 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'; +export const WEB_CLIENT_KIND = 'web'; +export const DEFAULT_CLIENT_VERSION = '0.27.5'; +export const CSRF_COOKIE_NAME = 'affine_csrf_token'; +export const GLOBAL_STATE_CLIENT_NONCE_KEY = 'global-state:auth-client-nonce'; +export const OTP_RESEND_COOLDOWN_SECONDS = 60; +const INVALID_OTP_MESSAGE = 'Invalid verification code'; + +/** + * Returns whether the given hostname belongs to the official AFFiNE cloud shell, + * used as fallback when GraphQL `serverConfig.type` is unavailable. + * + * @param {string | null | undefined} hostname + * @returns {boolean} + */ +export function isOfficialCloudHost(hostname) { + const host = String(hostname || '') + .toLowerCase() + .replace(/\.$/, ''); + return ( + host === 'affine.pro' || + host.endsWith('.affine.pro') || + host === 'affine.fail' || + host.endsWith('.affine.fail') + ); +} + +const NATIVE_CLIENT_SCHEMES = new Set([ + 'affine', + 'affine-canary', + 'affine-beta', + 'affine-dev', +]); +const OAUTH_PROVIDERS = new Set(['Google', 'GitHub', 'Apple', 'OIDC']); +const TRUSTED_REDIRECT_DOMAINS = [ + 'google.com', + 'stripe.com', + 'github.com', + 'twitter.com', + 'discord.gg', + 'youtube.com', + 't.me', + 'reddit.com', + 'affine.pro', +]; +const CONSUMED_CODES_STORAGE_KEY = 'affine_consumed_auth_codes'; +const CLIENT_NONCE_STORAGE_KEY = 'affine_auth_client_nonce'; + +const OAUTH_PROVIDER_ICONS = Object.freeze({ + Google: + '', + Apple: + '', + GitHub: + '', + OIDC: '', +}); + +/** + * Classifies standalone authentication routes served by `sign-in.html`. + * + * @param {string} pathname + * @returns {'sign-in' | 'magic-link' | 'oauth' | 'redirect-proxy' | 'open-app' | 'unknown'} + */ +export function classifyAuthRoute(pathname) { + const path = String(pathname || '/').replace(/\/+$/, '') || '/'; + if (path === '/sign-in' || path === '/sign-in.html') { + return 'sign-in'; + } + if (path === '/magic-link') { + return 'magic-link'; + } + if (path === '/oauth' || path.startsWith('/oauth/')) { + return 'oauth'; + } + if (path === '/redirect-proxy') { + return 'redirect-proxy'; + } + if (path === '/open-app' || path.startsWith('/open-app/')) { + return 'open-app'; + } + return 'unknown'; +} + +/** + * Reads a named cookie value from `document.cookie`. + * + * @param {string} name + * @param {{ cookie?: string } | null | undefined} [doc] + * @returns {string | null} + */ +export function readCookieValue(name, doc = globalThis.document) { + const raw = doc && typeof doc.cookie === 'string' ? doc.cookie : ''; + if (!raw) { + return null; + } + for (const part of raw.split(';')) { + const trimmed = part.trim(); + const eq = trimmed.indexOf('='); + const key = eq === -1 ? trimmed : trimmed.slice(0, eq); + if (key === name) { + if (eq === -1) { + return ''; + } + const rawVal = trimmed.slice(eq + 1); + try { + return decodeURIComponent(rawVal); + } catch { + return rawVal; + } + } + } + return null; +} + +/** + * Reads the same-origin `affine_csrf_token` cookie for session-mutating calls. + * + * @param {{ cookie?: string } | null | undefined} [doc] + * @returns {string | null} + */ +export function readCsrfToken(doc = globalThis.document) { + const token = readCookieValue(CSRF_COOKIE_NAME, doc); + return token && token.trim() ? token.trim() : null; +} + +/** + * Reads the client version from `` if present, + * falling back to `DEFAULT_CLIENT_VERSION`. + * + * @param {Document | null | undefined} [doc] + * @returns {string} + */ +function resolveClientVersion(doc = globalThis.document) { + if (doc && typeof doc.querySelector === 'function') { + const meta = doc.querySelector('meta[name="affine-version"]'); + const content = meta?.getAttribute?.('content'); + if (content && content.trim()) { + return content.trim(); + } + } + return DEFAULT_CLIENT_VERSION; +} + +/** + * Builds canonical same-origin Web auth headers. Every request carries + * `x-affine-client-kind: web` and `x-affine-version`. + * + * @param {Object} [options] + * @param {boolean} [options.includeJson=false] + * @param {string | null} [options.csrfToken] + * @param {string | null} [options.captchaProvider] + * @param {string | null} [options.captchaToken] + * @param {string | null} [options.captchaChallenge] + * @param {string} [options.clientVersion] + * @returns {Record} + */ +export function buildWebAuthHeaders(options = {}) { + /** @type {Record} */ + const headers = { + accept: 'application/json', + 'x-affine-client-kind': WEB_CLIENT_KIND, + 'x-affine-version': options.clientVersion || DEFAULT_CLIENT_VERSION, + }; + if (options.includeJson) { + headers['content-type'] = 'application/json'; + } + if (options.csrfToken) { + headers['x-affine-csrf-token'] = options.csrfToken; + } + if (options.captchaToken) { + headers['x-captcha-provider'] = options.captchaProvider || 'turnstile'; + headers['x-captcha-token'] = options.captchaToken; + if (options.captchaChallenge) { + headers['x-captcha-challenge'] = options.captchaChallenge; + } + } + return headers; +} + +/** + * Checks whether a string contains any ASCII control character (U+0000..U+001F or U+007F). + * + * @param {string} str + * @returns {boolean} + */ +function hasControlChar(str) { + for (let i = 0; i < str.length; i += 1) { + const code = str.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) { + return true; + } + } + return false; +} + +/** + * Rejects backslashes, ASCII control characters (including tabs/CR/LF), and + * percent-encoded leading backslashes (`/%5c`) that browsers normalize into + * protocol-relative cross-origin URLs. + * + * @param {string} raw + * @returns {boolean} + */ +function hasUnsafeRedirectChars(raw) { + if (raw.includes('\\') || hasControlChar(raw)) { + return true; + } + if (/^\/%5c/i.test(raw) || raw.startsWith('//')) { + return true; + } + return false; +} + +/** + * Checks whether a `/redirect-proxy` target is allowed on Web: safe + * same-origin paths/URLs or trusted allowlisted domains matching 0.27.5 + * `packages/common/infra/src/utils/redirect-allowlist.ts`. + * + * @param {string | null | undefined} rawTarget + * @param {string} currentOrigin + * @returns {boolean} + */ +export function isAllowedRedirectTarget(rawTarget, currentOrigin) { + if (!rawTarget || typeof rawTarget !== 'string') { + return false; + } + const trimmed = rawTarget.trim(); + if (!trimmed || hasUnsafeRedirectChars(trimmed)) { + return false; + } + let parsed; + let originUrl; + try { + originUrl = new URL(currentOrigin); + parsed = new URL(trimmed, originUrl.origin); + } catch { + return false; + } + if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { + return false; + } + if (parsed.origin === originUrl.origin) { + return true; + } + if (parsed.protocol !== 'https:') { + return false; + } + const host = parsed.hostname.toLowerCase().replace(/\.$/, ''); + return TRUSTED_REDIRECT_DOMAINS.some( + domain => host === domain || host.endsWith(`.${domain}`) + ); +} + +/** + * Resolves a safe same-origin post-authentication redirect URL, returning a + * normalized relative path (`pathname + search + hash`) or `'/'`. + * + * @param {string | null | undefined} redirectUri + * @param {string} currentOrigin + * @returns {string} + */ +export function resolveSafeAuthRedirect(redirectUri, currentOrigin) { + if (!redirectUri || typeof redirectUri !== 'string') { + return '/'; + } + const trimmed = redirectUri.trim(); + if (!trimmed || hasUnsafeRedirectChars(trimmed)) { + return '/'; + } + try { + const originUrl = new URL(currentOrigin); + const resolved = new URL(trimmed, originUrl.origin); + if ( + resolved.origin !== originUrl.origin || + !resolved.pathname.startsWith('/') || + resolved.pathname.startsWith('//') || + resolved.pathname.includes('\\') + ) { + return '/'; + } + return `${resolved.pathname}${resolved.search}${resolved.hash}`; + } catch { + return '/'; + } +} + +/** + * Validates that a `/open-app/url` target uses an allowed AFFiNE desktop or + * mobile custom URL scheme. + * + * @param {string | null | undefined} rawUrl + * @returns {boolean} + */ +export function isAllowedNativeAppUrl(rawUrl) { + if (!rawUrl || typeof rawUrl !== 'string') { + return false; + } + let parsed; + try { + parsed = new URL(rawUrl.trim()); + } catch { + return false; + } + const scheme = parsed.protocol.replace(/:$/, '').toLowerCase(); + return NATIVE_CLIENT_SCHEMES.has(scheme); +} + +/** + * Tracks single-use authorization codes (OAuth `code`, Magic Link `token`, + * Open-App `code`) with separate `inFlight` (in-memory concurrency lock) and + * `consumed` (persisted in `sessionStorage`) sets so transient network errors + * or 5xx responses release the lock for retry while 2xx/4xx outcomes persist + * single-use consumption. + * + * @param {Pick | null | undefined} [storage] + */ +/** + * Safely accesses `sessionStorage` without throwing `SecurityError` in + * restricted privacy contexts. + * + * @param {{ sessionStorage?: Storage } | null | undefined} win + * @returns {Storage | null} + */ +function safeGetSessionStorage(win) { + try { + return win?.sessionStorage ?? null; + } catch { + return null; + } +} + +/** + * Safely accesses `localStorage` without throwing `SecurityError` in + * restricted privacy contexts. + * + * @param {{ localStorage?: Storage } | null | undefined} win + * @returns {Storage | null} + */ +function safeGetLocalStorage(win) { + try { + return win?.localStorage ?? null; + } catch { + return null; + } +} + +export function createSingleUseCodeGuard(storage) { + const effectiveStorage = + storage !== undefined ? storage : safeGetSessionStorage(globalThis); + /** @type {Set} */ + const consumed = new Set(); + /** @type {Set} */ + const inFlight = new Set(); + + if (effectiveStorage && typeof effectiveStorage.getItem === 'function') { + try { + const saved = JSON.parse( + effectiveStorage.getItem(CONSUMED_CODES_STORAGE_KEY) || '[]' + ); + if (Array.isArray(saved)) { + for (const item of saved) { + if (typeof item === 'string') { + consumed.add(item); + } + } + } + } catch { + // Ignore corrupt sessionStorage entries. + } + } + + /** + * Acquires an in-flight lock for a single-use code without marking it + * permanently consumed yet. Returns `false` if already consumed or in flight. + * + * @param {string} code + * @returns {boolean} + */ + function acquire(code) { + const key = String(code || '').trim(); + if (!key || consumed.has(key) || inFlight.has(key)) { + return false; + } + inFlight.add(key); + return true; + } + + /** + * Releases an in-flight lock without marking the code consumed (used on + * network failures or 5xx responses so the caller can safely retry). + * + * @param {string} code + */ + function release(code) { + const key = String(code || '').trim(); + if (key) { + inFlight.delete(key); + } + } + + /** + * Persists a code as permanently consumed (used after a deterministic + * `< 500` server response). + * + * @param {string} code + */ + function commit(code) { + const key = String(code || '').trim(); + if (!key) { + return; + } + inFlight.delete(key); + consumed.add(key); + if (effectiveStorage && typeof effectiveStorage.setItem === 'function') { + try { + effectiveStorage.setItem( + CONSUMED_CODES_STORAGE_KEY, + JSON.stringify([...consumed]) + ); + } catch { + // Ignore storage quota errors; in-memory set still guards this tab. + } + } + } + + /** + * Attempts to claim and immediately commit a single-use code. + * + * @param {string} code + * @returns {boolean} + */ + function tryConsume(code) { + if (!acquire(code)) { + return false; + } + commit(code); + return true; + } + + return { + acquire, + release, + commit, + tryConsume, + isInFlight: code => inFlight.has(String(code || '').trim()), + hasConsumed: code => consumed.has(String(code || '').trim()), + }; +} + +/** + * Strips single-use query parameters (`code`, `state`, `token`) from the + * browser address bar via `history.replaceState` once consumed. + * + * @param {Window | null | undefined} win + */ +export function stripAuthParamsFromUrl(win) { + if ( + !win || + !win.location || + !win.history || + typeof win.history.replaceState !== 'function' + ) { + return; + } + try { + const url = new URL(win.location.href); + let changed = false; + for (const key of ['code', 'state', 'token']) { + if (url.searchParams.has(key)) { + url.searchParams.delete(key); + changed = true; + } + } + if (changed) { + win.history.replaceState(null, '', url.pathname + url.search + url.hash); + } + } catch { + // Ignore invalid test URLs. + } +} + +/** + * Generates and persists a per-session OAuth `client_nonce` into both + * `localStorage['global-state:auth-client-nonce']` (JSON-encoded for 0.27.5 + * `LocalStorageGlobalState` dual-shell compatibility) and + * `sessionStorage['affine_auth_client_nonce']`. + * + * @param {Pick | null | undefined} [sessionStore] + * @param {Pick | null | undefined} [localStore] + * @returns {string} + */ +export function createClientNonce( + sessionStore = globalThis.sessionStorage, + localStore = globalThis.localStorage +) { + const bytes = new Uint8Array(16); + if ( + globalThis.crypto && + typeof globalThis.crypto.getRandomValues === 'function' + ) { + globalThis.crypto.getRandomValues(bytes); + } else { + for (let i = 0; i < bytes.length; i += 1) { + bytes[i] = (Date.now() + i * 31) & 0xff; + } + } + const nonce = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join( + '' + ); + if (localStore && typeof localStore.setItem === 'function') { + try { + localStore.setItem(GLOBAL_STATE_CLIENT_NONCE_KEY, JSON.stringify(nonce)); + } catch { + // Ignore storage errors. + } + } + if (sessionStore && typeof sessionStore.setItem === 'function') { + try { + sessionStore.setItem(CLIENT_NONCE_STORAGE_KEY, nonce); + } catch { + // Ignore storage errors. + } + } + return nonce; +} + +/** + * Reads the previously stored OAuth `client_nonce`, preferring the 0.27.5 + * `localStorage['global-state:auth-client-nonce']` key (JSON-encoded string) + * and falling back to `sessionStorage['affine_auth_client_nonce']`. + * + * @param {Pick | null | undefined} [sessionStore] + * @param {Pick | null | undefined} [localStore] + * @returns {string | undefined} + */ +export function readClientNonce( + sessionStore = globalThis.sessionStorage, + localStore = globalThis.localStorage +) { + if (localStore && typeof localStore.getItem === 'function') { + try { + const raw = localStore.getItem(GLOBAL_STATE_CLIENT_NONCE_KEY); + if (raw && raw.trim()) { + try { + const parsed = JSON.parse(raw); + if (typeof parsed === 'string' && parsed.trim()) { + return parsed.trim(); + } + } catch { + return raw.trim(); + } + } + } catch { + // Fall through to sessionStorage. + } + } + if (!sessionStore || typeof sessionStore.getItem !== 'function') { + return undefined; + } + try { + const val = sessionStore.getItem(CLIENT_NONCE_STORAGE_KEY); + return val && val.trim() ? val.trim() : undefined; + } catch { + return undefined; + } +} + +/** + * Returns whether the backend's configured `baseUrl` is a valid absolute URL + * whose origin matches `currentOrigin`. + * + * @param {string | null | undefined} baseUrl + * @param {string | null | undefined} currentOrigin + * @returns {boolean} + */ +function isSameOriginBaseUrl(baseUrl, currentOrigin) { + if ( + typeof baseUrl !== 'string' || + !baseUrl.trim() || + typeof currentOrigin !== 'string' || + !currentOrigin.trim() + ) { + return false; + } + try { + const parsedBase = new URL(baseUrl.trim()); + const parsedCurrent = new URL(currentOrigin.trim()); + return ( + (parsedBase.protocol === 'https:' || parsedBase.protocol === 'http:') && + parsedBase.origin === parsedCurrent.origin + ); + } catch { + return false; + } +} + +/** + * Queries same-origin `/graphql` using the frozen 0.27.5 `ServerConfigType` + * fields (`name`, `baseUrl`, `features`, `oauthProviders`, `type`). + * Enables third-party OAuth providers ONLY when `baseUrl` is a valid absolute + * URL whose origin matches `currentOrigin`. Degrades silently to an empty + * provider list when offline, unavailable, or behind a cross-origin proxy. + * + * @param {{ fetchImpl?: typeof fetch, clientVersion?: string, currentOrigin?: string | null }} [options] + * @returns {Promise<{ serverName: string, oauth: boolean, providers: string[], crossOriginProxy?: boolean, deploymentType?: string }>} + */ +export async function fetchOAuthProviders(options = {}) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const currentOrigin = + options.currentOrigin !== undefined + ? options.currentOrigin + : globalThis.window?.location?.origin || null; + try { + const response = await fetchImpl('/graphql', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ + includeJson: true, + clientVersion: options.clientVersion, + }), + body: JSON.stringify({ + query: + 'query { serverConfig { name baseUrl features oauthProviders type } }', + }), + }); + if (!response.ok) { + return { serverName: 'AFFiNE', oauth: false, providers: [] }; + } + const payload = await response.json(); + const cfg = payload?.data?.serverConfig; + const rawProviders = Array.isArray(cfg?.oauthProviders) + ? cfg.oauthProviders + : []; + const providers = rawProviders + .map(p => String(p)) + .filter(p => OAUTH_PROVIDERS.has(p)); + const features = Array.isArray(cfg?.features) + ? cfg.features.map(f => String(f)) + : null; + const sameOrigin = isSameOriginBaseUrl(cfg?.baseUrl, currentOrigin); + const oauthEnabled = + sameOrigin && + providers.length > 0 && + (features === null || features.includes('OAuth')); + const deploymentType = + typeof cfg?.type === 'string' && cfg.type.trim() ? cfg.type.trim() : null; + return { + serverName: + typeof cfg?.name === 'string' && cfg.name.trim() + ? cfg.name.trim() + : 'AFFiNE', + oauth: oauthEnabled, + providers: oauthEnabled ? providers : [], + ...(!sameOrigin ? { crossOriginProxy: true } : {}), + ...(deploymentType ? { deploymentType } : {}), + }; + } catch { + return { serverName: 'AFFiNE', oauth: false, providers: [] }; + } +} + +/** + * Renders dynamic OAuth provider buttons inside `#oauth-providers`. + * + * @param {Object} options + * @param {Document} options.doc + * @param {HTMLElement | null} options.container + * @param {HTMLElement | null} [options.divider] + * @param {string[]} options.providers + * @param {string | null} [options.redirectUri] + * @param {(url: string) => void} options.onNavigate + */ +export function renderOAuthProviders(options) { + const { doc, container, divider, providers, redirectUri, onNavigate } = + options; + if (!container) { + return; + } + const valid = (providers || []).filter(p => OAUTH_PROVIDERS.has(p)); + if (!valid.length) { + container.hidden = true; + if (divider) { + divider.hidden = true; + } + return; + } + if ('textContent' in container) { + container.textContent = ''; + } + for (const provider of valid) { + const btn = doc.createElement('button'); + btn.type = 'button'; + btn.className = 'oauth-btn'; + btn.dataset.provider = provider; + const iconMarkup = + OAUTH_PROVIDER_ICONS[ + /** @type {keyof typeof OAUTH_PROVIDER_ICONS} */ (provider) + ] || ''; + if (iconMarkup && typeof doc.createTextNode === 'function') { + btn.innerHTML = iconMarkup; + btn.append(doc.createTextNode(`Continue with ${provider}`)); + } else { + btn.textContent = `Continue with ${provider}`; + } + btn.addEventListener?.('click', () => { + const params = new URLSearchParams({ + provider, + flow: 'redirect', + }); + if (redirectUri) { + params.set('redirect_uri', redirectUri); + } + onNavigate(`/oauth/login?${params.toString()}`); + }); + container.append(btn); + } + container.hidden = false; + if (divider) { + divider.hidden = false; + } +} + +/** + * Queries `/api/auth/captcha` (matching the server contract + * `{ provider: 'turnstile', siteKey, action }`) and injects the Cloudflare + * Turnstile script only when a non-empty `siteKey` is returned. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {Document} options.documentRef + * @param {Window} [options.windowRef] + * @param {HTMLElement | null} [options.container] + * @param {string} [options.captchaEndpoint='/api/auth/captcha'] + * @param {string} [options.scriptUrl] + * @param {(token: string) => void} [options.onToken] + * @returns {Promise<{ loaded: boolean, provider: string | null, siteKey: string | null, action: string | null }>} + */ +export async function maybeLoadTurnstile(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const endpoint = options.captchaEndpoint || '/api/auth/captcha'; + const scriptUrl = options.scriptUrl || TURNSTILE_SCRIPT_URL; + const winRef = options.windowRef || globalThis.window; + const loadTimeoutMs = + typeof options.loadTimeoutMs === 'number' ? options.loadTimeoutMs : 10_000; + + let response; + try { + response = await fetchImpl(endpoint, { + method: 'GET', + credentials: 'same-origin', + headers: buildWebAuthHeaders(), + }); + } catch { + return { loaded: false, provider: null, siteKey: null, action: null }; + } + if (!response || !response.ok) { + return { loaded: false, provider: null, siteKey: null, action: null }; + } + + /** @type {{ provider?: string, siteKey?: string, action?: string, challenge?: string } | null} */ + let payload = null; + try { + payload = await response.json(); + } catch { + return { loaded: false, provider: null, siteKey: null, action: null }; + } + const provider = payload?.provider ? String(payload.provider) : 'turnstile'; + const siteKey = + payload && typeof payload.siteKey === 'string' && payload.siteKey.trim() + ? payload.siteKey.trim() + : null; + const action = + payload && typeof payload.action === 'string' && payload.action.trim() + ? payload.action.trim() + : null; + const challenge = + payload && typeof payload.challenge === 'string' && payload.challenge.trim() + ? payload.challenge.trim() + : null; + + if (!siteKey || provider.toLowerCase() !== 'turnstile') { + return { + loaded: false, + provider: challenge ? provider.toLowerCase() : null, + siteKey: null, + action: null, + ...(challenge ? { challenge } : {}), + }; + } + + const doc = options.documentRef; + if (options.container) { + options.container.dataset.sitekey = siteKey; + if (action) { + options.container.dataset.action = action; + } + } + + const scripts = + typeof doc.querySelectorAll === 'function' + ? Array.from(doc.querySelectorAll('script')) + : []; + let scriptEl = + scripts.find( + node => + node.src === scriptUrl || + (typeof node.getAttribute === 'function' && + node.getAttribute('src') === scriptUrl) + ) || null; + if (!scriptEl) { + scriptEl = doc.createElement('script'); + scriptEl.src = scriptUrl; + scriptEl.async = true; + scriptEl.defer = true; + (doc.head || doc.body).append(scriptEl); + } + + let rendered = false; + let failed = false; + /** @type {ReturnType | null} */ + let loadTimer = null; + /** @type {string | number | undefined} */ + let widgetId; + + function clearLoadTimer() { + if (loadTimer !== null) { + clearTimeout(loadTimer); + loadTimer = null; + } + } + + /** @param {string} reason */ + function reportError(reason) { + if (failed) { + return; + } + failed = true; + clearLoadTimer(); + options.onToken?.(null); + options.onError?.(reason); + } + + function renderWidget() { + if (rendered || !options.container) { + return; + } + const turnstileApi = + /** @type {{ turnstile?: { render?: Function, reset?: Function } }} */ ( + /** @type {unknown} */ (winRef || globalThis) + ).turnstile; + if (turnstileApi && typeof turnstileApi.render === 'function') { + rendered = true; + failed = false; + clearLoadTimer(); + widgetId = turnstileApi.render(options.container, { + sitekey: siteKey, + ...(action ? { action } : {}), + callback: token => { + if (typeof token === 'string' && options.onToken) { + options.onToken(token); + } + }, + 'expired-callback': () => { + options.onToken?.(null); + }, + 'error-callback': () => { + reportError('turnstile-widget-error'); + }, + }); + if (typeof options.onResetReady === 'function') { + options.onResetReady(() => { + options.onToken?.(null); + if (typeof turnstileApi.reset === 'function') { + if (widgetId !== undefined) { + turnstileApi.reset(widgetId); + } else { + turnstileApi.reset(); + } + } + }); + } + } + } + + renderWidget(); + if ( + !rendered && + scriptEl && + typeof scriptEl.addEventListener === 'function' + ) { + scriptEl.addEventListener('load', renderWidget, { once: true }); + scriptEl.addEventListener( + 'error', + () => { + scriptEl.remove?.(); + reportError('turnstile-script-error'); + }, + { once: true } + ); + if (loadTimeoutMs > 0) { + loadTimer = setTimeout(() => { + if (!rendered) { + scriptEl.remove?.(); + reportError('turnstile-script-timeout'); + } + }, loadTimeoutMs); + } + } + + return { + loaded: true, + provider: 'turnstile', + siteKey, + action, + ...(challenge ? { challenge } : {}), + }; +} + +/** + * Submits email/password, magic-link request, or magic-link OTP credentials as + * `application/json`, always sending `credentials: 'same-origin'` and + * `x-affine-client-kind: web`, plus captcha headers whenever present. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {string} [options.endpoint='/api/auth/sign-in'] + * @param {string} options.email + * @param {string} [options.password] + * @param {string} [options.otp] + * @param {string} [options.callbackUrl] + * @param {string | null} [options.captchaProvider] + * @param {string | null} [options.captchaToken] + * @param {string | null} [options.captchaChallenge] + * @returns {Promise<{ ok: boolean, status: number, method: 'password' | 'magic-link-otp' | 'magic-link-send' }>} + */ +/** + * Reads structured backend error `{ name, code, message }` from a failed JSON + * response without throwing on non-JSON or missing `.json()`. + * + * @param {Response | { json?: () => Promise }} response + * @returns {Promise<{ errorCode?: string, errorMessage?: string }>} + */ +async function readAuthErrorPayload(response) { + if (!response || typeof response.json !== 'function') { + return {}; + } + try { + const data = await response.json(); + const errorCode = + (typeof data?.name === 'string' && data.name.trim()) || + (typeof data?.type === 'string' && data.type.trim()) || + (typeof data?.code === 'string' && data.code.trim()) || + undefined; + const errorMessage = + typeof data?.message === 'string' && data.message.trim() + ? data.message.trim() + : undefined; + return { + ...(errorCode ? { errorCode } : {}), + ...(errorMessage ? { errorMessage } : {}), + }; + } catch { + return {}; + } +} + +/** + * Formats a human-readable authentication error message from a backend error + * code, falling back to a clear status message. + * + * @param {string | undefined} errorCode + * @param {string | undefined} errorMessage + * @param {string} fallback + * @returns {string} + */ +function formatAuthErrorMessage(errorCode, errorMessage, fallback) { + switch (errorCode) { + case 'WRONG_SIGN_IN_CREDENTIALS': + return 'Incorrect email or password.'; + case 'INVALID_EMAIL': + return 'Please enter a valid email address.'; + case 'EMAIL_TOKEN_NOT_FOUND': + return INVALID_OTP_MESSAGE; + case 'CAPTCHA_VERIFICATION_FAILED': + return 'Verification failed. Please try again.'; + case 'PASSWORD_REQUIRED': + return 'Please enter your password.'; + default: + return errorMessage || fallback; + } +} + +export async function submitSignInForm(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const email = String(options.email || '').trim(); + const password = options.password ? String(options.password) : ''; + const otp = options.otp ? String(options.otp).trim() : ''; + + if (otp && !password) { + /** @type {Record} */ + const otpBody = { email, token: otp }; + if (options.clientNonce) { + otpBody.client_nonce = options.clientNonce; + } + const response = await fetchImpl('/api/auth/magic-link', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ + includeJson: true, + clientVersion: options.clientVersion, + }), + body: JSON.stringify(otpBody), + }); + const errInfo = response.ok ? {} : await readAuthErrorPayload(response); + return { + ok: Boolean(response.ok), + status: response.status, + method: 'magic-link-otp', + ...errInfo, + }; + } + + const endpoint = options.endpoint || '/api/auth/sign-in'; + /** @type {Record} */ + const body = { email }; + /** @type {'password' | 'magic-link-send'} */ + let method = 'magic-link-send'; + if (password) { + body.password = password; + method = 'password'; + } else { + body.callbackUrl = options.callbackUrl || '/magic-link'; + if (options.clientNonce) { + body.client_nonce = options.clientNonce; + } + } + + const response = await fetchImpl(endpoint, { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ + includeJson: true, + captchaProvider: options.captchaProvider, + captchaToken: options.captchaToken, + captchaChallenge: options.captchaChallenge, + clientVersion: options.clientVersion, + }), + body: JSON.stringify(body), + }); + const errInfo = response.ok ? {} : await readAuthErrorPayload(response); + return { + ok: Boolean(response.ok), + status: response.status, + method, + ...errInfo, + }; +} + +/** + * Signs out the current same-origin Web cookie session using the + * `affine_csrf_token` double-submit CSRF header. + * + * @param {Object} [options] + * @param {typeof fetch} [options.fetchImpl] + * @param {{ cookie?: string }} [options.documentRef] + * @param {string | null} [options.csrfToken] + * @returns {Promise<{ ok: boolean, status: number }>} + */ +export async function signOutWebSession(options = {}) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const csrfToken = + options.csrfToken ?? + readCsrfToken(options.documentRef || globalThis.document); + const response = await fetchImpl('/api/auth/sign-out', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ csrfToken }), + }); + return { ok: Boolean(response.ok), status: response.status }; +} + +/** + * Starts a same-origin Web OAuth login flow via `/api/oauth/preflight`. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {string} options.provider + * @param {string} [options.client='web'] + * @param {string | null} [options.redirectUri] + * @param {'redirect' | 'popup'} [options.flow='redirect'] + * @param {{ cookie?: string }} [options.documentRef] + * @param {Pick | null} [options.sessionStorage] + * @returns {Promise<{ ok: boolean, status: number, url?: string, clientNonce?: string }>} + */ +export async function startOAuthLogin(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const provider = String(options.provider || ''); + const client = options.client || WEB_CLIENT_KIND; + if (!OAUTH_PROVIDERS.has(provider)) { + return { ok: false, status: 400 }; + } + if (client === WEB_CLIENT_KIND) { + await signOutWebSession({ + fetchImpl, + documentRef: options.documentRef, + }); + } + const clientNonce = createClientNonce( + options.sessionStorage, + options.localStorage + ); + const response = await fetchImpl('/api/oauth/preflight', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ includeJson: true }), + body: JSON.stringify({ + provider, + client, + ...(options.redirectUri ? { redirect_uri: options.redirectUri } : {}), + client_nonce: clientNonce, + }), + }); + if (!response.ok) { + return { ok: false, status: response.status }; + } + const data = await response.json(); + let url = typeof data?.url === 'string' ? data.url : ''; + if (url && options.flow) { + try { + const parsed = new URL(url); + const rawState = parsed.searchParams.get('state'); + if (rawState) { + const stateObj = JSON.parse(rawState); + parsed.searchParams.set( + 'state', + JSON.stringify({ ...stateObj, flow: options.flow }) + ); + url = parsed.toString(); + } + } catch { + // Keep original URL if state is not JSON. + } + } + return { ok: true, status: response.status, url, clientNonce }; +} + +/** + * Completes an OAuth callback via `POST /api/oauth/callback` while guarding + * single-use `code` against duplicate consumption. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {string} options.code + * @param {string} options.state + * @param {string} [options.clientNonce] + * @param {ReturnType} [options.codeGuard] + * @param {Window | null} [options.windowRef] + * @returns {Promise<{ ok: boolean, status: number, duplicate?: boolean, redirectUri?: string, flow?: 'popup' | 'redirect' }>} + */ +export async function completeOAuthCallback(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const code = String(options.code || '').trim(); + const rawState = String(options.state || '').trim(); + if (!code || !rawState) { + return { ok: false, status: 400 }; + } + + const guard = + options.codeGuard || + createSingleUseCodeGuard(safeGetSessionStorage(options.windowRef)); + const guardKey = `oauth:${code}`; + if (!guard.acquire(guardKey)) { + return { ok: false, status: 409, duplicate: true }; + } + + let innerState = rawState; + /** @type {'popup' | 'redirect'} */ + let flow = 'redirect'; + try { + const parsed = JSON.parse(rawState); + if (parsed && typeof parsed.state === 'string') { + innerState = parsed.state; + } + if (parsed && parsed.flow === 'popup') { + flow = 'popup'; + } + } catch { + // Plain state string is also accepted by server. + } + + const clientNonce = + options.clientNonce ?? + readClientNonce( + safeGetSessionStorage(options.windowRef), + safeGetLocalStorage(options.windowRef) + ); + let response; + try { + response = await fetchImpl('/api/oauth/callback', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ includeJson: true }), + body: JSON.stringify({ + code, + state: innerState, + ...(clientNonce ? { client_nonce: clientNonce } : {}), + }), + }); + } catch (error) { + guard.release(guardKey); + throw error; + } + if (response.status >= 500) { + guard.release(guardKey); + return { ok: false, status: response.status, flow }; + } + guard.commit(guardKey); + stripAuthParamsFromUrl(options.windowRef); + if (!response.ok) { + return { ok: false, status: response.status, flow }; + } + const payload = await response.json().catch(() => ({})); + return { + ok: true, + status: response.status, + redirectUri: + typeof payload?.redirectUri === 'string' ? payload.redirectUri : '/', + flow, + }; +} + +/** + * Completes a `/magic-link` callback once. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {string} options.email + * @param {string} options.token + * @param {ReturnType} [options.codeGuard] + * @param {Window | null} [options.windowRef] + * @returns {Promise<{ ok: boolean, status: number, duplicate?: boolean }>} + */ +export async function completeMagicLink(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const email = String(options.email || '').trim(); + const token = String(options.token || '').trim(); + if (!email || !token) { + return { ok: false, status: 400 }; + } + const guard = + options.codeGuard || + createSingleUseCodeGuard(safeGetSessionStorage(options.windowRef)); + const guardKey = `magic:${token}`; + if (!guard.acquire(guardKey)) { + return { ok: false, status: 409, duplicate: true }; + } + let response; + try { + response = await fetchImpl('/api/auth/magic-link', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ includeJson: true }), + body: JSON.stringify({ email, token }), + }); + } catch (error) { + guard.release(guardKey); + throw error; + } + if (response.status >= 500) { + guard.release(guardKey); + return { ok: false, status: response.status }; + } + guard.commit(guardKey); + stripAuthParamsFromUrl(options.windowRef); + return { ok: Boolean(response.ok), status: response.status }; +} + +/** + * Completes an `/open-app` sign-in code exchange once. + * + * @param {Object} options + * @param {typeof fetch} [options.fetchImpl] + * @param {string} options.code + * @param {ReturnType} [options.codeGuard] + * @param {Window | null} [options.windowRef] + * @returns {Promise<{ ok: boolean, status: number, duplicate?: boolean }>} + */ +export async function completeOpenAppSignIn(options) { + const fetchImpl = options.fetchImpl || globalThis.fetch; + const code = String(options.code || '').trim(); + if (!code) { + return { ok: false, status: 400 }; + } + const guard = + options.codeGuard || + createSingleUseCodeGuard(safeGetSessionStorage(options.windowRef)); + const guardKey = `open-app:${code}`; + if (!guard.acquire(guardKey)) { + return { ok: false, status: 409, duplicate: true }; + } + let response; + try { + response = await fetchImpl('/api/auth/open-app/sign-in', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ includeJson: true }), + body: JSON.stringify({ code }), + }); + } catch (error) { + guard.release(guardKey); + throw error; + } + if (response.status >= 500) { + guard.release(guardKey); + return { ok: false, status: response.status }; + } + guard.commit(guardKey); + stripAuthParamsFromUrl(options.windowRef); + return { ok: Boolean(response.ok), status: response.status }; +} + +/** + * Boots the zero-framework standalone authentication page for all Web auth + * routes (`/sign-in`, `/magic-link`, `/oauth/*`, `/redirect-proxy`, + * `/open-app/*`). Uses same-origin endpoints only. + * + * @param {Object} [env] + * @param {Window} [env.win] + * @param {Document} [env.doc] + * @param {typeof fetch} [env.fetchImpl] + * @param {ReturnType} [env.codeGuard] + */ +export async function bootSignInPage(env = {}) { + const win = env.win || globalThis.window; + const doc = env.doc || globalThis.document; + if (!win || !doc) { + return null; + } + + const fetchImpl = env.fetchImpl || win.fetch.bind(win); + const href = + win.location.href || + `https://app.affine.pro${win.location.pathname || '/sign-in'}${win.location.search || ''}`; + const currentUrl = new URL(href); + const route = classifyAuthRoute(currentUrl.pathname); + const statusEl = doc.getElementById('auth-status'); + const form = doc.getElementById('sign-in-form'); + const returnToSignInEl = doc.getElementById('return-to-sign-in'); + const sessionStore = safeGetSessionStorage(win); + const localStore = safeGetLocalStorage(win); + const codeGuard = env.codeGuard || createSingleUseCodeGuard(sessionStore); + + /** @param {string} target */ + function navigateTo(target) { + if (typeof win.location.replace === 'function') { + win.location.replace(target); + } else if (typeof win.location.assign === 'function') { + win.location.assign(target); + } else { + win.location.href = target; + } + } + + /** @param {string} text @param {'info' | 'error'} [tone='info'] */ + function setStatus(text, tone = 'info') { + if (!statusEl) { + return; + } + statusEl.textContent = text; + if (statusEl.dataset) { + statusEl.dataset.tone = tone; + } + } + + /** @param {string} text */ + function showSubRouteError(text) { + if (form) { + form.hidden = true; + } + setStatus(text, 'error'); + if (returnToSignInEl) { + returnToSignInEl.hidden = false; + } + } + + if (route !== 'sign-in' && form) { + form.hidden = true; + } + + if (route === 'redirect-proxy') { + const target = currentUrl.searchParams.get('redirect_uri'); + if (isAllowedRedirectTarget(target, currentUrl.origin)) { + setStatus('Redirecting...', 'info'); + navigateTo(/** @type {string} */ (target)); + return { route, redirected: true, target }; + } + showSubRouteError('Blocked untrusted redirect target.'); + return { route, redirected: false, target: null }; + } + + if (route === 'open-app') { + const appUrl = currentUrl.searchParams.get('url'); + const code = currentUrl.searchParams.get('code'); + if (appUrl) { + if (isAllowedNativeAppUrl(appUrl)) { + setStatus('Opening AFFiNE app...', 'info'); + navigateTo(appUrl); + return { route, handedOff: true, target: appUrl }; + } + showSubRouteError('Blocked invalid app URL.'); + return { route, handedOff: false, target: null }; + } + if (code) { + const result = await completeOpenAppSignIn({ + fetchImpl, + code, + codeGuard, + windowRef: win, + }); + if (result.ok) { + const nextUrl = resolveSafeAuthRedirect( + currentUrl.searchParams.get('redirect_uri'), + currentUrl.origin + ); + setStatus('Signed in.', 'info'); + navigateTo(nextUrl); + return { route, result, target: nextUrl }; + } + showSubRouteError( + result.duplicate + ? 'Sign-in code already used.' + : `Open-app sign-in failed (${result.status}).` + ); + return { route, result }; + } + setStatus('Handling open-app...', 'info'); + return { route }; + } + + if (route === 'magic-link') { + const email = currentUrl.searchParams.get('email') || ''; + const token = currentUrl.searchParams.get('token') || ''; + const client = currentUrl.searchParams.get('client'); + const redirectUri = currentUrl.searchParams.get('redirect_uri'); + + if (!email || !token) { + showSubRouteError('Invalid magic link.'); + return { route, ok: false, status: 400 }; + } + if (client && client !== WEB_CLIENT_KIND) { + if (!NATIVE_CLIENT_SCHEMES.has(client)) { + showSubRouteError('Invalid magic link client.'); + return { route, ok: false, status: 400 }; + } + const deepLink = new URL(`${client}://authentication`); + deepLink.searchParams.set('method', 'magic-link'); + deepLink.searchParams.set( + 'payload', + JSON.stringify({ email, token, redirectUri }) + ); + deepLink.searchParams.set('server', currentUrl.origin); + const handoff = `/open-app/url?url=${encodeURIComponent(deepLink.toString())}`; + navigateTo(handoff); + return { route, handedOff: true, target: handoff }; + } + + const result = await completeMagicLink({ + fetchImpl, + email, + token, + codeGuard, + windowRef: win, + }); + if (result.ok) { + const nextUrl = resolveSafeAuthRedirect(redirectUri, currentUrl.origin); + setStatus('Signed in.', 'info'); + navigateTo(nextUrl); + return { route, result, target: nextUrl }; + } + showSubRouteError( + result.duplicate + ? 'Magic link already used.' + : `Magic link sign-in failed (${result.status}).` + ); + return { route, result }; + } + + if (route === 'oauth') { + if (currentUrl.pathname.endsWith('/login')) { + const provider = currentUrl.searchParams.get('provider') || ''; + const client = currentUrl.searchParams.get('client') || WEB_CLIENT_KIND; + const redirectUri = currentUrl.searchParams.get('redirect_uri'); + const flow = + currentUrl.searchParams.get('flow') === 'popup' ? 'popup' : 'redirect'; + const result = await startOAuthLogin({ + fetchImpl, + provider, + client, + redirectUri, + flow, + documentRef: doc, + sessionStorage: sessionStore, + localStorage: localStore, + }); + if (result.ok && result.url) { + setStatus(`Continuing with ${provider}...`, 'info'); + navigateTo(result.url); + return { route, result }; + } + showSubRouteError(`OAuth start failed (${result.status}).`); + return { route, result }; + } + + const oauthError = currentUrl.searchParams.get('error'); + if (oauthError && oauthError.trim()) { + const oauthDesc = currentUrl.searchParams.get('error_description'); + const msg = + oauthDesc && oauthDesc.trim() + ? oauthDesc.trim() + : `OAuth sign-in failed: ${oauthError.trim()}.`; + showSubRouteError(msg); + return { route, ok: false, status: 400, error: oauthError.trim() }; + } + + const code = currentUrl.searchParams.get('code') || ''; + const state = currentUrl.searchParams.get('state') || ''; + if (code && state) { + // Check for native client OAuth handoff BEFORE consuming the single-use + // code (1:1 aligned with 0.27.5 `oauth-callback.tsx:38-71`). + let parsedState = null; + try { + parsedState = JSON.parse(state); + } catch { + parsedState = null; + } + if ( + parsedState && + typeof parsedState.client === 'string' && + parsedState.client && + parsedState.client !== WEB_CLIENT_KIND + ) { + if ( + !NATIVE_CLIENT_SCHEMES.has(parsedState.client) || + !parsedState.state || + !parsedState.provider + ) { + showSubRouteError('Invalid OAuth callback parameters.'); + return { route, ok: false, status: 400 }; + } + const flow = parsedState.flow === 'popup' ? 'popup' : 'redirect'; + const deepParams = new URLSearchParams(); + deepParams.set('method', 'oauth'); + deepParams.set( + 'payload', + JSON.stringify({ + state: parsedState.state, + code, + flow, + provider: parsedState.provider, + }) + ); + deepParams.set('server', currentUrl.origin); + const deepLink = `${parsedState.client}://authentication?${deepParams.toString()}`; + const handoff = `/open-app/url?url=${encodeURIComponent(deepLink)}`; + navigateTo(handoff); + return { route, handedOff: true, target: handoff }; + } + + const result = await completeOAuthCallback({ + fetchImpl, + code, + state, + codeGuard, + windowRef: win, + }); + if (result.ok) { + if (result.flow === 'popup' && typeof win.close === 'function') { + win.close(); + return { route, result, closedPopup: true }; + } + const nextUrl = resolveSafeAuthRedirect( + result.redirectUri, + currentUrl.origin + ); + setStatus('Signed in.', 'info'); + navigateTo(nextUrl); + return { route, result, target: nextUrl }; + } + showSubRouteError( + result.duplicate + ? 'OAuth code already consumed.' + : `OAuth sign-in failed (${result.status}).` + ); + return { route, result }; + } + + showSubRouteError('Missing OAuth callback parameters.'); + return { route, ok: false, status: 400 }; + } + + if (statusEl && route !== 'sign-in') { + setStatus(`Handling ${route}...`, 'info'); + } + + const clientVersion = env.clientVersion || resolveClientVersion(doc); + const nowImpl = + typeof env.nowImpl === 'function' ? env.nowImpl : () => Date.now(); + const setIntervalImpl = + env.setIntervalImpl || + (typeof win.setInterval === 'function' + ? win.setInterval.bind(win) + : globalThis.setInterval); + const clearIntervalImpl = + env.clearIntervalImpl || + (typeof win.clearInterval === 'function' + ? win.clearInterval.bind(win) + : globalThis.clearInterval); + + const legalNoticeEl = doc.getElementById('auth-legal-notice'); + /** @param {string | null | undefined} deploymentType */ + function syncLegalNoticeVisibility(deploymentType) { + if (!legalNoticeEl) { + return; + } + const showLegal = + typeof env.showLegalNotice === 'boolean' + ? env.showLegalNotice + : deploymentType + ? deploymentType.toLowerCase() === 'affine' + : isOfficialCloudHost(currentUrl.hostname); + legalNoticeEl.hidden = !showLegal; + } + syncLegalNoticeVisibility(null); + + // Bind `#use-local-btn` synchronously BEFORE any async network calls so + // offline users can always skip sign-in immediately. + const useLocalBtn = doc.getElementById('use-local-btn'); + useLocalBtn?.addEventListener?.('click', () => { + navigateTo('/'); + }); + + const initialError = currentUrl.searchParams.get('error'); + if (initialError && initialError.trim()) { + setStatus(initialError.trim(), 'error'); + } + + /** @type {string | null} */ + let captchaToken = null; + let captchaRequired = false; + /** @type {{ loaded: boolean, provider: string | null, siteKey: string | null, action: string | null, challenge?: string }} */ + let captcha = { loaded: false, provider: null, siteKey: null, action: null }; + /** @type {string | null} */ + let captchaChallenge = null; + /** @type {(() => void) | null} */ + let resetTurnstile = null; + /** @type {'email' | 'password' | 'otp'} */ + let currentStep = 'email'; + let passwordAvailable = false; + let submitInFlight = false; + let preflightSeq = 0; + let stepEpoch = 0; + let stepBoundEmail = ''; + /** @type {Map} */ + const otpSendingCountByEmail = new Map(); + let resendCooldown = 0; + /** @type {string} */ + let activeCooldownEmail = ''; + /** @type {Map} */ + const resendCooldownUntilByEmail = new Map(); + /** @type {unknown} */ + let resendTimerId = null; + const submitButtonEl = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('submit-button') + ); + const passwordSubmitButtonEl = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('password-submit-button') + ); + const otpSubmitButtonEl = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('otp-submit-button') + ); + const switchToOtpBtn = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('switch-to-otp-btn') + ); + const resendOtpBtn = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('resend-otp-btn') + ); + const togglePasswordBtn = /** @type {HTMLButtonElement | null} */ ( + doc.getElementById('toggle-password-btn') + ); + + function normalizeEmailKey(emailVal) { + return String(emailVal || '') + .trim() + .toLowerCase(); + } + + function isOtpSendInFlightFor(emailVal) { + const key = normalizeEmailKey(emailVal); + return key ? (otpSendingCountByEmail.get(key) || 0) > 0 : false; + } + + function remainingCooldownSeconds(emailVal) { + const key = normalizeEmailKey(emailVal); + if (!key) { + return 0; + } + const until = resendCooldownUntilByEmail.get(key) || 0; + const remainingMs = until - nowImpl(); + if (remainingMs <= 0) { + resendCooldownUntilByEmail.delete(key); + return 0; + } + return Math.ceil(remainingMs / 1000); + } + + function syncSubmitButtonsDisabled() { + const waitingForCaptcha = captchaRequired && !captchaToken; + const stepOtpInFlight = + (currentStep === 'otp' || currentStep === 'password') && + isOtpSendInFlightFor(stepBoundEmail); + if (submitButtonEl) { + submitButtonEl.disabled = waitingForCaptcha || submitInFlight; + } + if (passwordSubmitButtonEl) { + passwordSubmitButtonEl.disabled = waitingForCaptcha || submitInFlight; + } + if (otpSubmitButtonEl) { + otpSubmitButtonEl.disabled = submitInFlight; + } + if (switchToOtpBtn) { + switchToOtpBtn.disabled = + waitingForCaptcha || stepOtpInFlight || submitInFlight; + } + if (resendOtpBtn) { + resendOtpBtn.disabled = + waitingForCaptcha || + stepOtpInFlight || + resendCooldown > 0 || + submitInFlight; + } + } + + function clearResendTimer() { + if (resendTimerId !== null) { + clearIntervalImpl?.(resendTimerId); + resendTimerId = null; + } + resendCooldown = 0; + activeCooldownEmail = ''; + if (resendOtpBtn) { + resendOtpBtn.textContent = 'Resend code'; + } + syncSubmitButtonsDisabled(); + } + + function runResendCountdown(emailVal) { + clearResendTimer(); + const key = normalizeEmailKey(emailVal); + const remaining = remainingCooldownSeconds(key); + if (remaining <= 0) { + return; + } + activeCooldownEmail = key; + resendCooldown = remaining; + if (resendOtpBtn) { + resendOtpBtn.textContent = `Resend in ${resendCooldown}s`; + } + syncSubmitButtonsDisabled(); + if (typeof setIntervalImpl === 'function') { + resendTimerId = setIntervalImpl(() => { + const nextRemaining = remainingCooldownSeconds(activeCooldownEmail); + if (nextRemaining <= 0) { + clearResendTimer(); + return; + } + resendCooldown = nextRemaining; + if (resendOtpBtn) { + resendOtpBtn.textContent = `Resend in ${resendCooldown}s`; + } + syncSubmitButtonsDisabled(); + }, 1000); + if ( + resendTimerId && + typeof (/** @type {{ unref?: Function }} */ (resendTimerId).unref) === + 'function' + ) { + /** @type {{ unref: () => void }} */ (resendTimerId).unref(); + } + } + } + + function recordCooldownDeadline( + emailVal, + seconds = OTP_RESEND_COOLDOWN_SECONDS + ) { + const key = normalizeEmailKey(emailVal); + if (key && seconds > 0) { + resendCooldownUntilByEmail.set( + key, + nowImpl() + Math.floor(seconds) * 1000 + ); + } + return key; + } + + const container = doc.getElementById('turnstile-container'); + const authCard = doc.getElementById('auth-card'); + const stepEmailEl = doc.getElementById('step-email'); + const stepPasswordEl = doc.getElementById('step-password'); + const stepOtpEl = doc.getElementById('step-otp'); + const stepEmailDisplay = doc.getElementById('step-email-display'); + const otpEmailDisplay = doc.getElementById('otp-email-display'); + const oauthContainer = doc.getElementById('oauth-providers'); + const oauthDivider = doc.getElementById('oauth-divider'); + const switchToPasswordBtn = doc.getElementById('switch-to-password-btn'); + const backFromPasswordBtn = doc.getElementById('back-from-password-btn'); + const backFromOtpBtn = doc.getElementById('back-from-otp-btn'); + const sessionContinueEl = doc.getElementById('session-continue'); + const continueSessionBtn = doc.getElementById('continue-session-btn'); + + const redirectUriParam = currentUrl.searchParams.get('redirect_uri'); + const clientParam = currentUrl.searchParams.get('client'); + const magicLinkParams = new URLSearchParams(); + if (redirectUriParam) { + magicLinkParams.set('redirect_uri', redirectUriParam); + } + if (clientParam) { + magicLinkParams.set('client', clientParam); + } + const magicLinkQuery = magicLinkParams.toString(); + const magicLinkCallbackUrl = magicLinkQuery + ? `/magic-link?${magicLinkQuery}` + : '/magic-link'; + + /** + * @param {'email' | 'password' | 'otp'} nextStep + * @param {string} [emailText] + */ + function setStep(nextStep, emailText) { + stepEpoch += 1; + currentStep = nextStep; + if (nextStep === 'email') { + stepBoundEmail = ''; + } else if (emailText !== undefined) { + stepBoundEmail = String(emailText).trim(); + } + if (authCard?.dataset) { + authCard.dataset.step = nextStep; + } + if (stepEmailEl) { + stepEmailEl.hidden = nextStep !== 'email'; + } + if (stepPasswordEl) { + stepPasswordEl.hidden = nextStep !== 'password'; + } + if (stepOtpEl) { + stepOtpEl.hidden = nextStep !== 'otp'; + } + if (emailText !== undefined) { + if (stepEmailDisplay) { + stepEmailDisplay.textContent = emailText; + } + if (otpEmailDisplay) { + otpEmailDisplay.textContent = emailText; + } + } + if (switchToPasswordBtn) { + switchToPasswordBtn.hidden = !passwordAvailable; + } + syncSubmitButtonsDisabled(); + const focusTargetId = + nextStep === 'password' + ? 'password' + : nextStep === 'otp' + ? 'otp' + : 'email'; + doc.getElementById(focusTargetId)?.focus?.(); + } + + let crossOriginProxy = false; + + const clearStepSecrets = () => { + const pwdEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('password') + ); + const codeEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('otp') + ); + if (pwdEl) { + pwdEl.value = ''; + pwdEl.type = 'password'; + } + if (togglePasswordBtn) { + togglePasswordBtn.textContent = 'Show'; + togglePasswordBtn.setAttribute?.('aria-label', 'Show password'); + togglePasswordBtn.setAttribute?.('aria-pressed', 'false'); + } + if (codeEl) { + codeEl.value = ''; + } + }; + + function returnToEmailStep() { + preflightSeq += 1; + submitInFlight = false; + clearResendTimer(); + clearStepSecrets(); + setStep('email'); + setStatus(''); + resetTurnstile?.(); + } + + backFromPasswordBtn?.addEventListener?.('click', returnToEmailStep); + backFromOtpBtn?.addEventListener?.('click', returnToEmailStep); + + togglePasswordBtn?.addEventListener?.('click', () => { + const pwdEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('password') + ); + if (!pwdEl) { + return; + } + const reveal = pwdEl.type !== 'text'; + pwdEl.type = reveal ? 'text' : 'password'; + togglePasswordBtn.textContent = reveal ? 'Hide' : 'Show'; + togglePasswordBtn.setAttribute?.( + 'aria-label', + reveal ? 'Hide password' : 'Show password' + ); + togglePasswordBtn.setAttribute?.('aria-pressed', String(reveal)); + }); + + /** @param {KeyboardEvent} event */ + function handleEscapeBack(event) { + if ( + event?.key === 'Escape' && + (currentStep === 'password' || currentStep === 'otp') + ) { + event.preventDefault?.(); + returnToEmailStep(); + } + } + doc.addEventListener?.('keydown', handleEscapeBack); + + const clearErrorOnInput = () => { + if (statusEl?.dataset?.tone === 'error') { + setStatus('', 'info'); + } + }; + doc.getElementById('email')?.addEventListener?.('input', () => { + clearErrorOnInput(); + if (currentStep === 'email') { + preflightSeq += 1; + submitInFlight = false; + clearStepSecrets(); + syncSubmitButtonsDisabled(); + } + }); + doc + .getElementById('password') + ?.addEventListener?.('input', clearErrorOnInput); + doc.getElementById('otp')?.addEventListener?.('input', clearErrorOnInput); + + switchToPasswordBtn?.addEventListener?.('click', () => { + preflightSeq += 1; + clearResendTimer(); + const emailVal = + stepBoundEmail || + (/** @type {HTMLInputElement | null} */ + (doc.getElementById('email'))?.value || '').trim(); + setStep('password', emailVal); + setStatus(''); + resetTurnstile?.(); + }); + + async function triggerMagicLinkSend(emailVal) { + const boundEmail = String(emailVal || '').trim(); + const emailKey = normalizeEmailKey(boundEmail); + if (!emailKey || isOtpSendInFlightFor(emailKey)) { + return { ok: false, status: 0, method: 'magic-link-send' }; + } + if (remainingCooldownSeconds(emailKey) > 0) { + if ( + currentStep === 'otp' && + normalizeEmailKey(stepBoundEmail) === emailKey + ) { + runResendCountdown(emailKey); + } + return { + ok: true, + status: 200, + method: 'magic-link-send', + skipped: true, + }; + } + const sendEpoch = stepEpoch; + const isSameStepAttempt = () => + sendEpoch === stepEpoch && + currentStep === 'otp' && + normalizeEmailKey(stepBoundEmail) === emailKey; + const isCurrentEmailOtpStep = () => + currentStep === 'otp' && normalizeEmailKey(stepBoundEmail) === emailKey; + otpSendingCountByEmail.set( + emailKey, + (otpSendingCountByEmail.get(emailKey) || 0) + 1 + ); + syncSubmitButtonsDisabled(); + try { + const sendRes = await submitSignInForm({ + fetchImpl, + endpoint: '/api/auth/sign-in', + email: boundEmail, + callbackUrl: magicLinkCallbackUrl, + captchaProvider: captcha.provider, + captchaToken, + captchaChallenge, + clientVersion, + clientNonce: readClientNonce(sessionStore, localStore), + }); + if (sendRes.ok) { + recordCooldownDeadline(emailKey); + } + if (isSameStepAttempt()) { + resetTurnstile?.(); + } + if (!isCurrentEmailOtpStep()) { + return { + ok: false, + status: sendRes.status, + method: 'magic-link-send', + stale: true, + }; + } + if (!sendRes.ok) { + setStatus( + formatAuthErrorMessage( + sendRes.errorCode, + sendRes.errorMessage, + `Failed to send code (${sendRes.status}).` + ), + 'error' + ); + } else { + runResendCountdown(emailKey); + setStatus( + crossOriginProxy + ? 'Enter the 6-digit verification code sent to your email.' + : '', + 'info' + ); + } + return sendRes; + } catch { + if (isSameStepAttempt()) { + resetTurnstile?.(); + } + if (isCurrentEmailOtpStep()) { + setStatus('Network error. Please try again.', 'error'); + } + return { ok: false, status: 0, method: 'magic-link-send' }; + } finally { + const remainingInFlight = (otpSendingCountByEmail.get(emailKey) || 1) - 1; + if (remainingInFlight <= 0) { + otpSendingCountByEmail.delete(emailKey); + } else { + otpSendingCountByEmail.set(emailKey, remainingInFlight); + } + syncSubmitButtonsDisabled(); + } + } + + switchToOtpBtn?.addEventListener?.('click', async () => { + preflightSeq += 1; + const emailVal = + stepBoundEmail || + (/** @type {HTMLInputElement | null} */ + (doc.getElementById('email'))?.value || '').trim(); + setStep('otp', emailVal); + await triggerMagicLinkSend(emailVal); + }); + resendOtpBtn?.addEventListener?.('click', async () => { + const emailVal = + stepBoundEmail || + (/** @type {HTMLInputElement | null} */ + (doc.getElementById('email'))?.value || '').trim(); + const res = await triggerMagicLinkSend(emailVal); + if (res.ok && !res.skipped) { + setStatus('A new verification code has been sent.', 'info'); + } + }); + + // Bind `
` submit listener SYNCHRONOUSLY before any + // async network calls so slow networks or captcha failures never trigger a + // native HTML POST navigation. + if (form && typeof form.addEventListener === 'function') { + form.addEventListener('submit', async event => { + event.preventDefault(); + if (submitInFlight) { + return; + } + if (currentStep !== 'otp' && captchaRequired && !captchaToken) { + setStatus('Please complete verification first.', 'error'); + return; + } + + const emailEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('email') + ); + const passwordEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('password') + ); + const otpEl = /** @type {HTMLInputElement | null} */ ( + doc.getElementById('otp') + ); + const emailVal = (emailEl?.value || '').trim(); + const passwordVal = passwordEl?.value || ''; + const otpVal = (otpEl?.value || '').trim(); + + setStatus('', 'info'); + + if (authCard && currentStep === 'email') { + const seq = ++preflightSeq; + const reqEmail = emailVal; + const isStalePreflight = () => + seq !== preflightSeq || + currentStep !== 'email' || + (emailEl?.value || '').trim() !== reqEmail; + clearStepSecrets(); + submitInFlight = true; + syncSubmitButtonsDisabled(); + try { + const preRes = await fetchImpl('/api/auth/preflight', { + method: 'POST', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ includeJson: true, clientVersion }), + body: JSON.stringify({ email: reqEmail }), + }); + if (isStalePreflight()) { + return; + } + if (!preRes.ok) { + const errInfo = await readAuthErrorPayload(preRes); + setStatus( + formatAuthErrorMessage( + errInfo.errorCode, + errInfo.errorMessage, + `Unable to verify account (${preRes.status}).` + ), + 'error' + ); + return; + } + const preData = await preRes.json(); + if (isStalePreflight()) { + return; + } + const methods = preData?.methods; + passwordAvailable = Boolean(methods?.password?.available); + if (passwordAvailable) { + setStep('password', reqEmail); + setStatus(''); + return; + } + const magicLinkUnavailable = + methods?.magicLink?.available === false || + methods?.email?.available === false || + (methods && + typeof methods === 'object' && + Object.keys(methods).length > 0 && + Object.values(methods).every( + m => m && typeof m === 'object' && m.available === false + )); + if (magicLinkUnavailable) { + setStatus( + 'Email sign-in is not available for this account.', + 'error' + ); + return; + } + setStep('otp', reqEmail); + submitInFlight = false; + syncSubmitButtonsDisabled(); + await triggerMagicLinkSend(reqEmail); + return; + } catch { + if (isStalePreflight()) { + return; + } + setStatus('Network error while checking account.', 'error'); + return; + } finally { + if (seq === preflightSeq) { + submitInFlight = false; + syncSubmitButtonsDisabled(); + } + } + } + + if (authCard && currentStep === 'password' && !passwordVal) { + setStatus('Please enter your password.', 'error'); + return; + } + + if (authCard && currentStep === 'otp' && !/^\d{6}$/.test(otpVal)) { + setStatus(INVALID_OTP_MESSAGE, 'error'); + return; + } + + const submitEmail = + currentStep === 'password' || currentStep === 'otp' + ? stepBoundEmail || emailVal + : emailVal; + + submitInFlight = true; + syncSubmitButtonsDisabled(); + try { + const result = await submitSignInForm({ + fetchImpl, + endpoint: form.getAttribute?.('action') || '/api/auth/sign-in', + email: submitEmail, + password: currentStep === 'otp' ? '' : passwordVal, + otp: currentStep === 'password' ? '' : otpVal, + callbackUrl: magicLinkCallbackUrl, + captchaProvider: captcha.provider, + captchaToken, + captchaChallenge, + clientVersion, + clientNonce: readClientNonce(sessionStore, localStore), + }); + if (result.method !== 'magic-link-otp') { + resetTurnstile?.(); + } + const errorText = + result.method === 'magic-link-otp' && + (result.status === 400 || result.status === 401) + ? INVALID_OTP_MESSAGE + : formatAuthErrorMessage( + result.errorCode, + result.errorMessage, + `Sign-in failed (${result.status}).` + ); + setStatus( + result.ok + ? result.method === 'magic-link-send' + ? crossOriginProxy + ? 'Enter the 6-digit verification code sent to your email.' + : 'Check your email for the sign-in link.' + : 'Signed in.' + : errorText, + result.ok ? 'info' : 'error' + ); + if (result.ok && result.method !== 'magic-link-send') { + clearResendTimer(); + navigateTo( + resolveSafeAuthRedirect(redirectUriParam, currentUrl.origin) + ); + } + } catch { + setStatus('Network error. Please try again.', 'error'); + } finally { + submitInFlight = false; + syncSubmitButtonsDisabled(); + } + }); + } + + function renderCaptchaRetryButton() { + if (!container || typeof doc.createElement !== 'function') { + return; + } + if (doc.getElementById('retry-captcha-btn')) { + return; + } + const btn = doc.createElement('button'); + btn.id = 'retry-captcha-btn'; + btn.type = 'button'; + btn.className = 'btn-secondary'; + btn.textContent = 'Retry verification'; + btn.addEventListener?.('click', () => { + btn.remove?.(); + setStatus('', 'info'); + void loadCaptcha(); + }); + container.append?.(btn); + } + + async function loadCaptcha() { + captcha = await maybeLoadTurnstile({ + fetchImpl, + documentRef: doc, + windowRef: win, + container, + loadTimeoutMs: env.captchaLoadTimeoutMs, + onToken: token => { + captchaToken = token; + if (token) { + doc.getElementById('retry-captcha-btn')?.remove?.(); + } + syncSubmitButtonsDisabled(); + }, + onError: () => { + captchaToken = null; + setStatus('Verification unavailable. Please retry.', 'error'); + renderCaptchaRetryButton(); + syncSubmitButtonsDisabled(); + }, + onResetReady: resetFn => { + resetTurnstile = () => { + resetFn(); + syncSubmitButtonsDisabled(); + }; + }, + }); + captchaRequired = Boolean(captcha.loaded); + captchaChallenge = + 'challenge' in captcha && typeof captcha.challenge === 'string' + ? captcha.challenge + : null; + syncSubmitButtonsDisabled(); + } + + await loadCaptcha(); + + if (oauthContainer || legalNoticeEl) { + const serverOAuth = await fetchOAuthProviders({ + fetchImpl, + clientVersion, + currentOrigin: currentUrl.origin, + }); + crossOriginProxy = Boolean(serverOAuth.crossOriginProxy); + syncLegalNoticeVisibility(serverOAuth.deploymentType); + if (oauthContainer) { + renderOAuthProviders({ + doc, + container: oauthContainer, + divider: oauthDivider, + providers: serverOAuth.providers, + redirectUri: redirectUriParam, + onNavigate: navigateTo, + }); + } + } + + // Non-blocking session probe on `/sign-in`. Redirects immediately when + // an explicit `redirect_uri` is present, or shows a lightweight "Continue as + // " action above the account-switch form. + if (route === 'sign-in' && (sessionContinueEl || redirectUriParam)) { + void (async () => { + try { + const res = await fetchImpl('/api/auth/session', { + method: 'GET', + credentials: 'same-origin', + headers: buildWebAuthHeaders({ clientVersion }), + }); + if (!res || !res.ok || typeof res.json !== 'function') { + return; + } + const data = await res.json(); + const userEmail = + typeof data?.user?.email === 'string' ? data.user.email.trim() : ''; + if (!userEmail) { + return; + } + if (redirectUriParam) { + navigateTo( + resolveSafeAuthRedirect(redirectUriParam, currentUrl.origin) + ); + return; + } + if (sessionContinueEl && continueSessionBtn) { + continueSessionBtn.textContent = `Continue as ${userEmail}`; + continueSessionBtn.addEventListener?.('click', () => { + navigateTo('/'); + }); + sessionContinueEl.hidden = false; + } + } catch { + // Silently ignore session probe failures; sign-in form stays usable. + } + })(); + } + + return { + route, + captcha, + getStep: () => currentStep, + getCaptchaToken: () => captchaToken, + getResendCooldown: () => resendCooldown, + resetTurnstile: () => resetTurnstile?.(), + dispose: () => { + clearResendTimer(); + doc.removeEventListener?.('keydown', handleEscapeBack); + }, + }; +} + +if ( + globalThis.window !== undefined && + globalThis.document !== undefined && + !globalThis.__AFFINE_WEB_HOST_TEST__ +) { + void bootSignInPage(); +} diff --git a/packages/frontend/hosts/web/src/wasm-scalar-rpc.js b/packages/frontend/hosts/web/src/wasm-scalar-rpc.js new file mode 100644 index 0000000000..6b1444f936 --- /dev/null +++ b/packages/frontend/hosts/web/src/wasm-scalar-rpc.js @@ -0,0 +1,143 @@ +// @ts-check + +const ALLOWED_STUB_IMPORT_MODULES = new Set([ + '__wbindgen_placeholder__', + '__wbindgen_externref_xform__', +]); + +/** + * Builds stub imports strictly for unused `wasm-bindgen` placeholder entries + * so the scalar worker exports run directly under `WebAssembly.instantiate` + * without `wasm-bindgen-cli`. Any unexpected external host import module throws + * immediately instead of silently returning `0`. + * + * @param {WebAssembly.Module} mod + * @returns {WebAssembly.Imports} + */ +export function buildStubImports(mod) { + /** @type {Record>} */ + const imports = {}; + for (const desc of WebAssembly.Module.imports(mod)) { + if (!ALLOWED_STUB_IMPORT_MODULES.has(desc.module)) { + throw new Error(`Unexpected wasm import: ${desc.module}.${desc.name}`); + } + if (!imports[desc.module]) { + imports[desc.module] = {}; + } + if (desc.kind === 'function') { + imports[desc.module][desc.name] = () => 0; + } else if (desc.kind === 'global') { + imports[desc.module][desc.name] = 0; + } + } + return imports; +} + +/** + * Resolves a raw scalar export from `instance.exports`, matching either the + * exact name or `wasm-bindgen`'s hashed export `_` (never matching + * `__wbindgen_describe_*` metadata exports). + * + * @param {Record} rawExports + * @param {string} baseName + * @param {string} [label='Wasm'] + * @returns {Function} + */ +export function resolveWasmExport(rawExports, baseName, label = 'Wasm') { + if (typeof rawExports[baseName] === 'function') { + return /** @type {Function} */ (rawExports[baseName]); + } + const prefix = `${baseName}_`; + for (const [key, value] of Object.entries(rawExports)) { + if (key.startsWith(prefix) && typeof value === 'function') { + return value; + } + } + throw new Error(`${label} wasm missing required export: ${baseName}`); +} + +/** + * @typedef {Object} WorkerAbi + * @property {WebAssembly.Memory} memory + * @property {Function} prepare + * @property {Function} invoke + * @property {Function} outputPtr + */ + +/** + * Binds the four exports of the preview worker linear-memory ABI: `memory`, + * `prepare(len) -> ptr`, `invoke() -> len`, and `output_ptr() -> ptr`. + * + * @param {Record} rawExports + * @param {string} [label='Worker'] + * @returns {WorkerAbi} + */ +export function bindWorkerAbi(rawExports, label = 'Worker') { + const memory = rawExports.memory; + if (!(memory instanceof WebAssembly.Memory)) { + throw new Error(`${label} wasm missing required export: memory`); + } + return { + memory, + prepare: resolveWasmExport(rawExports, 'prepare', label), + invoke: resolveWasmExport(rawExports, 'invoke', label), + outputPtr: resolveWasmExport(rawExports, 'output_ptr', label), + }; +} + +/** + * Returns a view of `len` bytes at the wasm32 address `ptr`. Reads + * `memory.buffer` again on every call because any export call can grow the + * memory and detach the previous buffer. + * + * @param {WebAssembly.Memory} memory + * @param {number} ptr + * @param {number} len + * @returns {Uint8Array} + */ +function linearView(memory, ptr, len) { + const buffer = memory.buffer; + const start = ptr >>> 0; + const size = len >>> 0; + if (start > buffer.byteLength || size > buffer.byteLength - start) { + throw new Error( + `Worker wasm range ${start}+${size} is outside its ${buffer.byteLength} B memory` + ); + } + return new Uint8Array(buffer, start, size); +} + +/** + * Writes the request frame `[opcode, ...parts]` into worker linear memory, + * runs it, and returns the response frame (`[0x01, ...ok]` or + * `[0x00, ...utf8Err]`). + * + * The returned view points into linear memory. It stays valid only until the + * next call into the same instance, so the caller must decode or copy it + * synchronously and never keep or transfer it. + * + * @param {WorkerAbi} abi + * @param {number} opcode + * @param {Uint8Array[]} parts + * @returns {Uint8Array} + */ +export function invokeScalarRpc(abi, opcode, parts) { + let total = 1; + for (const part of parts) { + total += part.byteLength; + } + const ptr = Number(abi.prepare(total)) >>> 0; + if (ptr === 0) { + throw new Error(`Worker request of ${total} B exceeds the worker limit`); + } + const input = linearView(abi.memory, ptr, total); + input[0] = opcode; + let at = 1; + for (const part of parts) { + input.set(part, at); + at += part.byteLength; + } + const outLen = Number(abi.invoke()); + const outPtr = Number(abi.outputPtr()); + return linearView(abi.memory, outPtr, outLen); +} diff --git a/packages/frontend/hosts/web/src/worker-loader.js b/packages/frontend/hosts/web/src/worker-loader.js new file mode 100644 index 0000000000..e0d079c57d --- /dev/null +++ b/packages/frontend/hosts/web/src/worker-loader.js @@ -0,0 +1,370 @@ +// @ts-check + +/** + * @typedef {Object} WorkerAssetSpec + * @property {string} script + * @property {string} wasm + */ + +/** + * @typedef {'mermaid' | 'math' | 'typst' | 'pdf'} PreviewWorkerKind + */ + +/** + * @typedef {Object} BuildManifest + * @property {string} shellVersion + * @property {string} buildHash + * @property {string} [buildId] + * @property {string} [shell_build_id] + * @property {string | null} [assetBaseUrl] + * @property {string | null} [appEntryJs] + * @property {string | null} [mainWasmJs] + * @property {Record} workers + * @property {Record} fonts + */ + +/** + * Freezes a build manifest deeply so cookie switches in another tab cannot + * mutate asset resolution for this document. + * + * @param {BuildManifest} raw + * @returns {Readonly} + */ +export function freezeBuildManifest(raw) { + if (!raw || typeof raw !== 'object') { + throw new TypeError('Build manifest must be an object'); + } + const effectiveBuildId = + (typeof raw.shell_build_id === 'string' && raw.shell_build_id) || + (typeof raw.buildId === 'string' && raw.buildId) || + (typeof raw.buildHash === 'string' && raw.buildHash) || + ''; + if (!effectiveBuildId) { + throw new TypeError('Build manifest requires a non-empty buildHash'); + } + /** @type {Record>} */ + const frozenWorkers = {}; + for (const [key, spec] of Object.entries(raw.workers || {})) { + if ( + !spec || + typeof spec.script !== 'string' || + typeof spec.wasm !== 'string' + ) { + throw new TypeError( + `Worker manifest entry "${key}" requires script and wasm URLs` + ); + } + frozenWorkers[key] = Object.freeze({ + script: spec.script, + wasm: spec.wasm, + }); + } + const workers = Object.freeze(frozenWorkers); + const fonts = Object.freeze({ ...raw.fonts }); + const assetBaseUrl = + typeof raw.assetBaseUrl === 'string' && raw.assetBaseUrl.trim() + ? raw.assetBaseUrl.trim() + : null; + const mainWasmJs = + typeof raw.mainWasmJs === 'string' && raw.mainWasmJs.trim() + ? raw.mainWasmJs.trim() + : null; + return Object.freeze({ + shellVersion: String(raw.shellVersion || 'mobile-v1'), + buildHash: effectiveBuildId, + buildId: effectiveBuildId, + shell_build_id: effectiveBuildId, + assetBaseUrl, + appEntryJs: typeof raw.appEntryJs === 'string' ? raw.appEntryJs : null, + mainWasmJs, + workers: /** @type {Record} */ ( + workers + ), + fonts, + }); +} + +/** + * Reads the embedded read-only build manifest from the page DOM. + * + * @param {Document} doc + * @param {string} [elementId='affine-build-manifest'] + * @returns {Readonly} + */ +export function readEmbeddedManifest(doc, elementId = 'affine-build-manifest') { + const node = doc.getElementById(elementId); + if (!node || !node.textContent) { + throw new Error(`Missing build manifest element #${elementId}`); + } + return freezeBuildManifest(JSON.parse(node.textContent)); +} + +/** + * Resolves a pinned asset URL against the locked asset root or site root so + * nested routes and dual-tab shell cookie switches never cause 404 errors. + * + * @param {string} assetUrl + * @param {string} baseUrl + * @param {string} buildId + * @param {string | null} [assetBaseUrl] + * @returns {string} + */ +export function pinUrl(assetUrl, baseUrl, buildId, assetBaseUrl = null) { + const siteRoot = new URL('/', baseUrl); + let resolved; + if (assetBaseUrl) { + const normalizedRoot = assetBaseUrl.endsWith('/') + ? assetBaseUrl + : `${assetBaseUrl}/`; + const lockedRoot = new URL(normalizedRoot, siteRoot); + const alreadyPrefixed = + assetUrl.startsWith(lockedRoot.pathname) || + assetUrl.startsWith(lockedRoot.href); + if (alreadyPrefixed) { + resolved = new URL(assetUrl, siteRoot); + } else { + const trimmed = + assetUrl.startsWith('/') && !assetUrl.startsWith('//') + ? assetUrl.slice(1) + : assetUrl; + resolved = new URL(trimmed, lockedRoot); + } + } else { + resolved = new URL(assetUrl, siteRoot); + } + if (!resolved.pathname.includes(buildId)) { + resolved.searchParams.set('v', buildId); + } + return resolved.toString(); +} + +/** + * Builds the ES module bootstrap source for a preview Web Worker. + * + * @param {string} hostOrigin + * @param {string} scriptUrl + * @param {string} wasmUrl + * @returns {string} + */ +export function buildWorkerBootstrapSource(hostOrigin, scriptUrl, wasmUrl) { + return [ + `globalThis.AFFINE_HOST_ORIGIN = ${JSON.stringify(hostOrigin)};`, + `globalThis.AFFINE_WORKER_WASM_URL = ${JSON.stringify(wasmUrl)};`, + 'const __q = [];', + 'const __onMsg = event => __q.push(event);', + "globalThis.addEventListener('message', __onMsg);", + `await import(${JSON.stringify(scriptUrl)});`, + "globalThis.removeEventListener('message', __onMsg);", + "for (const event of __q) globalThis.dispatchEvent(new MessageEvent('message', { data: event.data, ports: event.ports }));", + ].join('\n'); +} + +/** + * Creates a lazy worker and on-demand font loader pinned to this page's + * immutable build hash manifest. + * + * @param {BuildManifest} rawManifest + * @param {Object} [options] + * @param {string} [options.baseUrl] + * @param {string | null} [options.assetBaseUrl] + * @param {string} [options.buildId] + * @param {(url: string, opts: WorkerOptions) => Worker} [options.createWorker] + * @param {(blob: Blob) => string} [options.createObjectURL] + * @param {(url: string) => void} [options.revokeObjectURL] + * @param {typeof fetch} [options.fetchImpl] + */ +export function createWorkerLoader(rawManifest, options = {}) { + const manifest = freezeBuildManifest({ + ...rawManifest, + buildId: options.buildId || rawManifest.buildId || rawManifest.buildHash, + assetBaseUrl: + options.assetBaseUrl !== undefined + ? options.assetBaseUrl + : rawManifest.assetBaseUrl, + }); + const baseUrl = + options.baseUrl || + (globalThis.location === undefined + ? 'https://app.affine.pro/' + : globalThis.location.href); + const lockedAssetBaseUrl = manifest.assetBaseUrl || null; + const lockedBuildId = manifest.buildId || manifest.buildHash; + const hostOrigin = new URL(baseUrl).origin; + const createWorker = + options.createWorker || ((url, workerOpts) => new Worker(url, workerOpts)); + const createObjectURL = + options.createObjectURL || (blob => URL.createObjectURL(blob)); + const revokeObjectURL = + options.revokeObjectURL || + (url => { + if (typeof URL.revokeObjectURL === 'function') { + URL.revokeObjectURL(url); + } + }); + const fetchImpl = options.fetchImpl || globalThis.fetch; + + /** @type {Map} */ + const workerCache = new Map(); + /** @type {Map} */ + const workerBlobUrls = new Map(); + + /** + * Resolves pinned `{ script, wasm }` asset URLs for one preview worker. + * + * @param {PreviewWorkerKind} kind + * @returns {{ script: string, wasm: string }} + */ + function resolveWorkerAssets(kind) { + const entry = manifest.workers[kind]; + if (!entry) { + throw new Error(`Unknown worker kind: ${kind}`); + } + return { + script: pinUrl(entry.script, baseUrl, lockedBuildId, lockedAssetBaseUrl), + wasm: pinUrl(entry.wasm, baseUrl, lockedBuildId, lockedAssetBaseUrl), + }; + } + + /** + * Resolves a pinned on-demand font asset URL from the frozen manifest. + * + * @param {string} scriptName + * @returns {string} + */ + function resolveFontUrl(scriptName) { + const entry = manifest.fonts[scriptName]; + if (!entry) { + throw new Error(`Unknown font script: ${scriptName}`); + } + return pinUrl(entry, baseUrl, lockedBuildId, lockedAssetBaseUrl); + } + + /** + * Resolves the pinned app entry JS URL (`default-app-entry.js`) when declared in the manifest. + * + * @returns {string | null} + */ + function resolveAppEntryUrl() { + if (!manifest.appEntryJs) { + return null; + } + return pinUrl( + manifest.appEntryJs, + baseUrl, + lockedBuildId, + lockedAssetBaseUrl + ); + } + + /** + * Resolves the pinned main Wasm JS glue URL (`playground.js`) when declared in the manifest. + * + * @returns {string | null} + */ + function resolveMainWasmJsUrl() { + if (!manifest.mainWasmJs) { + return null; + } + return pinUrl( + manifest.mainWasmJs, + baseUrl, + lockedBuildId, + lockedAssetBaseUrl + ); + } + + /** + * Lazily spawns and caches a preview Web Worker via a pinned ES module + * `blob:` bootstrap script (never passes a `.wasm` URL to `new Worker`). + * + * @param {PreviewWorkerKind} kind + * @returns {Worker} + */ + function loadWorker(kind) { + const existing = workerCache.get(kind); + if (existing) { + return existing; + } + const { script, wasm } = resolveWorkerAssets(kind); + const source = buildWorkerBootstrapSource(hostOrigin, script, wasm); + const blob = new Blob([source], { type: 'text/javascript' }); + const blobUrl = createObjectURL(blob); + const worker = createWorker(blobUrl, { + type: 'module', + name: `affine-${kind}-${lockedBuildId}`, + }); + workerCache.set(kind, worker); + workerBlobUrls.set(kind, blobUrl); + return worker; + } + + /** + * Returns true when a worker of `kind` has already been spawned. + * + * @param {PreviewWorkerKind} kind + * @returns {boolean} + */ + function hasLoadedWorker(kind) { + return workerCache.has(kind); + } + + /** + * Terminates and removes a spawned worker of `kind`. + * + * @param {PreviewWorkerKind} kind + * @returns {boolean} + */ + function terminateWorker(kind) { + const worker = workerCache.get(kind); + if (!worker) { + return false; + } + workerCache.delete(kind); + const blobUrl = workerBlobUrls.get(kind); + if (blobUrl) { + workerBlobUrls.delete(kind); + revokeObjectURL(blobUrl); + } + worker.terminate?.(); + return true; + } + + /** + * Terminates all spawned preview workers. + */ + function dispose() { + for (const kind of workerCache.keys()) { + terminateWorker(/** @type {PreviewWorkerKind} */ (kind)); + } + } + + /** + * Fetches an on-demand TTF/OTF font binary pinned to this page's build hash. + * + * @param {string} scriptName + * @returns {Promise} + */ + async function loadFont(scriptName) { + const url = resolveFontUrl(scriptName); + const response = await fetchImpl(url, { credentials: 'same-origin' }); + if (!response.ok) { + throw new Error(`Font fetch failed (${response.status}): ${url}`); + } + return response.arrayBuffer(); + } + + return Object.freeze({ + manifest, + buildId: lockedBuildId, + assetBaseUrl: lockedAssetBaseUrl, + resolveWorkerAssets, + resolveFontUrl, + resolveAppEntryUrl, + resolveMainWasmJsUrl, + loadWorker, + hasLoadedWorker, + terminateWorker, + dispose, + loadFont, + }); +} diff --git a/packages/frontend/hosts/web/src/workers/math-worker.js b/packages/frontend/hosts/web/src/workers/math-worker.js new file mode 100644 index 0000000000..bd506623d8 --- /dev/null +++ b/packages/frontend/hosts/web/src/workers/math-worker.js @@ -0,0 +1,4 @@ +// @ts-check +import { startPreviewWorker } from './preview-worker-core.js'; + +startPreviewWorker('math'); diff --git a/packages/frontend/hosts/web/src/workers/mermaid-worker.js b/packages/frontend/hosts/web/src/workers/mermaid-worker.js new file mode 100644 index 0000000000..1cb9674f71 --- /dev/null +++ b/packages/frontend/hosts/web/src/workers/mermaid-worker.js @@ -0,0 +1,4 @@ +// @ts-check +import { startPreviewWorker } from './preview-worker-core.js'; + +startPreviewWorker('mermaid'); diff --git a/packages/frontend/hosts/web/src/workers/pdf-worker.js b/packages/frontend/hosts/web/src/workers/pdf-worker.js new file mode 100644 index 0000000000..b3d9433979 --- /dev/null +++ b/packages/frontend/hosts/web/src/workers/pdf-worker.js @@ -0,0 +1,4 @@ +// @ts-check +import { startPreviewWorker } from './preview-worker-core.js'; + +startPreviewWorker('pdf'); diff --git a/packages/frontend/hosts/web/src/workers/preview-worker-core.js b/packages/frontend/hosts/web/src/workers/preview-worker-core.js new file mode 100644 index 0000000000..ce5c6be062 --- /dev/null +++ b/packages/frontend/hosts/web/src/workers/preview-worker-core.js @@ -0,0 +1,323 @@ +// @ts-check + +import { + bindWorkerAbi, + buildStubImports, + invokeScalarRpc, +} from '../wasm-scalar-rpc.js'; + +const OPCODE_REGISTER_FONT = 1; +const OPCODE_MERMAID_SVG = 2; +const OPCODE_MATH_SVG = 3; +const OPCODE_TYPST_SVG = 4; +const OPCODE_PDF_OPEN = 5; +const OPCODE_PDF_RENDER = 6; +const OPCODE_PDF_CLOSE = 7; +const OPCODE_MATH_RGBA = 8; + +const PDF_PAGE_HEADER_BYTES = 13; +const MATH_RGBA_HEADER_BYTES = 21; + +const KINDS = new Set(['mermaid', 'math', 'typst', 'pdf']); + +/** + * Instantiates the pinned `.wasm` binary and binds its linear-memory ABI. + * + * @param {string} wasmUrl + */ +async function loadWorkerAbi(wasmUrl) { + const response = await globalThis.fetch(wasmUrl); + if (!response.ok) { + throw new Error( + `Failed to fetch worker wasm (${response.status}): ${wasmUrl}` + ); + } + const bytes = new Uint8Array(await response.arrayBuffer()); + const mod = await WebAssembly.compile(bytes); + const instance = await WebAssembly.instantiate(mod, buildStubImports(mod)); + return bindWorkerAbi( + /** @type {Record} */ ( + /** @type {unknown} */ (instance.exports) + ), + 'Worker' + ); +} + +/** + * @param {...number} words + * @returns {Uint8Array} + */ +function u32Words(...words) { + const buf = new Uint8Array(words.length * 4); + const view = new DataView(buf.buffer); + words.forEach((word, idx) => view.setUint32(idx * 4, word >>> 0, true)); + return buf; +} + +/** + * @param {unknown} value + * @returns {Uint8Array} + */ +function toBytes(value) { + if (value instanceof Uint8Array) { + return value; + } + if (value instanceof ArrayBuffer) { + return new Uint8Array(value); + } + return new Uint8Array(/** @type {ArrayLike} */ (value || [])); +} + +/** + * @param {Uint8Array} frame + */ +function frameView(frame) { + return new DataView(frame.buffer, frame.byteOffset, frame.byteLength); +} + +/** + * Encodes a `math` RGBA rasterization request (`OPCODE_MATH_RGBA = 8`). + * + * @param {TextEncoder} encoder + * @param {{ display?: boolean, fontSizePt?: number, paddingPt?: number, scaleFactor?: number, colorCss?: string, latex?: string, source?: string }} msg + * @returns {Uint8Array[]} + */ +function encodeMathRgbaParts(encoder, msg) { + const colorBytes = encoder.encode(String(msg.colorCss || '#000000')); + const latexBytes = encoder.encode(String(msg.latex ?? msg.source ?? '')); + const head = new Uint8Array(15); + const view = new DataView(head.buffer); + head[0] = msg.display ? 1 : 0; + view.setFloat32(1, Number(msg.fontSizePt) || 16.0, true); + view.setFloat32( + 5, + Number.isFinite(Number(msg.paddingPt)) + ? Number(msg.paddingPt) + : msg.display + ? 4.0 + : 1.5, + true + ); + view.setFloat32(9, Number(msg.scaleFactor) || 2.0, true); + view.setUint16(13, colorBytes.length, true); + return [head, colorBytes, latexBytes]; +} + +/** + * Starts a dedicated preview Web Worker for one capability (`mermaid`, `math`, + * `typst`, or `pdf`), reading its pinned `.wasm` URL from + * `globalThis.AFFINE_WORKER_WASM_URL`. + * + * Messages that arrive before the module is ready wait on one shared start-up + * promise and then run in arrival order. Each request runs synchronously after + * that, so a `pdf_open`, `pdf_render`, `pdf_close` sequence keeps its order. + * + * @param {'mermaid' | 'math' | 'typst' | 'pdf'} kind + */ +export function startPreviewWorker(kind) { + if (!KINDS.has(kind)) { + throw new Error(`Unsupported preview worker kind: ${kind}`); + } + /** @type {Promise | null} */ + let abiPromise = null; + + function ensureAbi() { + if (!abiPromise) { + const wasmUrl = + /** @type {{ AFFINE_WORKER_WASM_URL?: string }} */ ( + /** @type {unknown} */ (globalThis) + ).AFFINE_WORKER_WASM_URL; + if (!wasmUrl) { + return Promise.reject( + new Error('Missing globalThis.AFFINE_WORKER_WASM_URL') + ); + } + abiPromise = loadWorkerAbi(wasmUrl).catch(err => { + abiPromise = null; + throw err; + }); + } + return abiPromise; + } + + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + /** + * Runs one request and returns the response frame view. Throws the worker + * error text for a failure frame. + * + * @param {import('../wasm-scalar-rpc.js').WorkerAbi} abi + * @param {number} opcode + * @param {Uint8Array[]} parts + * @param {number} minLength + */ + function call(abi, opcode, parts, minLength) { + const frame = invokeScalarRpc(abi, opcode, parts); + if (frame.length === 0 || frame[0] !== 1) { + throw new Error(decoder.decode(frame.subarray(1)) || 'worker error'); + } + if (frame.length < minLength) { + throw new Error(`Truncated worker response (${frame.length} B)`); + } + return frame; + } + + /** + * Copies `widthPx * heightPx * 4` RGBA bytes after `headerBytes` out of + * linear memory into a compact buffer that the caller can transfer. + * + * @param {Uint8Array} frame + * @param {number} headerBytes + * @param {number} widthPx + * @param {number} heightPx + */ + function copyRgba(frame, headerBytes, widthPx, heightPx) { + const expected = widthPx * heightPx * 4; + if (frame.byteLength - headerBytes !== expected) { + throw new Error( + `RGBA length mismatch: got ${frame.byteLength - headerBytes}, expected ${expected}` + ); + } + return frame.slice(headerBytes); + } + + /** + * @param {import('../wasm-scalar-rpc.js').WorkerAbi} abi + * @param {Record} msg + * @returns {{ result: Record, transfer: Transferable[] }} + */ + function handle(abi, msg) { + if (msg.op === 'register_font') { + const frame = call( + abi, + OPCODE_REGISTER_FONT, + [toBytes(msg.fontBytes)], + 5 + ); + return { + result: { faceCount: frameView(frame).getUint32(1, true) }, + transfer: [], + }; + } + if (kind === 'pdf') { + const docId = Number(msg.docId) >>> 0; + if (msg.op === 'pdf_open') { + const frame = call( + abi, + OPCODE_PDF_OPEN, + [u32Words(docId), toBytes(msg.pdfBytes)], + 5 + ); + return { + result: { kind, pageCount: frameView(frame).getUint32(1, true) }, + transfer: [], + }; + } + if (msg.op === 'pdf_render') { + const head = u32Words(docId, Number(msg.pageIndex ?? 0), 0); + new DataView(head.buffer).setFloat32(8, Number(msg.scale) || 1, true); + const frame = call( + abi, + OPCODE_PDF_RENDER, + [head], + PDF_PAGE_HEADER_BYTES + ); + const view = frameView(frame); + const pageCount = view.getUint32(1, true); + const widthPx = view.getUint32(5, true); + const heightPx = view.getUint32(9, true); + const rgba = copyRgba(frame, PDF_PAGE_HEADER_BYTES, widthPx, heightPx); + return { + result: { kind, pageCount, widthPx, heightPx, rgba }, + transfer: [rgba.buffer], + }; + } + if (msg.op === 'pdf_close') { + call(abi, OPCODE_PDF_CLOSE, [u32Words(docId)], 1); + return { result: { kind }, transfer: [] }; + } + throw new Error(`Unsupported pdf worker op: ${String(msg.op)}`); + } + if (kind === 'math' && msg.op === 'rgba') { + const frame = call( + abi, + OPCODE_MATH_RGBA, + encodeMathRgbaParts(encoder, msg), + MATH_RGBA_HEADER_BYTES + ); + const view = frameView(frame); + const widthPx = view.getUint32(13, true); + const heightPx = view.getUint32(17, true); + const rgba = copyRgba(frame, MATH_RGBA_HEADER_BYTES, widthPx, heightPx); + return { + result: { + kind, + widthPt: view.getFloat32(1, true), + ascentPt: view.getFloat32(5, true), + descentPt: view.getFloat32(9, true), + widthPx, + heightPx, + rgba, + }, + transfer: [rgba.buffer], + }; + } + if (kind === 'typst') { + const frame = call( + abi, + OPCODE_TYPST_SVG, + [ + u32Words(Number(msg.pageIndex ?? 0)), + encoder.encode(String(msg.source ?? '')), + ], + 5 + ); + return { + result: { + kind, + pageCount: frameView(frame).getUint32(1, true), + svg: decoder.decode(frame.subarray(5)), + }, + transfer: [], + }; + } + /** @type {Uint8Array[]} */ + let parts; + let opcode = OPCODE_MATH_SVG; + if (kind === 'mermaid') { + opcode = OPCODE_MERMAID_SVG; + const themeTag = msg.theme === 'light' ? 1 : msg.theme === 'dark' ? 2 : 0; + parts = [ + Uint8Array.of(themeTag), + encoder.encode(String(msg.source ?? '')), + ]; + } else { + parts = [encoder.encode(String(msg.latex ?? msg.source ?? ''))]; + } + const frame = call(abi, opcode, parts, 1); + return { + result: { kind, svg: decoder.decode(frame.subarray(1)) }, + transfer: [], + }; + } + + globalThis.addEventListener('message', async event => { + const msg = event?.data; + if (!msg || typeof msg !== 'object') { + return; + } + const id = msg.id ?? null; + try { + const abi = await ensureAbi(); + const { result, transfer } = handle(abi, msg); + globalThis.postMessage({ id, ok: true, result }, transfer); + } catch (error) { + globalThis.postMessage({ + id, + ok: false, + error: error instanceof Error ? error.message : String(error), + }); + } + }); +} diff --git a/packages/frontend/hosts/web/src/workers/typst-worker.js b/packages/frontend/hosts/web/src/workers/typst-worker.js new file mode 100644 index 0000000000..2acaf975e9 --- /dev/null +++ b/packages/frontend/hosts/web/src/workers/typst-worker.js @@ -0,0 +1,4 @@ +// @ts-check +import { startPreviewWorker } from './preview-worker-core.js'; + +startPreviewWorker('typst'); diff --git a/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs b/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs new file mode 100644 index 0000000000..196acd77bb --- /dev/null +++ b/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs @@ -0,0 +1,376 @@ +// @ts-check + +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; + +import { + extractWasmDataSegments, + scanWasmDataPrefixes, + verifySourcePrefixes, + ZERO_IN_PRODUCTION, +} from '../../../scripts/check-snapshot-prefixes.mjs'; + +/** + * Encodes an unsigned integer as LEB128. + * + * @param {number} value + * @returns {number[]} + */ +function encodeU32Leb(value) { + const out = []; + let v = value >>> 0; + do { + let byte = v & 0x7f; + v >>>= 7; + if (v !== 0) byte |= 0x80; + out.push(byte); + } while (v !== 0); + return out; +} + +/** + * Encodes a signed i32 as LEB128. + * + * @param {number} value + * @returns {number[]} + */ +function encodeI32Leb(value) { + const out = []; + let v = value | 0; + let more = true; + while (more) { + let byte = v & 0x7f; + v >>= 7; + if ((v === 0 && (byte & 0x40) === 0) || (v === -1 && (byte & 0x40) !== 0)) { + more = false; + } else { + byte |= 0x80; + } + out.push(byte); + } + return out; +} + +/** + * Builds a Wasm section byte array. + * + * @param {number} id + * @param {number[]} payload + * @returns {number[]} + */ +function buildSection(id, payload) { + return [id, ...encodeU32Leb(payload.length), ...payload]; +} + +/** + * Builds a Wasm custom section (ID 0). + * + * @param {string} name + * @param {string} body + * @returns {number[]} + */ +function buildCustomSection(name, body) { + const nameBytes = Array.from(Buffer.from(name, 'utf8')); + const bodyBytes = Array.from(Buffer.from(body, 'utf8')); + return buildSection(0, [ + ...encodeU32Leb(nameBytes.length), + ...nameBytes, + ...bodyBytes, + ]); +} + +/** + * Builds a Wasm Section 11 (Data) from segment descriptors. + * + * @param {Array<{ mode: 0 | 1 | 2, offset?: number, memIdx?: number, data: string | Uint8Array }>} segments + * @returns {number[]} + */ +function buildDataSection(segments) { + const body = [...encodeU32Leb(segments.length)]; + for (const seg of segments) { + body.push(...encodeU32Leb(seg.mode)); + if (seg.mode === 0) { + // i32.const end + body.push(0x41, ...encodeI32Leb(seg.offset ?? 0), 0x0b); + } else if (seg.mode === 2) { + body.push( + ...encodeU32Leb(seg.memIdx ?? 0), + 0x41, + ...encodeI32Leb(seg.offset ?? 0), + 0x0b + ); + } + const raw = + typeof seg.data === 'string' + ? Array.from(Buffer.from(seg.data, 'utf8')) + : Array.from(seg.data); + body.push(...encodeU32Leb(raw.length), ...raw); + } + return buildSection(11, body); +} + +/** + * Builds a complete Wasm module binary. + * + * @param {number[][]} sections + * @returns {Uint8Array} + */ +function buildWasm(sections) { + const bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]; + for (const section of sections) { + bytes.push(...section); + } + return Uint8Array.from(bytes); +} + +await test('passes on clean Section 11 segments with 0x0b offset', () => { + // Offset 11 (0x0b) verifies const-expr skipping does not stop early on a literal 0x0b byte. + const wasm = buildWasm([ + buildDataSection([ + { mode: 0, offset: 11, data: 'hello world' }, + { mode: 1, data: 'clean passive payload' }, + { mode: 2, memIdx: 1, offset: 64, data: 'clean active mem1 payload' }, + ]), + ]); + + const parsed = extractWasmDataSegments(wasm); + assert.equal(parsed.segments.length, 3); + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, true); + assert.deepEqual(result.hits, []); + assert.equal(result.segmentCount, 3); + assert.match(result.sha256, /^[0-9a-f]{64}$/); +}); + +await test('fails on active data segment hit with index and offset', () => { + const wasm = buildWasm([ + buildDataSection([ + { mode: 0, offset: 0, data: 'clean' }, + { + mode: 0, + offset: 32, + data: 'abc edgeless.surface.rect def edgeless.surface.line', + }, + ]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, false); + assert.deepEqual(result.hits, [ + { + prefix: 'edgeless.surface.', + count: 2, + firstSegment: 1, + firstOffset: 4, + }, + ]); +}); + +await test('fails on passive data segment hit', () => { + const wasm = buildWasm([ + buildDataSection([ + { mode: 1, data: 'prefix overlay.slash_menu.item.h1 suffix' }, + ]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, false); + assert.deepEqual(result.hits, [ + { + prefix: 'overlay.slash_menu.item.', + count: 1, + firstSegment: 0, + firstOffset: 7, + }, + { + prefix: 'overlay.slash_menu', + count: 1, + firstSegment: 0, + firstOffset: 7, + }, + ]); +}); + +await test('catches bare container IDs and Slice 9A ratchet prefixes', () => { + const wasm = buildWasm([ + buildDataSection([ + { + mode: 0, + offset: 0, + data: 'overlay.bookmark_toolbar\0overlay.table_hover.add_col\0chrome.edgeless_element_toolbar.opacity\0edgeless.handle.rotate_ne', + }, + ]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, false); + assert.deepEqual( + result.hits.map(hit => hit.prefix), + [ + 'overlay.bookmark_toolbar', + 'overlay.table_hover.', + 'chrome.edgeless_element_toolbar.', + 'edgeless.handle.rotate_', + 'chrome.edgeless_element_toolbar', + ] + ); +}); + +await test('ignores matching strings in custom sections', () => { + const wasm = buildWasm([ + buildCustomSection( + 'name', + 'edgeless.surface.box page.presence.1 overlay.linked_doc_menu.journal.0' + ), + buildDataSection([{ mode: 0, offset: 0, data: 'clean data payload' }]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, true); + assert.deepEqual(result.hits, []); +}); + +await test('ignores prefixes split across two data segments', () => { + const wasm = buildWasm([ + buildDataSection([ + { mode: 0, offset: 0, data: 'edgeless.sur' }, + { mode: 0, offset: 12, data: 'face.box' }, + ]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, true); + assert.deepEqual(result.hits, []); +}); + +await test('rejects malformed or missing Data sections', () => { + const cases = [ + ['missing Data section', buildWasm([buildCustomSection('name', 'clean')])], + ['empty Data section payload', buildWasm([buildSection(11, [])])], + ['zero Data segments', buildWasm([buildDataSection([])])], + [ + 'empty Data segment payloads', + buildWasm([buildDataSection([{ mode: 1, data: '' }])]), + ], + ['bad magic header', Uint8Array.from([0x00, 0x00, 0x00, 0x00, 1, 0, 0, 0])], + [ + 'truncated LEB128 section length', + Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, 11, 0x80]), + ], + [ + 'section length out of bounds', + Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, 11, 0x10, 0x01]), + ], + ]; + + for (const [label, bytes] of cases) { + assert.throws( + () => scanWasmDataPrefixes(bytes), + Error, + `Expected error for case: ${label}` + ); + } +}); + +await test('verifies source liveness and catches missing prefixes', () => { + const live = verifySourcePrefixes(); + assert.equal( + live.ok, + true, + `Missing prefixes in repo: ${live.missing.join(', ')}` + ); + assert.equal(Object.keys(live.counts).length, ZERO_IN_PRODUCTION.length); + + const dir = mkdtempSync(join(tmpdir(), 'snapshot-prefix-src-')); + try { + const srcDir = join(dir, 'blocksuite', 'crates', 'demo', 'src'); + mkdirSync(srcDir, { recursive: true }); + writeFileSync( + join(srcDir, 'lib.rs'), + 'const A: &str = "edgeless.surface.";\n' + ); + + const missing = verifySourcePrefixes({ + repoRoot: dir, + prefixes: ['edgeless.surface.', 'nonexistent.prefix.'], + }); + assert.equal(missing.ok, false); + assert.deepEqual(missing.missing, ['nonexistent.prefix.']); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +await test('source liveness ignores prefixes in test modules', () => { + const dir = mkdtempSync(join(tmpdir(), 'snapshot-prefix-tests-')); + try { + const srcDir = join(dir, 'blocksuite', 'crates', 'demo', 'src'); + mkdirSync(join(srcDir, 'tests'), { recursive: true }); + const files = { + 'lib.rs': [ + 'mod hit_test;', + 'mod paint;', + '#[cfg(test)]', + 'mod tests;', + '#[cfg(all(test, feature = "harness"))]', + 'mod helpers {', + ' const H: &str = "edgeless.note.";', + '}', + "pub fn after() -> &'static str {", + ' "edgeless.frame."', + '}', + ], + 'hit_test.rs': ['const S: &str = "overlay.slash_menu.item.";'], + 'paint.rs': [ + 'const P: &str = "edgeless.surface.";', + '#[cfg(test)]', + 'mod tests {', + ' #[test]', + ' fn prefix() {', + ' assert_eq!(super::P, "edgeless.surface.");', + ' assert_ne!(super::P, "edgeless.text.");', + ' }', + '}', + ], + 'tests.rs': ['mod nested;', 'const T: &str = "edgeless.block.";'], + 'tests/nested.rs': ['const N: &str = "page.presence.";'], + }; + for (const [name, lines] of Object.entries(files)) { + writeFileSync(join(srcDir, name), lines.join('\n') + '\n'); + } + + const result = verifySourcePrefixes({ + repoRoot: dir, + prefixes: [ + 'edgeless.surface.', + 'edgeless.frame.', + 'overlay.slash_menu.item.', + 'edgeless.note.', + 'edgeless.text.', + 'edgeless.block.', + 'page.presence.', + ], + }); + assert.equal(result.scannedFiles, 3); + assert.deepEqual(result.counts, { + 'edgeless.surface.': 1, + 'edgeless.frame.': 1, + 'overlay.slash_menu.item.': 1, + 'edgeless.note.': 0, + 'edgeless.text.': 0, + 'edgeless.block.': 0, + 'page.presence.': 0, + }); + assert.deepEqual(result.missing, [ + 'edgeless.note.', + 'edgeless.text.', + 'edgeless.block.', + 'page.presence.', + ]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/frontend/hosts/web/tests/chromium-harness.test.mjs b/packages/frontend/hosts/web/tests/chromium-harness.test.mjs new file mode 100644 index 0000000000..aa010ad16e --- /dev/null +++ b/packages/frontend/hosts/web/tests/chromium-harness.test.mjs @@ -0,0 +1,665 @@ +// @ts-check + +/** + * Lifecycle tests for `scripts/chromium-harness.mjs`. + * + * Each test starts this file again as a `runner` process that owns a harness. + * The harness starts this file as a fake `server`, and the server starts a + * `grandchild` in its process group. The server and the grandchild each hold a + * TCP socket of the test open. The kernel closes that socket when its process + * dies, so the test waits for events and never for a fixed time. + */ + +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { + existsSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, + writeSync, +} from 'node:fs'; +import { createServer as createHttpServer } from 'node:http'; +import { connect, createServer as createTcpServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { createChromiumHarness } from '../scripts/chromium-harness.mjs'; + +const SELF = fileURLToPath(import.meta.url); + +/** For the scenarios where the harness waits until a time limit ends. */ +const SHORT_LIMITS = { termGraceMs: 50, groupGoneTimeoutMs: 100 }; + +/** + * The runner scenarios. `server` is the mode of the fake server, `signals` + * patches the answers for process-group signals, and `limits` goes to the + * harness. + * + * @type {Record} + */ +const RUNNER_SCENARIOS = { + close: {}, + throw: {}, + wait: {}, + exit: {}, + 'denied-close': { signals: 'denied', limits: SHORT_LIMITS }, + 'denied-exit': { signals: 'denied' }, + 'alive-close': { signals: 'alive', limits: SHORT_LIMITS }, + 'kill-denied-close': { + server: 'ignore-term', + signals: 'denied-after-term', + limits: SHORT_LIMITS, + }, + 'reaped-late-close': { signals: 'denied-until-reaped' }, + 'signal-during-health': {}, + 'health-hangs': { limits: { serverHealthTimeoutMs: 100 } }, + 'launch-fails': {}, +}; + +/** Listens on a free TCP port and keeps each accepted socket open. */ +async function listenLiveness() { + /** @type {import('node:net').Socket[]} */ + const held = []; + const server = createTcpServer(socket => { + socket.on('error', () => {}); + socket.resume(); + held.push(socket); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + return /** @type {import('node:net').AddressInfo} */ (server.address()).port; +} + +/** Ignores `SIGTERM`: only the `SIGKILL` of its process group stops it. */ +async function runGrandchild() { + process.on('SIGTERM', () => {}); + process.stdout.write(`${await listenLiveness()}\n`); +} + +/** + * `plain` answers the health check. `ignore-term` also ignores `SIGTERM`. + * `signal-on-health` ignores `SIGTERM` and never answers the health check. It + * sends `SIGTERM` to the runner when the health request arrives. + * + * @param {string[]} args Info file path and mode. + */ +async function runFakeServer([infoPath, mode]) { + const grandchild = spawn(process.execPath, [SELF, 'grandchild'], { + stdio: ['ignore', 'pipe', 'inherit'], + }); + const [grandchildPort] = await once(grandchild.stdout, 'data'); + const livenessPorts = [ + await listenLiveness(), + Number(String(grandchildPort)), + ]; + if (mode !== 'plain') { + process.on('SIGTERM', () => {}); + } + const server = createHttpServer((req, res) => { + if (req.url === '/exit') { + res.end(() => process.exit(0)); + } else if (mode === 'signal-on-health') { + process.kill(process.ppid, 'SIGTERM'); + } else { + res.end('ok'); + } + }).listen(0, '127.0.0.1'); + await once(server, 'listening'); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + server.address() + ); + const info = { + pgid: process.pid, + livenessPorts, + baseUrl: `http://127.0.0.1:${port}`, + }; + writeFileSync(infoPath + '.tmp', JSON.stringify(info)); + renameSync(infoPath + '.tmp', infoPath); +} + +/** + * Replaces the answer of the kernel for process-group signals. + * + * - `denied`: each signal gets `EPERM`. + * - `alive`: each probe finds the group. + * - `denied-after-term`: `SIGTERM` arrives. Each other signal gets `EPERM`. + * - `denied-until-reaped`: the answers of macOS for a group that holds only + * zombies. After Node reaps the leader, the next three signals arrive but + * get `EPERM`. Then the kernel answers again. + * + * @param {string} mode + * @returns {() => number} How many `EPERM` answers of `denied-until-reaped` are still to come. + */ +function patchGroupSignals(mode) { + const realKill = process.kill.bind(process); + const deny = () => { + throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' }); + }; + /** @param {number} pid */ + const isReaped = pid => { + try { + realKill(pid, 0); + return false; + } catch { + return true; + } + }; + let transientDenials = mode === 'denied-until-reaped' ? 3 : 0; + process.kill = (pid, signal) => { + if (pid >= 0) { + return realKill(pid, signal); + } + if ( + mode === 'denied' || + (mode === 'denied-after-term' && signal !== 'SIGTERM') + ) { + deny(); + } + if (mode === 'alive' && signal === 0) { + return true; + } + if (transientDenials > 0 && isReaped(-pid)) { + transientDenials -= 1; + try { + realKill(pid, signal); + } catch { + // The group is gone. + } + deny(); + } + return realKill(pid, signal); + }; + return () => transientDenials; +} + +/** + * @param {string[]} args Scenario and info file path. + */ +async function runRunner([scenario, infoPath]) { + const { server = 'plain', signals, limits } = RUNNER_SCENARIOS[scenario]; + const harness = createChromiumHarness({ + tmpPrefix: 'affine-harness-test-', + limits, + }); + const getBaseUrl = () => + existsSync(infoPath) + ? JSON.parse(readFileSync(infoPath, 'utf8')).baseUrl + : undefined; + /** + * @param {string} mode + * @param {string | (() => string | undefined)} [healthUrl] + */ + const startServer = (mode, healthUrl = getBaseUrl) => + harness.startServer({ + bin: process.execPath, + args: [SELF, 'server', infoPath, mode], + baseUrl: healthUrl, + }); + /** @param {object} fields */ + const report = fields => { + writeSync( + 1, + `${JSON.stringify({ workTmp: harness.workTmp, ...fields })}\n` + ); + }; + + /** + * Runs a start that fails, closes the harness, and reports the error. + * + * @param {() => Promise} start + */ + const reportFailedStart = async start => { + let message = ''; + try { + await start(); + } catch (err) { + message = String(err); + } finally { + await harness.close(); + } + report({ message }); + }; + + if (scenario === 'launch-fails') { + await reportFailedStart(() => harness.launchChromium()); + return; + } + + if (scenario === 'health-hangs') { + // The health URL is a listener in this process that never answers. Thus + // the health request is in flight when the time limit ends. + const silent = createHttpServer(() => {}).listen(0, '127.0.0.1'); + await once(silent, 'listening'); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + silent.address() + ); + await reportFailedStart(() => + startServer('plain', `http://127.0.0.1:${port}`) + ); + silent.close(); + silent.closeAllConnections(); + return; + } + + if (scenario === 'signal-during-health') { + const refusals = []; + for (const mode of ['signal-on-health', 'plain']) { + try { + await startServer(mode); + refusals.push(null); + } catch (err) { + refusals.push(String(err)); + } + } + report({ refusals }); + await once(process.stdin, 'data'); + process.stdin.pause(); + // The escalation to `SIGKILL` can stop the server before this request. + await fetch(`${getBaseUrl()}/exit`).catch(() => {}); + return; + } + + await startServer(server); + const pendingDenials = signals ? patchGroupSignals(signals) : () => 0; + report({}); + // The test says when to go on. The `wait` scenario never gets this line. + await once(process.stdin, 'data'); + process.stdin.pause(); + if (scenario === 'exit' || scenario === 'denied-exit') { + process.exit(7); + } + try { + assert.notEqual(scenario, 'throw'); + } finally { + await harness.close(); + } + // The scenario is void if the harness did not get each `EPERM` answer. + assert.equal(pendingDenials(), 0); +} + +/** + * Connects to a liveness port. The result resolves when the peer process is + * dead: the kernel then ends, resets, or refuses the connection. + * + * @param {number} port + * @returns {Promise} + */ +function watchLiveness(port) { + const socket = connect(port, '127.0.0.1'); + socket.on('error', () => {}); + socket.resume(); + return new Promise(resolve => { + socket.once('close', () => resolve()); + }); +} + +/** + * Starts a runner and resolves after its first report line. + * + * @param {import('node:test').TestContext} t + * @param {string} scenario + * @param {NodeJS.ProcessEnv} [env] + */ +async function startScenario(t, scenario, env = {}) { + const scratch = mkdtempSync(join(tmpdir(), 'affine-harness-scratch-')); + const infoPath = join(scratch, 'info.json'); + /** @returns {{ pgid: number, livenessPorts: number[] } | null} */ + const readInfo = () => + existsSync(infoPath) ? JSON.parse(readFileSync(infoPath, 'utf8')) : null; + const runner = spawn(process.execPath, [SELF, 'runner', scenario, infoPath], { + stdio: 'pipe', + env: { ...process.env, ...env }, + }); + /** @type {string | null} */ + let workTmp = null; + let dead = false; + // A harness defect must not leave processes or directories behind the test. + t.after(() => { + runner.kill('SIGKILL'); + const info = readInfo(); + if (info && !dead) { + try { + process.kill(-info.pgid, 'SIGKILL'); + } catch { + // Already gone. + } + } + if (workTmp) { + rmSync(workTmp, { recursive: true, force: true }); + } + rmSync(scratch, { recursive: true, force: true }); + }); + let stdout = ''; + let stderr = ''; + runner.stderr.on('data', chunk => { + stderr += String(chunk); + }); + /** @type {Promise<{ code: number | null, signal: string | null }>} */ + const exit = once(runner, 'close').then(([code, signal]) => ({ + code, + signal, + })); + /** @type {Promise>} */ + const firstReport = new Promise((resolve, reject) => { + runner.stdout.on('data', chunk => { + stdout += String(chunk); + const end = stdout.indexOf('\n'); + if (end >= 0) { + resolve(JSON.parse(stdout.slice(0, end))); + } + }); + void exit.then(() => + reject(new Error(`The runner ended before its report: ${stderr}`)) + ); + }); + const report = await firstReport; + workTmp = report.workTmp; + const info = readInfo(); + const allDead = Promise.all( + (info?.livenessPorts ?? []).map(watchLiveness) + ).then(() => { + dead = true; + }); + return { + report, + info, + exit, + allDead, + stderr: () => stderr, + /** Tells the runner to go on. */ + go: () => runner.stdin.end('go\n'), + /** @param {NodeJS.Signals} signal */ + signal: signal => runner.kill(signal), + }; +} + +/** @param {number} pgid */ +function assertGroupGone(pgid) { + assert.throws(() => process.kill(-pgid, 0), { code: 'ESRCH' }); +} + +const END_PATHS = [ + { name: 'normal end', scenario: 'close', code: 0, reaped: true }, + { name: 'failed assertion', scenario: 'throw', code: 1, reaped: true }, + { name: 'SIGINT', scenario: 'wait', code: 130, reaped: true }, + { name: 'SIGTERM', scenario: 'wait', code: 143, reaped: true }, + { + name: 'close() while the group answers EPERM until the system reaps it', + scenario: 'reaped-late-close', + code: 0, + reaped: true, + }, + // `process.exit()` cannot wait for the reap: only the deaths are checked. + { name: 'process.exit()', scenario: 'exit', code: 7, reaped: false }, +]; + +const SURVIVOR_PATHS = [ + { + name: 'close() cannot signal the group', + scenario: 'denied-close', + code: 0, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'process.exit() cannot signal the group', + scenario: 'denied-exit', + code: 7, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'close() sends SIGTERM to a group that ignores it, and cannot send SIGKILL', + scenario: 'kill-denied-close', + code: 0, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'close() finds the group still alive', + scenario: 'alive-close', + code: 0, + reason: 'is still alive', + }, +]; + +function registerTests() { + void test('long temporary path falls back to a short socket directory', async t => { + const warn = t.mock.method(console, 'warn', () => {}); + const original = process.env.TMPDIR; + try { + process.env.TMPDIR = '/tmp/' + '長'.repeat(35); + const harness = createChromiumHarness({ tmpPrefix: 'socket-check-' }); + try { + assert.ok(harness.workTmp.startsWith('/tmp/socket-check-')); + assert.equal(warn.mock.callCount(), 1); + const [message] = warn.mock.calls[0].arguments; + assert.match(message, /socket path needs \d+ bytes \(limit \d+\)/); + assert.ok(message.endsWith('Using ' + harness.workTmp)); + } finally { + await harness.close(); + } + assert.throws( + () => createChromiumHarness({ tmpPrefix: '長'.repeat(48) }), + /socket path needs \d+ bytes \(limit \d+\).*SingletonSocket/ + ); + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + } + }); + + void test('Chromium refuses arguments that override harness settings', async () => { + const harness = createChromiumHarness({ + tmpPrefix: 'affine-harness-test-', + }); + try { + for (const arg of [ + 'about:blank', + '--remote-debugging-port=9010', + '--remote-debugging-pipe', + '--user-data-dir=/tmp', + ]) { + await assert.rejects(harness.launchChromium({ args: [arg] }), { + message: 'Invalid extra Chromium argument: ' + arg, + }); + } + } finally { + await harness.close(); + } + }); + + void test('the Chromium handshake owns the profile and reaps failed launches', async t => { + const scratch = mkdtempSync(join(tmpdir(), 'affine-harness-chrome-')); + const wrapper = join(scratch, 'chrome-wrapper'); + const previous = process.env.CHROME_PATH; + try { + process.env.CHROME_PATH = wrapper; + for (const [ + name, + script, + error, + ] of /** @type {Array<[string, string, RegExp | null]>} */ ([ + [ + 'early exit with an open stderr pipe', + 'tail -f /dev/null >&2 &\necho startup-failed >&2\nexit 22', + /exited early \(22\): startup-failed/, + ], + ['handshake timeout', 'exec tail -f /dev/null', /DevTools timeout/], + [ + 'handshake timeout ignoring SIGTERM', + 'trap "" TERM\necho ignoring-term >&2\nexec tail -f /dev/null', + /DevTools timeout \(running\): ignoring-term \[\d+ms\]/, + ], + [ + 'profile in use', + 'echo "DevTools listening on ws://127.0.0.1:9001/test" >&2\nexec tail -f /dev/null', + null, + ], + ])) { + await t.test(name, async () => { + writeFileSync( + wrapper, + '#!/bin/sh\necho $$ > "$0.pid"\n' + script + '\n', + { mode: 0o755 } + ); + const harness = createChromiumHarness({ + tmpPrefix: 'affine-harness-test-', + }); + try { + const launch = harness.launchChromium({ + timeoutMs: name.startsWith('handshake timeout') ? 200 : 3000, + }); + if (error) { + await assert.rejects(launch, error); + assert.equal(existsSync(harness.workTmp), false); + assertGroupGone(Number(readFileSync(wrapper + '.pid', 'utf8'))); + } else { + assert.equal(await launch, '9001'); + await assert.rejects(harness.launchChromium(), /already in use/); + } + } finally { + await harness.close(); + } + }); + } + } finally { + if (previous === undefined) delete process.env.CHROME_PATH; + else process.env.CHROME_PATH = previous; + rmSync(scratch, { recursive: true, force: true }); + } + }); + + void test('each way to end stops the owned process group and removes the work directory', async t => { + for (const path of END_PATHS) { + await t.test(path.name, { timeout: 60000 }, async st => { + const run = await startScenario(st, path.scenario); + assert.ok(run.info); + assert.equal(existsSync(run.report.workTmp), true); + if (path.scenario === 'wait') { + run.signal(/** @type {NodeJS.Signals} */ (path.name)); + } else { + run.go(); + } + assert.deepEqual(await run.exit, { code: path.code, signal: null }); + await run.allDead; + if (path.reaped) { + assertGroupGone(run.info.pgid); + } + assert.equal(existsSync(run.report.workTmp), false); + assert.doesNotMatch(run.stderr(), /\[chromium-harness\]/); + }); + } + }); + + void test('a process group that cannot be signalled or stays alive keeps the work directory and prints its path', async t => { + for (const path of SURVIVOR_PATHS) { + await t.test(path.name, { timeout: 60000 }, async st => { + const run = await startScenario(st, path.scenario); + assert.ok(run.info); + run.go(); + assert.deepEqual(await run.exit, { code: path.code, signal: null }); + assert.equal(existsSync(run.report.workTmp), true); + assert.ok( + run + .stderr() + .includes( + `[chromium-harness] kept ${run.report.workTmp}: server process group ${run.info.pgid} ${path.reason}` + ), + run.stderr() + ); + }); + } + }); + + void test( + 'a signal during the server health check refuses that server and each later start', + { timeout: 60000 }, + async t => { + const run = await startScenario(t, 'signal-during-health'); + assert.ok(run.info); + run.go(); + assert.match( + run.report.refusals[0], + /Refused use of the server at http:\/\/127\.0\.0\.1:\d+: teardown is in progress/ + ); + assert.match( + run.report.refusals[1], + /Refused start of server: teardown is in progress/ + ); + assert.deepEqual(await run.exit, { code: 143, signal: null }); + await run.allDead; + assertGroupGone(run.info.pgid); + assert.equal(existsSync(run.report.workTmp), false); + } + ); + + void test( + 'a health request without an answer stops at the time limit, the server start fails, and close() removes the work directory', + { timeout: 60000 }, + async t => { + const run = await startScenario(t, 'health-hangs'); + assert.match(run.report.message, /did not become healthy/); + assert.deepEqual(await run.exit, { code: 0, signal: null }); + await run.allDead; + assert.equal(existsSync(run.report.workTmp), false); + assert.doesNotMatch(run.stderr(), /\[chromium-harness\]/); + } + ); + + void test('the harness uses the browser path from CHROME_PATH as given, and close() removes the work directory after a failed launch', async t => { + const scratch = mkdtempSync(join(tmpdir(), 'affine-harness-chrome-')); + t.after(() => rmSync(scratch, { recursive: true, force: true })); + // The wrapper records its start in a marker file and exits before + // DevTools is ready. + const wrapper = join(scratch, 'chrome-wrapper'); + const marker = `${wrapper}.started`; + writeFileSync(wrapper, '#!/bin/sh\n: > "$0.started"\nexit 22\n', { + mode: 0o755, + }); + const paths = [ + { + name: 'a shell wrapper starts, and CHROME_BIN does not replace it', + env: { CHROME_PATH: wrapper, CHROME_BIN: process.execPath }, + message: /Chromium exited early \(22\)/, + started: true, + }, + { + name: 'CHROME_BIN selects the browser when CHROME_PATH is empty', + env: { CHROME_PATH: '', CHROME_BIN: wrapper }, + message: /Chromium exited early \(22\)/, + started: true, + }, + { + name: 'a path that does not exist is an error, and CHROME_BIN does not replace it', + env: { CHROME_PATH: join(scratch, 'missing'), CHROME_BIN: wrapper }, + message: /CHROME_PATH or CHROME_BIN does not exist/, + started: false, + }, + ]; + for (const path of paths) { + await t.test(path.name, { timeout: 60000 }, async st => { + rmSync(marker, { force: true }); + const run = await startScenario(st, 'launch-fails', path.env); + assert.match(run.report.message, path.message); + assert.equal(existsSync(marker), path.started); + assert.deepEqual(await run.exit, { code: 0, signal: null }); + assert.equal(existsSync(run.report.workTmp), false); + }); + } + }); +} + +const [role, ...roleArgs] = process.argv.slice(2); +if (role === 'runner') { + await runRunner(roleArgs); +} else if (role === 'server') { + await runFakeServer(roleArgs); +} else if (role === 'grandchild') { + await runGrandchild(); +} else { + registerTests(); +} diff --git a/packages/frontend/hosts/web/tests/desktop-wheel-diagnostics.test.mjs b/packages/frontend/hosts/web/tests/desktop-wheel-diagnostics.test.mjs new file mode 100644 index 0000000000..a015d0f764 --- /dev/null +++ b/packages/frontend/hosts/web/tests/desktop-wheel-diagnostics.test.mjs @@ -0,0 +1,118 @@ +import assert from 'node:assert/strict'; +import { getEventListeners } from 'node:events'; +import test from 'node:test'; +import { setImmediate } from 'node:timers/promises'; + +import { failWithWheelDiagnostics } from '../scripts/verify-desktop-persistence.mjs'; + +const target = { x: 100, y: 200, iframe: 'null', hit: 'null' }; +const version = { product: 'Chrome/test' }; +const snapshot = { wheelCount: 0, lastWheel: null }; + +function setup(t) { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const schedule = t.mock.method(globalThis, 'setTimeout'); + const cancel = t.mock.method(globalThis, 'clearTimeout'); + const ws = Object.assign(new EventTarget(), { readyState: WebSocket.OPEN }); + const page = { + ws, + send: t.mock.fn(async () => version), + evaluate: t.mock.fn(async () => snapshot), + }; + const original = new Error('The wheel event did not reach the canvas'); + return { + page, + original, + fail: () => failWithWheelDiagnostics(page, original, target), + assertCleanup(timerCount) { + assert.equal(getEventListeners(ws, 'close').length, 0); + assert.equal(getEventListeners(ws, 'error').length, 0); + assert.equal(schedule.mock.callCount(), timerCount); + assert.equal(cancel.mock.callCount(), timerCount); + if (timerCount) { + assert.equal( + cancel.mock.calls[0].arguments[0], + schedule.mock.calls[0].result + ); + } + }, + }; +} + +for (const method of ['send', 'evaluate']) { + void test(`wheel diagnostics stop at the deadline when ${method} stalls`, async t => { + const { page, original, fail, assertCleanup } = setup(t); + const stalled = Promise.withResolvers(); + page[method].mock.mockImplementation(() => stalled.promise); + let failure; + const result = fail().catch(error => { + failure = error; + }); + + t.mock.timers.tick(999); + await setImmediate(); + assert.equal(failure, undefined); + t.mock.timers.tick(1); + await setImmediate(); + + assert.equal(failure, original); + await result; + assert.equal(page.ws.readyState, WebSocket.OPEN); + assertCleanup(1); + + stalled.reject(new Error('The CDP request failed after the deadline')); + await setImmediate(); + }); +} + +void test('wheel diagnostics include the browser snapshot and original cause', async t => { + const { original, page, fail, assertCleanup } = setup(t); + await assert.rejects(fail(), error => { + assert.equal(error.cause, original); + const [message, heading, json] = error.message.split('\n'); + assert.equal(message, String(original)); + assert.equal(heading, 'HTML preview wheel diagnostics'); + assert.deepEqual(JSON.parse(json), { + product: version.product, + x: target.x, + y: target.y, + ...snapshot, + }); + return true; + }); + assert.deepEqual(page.send.mock.calls[0].arguments, ['Browser.getVersion']); + assertCleanup(1); +}); + +void test('wheel diagnostics preserve the original error when the session is already closed', async t => { + const { original, page, fail, assertCleanup } = setup(t); + page.ws.readyState = WebSocket.CLOSED; + await assert.rejects(fail(), error => error === original); + assert.equal(page.send.mock.callCount(), 0); + assert.equal(page.evaluate.mock.callCount(), 0); + assertCleanup(0); +}); + +for (const event of ['close', 'error']) { + void test(`wheel diagnostics preserve the original error on socket ${event}`, async t => { + const { original, page, fail, assertCleanup } = setup(t); + const stalled = Promise.withResolvers(); + page.evaluate.mock.mockImplementation(() => stalled.promise); + const result = fail(); + page.ws.dispatchEvent(new Event(event)); + await assert.rejects(result, error => error === original); + assertCleanup(1); + + stalled.reject(new Error('The CDP request failed after disconnection')); + await setImmediate(); + }); +} + +void test('wheel diagnostics preserve the original error when a CDP request fails', async t => { + const { original, page, fail, assertCleanup } = setup(t); + page.send.mock.mockImplementation(async () => { + throw new Error('The CDP request failed'); + }); + await assert.rejects(fail(), error => error === original); + assertCleanup(1); +}); diff --git a/packages/frontend/hosts/web/tests/desktop.test.mjs b/packages/frontend/hosts/web/tests/desktop.test.mjs new file mode 100644 index 0000000000..e77c717136 --- /dev/null +++ b/packages/frontend/hosts/web/tests/desktop.test.mjs @@ -0,0 +1,1742 @@ +import assert from 'node:assert/strict'; +import { randomFillSync } from 'node:crypto'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { deflateSync } from 'node:zlib'; + +import { + clearDesktopSplit, + DESKTOP_START_LOCK, + flushDesktopOnHide, + openDesktopStore, + startDesktop, +} from '../desktop/start.js'; +import { verifyZeroThirdPartyJs } from '../scripts/verify-zero-third-party-js.mjs'; +import { + createIdbWorkspaceStorage, + openWorkspaceIdb, +} from '../src/idb-storage.js'; +import { createBroadcastBus, createMemoryIdbFactory } from './memory-idb.mjs'; + +globalThis.BroadcastChannel = createBroadcastBus(); + +const desktopHtml = new URL('../desktop/index.html', import.meta.url); +const desktopBoot = new URL('../desktop/boot.js', import.meta.url); + +void test('the desktop CSP permits the boot module, Wasm, the preview wheel bridge, and blob workers', async () => { + const html = await readFile(desktopHtml, 'utf8'); + assert.match( + html, + /script-src 'self' 'wasm-unsafe-eval' 'sha256-[\w+/]{43}=';/ + ); + assert.match(html, /worker-src 'self' blob:;/); + assert.deepEqual( + [...html.matchAll(/]*)>([\s\S]*?)<\/script>/g)].map( + ([, attributes, body]) => [attributes.trim(), body.trim()] + ), + [ + ['id="affine-desktop-manifest" type="application/json"', '{}'], + ['type="module" src="/desktop/boot.js"', ''], + ] + ); +}); + +void test('both desktop URLs load the same boot module and imports', async () => { + const html = await readFile(desktopHtml, 'utf8'); + const bootTag = html.match(/') + ); + await writeFile(join(webRoot, 'desktop/boot.js'), "import 'third-party';\n"); + const { violations } = verifyZeroThirdPartyJs({ + webRoot, + hostsRoot: webRoot, + }); + assert.ok( + violations.some(v => v.includes('desktop/index.html: inline executable')) + ); + for (const token of ["'unsafe-inline'", 'blob:', `'sha256-${wrongHash}'`]) { + assert.ok( + violations.some(v => + v.includes( + `desktop/index.html: forbidden CSP script-src token "${token}"` + ) + ) + ); + } + assert.ok( + violations.some(v => + v.includes('desktop/index.html: CSP script-src must include') + ) + ); + assert.ok( + violations.some(v => + v.includes( + 'desktop/boot.js: bare or external static import "third-party"' + ) + ) + ); +}); + +void test('desktop boot loads the configured fonts and workers before mount', async t => { + const boot = await readFile(desktopBoot, 'utf8'); + const desktopStart = JSON.stringify( + new URL('../desktop/start.js', import.meta.url).href + ); + const serif = '/assets/fonts/SourceSerif4-VariableFont_opsz,wght.ttf'; + const serifItalic = + '/assets/fonts/SourceSerif4-Italic-VariableFont_opsz,wght.ttf'; + const fallbackFonts = [ + 'Inter-VariableFont_slnt,wght.ttf', + 'IBMPlexMono-Regular.ttf', + 'IBMPlexMono-Bold.ttf', + 'IBMPlexMono-Italic.ttf', + 'IBMPlexMono-BoldItalic.ttf', + 'NotoSansArabic-Regular.ttf', + 'NotoSansHebrew-Regular.ttf', + ] + .map(name => '/assets/fonts/' + name) + .concat(serif, serifItalic); + const baseFonts = { + latin: '/latin', + mono: '/mono', + monoBold: '/mono-bold', + monoItalic: '/mono-italic', + monoBoldItalic: '/mono-bold-italic', + arabic: '/arabic', + hebrew: '/hebrew', + }; + const baseUrls = Object.values(baseFonts); + const legacyFonts = baseUrls.map(url => '/legacy' + url); + const manifestSerif = '/fonts/serif-hash.ttf'; + const manifestSerifItalic = '/fonts/serif-italic-hash.ttf'; + const workers = { + math: { script: '/math.js', wasm: '/math.wasm' }, + mermaid: { script: '/mermaid.js', wasm: '/mermaid.wasm' }, + pdf: { script: '/pdf.js', wasm: '/pdf.wasm' }, + typst: { script: '/typst.js', wasm: '/typst.wasm' }, + }; + const legacyWorkers = { mathScript: '/legacy-math.js' }; + const cases = [ + { + name: 'release manifest with both serif fonts', + manifest: { + fonts: { + ...baseFonts, + serif: manifestSerif, + serifItalic: manifestSerifItalic, + }, + workers, + }, + legacyFonts, + legacyWorkers, + expectedFonts: [...baseUrls, manifestSerif, manifestSerifItalic], + expectedWorkers: { + mathScript: '/math.js', + mathWasm: '/math.wasm', + mermaidScript: '/mermaid.js', + mermaidWasm: '/mermaid.wasm', + pdfScript: '/pdf.js', + pdfWasm: '/pdf.wasm', + typstScript: '/typst.js', + typstWasm: '/typst.wasm', + }, + }, + { + name: 'release manifest with one serif font', + manifest: { fonts: { ...baseFonts, serif: manifestSerif } }, + expectedFonts: [...baseUrls, manifestSerif], + }, + { + name: 'older release manifest without serif assets', + manifest: { fonts: baseFonts }, + expectedFonts: baseUrls, + }, + { name: 'empty manifest', manifest: {}, expectedFonts: fallbackFonts }, + { name: 'missing manifest', expectedFonts: fallbackFonts }, + { + name: 'empty manifest with legacy fonts', + manifest: {}, + legacyFonts, + expectedFonts: legacyFonts, + }, + { + name: 'incomplete fonts and empty workers use legacy overrides', + manifest: { fonts: { latin: '/partial-latin' }, workers: {} }, + legacyFonts, + legacyWorkers, + expectedFonts: legacyFonts, + expectedWorkers: legacyWorkers, + }, + { + name: 'incomplete manifest with a declared serif font and legacy fonts', + manifest: { fonts: { serifItalic: manifestSerifItalic } }, + legacyFonts, + expectedFonts: [...legacyFonts, manifestSerifItalic], + }, + { + name: 'missing required mono font', + manifest: { fonts: baseFonts }, + expectedFonts: baseUrls, + missingFont: baseFonts.mono, + }, + ]; + const moduleUrl = source => + 'data:text/javascript,' + encodeURIComponent(source); + for (const entry of cases) { + await t.test(entry.name, async t => { + const requestedFonts = []; + t.mock.method(globalThis, 'fetch', async url => { + requestedFonts.push(url); + const index = entry.expectedFonts.indexOf(url); + return index === -1 || url === entry.missingFont + ? new Response(null, { status: 404 }) + : new Response(Uint8Array.of(index)); + }); + const errors = t.mock.method(console, 'error', () => {}); + const fixtures = moduleUrl(` + // ${entry.name} + import { startDesktop as mountDesktop } from ${desktopStart}; + export { desktopFontUrls } from ${desktopStart}; + export const calls = []; + export const window = { + __AFFINE_FONT_ASSETS__: ${JSON.stringify(entry.legacyFonts)}, + __AFFINE_WORKER_ASSETS__: ${JSON.stringify(entry.legacyWorkers)}, + __playgroundPreview: { + registerFont: bytes => calls.push(['preview-font', ...bytes]), + }, + }; + export const document = { + getElementById: id => id === 'affine-desktop-manifest' + ? ${JSON.stringify(entry.manifest && { textContent: JSON.stringify(entry.manifest) }) ?? 'null'} + : null, + createElement: () => ({ setAttribute() {} }), + body: { append: notice => calls.push(['alert', notice.textContent]) }, + }; + export const location = { origin: 'https://example.org', search: '?doc=a' }; + export const matchMedia = () => ({ matches: true }); + export function installPlaygroundPreviewBridge(wasm, base) { + calls.push(['preview', wasm.name, base, window.__AFFINE_WORKER_ASSETS__]); + } + export function startDesktop(wasm, fonts, query, dark, preview) { + calls.push(['start', wasm.name, fonts, query, dark, preview]); + return mountDesktop(wasm, fonts, query, dark, preview, async () => 'store', null, {}); + } + export default function init() {} + export const register_web_desktop_font = bytes => calls.push(['font', ...bytes]); + export const web_desktop_workspace_ids = () => []; + export const wasm_desktop_main = () => calls.push(['mount']); + export function flushDesktopOnHide(wasm, store, target) { + calls.push(['flush', wasm.name, store, target === window]); + } + export const name = 'desktop-wasm'; + `); + const source = + `import { window, document, location, matchMedia } from ${JSON.stringify(fixtures)};\n` + + boot + .replace("'../preview-workers.js'", JSON.stringify(fixtures)) + .replace("'./start.js'", JSON.stringify(fixtures)) + .replace("'/pkg/affine_desktop.js'", JSON.stringify(fixtures)); + await import(moduleUrl(source)); + const { calls, window } = await import(fixtures); + assert.deepEqual(calls, [ + [ + 'preview', + 'desktop-wasm', + 'https://example.org/', + entry.expectedWorkers, + ], + [ + 'start', + 'desktop-wasm', + entry.expectedFonts, + '?doc=a', + true, + window.__playgroundPreview, + ], + ...(entry.missingFont + ? [ + [ + 'alert', + `AFFiNE Desktop could not start: Font ${entry.missingFont} returned HTTP 404`, + ], + ] + : [ + ...entry.expectedFonts.flatMap((_, index) => [ + ['font', index], + ['preview-font', index], + ]), + ['mount'], + ['flush', 'desktop-wasm', 'store', true], + ]), + ]); + assert.deepEqual(requestedFonts, entry.expectedFonts); + assert.equal(errors.mock.callCount(), entry.missingFont ? 1 : 0); + }); + } +}); + +void test('the desktop registers fonts in order, then, under the start lock, opens its store, mounts the selected theme, panes, and document, and waits until the seeded workspaces are written', async t => { + for (const [query, prefersDark, preference, split, workspace, doc] of [ + ['', false, 'system', false, undefined, undefined], + ['', true, 'system', false, undefined, undefined], + ['?theme=light&split=1', true, 'light', true, undefined, undefined], + ['?theme=dark&split=true', false, 'dark', true, undefined, undefined], + [ + '?theme=system&split=false&workspace=ws-b&doc=doc-arch', + true, + 'system', + false, + 'ws-b', + 'doc-arch', + ], + ]) { + await t.test(query + ' system dark=' + prefersDark, async t => { + const requests = []; + const calls = []; + const store = { + docIds: () => [], + get seeded() { + calls.push('seeded'); + return Promise.resolve(); + }, + }; + const locks = { + request: async (name, task) => { + calls.push(['lock', name]); + const result = await task(); + calls.push('unlock'); + return result; + }, + }; + t.mock.method(Date, 'now', () => 42); + t.mock.method(globalThis, 'fetch', async url => { + requests.push(url); + return new Response(Uint8Array.of(url.endsWith('latin') ? 1 : 2)); + }); + const wasm = { + default: async () => calls.push('init'), + register_web_desktop_font: bytes => calls.push(['font', ...bytes]), + web_desktop_workspace_ids: () => ['ws-a', 'ws-b'], + wasm_desktop_main: (...args) => { + const host = args.pop(); + assert.equal(typeof host.onSplitClosed, 'function'); + assert.equal(host.themePreference, preference); + calls.push(['mount', ...args]); + }, + }; + const preview = { + registerFont: bytes => calls.push(['preview', ...bytes]), + }; + const opened = await startDesktop( + wasm, + ['/latin', '/mono'], + query, + prefersDark, + preview, + async ids => { + calls.push(['store', ...ids]); + return store; + }, + locks + ); + assert.equal(opened, store); + assert.deepEqual(requests, ['/latin', '/mono']); + assert.deepEqual(calls, [ + 'init', + ['font', 1], + ['preview', 1], + ['font', 2], + ['preview', 2], + ['lock', DESKTOP_START_LOCK], + ['store', 'ws-a', 'ws-b'], + ['mount', prefersDark, split, workspace, doc, store, 42], + 'seeded', + 'unlock', + ]); + }); + } +}); + +void test('a desktop URL passes its decoded target, mode and ordered selection IDs to Wasm', async () => { + for (const [query, initialDocMode, blockIds, elementIds = []] of [ + ['', undefined, []], + ['&mode=page&blockIds=first%2Csecond', 'page', ['first', 'second']], + [ + '&blockIds=first,,&blockIds=second%2Cfirst&blockIds=', + undefined, + ['first', 'second'], + ], + [ + '&mode=edgeless&blockIds=note&elementIds=shape%2Cframe&elementIds=shape,,arrow', + 'edgeless', + ['note'], + ['shape', 'frame', 'arrow'], + ], + ['&mode=foo', undefined, []], + ]) { + const wasm = { + default() {}, + web_desktop_workspace_ids: () => [], + wasm_desktop_main(_dark, split, workspace, doc, _store, _now, host) { + assert.equal(split, false); + assert.equal(workspace, 'a/b &'); + assert.equal(doc, '文?#+%'); + assert.equal(host.initialDocMode, initialDocMode); + assert.deepEqual(host.initialBlockIds, blockIds); + assert.deepEqual(host.initialElementIds, elementIds); + }, + }; + await startDesktop( + wasm, + [], + `?workspace=a%2Fb%20%26&doc=%E6%96%87%3F%23%2B%25${query}`, + false, + {}, + async () => null + ); + } +}); + +void test('desktop restores saved preferences after a cold mount and forwards live system changes', async () => { + const media = new EventTarget(); + media.matches = false; + const stored = new Map(); + const changes = []; + const env = { + localStorage: { + getItem: key => stored.get(key) ?? null, + setItem: (key, value) => stored.set(key, value), + }, + matchMedia(query) { + assert.equal(query, '(prefers-color-scheme: dark)'); + return media; + }, + }; + const mount = async search => { + let mounted; + const wasm = { + default() {}, + web_desktop_workspace_ids: () => [], + wasm_desktop_main( + systemDark, + _split, + _workspace, + _doc, + _store, + _now, + host + ) { + mounted = { host, systemDark }; + }, + }; + await startDesktop( + wasm, + [], + search, + false, + {}, + async () => null, + null, + env + ); + return mounted; + }; + + const first = await mount(''); + assert.equal(first.host.defaultDocMode, 'page'); + assert.equal(first.host.themePreference, 'system'); + assert.equal(first.systemDark, false); + first.host.savePreferences(undefined, 'light'); + first.host.savePreferences('edgeless', undefined); + + media.matches = true; + const second = await mount('?theme=dark'); + assert.equal(second.host.defaultDocMode, 'edgeless'); + assert.equal(second.host.themePreference, 'light'); + assert.equal(second.systemDark, true); + second.host.watchSystemTheme(dark => changes.push(dark)); + for (const matches of [false, true]) { + const event = new Event('change'); + event.matches = matches; + media.dispatchEvent(event); + } + assert.deepEqual(changes, [false, true]); +}); + +void test('closing the final split removes only split from the desktop URL', () => { + const state = { scroll: 24 }; + const env = { + location: { + href: 'https://example.com/desktop/?workspace=ws&doc=page&theme=dark&mode=edgeless&split=1&split=true#block', + }, + history: { + state, + replaceState(received, title, url) { + assert.equal(received, state); + assert.equal(title, ''); + env.location.href = url.href; + this.calls++; + }, + calls: 0, + }, + }; + clearDesktopSplit(env); + clearDesktopSplit(env); + assert.equal(env.history.calls, 1); + assert.equal( + env.location.href, + 'https://example.com/desktop/?workspace=ws&doc=page&theme=dark&mode=edgeless#block' + ); +}); + +void test('the desktop writes queued changes when its page is hidden or unloaded', () => { + const calls = []; + const win = new EventTarget(); + win.document = new EventTarget(); + win.document.visibilityState = 'visible'; + flushDesktopOnHide( + { flush_web_desktop: () => calls.push('wasm') }, + { flush: async () => calls.push('store') }, + win + ); + win.document.dispatchEvent(new Event('visibilitychange')); + assert.deepEqual(calls, []); + win.document.visibilityState = 'hidden'; + win.document.dispatchEvent(new Event('visibilitychange')); + win.dispatchEvent(new Event('pagehide')); + win.dispatchEvent(new Event('beforeunload')); + assert.deepEqual(calls, ['wasm', 'store', 'wasm', 'store', 'wasm', 'store']); +}); + +async function openTestStore(indexedDB) { + return { store: await openDesktopStore(['ws'], { indexedDB }) }; +} + +async function storedFrames(indexedDB, docId) { + const { store } = await openTestStore(indexedDB); + return store.docFrames('ws', docId).map(bin => [...bin]); +} + +void test('desktop startup releases all initial frames after mount or mount failure and keeps writing', async t => { + for (const fails of [false, true]) { + await t.test(fails ? 'mount fails' : 'mount succeeds', async () => { + const indexedDB = createMemoryIdbFactory(); + const { store: seed } = await openTestStore(indexedDB); + seed.pushUpdate('ws', 'page', Uint8Array.of(1)); + seed.pushUpdate('ws', 'other', Uint8Array.of(2)); + await seed.flush(); + + const failure = new Error('mount failed'); + let store; + const wasm = { + default() {}, + web_desktop_workspace_ids: () => ['ws'], + wasm_desktop_main(_dark, _split, _workspace, _doc, mountedStore) { + store = mountedStore; + assert.deepEqual(store.docIds('ws').sort(), ['other', 'page']); + assert.deepEqual(store.docFrames('ws', 'page'), [Uint8Array.of(1)]); + if (fails) throw failure; + }, + }; + const startup = startDesktop(wasm, [], '', false, {}, ids => + openDesktopStore(ids, { indexedDB }) + ); + if (fails) await assert.rejects(startup, failure); + else assert.equal(await startup, store); + assert.deepEqual(store.docIds('ws'), []); + assert.deepEqual(store.docFrames('ws', 'page'), []); + assert.deepEqual(store.docFrames('ws', 'other'), []); + + store.pushUpdate('ws', 'page', Uint8Array.of(3)); + store.deleteDoc('ws', 'other'); + await store.flush(); + const { store: reopened } = await openTestStore(indexedDB); + assert.deepEqual(reopened.docIds('ws'), ['page']); + assert.deepEqual(reopened.docFrames('ws', 'page'), [ + Uint8Array.of(1), + Uint8Array.of(3), + ]); + }); + } +}); + +void test('the desktop store applies the updates and deletions of a document in call order', async () => { + for (const [name, steps, frames] of [ + [ + 'update, flush, delete, update', + ['put 10', 'flush', 'delete', 'put 20'], + [[20]], + ], + ['update, update, delete', ['put 10', 'put 20', 'delete'], []], + ['update, flush, delete', ['put 10', 'flush', 'delete'], []], + [ + 'delete, update', + ['put 10', 'flush', 'delete', 'flush', 'put 30'], + [[30]], + ], + ]) { + const idb = createMemoryIdbFactory(); + const { store } = await openTestStore(idb); + for (const step of steps) { + const [op, byte] = step.split(' '); + if (op === 'put') store.pushUpdate('ws', 'page', Uint8Array.of(+byte)); + else if (op === 'delete') store.deleteDoc('ws', 'page'); + else await store.flush(); + } + await store.flush(); + assert.deepEqual(await storedFrames(idb, 'page'), frames, name); + } +}); + +void test('a second flush resolves after the writes that an earlier flush started', async () => { + const idb = createMemoryIdbFactory(); + const { store } = await openTestStore(idb); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + let firstDone = false; + const first = store.flush().then(() => { + firstDone = true; + }); + await store.flush(); + assert.equal(firstDone, true); + assert.deepEqual(await storedFrames(idb, 'page'), [[1]]); + await first; +}); + +void test('desktop flush waits for a batch queued while the media and document transaction before it commits', async t => { + const indexedDB = createMemoryIdbFactory(); + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'ws' }, + { indexedDB } + ); + t.after(() => db.close()); + const transaction = db.transaction.bind(db); + const commits = [Promise.withResolvers(), Promise.withResolvers()]; + const scopes = []; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite') { + const gate = commits[scopes.length]; + scopes.push(stores.includes('blobData')); + const commit = tx.commit.bind(tx); + tx.commit = () => gate.resolve(commit); + } + return tx; + }); + const store = await openDesktopStore(['ws'], { + indexedDB: { + open() { + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }); + store.putBlob('ws', 'media', Uint8Array.of(9)); + store.pushUpdate('ws', 'a', Uint8Array.of(1)); + const commitA = await commits[0].promise; + store.pushUpdate('ws', 'b', Uint8Array.of(2)); + let done = false; + const flushed = store.flush().then(() => { + done = true; + }); + commitA(); + const commitB = await commits[1].promise; + await new Promise(resolve => setImmediate(resolve)); + assert.equal(done, false); + commitB(); + await flushed; + assert.deepEqual(scopes, [true, false]); + + const { store: cold } = await openTestStore(indexedDB); + assert.deepEqual(cold.docFrames('ws', 'a'), [Uint8Array.of(1)]); + assert.deepEqual(cold.docFrames('ws', 'b'), [Uint8Array.of(2)]); + assert.deepEqual(cold.blobBytes('ws', 'media'), Uint8Array.of(9)); +}); + +void test('the desktop store flush resolves after a failed transaction is written again in call order', async t => { + const errors = []; + t.mock.method(console, 'error', (...args) => errors.push(args[0])); + t.mock.method(Date, 'now', () => 1_000); + const diskFull = async (idb, store) => { + store.pushUpdate('ws', 'page', Uint8Array.of(2)); + idb.failNextWriteTransaction(new Error('disk full')); + }; + for (const [name, fail, later, page] of [ + ['the transaction failed', diskFull, [], [[2]]], + ['the transaction failed before a deletion', diskFull, ['delete'], []], + [ + 'the transaction failed before a deletion and an update', + diskFull, + ['delete', 'put 3'], + [[3]], + ], + ]) { + errors.length = 0; + const idb = createMemoryIdbFactory(); + const { store } = await openTestStore(idb); + await fail(idb, store); + const failed = store.flush(); + store.pushUpdate('ws', 'other', Uint8Array.of(7)); + for (const step of later) { + if (step === 'delete') store.deleteDoc('ws', 'page'); + else store.pushUpdate('ws', 'page', Uint8Array.of(+step.split(' ')[1])); + } + await store.flush(); + await failed; + assert.deepEqual((await storedFrames(idb, 'page')).sort(), page, name); + assert.deepEqual(await storedFrames(idb, 'other'), [[7]], name); + assert.equal(errors.length, 1, name); + } +}); + +for (const recovery of ['transient', 'flush', 'pagehide', 'new write']) { + void test(`the first desktop write failure releases the start lock before recovery by ${recovery}`, async t => { + const idb = globalThis.indexedDB ?? createMemoryIdbFactory(); + const workspace = `ws-start-${recovery}`; + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + const transient = recovery === 'transient'; + const releaseRead = Promise.withResolvers(); + const retryRead = Promise.withResolvers(); + const warnings = t.mock.method(console, 'warn', () => {}); + const errors = t.mock.method(console, 'error', () => {}); + let writes = 0; + let locked = false; + let firstFlush; + const locks = { + async request(name, mount) { + assert.equal(name, DESKTOP_START_LOCK); + locked = true; + try { + return await mount(); + } finally { + locked = false; + } + }, + }; + const wasm = { + default() {}, + web_desktop_workspace_ids: () => [workspace], + wasm_desktop_main(_dark, _split, _workspace, _doc, store) { + store.pushUpdate(workspace, 'root', Uint8Array.of(1)); + firstFlush = store.flush(); + }, + }; + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: workspace }, + { indexedDB: idb } + ); + t.after(() => db.close()); + const transaction = db.transaction.bind(db); + t.mock.method(db, 'transaction', (stores, mode) => { + if (mode === 'readwrite' && ++writes === 1 && transient) { + throw new DOMException('Write failed', 'AbortError'); + } + const tx = transaction(stores, mode); + if (mode === 'readwrite' && writes === 1) { + tx.commit = () => { + Object.defineProperty(tx, 'error', { value: quota, writable: true }); + tx.abort(quota); + }; + } + if (mode === 'readonly' && writes === 1 && transient) { + Object.defineProperty(tx, 'oncomplete', { + set(complete) { + Object.defineProperty(tx, 'oncomplete', { + value: async event => { + retryRead.resolve(); + await releaseRead.promise; + complete(event); + }, + }); + }, + }); + } + return tx; + }); + const openStore = ids => + openDesktopStore(ids, { + indexedDB: { + open() { + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }); + const store = await startDesktop(wasm, [], '', false, {}, openStore, locks); + assert.equal(locked, false); + assert.equal(writes, 1); + if (transient) { + await retryRead.promise; + releaseRead.resolve(); + await firstFlush; + assert.equal(errors.mock.callCount(), 1); + } else { + await assert.rejects(firstFlush, quota); + assert.equal(warnings.mock.callCount(), 1); + assert.equal(errors.mock.callCount(), 0); + if (recovery === 'pagehide') { + const win = new EventTarget(); + win.document = new EventTarget(); + flushDesktopOnHide({ flush_web_desktop() {} }, store, win); + win.dispatchEvent(new Event('pagehide')); + assert.equal( + writes, + 2, + 'pagehide starts the transaction synchronously' + ); + } else if (recovery === 'new write') { + store.pushUpdate(workspace, 'root', Uint8Array.of(2)); + } + await store.flush(); + } + assert.equal(writes, 2); + const cold = await openDesktopStore([workspace], { indexedDB: idb }); + assert.deepEqual( + cold.docFrames(workspace, 'root').map(bin => [...bin]), + recovery === 'new write' ? [[1], [2]] : [[1]] + ); + }); +} + +void test('the desktop store is seeded once a write to each workspace that it held no document of commits', async () => { + const idb = createMemoryIdbFactory(); + const state = async store => { + let done = false; + void store.seeded.then(() => { + done = true; + }); + await new Promise(resolve => setImmediate(resolve)); + return done; + }; + const empty = await openDesktopStore(['ws', 'other'], { indexedDB: idb }); + assert.equal(await state(empty), false, 'nothing written'); + empty.pushUpdate('ws', 'page', Uint8Array.of(1)); + await empty.flush(); + assert.equal(await state(empty), false, 'one of two workspaces written'); + empty.pushUpdate('other', 'page', Uint8Array.of(2)); + await empty.flush(); + assert.equal(await state(empty), true, 'both workspaces written'); + + const stored = await openDesktopStore(['ws', 'other'], { indexedDB: idb }); + assert.equal(await state(stored), true, 'the store holds both workspaces'); + + const failed = await openDesktopStore(['new'], { indexedDB: idb }); + failed.reportError('the stored documents do not decode'); + assert.equal(await state(failed), true, 'the desktop runs in memory only'); +}); + +const mediaPng = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAcnRFWHRDb21tZW50AHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHibF5f4AAAADUlEQVR4nGOQnHbnPwAE4gKL26X5MQAAAABJRU5ErkJggg==', + 'base64' + ) +); + +const turn = () => new Promise(resolve => setImmediate(resolve)); + +/** Opens `ids` with the database of `quotaId` limited to `limit()` bytes of media and frames per transaction. */ +async function openQuotaLimitedDesktop(t, indexedDB, ids, quotaId, limit) { + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: quotaId }, + { indexedDB } + ); + t.after(() => db.close()); + const transaction = db.transaction.bind(db); + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + /** Store scope of each `readwrite` transaction of `quotaId`. */ + const writes = []; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode !== 'readwrite') return tx; + writes.push([...stores].sort().join(',')); + let bytes = 0; + const objectStore = tx.objectStore.bind(tx); + tx.objectStore = name => { + const store = objectStore(name); + for (const method of ['add', 'put']) { + const write = store[method].bind(store); + store[method] = record => { + bytes += (record.data ?? record.bin)?.byteLength ?? 0; + return write(record); + }; + } + return store; + }; + const commit = tx.commit.bind(tx); + tx.commit = () => { + if (bytes <= limit()) return commit(); + Object.defineProperty(tx, 'error', { value: quota, writable: true }); + tx.abort(quota); + }; + return tx; + }); + const store = await openDesktopStore(ids, { + indexedDB: { + open(name, version) { + if (!name.endsWith(`:${quotaId}`)) return indexedDB.open(name, version); + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }); + return { store, quota, writes }; +} + +const MEDIA_SCOPE = 'blobData,blobs,clocks,snapshots,updates'; + +for (const recovery of ['deleteDoc', 'retryBlobWrites', 'flush', 'pagehide']) { + void test(`a quota-blocked desktop workspace keeps 16 updates and its media without new transactions, other workspaces keep saving, and ${recovery} writes all of them in one transaction`, async t => { + const warnings = t.mock.method(console, 'warn', () => {}); + const errors = t.mock.method(console, 'error', () => {}); + const indexedDB = createMemoryIdbFactory(); + const ids = ['ws', 'ws2']; + let limit = 1024 * 1024; + const { store, quota, writes } = await openQuotaLimitedDesktop( + t, + indexedDB, + ids, + 'ws', + () => limit + ); + store.pushUpdate('ws', 'old', Uint8Array.of(0)); + await store.flush(); + + const image = randomFillSync(new Uint8Array(8 * 1024 * 1024)); + const icon = randomFillSync(new Uint8Array(4096)); + store.putBlob('ws', 'image', image); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + await assert.rejects(store.flush(), quota); + assert.deepEqual(writes, ['clocks,snapshots,updates', MEDIA_SCOPE]); + + for (let byte = 2; byte <= 17; byte++) { + store.pushUpdate('ws', 'page', Uint8Array.of(byte)); + if (byte === 9) store.putBlob('ws', 'icon', icon); + await turn(); + } + store.pushUpdate('ws2', 'page', Uint8Array.of(9)); + await turn(); + assert.equal( + writes.length, + 2, + 'the paused workspace starts no transaction' + ); + const paused = await openDesktopStore(ids, { indexedDB }); + assert.deepEqual(paused.docFrames('ws2', 'page'), [Uint8Array.of(9)]); + assert.deepEqual(paused.docIds('ws'), ['old']); + assert.deepEqual(paused.blobIds('ws'), []); + + limit = Infinity; + if (recovery === 'deleteDoc') { + store.deleteDoc('ws', 'old'); + for (let tick = 0; tick < 4; tick++) await turn(); + } else if (recovery === 'retryBlobWrites') { + store.retryBlobWrites(); + for (let tick = 0; tick < 4; tick++) await turn(); + } else if (recovery === 'flush') { + await store.flush(); + } else { + const win = new EventTarget(); + win.document = new EventTarget(); + flushDesktopOnHide({ flush_web_desktop() {} }, store, win); + win.dispatchEvent(new Event('pagehide')); + assert.equal(writes.length, 3, 'pagehide starts the transaction at once'); + await store.flush(); + } + assert.deepEqual(writes.slice(2), [MEDIA_SCOPE]); + assert.equal(warnings.mock.callCount(), 1); + assert.equal(errors.mock.callCount(), 0); + + const cold = await openDesktopStore(ids, { indexedDB }); + assert.deepEqual( + cold.docFrames('ws', 'page'), + Array.from({ length: 17 }, (_, i) => Uint8Array.of(i + 1)) + ); + assert.deepEqual( + cold.docIds('ws').sort(), + recovery === 'deleteDoc' ? ['page'] : ['old', 'page'] + ); + assert.deepEqual(cold.blobBytes('ws', 'image'), image); + assert.deepEqual(cold.blobBytes('ws', 'icon'), icon); + assert.deepEqual(cold.docFrames('ws2', 'page'), [Uint8Array.of(9)]); + }); +} + +void test('a quota-blocked desktop workspace keeps only the newest bytes of a replaced image, so a flush under the same 1 MiB quota writes the image and all 9 updates', async t => { + t.mock.method(console, 'warn', () => {}); + const indexedDB = createMemoryIdbFactory(); + const { store, quota, writes } = await openQuotaLimitedDesktop( + t, + indexedDB, + ['ws'], + 'ws', + () => 1024 * 1024 + ); + store.putBlob('ws', 'k', new Uint8Array(8 * 1024 * 1024)); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + await assert.rejects(store.flush(), quota); + for (let byte = 2; byte <= 9; byte++) { + store.putBlob( + 'ws', + 'k', + byte === 9 ? Uint8Array.of(7) : new Uint8Array(1024 * 1024) + ); + store.pushUpdate('ws', 'page', Uint8Array.of(byte)); + await turn(); + } + assert.equal(writes.length, 1); + await store.flush(); + assert.deepEqual(writes, [MEDIA_SCOPE, MEDIA_SCOPE]); + + const cold = await openDesktopStore(['ws'], { indexedDB }); + assert.deepEqual(cold.blobBytes('ws', 'k'), Uint8Array.of(7)); + assert.deepEqual( + cold.docFrames('ws', 'page'), + Array.from({ length: 9 }, (_, i) => Uint8Array.of(i + 1)) + ); +}); + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +/** A valid RGB PNG of random pixels, which no codec can make smaller. */ +function incompressiblePng(side) { + const chunk = (type, data) => { + const body = Buffer.concat([Buffer.from(type, 'latin1'), data]); + let crc = 0xffffffff; + for (const byte of body) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); + const out = Buffer.alloc(body.length + 8); + out.writeUInt32BE(data.length, 0); + body.copy(out, 4); + out.writeUInt32BE((crc ^ 0xffffffff) >>> 0, body.length + 4); + return out; + }; + const header = Buffer.alloc(13); + header.writeUInt32BE(side, 0); + header.writeUInt32BE(side, 4); + header.set([8, 2, 0, 0, 0], 8); + const rows = randomFillSync(Buffer.alloc(side * (side * 3 + 1))); + for (let y = 0; y < side; y++) rows[y * (side * 3 + 1)] = 0; + return new Uint8Array( + Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', header), + chunk('IDAT', deflateSync(rows)), + chunk('IEND', Buffer.alloc(0)), + ]) + ); +} + +for (const outcome of ['commits', 'exceeds the quota']) { + void test(`six documents with incompressible PNG media restore all or none of their media and frames when their one transaction ${outcome}`, async t => { + t.mock.method(console, 'warn', () => {}); + const indexedDB = createMemoryIdbFactory(); + const full = outcome !== 'commits'; + const { store, quota, writes } = await openQuotaLimitedDesktop( + t, + indexedDB, + ['ws'], + 'ws', + () => (full ? 0 : Infinity) + ); + const docs = Array.from({ length: 6 }, (_, i) => ({ + docId: `page-${i}`, + blobId: `image-${i}`, + png: incompressiblePng(203), + })); + for (const { docId, blobId, png } of docs) { + assert.ok(png.byteLength >= 123_218, `${png.byteLength} bytes`); + assert.ok(deflateSync(png).byteLength >= png.byteLength); + store.putBlob('ws', blobId, png); + store.pushUpdate('ws', docId, Uint8Array.of(1)); + } + if (full) await assert.rejects(store.flush(), quota); + else await store.flush(); + assert.deepEqual(writes, [MEDIA_SCOPE]); + + const cold = await openDesktopStore(['ws'], { indexedDB }); + const restored = docs.filter( + ({ docId, blobId, png }) => + cold.docFrames('ws', docId).length === 1 && + Buffer.from(png).equals(cold.blobBytes('ws', blobId) ?? Buffer.alloc(0)) + ); + t.diagnostic( + `Restored ${restored.length}/6 documents with ${docs[0].png.byteLength} B PNG media` + ); + assert.equal(restored.length, full ? 0 : 6); + assert.equal(cold.blobIds('ws').length, full ? 0 : 6); + }); +} + +void test('a cold desktop store reads the media of each workspace with documents in one transaction, skips the media of an empty workspace, and releases it', async t => { + const indexedDB = createMemoryIdbFactory(); + const ids = ['full', 'empty']; + const seed = await openDesktopStore(ids, { indexedDB }); + seed.putBlob('full', 'a', Uint8Array.of(1)); + seed.putBlob('full', 'b', Uint8Array.of(2)); + seed.pushUpdate('full', 'page', Uint8Array.of(3)); + seed.putBlob('empty', 'orphan', Uint8Array.of(4)); + seed.pushUpdate('empty', 'page', Uint8Array.of(5)); + seed.deleteDoc('empty', 'page'); + await seed.flush(); + + const reads = new Map(); + const dbs = new Map(); + for (const id of ids) { + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id }, + { indexedDB } + ); + t.after(() => db.close()); + const transaction = db.transaction.bind(db); + reads.set(id, 0); + t.mock.method(db, 'transaction', (stores, mode) => { + if ([stores].flat().includes('blobs')) reads.set(id, reads.get(id) + 1); + return transaction(stores, mode); + }); + dbs.set(`local:workspace:${id}`, db); + } + const cold = await openDesktopStore(ids, { + indexedDB: { + open(name) { + const req = { result: dbs.get(name) }; + assert.ok(req.result, name); + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }); + assert.deepEqual(Object.fromEntries(reads), { full: 1, empty: 0 }); + assert.deepEqual(cold.blobIds('full'), ['a', 'b']); + assert.deepEqual(cold.blobBytes('full', 'b'), Uint8Array.of(2)); + assert.deepEqual(cold.blobIds('empty'), []); + + cold.releaseInitialFrames(); + assert.deepEqual(cold.blobIds('full'), []); + assert.equal(cold.blobBytes('full', 'a'), undefined); + assert.deepEqual(cold.docIds('full'), []); +}); + +void test('desktop commits each workspace blob with its document in one transaction and restores the latest bytes at cold mount', async t => { + const indexedDB = createMemoryIdbFactory(); + const ids = ['ws-a', 'ws-b', 'ws-empty']; + const openStore = workspaceIds => + openDesktopStore(workspaceIds, { indexedDB }); + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'ws-a' }, + { indexedDB } + ); + const errors = t.mock.method(console, 'error', () => {}); + const warnings = t.mock.method(console, 'warn', () => {}); + const transaction = db.transaction.bind(db); + const failure = new DOMException('Storage is full', 'QuotaExceededError'); + const env = { + indexedDB: { + open(name, version) { + if (!name.endsWith(':ws-a')) return indexedDB.open(name, version); + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }; + let fail = true; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (fail && mode === 'readwrite' && stores.includes('blobData')) { + fail = false; + tx.commit = () => tx.abort(failure); + } + return tx; + }); + const store = await openDesktopStore(ids, env); + const source = 'same-source'; + const otherBytes = Uint8Array.of(7, 8); + assert.equal(mediaPng.length, 196); + + store.putBlob('ws-a', source, mediaPng); + store.pushUpdate('ws-a', 'page', Uint8Array.of(1)); + store.putBlob('ws-b', source, otherBytes); + store.pushUpdate('ws-b', 'page', Uint8Array.of(2)); + await assert.rejects(store.flush(), failure); + const beforeRetry = await openStore(ids); + assert.deepEqual(beforeRetry.blobIds('ws-a'), []); + assert.deepEqual(beforeRetry.docIds('ws-a'), []); + + const win = new EventTarget(); + win.document = new EventTarget(); + flushDesktopOnHide({ flush_web_desktop() {} }, store, win); + win.dispatchEvent(new Event('pagehide')); + await store.flush(); + assert.equal(errors.mock.callCount(), 0); + assert.equal(warnings.mock.callCount(), 1); + + for (const [id, bytes] of [ + ['ws-a', mediaPng], + ['ws-b', otherBytes], + ]) { + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id, + indexedDB, + }); + try { + assert.deepEqual((await storage.getBlob(source))?.data, bytes); + } finally { + storage.close(); + } + } + + const changed = mediaPng.slice(0, 12); + store.putBlob('ws-a', source, changed); + const writing = store.flush(); + store.putBlob('ws-a', source, mediaPng); + await writing; + + let mountedStore; + const wasm = { + default() {}, + web_desktop_workspace_ids: () => ids, + wasm_desktop_main(_dark, _split, workspace, doc, cold) { + mountedStore = cold; + assert.equal(workspace, 'ws-a'); + assert.equal(doc, 'page'); + assert.deepEqual(cold.docFrames('ws-a', 'page'), [Uint8Array.of(1)]); + assert.deepEqual(cold.blobIds('ws-a'), [source]); + assert.deepEqual(cold.blobBytes('ws-a', source), mediaPng); + assert.deepEqual(cold.blobBytes('ws-b', source), otherBytes); + assert.deepEqual(cold.blobIds('ws-empty'), []); + cold.pushUpdate('ws-empty', 'root', Uint8Array.of(3)); + }, + }; + assert.equal( + await startDesktop( + wasm, + [], + '?workspace=ws-a&doc=page', + false, + {}, + openStore + ), + mountedStore + ); + assert.deepEqual(mountedStore.blobIds('ws-a'), []); +}); + +void test('a failed IDB blob request leaves no committed data and can be retried', async () => { + const indexedDB = createMemoryIdbFactory(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws', + indexedDB, + }); + const failure = new Error('blob request failed'); + const blob = { key: 'image', mime: 'image/png', data: mediaPng }; + try { + await storage.open(); + indexedDB.failNextWriteTransaction(failure); + await assert.rejects(storage.setBlob(blob), failure); + assert.equal(await storage.getBlob(blob.key), null); + await storage.setBlob(blob); + assert.deepEqual((await storage.getBlob(blob.key))?.data, mediaPng); + } finally { + storage.close(); + } +}); + +void test('desktop keeps cold URL targets only for the matching route selected by Wasm', async () => { + const indexedDB = createMemoryIdbFactory(); + const initial = await openDesktopStore(['ws'], { indexedDB }); + initial.pushUpdate('ws', 'trashed-page', Uint8Array.of(1)); + await initial.flush(); + + for (const doc of ['trashed-page', 'visible-page', undefined]) { + const location = { + href: 'https://example.com/desktop/?theme=dark&workspace=ws&doc=trashed-page&mode=page&blockIds=first%2Csecond&blockIds=third&elementIds=shape', + }; + const history = { + state: { keep: true }, + replaceState(state, _title, url) { + assert.equal(state, this.state); + location.href = url.href; + }, + }; + const wasm = { + default() {}, + web_desktop_workspace_ids: () => ['ws'], + wasm_desktop_main(_dark, _split, workspace, requested, cold) { + assert.equal(requested, 'trashed-page'); + assert.deepEqual(cold.docFrames(workspace, requested), [ + Uint8Array.of(1), + ]); + cold.setRoute(workspace, doc); + }, + }; + await startDesktop( + wasm, + [], + new URL(location.href).search, + false, + {}, + ids => openDesktopStore(ids, { indexedDB, location, history }) + ); + assert.equal(new URL(location.href).searchParams.get('theme'), 'dark'); + const params = new URL(location.href).searchParams; + assert.equal(params.get('doc'), doc ?? null); + assert.equal(params.get('mode'), doc === 'trashed-page' ? 'page' : null); + assert.deepEqual( + params.getAll('blockIds'), + doc === 'trashed-page' ? ['first,second', 'third'] : [] + ); + assert.equal( + params.get('elementIds'), + doc === 'trashed-page' ? 'shape' : null + ); + } +}); + +void test('desktop group URLs round-trip with one target and drop document selections', async () => { + const indexedDB = createMemoryIdbFactory(); + const ids = ['ws']; + const initial = await openDesktopStore(ids, { indexedDB }); + initial.pushUpdate('ws', 'page', Uint8Array.of(1)); + await initial.flush(); + + for (const [key, id] of [ + ['tag', 'tag / 文'], + ['collection', 'collection ?#&'], + ]) { + const location = { + href: 'https://example.com/desktop/?workspace=ws&doc=page&mode=edgeless&blockIds=note&elementIds=shape&theme=dark', + }; + const history = { + replaceState(_state, _title, url) { + location.href = url.href; + }, + }; + const openStore = () => + openDesktopStore(ids, { indexedDB, location, history }); + const store = await openStore(); + const setGroup = store => + store.setRoute( + 'ws', + undefined, + key === 'tag' ? id : undefined, + key === 'collection' ? id : undefined + ); + + setGroup(store); + const expected = new URLSearchParams({ + workspace: 'ws', + theme: 'dark', + [key]: id, + }); + assert.deepEqual([...new URL(location.href).searchParams], [...expected]); + const wasm = { + default() {}, + web_desktop_workspace_ids: () => ids, + wasm_desktop_main(_dark, _split, workspace, doc, cold, _now, host) { + assert.equal(workspace, 'ws'); + assert.equal(doc, undefined); + assert.equal(host.initialTagId, key === 'tag' ? id : undefined); + assert.equal( + host.initialCollectionId, + key === 'collection' ? id : undefined + ); + assert.equal(host.initialDocMode, undefined); + assert.deepEqual(host.initialBlockIds, []); + assert.deepEqual(host.initialElementIds, []); + setGroup(cold); + }, + }; + await startDesktop( + wasm, + [], + new URL(location.href).search, + false, + {}, + openStore + ); + assert.deepEqual([...new URL(location.href).searchParams], [...expected]); + store.setRoute('ws', 'next-page'); + assert.deepEqual( + [...new URL(location.href).searchParams], + [ + ['workspace', 'ws'], + ['theme', 'dark'], + ['doc', 'next-page'], + ] + ); + store.setRoute('ws'); + assert.deepEqual( + [...new URL(location.href).searchParams], + [ + ['workspace', 'ws'], + ['theme', 'dark'], + ] + ); + } +}); + +void test('openDesktopStore rejects unregistered workspaces while lazily opening registered workspaces with env', async t => { + const indexedDB = createMemoryIdbFactory(); + const storageMap = new Map(); + const openedNames = []; + const trackedIdb = { + open(name, version) { + openedNames.push(name); + return indexedDB.open(name, version); + }, + }; + const errors = []; + t.mock.method(console, 'error', (_msg, err) => { + errors.push(err?.message ?? String(_msg)); + }); + const env = { + indexedDB: trackedIdb, + BroadcastChannel: createBroadcastBus(), + localStorage: { + getItem: key => storageMap.get(key) ?? null, + setItem: (key, value) => storageMap.set(key, value), + }, + }; + const store = await openDesktopStore(['ws-initial'], env); + + store.pushUpdate('ws-unregistered', 'doc-1', Uint8Array.of(9)); + await store.flush(); + await store.seeded; + assert.ok( + errors.some(msg => + msg.includes('Unknown desktop workspace ws-unregistered') + ) + ); + assert.ok(!openedNames.includes('local:workspace:ws-unregistered')); + + storageMap.set( + 'affine.desktop.workspaceRegistry', + JSON.stringify([{ id: 'ws-registry', name: 'Registry', cloud: false }]) + ); + store.pushUpdate('ws-registry', 'root', Uint8Array.of(1, 2)); + store.registerWorkspace('ws-explicit'); + store.pushUpdate('ws-explicit', 'root', Uint8Array.of(3, 4)); + await store.flush(); + + const cold = await openDesktopStore( + ['ws-initial', 'ws-registry', 'ws-explicit'], + { indexedDB } + ); + assert.deepEqual(cold.docFrames('ws-registry', 'root'), [ + Uint8Array.of(1, 2), + ]); + assert.deepEqual(cold.docFrames('ws-explicit', 'root'), [ + Uint8Array.of(3, 4), + ]); +}); + +for (const recreate of [false, true]) { + void test( + recreate + ? 'desktop uses a new slot when the same workspace opens after deletion' + : 'desktop closes a late open from a deleted workspace without writing', + async t => { + const beforeDelete = createMemoryIdbFactory(); + const afterDelete = createMemoryIdbFactory(); + const releaseOpen = Promise.withResolvers(); + const releaseDelete = Promise.withResolvers(); + const requests = []; + const closed = []; + let current = beforeDelete; + const indexedDB = { + open(name, version) { + requests.push('open'); + const backend = current; + const req = { result: null, onsuccess: null, onupgradeneeded: null }; + const issue = () => { + const opened = backend.open(name, version); + opened.onupgradeneeded = event => req.onupgradeneeded(event); + opened.onsuccess = () => { + req.result = opened.result; + if (backend === beforeDelete) { + t.mock.method(req.result, 'close', () => closed.push(name)); + void releaseOpen.promise.then(() => req.onsuccess()); + } else { + req.onsuccess(); + } + }; + }; + if (backend === beforeDelete) issue(); + else void releaseDelete.promise.then(issue); + return req; + }, + deleteDatabase() { + requests.push('delete'); + current = afterDelete; + }, + }; + const errors = t.mock.method(console, 'error', () => {}); + const store = await openDesktopStore([], { indexedDB }); + store.registerWorkspace('ws'); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + store.putBlob('ws', 'old', Uint8Array.of(2)); + const deleted = store.flush(); + store.deleteWorkspace('ws'); + + if (recreate) { + store.registerWorkspace('ws'); + store.pushUpdate('ws', 'page', Uint8Array.of(3)); + store.putBlob('ws', 'new', Uint8Array.of(4)); + } else { + await deleted; + } + releaseOpen.resolve(); + await turn(); + assert.deepEqual(closed, ['local:workspace:ws']); + + // Deliver the replacement only after the old open settles and closes. + if (recreate) store.pushUpdate('ws', 'page', Uint8Array.of(5)); + const flushed = store.flush(); + assert.deepEqual( + requests, + recreate ? ['open', 'delete', 'open'] : ['open', 'delete'] + ); + releaseDelete.resolve(); + await Promise.all([deleted, flushed]); + assert.equal(errors.mock.callCount(), 0); + + const old = await openDesktopStore(['ws'], { indexedDB: beforeDelete }); + assert.deepEqual(old.docIds('ws'), []); + assert.deepEqual(old.blobIds('ws'), []); + if (recreate) { + const cold = await openDesktopStore(['ws'], { indexedDB: afterDelete }); + assert.deepEqual(cold.docFrames('ws', 'page'), [ + Uint8Array.of(3), + Uint8Array.of(5), + ]); + assert.deepEqual(cold.blobIds('ws'), ['new']); + assert.deepEqual(cold.blobBytes('ws', 'new'), Uint8Array.of(4)); + } + } + ); +} + +void test('desktop saves only the new workspace after a blocked upgrade and same-ID deletion', async () => { + const oldDatabase = createMemoryIdbFactory(); + const newDatabase = createMemoryIdbFactory(); + const name = 'local:workspace:ws'; + const v2 = oldDatabase.open(name, 2); + const v2Connection = await new Promise(resolve => { + v2.onsuccess = () => resolve(v2.result); + }); + const deleted = Promise.withResolvers(); + const events = []; + let upgrade; + const indexedDB = { + open(name, version) { + if (!upgrade) { + upgrade = {}; + return upgrade; + } + const request = {}; + void deleted.promise.then(() => { + events.push('new open'); + const opened = newDatabase.open(name, version); + opened.onupgradeneeded = request.onupgradeneeded; + opened.onsuccess = () => { + request.result = opened.result; + request.onsuccess(); + }; + }); + return request; + }, + deleteDatabase(dbName) { + assert.equal(dbName, name); + events.push('delete requested'); + }, + }; + + const store = await openDesktopStore([], { indexedDB }); + store.registerWorkspace('ws'); + store.pushUpdate('ws', 'old-page', Uint8Array.of(1)); + const oldFlush = store.flush(); + upgrade.onblocked(); + store.deleteWorkspace('ws'); + store.registerWorkspace('ws'); + store.pushUpdate('ws', 'new-page', Uint8Array.of(2)); + const newFlush = store.flush(); + assert.deepEqual(events, ['delete requested']); + + v2Connection.close(); + const upgraded = oldDatabase.open(name, 3); + upgraded.onupgradeneeded = upgrade.onupgradeneeded; + await new Promise(resolve => { + upgraded.onsuccess = () => { + events.push('old open succeeds'); + upgrade.result = upgraded.result; + upgrade.result.close = () => { + events.push('delete completes'); + deleted.resolve(); + }; + upgrade.onsuccess(); + resolve(); + }; + }); + assert.deepEqual(events.slice(0, 3), [ + 'delete requested', + 'old open succeeds', + 'delete completes', + ]); + await Promise.all([oldFlush, newFlush]); + assert.equal(events.at(-1), 'new open'); + const cold = await openDesktopStore(['ws'], { indexedDB }); + assert.deepEqual(cold.docIds('ws'), ['new-page']); + assert.deepEqual(cold.docFrames('ws', 'new-page'), [Uint8Array.of(2)]); +}); + +void test('desktop cancels writes to a deleted open workspace while preserving writes and errors in other workspaces', async t => { + const indexedDB = createMemoryIdbFactory(); + const errors = t.mock.method(console, 'error', () => {}); + t.mock.method(console, 'warn', () => {}); + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'deleted' }, + { indexedDB } + ); + const closed = t.mock.method(db, 'close'); + const transaction = db.transaction.bind(db); + let commit; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite') { + commit = tx.commit.bind(tx); + tx.commit = () => {}; + } + return tx; + }); + const store = await openDesktopStore(['deleted', 'kept'], { + indexedDB: { + open(name, version) { + if (!name.endsWith(':deleted')) return indexedDB.open(name, version); + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }); + store.pushUpdate('deleted', 'in-flight', Uint8Array.of(1)); + store.pushUpdate('kept', 'page', Uint8Array.of(2)); + const flushed = store.flush(); + assert.equal(typeof commit, 'function'); + store.pushUpdate('deleted', 'queued', Uint8Array.of(3)); + store.deleteWorkspace('deleted'); + assert.equal(closed.mock.callCount(), 1); + await flushed; + assert.equal(errors.mock.callCount(), 0); + commit(); + + const cold = await openDesktopStore(['kept'], { indexedDB }); + assert.deepEqual(cold.docFrames('kept', 'page'), [Uint8Array.of(2)]); + + const failure = new DOMException('Storage is full', 'QuotaExceededError'); + indexedDB.failNextWriteTransaction(failure); + store.pushUpdate('kept', 'page', Uint8Array.of(4)); + await assert.rejects(store.flush(), error => error === failure); +}); + +void test('desktop propagates an open error for a current workspace and can reopen it', async t => { + const indexedDB = createMemoryIdbFactory(); + const failure = new Error('Cannot open workspace'); + const errors = t.mock.method(console, 'error', () => {}); + let first = true; + const store = await openDesktopStore([], { + indexedDB: { + open(name, version) { + if (!first) return indexedDB.open(name, version); + first = false; + const req = { error: failure }; + queueMicrotask(() => req.onerror()); + return req; + }, + }, + }); + store.registerWorkspace('ws'); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + await assert.rejects(store.flush(), error => error === failure); + assert.equal(errors.mock.callCount(), 1); + + store.pushUpdate('ws', 'page', Uint8Array.of(2)); + await store.flush(); + const cold = await openDesktopStore(['ws'], { indexedDB }); + assert.deepEqual(cold.docFrames('ws', 'page'), [Uint8Array.of(2)]); +}); + +void test('desktop releases the start lock when the last workspace awaiting a seed is deleted', async () => { + const indexedDB = createMemoryIdbFactory(); + const mounted = Promise.withResolvers(); + let released = false; + const started = startDesktop( + { + default: async () => {}, + web_desktop_workspace_ids: () => ['kept', 'deleted'], + wasm_desktop_main: (_dark, _split, _workspace, _doc, store) => + mounted.resolve(store), + }, + [], + '', + false, + {}, + openDesktopStore, + { + async request(name, mount) { + assert.equal(name, DESKTOP_START_LOCK); + const store = await mount(); + released = true; + return store; + }, + }, + { indexedDB } + ); + const store = await mounted.promise; + store.pushUpdate('kept', 'page', Uint8Array.of(1)); + await store.flush(); + assert.equal(released, false); + + store.deleteWorkspace('deleted'); + await turn(); + assert.equal(released, true); + assert.equal(await started, store); +}); diff --git a/packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs b/packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs new file mode 100644 index 0000000000..0fb9917f14 --- /dev/null +++ b/packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs @@ -0,0 +1,201 @@ +// Run with node --test after installing repository dependencies and Chromium. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import test from 'node:test'; + +import { + closeBrowserResources, + createChromiumHarness, + openPageTarget, +} from '../scripts/chromium-harness.mjs'; +import { writeDefaultLegacyShell } from '../scripts/stage-canary-dual-shell.mjs'; +import { + assertSaveClocks, + connectCdpTarget, + gateSaveConnections, + readSavedWorkspace, + waitForCondition, +} from '../scripts/verify-canary-dual-shell-e2e.mjs'; + +await test('synthetic legacy saves use real IndexedDB and Yjs', async t => { + let harness; + let server; + let tab; + try { + harness = createChromiumHarness({ tmpPrefix: 'affine-save-' }); + const dir = join(harness.workTmp, 'mobile-legacy'); + writeDefaultLegacyShell(dir, 'test', null); + const assets = new Map([ + ['index.html', 'text/html'], + ['app.js', 'text/javascript'], + ['yjs.mjs', 'text/javascript'], + ['idb-storage.js', 'text/javascript'], + ]); + server = createServer((req, res) => { + const file = new URL(req.url, 'http://localhost').pathname + .split('/') + .at(-1); + if (!assets.has(file)) { + res.writeHead(404).end(); + return; + } + res.writeHead(200, { 'Content-Type': assets.get(file) }); + res.end(readFileSync(join(dir, file))); + }); + await new Promise((ok, fail) => { + server.once('error', fail); + server.listen(0, '127.0.0.1', ok); + }); + const port = await harness.launchChromium({ args: ['--disable-gpu'] }); + const target = await openPageTarget(port); + tab = await connectCdpTarget(target.webSocketDebuggerUrl); + await tab.send('Page.navigate', { + url: `http://127.0.0.1:${server.address().port}/mobile-legacy/index.html`, + }); + await waitForCondition(tab.evalJs, 'window.__AFFINE_LEGACY_SHELL__?.ready'); + const saved = id => + tab.evalJs(`(${readSavedWorkspace})(${JSON.stringify(id)})`); + const append = (wsId, id, text) => + tab.evalJs( + `window.__AFFINE_LEGACY_SHELL__.appendParagraphEdit(...${JSON.stringify(['local:workspace:' + wsId, id, text])})` + ); + const paragraphs = (wsId, id) => + tab.evalJs( + `window.__AFFINE_LEGACY_SHELL__.recoveredDocs.find(d => + d.dbName === ${JSON.stringify('local:workspace:' + wsId)} && + d.docId === ${JSON.stringify(id)})?.paragraphs` + ); + + for (const [ws, second] of [ + ['same', 'a'], + ['different', 'b'], + ]) { + await t.test( + ws + ' document first saves on two connections', + async () => { + await tab.evalJs(`(${gateSaveConnections})(2)`); + // Release stale standalone reads together. A write transaction never waits here. + await tab.evalJs(`(() => { + const original = IDBObjectStore.prototype.getAll; + const name = ${JSON.stringify('local:workspace:' + ws)}; + const reads = []; + const transaction = IDBDatabase.prototype.transaction; + IDBDatabase.prototype.transaction = function (stores, mode, ...rest) { + if (this.name === name && mode === 'readwrite') { + IDBObjectStore.prototype.getAll = original; + IDBDatabase.prototype.transaction = transaction; + } + return transaction.call(this, stores, mode, ...rest); + }; + IDBObjectStore.prototype.getAll = function (...args) { + const req = original.apply(this, args); + if (this.transaction.db.name === name && + this.transaction.mode === 'readonly' && this.name === 'updates') { + req.addEventListener('success', event => { + event.stopImmediatePropagation(); + reads.push(() => req.onsuccess(event)); + if (reads.length === 2) { + IDBObjectStore.prototype.getAll = original; + reads.forEach(deliver => deliver()); + } + }, { once: true }); + } + return req; + }; + })()`); + const saves = Promise.all([ + append(ws, 'a', 'one'), + append(ws, second, 'two'), + ]); + await tab.evalJs('window.connectionsReady'); + await tab.evalJs('window.releaseConnections()'); + await saves; + const state = await saved(ws); + if (second === 'a') { + assert.deepEqual((await paragraphs(ws, 'a')).sort(), [ + 'one', + 'two', + ]); + assert.deepEqual(state.catalog, ['a']); + assertSaveClocks(state, { a: 2, same: 1 }); + } else { + assert.deepEqual(state.catalog.sort(), ['a', 'b']); + assert.deepEqual(await paragraphs(ws, 'a'), ['one']); + assert.deepEqual(await paragraphs(ws, 'b'), ['two']); + assertSaveClocks(state, { a: 1, b: 1, different: 2 }); + } + } + ); + } + + await t.test('abort rolls back updates and clocks', async () => { + await tab.evalJs(`(() => { + const add = IDBObjectStore.prototype.add; + IDBObjectStore.prototype.add = function (...args) { + const req = add.apply(this, args); + IDBObjectStore.prototype.add = add; + req.addEventListener('success', () => this.transaction.abort()); + return req; + }; + })()`); + await assert.rejects( + append('abort', 'a', 'discard'), + /abort|write failed/i + ); + const state = await saved('abort'); + assert.deepEqual(state.updates, []); + assert.deepEqual(state.clocks, []); + }); + + await t.test( + 'repeat save preserves catalog metadata from a snapshot', + async () => { + await append('existing', 'page', 'first'); + await tab.evalJs(`(async () => { + const Y = await import('/mobile-legacy/yjs.mjs'); + const db = await new Promise(ok => { + const req = indexedDB.open('local:workspace:existing'); + req.onsuccess = () => ok(req.result); + }); + try { + const tx = db.transaction(['updates','snapshots','clocks'], 'readwrite'); + tx.objectStore('clocks').put({ docId: 'page', timestamp: new Date('2100-01-01') }); + const rows = tx.objectStore('updates').index('docId').getAll('existing'); + rows.onsuccess = () => { + const doc = new Y.Doc(); + for (const row of rows.result) Y.applyUpdate(doc, row.bin); + const meta = doc.getMap('meta'); + meta.set('foreign', 'kept'); + meta.get('pages').get(0).set('title', 'Original'); + tx.objectStore('snapshots').put({ docId: 'existing', bin: Y.encodeStateAsUpdate(doc) }); + }; + await new Promise((ok, fail) => { tx.oncomplete = ok; tx.onabort = () => fail(tx.error); }); + } finally { db.close(); } + })()`); + await append('existing', 'page', 'second'); + const state = await saved('existing'); + assert.deepEqual(await paragraphs('existing', 'page'), [ + 'first', + 'second', + ]); + assert.deepEqual(state.catalog, ['page']); + assert.equal(state.meta.pages[0].title, 'Original'); + assert.equal(state.meta.foreign, 'kept'); + assertSaveClocks(state, { existing: 1, page: 2 }); + assert.equal( + new Map(state.clocks).get('page'), + Date.UTC(2100, 0, 1) + 1 + ); + } + ); + + await t.test('workspace and page share one key', async () => { + await append('root', 'root', 'body'); + assertSaveClocks(await saved('root'), { root: 1 }); + }); + } finally { + await closeBrowserResources(harness, tab, server); + } +}); diff --git a/packages/frontend/hosts/web/tests/dual-shell-verifiers.browser.mjs b/packages/frontend/hosts/web/tests/dual-shell-verifiers.browser.mjs new file mode 100644 index 0000000000..daaf58cc91 --- /dev/null +++ b/packages/frontend/hosts/web/tests/dual-shell-verifiers.browser.mjs @@ -0,0 +1,337 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + readlinkSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import * as Y from 'yjs'; + +import { + closeBrowserResources, + createChromiumHarness, + openPageTarget, +} from '../scripts/chromium-harness.mjs'; +import { connectCdpTarget } from '../scripts/verify-canary-dual-shell-e2e.mjs'; +import { openSignIn } from '../scripts/verify-workerd-bundle-e2e.mjs'; +import { writeWasmFixture } from './dual-shell-wasm-fixture.mjs'; + +async function listen(server) { + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + return 'http://127.0.0.1:' + server.address().port; +} + +await test('sign-in consumes the provider configuration before checking the buttons', async t => { + for (const sameOrigin of [true, false]) { + await t.test( + sameOrigin + ? 'same origin shows Google' + : 'cross-origin proxy hides Google', + async () => { + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + let harness; + let tab; + let server; + let url; + try { + server = createServer(async (req, res) => { + const pathname = new URL(req.url, url).pathname; + if (pathname === '/sign-in' || pathname === '/src/sign-in.js') { + const html = pathname === '/sign-in'; + res.setHeader( + 'Content-Type', + html ? 'text/html' : 'text/javascript' + ); + res.end( + readFileSync( + new URL( + html ? '../sign-in.html' : '../src/sign-in.js', + import.meta.url + ) + ) + ); + return; + } + res.setHeader('Content-Type', 'application/json'); + if (pathname === '/graphql') { + requested.resolve(); + await release.promise; + const serverConfig = { + name: 'Local', + baseUrl: sameOrigin ? url : 'https://upstream.example', + features: ['OAuth'], + oauthProviders: ['Google'], + }; + res.end(JSON.stringify({ data: { serverConfig } })); + } else { + res.end('{}'); + } + }); + url = await listen(server); + harness = createChromiumHarness({ tmpPrefix: 'affine-provider-' }); + const port = await harness.launchChromium({ + args: ['--disable-gpu'], + }); + const target = await openPageTarget(port); + tab = await connectCdpTarget(target.webSocketDebuggerUrl); + let settled = false; + const ready = openSignIn(tab, url).finally(() => { + settled = true; + }); + await Promise.race([requested.promise, ready]); + const form = await tab.send('Runtime.evaluate', { + expression: + "getEventListeners(document.querySelector('form')).submit.length > 0 && document.querySelector('#oauth-providers').hidden", + includeCommandLineAPI: true, + returnByValue: true, + }); + assert.equal(form.result.value, true); + assert.equal( + settled, + false, + 'Configuration response is still on hold' + ); + release.resolve(); + const { config, ui } = await ready; + assert.deepEqual(config.oauthProviders, ['Google']); + assert.deepEqual(ui, { + hidden: !sameOrigin, + providers: sameOrigin ? ['Google'] : [], + }); + } finally { + release.resolve(); + await closeBrowserResources(harness, tab, server); + } + } + ); + } +}); + +await test('the legacy CLI requires a mounted workspace document and reaps Chromium', async t => { + const dir = mkdtempSync(join(tmpdir(), 'legacy-fixtures-')); + const wasm = join(dir, 'wasm'); + const legacy = join(dir, 'legacy'); + const cli = fileURLToPath( + new URL('../scripts/verify-canary-dual-shell-e2e.mjs', import.meta.url) + ); + + const rootDoc = new Y.Doc(); + const pages = new Y.Array(); + const pageEntry = new Y.Map(); + pageEntry.set('id', 'doc-cli'); + pages.push([pageEntry]); + rootDoc.getMap('meta').set('pages', pages); + const rootBin = Array.from(Y.encodeStateAsUpdate(rootDoc)); + + const pageDoc = new Y.Doc(); + const pageBlock = new Y.Map(); + pageBlock.set('sys:id', 'block-root'); + pageBlock.set('sys:flavour', 'affine:page'); + pageDoc.getMap('blocks').set('block-root', pageBlock); + const pageBin = Array.from(Y.encodeStateAsUpdate(pageDoc)); + + const editorPage = script => `
+
+ Mounted +
+
+ `; + // The shell moves to the document route with the History API, so only a + // direct GET of the route shows whether the server can serve a deep link. + const spaRoute = + "history.replaceState(null, '', '/workspace/ws-cli/doc-cli');"; + + const cases = [ + [ + 'valid workspace document', + { + redirectTo: '/workspace/ws-cli/doc-cli', + html: editorPage('writeWorkspace();'), + }, + null, + ], + [ + 'deep-link-404', + { html: editorPage(spaRoute + 'writeWorkspace();') }, + /Legacy shell HTTP 404: http:\/\/127\.0\.0\.1:\d+\/workspace\/ws-cli\/doc-cli/, + ], + [ + 'route-lost', + { + // The first read-only IndexedDB probe of the verifier (an open without + // a version) moves the shell back to the Retry route before the + // workspace is written. + html: editorPage(`${spaRoute} + const open = indexedDB.open.bind(indexedDB); + indexedDB.open = (...args) => { + const req = open(...args); + if (args.length === 1) { + indexedDB.open = open; + history.replaceState(null, '', '/'); + document.querySelector('#app').innerHTML = ''; + writeWorkspace(); + } + return req; + };`), + }, + /Legacy shell lost the mounted document \/workspace\/ws-cli\/doc-cli: Legacy shell route "\/" is not a valid/, + ], + [ + 'retry button on root', + { + html: '
', + }, + /not a valid \/workspace\/\/ path/, + ], + [ + 'exception after progress', + { + html: '
', + }, + /editor startup failed/, + ], + [ + 'missing entry', + { + html: '
', + }, + /404.*missing\.js/, + ], + [ + 'invalid module', + { + html: '
', + }, + /SyntaxError/, + ], + [ + 'editor DOM without IndexedDB', + { + redirectTo: '/workspace/ws-no-db/doc-cli', + html: '
Mounted
', + }, + /IndexedDB database does not exist: local:workspace:ws-no-db/, + ], + ]; + try { + mkdirSync(wasm); + mkdirSync(legacy); + writeWasmFixture(wasm); + for (const [name, fixture, error] of cases) { + await t.test(name, async () => { + let server; + let pid; + const temp = mkdtempSync('/tmp/v-'); + const index = join(legacy, 'index.html'); + try { + writeFileSync(index, fixture.html); + server = createServer((req, res) => { + const pathname = new URL(req.url, 'http://localhost').pathname; + const work = readdirSync(temp).find(value => + value.startsWith('affine-canary-') + ); + if (work) { + const lock = readlinkSync( + join(temp, work, 'chrome-profile', 'SingletonLock') + ); + pid = Number(lock.slice(lock.lastIndexOf('-') + 1)); + } + if (pathname === '/' && fixture.redirectTo) { + res.writeHead(302, { + Location: fixture.redirectTo, + 'Set-Cookie': 'affine_shell=legacy; Path=/', + }); + res.end(); + return; + } + if (pathname !== '/' && pathname !== fixture.redirectTo) { + res.writeHead(404).end(); + return; + } + res.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': 'affine_shell=legacy; Path=/', + }); + res.end(readFileSync(index)); + }); + const url = await listen(server); + const run = promisify(execFile)( + process.execPath, + [ + cli, + '--legacy-dir', + legacy, + '--wasm-dir', + wasm, + '--base-url', + url, + ], + { + env: { + ...process.env, + TMPDIR: temp, + AFFINE_LEGACY_CONTROL_TIMEOUT_MS: '2000', + }, + } + ); + if (error) { + await assert.rejects(run, failure => { + assert.equal(failure.code, 1); + assert.match(failure.stderr, error); + return true; + }); + } else { + const { stdout } = await run; + assert.match(stdout, /mounted on the legacy route/); + assert.match( + stdout, + /"reopened":\{"pathname":"\/workspace\/ws-cli\/doc-cli","workspaceDbNames":\["local:workspace:ws-cli"\]\}/ + ); + } + assert.ok(pid > 0); + assert.throws(() => process.kill(-pid, 0), { code: 'ESRCH' }); + assert.deepEqual(readdirSync(temp), []); + } finally { + await closeBrowserResources(undefined, undefined, server); + rmSync(temp, { recursive: true, force: true }); + } + }); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/frontend/hosts/web/tests/dual-shell-wasm-fixture.mjs b/packages/frontend/hosts/web/tests/dual-shell-wasm-fixture.mjs new file mode 100644 index 0000000000..921c3a13fa --- /dev/null +++ b/packages/frontend/hosts/web/tests/dual-shell-wasm-fixture.mjs @@ -0,0 +1,89 @@ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export function writeWasmFixture(tmpWasm) { + const encodeUleb = n => { + const out = []; + let v = n >>> 0; + do { + let b = v & 0x7f; + v >>>= 7; + if (v !== 0) b |= 0x80; + out.push(b); + } while (v !== 0); + return out; + }; + const section = (id, body) => [id, ...encodeUleb(body.length), ...body]; + const makeValidTestWasm = (exportNames, { memory = false } = {}) => { + const typeSec = section(1, [1, 0x60, 0, 0]); + const funcSec = section(3, [ + ...encodeUleb(exportNames.length), + ...exportNames.map(() => 0), + ]); + const expEntries = []; + for (const [idx, name] of exportNames.entries()) { + const nb = Buffer.from(name, 'utf8'); + expEntries.push( + ...encodeUleb(nb.length), + ...nb, + 0x00, + ...encodeUleb(idx) + ); + } + if (memory) { + const nb = Buffer.from('memory', 'utf8'); + expEntries.push(...encodeUleb(nb.length), ...nb, 0x02, 0); + } + const memorySec = memory ? section(5, [1, 0x00, 1]) : []; + const exportSec = section(7, [ + ...encodeUleb(exportNames.length + (memory ? 1 : 0)), + ...expEntries, + ]); + const codeBodies = []; + for (const _ of exportNames) { + codeBodies.push(2, 0, 0x0b); + } + const codeSec = section(10, [ + ...encodeUleb(exportNames.length), + ...codeBodies, + ]); + const padName = Buffer.from('pad', 'utf8'); + const customSec = section(0, [ + ...encodeUleb(padName.length), + ...padName, + ...new Uint8Array(11 * 1024), + ]); + return Buffer.from([ + 0x00, + 0x61, + 0x73, + 0x6d, + 0x01, + 0x00, + 0x00, + 0x00, + ...typeSec, + ...funcSec, + ...memorySec, + ...exportSec, + ...codeSec, + ...customSec, + ]); + }; + const workerExports = ['prepare', 'invoke', 'output_ptr']; + for (const kind of ['mermaid', 'math', 'typst', 'pdf']) { + writeFileSync( + join(tmpWasm, `${kind}.wasm`), + makeValidTestWasm(workerExports, { memory: true }) + ); + } + mkdirSync(join(tmpWasm, 'pkg'), { recursive: true }); + writeFileSync( + join(tmpWasm, 'pkg/playground.js'), + 'export default async function init() {}\nexport function merge_updates_v1(u) { return u[0]; }\nexport function extract_subdoc_ids() { return []; }\n' + ); + writeFileSync( + join(tmpWasm, 'pkg/playground_bg.wasm'), + makeValidTestWasm(['merge_updates_v1', 'extract_subdoc_ids']) + ); +} diff --git a/packages/frontend/hosts/web/tests/extract-tokens-shadow.test.mjs b/packages/frontend/hosts/web/tests/extract-tokens-shadow.test.mjs new file mode 100644 index 0000000000..1ed38b5f68 --- /dev/null +++ b/packages/frontend/hosts/web/tests/extract-tokens-shadow.test.mjs @@ -0,0 +1,145 @@ +// @ts-check + +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { + formatF32, + formatShadowLayer, + parseShadowLayers, +} from '../../../../ui/tokens/extract-tokens.mjs'; + +void test('formatF32 emits valid Rust f32 literals for scientific notation and rejects non-finite or out-of-range f32 values', () => { + assert.equal(formatF32(0.0000001, '--test-shadow'), '1e-7_f32'); + assert.equal(formatF32(-0, '--test-shadow'), '0.0_f32'); + assert.equal(formatF32(12, '--test-shadow'), '12.0_f32'); + assert.equal(formatF32(0.14, '--test-shadow'), '0.14_f32'); + assert.throws(() => formatF32(Number.NaN, '--test-shadow'), /--test-shadow/); + assert.throws( + () => formatF32(Number.POSITIVE_INFINITY, '--test-shadow'), + /--test-shadow/ + ); + assert.throws( + () => formatF32(1e39, '--affine-overflow-shadow'), + /--affine-overflow-shadow/ + ); + const overflowLayers = parseShadowLayers( + '0px 1e39px 0px #000', + '--affine-overflow-shadow' + ); + assert.throws( + () => formatShadowLayer(overflowLayers[0], '--affine-overflow-shadow'), + /--affine-overflow-shadow/ + ); +}); + +void test('extract-tokens.mjs runs CLI main() even when invoked through a symlink', () => { + const tmp = mkdtempSync(join(tmpdir(), 'affine-extract-tokens-symlink-')); + try { + const targetScript = resolve( + fileURLToPath( + new URL('../../../../ui/tokens/extract-tokens.mjs', import.meta.url) + ) + ); + const linkScript = join(tmp, 'extract-tokens-link.mjs'); + symlinkSync(targetScript, linkScript); + + const res = spawnSync(process.execPath, [linkScript, '--unknown-flag'], { + encoding: 'utf8', + }); + assert.notEqual( + res.status, + 0, + 'symlink invocation must execute CLI main() and fail non-zero on --unknown-flag' + ); + assert.match(res.stderr || '', /--unknown-flag/); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +void test('parseShadowLayers rejects malformed numeric tokens without silent parseFloat truncation', () => { + assert.throws( + () => + parseShadowLayers( + '0px 4px 8px rgba(1..2, 0, 0, .14)', + '--affine-broken-shadow' + ), + err => { + const msg = String(err?.message || err); + assert.match(msg, /--affine-broken-shadow/); + return true; + } + ); + assert.throws( + () => + parseShadowLayers( + '0px 4px 8px rgba(10, 20, 30, 0.1.2)', + '--affine-broken-alpha' + ), + /--affine-broken-alpha/ + ); +}); + +void test('parseShadowLayers preserves fractional RGB channel precision without rounding', () => { + const layers = parseShadowLayers( + '0px 2px 4px rgba(12.5, 18, 255, .0000001)', + '--affine-fractional-shadow' + ); + assert.equal(layers.length, 1); + const rendered = formatShadowLayer(layers[0], '--affine-fractional-shadow'); + assert.match(rendered, /r: 12\.5_f32 \/ 255\.0_f32/); + assert.match(rendered, /g: 18\.0_f32 \/ 255\.0_f32/); + assert.match(rendered, /b: 255\.0_f32 \/ 255\.0_f32/); + assert.match(rendered, /a: 1e-7_f32/); +}); + +void test('parseShadowLayers rejects negative blur radius while preserving negative spread radius', () => { + assert.throws( + () => parseShadowLayers('0px 0px -2px #000', '--affine-neg-blur-shadow'), + err => { + const msg = String(err?.message || err); + assert.match(msg, /--affine-neg-blur-shadow/); + assert.match(msg, /blur/i); + return true; + } + ); + + const layers = parseShadowLayers( + '0px 4px 6px -3px rgba(66, 65, 73, .1), 0px 10px 12px -2px rgba(66, 65, 73, .1)', + '--affine-float-button-shadow-1' + ); + assert.equal(layers.length, 2); + assert.equal(layers[0].blur_radius, 6); + assert.equal(layers[0].spread_radius, -3); + assert.equal(layers[1].blur_radius, 12); + assert.equal(layers[1].spread_radius, -2); +}); + +void test('parseShadowLayers handles unset, inset omission, 3-layer paper shadow, and hex alpha', () => { + assert.deepEqual( + parseShadowLayers('unset', '--affine-button-inner-shadow'), + [] + ); + + const popover = parseShadowLayers( + '0px 0px 30px rgba(75, 75, 75, .2), 0px 0px 4px rgba(75, 75, 75, .3), inset 0px 0px 0px rgba(227, 226, 228, 1)', + '--affine-popover-shadow' + ); + assert.equal(popover.length, 2); + + const toolbar = parseShadowLayers( + '0px 6px 16px #00000024', + '--affine-toolbar-shadow' + ); + assert.equal(toolbar.length, 1); + assert.equal( + formatShadowLayer(toolbar[0], '--affine-toolbar-shadow'), + 'ShadowLayer { offset_x: 0.0_f32, offset_y: 6.0_f32, blur_radius: 16.0_f32, spread_radius: 0.0_f32, r: 0.0_f32 / 255.0_f32, g: 0.0_f32 / 255.0_f32, b: 0.0_f32 / 255.0_f32, a: 36.0_f32 / 255.0_f32 }' + ); +}); diff --git a/packages/frontend/hosts/web/tests/idb-storage.test.mjs b/packages/frontend/hosts/web/tests/idb-storage.test.mjs new file mode 100644 index 0000000000..9a24ab4601 --- /dev/null +++ b/packages/frontend/hosts/web/tests/idb-storage.test.mjs @@ -0,0 +1,2680 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { openDesktopStore } from '../desktop/start.js'; +import { bootWebHost, flushBeforeNavigation } from '../src/host.js'; +import { + addLocalWorkspaceId, + createIdbV1ReadonlyReader, + createIdbWorkspaceStorage, + createPendingWriteFlusher, + formatIdbChannelName, + formatIdbName, + getLocalWorkspaceIds, + getWebPreference, + IDB_SCHEMA_VERSION, + IDB_STORE_NAMES, + LOCAL_WORKSPACE_CHANGED_CHANNEL, + LOCAL_WORKSPACE_LOCAL_STORAGE_KEY, + openWorkspaceIdb, + removeLocalWorkspaceId, + setWebPreference, + V1_CONST_TIMESTAMP, +} from '../src/idb-storage.js'; +import { + createBroadcastBus, + createMemoryIdbFactory, + createMemoryStorage, +} from './memory-idb.mjs'; + +function createIdbTestFactory() { + return globalThis.indexedDB ?? createMemoryIdbFactory(); +} + +function mockBroadcastChannel(t) { + const original = globalThis.BroadcastChannel; + globalThis.BroadcastChannel = createBroadcastBus(); + t.after(() => { + globalThis.BroadcastChannel = original; + }); +} + +void test('a blocked workspace open rejects and closes a database that arrives later', async t => { + const request = {}; + const close = t.mock.fn(); + const opened = openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'blocked' }, + { indexedDB: { open: () => request } } + ); + request.onblocked(); + await assert.rejects(opened, { + message: 'IndexedDB open blocked for local:workspace:blocked', + }); + request.result = { close }; + request.onsuccess(); + assert.equal(close.mock.callCount(), 1); +}); + +void test('IDB v3 schema freezes at version 3 with all 12 0.27.5 objectStores and indexes', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-schema', + indexedDB: idb, + BroadcastChannelImpl, + }); + + assert.equal( + formatIdbName({ flavour: 'local', type: 'workspace', id: 'ws-schema' }), + 'local:workspace:ws-schema' + ); + assert.equal( + formatIdbChannelName('local:workspace:ws-schema'), + 'idb:local:workspace:ws-schema' + ); + assert.equal(IDB_SCHEMA_VERSION, 3); + assert.equal(IDB_STORE_NAMES.length, 12); + + const db = await storage.open(); + assert.equal(db.version, 3); + for (const storeName of IDB_STORE_NAMES) { + assert.ok( + db.objectStoreNames.contains(storeName), + `missing 0.27.5 objectStore: ${storeName}` + ); + } + + const meta = idb.getMeta('local:workspace:ws-schema'); + assert.deepEqual( + [...meta.stores.get('snapshots').indexes.keys()], + ['updatedAt'] + ); + assert.deepEqual([...meta.stores.get('updates').indexes.keys()], ['docId']); + assert.deepEqual( + [...meta.stores.get('clocks').indexes.keys()], + ['timestamp'] + ); + assert.deepEqual([...meta.stores.get('peerClocks').indexes.keys()], ['peer']); + assert.deepEqual([...meta.stores.get('blobSync').indexes.keys()], ['peer']); + assert.deepEqual( + [...meta.stores.get('indexerRecords').indexes.keys()], + ['table', 'id'] + ); + assert.deepEqual( + [...meta.stores.get('invertedIndex').indexes.keys()], + ['key', 'nid'] + ); + + storage.close(); +}); + +function testMergeFrames(frames) { + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + return encoder.encode(frames.map(f => decoder.decode(f)).join('')); +} + +void test('pre-populated 0.27.5 data opens offline, persists 1-char edit, syncs peer clocks, and broadcasts across tabs', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + let fakeNow = 1_750_000_000_000; + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const tabA = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-0275', + indexedDB: idb, + BroadcastChannelImpl, + now: () => ++fakeNow, + mergeUpdates: testMergeFrames, + }); + const tabB = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-0275', + indexedDB: idb, + BroadcastChannelImpl, + now: () => ++fakeNow, + mergeUpdates: testMergeFrames, + }); + const rawOnlyTab = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-0275', + indexedDB: idb, + BroadcastChannelImpl, + now: () => ++fakeNow, + }); + + // Seed realistic 0.27.5 snapshot + blob + peer clock before opening offline. + const db = await tabA.open(); + const seedTx = db.transaction( + ['snapshots', 'clocks', 'blobs', 'blobData'], + 'readwrite' + ); + seedTx.objectStore('snapshots').put({ + docId: 'doc-1', + bin: encoder.encode('Hello'), + createdAt: new Date(1_740_000_000_000), + updatedAt: new Date(1_740_000_000_500), + }); + seedTx.objectStore('clocks').put({ + docId: 'doc-1', + timestamp: new Date(1_740_000_000_500), + }); + seedTx.objectStore('blobs').put({ + key: 'blob-cover', + mime: 'image/png', + size: 4, + createdAt: new Date(1_740_000_000_500), + deletedAt: null, + }); + seedTx.objectStore('blobData').put({ + key: 'blob-cover', + data: new Uint8Array([137, 80, 78, 71]), + }); + await new Promise((resolve, reject) => { + seedTx.oncomplete = resolve; + seedTx.onabort = reject; + seedTx.commit(); + }); + + await tabB.open(); + const tabBReceived = []; + const unsub = tabB.subscribeDocUpdate((update, origin) => { + tabBReceived.push({ update, origin }); + }); + + // Offline open original document. + const initialDoc = await tabA.getDoc('doc-1'); + assert.equal(decoder.decode(initialDoc.bin), 'Hello'); + const blob = await tabA.getBlob('blob-cover'); + assert.equal(blob.mime, 'image/png'); + assert.deepEqual([...blob.data], [137, 80, 78, 71]); + + // Append 1-character CRDT edit and persist to same-origin IDB. + const pushed = await tabA.pushDocUpdate( + { docId: 'doc-1', bin: encoder.encode('!') }, + 'local-editor' + ); + assert.ok(pushed.timestamp.getTime() > 1_740_000_000_500); + + // Cross-tab BroadcastChannel('idb:local:workspace:ws-0275') delivers update to Tab B. + assert.equal(tabBReceived.length, 1); + assert.equal(tabBReceived[0].origin, 'local-editor'); + assert.equal(tabBReceived[0].update.docId, 'doc-1'); + assert.equal(decoder.decode(tabBReceived[0].update.bin), '!'); + + // Simulate cloud sync push & indexer sync clocks. + await tabA.setPeerPushedClock('cloud', { + docId: 'doc-1', + timestamp: pushed.timestamp, + }); + await tabA.setPeerRemoteClock('cloud', { + docId: 'doc-1', + timestamp: pushed.timestamp, + }); + await tabA.setPeerPulledRemoteClock('cloud', { + docId: 'doc-1', + timestamp: pushed.timestamp, + }); + await tabA.setBlobUploadedAt('cloud', 'blob-cover', pushed.timestamp); + await tabA.setDocIndexedClock({ + docId: 'doc-1', + timestamp: pushed.timestamp, + indexerVersion: 2, + }); + + // Without mergeUpdates, getDoc must throw instead of raw-concatenating CRDT frames; + // getDocRaw returns raw ordered frames for Rust y-octo to apply safely. + await assert.rejects(() => rawOnlyTab.getDoc('doc-1'), TypeError); + const rawFrames = await rawOnlyTab.getDocRaw('doc-1'); + assert.equal(decoder.decode(rawFrames.snapshot), 'Hello'); + assert.deepEqual( + rawFrames.updates.map(u => decoder.decode(u)), + ['!'] + ); + + // Concurrent write during async mergeUpdates must NOT be overwritten/dropped by compact: true. + let releaseMerge; + const mergeBarrier = new Promise(resolve => { + releaseMerge = resolve; + }); + const compactPromise = tabB.getDoc('doc-1', { + compact: true, + mergeUpdates: async frames => { + await mergeBarrier; + return testMergeFrames(frames); + }, + }); + // While compact read->merge is in flight, mutate snapshot concurrently. + const concurrentDb = await tabA.open(); + const concTx = concurrentDb.transaction('snapshots', 'readwrite'); + concTx.objectStore('snapshots').put({ + docId: 'doc-1', + bin: encoder.encode('Hello-concurrent'), + createdAt: new Date(1_740_000_000_000), + updatedAt: new Date(1_740_000_001_000), + }); + await new Promise((resolve, reject) => { + concTx.oncomplete = resolve; + concTx.onabort = reject; + concTx.commit(); + }); + releaseMerge(); + const staleRead = await compactPromise; + assert.equal(decoder.decode(staleRead.bin), 'Hello!'); + // Concurrent snapshot and pending '!' update must both remain intact. + const afterRace = await rawOnlyTab.getDocRaw('doc-1'); + assert.equal(decoder.decode(afterRace.snapshot), 'Hello-concurrent'); + assert.deepEqual( + afterRace.updates.map(u => decoder.decode(u)), + ['!'] + ); + + // Tab B reads back merged document with clean compaction and sync clocks consistently. + const readBack = await tabB.getDoc('doc-1', { compact: true }); + assert.equal(decoder.decode(readBack.bin), 'Hello-concurrent!'); + assert.equal( + (await tabB.getPeerPushedClock('cloud', 'doc-1')).timestamp.getTime(), + pushed.timestamp.getTime() + ); + assert.equal( + (await tabB.getBlobUploadedAt('cloud', 'blob-cover')).getTime(), + pushed.timestamp.getTime() + ); + assert.equal((await tabB.getDocIndexedClock('doc-1')).indexerVersion, 2); + + unsub(); + rawOnlyTab.close(); + tabA.close(); + tabB.close(); +}); + +void test('V1 readonly fallback reads legacy affine-local docs and blobs without creating empty DBs', async () => { + const idb = createMemoryIdbFactory(); + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + // When no V1 DB exists (even without indexedDB.databases()), reader aborts + // upgrade, returns null, and creates zero empty DBs. + const idbNoDatabases = { open: idb.open.bind(idb) }; + const emptyReader = createIdbV1ReadonlyReader({ + workspaceId: 'ws-missing', + indexedDB: idbNoDatabases, + }); + assert.equal(emptyReader.readonly, true); + assert.equal(await emptyReader.getV1Doc('ws-missing'), null); + assert.equal(await emptyReader.getV1Blob('b1'), null); + assert.equal(idb.getMeta('affine-local'), undefined); + assert.equal(idb.getMeta('ws-missing_blob'), undefined); + + // Seed legacy V1 doc DB ('affine-local') and blob DB ('ws-v1_blob'). + const docDb = await new Promise((resolve, reject) => { + const req = idb.open('affine-local', 1); + req.onupgradeneeded = () => { + req.result.createObjectStore('workspace', { keyPath: 'id' }); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const docTx = docDb.transaction('workspace', 'readwrite'); + docTx.objectStore('workspace').put({ + id: 'ws-v1', + updates: [ + { timestamp: 100, update: encoder.encode('V1-') }, + { timestamp: 200, update: encoder.encode('DOC') }, + ], + }); + docTx.objectStore('workspace').put({ + id: 'page-subdoc-1', + updates: [{ timestamp: 250, update: encoder.encode('SUBDOC') }], + }); + docTx.objectStore('workspace').put({ + id: 'other-ws-subdoc', + updates: [{ timestamp: 255, update: encoder.encode('OTHER-SUBDOC') }], + }); + docTx.objectStore('workspace').put({ + id: 'db$ws-v1$page-1', + updates: [{ timestamp: 300, update: encoder.encode('PAGE') }], + }); + docTx.objectStore('workspace').put({ + id: 'userdata$u1$ws-v1', + updates: [{ timestamp: 301, update: encoder.encode('USER') }], + }); + docTx.objectStore('workspace').put({ + id: 'userdata$u1$ws-v1$doc-9', + updates: [{ timestamp: 302, update: encoder.encode('USER-DOC') }], + }); + docTx.objectStore('workspace').put({ + id: 'other-ws', + updates: [{ timestamp: 400, update: encoder.encode('OTHER') }], + }); + await new Promise((resolve, reject) => { + docTx.oncomplete = resolve; + docTx.onabort = reject; + docTx.commit(); + }); + + const blobDb = await new Promise((resolve, reject) => { + const req = idb.open('ws-v1_blob', 1); + req.onupgradeneeded = () => { + req.result.createObjectStore('blob'); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const blobTx = blobDb.transaction('blob', 'readwrite'); + blobTx.objectStore('blob').put(new Uint8Array([1, 2, 3]).buffer, 'img-1'); + await new Promise((resolve, reject) => { + blobTx.oncomplete = resolve; + blobTx.onabort = reject; + blobTx.commit(); + }); + + const v1RawOnly = createIdbV1ReadonlyReader({ + workspaceId: 'ws-v1', + indexedDB: idb, + }); + await assert.rejects(() => v1RawOnly.getV1Doc('ws-v1'), TypeError); + const v1Raw = await v1RawOnly.getV1DocRaw('ws-v1'); + assert.deepEqual( + v1Raw.updates.map(u => decoder.decode(u)), + ['V1-', 'DOC'] + ); + + const v1 = createIdbV1ReadonlyReader({ + workspaceId: 'ws-v1', + indexedDB: idb, + mergeUpdates: testMergeFrames, + }); + const rootDoc = await v1.getV1Doc('ws-v1'); + assert.equal(decoder.decode(rootDoc.bin), 'V1-DOC'); + assert.equal(rootDoc.timestamp.getTime(), V1_CONST_TIMESTAMP.getTime()); + assert.deepEqual( + await v1.listV1DocIds({ + extractSubdocIds: rootUpdates => { + assert.equal(rootUpdates.length, 2); + return ['page-subdoc-1', 'missing-subdoc-999', 'ws-v1']; + }, + }), + [ + 'ws-v1', + 'page-subdoc-1', + 'db$ws-v1$page-1', + 'userdata$u1$ws-v1', + 'userdata$u1$ws-v1$doc-9', + ] + ); + const v1Blob = await v1.getV1Blob('img-1'); + assert.deepEqual([...v1Blob.data], [1, 2, 3]); +}); + +void test('Iron Rule F1: deleted workspace with leftover IDB has 0 resurrection and never calls indexedDB.databases()', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + + // Both ws-keep and ws-deleted have populated IDB databases on disk. + const keepStore = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-keep', + indexedDB: idb, + BroadcastChannelImpl, + }); + const deletedStore = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-deleted', + indexedDB: idb, + BroadcastChannelImpl, + }); + await keepStore.open(); + await deletedStore.open(); + + // localStorage only lists ws-keep (ws-deleted was removed in 0.27.5). + const localStorage = createMemoryStorage({ + [LOCAL_WORKSPACE_LOCAL_STORAGE_KEY]: JSON.stringify(['ws-keep']), + }); + const peerChannel = new BroadcastChannelImpl(LOCAL_WORKSPACE_CHANGED_CHANNEL); + const myChannel = new BroadcastChannelImpl(LOCAL_WORKSPACE_CHANGED_CHANNEL); + const notifications = []; + peerChannel.addEventListener('message', ev => notifications.push(ev.data)); + + const listed = getLocalWorkspaceIds(localStorage); + assert.deepEqual(listed, ['ws-keep']); + assert.equal( + idb.getDatabasesCallCount(), + 0, + 'local workspace enumeration must never call indexedDB.databases()' + ); + + addLocalWorkspaceId('ws-new', localStorage, myChannel); + assert.deepEqual(getLocalWorkspaceIds(localStorage), ['ws-keep', 'ws-new']); + removeLocalWorkspaceId('ws-keep', localStorage, myChannel); + assert.deepEqual(getLocalWorkspaceIds(localStorage), ['ws-new']); + assert.deepEqual(notifications, ['ws-new', 'ws-keep']); + + // Preferences helper reads/writes same-origin localStorage cleanly. + setWebPreference('affine-theme', 'dark', localStorage); + assert.equal(getWebPreference('affine-theme', localStorage), 'dark'); + setWebPreference('affine-theme', null, localStorage); + assert.equal(getWebPreference('affine-theme', localStorage), null); + + // Missing storage or missing setItem/removeItem throws with zero broadcasts. + const countBeforeNullWrites = notifications.length; + assert.throws(() => addLocalWorkspaceId('ws-null', null, myChannel), { + message: /localStorage\.setItem is unavailable/, + }); + assert.throws( + () => + removeLocalWorkspaceId( + 'ws-new', + { getItem: () => '["ws-new"]' }, + myChannel + ), + { message: /localStorage\.setItem is unavailable/ } + ); + assert.throws(() => setWebPreference('language', 'zh-Hant', null), { + message: /localStorage\.setItem is unavailable/, + }); + assert.throws(() => setWebPreference('language', null, { setItem() {} }), { + message: /localStorage\.removeItem is unavailable/, + }); + assert.equal(notifications.length, countBeforeNullWrites); + assert.deepEqual(getLocalWorkspaceIds(null), []); + + peerChannel.close(); + myChannel.close(); + keepStore.close(); + deletedStore.close(); +}); + +void test('real IDB flushBeforeNavigation retains buffered writes and aborts navigation on transaction failure, then succeeds on retry', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-flush', + indexedDB: idb, + BroadcastChannelImpl, + now: () => 1_760_000_000_000, + }); + const flusher = createPendingWriteFlusher(storage); + flusher.enqueue({ + docId: 'doc-unsaved', + bin: encoder.encode('critical-edit'), + origin: 'editor', + }); + assert.equal(flusher.pendingCount(), 1); + + // Inject real IDB transaction abort/failure. + idb.failNextWriteTransaction(new Error('QuotaExceededError')); + const events = []; + const aborted = await flushBeforeNavigation({ + pauseInput: () => events.push('pause'), + flushPendingWrites: () => flusher.flush(), + navigate: url => events.push(`nav:${url}`), + resumeInput: () => events.push('resume'), + targetUrl: '/sign-in', + }); + + assert.equal(aborted.navigated, false); + assert.equal(aborted.reason, 'flush-rejected'); + assert.deepEqual(events, ['pause', 'resume']); + assert.equal( + flusher.pendingCount(), + 1, + 'failed IDB flush must retain pending CRDT writes in buffer' + ); + assert.equal(await storage.getDoc('doc-unsaved'), null); + + // Retry without fault -> commits to IDB oncomplete, drains buffer, navigates. + const retryEvents = []; + const ok = await flushBeforeNavigation({ + pauseInput: () => retryEvents.push('pause'), + flushPendingWrites: () => flusher.flush(), + navigate: url => retryEvents.push(`nav:${url}`), + resumeInput: () => retryEvents.push('resume'), + targetUrl: '/sign-in', + }); + + assert.deepEqual(ok, { navigated: true }); + assert.deepEqual(retryEvents, ['pause', 'nav:/sign-in']); + assert.equal(flusher.pendingCount(), 0); + const persisted = await storage.getDoc('doc-unsaved'); + assert.equal(decoder.decode(persisted.bin), 'critical-edit'); + + // Verify bootWebHost wires real IDB pendingWrites into navigateWithFlush. + const assigned = []; + const fakeIme = { readOnly: false, tabIndex: 0, blur() {} }; + const host = await bootWebHost({ + win: { + navigator: { gpu: {} }, + location: { + href: 'https://app.affine.pro/workspace/ws-flush/doc-unsaved', + assign: url => assigned.push(url), + }, + localStorage: createMemoryStorage({ + [LOCAL_WORKSPACE_LOCAL_STORAGE_KEY]: JSON.stringify(['ws-flush']), + }), + }, + doc: { + createElement: () => ({ getContext: () => ({}) }), + getElementById(id) { + if (id === 'affine-build-manifest') { + return { + textContent: JSON.stringify({ + shellVersion: 'mobile-v1', + buildHash: 'test-hash', + appEntryJs: null, + workers: {}, + fonts: {}, + }), + }; + } + if (id === 'ime') return fakeIme; + return null; + }, + }, + workspaceStorage: storage, + BroadcastChannelImpl, + }); + + // Verify bootWebHost broadcasts and subscribes local workspace list changes. + const peerListChannel = new BroadcastChannelImpl( + LOCAL_WORKSPACE_CHANGED_CHANNEL + ); + const peerNotices = []; + peerListChannel.addEventListener('message', ev => peerNotices.push(ev.data)); + const hostNotices = []; + const unsubHostList = host.subscribeLocalWorkspaceIds((ids, changedId) => { + hostNotices.push({ ids, changedId }); + }); + host.setLocalWorkspaceIds(['ws-flush', 'ws-extra'], 'ws-extra'); + assert.deepEqual(peerNotices, ['ws-extra']); + peerListChannel.postMessage('ws-peer'); + assert.equal(hostNotices.length, 1); + assert.equal(hostNotices[0].changedId, 'ws-peer'); + assert.deepEqual(hostNotices[0].ids, ['ws-flush', 'ws-extra']); + unsubHostList(); + peerListChannel.close(); + + host.pendingWrites.enqueue({ + docId: 'doc-nav', + bin: encoder.encode('nav-edit'), + }); + const navRes = await host.navigateWithFlush('/sign-in'); + assert.deepEqual(navRes, { navigated: true }); + assert.deepEqual(assigned, ['/sign-in']); + assert.equal( + decoder.decode((await storage.getDoc('doc-nav')).bin), + 'nav-edit' + ); + + host.dispose(); +}); + +void test('single-flight overlapping flush, compactDocWithMerged CAS, built-in Yjs v1 subdoc extractor, and attachWorkspace', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + let fakeNow = 1_770_000_000_000; + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-r4', + indexedDB: idb, + BroadcastChannelImpl, + now: () => ++fakeNow, + }); + + // 1. Overlapping flush() + concurrent enqueue('c') persists all 3 items once each with 0 drops. + const flusher = createPendingWriteFlusher(storage); + flusher.enqueue({ docId: 'd-a', bin: encoder.encode('a') }); + flusher.enqueue({ docId: 'd-b', bin: encoder.encode('b') }); + const p1 = flusher.flush(); + const p2 = flusher.flush(); + flusher.enqueue({ docId: 'd-c', bin: encoder.encode('c') }); + const [r1, r2] = await Promise.all([p1, p2]); + assert.equal(r1.ok, true); + assert.equal(r2.ok, true); + assert.equal(flusher.pendingCount(), 0); + assert.equal((await storage.getDocRaw('d-a')).updates.length, 1); + assert.equal((await storage.getDocRaw('d-b')).updates.length, 1); + assert.equal((await storage.getDocRaw('d-c')).updates.length, 1); + + // 2. compactDocWithMerged compacts when the snapshot it read is still stored, and skips otherwise. + const beforeCompact = await storage.getDocRaw('d-a'); + const compacted = await storage.compactDocWithMerged({ + docId: 'd-a', + mergedBin: encoder.encode('a-merged'), + source: beforeCompact, + }); + assert.equal(compacted.compacted, true); + const afterCompact = await storage.getDocRaw('d-a'); + assert.equal(decoder.decode(afterCompact.snapshot), 'a-merged'); + assert.equal(afterCompact.updates.length, 0); + const staleCompact = await storage.compactDocWithMerged({ + docId: 'd-a', + mergedBin: encoder.encode('stale'), + source: beforeCompact, + }); + assert.equal(staleCompact.compacted, false); + + // 3. Built-in pure-JS Yjs v1 ContentDoc subdoc extractor discovers top-level subdoc GUID without external callback. + const encStr = str => { + const b = encoder.encode(str); + return [b.byteLength, ...b]; + }; + const yjsV1Root = new Uint8Array([ + 1, // numClients + 1, // numStructs + 1, // clientId + 0, // clock + 0x20 | 9, // hasParentSub | ContentDoc (tag=9) + 1, // hasParentYKey + ...encStr('spaces'), + ...encStr('page-1'), + ...encStr('guid-page-1'), + 126, // lib0 null opts + 0, // empty DeleteSet (numDsClients = 0) + ]); + const v1Db = await new Promise((resolve, reject) => { + const req = idb.open('affine-local', 1); + req.onupgradeneeded = () => { + req.result.createObjectStore('workspace', { keyPath: 'id' }); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const v1Tx = v1Db.transaction('workspace', 'readwrite'); + v1Tx.objectStore('workspace').put({ + id: 'ws-yjs-v1', + updates: [{ timestamp: 1, update: yjsV1Root }], + }); + v1Tx.objectStore('workspace').put({ + id: 'guid-page-1', + updates: [{ timestamp: 2, update: encoder.encode('body') }], + }); + await new Promise((resolve, reject) => { + v1Tx.oncomplete = resolve; + v1Tx.onabort = reject; + v1Tx.commit(); + }); + const defaultV1 = createIdbV1ReadonlyReader({ + workspaceId: 'ws-yjs-v1', + indexedDB: idb, + }); + await assert.rejects(() => defaultV1.listV1DocIds(), TypeError); + assert.deepEqual( + await defaultV1.listV1DocIds({ + extractSubdocIds: () => ['guid-page-1'], + }), + ['ws-yjs-v1', 'guid-page-1'] + ); + + // 4. bootWebHost unbound -> attachWorkspace dynamically binds storage & flusher. + const host = await bootWebHost({ + win: { + navigator: { gpu: {} }, + location: { href: 'https://app.affine.pro/', assign() {} }, + }, + doc: { + createElement: () => ({ getContext: () => ({}) }), + getElementById: id => + id === 'affine-build-manifest' + ? { + textContent: JSON.stringify({ + shellVersion: 'mobile-v1', + buildHash: 'r4', + appEntryJs: null, + workers: {}, + fonts: {}, + }), + } + : null, + }, + indexedDB: idb, + BroadcastChannelImpl, + }); + assert.equal(host.workspaceBound, false); + host.attachWorkspace({ + peer: 'local', + spaceType: 'workspace', + spaceId: 'ws-dyn', + }); + assert.equal(host.workspaceBound, true); + assert.equal(host.workspaceStorage.dbName, 'local:workspace:ws-dyn'); + + // attachWorkspace refuses to discard unflushed writes; switchWorkspace flushes first. + host.pendingWrites.enqueue({ docId: 'doc-switch', bin: encoder.encode('s') }); + assert.throws( + () => + host.attachWorkspace({ + peer: 'local', + spaceType: 'workspace', + spaceId: 'ws-dyn-2', + }), + /unflushed/ + ); + const prevStorage = host.workspaceStorage; + await host.switchWorkspace({ + peer: 'local', + spaceType: 'workspace', + spaceId: 'ws-dyn-2', + }); + assert.equal(host.workspaceStorage.dbName, 'local:workspace:ws-dyn-2'); + const prevCheck = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-dyn', + indexedDB: idb, + BroadcastChannelImpl, + }); + assert.equal((await prevCheck.getDocRaw('doc-switch')).updates.length, 1); + prevCheck.close(); + prevStorage.close(); + host.dispose(); + storage.close(); +}); + +void test('listV1DocIds requires extractSubdocIds for non-empty rootUpdates, wires bootWebHost codecs, and matches 3/4-segment userdata keys', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + const encoder = new TextEncoder(); + const v1Db = await new Promise((resolve, reject) => { + const req = idb.open('affine-local', 1); + req.onupgradeneeded = () => { + req.result.createObjectStore('workspace', { keyPath: 'id' }); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const tx = v1Db.transaction('workspace', 'readwrite'); + tx.objectStore('workspace').put({ + id: 'ws', + updates: [ + { timestamp: 1, update: encoder.encode('root-frame-1') }, + { timestamp: 2, update: encoder.encode('root-frame-2') }, + ], + }); + for (const key of [ + 'live-guid', + 'old-guid', + 'foreign-guid', + 'userdata$u$ws', + 'userdata$u$ws$fav', + 'userdata$u$ws$fav$extra', + 'userdata$u$other', + ]) { + tx.objectStore('workspace').put({ + id: key, + updates: [{ timestamp: 10, update: encoder.encode(key) }], + }); + } + await new Promise((resolve, reject) => { + tx.oncomplete = resolve; + tx.onabort = reject; + tx.commit(); + }); + + // Fail-fast when non-empty rootUpdates exist and no extractSubdocIds callback is configured. + const unconfigured = createIdbV1ReadonlyReader({ + workspaceId: 'ws', + indexedDB: idb, + }); + await assert.rejects(() => unconfigured.listV1DocIds(), TypeError); + + // Injected extractSubdocIds discovers live subdocs and filters 3/4-segment userdata$ keys. + const reader = createIdbV1ReadonlyReader({ + workspaceId: 'ws', + indexedDB: idb, + extractSubdocIds: rootUpdates => { + assert.equal(rootUpdates.length, 2); + return ['live-guid']; + }, + }); + assert.deepEqual(await reader.listV1DocIds(), [ + 'ws', + 'live-guid', + 'userdata$u$ws', + 'userdata$u$ws$fav', + ]); + + // bootWebHost forwards env.mergeUpdates / env.extractSubdocIds and supports dynamic setCrdtCodecs(). + const host = await bootWebHost({ + win: { + navigator: { gpu: {} }, + location: { href: 'https://app.affine.pro/', assign() {} }, + }, + doc: { + createElement: () => ({ getContext: () => ({}) }), + getElementById: id => + id === 'affine-build-manifest' + ? { + textContent: JSON.stringify({ + shellVersion: 'mobile-v1', + buildHash: 'm5', + appEntryJs: null, + workers: {}, + fonts: {}, + }), + } + : null, + }, + indexedDB: idb, + BroadcastChannelImpl, + space: { flavour: 'local', type: 'workspace', id: 'ws' }, + }); + await assert.rejects(() => host.v1Reader.listV1DocIds(), TypeError); + host.setCrdtCodecs({ + mergeUpdates: testMergeFrames, + extractSubdocIds: () => ['live-guid'], + }); + assert.deepEqual(await host.v1Reader.listV1DocIds(), [ + 'ws', + 'live-guid', + 'userdata$u$ws', + 'userdata$u$ws$fav', + ]); + host.dispose(); +}); + +void test('empty flush microtask race and throwing post-commit update listener never drop or duplicate writes', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + let fakeNow = 1_780_000_000_000; + const encoder = new TextEncoder(); + + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-r5-flush', + indexedDB: idb, + BroadcastChannelImpl, + now: () => ++fakeNow, + }); + const flusher = createPendingWriteFlusher(storage); + + // 1. Empty flush() followed in same microtask turn by enqueue(B) + flushBeforeNavigation + // must persist B before navigation callback runs. + let navCheckPromise = null; + await flusher.flush().then(async () => { + flusher.enqueue({ docId: 'doc-b', bin: encoder.encode('b') }); + const navRes = await flushBeforeNavigation({ + pauseInput() {}, + resumeInput() {}, + flushPendingWrites: () => flusher.flush(), + navigate: () => { + navCheckPromise = storage.getDocRaw('doc-b'); + }, + }); + assert.equal(navRes.navigated, true); + }); + const docBAtNav = await navCheckPromise; + assert.equal(docBAtNav?.updates.length, 1); + assert.equal(flusher.pendingCount(), 0); + + // 2. Throwing updateListener after IDB commit must NOT fail flush() or cause duplicate persistence on next flush. + const unsubBad = storage.subscribeDocUpdate(() => { + throw new Error('subscriber boom'); + }); + flusher.enqueue({ docId: 'doc-sub', bin: encoder.encode('once') }); + const r1 = await flusher.flush(); + assert.equal(r1.ok, true); + assert.equal(flusher.pendingCount(), 0); + unsubBad(); + const r2 = await flusher.flush(); + assert.equal(r2.ok, true); + assert.equal((await storage.getDocRaw('doc-sub')).updates.length, 1); + + storage.close(); +}); + +void test('idb-storage v3 schema stays 1:1 locked to packages/common/nbstore/src/impls/idb/schema.ts and read-only lookups never create empty databases', async () => { + const { readFileSync } = await import('node:fs'); + const { fileURLToPath } = await import('node:url'); + const { resolve } = await import('node:path'); + const nbstoreSchemaPath = resolve( + fileURLToPath(new URL('.', import.meta.url)), + '../../../../common/nbstore/src/impls/idb/schema.ts' + ); + const schemaSrc = readFileSync(nbstoreSchemaPath, 'utf8'); + + const migMatch = schemaSrc.match( + /const\s+migrations\s*:\s*Migrate\[\]\s*=\s*\[([^\]]+)\]/ + ); + assert.ok(migMatch, 'Must find migrations array in nbstore schema.ts'); + const migItems = migMatch[1] + .split(',') + .map(s => s.trim()) + .filter(Boolean); + assert.equal( + migItems.length, + IDB_SCHEMA_VERSION, + `Expected nbstore migrations length (${migItems.length}) === IDB_SCHEMA_VERSION (${IDB_SCHEMA_VERSION})` + ); + + const nbStores = new Map(); + const storeRegex = + /(?:const\s+(\w+)\s*=\s*)?db\.createObjectStore\(\s*'([^']+)'(?:\s*,\s*\{([^}]*)\})?\s*\)/g; + for (const m of schemaSrc.matchAll(storeRegex)) { + const varName = m[1] || null; + const storeName = m[2]; + const body = m[3] || ''; + let keyPath = null; + const arrKp = body.match(/keyPath\s*:\s*\[([^\]]+)\]/); + const strKp = body.match(/keyPath\s*:\s*'([^']+)'/); + if (arrKp) { + keyPath = arrKp[1] + .split(',') + .map(s => s.trim().replace(/^'|'$/g, '')) + .filter(Boolean); + } else if (strKp) { + keyPath = strKp[1]; + } + const autoIncMatch = body.match(/autoIncrement\s*:\s*(true|false)/); + const autoIncrement = autoIncMatch ? autoIncMatch[1] === 'true' : false; + nbStores.set(storeName, { + varName, + keyPath, + autoIncrement, + indexes: new Map(), + }); + } + const indexRegex = + /(\w+)\.createIndex\(\s*'([^']+)'\s*,\s*(\[[^\]]+\]|'[^']+')\s*,\s*\{([^}]*)\}\s*\)/g; + for (const m of schemaSrc.matchAll(indexRegex)) { + const targetVar = m[1]; + const indexName = m[2]; + const rawKp = m[3].trim(); + const keyPath = rawKp.startsWith('[') + ? rawKp + .slice(1, -1) + .split(',') + .map(s => s.trim().replace(/^'|'$/g, '')) + .filter(Boolean) + : rawKp.replace(/^'|'$/g, ''); + const unique = /unique\s*:\s*true/.test(m[4]); + const owner = [...nbStores.values()].find(s => s.varName === targetVar); + assert.ok( + owner, + `Index ${indexName} owner variable ${targetVar} not found` + ); + owner.indexes.set(indexName, { keyPath, unique }); + } + + assert.deepEqual([...nbStores.keys()].sort(), [...IDB_STORE_NAMES].sort()); + + const idb = createMemoryIdbFactory(); + const verifyStorage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'schema-check', + indexedDB: idb, + }); + const liveDb = await verifyStorage.open(); + assert.equal(liveDb.version, IDB_SCHEMA_VERSION); + const rawMeta = idb.getMeta('local:workspace:schema-check'); + for (const [storeName, expected] of nbStores.entries()) { + const actual = rawMeta.stores.get(storeName); + assert.ok(actual, `Missing store ${storeName} in idb-storage.js`); + assert.deepEqual( + actual.keyPath, + expected.keyPath, + `keyPath mismatch on ${storeName}` + ); + assert.equal( + actual.autoIncrement, + expected.autoIncrement, + `autoIncrement mismatch on ${storeName}` + ); + assert.deepEqual( + [...actual.indexes.keys()].sort(), + [...expected.indexes.keys()].sort(), + `index names mismatch on ${storeName}` + ); + for (const [idxName, expIdx] of expected.indexes.entries()) { + const actIdx = actual.indexes.get(idxName); + assert.deepEqual(actIdx.keyPath, expIdx.keyPath); + assert.equal(actIdx.unique, expIdx.unique); + } + } + verifyStorage.close(); + + // Navigating to an unknown/cloud workspace URL on bootWebHost + openDoc MUST NOT create an empty local IndexedDB. + const freshIdb = createMemoryIdbFactory(); + const hostDoc = { + createElement: () => ({ + getContext: type => (type === 'webgl2' ? {} : null), + }), + getElementById: id => { + if (id === 'affine-build-manifest') { + return { + textContent: JSON.stringify({ + shellVersion: 'mobile-v1', + shell_build_id: 'noidbcheck12', + assetBaseUrl: '/mobile/', + mainWasmJs: '/pkg/playground.js', + }), + }; + } + if (id === 'app-canvas') { + return { + getContext: type => (type === 'webgl2' ? {} : null), + addEventListener() {}, + removeEventListener() {}, + }; + } + return null; + }, + querySelectorAll: () => [], + }; + let freedCount = 0; + const host = await bootWebHost({ + win: { + indexedDB: freshIdb, + navigator: {}, + location: { + href: 'https://app.affine.pro/workspace/cloud-ws-unregistered/doc-404', + assign() {}, + replace() {}, + }, + }, + doc: hostDoc, + importModule: async () => ({ + WasmLocalDocSession: class { + free() { + freedCount += 1; + } + }, + merge_updates_v1: u => u[0] || new Uint8Array(), + extract_subdoc_ids: () => [], + }), + }); + const missingOpen = await host.openDoc('doc-404'); + assert.equal(missingOpen, null); + assert.equal(freedCount, 1); + assert.deepEqual( + await freshIdb.databases(), + [], + 'Read-only openDoc on non-existent workspace must create 0 IndexedDB databases' + ); + host.dispose(); + + // Same-origin dual-tab concurrent `?create=1` (`openDoc(..., { createIfMissing })`) + // on an empty document persists ONLY ONE initialization update, converges both tabs + // onto the single winning content, and stays identical across reload. + const sharedRaceIdb = createMemoryIdbFactory(); + const sharedBus = createBroadcastBus(); + const seedWs = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-dual-create', + indexedDB: sharedRaceIdb, + BroadcastChannelImpl: sharedBus.BroadcastChannel, + }); + await seedWs.open(); + seedWs.close(); + + const tabAStorageBase = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-dual-create', + indexedDB: sharedRaceIdb, + BroadcastChannelImpl: sharedBus.BroadcastChannel, + now: () => 1_700_000_000_000, + }); + const tabBStorageBase = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-dual-create', + indexedDB: sharedRaceIdb, + BroadcastChannelImpl: sharedBus.BroadcastChannel, + now: () => 1_700_000_000_000, + }); + + let bothEnteredRead = 0; + let releaseBothReads; + const bothReadsBarrier = new Promise(resolve => { + releaseBothReads = resolve; + }); + const wrapGatedStorage = base => ({ + ...base, + async getDocRaw(docId) { + const res = await base.getDocRaw(docId); + if (docId === 'doc-race-1' && bothEnteredRead < 2) { + bothEnteredRead += 1; + if (bothEnteredRead === 2) { + releaseBothReads(); + } + await bothReadsBarrier; + } + return res; + }, + }); + + const raceSessions = []; + class RaceFakeWasmSession { + constructor(docId, clientId) { + this.docId = docId; + this.clientId = clientId; + this.paragraphs = []; + this.freed = 0; + raceSessions.push(this); + } + initialize_page(title, firstParagraph) { + const line = `${title}:${firstParagraph}`; + this.paragraphs = [line]; + return new TextEncoder().encode(line); + } + apply_update_v1(bin) { + this.paragraphs.push(new TextDecoder().decode(bin)); + } + read_snapshot_json() { + return JSON.stringify({ paragraphs: this.paragraphs }); + } + free() { + this.freed += 1; + } + } + + const makeRaceHost = storage => + bootWebHost({ + win: { + indexedDB: sharedRaceIdb, + navigator: {}, + location: { + href: 'https://app.affine.pro/workspace/ws-dual-create/doc-race-1?create=1', + assign() {}, + replace() {}, + }, + }, + doc: hostDoc, + BroadcastChannelImpl: sharedBus.BroadcastChannel, + workspaceStorage: wrapGatedStorage(storage), + importModule: async () => ({ + WasmLocalDocSession: RaceFakeWasmSession, + merge_updates_v1: u => u[0] || new Uint8Array(), + extract_subdoc_ids: () => [], + }), + }); + + const [tabAHost, tabBHost] = await Promise.all([ + makeRaceHost(tabAStorageBase), + makeRaceHost(tabBStorageBase), + ]); + + try { + const [tabASession, tabBSession] = await Promise.all([ + tabAHost.openDoc('doc-race-1', { + createIfMissing: { title: 'Title A', firstParagraph: 'Init A' }, + }), + tabBHost.openDoc('doc-race-1', { + createIfMissing: { title: 'Title B', firstParagraph: 'Init B' }, + }), + ]); + + assert.ok(tabASession); + assert.ok(tabBSession); + const persistedRaceRaw = await tabAStorageBase.getDocRaw('doc-race-1'); + assert.ok(persistedRaceRaw); + assert.equal( + persistedRaceRaw.updates.length, + 1, + 'Concurrent createIfMissing across two tabs must persist exactly ONE initialization update' + ); + const winningText = new TextDecoder().decode(persistedRaceRaw.updates[0]); + assert.ok( + winningText === 'Title A:Init A' || winningText === 'Title B:Init B' + ); + assert.deepEqual(tabASession.getSnapshot().paragraphs, [winningText]); + assert.deepEqual(tabBSession.getSnapshot().paragraphs, [winningText]); + + const reloadedAfterRace = await tabBHost.openDoc('doc-race-1'); + assert.deepEqual(reloadedAfterRace.getSnapshot().paragraphs, [winningText]); + } finally { + tabAHost.dispose(); + tabBHost.dispose(); + tabAStorageBase.close(); + tabBStorageBase.close(); + } + assert.ok(raceSessions.every(s => s.freed === 1)); +}); + +for (const replaced of [false, true]) { + void test(`compactDocWithMerged ${replaced ? 'keeps all updates when a source key has new bytes' : 'deletes only the numeric and Date keys that it read'}`, async t => { + const idb = createIdbTestFactory(); + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: `ws-keycursor-${replaced}`, + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + }); + t.after(() => storage.close()); + + // Put numeric and Date createdAt keys directly into the `updates` store. + await storage.pushDocUpdate({ docId: 'd-other', bin: enc.encode('other') }); + const rawDb = await storage.open(); + const putUpdates = rows => + new Promise((resolve, reject) => { + const tx = rawDb.transaction(['updates'], 'readwrite'); + for (const [createdAt, text] of rows) { + tx.objectStore('updates').put({ + docId: 'd-k', + createdAt, + bin: enc.encode(text), + }); + } + tx.oncomplete = () => resolve(undefined); + tx.onerror = () => reject(tx.error); + tx.onabort = () => reject(tx.error); + tx.commit(); + }); + await putUpdates([ + [999, 'num-read'], + [new Date(1000), 'date-read'], + ]); + const source = await storage.getDocRaw('d-k'); + await putUpdates([ + [1001, 'num-late'], + [new Date(998), 'date-late-below'], + ]); + if (replaced) await putUpdates([[999, 'num-replaced']]); + + const res = await storage.compactDocWithMerged({ + docId: 'd-k', + mergedBin: enc.encode('merged-read'), + source, + }); + assert.deepEqual(res, { compacted: !replaced }); + + const after = await storage.getDocRaw('d-k'); + const remaining = after.updates.map(u => dec.decode(u)).sort(); + if (replaced) { + assert.equal(after.snapshot, null); + assert.equal(await storage.getDocTimestamp('d-k'), null); + assert.deepEqual(remaining, [ + 'date-late-below', + 'date-read', + 'num-late', + 'num-replaced', + ]); + } else { + assert.equal(dec.decode(after.snapshot), 'merged-read'); + assert.equal(after.snapshotUpdatedAt.getTime(), 1000); + assert.equal( + (await storage.getDocTimestamp('d-k')).timestamp.getTime(), + 1000 + ); + assert.deepEqual(remaining, ['date-late-below', 'num-late']); + } + + const other = await storage.getDocRaw('d-other'); + assert.equal(other.updates.length, 1); + assert.equal(dec.decode(other.updates[0]), 'other'); + }); +} + +for (const recreated of [false, true]) { + void test(`compaction rejects the source ${recreated ? 'after deletion and recreation' : 'after deletion'}`, async t => { + const idb = createIdbTestFactory(); + const workspaceId = `ws-compact-deleted-${recreated}`; + const connect = () => + createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: workspaceId, + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + const a = connect(); + const b = connect(); + t.after(() => { + a.close(); + b.close(); + }); + const docId = 'doc'; + const frame = value => ({ docId, bin: Uint8Array.of(value) }); + await a.pushDocUpdate(frame(9)); + const source = await a.getDocRaw(docId); + assert.equal(source.snapshot, null); + assert.deepEqual(source.updates, [Uint8Array.of(9)]); + + await b.deleteDoc(docId); + assert.equal(await b.getDocRaw(docId), null); + if (recreated) await b.pushDocUpdate(frame(10)); + const before = await b.getDocRaw(docId); + const timestamps = await b.getDocTimestamps(); + assert.deepEqual( + await a.compactDocWithMerged({ + docId, + mergedBin: Uint8Array.of(9), + source, + }), + { compacted: false } + ); + assert.deepEqual(await b.getDocRaw(docId), before); + assert.deepEqual(await b.getDocTimestamps(), timestamps); + if (recreated) { + assert.equal(before.snapshot, null); + assert.deepEqual(before.updates, [Uint8Array.of(10)]); + } else { + assert.equal(before, null); + assert.deepEqual(Object.keys(timestamps), []); + assert.equal(await b.getDocTimestamp(docId), null); + mockBroadcastChannel(t); + const desktop = await openDesktopStore([workspaceId], { + indexedDB: idb, + }); + assert.deepEqual(desktop.docIds(workspaceId), []); + } + }); +} + +void test('an update that another connection writes between two compactions survives, and the clock only goes up', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + const connect = async () => { + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-compact-race', + indexedDB: idb, + BroadcastChannelImpl, + now: () => 1_000, + }); + await storage.open(); + return storage; + }; + // `b` opens before `a` writes and reads nothing of `d`. + const [a, b] = [await connect(), await connect()]; + const frame = byte => ({ docId: 'd', bin: Uint8Array.of(byte) }); + const clocks = []; + const noteClock = async () => + clocks.push( + (await (await connect()).getDocTimestamp('d')).timestamp.getTime() + ); + + await a.writeDocOpsNow([frame(1), frame(2)]); + await noteClock(); + await a.compactDocWithMerged({ + docId: 'd', + mergedBin: Uint8Array.of(1, 2), + source: await a.getDocRaw('d'), + }); + const compacted = await a.getDocRaw('d'); + await b.writeDocOpsNow([frame(3)]); + await noteClock(); + const second = await a.compactDocWithMerged({ + docId: 'd', + mergedBin: Uint8Array.of(1, 2), + source: compacted, + }); + assert.equal(second.compacted, true); + await b.writeDocOpsNow([frame(4)]); + await noteClock(); + + const raw = await (await connect()).getDocRaw('d'); + assert.deepEqual([...raw.snapshot], [1, 2]); + assert.deepEqual( + raw.updates.map(bin => [...bin]), + [[3], [4]] + ); + assert.deepEqual(clocks, [1_001, 1_002, 1_003]); + assert.deepEqual( + raw.updateTimes.map(t => t.getTime()), + [1_002, 1_003] + ); +}); + +void test('a connection that writes right after another connection of the page compacted, with no task in between, writes after it', async () => { + const idb = createMemoryIdbFactory(); + // A channel that never delivers: only the page-wide times can tell `b`. + const silent = class { + postMessage() {} + addEventListener() {} + removeEventListener() {} + close() {} + }; + const connect = async () => { + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-same-page', + indexedDB: idb, + BroadcastChannelImpl: silent, + now: () => 1_000, + }); + await storage.open(); + return storage; + }; + const [a, b] = [await connect(), await connect()]; + const frame = byte => ({ docId: 'd', bin: Uint8Array.of(byte) }); + await a.writeDocOpsNow([frame(1), frame(2)]); + await a.compactDocWithMerged({ + docId: 'd', + mergedBin: Uint8Array.of(1, 2), + source: await a.getDocRaw('d'), + }); + await b.writeDocOpsNow([frame(3)]); + const raw = await b.getDocRaw('d'); + assert.deepEqual( + raw.updateTimes.map(t => t.getTime()), + [1_002] + ); + assert.deepEqual( + Object.entries(await a.getDocTimestamps(new Date(1_001))).map( + ([docId, ts]) => [docId, ts.getTime()] + ), + [['d', 1_002]] + ); +}); + +void test('getDocTimestamps gives each document the newest of its clock, snapshot time, and update keys', async () => { + const idb = createMemoryIdbFactory(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-newest', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + }); + await storage.open(); + const rawDb = await new Promise((resolve, reject) => { + const req = idb.open( + formatIdbName({ flavour: 'local', type: 'workspace', id: 'ws-newest' }), + IDB_SCHEMA_VERSION + ); + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + await new Promise((resolve, reject) => { + const tx = rawDb.transaction( + ['clocks', 'snapshots', 'updates'], + 'readwrite' + ); + const bin = Uint8Array.of(1); + tx.objectStore('clocks').put({ docId: 'clock', timestamp: new Date(30) }); + tx.objectStore('updates').put({ + docId: 'clock', + createdAt: new Date(10), + bin, + }); + tx.objectStore('clocks').put({ docId: 'update', timestamp: new Date(10) }); + tx.objectStore('updates').put({ + docId: 'update', + createdAt: new Date(40), + bin, + }); + tx.objectStore('snapshots').put({ + docId: 'snapshot', + bin, + createdAt: new Date(5), + updatedAt: new Date(50), + }); + tx.objectStore('updates').put({ + docId: 'old', + createdAt: new Date(20), + bin, + }); + tx.oncomplete = () => resolve(undefined); + tx.onerror = () => reject(tx.error); + tx.commit(); + }); + const times = await storage.getDocTimestamps(new Date(20)); + assert.deepEqual( + Object.fromEntries( + Object.entries(times).map(([docId, ts]) => [docId, ts.getTime()]) + ), + { clock: 30, update: 40, snapshot: 50 } + ); +}); + +void test('getAllDocsRaw selects documents by time, reads ordered frames in one transaction, and remembers clocks', async t => { + const options = { + flavour: 'local', + type: 'workspace', + id: 'ws-all-raw', + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1, + }; + const reader = createIdbWorkspaceStorage(options); + const writer = createIdbWorkspaceStorage(options); + t.after(() => { + reader.close(); + writer.close(); + }); + const db = await reader.open(); + await writer.open(); + const stores = ['clocks', 'snapshots', 'updates']; + const tx = db.transaction(stores, 'readwrite'); + const seeded = new Promise((resolve, reject) => { + tx.oncomplete = resolve; + tx.onabort = () => reject(tx.error); + }); + const clocks = tx.objectStore('clocks'); + clocks.put({ docId: 'deleted', timestamp: new Date(100) }); + clocks.put({ docId: 'positive-clock', timestamp: new Date(5) }); + const snapshots = tx.objectStore('snapshots'); + snapshots.put({ docId: 'root', updatedAt: 1, bin: Uint8Array.of(1) }); + snapshots.put({ docId: 'empty', updatedAt: 1, bin: new Uint8Array() }); + for (const [docId, updatedAt, bin] of [ + ['negative-snapshot', -1, Uint8Array.of(7)], + ['zero-snapshot', 0, Uint8Array.of(7)], + ['positive-clock', 0, Uint8Array.of(7)], + ['positive-update', 0, Uint8Array.of(7)], + ['positive-empty-update', -1, Uint8Array.of(7)], + ['positive-empty-snapshot', 5, new Uint8Array()], + ['invalid-snapshot', Infinity, Uint8Array.of(7)], + ]) { + snapshots.put({ docId, updatedAt, bin }); + } + const updates = tx.objectStore('updates'); + for (const [docId, createdAt, bin] of [ + ['root', 30, Uint8Array.of(5)], + ['root', 20, Uint8Array.of(3)], + ['child', 1, Uint8Array.of(6).buffer], + ['root', new Date(10), Uint8Array.of(2)], + ['root', 15, new Uint8Array()], + ['root', new Date(20), Uint8Array.of(4)], + ['empty', 10, new Uint8Array()], + ['zero-update', 0, Uint8Array.of(8)], + ['positive-clock', 0, Uint8Array.of(8)], + ['positive-update', 5, Uint8Array.of(8)], + ['positive-empty-update', 5, new Uint8Array()], + ['positive-empty-snapshot', 0, Uint8Array.of(8)], + ]) { + updates.put({ docId, createdAt, bin }); + } + tx.commit?.(); + await seeded; + + const transactions = t.mock.method(db, 'transaction'); + const docs = await reader.getAllDocsRaw(); + assert.deepEqual( + transactions.mock.calls.map(call => call.arguments), + [[stores, 'readonly']] + ); + transactions.mock.restore(); + assert.deepEqual( + docs, + new Map([ + ['root', [1, 2, 3, 4, 5].map(byte => Uint8Array.of(byte))], + ['child', [Uint8Array.of(6)]], + ['positive-clock', [Uint8Array.of(7), Uint8Array.of(8)]], + ['positive-update', [Uint8Array.of(7), Uint8Array.of(8)]], + ['positive-empty-update', [Uint8Array.of(7)]], + ['positive-empty-snapshot', [Uint8Array.of(8)]], + ]) + ); + assert.equal(await reader.getDocRaw('deleted'), null); + + const cleanup = db.transaction('clocks', 'readwrite'); + const removed = new Promise((resolve, reject) => { + cleanup.oncomplete = resolve; + cleanup.onabort = () => reject(cleanup.error); + }); + cleanup.objectStore('clocks').delete('deleted'); + cleanup.commit?.(); + await removed; + + const legacyDocs = new Map(); + for (const docId of Object.keys(await reader.getDocTimestamps())) { + const raw = await reader.getDocRaw(docId); + if (!raw) continue; + const frames = [raw.snapshot, ...raw.updates] + .filter(bin => bin?.byteLength > 0) + .map(bin => new Uint8Array(bin)); + if (frames.length) legacyDocs.set(docId, frames); + } + assert.deepEqual(docs, legacyDocs); + + await writer.writeDocOpsNow([{ docId: 'deleted', bin: Uint8Array.of(7) }]); + assert.deepEqual((await reader.getDocRaw('deleted')).updateTimes, [ + new Date(101), + ]); +}); + +void test('writeDocOpsNow writes each update after the stored times of its document and the times the storage read or wrote', async () => { + const idb = createMemoryIdbFactory(); + const BroadcastChannelImpl = createBroadcastBus(); + const space = { flavour: 'local', type: 'workspace', id: 'ws-now' }; + const clock = 1_000; + const storage = createIdbWorkspaceStorage({ + ...space, + indexedDB: idb, + BroadcastChannelImpl, + now: () => clock, + }); + await storage.open(); + await storage.pushDocUpdatesBatch([ + { docId: 'doc-a', bin: Uint8Array.of(1) }, + ]); + await storage.writeDocOpsNow([ + { docId: 'doc-a', bin: Uint8Array.of(2) }, + { docId: 'doc-a', bin: Uint8Array.of(3) }, + { docId: 'doc-b', bin: Uint8Array.of(4) }, + ]); + + const reopened = createIdbWorkspaceStorage({ + ...space, + indexedDB: idb, + BroadcastChannelImpl, + now: () => clock, + }); + await reopened.open(); + const clocks = await reopened.getDocTimestamps(); + await reopened.writeDocOpsNow([{ docId: 'doc-a', bin: Uint8Array.of(5) }]); + + for (const [docId, frames, last] of [ + ['doc-a', [[1], [2], [3], [5]], 1_003], + ['doc-b', [[4]], 1_000], + ]) { + const raw = await reopened.getDocRaw(docId); + assert.deepEqual( + raw.updates.map(bin => [...bin]), + frames, + docId + ); + assert.equal(raw.timestamp.getTime(), last, docId); + } + assert.deepEqual( + Object.fromEntries( + Object.entries(clocks).map(([id, ts]) => [id, ts.getTime()]) + ), + { 'doc-a': 1_002, 'doc-b': 1_000 } + ); +}); + +void test('writeDocOpsNow writes again, after a read of the stored times, a write that another page made first in the same millisecond', async t => { + const errors = []; + t.mock.method(console, 'error', (...args) => errors.push(args[0])); + const idb = createMemoryIdbFactory(); + // A second import is the storage module of another page. + const otherPage = await import('../src/idb-storage.js?other-page'); + const open = async (create = createIdbWorkspaceStorage) => { + const storage = create({ + flavour: 'local', + type: 'workspace', + id: 'ws-race', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + await storage.open(); + return storage; + }; + // Two pages with a channel of their own each: neither hears of the writes + // of the other. + const [first, second] = [ + await open(), + await open(otherPage.createIdbWorkspaceStorage), + ]; + const frame = byte => ({ docId: 'doc', bin: Uint8Array.of(byte) }); + + await Promise.all([ + first.writeDocOpsNow([frame(1)]), + second.writeDocOpsNow([frame(2), frame(3)]), + ]); + await Promise.all([ + first.pushDocUpdate(frame(4)), + first.writeDocOpsNow([frame(5)]), + second.writeDocOpsNow([frame(6)]), + ]); + + const raw = await (await open()).getDocRaw('doc'); + assert.deepEqual(raw.updates.map(bin => [...bin]).sort(), [ + [1], + [2], + [3], + [4], + [5], + [6], + ]); + const times = raw.updateTimes.map(t => t.getTime()); + assert.deepEqual( + times, + [...new Set(times)].sort((x, y) => x - y) + ); + assert.equal(errors.length, 1); +}); + +function failUpdateTransaction(tx) { + const objectStore = tx.objectStore.bind(tx); + const updates = objectStore('updates'); + const add = updates.add.bind(updates); + updates.add = record => { + add(record); + return add(record); + }; + tx.objectStore = name => (name === 'updates' ? updates : objectStore(name)); +} + +void test('closing the storage cancels a failed write and clears its retry before reopening', async t => { + const idb = createIdbTestFactory(); + t.mock.method(console, 'error', () => {}); + const scheduled = Promise.withResolvers(); + let timer = null; + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-closed', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + setTimeout: fn => { + timer = fn; + scheduled.resolve(fn); + return 1; + }, + clearTimeout: id => { + assert.equal(id, 1); + timer = null; + }, + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + let attempts = 0; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite' && ++attempts <= 2) failUpdateTransaction(tx); + return tx; + }); + + const frame = (docId, byte) => ({ docId, bin: Uint8Array.of(byte) }); + const written = storage.writeDocOpsNow([frame('old', 1)]); + const staleRetry = await scheduled.promise; + assert.equal(attempts, 2); + const rejected = assert.rejects(written, /IndexedDB storage was closed/); + storage.close(); + assert.equal(timer, null); + await rejected; + + await storage.open(); + staleRetry(); + await storage.writeDocOpsNow([frame('new', 2)]); + assert.equal(await storage.getDocRaw('old'), null); + assert.deepEqual((await storage.getDocRaw('new')).updates, [ + Uint8Array.of(2), + ]); +}); + +for (const phase of ['clock read', 'retry wait']) { + void test(`failed writes retry with fresh clocks when another write arrives during the ${phase}`, async t => { + const idb = createIdbTestFactory(); + mockBroadcastChannel(t); + t.mock.method(Date, 'now', () => 1_000); + const failures = []; + t.mock.method(console, 'error', (message, error) => { + if (message === 'IndexedDB write failed and is written again') { + failures.push(error); + } + }); + const scheduled = Promise.withResolvers(); + const second = Promise.withResolvers(); + const setTimeout = globalThis.setTimeout; + t.mock.method(globalThis, 'setTimeout', (fn, delay, ...args) => { + if (delay !== 250) return setTimeout(fn, delay, ...args); + scheduled.resolve(fn); + return 1; + }); + const opts = { + flavour: 'local', + type: 'workspace', + id: `ws-overlap-${phase}`, + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }; + let db; + const writer = await openDesktopStore([opts.id], { + indexedDB: { + open: (...args) => + new Proxy(idb.open(...args), { + set(request, name, callback) { + request[name] = + name === 'onsuccess' + ? () => { + db = request.result; + callback(); + } + : callback; + return true; + }, + }), + }, + }); + const otherPage = await import('../src/idb-storage.js?other-page'); + const peer = otherPage.createIdbWorkspaceStorage({ + ...opts, + BroadcastChannelImpl: createBroadcastBus(), + }); + t.after(() => { + db.close(); + peer.close(); + }); + const frame = (docId, byte) => ({ docId, bin: Uint8Array.of(byte) }); + await peer.pushDocUpdatesBatch([ + frame('alpha', 1), + frame('beta', 3), + frame('beta', 4), + ]); + + const transaction = db.transaction.bind(db); + const write = (docId, byte) => { + writer.pushUpdate(opts.id, docId, Uint8Array.of(byte)); + return writer.flush(); + }; + const writeBeta = () => second.resolve(write('beta', 5)); + let reads = 0; + let writes = 0; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readonly' && ++reads === 1 && phase === 'clock read') { + queueMicrotask(writeBeta); + } + if (mode === 'readwrite' && ++writes === 2 && phase === 'retry wait') { + failUpdateTransaction(tx); + } + return tx; + }); + + const first = write('alpha', 2); + if (phase === 'retry wait') { + const retry = await scheduled.promise; + writeBeta(); + retry(); + assert.equal(reads, 1, 'the retry waits while beta is in flight'); + } + await Promise.all([first, second.promise, writer.flush()]); + assert.equal(reads, 2); + assert.equal(failures.length, phase === 'clock read' ? 2 : 3); + assert.deepEqual((await peer.getDocRaw('alpha')).updates, [ + Uint8Array.of(1), + Uint8Array.of(2), + ]); + assert.deepEqual((await peer.getDocRaw('beta')).updates, [ + Uint8Array.of(3), + Uint8Array.of(4), + Uint8Array.of(5), + ]); + }); +} + +void test('the desktop store releases startup when a write throws before it starts', async t => { + t.mock.method(console, 'error', () => {}); + mockBroadcastChannel(t); + const store = await openDesktopStore(['ws-startup-error'], { + indexedDB: createIdbTestFactory(), + }); + store.pushUpdate('missing-workspace', 'doc', Uint8Array.of(1)); + await store.flush(); + await store.seeded; +}); + +void test('writeDocOpsNow writes again a failed transaction and the later deletions of its documents, in call order', async t => { + t.mock.method(console, 'error', () => {}); + const idb = createMemoryIdbFactory(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-retry', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + await storage.open(); + idb.failNextWriteTransaction(new Error('disk full')); + await Promise.all([ + storage.writeDocOpsNow([ + { docId: 'gone', bin: Uint8Array.of(1) }, + { docId: 'kept', bin: Uint8Array.of(2) }, + ]), + storage.writeDocOpsNow([ + { docId: 'gone', delete: true }, + { docId: 'other', bin: Uint8Array.of(3) }, + ]), + ]); + for (const [docId, frames] of [ + ['gone', null], + ['kept', [[2]]], + ['other', [[3]]], + ]) { + const raw = await storage.getDocRaw(docId); + assert.deepEqual(raw && raw.updates.map(bin => [...bin]), frames, docId); + } +}); + +const update = (docId, byte) => ({ docId, bin: Uint8Array.of(byte) }); +const remove = docId => ({ docId, delete: true }); + +async function openQuotaLimitedStorage(t, id) { + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + const warnings = t.mock.method(console, 'warn', () => {}); + const errors = t.mock.method(console, 'error', () => {}); + const failures = []; + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: `ws-quota-${id}`, + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + onDocWriteFailure: error => failures.push(error), + setTimeout: () => assert.fail('quota failures must not start a timer'), + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + const batches = []; + let full = true; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode !== 'readwrite') return tx; + const batch = []; + batches.push(batch); + const updates = tx.objectStore('updates'); + const objectStore = tx.objectStore.bind(tx); + const add = updates.add.bind(updates); + updates.add = record => { + batch.push(record.docId); + return add(record); + }; + tx.objectStore = name => (name === 'updates' ? updates : objectStore(name)); + if (full) { + tx.commit = () => { + Object.defineProperty(tx, 'error', { value: quota, writable: true }); + tx.abort(quota); + }; + } + return tx; + }); + + return { + storage, + quota, + batches, + failures, + warnings, + errors, + freeSpace: () => { + full = false; + }, + }; +} + +for (const resume of ['explicit retry', 'delete']) { + void test(`quota failures pause without a timer, keep new writes without a transaction, and replay them on ${resume}`, async t => { + const { storage, quota, batches, failures, warnings, errors, freeSpace } = + await openQuotaLimitedStorage(t, resume); + + await assert.rejects( + storage.writeDocOpsNow([update('root', 1), update('large', 2)]), + quota + ); + await assert.rejects(storage.retryPausedWrites(), quota); + assert.deepEqual(failures, [quota, quota]); + assert.equal(warnings.mock.callCount(), 1); + assert.equal(errors.mock.callCount(), 0); + assert.equal(await storage.getDocRaw('root'), null); + assert.equal(await storage.getDocRaw('large'), null); + + await assert.rejects(storage.writeDocOpsNow([update('large', 4)]), quota); + await assert.rejects(storage.writeDocOpsNow([update('large', 5)]), quota); + freeSpace(); + await assert.rejects(storage.writeDocOpsNow([update('root', 6)]), quota); + assert.equal(batches.length, 2); + + const replay = + resume === 'explicit retry' + ? storage.retryPausedWrites() + : storage.writeDocOpsNow([remove('large'), update('root', 3)]); + assert.deepEqual( + batches.at(-1), + resume === 'explicit retry' + ? ['root', 'large', 'large', 'large', 'root'] + : ['root', 'root', 'root'] + ); + await replay; + assert.equal(batches.length, 3); + assert.equal(storage.retryPausedWrites(), null); + assert.deepEqual( + (await storage.getDocRaw('root')).updates, + (resume === 'explicit retry' ? [1, 6] : [1, 6, 3]).map(byte => + Uint8Array.of(byte) + ) + ); + assert.deepEqual( + (await storage.getDocRaw('large'))?.updates, + resume === 'delete' ? undefined : [2, 4, 5].map(b => Uint8Array.of(b)) + ); + }); +} + +for (const count of [64, 256, 512]) { + void test(`quota failures start no transaction for ${count} new writes and an explicit retry restores them in order`, async t => { + const { storage, quota, batches, freeSpace } = + await openQuotaLimitedStorage(t, count); + const frames = Array.from({ length: count }, (_, index) => { + const bin = new Uint8Array(8 * 1024); + new DataView(bin.buffer).setUint32(0, index); + return bin; + }); + for (const bin of frames) { + await assert.rejects( + storage.writeDocOpsNow([{ docId: 'root', bin }]), + quota + ); + } + assert.equal(batches.length, 1); + + freeSpace(); + const replay = storage.retryPausedWrites(); + assert.equal(batches.at(-1).length, count); + await replay; + const restored = (await storage.getAllDocsRaw()).get('root'); + assert.deepEqual(restored, frames); + t.diagnostic( + `Started ${batches.length} transactions for ${count} writes and restored ${restored.length}/${count} frames` + ); + }); +} + +const blob = (blobKey, bytes) => ({ blobKey, data: Uint8Array.from(bytes) }); + +for (const batching of ['same batch', 'separate batches']) { + void test(`quota replay clears old frames and keeps a recreated document in ${batching}`, async t => { + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + t.mock.method(console, 'warn', () => {}); + const options = { + flavour: 'local', + type: 'workspace', + id: 'ws-quota-recreate', + indexedDB: createMemoryIdbFactory(), + BroadcastChannelImpl: createBroadcastBus(), + }; + const storage = createIdbWorkspaceStorage(options); + t.after(() => storage.close()); + const db = await storage.open(); + await storage.writeDocOpsNow([update('page', 1)]); + + const transaction = db.transaction.bind(db); + const writes = []; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite') { + writes.push({ tx, commit: tx.commit.bind(tx) }); + tx.commit = () => {}; + } + return tx; + }); + const failed = assert.rejects( + storage.writeDocOpsNow([blob('image', [9]), update('page', 2)]), + quota + ); + const pending = storage.writeDocOpsNow([update('other', 3)]); + writes[0].tx.abort(quota); + await failed; + + await assert.rejects(storage.writeDocOpsNow([blob('image', [4])]), quota); + const rebuilt = update('page', 5); + const replay = storage.writeDocOpsNow( + batching === 'same batch' ? [remove('page'), rebuilt] : [remove('page')] + ); + if (batching === 'separate batches') { + await Promise.resolve(); + await assert.rejects(storage.writeDocOpsNow([rebuilt]), quota); + } + assert.equal(writes.length, 2); + + writes[1].commit(); + await pending; + assert.equal(writes.length, 3); + writes[2].commit(); + await replay; + storage.close(); + + const reopened = createIdbWorkspaceStorage(options); + t.after(() => reopened.close()); + assert.deepEqual(await storedBlobAndDoc(reopened, 'image', 'page'), { + blob: [4], + frames: [[5]], + clock: true, + }); + assert.deepEqual((await reopened.getDocRaw('other')).updates, [ + Uint8Array.of(3), + ]); + }); +} + +for (const [firstFailure, replacement] of [ + ['quota', 'quota'], + ['transient', 'commit'], + ['transient', 'quota'], + ['transient', 'close'], + ['transient', 'two commits'], + ['transient', 'commit then quota'], +]) { + void test(`blob write promises follow the replacement after a ${firstFailure} failure and ${replacement}`, async t => { + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + t.mock.method(console, 'warn', () => {}); + t.mock.method(console, 'error', () => {}); + const failed = Promise.withResolvers(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-blob-replacement', + indexedDB: createMemoryIdbFactory(), + BroadcastChannelImpl: createBroadcastBus(), + onDocWriteFailure: failed.resolve, + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + const writes = []; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite') { + writes.push({ tx, commit: tx.commit.bind(tx) }); + tx.commit = () => {}; + } + return tx; + }); + + const tick = () => new Promise(resolve => setImmediate(resolve)); + const split = + replacement.startsWith('two') || replacement.endsWith('then quota'); + let oldKeyReads = 0; + const oldBlob = { + get blobKey() { + oldKeyReads += 1; + return 'k'; + }, + data: new Uint8Array(8 * 1024 * 1024), + }; + let oldResult = 'pending'; + const old = storage + .writeDocOpsNow(split ? [oldBlob, blob('other', [1])] : [oldBlob]) + .then( + () => (oldResult = 'committed'), + error => (oldResult = error) + ); + const newer = () => + storage.writeDocOpsNow([blob('k', [2])]).catch(error => error); + let next; + if (firstFailure === 'quota') { + next = newer(); + writes[0].tx.abort(quota); + await tick(); + assert.equal(oldResult, quota); + } else { + writes[0].tx.abort(new Error('Aborted')); + await failed.promise; + next = newer(); + await tick(); + assert.equal(oldResult, 'pending'); + } + + const readsAfterReplacement = oldKeyReads; + const other = storage + .writeDocOpsNow([blob('other', [3])]) + .catch(error => error); + assert.equal(oldKeyReads, readsAfterReplacement); + if (replacement === 'close') { + storage.close(); + writes[1].tx.abort(); + writes[2].tx.abort(); + assert.match((await old).message, /storage was closed/); + assert.equal(await next, oldResult); + assert.equal(await other, oldResult); + return; + } + if (replacement === 'quota') { + writes[1].tx.abort(quota); + writes[2]?.tx.abort(quota); + assert.equal(await old, quota); + assert.equal(await next, quota); + assert.equal(await other, quota); + assert.deepEqual(await storage.getAllBlobsRaw(), new Map()); + return; + } + writes[1].commit(); + assert.equal(await next, undefined); + if (!split) { + assert.equal(await old, 'committed'); + } else { + assert.equal(oldResult, 'pending'); + if (replacement === 'commit then quota') { + writes[2].tx.abort(quota); + assert.equal(await old, quota); + assert.equal(await other, quota); + assert.deepEqual( + await storage.getAllBlobsRaw(), + new Map([['k', Uint8Array.of(2)]]) + ); + return; + } + } + writes[2].commit(); + assert.equal(await other, undefined); + assert.equal(await old, 'committed'); + assert.deepEqual( + await storage.getAllBlobsRaw(), + new Map([ + ['k', Uint8Array.of(2)], + ['other', Uint8Array.of(3)], + ]) + ); + }); +} + +void test('8192 document edits do not scan failed blob writes while quota is paused', async t => { + const { storage, quota, batches } = await openQuotaLimitedStorage( + t, + 'no-blob-scan' + ); + let blobKeyReads = 0; + await assert.rejects( + storage.writeDocOpsNow([ + { + get blobKey() { + blobKeyReads += 1; + return 'k'; + }, + data: Uint8Array.of(1), + }, + ]), + quota + ); + const readsAfterFailure = blobKeyReads; + const start = performance.now(); + for (let batch = 0; batch < 2; batch += 1) { + for (let i = 0; i < 4096; i += 1) { + const result = await storage + .writeDocOpsNow([update('page', i)]) + .catch(error => error); + assert.equal(result, quota); + } + } + t.diagnostic( + `Queued 4096 + 4096 edits in ${Math.round(performance.now() - start)} ms` + ); + assert.equal(blobKeyReads, readsAfterFailure); + assert.equal(batches.length, 1); +}); + +async function storedBlobAndDoc(storage, key, docId) { + const [blobs, docs, times] = await Promise.all([ + storage.getAllBlobsRaw(), + storage.getAllDocsRaw(), + storage.getDocTimestamps(), + ]); + return { + blob: blobs.get(key) && [...blobs.get(key)], + frames: docs.get(docId)?.map(bin => [...bin]), + clock: docId in times, + }; +} + +for (const [name, error] of [ + ['an aborted', new Error('aborted')], + [ + 'a quota-blocked', + new DOMException('Storage is full', 'QuotaExceededError'), + ], +]) { + void test(`${name} transaction rolls back a blob op with its document updates and clocks`, async t => { + t.mock.method(console, 'warn', () => {}); + t.mock.method(console, 'error', () => {}); + let retry = null; + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: `ws-blob-atomic-${name}`, + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + setTimeout: callback => { + retry = callback; + return 1; + }, + clearTimeout: () => {}, + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + const scopes = []; + let fail = true; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode !== 'readwrite') return tx; + scopes.push([...stores].sort()); + if (fail) tx.commit = () => tx.abort(error); + return tx; + }); + const write = storage.writeDocOpsNow([ + blob('image', [1, 2, 3]), + update('page', 4), + ]); + if (error.name === 'QuotaExceededError') { + await assert.rejects(write, error); + } else { + while (!retry) await new Promise(resolve => setImmediate(resolve)); + } + assert.ok(scopes.length >= 1); + for (const scope of scopes) { + assert.deepEqual(scope, [ + 'blobData', + 'blobs', + 'clocks', + 'snapshots', + 'updates', + ]); + } + assert.deepEqual(await storedBlobAndDoc(storage, 'image', 'page'), { + blob: undefined, + frames: undefined, + clock: false, + }); + + fail = false; + if (retry) { + retry(); + await write; + } else { + await storage.retryPausedWrites(); + } + assert.deepEqual(await storedBlobAndDoc(storage, 'image', 'page'), { + blob: [1, 2, 3], + frames: [[4]], + clock: true, + }); + }); +} + +void test('after a quota failure, new bytes of a blob replace its older failed bytes, and a retry under the same quota writes only the newest bytes', async t => { + const quota = new DOMException('Storage is full', 'QuotaExceededError'); + t.mock.method(console, 'warn', () => {}); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-blob-quota-replace', + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + setTimeout: () => assert.fail('quota failures must not start a timer'), + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + const puts = []; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode !== 'readwrite') return tx; + const batch = []; + puts.push(batch); + const objectStore = tx.objectStore.bind(tx); + tx.objectStore = name => { + const store = objectStore(name); + if (name === 'blobData') { + const put = store.put.bind(store); + store.put = record => { + batch.push(record.data.byteLength); + return put(record); + }; + } + return store; + }; + const commit = tx.commit.bind(tx); + tx.commit = () => { + if (batch.reduce((sum, size) => sum + size, 0) <= 1024 * 1024) { + return commit(); + } + Object.defineProperty(tx, 'error', { value: quota, writable: true }); + tx.abort(quota); + }; + return tx; + }); + + await assert.rejects( + storage.writeDocOpsNow([ + { blobKey: 'k', data: new Uint8Array(8 * 1024 * 1024) }, + update('page', 1), + ]), + quota + ); + for (let byte = 2; byte <= 8; byte++) { + await assert.rejects( + storage.writeDocOpsNow([ + { blobKey: 'k', data: new Uint8Array(1024 * 1024) }, + update('page', byte), + ]), + quota + ); + } + await assert.rejects( + storage.writeDocOpsNow([blob('k', [7]), update('page', 9)]), + quota + ); + await storage.retryPausedWrites(); + assert.deepEqual(puts, [[8 * 1024 * 1024], [1]]); + assert.deepEqual(await storedBlobAndDoc(storage, 'k', 'page'), { + blob: [7], + frames: Array.from({ length: 9 }, (_, i) => [i + 1]), + clock: true, + }); +}); + +void test('a committed blob op supersedes an older failed op of the same blob', async t => { + t.mock.method(console, 'error', () => {}); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-blob-supersede', + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + t.after(() => storage.close()); + const db = await storage.open(); + const transaction = db.transaction.bind(db); + t.mock.method( + db, + 'transaction', + (stores, mode) => { + const tx = transaction(stores, mode); + tx.commit = () => tx.abort(new Error('aborted')); + return tx; + }, + { times: 1 } + ); + await Promise.all([ + storage.writeDocOpsNow([blob('image', [1]), update('page', 1)]), + storage.writeDocOpsNow([blob('image', [2])]), + ]); + assert.deepEqual(await storedBlobAndDoc(storage, 'image', 'page'), { + blob: [2], + frames: [[1]], + clock: true, + }); +}); + +void test('getAllBlobsRaw reads every stored blob that is not deleted in one transaction', async t => { + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-blob-read', + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + }); + t.after(() => storage.close()); + assert.deepEqual(await storage.getAllBlobsRaw(), new Map()); + const db = await storage.open(); + await storage.writeDocOpsNow([blob('a', [1]), blob('b', [2, 3])]); + await storage.setBlob({ + key: 'c', + mime: 'image/png', + data: Uint8Array.of(4), + }); + const tx = db.transaction('blobs', 'readwrite'); + tx.objectStore('blobs').put({ key: 'c', deletedAt: new Date(1) }); + const deleted = new Promise(resolve => { + tx.oncomplete = resolve; + }); + tx.commit?.(); + await deleted; + const transaction = db.transaction.bind(db); + const reads = t.mock.method(db, 'transaction', transaction); + const blobs = await storage.getAllBlobsRaw(); + assert.equal(reads.mock.callCount(), 1); + assert.deepEqual( + [...blobs].map(([key, data]) => [key, [...data]]), + [ + ['a', [1]], + ['b', [2, 3]], + ] + ); +}); + +for (const [name, ops, frames] of [ + ['delete', [remove('note')], [[3], [4]]], + ['delete then put', [remove('note'), update('note', 2)], [[2], [3], [4]]], + ['put then delete', [update('note', 2), remove('note')], [[3], [4]]], +]) { + void test(`a committed ${name} supersedes older failed ops and keeps later writes`, async t => { + t.mock.method(console, 'error', () => {}); + const opts = { + flavour: 'local', + type: 'workspace', + id: `ws-retry-${name}`, + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }; + const storage = createIdbWorkspaceStorage(opts); + const peer = createIdbWorkspaceStorage(opts); + const reader = createIdbWorkspaceStorage(opts); + t.after(() => { + storage.close(); + peer.close(); + reader.close(); + }); + const db = await storage.open(); + await peer.open(); + const transaction = db.transaction.bind(db); + let attempts = 0; + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + if (mode === 'readwrite' && [1, 3].includes(++attempts)) { + failUpdateTransaction(tx); + } + return tx; + }); + + const older = storage.writeDocOpsNow([ + update('note', 1), + remove('note'), + update('other', 5), + ]); + const deleted = storage.writeDocOpsNow(ops); + const later = storage.writeDocOpsNow([update('note', 4)]); + await deleted; + await peer.writeDocOpsNow([update('note', 3)]); + await Promise.all([older, later]); + + const raw = await reader.getDocRaw('note'); + assert.deepEqual( + raw.updates.map(bin => [...bin]), + frames + ); + assert.deepEqual((await reader.getDocRaw('other')).updates, [ + Uint8Array.of(5), + ]); + }); +} + +void test('a failed delete retries and preserves the updates that committed after it', async t => { + t.mock.method(console, 'error', () => {}); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-retry-failed-delete', + indexedDB: createIdbTestFactory(), + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + t.after(() => storage.close()); + const db = await storage.open(); + await storage.writeDocOpsNow([update('note', 1)]); + const transaction = db.transaction.bind(db); + t.mock.method( + db, + 'transaction', + (stores, mode) => { + const tx = transaction(stores, mode); + failUpdateTransaction(tx); + return tx; + }, + { times: 1 } + ); + await Promise.all([ + storage.writeDocOpsNow([update('other', 2), remove('note')]), + storage.writeDocOpsNow([update('note', 3)]), + ]); + assert.deepEqual((await storage.getDocRaw('note')).updates, [ + Uint8Array.of(3), + ]); + assert.deepEqual((await storage.getDocRaw('other')).updates, [ + Uint8Array.of(2), + ]); +}); + +void test('writeDocOpsNow applies deletions and updates in order', async () => { + const idb = createMemoryIdbFactory(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-delete', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + await storage.open(); + await storage.writeDocOpsNow([ + { docId: 'kept', bin: Uint8Array.of(1) }, + { docId: 'gone', bin: Uint8Array.of(2) }, + { docId: 'again', bin: Uint8Array.of(3) }, + ]); + await storage.writeDocOpsNow([ + { docId: 'gone', delete: true }, + { docId: 'again', delete: true }, + { docId: 'again', bin: Uint8Array.of(4) }, + ]); + for (const [docId, frames] of [ + ['kept', [[1]]], + ['gone', null], + ['again', [[4]]], + ]) { + const raw = await storage.getDocRaw(docId); + assert.deepEqual(raw && raw.updates.map(bin => [...bin]), frames, docId); + } + assert.deepEqual(Object.keys(await storage.getDocTimestamps()).sort(), [ + 'again', + 'kept', + ]); +}); diff --git a/packages/frontend/hosts/web/tests/legacy-workspace-readiness.browser.mjs b/packages/frontend/hosts/web/tests/legacy-workspace-readiness.browser.mjs new file mode 100644 index 0000000000..d652ccedf4 --- /dev/null +++ b/packages/frontend/hosts/web/tests/legacy-workspace-readiness.browser.mjs @@ -0,0 +1,779 @@ +// @ts-check + +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { createServer } from 'node:http'; +import test from 'node:test'; + +import * as Y from 'yjs'; + +import { + closeBrowserResources, + connectBrowserTarget, + createChromiumHarness, + openPageTarget, + withIsolatedPage, +} from '../scripts/chromium-harness.mjs'; +import { + listLegacyWorkspaceDatabases, + verifyLegacyWorkspaceReadiness, +} from '../scripts/legacy-workspace-readiness.mjs'; +import { connectCdpTarget } from '../scripts/verify-canary-dual-shell-e2e.mjs'; + +/** + * Encodes a real Yjs root workspace update whose `meta.pages` lists `docIds`. + * + * @param {string[]} docIds + * @returns {number[]} + */ +function encodeRootDocUpdate(docIds) { + const doc = new Y.Doc(); + const meta = doc.getMap('meta'); + const pages = new Y.Array(); + for (const id of docIds) { + const entry = new Y.Map(); + entry.set('id', id); + entry.set('title', 'Workspace Doc'); + pages.push([entry]); + } + meta.set('pages', pages); + return Array.from(Y.encodeStateAsUpdate(doc)); +} + +/** + * Encodes a real Yjs page document update with the requested block flavour. + * + * @param {string} flavour + * @returns {number[]} + */ +function encodePageDocUpdate(flavour) { + const doc = new Y.Doc(); + const blocks = doc.getMap('blocks'); + const pageBlock = new Y.Map(); + pageBlock.set('sys:id', 'block-root'); + pageBlock.set('sys:flavour', flavour); + blocks.set('block-root', pageBlock); + return Array.from(Y.encodeStateAsUpdate(doc)); +} + +/** + * Returns a page expression that seeds a `local:workspace:` IndexedDB + * database inside the current origin. + * + * @param {string} wsId + * @param {Array<{ store: 'snapshots' | 'updates', docId: string, bin: number[], createdAt?: number }>} records + */ +function seedWorkspaceScript(wsId, records) { + return `(async () => { + const dbName = ${JSON.stringify('local:workspace:' + wsId)}; + const records = ${JSON.stringify(records)}; + const db = await new Promise((resolve, reject) => { + const req = indexedDB.open(dbName, 3); + req.onupgradeneeded = () => { + const d = req.result; + if (!d.objectStoreNames.contains('snapshots')) { + d.createObjectStore('snapshots', { keyPath: 'docId' }); + } + if (!d.objectStoreNames.contains('updates')) { + const store = d.createObjectStore('updates', { keyPath: ['docId', 'createdAt'] }); + store.createIndex('docId', 'docId', { unique: false }); + } + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + try { + const tx = db.transaction(['snapshots', 'updates'], 'readwrite'); + for (const rec of records) { + const bytes = Uint8Array.from(rec.bin); + if (rec.store === 'snapshots') { + tx.objectStore('snapshots').put({ + docId: rec.docId, + bin: bytes, + createdAt: new Date(rec.createdAt ?? 1000), + updatedAt: new Date(rec.createdAt ?? 1000), + }); + } else { + tx.objectStore('updates').put({ + docId: rec.docId, + bin: bytes, + createdAt: new Date(rec.createdAt ?? 2000), + }); + } + } + await new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(true); + tx.onabort = () => reject(tx.error || new Error('seed tx aborted')); + tx.onerror = () => reject(tx.error || new Error('seed tx error')); + }); + } finally { + db.close(); + } + })()`; +} + +/** + * Seeds a `local:workspace:` IndexedDB database inside the current origin. + * + * @param {any} tab + * @param {string} wsId + * @param {Parameters[1]} records + */ +async function seedWorkspaceDb(tab, wsId, records) { + await tab.evalJs(seedWorkspaceScript(wsId, records)); +} + +/** + * Returns root catalog and page records for a workspace whose catalog lists + * `docIds` and whose page documents each hold an `affine:page` block. + * + * @param {string} wsId + * @param {string[]} docIds + * @returns {Parameters[1]} + */ +function workspaceRecords(wsId, docIds) { + return [ + { store: 'snapshots', docId: wsId, bin: encodeRootDocUpdate(docIds) }, + ...docIds.map(docId => ({ + store: /** @type {const} */ ('updates'), + docId, + bin: encodePageDocUpdate('affine:page'), + })), + ]; +} + +/** + * Starts a local HTTP server and returns its base URL. + * + * @param {import('node:http').RequestListener} handler + */ +async function startMockServer(handler) { + const server = createServer(handler); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => resolve(undefined)); + }); + const addr = server.address(); + assert.ok(addr && typeof addr === 'object'); + return { server, baseUrl: `http://127.0.0.1:${addr.port}` }; +} + +/** + * Renders an editor HTML page matching frozen `@affine/mobile 0.27.5` selectors. + * + * @param {string} docId + * @param {string} [extraScript] + */ +function editorHtml(docId, extraScript = '') { + return ` + + +
+
+ Mounted +
+
+ ${extraScript} + +`; +} + +await test('legacy workspace readiness rejects negative cases and passes positive cases with zero leaks', async t => { + let hungRequestSeen = false; + const negativeCases = [ + { + name: 'negative 1: stays on / showing visible clickable Retry button even when another local:workspace:other exists', + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb(tab, 'other', [ + { + store: 'snapshots', + docId: 'other', + bin: encodeRootDocUpdate(['doc-other']), + }, + { + store: 'updates', + docId: 'doc-other', + bin: encodePageDocUpdate('affine:page'), + }, + ]); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/?shell=legacy&case=retry-root', + }), + /not a valid \/workspace\/\/ path/ + ); + + const dbs = await listLegacyWorkspaceDatabases(tab); + assert.deepEqual( + dbs, + ['local:workspace:other'], + 'Must not create any extra empty workspace database' + ); + }, + }, + { + name: 'negative 2: editor-host DOM exists but IndexedDB has no database for wsId (and leaves no empty DB behind)', + async run(tab, baseUrl) { + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/missing-ws/doc-1?shell=legacy', + }), + /IndexedDB database does not exist: local:workspace:missing-ws/ + ); + + const dbs = await listLegacyWorkspaceDatabases(tab); + assert.deepEqual( + dbs, + [], + 'onupgradeneeded abort must not leave an empty database behind' + ); + }, + }, + { + name: 'negative 3: route wsId does not match the database stored in IndexedDB', + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb(tab, 'stored-ws', [ + { + store: 'snapshots', + docId: 'stored-ws', + bin: encodeRootDocUpdate(['doc-1']), + }, + { + store: 'updates', + docId: 'doc-1', + bin: encodePageDocUpdate('affine:page'), + }, + ]); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/route-ws/doc-1?shell=legacy', + }), + /IndexedDB database does not exist: local:workspace:route-ws/ + ); + + const dbs = await listLegacyWorkspaceDatabases(tab); + assert.deepEqual(dbs, ['local:workspace:stored-ws']); + }, + }, + { + name: 'negative 4a: root workspace DB exists but meta.pages is missing target docId', + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb(tab, 'ws-missing-doc', [ + { + store: 'snapshots', + docId: 'ws-missing-doc', + bin: encodeRootDocUpdate(['another-doc']), + }, + { + store: 'updates', + docId: 'target-doc', + bin: encodePageDocUpdate('affine:page'), + }, + ]); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/ws-missing-doc/target-doc?shell=legacy', + }), + /meta\.pages does not contain "target-doc"/ + ); + }, + }, + { + name: 'negative 4b: root workspace DB lists docId but page doc lacks affine:page block', + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb(tab, 'ws-no-page-flavour', [ + { + store: 'snapshots', + docId: 'ws-no-page-flavour', + bin: encodeRootDocUpdate(['doc-bad-flavour']), + }, + { + store: 'updates', + docId: 'doc-bad-flavour', + bin: encodePageDocUpdate('affine:paragraph'), + }, + ]); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: + '/workspace/ws-no-page-flavour/doc-bad-flavour?shell=legacy', + }), + /no block with sys:flavour === "affine:page"/ + ); + }, + }, + ...[ + { + name: 'negative 5: shell falls back to Retry before IndexedDB persistence', + delayMs: 0, + fallback: true, + }, + { + name: 'slow initial response: reports the Retry route after the editor mounts', + delayMs: 1100, + fallback: true, + }, + { + name: 'slow initial response: reports missing IndexedDB when the editor stays mounted', + delayMs: 1100, + fallback: false, + }, + ].map(({ name, delayMs, fallback }) => ({ + name, + serve(pathname, res, headers) { + if (pathname !== '/workspace/ws-lost/doc-lost') return false; + // The first read-only probe can move the shell to Retry before the write. + const respond = () => + res.writeHead(200, headers).end( + editorHtml( + 'doc-lost', + fallback + ? `` + : '' + ) + ); + if (delayMs) { + // Delay the document response to exceed the 900 ms readiness budget. + const timer = setTimeout(respond, delayMs); + res.once('close', () => clearTimeout(timer)); + } else { + respond(); + } + return true; + }, + async run(tab, baseUrl) { + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/ws-lost/doc-lost?shell=legacy', + }), + fallback + ? /Legacy shell lost the mounted document \/workspace\/ws-lost\/doc-lost: Legacy shell route "\/" is not a valid/ + : /IndexedDB database does not exist: local:workspace:ws-lost/ + ); + assert.deepEqual( + await listLegacyWorkspaceDatabases(tab), + fallback ? ['local:workspace:ws-lost'] : [] + ); + }, + })), + { + name: 'hung initial navigation: reports the pending document request', + serve(pathname) { + if (pathname !== '/hung') return false; + hungRequestSeen = true; + return true; + }, + async run(tab, baseUrl) { + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + navigationTimeoutMs: 1500, + entryPath: '/hung', + }), + { + message: `Legacy shell initial navigation timed out after 1500ms: ${baseUrl}/hung`, + } + ); + assert.ok(hungRequestSeen, 'The mock server must receive the request'); + }, + }, + { + name: 'negative 6: catalog document picked on /home redirects to another document of the workspace', + serve(pathname, res, headers) { + if (pathname === '/workspace/ws-redirect/home') { + res + .writeHead(200, headers) + .end('

Workspace Home

'); + return true; + } + if (pathname === '/workspace/ws-redirect/doc-a') { + res + .writeHead(302, { + ...headers, + Location: '/workspace/ws-redirect/doc-b', + }) + .end(); + return true; + } + return false; + }, + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb( + tab, + 'ws-redirect', + workspaceRecords('ws-redirect', ['doc-a', 'doc-b']) + ); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/ws-redirect/home?shell=legacy', + }), + /Legacy shell doc "doc-b" does not match expected "doc-a"/ + ); + }, + }, + { + name: 'negative 7: visible editor container without a mounted editor-host', + serve(pathname, res, headers) { + if (pathname !== '/workspace/ws-no-host/doc-no-host') return false; + res + .writeHead(200, headers) + .end( + '
Loading
' + ); + return true; + }, + async run(tab, baseUrl) { + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/ws-no-host/doc-no-host?shell=legacy', + }), + /Missing editor-host inside \[data-affine-editor-container\]\[data-testid="editor-doc-no-host"\]/ + ); + }, + }, + { + name: 'negative 8: updates row whose createdAt is not a Date', + async run(tab, baseUrl) { + await tab.send('Page.navigate', { url: `${baseUrl}/seed` }); + await seedWorkspaceDb(tab, 'ws-bad-row', [ + { + store: 'snapshots', + docId: 'ws-bad-row', + bin: encodeRootDocUpdate(['doc-bad-row']), + }, + ]); + await tab.evalJs(`new Promise((resolve, reject) => { + const req = indexedDB.open('local:workspace:ws-bad-row'); + req.onerror = () => reject(req.error); + req.onsuccess = () => { + const db = req.result; + const tx = db.transaction('updates', 'readwrite'); + tx.objectStore('updates').put({ + docId: 'doc-bad-row', + bin: Uint8Array.from(${JSON.stringify(encodePageDocUpdate('affine:page'))}), + createdAt: 2000, + }); + tx.oncomplete = () => { + db.close(); + resolve(true); + }; + tx.onerror = () => reject(tx.error); + }; + })`); + + await assert.rejects( + verifyLegacyWorkspaceReadiness(tab, baseUrl, { + timeoutMs: 900, + entryPath: '/workspace/ws-bad-row/doc-bad-row?shell=legacy', + }), + /updates row of "doc-bad-row" needs a non-empty Uint8Array bin and a Date createdAt/ + ); + }, + }, + ]; + + const negativeHarness = createChromiumHarness({ + tmpPrefix: 'affine-legacy-neg-', + }); + let browser; + try { + const port = await negativeHarness.launchChromium({ + args: ['--disable-gpu'], + }); + browser = await connectBrowserTarget(port); + for (const tc of negativeCases) { + await t.test(tc.name, async () => { + const started = await startMockServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + const headers = { + 'Content-Type': 'text/html; charset=utf-8', + 'Set-Cookie': 'affine_shell=legacy; Path=/', + }; + if (tc.serve?.(url.pathname, res, headers)) { + return; + } + if (url.pathname === '/seed') { + res + .writeHead(200, headers) + .end('
'); + return; + } + if (url.pathname === '/') { + res + .writeHead(200, headers) + .end( + '
' + ); + return; + } + const match = /^\/workspace\/([^/]+)\/([^/]+)$/.exec(url.pathname); + if (match) { + res.writeHead(200, headers).end(editorHtml(match[2])); + return; + } + res.writeHead(404).end(); + }); + try { + await withIsolatedPage(browser, connectCdpTarget, tab => + tc.run(tab, started.baseUrl) + ); + } finally { + // Close a mock connection even if it never sent response headers. + const closing = closeBrowserResources( + undefined, + undefined, + started.server + ); + started.server.closeAllConnections(); + await closing; + } + }); + } + const { browserContextIds } = await browser.send( + 'Target.getBrowserContexts' + ); + assert.deepEqual(browserContextIds, []); + } finally { + await closeBrowserResources(negativeHarness, browser); + assert.equal( + existsSync(negativeHarness.workTmp), + false, + `Chromium harness temp directory leaked: ${negativeHarness.workTmp}` + ); + } + + await t.test( + 'positive 1: direct arrival at /workspace// passes', + async () => { + let harness; + let tab; + let server; + let workTmp; + try { + const wsId = 'ws-direct'; + const docId = 'doc-direct-1'; + const rootBin = encodeRootDocUpdate([docId]); + const pageBin = encodePageDocUpdate('affine:page'); + + const started = await startMockServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + const headers = { + 'Content-Type': 'text/html; charset=utf-8', + 'Set-Cookie': 'affine_shell=legacy; Path=/', + }; + if (url.pathname === '/') { + res.writeHead(302, { + ...headers, + Location: `/workspace/${wsId}/${docId}`, + }); + res.end(); + return; + } + if (url.pathname === `/workspace/${wsId}/${docId}`) { + res.writeHead(200, headers).end( + editorHtml( + docId, + `` + ) + ); + return; + } + res.writeHead(404).end(); + }); + server = started.server; + harness = createChromiumHarness({ tmpPrefix: 'affine-legacy-p1-' }); + workTmp = harness.workTmp; + const port = await harness.launchChromium({ args: ['--disable-gpu'] }); + const target = await openPageTarget(port); + tab = await connectCdpTarget(target.webSocketDebuggerUrl); + + const result = await verifyLegacyWorkspaceReadiness( + tab, + started.baseUrl, + { timeoutMs: 5000 } + ); + assert.equal(result.wsId, wsId); + assert.equal(result.docId, docId); + assert.equal(result.navigatedFromHome, false); + assert.deepEqual(result.catalogDocIds, [docId]); + } finally { + await closeBrowserResources(harness, tab, server); + if (workTmp) { + assert.equal(existsSync(workTmp), false); + } + } + } + ); + + await t.test( + 'positive 2 & 3: fresh launch on /home navigates once to real docId, and same-profile reopen without welcome template keeps DB count unchanged', + async () => { + let harness; + let tab; + let reopenTab; + let server; + let workTmp; + let allowWelcomeTemplate = true; + let welcomeTemplateHitsDuringReopen = 0; + + try { + const wsId = 'ws-home-flow'; + const docId = 'doc-from-catalog'; + const rootBin = encodeRootDocUpdate([docId]); + const pageBin = encodePageDocUpdate('affine:page'); + + const started = await startMockServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + const headers = { + 'Content-Type': 'text/html; charset=utf-8', + 'Set-Cookie': 'affine_shell=legacy; Path=/', + }; + if (url.pathname === '/welcome-template.json') { + if (!allowWelcomeTemplate) { + welcomeTemplateHitsDuringReopen += 1; + res.writeHead(404).end('template disabled'); + return; + } + res + .writeHead(200, { 'Content-Type': 'application/json' }) + .end(JSON.stringify({ docId })); + return; + } + if (url.pathname === '/') { + res.writeHead(302, { + ...headers, + Location: `/workspace/${wsId}/home`, + }); + res.end(); + return; + } + if (url.pathname === `/workspace/${wsId}/home`) { + res.writeHead(200, headers).end(` +

Workspace Home

+ `); + return; + } + if (url.pathname === `/workspace/${wsId}/${docId}`) { + res.writeHead(200, headers).end(editorHtml(docId)); + return; + } + res.writeHead(404).end(); + }); + + server = started.server; + harness = createChromiumHarness({ tmpPrefix: 'affine-legacy-p23-' }); + workTmp = harness.workTmp; + const port = await harness.launchChromium({ args: ['--disable-gpu'] }); + + // Positive 2: fresh launch lands on /workspace//home and navigates once. + const target = await openPageTarget(port); + tab = await connectCdpTarget(target.webSocketDebuggerUrl); + const initial = await verifyLegacyWorkspaceReadiness( + tab, + started.baseUrl, + { timeoutMs: 5000 } + ); + assert.equal(initial.wsId, wsId); + assert.equal(initial.docId, docId); + assert.equal(initial.navigatedFromHome, true); + const dbNamesBeforeReopen = await listLegacyWorkspaceDatabases(tab); + assert.deepEqual(dbNamesBeforeReopen, [`local:workspace:${wsId}`]); + + // Positive 3: same profile reopens deep link with welcome template disabled. + allowWelcomeTemplate = false; + const reopenTarget = await openPageTarget(port); + reopenTab = await connectCdpTarget(reopenTarget.webSocketDebuggerUrl); + const reopened = await verifyLegacyWorkspaceReadiness( + reopenTab, + started.baseUrl, + { + mode: 'reopen', + timeoutMs: 5000, + expectedWsId: wsId, + expectedDocId: docId, + expectedWorkspaceDbCount: dbNamesBeforeReopen.length, + } + ); + assert.equal(reopened.wsId, wsId); + assert.equal(reopened.docId, docId); + assert.equal(reopened.navigatedFromHome, false); + assert.deepEqual(reopened.workspaceDbNames, dbNamesBeforeReopen); + assert.equal(welcomeTemplateHitsDuringReopen, 0); + } finally { + reopenTab?.close(); + await closeBrowserResources(harness, tab, server); + if (workTmp) { + assert.equal(existsSync(workTmp), false); + } + } + } + ); +}); diff --git a/packages/frontend/hosts/web/tests/memory-idb.mjs b/packages/frontend/hosts/web/tests/memory-idb.mjs new file mode 100644 index 0000000000..f046126095 --- /dev/null +++ b/packages/frontend/hosts/web/tests/memory-idb.mjs @@ -0,0 +1,563 @@ +// In-memory IndexedDB, BroadcastChannel, and Web Storage doubles shared by the +// Node tests of `src/idb-storage.js` and `desktop/start.js`. + +if (!globalThis.IDBKeyRange) { + globalThis.IDBKeyRange = { + bound: (lower, upper, lowerOpen = false, upperOpen = false) => ({ + lower, + upper, + lowerOpen, + upperOpen, + }), + }; +} + +/** + * Deterministic key serialization matching IndexedDB scalar, Date, and compound + * array keys for our W3C-semantics in-memory IDBFactory test harness. + */ +function serializeKey(key) { + if (key instanceof Date) { + return `D:${key.getTime()}`; + } + if (Array.isArray(key)) { + return `A:[${key.map(serializeKey).join(',')}]`; + } + if (key instanceof ArrayBuffer) { + return `B:${Buffer.from(key).toString('hex')}`; + } + return `${typeof key}:${String(key)}`; +} + +function extractKey(value, keyPath) { + if (Array.isArray(keyPath)) { + return keyPath.map(part => value[part]); + } + return value[keyPath]; +} + +// W3C IndexedDB key type order: number (0) < Date (1) < string (2) < Array (3). +function keyTypeRank(v) { + if (typeof v === 'number') return 0; + if (v instanceof Date) return 1; + if (typeof v === 'string') return 2; + if (Array.isArray(v)) return 3; + return 4; +} + +function cmpVal(a, b) { + const ra = keyTypeRank(a); + const rb = keyTypeRank(b); + if (ra !== rb) return ra - rb; + if (ra === 0) return a < b ? -1 : a > b ? 1 : 0; + if (ra === 1) { + const ta = a.getTime(); + const tb = b.getTime(); + return ta < tb ? -1 : ta > tb ? 1 : 0; + } + if (ra === 2) return a < b ? -1 : a > b ? 1 : 0; + if (ra === 3) { + const len = Math.min(a.length, b.length); + for (let i = 0; i < len; i += 1) { + const d = cmpVal(a[i], b[i]); + if (d !== 0) return d; + } + return a.length - b.length; + } + return 0; +} + +function matchesRange(key, range) { + if (!range) return true; + if (range.lower !== undefined) { + const c = cmpVal(key, range.lower); + if (range.lowerOpen ? c <= 0 : c < 0) return false; + } + if (range.upper !== undefined) { + const c = cmpVal(key, range.upper); + if (range.upperOpen ? c >= 0 : c > 0) return false; + } + return true; +} + +function isKeyRange(key) { + return ( + key !== null && + typeof key === 'object' && + !Array.isArray(key) && + !(key instanceof Date) && + !(key instanceof ArrayBuffer) + ); +} + +export function createMemoryStorage(initial = {}) { + const map = new Map(Object.entries(initial)); + return { + getItem: key => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => { + map.set(key, String(value)); + }, + removeItem: key => { + map.delete(key); + }, + }; +} + +export function createBroadcastBus() { + /** @type {Map, closed: boolean }>>} */ + const channels = new Map(); + + class MemoryBroadcastChannel { + constructor(name) { + this.name = name; + this.listeners = new Set(); + this.closed = false; + if (!channels.has(name)) { + channels.set(name, new Set()); + } + channels.get(name).add(this); + } + + addEventListener(type, fn) { + if (type === 'message') { + this.listeners.add(fn); + } + } + + removeEventListener(type, fn) { + if (type === 'message') { + this.listeners.delete(fn); + } + } + + postMessage(data) { + if (this.closed) { + return; + } + const peers = channels.get(this.name); + if (!peers) { + return; + } + for (const peer of peers) { + if (peer === this || peer.closed) { + continue; + } + const event = { data }; + for (const fn of peer.listeners) { + fn(event); + } + } + } + + close() { + this.closed = true; + channels.get(this.name)?.delete(this); + } + } + + return MemoryBroadcastChannel; +} + +/** + * In-memory W3C IDBFactory supporting versioned upgrades, compound keyPaths, + * indexes, `oncomplete`/`onerror`/`onabort` transaction lifecycle, rollback on + * abort, and deterministic fault injection. + */ +export function createMemoryIdbFactory() { + /** @type {Map, indexes: Map }> }>} */ + const dbs = new Map(); + let databasesCalls = 0; + let nextTxFailure = null; + + function cloneRecordMap(map) { + return new Map( + [...map.entries()].map(([k, v]) => [k, { key: v.key, value: v.value }]) + ); + } + + function makeRequest(executor, onSettled, gate = null) { + const req = { + result: undefined, + error: null, + onsuccess: null, + onerror: null, + }; + const run = () => { + try { + req.result = executor(); + req.onsuccess?.({ target: req }); + onSettled?.(null); + } catch (err) { + req.error = err; + req.onerror?.({ target: req }); + onSettled?.(err); + } + }; + if (gate) { + gate.then(() => queueMicrotask(run)); + } else { + queueMicrotask(run); + } + return req; + } + + function wrapDb(meta) { + const listeners = new Map(); + + const dbApi = { + get name() { + return meta.name; + }, + get version() { + return meta.version; + }, + get objectStoreNames() { + const names = [...meta.stores.keys()]; + return { + length: names.length, + contains: name => meta.stores.has(name), + [Symbol.iterator]: () => names[Symbol.iterator](), + }; + }, + createObjectStore(name, opts = {}) { + const storeMeta = { + name, + keyPath: opts.keyPath ?? null, + autoIncrement: Boolean(opts.autoIncrement), + nextId: 1, + records: new Map(), + indexes: new Map(), + }; + meta.stores.set(name, storeMeta); + return { + createIndex(indexName, keyPath, indexOpts = {}) { + storeMeta.indexes.set(indexName, { + name: indexName, + keyPath, + unique: Boolean(indexOpts.unique), + }); + return { name: indexName, keyPath }; + }, + }; + }, + transaction(storeNames, mode = 'readonly') { + const names = Array.isArray(storeNames) ? storeNames : [storeNames]; + for (const name of names) { + if (!meta.stores.has(name)) { + throw new Error(`Missing objectStore ${name}`); + } + } + const snapshots = new Map(); + let snapshotsCaptured = false; + let finished = false; + let pendingOps = 0; + let commitRequested = false; + let releaseRw = null; + let rwGate = null; + if (mode === 'readwrite') { + const prevRw = meta.rwQueue || Promise.resolve(); + meta.rwQueue = new Promise(resolve => { + releaseRw = resolve; + }); + rwGate = prevRw.then(() => { + if (!snapshotsCaptured && !finished) { + snapshotsCaptured = true; + for (const name of names) { + snapshots.set( + name, + cloneRecordMap(meta.stores.get(name).records) + ); + } + } + }); + } + + const tx = { + mode, + error: null, + oncomplete: null, + onerror: null, + onabort: null, + abort(err) { + if (finished) { + return; + } + finished = true; + if (mode === 'readwrite' && snapshotsCaptured) { + for (const [name, snap] of snapshots.entries()) { + meta.stores.get(name).records = snap; + } + } + tx.error = err || new Error('Transaction aborted'); + queueMicrotask(() => { + releaseRw?.(); + tx.onabort?.({ target: tx }); + }); + }, + commit() { + commitRequested = true; + maybeComplete(); + }, + objectStore(storeName) { + if (!names.includes(storeName)) { + throw new Error(`Store ${storeName} not in transaction scope`); + } + const storeMeta = meta.stores.get(storeName); + + const track = executor => { + pendingOps += 1; + return makeRequest( + () => { + if (finished) { + throw new Error('Transaction already finished'); + } + if (mode === 'readwrite' && nextTxFailure) { + const err = nextTxFailure; + nextTxFailure = null; + tx.abort(err); + throw err; + } + return executor(); + }, + err => { + pendingOps -= 1; + if (err) { + if (!finished) { + tx.abort(err); + } + } else { + maybeComplete(); + } + }, + rwGate + ); + }; + + return { + get: key => + track(() => storeMeta.records.get(serializeKey(key))?.value), + getAll: () => + track(() => [...storeMeta.records.values()].map(r => r.value)), + getAllKeys: () => + track(() => [...storeMeta.records.values()].map(r => r.key)), + add: (value, explicitKey) => + track(() => { + if (mode !== 'readwrite') { + throw new Error('ReadOnlyError'); + } + const key = + explicitKey !== undefined + ? explicitKey + : storeMeta.keyPath + ? extractKey(value, storeMeta.keyPath) + : storeMeta.nextId++; + const sk = serializeKey(key); + if (storeMeta.records.has(sk)) { + throw new Error(`ConstraintError: duplicate key ${sk}`); + } + storeMeta.records.set(sk, { key, value }); + return key; + }), + put: (value, explicitKey) => + track(() => { + if (mode !== 'readwrite') { + throw new Error('ReadOnlyError'); + } + const key = + explicitKey !== undefined + ? explicitKey + : storeMeta.keyPath + ? extractKey(value, storeMeta.keyPath) + : storeMeta.nextId++; + const sk = serializeKey(key); + storeMeta.records.set(sk, { key, value }); + return key; + }), + delete: key => + track(() => { + if (mode !== 'readwrite') { + throw new Error('ReadOnlyError'); + } + if (!isKeyRange(key)) { + storeMeta.records.delete(serializeKey(key)); + return; + } + for (const [sk, record] of storeMeta.records) { + if (matchesRange(record.key, key)) { + storeMeta.records.delete(sk); + } + } + }), + openKeyCursor: (range, direction = 'next') => { + const req = { + result: null, + error: null, + onsuccess: null, + onerror: null, + }; + pendingOps += 1; + /** @type {unknown[]} */ + let keys = []; + let idx = 0; + const settle = () => { + pendingOps -= 1; + maybeComplete(); + }; + const step = () => { + if (finished) { + pendingOps -= 1; + return; + } + if (idx < keys.length) { + const k = keys[idx]; + idx += 1; + let continued = false; + req.result = { + key: k, + primaryKey: k, + continue: () => { + continued = true; + queueMicrotask(step); + }, + }; + req.onsuccess?.({ target: req }); + if (!continued) settle(); + } else { + req.result = null; + req.onsuccess?.({ target: req }); + settle(); + } + }; + const start = () => { + keys = [...storeMeta.records.values()] + .map(r => r.key) + .filter(key => matchesRange(key, range)) + .sort(cmpVal); + if (direction === 'prev') keys.reverse(); + queueMicrotask(step); + }; + if (rwGate) { + rwGate.then(start); + } else { + start(); + } + return req; + }, + index(indexName) { + const idx = storeMeta.indexes.get(indexName); + if (!idx) { + throw new Error(`Missing index ${indexName} on ${storeName}`); + } + return { + getAll: queryKey => + track(() => { + const target = serializeKey(queryKey); + const out = []; + for (const { value } of storeMeta.records.values()) { + const actual = extractKey(value, idx.keyPath); + if (serializeKey(actual) === target) { + out.push(value); + } + } + return out; + }), + }; + }, + }; + }, + }; + + function maybeComplete() { + if (finished || pendingOps > 0) { + return; + } + if (commitRequested || mode === 'readonly') { + finished = true; + queueMicrotask(() => { + releaseRw?.(); + tx.oncomplete?.({ target: tx }); + }); + } + } + + // Readonly transactions auto-complete once all microtask ops drain. + if (mode === 'readonly') { + queueMicrotask(() => maybeComplete()); + } + + return tx; + }, + addEventListener(type, fn) { + listeners.set(type, fn); + }, + removeEventListener(type) { + listeners.delete(type); + }, + close() {}, + }; + + return dbApi; + } + + return { + open(name, version = 1) { + const req = { + result: null, + error: null, + transaction: null, + onupgradeneeded: null, + onsuccess: null, + onerror: null, + onblocked: null, + }; + queueMicrotask(() => { + let meta = dbs.get(name); + const existed = Boolean(meta); + const oldVersion = meta ? meta.version : 0; + if (!meta) { + meta = { name, version, stores: new Map() }; + dbs.set(name, meta); + } else if (version > meta.version) { + meta.version = version; + } + const db = wrapDb(meta); + req.result = db; + let upgradeAborted = false; + req.transaction = { + abort() { + upgradeAborted = true; + if (!existed) { + dbs.delete(name); + } else { + meta.version = oldVersion; + } + }, + }; + if (oldVersion < version) { + req.onupgradeneeded?.({ + target: req, + oldVersion, + newVersion: version, + }); + } + req.transaction = null; + if (upgradeAborted) { + req.error = new Error('Upgrade transaction aborted'); + req.onerror?.({ target: req }); + return; + } + req.onsuccess?.({ target: req }); + }); + return req; + }, + async databases() { + databasesCalls += 1; + return [...dbs.values()].map(d => ({ name: d.name, version: d.version })); + }, + getMeta: name => dbs.get(name), + getDatabasesCallCount: () => databasesCalls, + failNextWriteTransaction(err) { + nextTxFailure = err; + }, + }; +} diff --git a/packages/frontend/hosts/web/tests/preview-workers.test.mjs b/packages/frontend/hosts/web/tests/preview-workers.test.mjs new file mode 100644 index 0000000000..081938133d --- /dev/null +++ b/packages/frontend/hosts/web/tests/preview-workers.test.mjs @@ -0,0 +1,948 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { installPlaygroundPreviewBridge } from '../../../../../blocksuite/crates/playground/web/preview-workers.js'; + +function createFakeDom() { + const children = []; + const embedLayer = { + style: {}, + append(el) { + children.push(el); + }, + }; + const revoked = []; + let blobSeq = 0; + + const originalWindow = globalThis.window; + const originalDocument = globalThis.document; + const originalWorker = globalThis.Worker; + const originalCreateObjectURL = URL.createObjectURL; + const originalRevokeObjectURL = URL.revokeObjectURL; + + const workers = []; + class FakeWorker { + constructor(url) { + this.url = url; + this.listeners = new Map(); + this.posted = []; + this.terminated = false; + workers.push(this); + } + terminate() { + this.terminated = true; + } + addEventListener(type, fn) { + const list = this.listeners.get(type) || []; + list.push(fn); + this.listeners.set(type, list); + } + postMessage(msg) { + this.posted.push(msg); + } + emit(type, event) { + return Promise.all((this.listeners.get(type) || []).map(fn => fn(event))); + } + } + + const windowListeners = new Map(); + globalThis.window = { + location: { href: 'https://app.affine.test/playground/' }, + addEventListener(type, fn) { + const list = windowListeners.get(type) || []; + list.push(fn); + windowListeners.set(type, list); + }, + removeEventListener(type, fn) { + const list = windowListeners.get(type) || []; + windowListeners.set( + type, + list.filter(item => item !== fn) + ); + }, + emit(type, event) { + for (const fn of windowListeners.get(type) || []) { + fn(event); + } + }, + listenerCount(type) { + return (windowListeners.get(type) || []).length; + }, + }; + globalThis.document = { + getElementById(id) { + return id === 'embed-layer' ? embedLayer : null; + }, + createElement(tag) { + const attrs = new Map(); + const listeners = new Map(); + const el = { + tagName: tag.toUpperCase(), + style: {}, + src: '', + setAttribute(k, v) { + attrs.set(k, String(v)); + }, + getAttribute(k) { + return attrs.get(k) ?? null; + }, + addEventListener(type, fn) { + const list = listeners.get(type) || []; + list.push(fn); + listeners.set(type, list); + }, + emit(type, event) { + for (const fn of listeners.get(type) || []) { + fn(event); + } + }, + getBoundingClientRect() { + const left = parseFloat(el.style.left) || 0; + const top = parseFloat(el.style.top) || 0; + const width = parseFloat(el.style.width) || 0; + const height = parseFloat(el.style.height) || 0; + return { + left, + top, + width, + height, + right: left + width, + bottom: top + height, + }; + }, + remove() { + const idx = children.indexOf(el); + if (idx >= 0) children.splice(idx, 1); + }, + click() {}, + }; + return el; + }, + }; + globalThis.Worker = FakeWorker; + URL.createObjectURL = () => `blob:test-${++blobSeq}`; + URL.revokeObjectURL = url => { + revoked.push(url); + }; + + return { + children, + embedLayer, + revoked, + workers, + restore() { + globalThis.window = originalWindow; + globalThis.document = originalDocument; + globalThis.Worker = originalWorker; + URL.createObjectURL = originalCreateObjectURL; + URL.revokeObjectURL = originalRevokeObjectURL; + }, + }; +} + +void test('reconcileHtmlEmbeds mounts, updates html blob URLs, and unmounts stale iframes without allow-same-origin', () => { + const env = createFakeDom(); + try { + installPlaygroundPreviewBridge({}); + const bridge = globalThis.window.__playgroundPreview; + + bridge.reconcileHtmlEmbeds( + JSON.stringify([ + { + id: 'ext-1', + html: '

v1

', + x: 20, + y: 100, + w: 300, + h: 120, + visible: true, + }, + ]) + ); + assert.equal(env.children.length, 1); + const iframe = env.children[0]; + assert.equal(iframe.getAttribute('sandbox'), 'allow-scripts'); + assert.equal( + iframe.getAttribute('sandbox').includes('allow-same-origin'), + false + ); + const firstUrl = iframe.src; + assert.equal(iframe.style.top, '100px'); + + // Scroll + HTML content update revokes old blob URL and refreshes src + position. + bridge.reconcileHtmlEmbeds([ + { + id: 'ext-1', + html: '

v2

', + x: 20, + y: 64, + w: 300, + h: 120, + visible: true, + }, + ]); + assert.equal(env.children.length, 1); + assert.notEqual(iframe.src, firstUrl); + assert.ok( + env.revoked.includes(firstUrl), + 'old blob URL must be revoked on HTML change' + ); + assert.equal(iframe.style.top, '64px'); + + // Re-installing the bridge cleans up previous global listeners (zero listener leak). + assert.equal(globalThis.window.listenerCount('pointerdown'), 1); + assert.equal(globalThis.window.listenerCount('wheel'), 1); + installPlaygroundPreviewBridge({}); + assert.equal(globalThis.window.listenerCount('pointerdown'), 1); + assert.equal(globalThis.window.listenerCount('wheel'), 1); + const activeBridge = globalThis.window.__playgroundPreview; + activeBridge.reconcileHtmlEmbeds([ + { + id: 'ext-1', + html: '

v2

', + x: 20, + y: 64, + w: 300, + h: 120, + visible: true, + }, + ]); + const liveIframe = env.children[0]; + assert.equal(liveIframe.style.pointerEvents, 'none'); + + // Click inside iframe activates pointerEvents; wheel or pointerleave deactivates for smooth scrolling. + globalThis.window.emit('pointerdown', { clientX: 50, clientY: 100 }); + assert.equal(liveIframe.style.pointerEvents, 'auto'); + globalThis.window.emit('wheel', {}); + assert.equal(liveIframe.style.pointerEvents, 'none'); + globalThis.window.emit('pointerdown', { clientX: 50, clientY: 100 }); + assert.equal(liveIframe.style.pointerEvents, 'auto'); + liveIframe.emit('pointerleave', {}); + assert.equal(liveIframe.style.pointerEvents, 'none'); + + // Cross-origin blob iframe wheel postMessage deactivates iframe capture immediately. + liveIframe.contentWindow = {}; + globalThis.window.emit('pointerdown', { clientX: 50, clientY: 100 }); + assert.equal(liveIframe.style.pointerEvents, 'auto'); + globalThis.window.emit('message', { + source: liveIframe.contentWindow, + data: { + type: '__affine_embed_wheel', + dx: 0, + dy: 120, + dm: 0, + cx: 10, + cy: 10, + }, + }); + assert.equal(liveIframe.style.pointerEvents, 'none'); + + // Switching mode / deleting block reconciles to [] and unmounts + revokes blob URL. + const secondUrl = liveIframe.src; + activeBridge.reconcileHtmlEmbeds([]); + assert.equal(env.children.length, 0); + assert.ok( + env.revoked.includes(secondUrl), + 'blob URL must be revoked on unmount' + ); + } finally { + env.restore(); + } +}); + +void test('a hidden split pane releases its iframe and leaves the other pane visible and interactive', () => { + const env = createFakeDom(); + try { + const bridge = installPlaygroundPreviewBridge({}); + const left = { id: 'p1-html', x: 10, y: 10, w: 100, h: 100, visible: true }; + const right = { ...left, id: 'p2-html', x: 210 }; + bridge.reconcileHtmlEmbeds([left, right]); + const [leftFrame, rightFrame] = env.children; + assert.equal(leftFrame.style.display, 'block'); + assert.equal(rightFrame.style.display, 'block'); + assert.notEqual(env.embedLayer.style.visibility, 'hidden'); + + globalThis.window.emit('pointerdown', { clientX: 50, clientY: 50 }); + assert.equal(leftFrame.style.pointerEvents, 'auto'); + bridge.reconcileHtmlEmbeds([{ ...left, visible: false }, right]); + assert.equal(leftFrame.style.display, 'none'); + assert.equal(leftFrame.style.pointerEvents, 'none'); + assert.equal(rightFrame.style.display, 'block'); + assert.notEqual(env.embedLayer.style.visibility, 'hidden'); + + globalThis.window.emit('pointerdown', { clientX: 250, clientY: 50 }); + assert.equal(rightFrame.style.pointerEvents, 'auto'); + bridge.reconcileHtmlEmbeds([right]); + assert.deepEqual(env.children, [rightFrame]); + assert.equal(rightFrame.style.display, 'block'); + assert.equal(rightFrame.style.pointerEvents, 'auto'); + assert.notEqual(env.embedLayer.style.visibility, 'hidden'); + } finally { + env.restore(); + } +}); + +for (const kind of ['mermaid', 'typst']) { + for (const cancellation of ['dispose', 'worker error']) { + void test(`${kind} settles once when ${cancellation} interrupts SVG decode`, async () => { + const env = createFakeDom(); + const originalImage = globalThis.Image; + let img; + globalThis.Image = class { + constructor() { + img = this; + } + }; + try { + const events = []; + const bridge = installPlaygroundPreviewBridge({ + deliver_code_preview: () => events.push('success'), + deliver_code_preview_error: (...args) => events.push(args), + }); + bridge.requestCodePreview(kind, 'source', false, 1); + const [worker] = env.workers; + const [{ id }] = worker.posted; + const completion = worker.emit('message', { + data: { + id, + ok: true, + result: { svg: '' }, + }, + }); + assert.deepEqual(events, []); + const svgUrl = img.src; + if (cancellation === 'dispose') { + bridge.dispose(); + } else { + await worker.emit('error', {}); + } + const reason = + cancellation === 'dispose' + ? 'preview bridge disposed' + : `${kind} worker error`; + const expected = [[kind, 'source', false, 1, reason]]; + assert.deepEqual(events, expected); + img.onload(); + await completion; + assert.deepEqual(events, expected); + assert.deepEqual(env.revoked, [worker.url, svgUrl]); + } finally { + globalThis.Image = originalImage; + env.restore(); + } + }); + } +} + +void test('SVG decode failure revokes its Blob URL and settles the preview once', async () => { + const env = createFakeDom(); + const originalImage = globalThis.Image; + let img; + globalThis.Image = class { + constructor() { + img = this; + } + }; + try { + const errors = []; + const bridge = installPlaygroundPreviewBridge({ + deliver_code_preview_error: (...args) => errors.push(args), + }); + bridge.requestCodePreview('mermaid', 'source', false, 1); + const [worker] = env.workers; + const [{ id }] = worker.posted; + const completion = worker.emit('message', { + data: { id, ok: true, result: { svg: '' } }, + }); + img.onerror(new Error('decode failed')); + await completion; + bridge.dispose(); + assert.deepEqual(errors, [ + ['mermaid', 'source', false, 1, 'Error: decode failed'], + ]); + assert.deepEqual(env.revoked, [img.src, worker.url]); + } finally { + globalThis.Image = originalImage; + env.restore(); + } +}); + +void test('worker construction failure revokes its Blob URL and settles the preview once', () => { + const env = createFakeDom(); + let failedUrl; + globalThis.Worker = class { + constructor(url) { + failedUrl = url; + throw new Error('worker blocked'); + } + }; + try { + const errors = []; + const bridge = installPlaygroundPreviewBridge({ + deliver_code_preview_error: (...args) => errors.push(args), + }); + bridge.requestCodePreview('typst', 'source', true, 2); + bridge.dispose(); + assert.deepEqual(errors, [ + ['typst', 'source', true, 2, 'Error: worker blocked'], + ]); + assert.deepEqual(env.revoked, [failedUrl]); + } finally { + env.restore(); + } +}); + +void test('mermaid and typst worker errors fail pending requests instead of stalling in Pending', () => { + const env = createFakeDom(); + try { + const errors = []; + installPlaygroundPreviewBridge({ + deliver_code_preview_error(kind, source, dark, dpr, msg) { + errors.push({ kind, source, dark, dpr, msg }); + }, + }); + const bridge = globalThis.window.__playgroundPreview; + + bridge.requestCodePreview('mermaid', 'graph TD; A-->B', false, 2); + assert.equal(env.workers.length, 1); + env.workers[0].emit('error', new Error('worker crashed')); + assert.equal( + env.workers[0].terminated, + true, + 'crashed mermaid worker must be terminated' + ); + assert.equal(errors.length, 1); + assert.equal(errors[0].kind, 'mermaid'); + + // Subsequent request after crash must spawn a fresh worker instance (self-healing). + bridge.requestCodePreview('mermaid', 'graph LR; X-->Y', false, 2); + assert.equal( + env.workers.length, + 2, + 'must spawn a fresh mermaid worker after error' + ); + assert.equal(env.workers[1].terminated, false); + assert.equal(env.workers[1].posted.length, 1); + + bridge.registerFont(new Uint8Array([0, 1, 0, 0])); + bridge.requestCodePreview('typst', '= Hello', true, 2); + assert.equal(env.workers.length, 3); + assert.equal( + env.workers[2].posted[0].op, + 'register_font', + 'typst worker must receive registered web fonts before its first compile' + ); + assert.ok( + env.workers[2].posted[1].source.includes( + '#show math.equation: set text(font: "New Computer Modern Math")' + ) && env.workers[2].posted[1].source.endsWith('= Hello') + ); + env.workers[2].emit('messageerror', {}); + assert.equal( + env.workers[2].terminated, + true, + 'crashed typst worker must be terminated' + ); + assert.equal(errors.length, 2); + assert.equal(errors[1].kind, 'typst'); + + bridge.requestCodePreview('typst', '= Retry', true, 2); + assert.equal( + env.workers.length, + 4, + 'must spawn a fresh typst worker after messageerror' + ); + assert.equal(env.workers[3].posted.length, 2); + assert.equal(env.workers[3].posted[0].op, 'register_font'); + assert.ok(env.workers[3].posted[1].source.endsWith('= Retry')); + } finally { + env.restore(); + } +}); + +void test('pickImages and pickAttachments bind requestId, finish on change/cancel, reject oversized files before arrayBuffer, and keep deliverPdfAttachment independent', async () => { + const env = createFakeDom(); + const createdInputs = []; + globalThis.document.body = { + append(el) { + createdInputs.push(el); + }, + }; + try { + const events = []; + installPlaygroundPreviewBridge({ + deliver_picked_image_for(reqId, bytes) { + events.push({ op: 'img', reqId, len: bytes.byteLength }); + }, + deliver_picked_attachment_for(reqId, bytes, name, mime) { + events.push({ op: 'att', reqId, len: bytes.byteLength, name, mime }); + }, + report_oversized_picked_media(reqId, isAttachment) { + events.push({ op: 'oversize', reqId, isAttachment }); + }, + finish_picked_media(reqId) { + events.push({ op: 'finish', reqId }); + }, + deliver_picked_pdf(bytes, name) { + events.push({ op: 'pdf', len: bytes.byteLength, name }); + }, + }); + const bridge = globalThis.window.__playgroundPreview; + + // 1. Interleaved pickImages(101) and pickImages(102): change on 101 finishes 101 in `finally`, + // oversized file skips `arrayBuffer()`, and cancel on 102 finishes 102 independently. + bridge.pickImages(101); + bridge.pickImages(102); + assert.equal(createdInputs.length, 2); + let oversizedRead = false; + createdInputs[0].files = [ + { + size: 33 * 1024 * 1024, + async arrayBuffer() { + oversizedRead = true; + return new ArrayBuffer(8); + }, + }, + { + size: 4, + async arrayBuffer() { + return new Uint8Array([1, 2, 3, 4]).buffer; + }, + }, + ]; + createdInputs[0].emit('change', {}); + await new Promise(resolve => setTimeout(resolve, 0)); + assert.equal( + oversizedRead, + false, + 'oversized file must not allocate arrayBuffer' + ); + createdInputs[1].emit('cancel', {}); + + // 2. pickAttachments(201) delivers in order and calls finish_picked_media(201), + // after which deliverPdfAttachment still works on Page B without stale target state. + bridge.pickAttachments(201); + createdInputs[2].files = [ + { + name: 'a.txt', + type: 'text/plain', + size: 3, + async arrayBuffer() { + return new Uint8Array([65, 66, 67]).buffer; + }, + }, + { + name: 'b.txt', + type: 'text/plain', + size: 2, + async arrayBuffer() { + return new Uint8Array([68, 69]).buffer; + }, + }, + ]; + createdInputs[2].emit('change', {}); + await new Promise(resolve => setTimeout(resolve, 0)); + bridge.deliverPdfAttachment( + new Uint8Array([37, 80, 68, 70, 45]), + 'report.pdf' + ); + + assert.deepEqual(events, [ + { op: 'oversize', reqId: 101, isAttachment: false }, + { op: 'img', reqId: 101, len: 4 }, + { op: 'finish', reqId: 101 }, + { op: 'finish', reqId: 102 }, + { op: 'att', reqId: 201, len: 3, name: 'a.txt', mime: 'text/plain' }, + { op: 'att', reqId: 201, len: 2, name: 'b.txt', mime: 'text/plain' }, + { op: 'finish', reqId: 201 }, + { op: 'pdf', len: 5, name: 'report.pdf' }, + ]); + } finally { + env.restore(); + } +}); + +void test('mermaid SVG with width="100%" + viewBox rasterizes at intrinsic viewBox/max-width size instead of 300x150 browser fallback', async () => { + const env = createFakeDom(); + const originalBlob = globalThis.Blob; + const originalImage = globalThis.Image; + const createdBlobs = []; + const createdCanvases = []; + globalThis.Blob = class FakeBlob { + constructor(parts, opts) { + this.text = parts.join(''); + this.type = opts?.type || ''; + createdBlobs.push(this); + } + }; + globalThis.Image = class FakeImage { + constructor() { + // Simulate Chromium's 300x150 default when `` lacks explicit px dimensions. + this.naturalWidth = 300; + this.naturalHeight = 150; + this.onload = null; + this.onerror = null; + } + set src(_url) { + const latestSvg = createdBlobs.at(-1)?.text || ''; + const wMatch = /\bwidth="([0-9.]+)"/.exec(latestSvg); + const hMatch = /\bheight="([0-9.]+)"/.exec(latestSvg); + if (wMatch && hMatch) { + this.naturalWidth = Number(wMatch[1]); + this.naturalHeight = Number(hMatch[1]); + } + queueMicrotask(() => this.onload?.()); + } + }; + const origCreateElement = globalThis.document.createElement; + globalThis.document.createElement = tag => { + if (tag === 'canvas') { + const canvas = { + width: 0, + height: 0, + scales: [], + draws: [], + getContext() { + return { + scale(sx, sy) { + canvas.scales.push([sx, sy]); + }, + drawImage(_img, x, y, w, h) { + canvas.draws.push([x, y, w, h]); + }, + getImageData(_x, _y, w, h) { + return { data: new Uint8ClampedArray(w * h * 4) }; + }, + }; + }, + }; + createdCanvases.push(canvas); + return canvas; + } + return origCreateElement(tag); + }; + try { + const delivered = []; + installPlaygroundPreviewBridge({ + deliver_code_preview(kind, source, dark, dpr, wPt, hPt, wPx, hPx, rgba) { + delivered.push({ + kind, + source, + dark, + dpr, + wPt, + hPt, + wPx, + hPx, + bytes: rgba.byteLength, + }); + }, + }); + const bridge = globalThis.window.__playgroundPreview; + bridge.requestCodePreview('mermaid', 'flowchart LR; A-->B-->C', false, 2); + assert.equal(env.workers.length, 1); + const reqId = env.workers[0].posted[0].id; + await env.workers[0].emit('message', { + data: { + id: reqId, + ok: true, + result: { + svg: '', + }, + }, + }); + assert.equal(delivered.length, 1); + assert.equal(delivered[0].wPt, 840); + assert.equal(delivered[0].hPt, 310); + assert.equal(delivered[0].wPx, 1680); + assert.equal(delivered[0].hPx, 620); + assert.equal(createdCanvases[0].width, 1680); + assert.equal(createdCanvases[0].height, 620); + assert.match(createdBlobs.at(-1).text, /^ { + const env = createFakeDom(); + try { + installPlaygroundPreviewBridge({}); + const bridge = globalThis.window.__playgroundPreview; + const fontA = new Uint8Array([1, 2, 3, 4]); + const fontB = new Uint8Array([5, 6, 7, 8]); + bridge.registerFont(fontA); + assert.equal(env.workers.length, 0); + + bridge.requestCodePreview('mermaid', 'flowchart LR; A-->B', false, 1); + assert.equal(env.workers.length, 1); + assert.equal(env.workers[0].posted[0].op, 'register_font'); + assert.deepEqual( + Array.from(env.workers[0].posted[0].fontBytes), + [1, 2, 3, 4] + ); + assert.equal(env.workers[0].posted[1].source, 'flowchart LR; A-->B'); + + bridge.registerFont(fontB); + assert.equal(env.workers[0].posted[2].op, 'register_font'); + assert.deepEqual( + Array.from(env.workers[0].posted[2].fontBytes), + [5, 6, 7, 8] + ); + + env.workers[0].emit('error', new Error('crash')); + bridge.requestCodePreview('mermaid', 'flowchart LR; C-->D', false, 1); + assert.equal(env.workers.length, 2); + assert.equal(env.workers[1].posted[0].op, 'register_font'); + assert.equal(env.workers[1].posted[1].op, 'register_font'); + assert.equal(env.workers[1].posted[2].source, 'flowchart LR; C-->D'); + } finally { + env.restore(); + } +}); + +function pdfDeliveryRecorder() { + const events = []; + return { + events, + exports: { + deliver_pdf_open(docId, count) { + events.push(['open', docId, count]); + }, + deliver_pdf_open_error(docId) { + events.push(['open_error', docId]); + }, + deliver_pdf_page(docId, pageIndex, pageCount, scale, wPx, hPx, rgba) { + events.push([ + 'page', + docId, + pageIndex, + pageCount, + scale, + wPx, + hPx, + rgba.byteLength, + ]); + }, + deliver_pdf_page_error(docId, pageIndex, scale) { + events.push(['page_error', docId, pageIndex, scale]); + }, + }, + }; +} + +void test('PDF bridge sends each document once by docId and keeps page errors per page', () => { + const env = createFakeDom(); + try { + const { events, exports } = pdfDeliveryRecorder(); + installPlaygroundPreviewBridge(exports); + const bridge = globalThis.window.__playgroundPreview; + const wasmMemory = new Uint8Array([0, 37, 80, 68, 70, 0]); + const pdfView = wasmMemory.subarray(1, 5); + + // Open and render go out back to back, without waiting for the open answer. + assert.equal(bridge.isPdfOpen(7), false); + bridge.openPdf(7, pdfView); + assert.equal(bridge.isPdfOpen(7), true); + bridge.requestPdfPage(7, 0, 1); + bridge.requestPdfPage(7, 1, 1); + bridge.openPdf(8, pdfView); + bridge.closePdf(99); + + assert.equal(env.workers.length, 1); + const [open7, p0, p1, open8] = env.workers[0].posted; + assert.equal( + env.workers[0].posted.length, + 4, + 'closing an unknown docId sends nothing' + ); + assert.deepEqual( + [open7.op, open7.docId, [...open7.pdfBytes]], + ['pdf_open', 7, [37, 80, 68, 70]] + ); + assert.notEqual( + open7.pdfBytes.buffer, + wasmMemory.buffer, + 'never send the main Wasm memory' + ); + assert.equal(open7.pdfBytes.byteOffset, 0); + assert.deepEqual( + [p0.op, p0.docId, p0.pageIndex, p0.scale], + ['pdf_render', 7, 0, 1] + ); + assert.equal( + 'pdfBytes' in p0, + false, + 'a page request carries no PDF bytes' + ); + + const answer = (msg, data) => + env.workers[0].emit('message', { data: { id: msg.id, ...data } }); + answer(open7, { ok: true, result: { pageCount: 5 } }); + answer(p0, { ok: false, error: 'page 0 render error' }); + answer(p1, { + ok: true, + result: { + pageCount: 5, + widthPx: 2, + heightPx: 2, + rgba: new Uint8Array(16), + }, + }); + answer(open8, { ok: false, error: 'Decryption(PasswordProtected)' }); + + bridge.closePdf(7); + const close7 = env.workers[0].posted.at(-1); + assert.deepEqual([close7.op, close7.docId], ['pdf_close', 7]); + assert.equal(bridge.isPdfOpen(7), false); + answer(close7, { ok: true, result: {} }); + + assert.deepEqual(events, [ + ['open', 7, 5], + ['page_error', 7, 0, 1], + ['page', 7, 1, 5, 1, 2, 2, 16], + ['open_error', 8], + ]); + } finally { + env.restore(); + } +}); + +void test('PDF bridge answers every sent request on a crash, ignores a late error of a replaced worker and restarts without stale documents', () => { + const env = createFakeDom(); + try { + const { events, exports } = pdfDeliveryRecorder(); + installPlaygroundPreviewBridge(exports); + const bridge = globalThis.window.__playgroundPreview; + const pdf = new Uint8Array([37, 80, 68, 70]); + + bridge.openPdf(1, pdf); + // The same page twice: each request sent gets its own answer. + bridge.requestPdfPage(1, 0, 1); + bridge.requestPdfPage(1, 0, 1); + const workerA = env.workers[0]; + // A message that cannot be sent leaves no pending request behind. + const postMessage = workerA.postMessage; + workerA.postMessage = () => { + throw new Error('DataCloneError'); + }; + assert.throws(() => bridge.requestPdfPage(1, 9, 1), /DataCloneError/); + workerA.postMessage = postMessage; + workerA.emit('error', { message: 'boom' }); + assert.equal(workerA.terminated, true); + assert.equal( + bridge.isPdfOpen(1), + false, + 'a crash forgets the open documents' + ); + assert.deepEqual(events.splice(0), [ + ['open_error', 1], + ['page_error', 1, 0, 1], + ['page_error', 1, 0, 1], + ]); + + bridge.openPdf(2, pdf); + bridge.requestPdfPage(2, 0, 1); + const workerB = env.workers[1]; + // Worker A answers late: an error event, a message error, and a message with B's id. + workerA.emit('messageerror', {}); + workerA.emit('error', { message: 'late' }); + workerA.emit('message', { + data: { id: workerB.posted[0].id, ok: true, result: { pageCount: 9 } }, + }); + assert.equal(workerB.terminated, false); + assert.equal(bridge.isPdfOpen(2), true); + assert.deepEqual(events, []); + + workerB.emit('message', { + data: { id: workerB.posted[0].id, ok: true, result: { pageCount: 3 } }, + }); + assert.deepEqual(events.splice(0), [['open', 2, 3]]); + + // A restart drops the pending page request without an answer. + bridge.restartPdfWorker(); + assert.equal(workerB.terminated, true); + assert.equal(bridge.isPdfOpen(2), false); + workerB.emit('message', { + data: { + id: workerB.posted[1].id, + ok: true, + result: { rgba: new Uint8Array(4) }, + }, + }); + assert.deepEqual(events, []); + + // Disposing the bridge fails what is on its way and terminates the worker. + bridge.openPdf(3, pdf); + const workerC = env.workers[2]; + globalThis.window.__playgroundPreviewDispose(); + assert.equal(workerC.terminated, true); + assert.deepEqual(events, [['open_error', 3]]); + } finally { + env.restore(); + } +}); + +void test('dispose terminates math, mermaid, typst, and pdf workers, fails pending requests, and lazily respawns on reuse', () => { + const env = createFakeDom(); + try { + const errors = []; + const bridge = installPlaygroundPreviewBridge({ + deliver_math_error(latex) { + errors.push(['math', latex]); + }, + deliver_code_preview_error(kind, source) { + errors.push([kind, source]); + }, + deliver_pdf_open_error(docId) { + errors.push(['pdf', docId]); + }, + }); + bridge.registerFont(new Uint8Array([1, 2, 3, 4])); + bridge.requestMath('x^2', false, 16, '#000', 2); + bridge.requestCodePreview('mermaid', 'graph TD; A-->B', false, 2); + bridge.requestCodePreview('typst', '= Hello', true, 2); + bridge.openPdf(11, new Uint8Array([37, 80, 68, 70])); + + assert.equal(env.workers.length, 4); + assert.equal( + env.workers.every(w => !w.terminated), + true + ); + + bridge.dispose(); + assert.equal( + env.workers.every(w => w.terminated), + true, + 'dispose() must terminate every active preview worker' + ); + assert.deepEqual(errors, [ + ['math', 'x^2'], + ['mermaid', 'graph TD; A-->B'], + ['typst', '= Hello'], + ['pdf', 11], + ]); + assert.equal(bridge.isPdfOpen(11), false); + + // Calling dispose() again is a safe no-op. + bridge.dispose(); + assert.equal(env.workers.length, 4); + + // Subsequent preview requests lazily respawn fresh workers and re-sync registered fonts. + bridge.requestMath('y^2', false, 16, '#000', 2); + bridge.requestCodePreview('mermaid', 'graph LR; C-->D', false, 2); + bridge.requestCodePreview('typst', '= Next', true, 2); + bridge.openPdf(12, new Uint8Array([37, 80, 68, 70])); + assert.equal(env.workers.length, 8); + assert.equal( + env.workers.slice(4).every(w => !w.terminated), + true + ); + assert.equal(env.workers[5].posted[0].op, 'register_font'); + assert.equal(env.workers[6].posted[0].op, 'register_font'); + } finally { + env.restore(); + } +}); diff --git a/packages/frontend/hosts/web/tests/sign-in-and-a11y.test.mjs b/packages/frontend/hosts/web/tests/sign-in-and-a11y.test.mjs new file mode 100644 index 0000000000..ee818b5eb9 --- /dev/null +++ b/packages/frontend/hosts/web/tests/sign-in-and-a11y.test.mjs @@ -0,0 +1,1687 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { createA11yTree } from '../src/a11y.js'; +import { bootWebHost } from '../src/host.js'; +import { + bootSignInPage, + buildWebAuthHeaders, + completeOAuthCallback, + createClientNonce, + createSingleUseCodeGuard, + DEFAULT_CLIENT_VERSION, + fetchOAuthProviders, + GLOBAL_STATE_CLIENT_NONCE_KEY, + isAllowedNativeAppUrl, + isAllowedRedirectTarget, + isOfficialCloudHost, + maybeLoadTurnstile, + readClientNonce, + readCsrfToken, + resolveSafeAuthRedirect, + signOutWebSession, + startOAuthLogin, + submitSignInForm, +} from '../src/sign-in.js'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); + +function createMockElement(tag = 'div') { + const attrs = new Map(); + const children = []; + const listeners = new Map(); + const el = { + tag, + tabIndex: 0, + readOnly: false, + inert: false, + hidden: false, + focused: false, + removed: false, + value: '', + textContent: '', + innerHTML: '', + style: {}, + dataset: {}, + children, + listeners, + setAttribute(name, value) { + attrs.set(name, String(value)); + }, + getAttribute(name) { + return attrs.has(name) ? attrs.get(name) : null; + }, + removeAttribute(name) { + attrs.delete(name); + }, + addEventListener(type, fn) { + listeners.set(type, fn); + }, + removeEventListener(type) { + listeners.delete(type); + }, + append(child) { + children.push(child); + }, + remove() { + el.removed = true; + }, + focus() { + el.focused = true; + listeners.get('focus')?.({}); + }, + blur() { + el.focused = false; + }, + }; + return el; +} + +function createMemorySessionStorage() { + const map = new Map(); + return { + getItem: key => (map.has(key) ? map.get(key) : null), + setItem: (key, val) => map.set(key, String(val)), + }; +} + +function relativeLuminance(hex) { + const clean = hex.replace(/^#/, ''); + const [r, g, b] = [0, 2, 4].map(i => { + const c = Number.parseInt(clean.slice(i, i + 2), 16) / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +function contrastRatio(hexA, hexB) { + const l1 = relativeLuminance(hexA); + const l2 = relativeLuminance(hexB); + return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); +} + +void test('Iron Rule F3 and WCAG AA contrast >= 4.5:1 on sign-in.html', () => { + const html = readFileSync(join(WEB_ROOT, 'sign-in.html'), 'utf8'); + const js = readFileSync(join(WEB_ROOT, 'src/sign-in.js'), 'utf8'); + + assert.ok(!/self-?host/i.test(html)); + assert.ok(!/add server/i.test(html)); + assert.ok(!/server[-_]?url/i.test(html)); + assert.ok(!/self-?host/i.test(js)); + assert.ok(!/add server/i.test(js)); + + // Turnstile container must live outside hidden step sections so all steps can render it. + const turnstileIdx = html.indexOf('
'); + const stepEmailIdx = html.indexOf('
0 && turnstileIdx < stepEmailIdx); + assert.ok(html.includes('min-height: 100dvh')); + assert.ok(html.includes('align-items: flex-start')); + assert.ok(html.includes('button:disabled')); + assert.ok(html.includes('id="auth-legal-notice"')); + assert.ok(html.includes('https://affine.pro/terms')); + assert.ok(html.includes('https://affine.pro/privacy')); + + // Assert WCAG AA >= 4.5:1 for all primary/link/error/secondary color tokens. + const pairs = [ + ['primary button text', '#ffffff', '#0b6bcb'], + ['light link on white', '#0b6bcb', '#ffffff'], + ['dark link on card', '#60b5ff', '#1c1c1e'], + ['light error on white', '#b91c1c', '#ffffff'], + ['dark error on card', '#fca5a5', '#1c1c1e'], + ['light secondary on white', '#52525b', '#ffffff'], + ['dark secondary on card', '#a1a1aa', '#1c1c1e'], + ]; + for (const [label, fg, bg] of pairs) { + const ratio = contrastRatio(fg, bg); + assert.ok( + ratio >= 4.5, + `${label} (${fg} on ${bg}) contrast ${ratio.toFixed(2)} < 4.5` + ); + } +}); + +void test('redirect allowlist and post-auth sanitizer block backslash, tab, and cross-origin open redirects', () => { + const origin = 'https://app.affine.pro'; + const proxyCases = [ + ['/workspace/123', true], + ['https://cloud.affine.pro/welcome', true], + ['https://github.com/toeverything/AFFiNE', true], + ['//evil.example/phish', false], + ['/\\evil.example/x', false], + ['/\\127.0.0.1:9999/landed', false], + ['/%5C127.0.0.1:9999/x', false], + ['/\t/evil.example', false], + ['https://evil.example/phish', false], + ['javascript:alert(1)', false], + ['data:text/html,hi', false], + ]; + for (const [input, expected] of proxyCases) { + assert.equal( + isAllowedRedirectTarget(input, origin), + expected, + `proxy allowlist mismatch for ${JSON.stringify(input)}` + ); + } + + const postAuthCases = [ + ['/workspace/ws-1?doc=2#top', '/workspace/ws-1?doc=2#top'], + ['https://app.affine.pro/workspace/ws-1', '/workspace/ws-1'], + ['//evil.example', '/'], + ['/..//evil.example', '/'], + ['/.//evil.example/path', '/'], + ['/x/..//evil.example?a=1', '/'], + ['/./%2e%2e//evil.example', '/'], + ['/\\evil.example/x', '/'], + ['/%5C127.0.0.1:9999/x', '/'], + ['/\t/evil.example', '/'], + ['https://evil.example/phish', '/'], + ['', '/'], + ]; + for (const [input, expected] of postAuthCases) { + assert.equal( + resolveSafeAuthRedirect(input, origin), + expected, + `post-auth redirect mismatch for ${JSON.stringify(input)}` + ); + } + + assert.equal(isAllowedNativeAppUrl('affine://authentication?code=1'), true); + assert.equal(isAllowedNativeAppUrl('javascript:alert(1)'), false); + assert.equal(isAllowedNativeAppUrl('https://app.affine.pro/'), false); +}); + +void test('auth headers, CSRF cookie parsing, and OAuth client_nonce dual-shell compatibility', async () => { + const headers = buildWebAuthHeaders({ includeJson: true, csrfToken: 'c1' }); + assert.equal(headers['x-affine-client-kind'], 'web'); + assert.equal(headers['x-affine-version'], DEFAULT_CLIENT_VERSION); + assert.equal(headers['x-affine-csrf-token'], 'c1'); + + // Malformed percent in cookie must not throw URIError. + assert.equal( + readCsrfToken({ cookie: 'broken=100%raw; affine_csrf_token=tok%zz' }), + 'tok%zz' + ); + + const signOutCalls = []; + const signOutRes = await signOutWebSession({ + documentRef: { cookie: 'affine_csrf_token=csrf-abc-123' }, + fetchImpl: async (url, init) => { + signOutCalls.push({ url, init }); + return { ok: true, status: 200 }; + }, + }); + assert.deepEqual(signOutRes, { ok: true, status: 200 }); + assert.equal(signOutCalls[0].init.headers['x-affine-client-kind'], 'web'); + assert.equal( + signOutCalls[0].init.headers['x-affine-version'], + DEFAULT_CLIENT_VERSION + ); + assert.equal( + signOutCalls[0].init.headers['x-affine-csrf-token'], + 'csrf-abc-123' + ); + + // Dual-shell client_nonce prefers localStorage['global-state:auth-client-nonce']. + const dualSession = createMemorySessionStorage(); + const dualLocal = createMemorySessionStorage(); + const created = createClientNonce(dualSession, dualLocal); + assert.equal( + dualLocal.getItem(GLOBAL_STATE_CLIENT_NONCE_KEY), + JSON.stringify(created) + ); + assert.equal(readClientNonce(dualSession, dualLocal), created); + dualLocal.setItem( + GLOBAL_STATE_CLIENT_NONCE_KEY, + JSON.stringify('legacy-shell-nonce') + ); + assert.equal(readClientNonce(dualSession, dualLocal), 'legacy-shell-nonce'); +}); + +void test('OAuth login, native client callback handoff, and single-use code retry semantics', async () => { + // 1. Native client OAuth callback hands off to /open-app/url without consuming code. + const nativeNav = []; + const nativeApiCalls = []; + const nativeState = JSON.stringify({ + state: 'srv-state', + client: 'affine', + provider: 'Google', + }); + const nativeRes = await bootSignInPage({ + win: { + location: { + href: `https://app.affine.pro/oauth/callback?code=one-time-native&state=${encodeURIComponent(nativeState)}`, + pathname: '/oauth/callback', + replace: u => nativeNav.push(u), + }, + }, + doc: { getElementById: () => ({ textContent: '' }) }, + fetchImpl: async url => { + nativeApiCalls.push(url); + return { ok: true, status: 200 }; + }, + }); + assert.equal(nativeRes.handedOff, true); + assert.equal(nativeApiCalls.length, 0); + assert.ok(nativeNav[0].startsWith('/open-app/url?url=')); + const deepUrl = new URL( + new URL(nativeNav[0], 'https://app.affine.pro').searchParams.get('url') + ); + assert.equal(deepUrl.protocol, 'affine:'); + assert.equal(deepUrl.searchParams.get('method'), 'oauth'); + assert.equal(deepUrl.searchParams.get('server'), 'https://app.affine.pro'); + assert.deepEqual(JSON.parse(deepUrl.searchParams.get('payload')), { + state: 'srv-state', + code: 'one-time-native', + flow: 'redirect', + provider: 'Google', + }); + + // 2. OAuth login preflight + single-use callback retry after network/503 failure. + const sessionStorage = createMemorySessionStorage(); + const localStorage = createMemorySessionStorage(); + const loginRes = await startOAuthLogin({ + provider: 'Google', + client: 'web', + redirectUri: '/workspace/ws-1', + flow: 'redirect', + documentRef: { cookie: 'affine_csrf_token=c1' }, + sessionStorage, + localStorage, + fetchImpl: async url => { + if (url === '/api/oauth/preflight') { + return { + ok: true, + status: 200, + json: async () => ({ + url: 'https://accounts.google.com/o/oauth2/v2/auth?state=%7B%22state%22%3A%22s-1%22%7D', + }), + }; + } + return { ok: true, status: 200 }; + }, + }); + assert.equal(loginRes.ok, true); + + const guard = createSingleUseCodeGuard(sessionStorage); + const replaced = []; + const cbWin = { + sessionStorage, + localStorage, + location: { + href: 'https://app.affine.pro/oauth/callback?code=retry-1&state=%7B%22state%22%3A%22s-r%22%7D', + }, + history: { replaceState: (_s, _t, u) => replaced.push(u) }, + }; + await assert.rejects(() => + completeOAuthCallback({ + code: 'retry-1', + state: JSON.stringify({ state: 's-r' }), + codeGuard: guard, + windowRef: cbWin, + fetchImpl: async () => { + throw new Error('network-blip'); + }, + }) + ); + assert.equal(guard.hasConsumed('oauth:retry-1'), false); + assert.equal(replaced.length, 0); + + const err503 = await completeOAuthCallback({ + code: 'retry-1', + state: JSON.stringify({ state: 's-r' }), + codeGuard: guard, + windowRef: cbWin, + fetchImpl: async () => ({ ok: false, status: 503 }), + }); + assert.equal(err503.status, 503); + assert.equal(guard.hasConsumed('oauth:retry-1'), false); + + const okCb = await completeOAuthCallback({ + code: 'retry-1', + state: JSON.stringify({ state: 's-r' }), + codeGuard: guard, + windowRef: cbWin, + fetchImpl: async () => ({ + ok: true, + status: 200, + json: async () => ({ redirectUri: '/workspace/ok' }), + }), + }); + assert.equal(okCb.ok, true); + assert.equal(guard.hasConsumed('oauth:retry-1'), true); + assert.deepEqual(replaced, ['/oauth/callback']); + + const dupCb = await completeOAuthCallback({ + code: 'retry-1', + state: JSON.stringify({ state: 's-r' }), + codeGuard: guard, + windowRef: cbWin, + fetchImpl: async () => { + throw new Error('must not call backend twice'); + }, + }); + assert.deepEqual(dupCb, { ok: false, status: 409, duplicate: true }); +}); + +void test('sign-in 3-step flow, frozen schema.gql OAuth query, Turnstile reset, and offline Use local workspace', async () => { + // 1. Frozen schema.gql ServerConfigType query gates OAuth on same-origin `baseUrl`. + const gqlBodies = []; + const oauthCfg = await fetchOAuthProviders({ + currentOrigin: 'https://app.affine.pro', + fetchImpl: async (_url, init) => { + gqlBodies.push(init.body); + return { + ok: true, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + baseUrl: 'https://app.affine.pro', + features: ['OAuth', 'Captcha'], + oauthProviders: ['Google', 'Apple', 'Unsupported'], + }, + }, + }), + }; + }, + }); + assert.ok(gqlBodies[0].includes('name baseUrl features oauthProviders')); + assert.ok(!gqlBodies[0].includes('serverName')); + assert.deepEqual(oauthCfg, { + serverName: 'AFFiNE Cloud', + oauth: true, + providers: ['Google', 'Apple'], + }); + + // Cross-origin reverse proxy, missing baseUrl, or invalid baseUrl must hide OAuth providers. + for (const [label, baseUrl, currentOrigin] of [ + ['cross-origin proxy', 'https://affine.fail', 'https://fail.affine.fail'], + ['missing baseUrl', undefined, 'https://app.affine.pro'], + ['invalid baseUrl', 'not-a-url', 'https://app.affine.pro'], + ['scheme mismatch', 'http://app.affine.pro', 'https://app.affine.pro'], + ]) { + const gated = await fetchOAuthProviders({ + currentOrigin, + fetchImpl: async () => ({ + ok: true, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + ...(baseUrl !== undefined ? { baseUrl } : {}), + features: ['OAuth'], + oauthProviders: ['Google', 'GitHub'], + }, + }, + }), + }), + }); + assert.deepEqual( + gated, + { + serverName: 'AFFiNE Cloud', + oauth: false, + providers: [], + crossOriginProxy: true, + }, + `OAuth must be hidden for ${label}` + ); + } + + // 2. Captcha challenge passthrough + Turnstile reset lifecycle. + const challengeRes = await maybeLoadTurnstile({ + fetchImpl: async () => ({ + ok: true, + json: async () => ({ provider: 'hashcash', challenge: 'hc-1' }), + }), + documentRef: { querySelectorAll: () => [] }, + }); + assert.equal(challengeRes.challenge, 'hc-1'); + const sentHeaders = []; + await submitSignInForm({ + fetchImpl: async (_u, init) => { + sentHeaders.push(init.headers); + return { ok: true, status: 200 }; + }, + email: 'hc@affine.pro', + password: 'pw', + captchaProvider: 'hashcash', + captchaToken: 'tok-1', + captchaChallenge: 'hc-1', + }); + assert.equal(sentHeaders[0]['x-captcha-challenge'], 'hc-1'); + + // 3. Full 3-step UI: Use local workspace bound before async fetches, strict preflight, Turnstile reset. + const nav = []; + const els = new Map(); + for (const id of [ + 'auth-card', + 'auth-status', + 'sign-in-form', + 'step-email', + 'step-password', + 'step-otp', + 'step-email-display', + 'otp-email-display', + 'oauth-providers', + 'oauth-divider', + 'turnstile-container', + 'email', + 'password', + 'otp', + 'use-local-btn', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'back-from-password-btn', + 'back-from-otp-btn', + ]) { + const el = createMockElement('div'); + el.hidden = id === 'step-password' || id === 'step-otp'; + els.set(id, el); + } + els.get('sign-in-form').getAttribute = name => + name === 'action' ? '/api/auth/sign-in' : null; + + let turnstileResets = 0; + let preflightStatus = 403; + const page = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in?redirect_uri=%2Fworkspace%2F9', + pathname: '/sign-in', + replace: u => nav.push(u), + }, + turnstile: { + render(_el, opts) { + opts.callback('ts-token-1'); + return 'wid-1'; + }, + reset(wid) { + assert.equal(wid, 'wid-1'); + turnstileResets += 1; + }, + }, + }, + doc: { + head: { append() {} }, + querySelectorAll: () => [], + getElementById: id => els.get(id) || null, + createElement: tag => createMockElement(tag), + createTextNode: text => text, + }, + fetchImpl: async url => { + if (url === '/api/auth/captcha') { + return { + ok: true, + status: 200, + json: async () => ({ + provider: 'turnstile', + siteKey: '0x4AAAAAA', + action: 'sign-in', + }), + }; + } + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE', + features: ['OAuth'], + oauthProviders: ['Google', 'Apple'], + }, + }, + }), + }; + } + if (url === '/api/auth/preflight') { + if (preflightStatus !== 200) { + return { ok: false, status: preflightStatus }; + } + return { + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: true }, + magicLink: { available: true }, + }, + }), + }; + } + return { ok: true, status: 200 }; + }, + }); + + // Strict preflight failure shows error and stays on email step (never blind-submits sign-in). + els.get('email').value = 'alice@affine.pro'; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'email'); + assert.ok(els.get('auth-status').textContent.includes('403')); + + // Preflight 200 advances to password step; empty password is rejected without calling sign-in. + preflightStatus = 200; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'password'); + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal( + els.get('auth-status').textContent, + 'Please enter your password.' + ); + + // Switching to OTP triggers magic-link send and resets Turnstile token. + await els.get('switch-to-otp-btn').listeners.get('click')(); + assert.equal(page.getStep(), 'otp'); + assert.equal(turnstileResets, 1); + assert.equal(page.getCaptchaToken(), null); + page.dispose(); + + // Use local workspace navigates safely to '/'. + els.get('use-local-btn').listeners.get('click')(); + assert.equal(nav[0], '/'); + + // Verify Turnstile submit buttons disable on reset and re-enable when a new token arrives, + // and preflight with both password & magicLink unavailable stays on email with 0 sign-in calls. + let signInPostCount = 0; + let capturedTurnstileCb = null; + const els2 = new Map([ + ['auth-card', createMockElement('main')], + ['auth-status', createMockElement('p')], + ['sign-in-form', createMockElement('form')], + ['turnstile-container', createMockElement('div')], + ['step-email', createMockElement('section')], + ['step-password', createMockElement('section')], + ['step-otp', createMockElement('section')], + ['submit-button', createMockElement('button')], + ['password-submit-button', createMockElement('button')], + [ + 'otp-submit-button', + Object.assign(createMockElement('button'), { disabled: false }), + ], + ['switch-to-otp-btn', createMockElement('button')], + ['resend-otp-btn', createMockElement('button')], + [ + 'email', + Object.assign(createMockElement('input'), { + value: 'blocked@affine.pro', + }), + ], + ]); + const page2 = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in', + assign() {}, + }, + turnstile: { + render(_c, opts) { + capturedTurnstileCb = opts.callback; + return 'w-r5'; + }, + reset() {}, + }, + }, + doc: { + head: createMockElement('head'), + createElement: tag => createMockElement(tag), + getElementById: id => els2.get(id) || null, + }, + fetchImpl: async url => { + if (url === '/api/auth/captcha') { + return { + ok: true, + status: 200, + json: async () => ({ + provider: 'turnstile', + siteKey: '0x4AAA', + challenge: 'ch-r5', + }), + }; + } + if (url === '/api/auth/preflight') { + return { + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: false }, + magicLink: { available: false }, + }, + }), + }; + } + if (url === '/api/auth/sign-in') { + signInPostCount += 1; + } + return { ok: true, status: 200 }; + }, + }); + + // Before Turnstile issues token, captcha-consuming buttons are disabled while #otp-submit-button stays enabled. + assert.equal(els2.get('submit-button').disabled, true); + assert.equal(els2.get('password-submit-button').disabled, true); + assert.equal(els2.get('switch-to-otp-btn').disabled, true); + assert.equal(els2.get('resend-otp-btn').disabled, true); + assert.equal(els2.get('otp-submit-button').disabled, false); + capturedTurnstileCb('tok-r5'); + assert.equal(els2.get('submit-button').disabled, false); + assert.equal(els2.get('password-submit-button').disabled, false); + assert.equal(els2.get('switch-to-otp-btn').disabled, false); + assert.equal(els2.get('resend-otp-btn').disabled, false); + page2.resetTurnstile(); + assert.equal(els2.get('submit-button').disabled, true); + assert.equal(els2.get('password-submit-button').disabled, true); + assert.equal(els2.get('resend-otp-btn').disabled, true); + assert.equal(els2.get('otp-submit-button').disabled, false); + capturedTurnstileCb('tok-r5-2'); + assert.equal(els2.get('submit-button').disabled, false); + assert.equal(els2.get('resend-otp-btn').disabled, false); + + // Submitting email when both password and magicLink are unavailable stays on email with 0 sign-in calls. + await els2.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page2.getStep(), 'email'); + assert.equal( + els2.get('auth-status').textContent, + 'Email sign-in is not available for this account.' + ); + assert.equal(signInPostCount, 0); + + // Returning from password step to email step clears stale password and re-runs preflight for new email B. + const seenPreflightEmails = []; + const els3 = new Map(); + for (const id of [ + 'auth-card', + 'email', + 'password', + 'otp', + 'auth-status', + 'submit-button', + 'password-submit-button', + 'otp-submit-button', + 'back-from-password-btn', + 'back-from-otp-btn', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'sign-in-form', + ]) { + els3.set(id, createMockElement(id.endsWith('-form') ? 'form' : 'div')); + } + els3.get('email').value = 'a@affine.pro'; + let bSignInPosts = 0; + const page3 = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in', + assign() {}, + }, + }, + doc: { + head: createMockElement('head'), + cookie: '', + getElementById: id => els3.get(id) || null, + createElement: tag => createMockElement(tag), + }, + fetchImpl: async (url, init) => { + if (url === '/api/auth/captcha') { + return { ok: false, status: 404 }; + } + if (url === '/api/auth/preflight') { + const parsed = JSON.parse(init.body); + seenPreflightEmails.push(parsed.email); + if (parsed.email === 'a@affine.pro') { + return { + ok: true, + status: 200, + json: async () => ({ + methods: { + password: { available: true }, + magicLink: { available: true }, + }, + }), + }; + } + return { + ok: true, + status: 200, + json: async () => ({ + methods: { + password: { available: false }, + magicLink: { available: false }, + }, + }), + }; + } + if (url === '/api/auth/sign-in') { + bSignInPosts += 1; + } + return { ok: true, status: 200 }; + }, + }); + await els3.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page3.getStep(), 'password'); + els3.get('password').value = 'secret-a'; + els3.get('back-from-password-btn').listeners.get('click')(); + assert.equal(page3.getStep(), 'email'); + assert.equal(els3.get('password').value, ''); + els3.get('email').value = 'b@affine.pro'; + await els3.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.deepEqual(seenPreflightEmails, ['a@affine.pro', 'b@affine.pro']); + assert.equal(bSignInPosts, 0); + assert.equal(page3.getStep(), 'email'); + page3.dispose(); +}); + +void test('sign-in OTP 6-digit validation, 60s resend cooldown, anti-reentry, cross-Back cooldown, and deployment-type Terms notice', async () => { + assert.equal(isOfficialCloudHost('app.affine.pro'), true); + assert.equal(isOfficialCloudHost('mobile.affine.fail'), true); + assert.equal(isOfficialCloudHost('localhost'), false); + assert.equal(isOfficialCloudHost('127.0.0.1'), false); + assert.equal(isOfficialCloudHost('notes.example.org'), false); + + const els = new Map(); + for (const id of [ + 'auth-card', + 'auth-status', + 'auth-legal-notice', + 'sign-in-form', + 'step-email', + 'step-password', + 'step-otp', + 'step-email-display', + 'otp-email-display', + 'turnstile-container', + 'email', + 'password', + 'otp', + 'submit-button', + 'password-submit-button', + 'otp-submit-button', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'back-from-password-btn', + 'back-from-otp-btn', + ]) { + const el = createMockElement(id.endsWith('-btn') ? 'button' : 'div'); + el.hidden = + id === 'step-password' || id === 'step-otp' || id === 'auth-legal-notice'; + els.set(id, el); + } + els.get('sign-in-form').getAttribute = name => + name === 'action' ? '/api/auth/sign-in' : null; + els.get('email').value = 'otp@affine.pro'; + + let nowMs = 1_000_000; + const intervals = new Map(); + let nextTimerId = 1; + let clearedCount = 0; + const setIntervalImpl = fn => { + const id = nextTimerId++; + intervals.set(id, fn); + return id; + }; + const clearIntervalImpl = id => { + if (intervals.delete(id)) { + clearedCount += 1; + } + }; + const tickSeconds = count => { + for (let i = 0; i < count; i += 1) { + nowMs += 1000; + for (const fn of Array.from(intervals.values())) { + fn(); + } + } + }; + + let signInSendCount = 0; + let otpVerifyCount = 0; + let otpVerifyStatus = 400; + let holdSignInSend = null; + + const page = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in', + pathname: '/sign-in', + replace() {}, + }, + }, + doc: { + head: createMockElement('head'), + querySelectorAll: () => [], + getElementById: id => els.get(id) || null, + createElement: tag => createMockElement(tag), + }, + nowImpl: () => nowMs, + setIntervalImpl, + clearIntervalImpl, + fetchImpl: async url => { + if (url === '/api/auth/captcha') { + return { ok: false, status: 404 }; + } + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + type: 'Affine', + features: ['OAuth'], + oauthProviders: [], + }, + }, + }), + }; + } + if (url === '/api/auth/preflight') { + return { + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: false }, + magicLink: { available: true }, + }, + }), + }; + } + if (url === '/api/auth/sign-in') { + signInSendCount += 1; + if (holdSignInSend) { + await holdSignInSend; + } + return { ok: true, status: 200 }; + } + if (url === '/api/auth/magic-link') { + otpVerifyCount += 1; + return { ok: otpVerifyStatus === 200, status: otpVerifyStatus }; + } + return { ok: true, status: 200 }; + }, + }); + + // Official cloud deployment type displays the Terms & Privacy notice. + assert.equal(els.get('auth-legal-notice').hidden, false); + + // In-flight OTP send immediately disables buttons and prevents duplicate sends on double-click. + let releaseSend; + holdSignInSend = new Promise(resolve => { + releaseSend = resolve; + }); + const firstSubmit = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(page.getStep(), 'otp'); + assert.equal(els.get('resend-otp-btn').disabled, true); + // Concurrent resend click while in-flight must not trigger a second request. + await els.get('resend-otp-btn').listeners.get('click')(); + assert.equal(signInSendCount, 1); + releaseSend(); + holdSignInSend = null; + await firstSubmit; + + assert.equal(page.getResendCooldown(), 60); + assert.equal(els.get('resend-otp-btn').disabled, true); + assert.equal(els.get('resend-otp-btn').textContent, 'Resend in 60s'); + + // Invalid OTP inputs are rejected locally with 0 network calls (never resending email). + for (const invalidOtp of ['', '123', 'abcdef', '1234567']) { + els.get('otp').value = invalidOtp; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal( + els.get('auth-status').textContent, + 'Invalid verification code' + ); + assert.equal(els.get('auth-status').dataset.tone, 'error'); + } + assert.equal(signInSendCount, 1); + assert.equal(otpVerifyCount, 0); + + // Valid 6-digit OTP returning 400 or 401 displays friendly invalid code message. + for (const status of [400, 401]) { + otpVerifyStatus = status; + els.get('otp').value = '123456'; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal( + els.get('auth-status').textContent, + 'Invalid verification code' + ); + assert.equal(els.get('auth-status').dataset.tone, 'error'); + } + assert.equal(otpVerifyCount, 2); + + // Going Back clears the UI timer, but re-entering with the same email within 60s keeps remaining cooldown. + tickSeconds(15); + assert.equal(page.getResendCooldown(), 45); + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(page.getStep(), 'email'); + assert.equal(intervals.size, 0); + assert.ok(clearedCount >= 1); + nowMs += 5000; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'otp'); + assert.equal(signInSendCount, 1); + assert.equal(page.getResendCooldown(), 40); + assert.equal(els.get('resend-otp-btn').disabled, true); + assert.equal(els.get('resend-otp-btn').textContent, 'Resend in 40s'); + + // Cooldown ticks down and re-enables resend at 0. + tickSeconds(39); + assert.equal(page.getResendCooldown(), 1); + assert.equal(els.get('resend-otp-btn').disabled, true); + assert.equal(els.get('resend-otp-btn').textContent, 'Resend in 1s'); + tickSeconds(1); + assert.equal(page.getResendCooldown(), 0); + assert.equal(els.get('resend-otp-btn').disabled, false); + assert.equal(els.get('resend-otp-btn').textContent, 'Resend code'); + + // Clicking resend after expiry sends a new code and restarts the 60s timer. + await els.get('resend-otp-btn').listeners.get('click')(); + assert.equal(signInSendCount, 2); + assert.equal(page.getResendCooldown(), 60); + assert.equal(els.get('resend-otp-btn').disabled, true); + page.dispose(); + + // Localhost with non-Affine deployment type hides the official cloud Terms & Privacy notice. + const localLegal = createMockElement('p'); + localLegal.hidden = false; + const localPage = await bootSignInPage({ + win: { + location: { + href: 'http://localhost:3010/sign-in', + pathname: '/sign-in', + replace() {}, + }, + }, + doc: { + head: createMockElement('head'), + querySelectorAll: () => [], + getElementById: id => (id === 'auth-legal-notice' ? localLegal : null), + createElement: tag => createMockElement(tag), + }, + fetchImpl: async url => { + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'Local Instance', + type: 'Selfhosted', + features: [], + oauthProviders: [], + }, + }, + }), + }; + } + return { ok: false, status: 404 }; + }, + }); + assert.equal(localLegal.hidden, true); + localPage.dispose(); +}); + +void test('a11y tree enforces inert + tabindex exclusivity and mountSandboxedEmbed does not steal focus until activated', async () => { + const root = createMockElement('div'); + const ime = createMockElement('textarea'); + const embedLayer = createMockElement('div'); + const doc = { createElement: tag => createMockElement(tag) }; + + const a11y = createA11yTree({ doc, root, ime, embedLayer }); + const entry = a11y.getNode(a11y.defaultEntryId); + assert.equal(root.inert, false); + assert.equal(entry.getAttribute('tabindex'), '0'); + assert.equal(ime.tabIndex, -1); + assert.equal(embedLayer.inert, true); + + // Focus IME: a11y becomes inert + child tabindex=-1; embed remains inert. + a11y.setFocusOwner('ime'); + assert.equal(root.inert, true); + assert.equal(entry.getAttribute('tabindex'), '-1'); + assert.equal(embedLayer.inert, true); + assert.equal(ime.tabIndex, 0); + assert.equal(ime.readOnly, false); + + // Focus embed: ime becomes readOnly + tabIndex=-1; a11y stays inert; embed active. + a11y.setFocusOwner('embed'); + assert.equal(root.inert, true); + assert.equal(embedLayer.inert, false); + assert.equal(ime.readOnly, true); + assert.equal(ime.tabIndex, -1); + + // Keyboard-reachable activateA11yEntry restores a11y inert=false + tabindex=0. + assert.equal(a11y.activateA11yEntry(), true); + assert.equal(root.inert, false); + assert.equal(entry.getAttribute('tabindex'), '0'); + assert.equal(embedLayer.inert, true); + + // Returning to 'ime' or 'none' restores ime.readOnly = false. + a11y.setFocusOwner('embed'); + a11y.setFocusOwner('ime'); + assert.equal(ime.readOnly, false); + a11y.setFocusOwner('embed'); + a11y.setFocusOwner('none'); + assert.equal(ime.readOnly, false); + + // Wired through bootWebHost: mounting an embed must NOT steal IME focus until activated, and unmounting restores prior owner. + const hostRoot = createMockElement('div'); + const hostIme = createMockElement('textarea'); + const hostEmbed = createMockElement('div'); + const host = await bootWebHost({ + win: { + navigator: { gpu: {} }, + location: { href: 'https://app.affine.pro/', assign() {} }, + }, + doc: { + createElement: tag => createMockElement(tag), + getElementById(id) { + if (id === 'a11y-tree') return hostRoot; + if (id === 'ime') return hostIme; + if (id === 'embed-layer') return hostEmbed; + if (id === 'affine-build-manifest') { + return { + textContent: JSON.stringify({ + shellVersion: 'mobile-v1', + buildHash: 'a11y-hash', + appEntryJs: null, + workers: {}, + fonts: {}, + }), + }; + } + return null; + }, + }, + }); + + assert.equal(host.focusImeInGesture({ inputMode: 'text' }), true); + assert.equal(host.a11yTree.getFocusOwner(), 'ime'); + const embedCtrl = host.mountSandboxedEmbed({ + src: 'blob:https://app.affine.pro/embed-1', + }); + // Mounting alone keeps IME focus & readOnly=false! + assert.equal(host.a11yTree.getFocusOwner(), 'ime'); + assert.equal(hostIme.readOnly, false); + assert.equal(embedCtrl.iframe.getAttribute('tabindex'), '-1'); + + // Explicit activation transfers focus to embed; unmount restores IME! + embedCtrl.activate(); + assert.equal(host.a11yTree.getFocusOwner(), 'embed'); + assert.equal(hostIme.readOnly, true); + embedCtrl.unmount(); + assert.equal(host.a11yTree.getFocusOwner(), 'ime'); + assert.equal(hostIme.readOnly, false); + + host.dispose(); +}); + +void test('sign-in async preflight race discards stale response and binds OTP/resend/verify to step email', async () => { + const els = new Map(); + for (const id of [ + 'auth-card', + 'auth-status', + 'auth-legal-notice', + 'sign-in-form', + 'step-email', + 'step-password', + 'step-otp', + 'step-email-display', + 'otp-email-display', + 'email', + 'password', + 'otp', + 'submit-button', + 'password-submit-button', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'back-from-password-btn', + 'back-from-otp-btn', + ]) { + const el = createMockElement(id.endsWith('-btn') ? 'button' : 'div'); + el.hidden = + id === 'step-password' || id === 'step-otp' || id === 'auth-legal-notice'; + els.set(id, el); + } + els.get('sign-in-form').getAttribute = name => + name === 'action' ? '/api/auth/sign-in' : null; + + let nowMs = 2_000_000; + const preflightResolvers = new Map(); + const sentEmails = []; + const verifiedEmails = []; + + const page = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in', + pathname: '/sign-in', + replace() {}, + }, + }, + doc: { + head: createMockElement('head'), + querySelectorAll: () => [], + getElementById: id => els.get(id) || null, + createElement: tag => createMockElement(tag), + }, + nowImpl: () => nowMs, + fetchImpl: async (url, init) => { + if (url === '/api/auth/captcha') { + return { ok: false, status: 404 }; + } + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + type: 'Affine', + features: ['OAuth'], + oauthProviders: [], + }, + }, + }), + }; + } + if (url === '/api/auth/preflight') { + const body = JSON.parse(String(init?.body || '{}')); + return await new Promise(resolve => { + preflightResolvers.set(body.email, resolve); + }); + } + if (url === '/api/auth/sign-in') { + const body = JSON.parse(String(init?.body || '{}')); + sentEmails.push(body.email); + return { ok: true, status: 200 }; + } + if (url === '/api/auth/magic-link') { + const body = JSON.parse(String(init?.body || '{}')); + verifiedEmails.push(body.email); + return { ok: true, status: 200 }; + } + return { ok: true, status: 200 }; + }, + }); + + // Start preflight for A, then edit #email to B and submit B before A resolves. + els.get('email').value = 'a@affine.pro'; + const submitA = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + await Promise.resolve(); + + els.get('email').value = 'b@affine.pro'; + els.get('email').listeners.get('input')?.(); + const submitB = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + await Promise.resolve(); + + // Resolve B first -> enters OTP step for B and sends OTP to B. + preflightResolvers.get('b@affine.pro')({ + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: false }, + magicLink: { available: true }, + }, + }), + }); + await submitB; + assert.equal(page.getStep(), 'otp'); + assert.equal(els.get('otp-email-display').textContent, 'b@affine.pro'); + assert.deepEqual(sentEmails, ['b@affine.pro']); + + // Stale A preflight now resolves out-of-order -> must be discarded completely. + preflightResolvers.get('a@affine.pro')({ + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: true }, + magicLink: { available: true }, + }, + }), + }); + await submitA; + assert.equal(page.getStep(), 'otp'); + assert.equal(els.get('otp-email-display').textContent, 'b@affine.pro'); + assert.deepEqual(sentEmails, ['b@affine.pro']); + + // Even if #email.value is mutated while on OTP step, resend and verify stay bound to B. + els.get('email').value = 'tampered@affine.pro'; + nowMs += 61_000; + await els.get('resend-otp-btn').listeners.get('click')(); + assert.deepEqual(sentEmails, ['b@affine.pro', 'b@affine.pro']); + + els.get('otp').value = '654321'; + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.deepEqual(verifiedEmails, ['b@affine.pro']); + + page.dispose(); +}); + +void test('sign-in initial OTP send network failure shows error for immediate retry and discards if Back clicked', async () => { + const els = new Map(); + for (const id of [ + 'auth-card', + 'auth-status', + 'auth-legal-notice', + 'sign-in-form', + 'step-email', + 'step-password', + 'step-otp', + 'step-email-display', + 'otp-email-display', + 'email', + 'password', + 'otp', + 'submit-button', + 'password-submit-button', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'back-from-password-btn', + 'back-from-otp-btn', + ]) { + const el = createMockElement(id.endsWith('-btn') ? 'button' : 'div'); + el.hidden = + id === 'step-password' || id === 'step-otp' || id === 'auth-legal-notice'; + els.set(id, el); + } + els.get('sign-in-form').getAttribute = name => + name === 'action' ? '/api/auth/sign-in' : null; + els.get('email').value = 'net@affine.pro'; + + let sendAttempt = 0; + let rejectSecondSend = null; + const page = await bootSignInPage({ + win: { + location: { + href: 'https://app.affine.pro/sign-in', + pathname: '/sign-in', + replace() {}, + }, + }, + doc: { + head: createMockElement('head'), + querySelectorAll: () => [], + getElementById: id => els.get(id) || null, + createElement: tag => createMockElement(tag), + }, + fetchImpl: async url => { + if (url === '/api/auth/captcha') { + return { ok: false, status: 404 }; + } + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + type: 'Affine', + features: ['OAuth'], + oauthProviders: [], + }, + }, + }), + }; + } + if (url === '/api/auth/preflight') { + return { + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: false }, + magicLink: { available: true }, + }, + }), + }; + } + if (url === '/api/auth/sign-in') { + sendAttempt += 1; + if (sendAttempt === 1) { + throw new Error('offline'); + } + if (sendAttempt === 2) { + return { ok: true, status: 200 }; + } + return await new Promise((_, reject) => { + rejectSecondSend = reject; + }); + } + return { ok: true, status: 200 }; + }, + }); + + // 1. Initial send rejects -> stays on OTP, shows error, cooldown stays 0, resend works immediately. + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'otp'); + assert.equal( + els.get('auth-status').textContent, + 'Network error. Please try again.' + ); + assert.equal(page.getResendCooldown(), 0); + assert.equal(els.get('resend-otp-btn').disabled, false); + + await els.get('resend-otp-btn').listeners.get('click')(); + assert.equal(sendAttempt, 2); + assert.equal( + els.get('auth-status').textContent, + 'A new verification code has been sent.' + ); + + // 2. Back clicked before in-flight send rejects -> stale error silently discarded. + els.get('back-from-otp-btn').listeners.get('click')(); + els.get('email').value = 'other@affine.pro'; + const pendingSubmit = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + els.get('back-from-otp-btn').listeners.get('click')(); + rejectSecondSend?.(new Error('late network failure')); + await pendingSubmit; + assert.equal(page.getStep(), 'email'); + assert.equal(els.get('auth-status').textContent, ''); + + page.dispose(); +}); + +void test('sign-in Back during in-flight OTP send isolates Turnstile token, button busy state, and late per-email cooldown', async () => { + const els = new Map(); + for (const id of [ + 'auth-card', + 'auth-status', + 'auth-legal-notice', + 'sign-in-form', + 'step-email', + 'step-password', + 'step-otp', + 'step-email-display', + 'otp-email-display', + 'turnstile-container', + 'email', + 'password', + 'otp', + 'submit-button', + 'password-submit-button', + 'switch-to-otp-btn', + 'switch-to-password-btn', + 'resend-otp-btn', + 'back-from-password-btn', + 'back-from-otp-btn', + ]) { + const el = createMockElement(id.endsWith('-btn') ? 'button' : 'div'); + el.hidden = + id === 'step-password' || id === 'step-otp' || id === 'auth-legal-notice'; + els.set(id, el); + } + els.get('sign-in-form').getAttribute = name => + name === 'action' ? '/api/auth/sign-in' : null; + + let nowMs = 10_000; + let turnstileResets = 0; + /** @type {((token: string) => void) | null} */ + let deliverCaptchaToken = null; + /** @type {Array<{ email: string, token: string, resolve: (v: { ok: boolean, status: number }) => void, reject: (e: Error) => void }>} */ + const pendingSends = []; + + const page = await bootSignInPage({ + nowImpl: () => nowMs, + setIntervalImpl: () => ({ unref() {} }), + clearIntervalImpl: () => {}, + win: { + location: { + href: 'https://app.affine.pro/sign-in', + pathname: '/sign-in', + replace() {}, + }, + turnstile: { + render(_el, opts) { + deliverCaptchaToken = opts.callback; + opts.callback('tok-a1'); + return 'wid-inflight'; + }, + reset(wid) { + assert.equal(wid, 'wid-inflight'); + turnstileResets += 1; + }, + }, + }, + doc: { + head: createMockElement('head'), + querySelectorAll: () => [], + getElementById: id => els.get(id) || null, + createElement: tag => createMockElement(tag), + }, + fetchImpl: async (url, init) => { + if (url === '/api/auth/captcha') { + return { + ok: true, + status: 200, + json: async () => ({ + provider: 'turnstile', + siteKey: '0x4AAAAAA', + action: 'sign-in', + }), + }; + } + if (url === '/graphql') { + return { + ok: true, + status: 200, + json: async () => ({ + data: { + serverConfig: { + name: 'AFFiNE Cloud', + features: [], + oauthProviders: [], + }, + }, + }), + }; + } + if (url === '/api/auth/preflight') { + return { + ok: true, + status: 200, + json: async () => ({ + registered: true, + methods: { + password: { available: false }, + magicLink: { available: true }, + }, + }), + }; + } + if (url === '/api/auth/sign-in') { + const body = JSON.parse(init.body); + return await new Promise((resolve, reject) => { + pendingSends.push({ + email: body.email, + token: init.headers['x-captcha-token'], + resolve, + reject, + }); + }); + } + return { ok: true, status: 200 }; + }, + }); + + // 1. Start OTP send for A; while A is in flight, click Back, enter B, and solve Turnstile. + els.get('email').value = 'a@affine.pro'; + const submitA = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + for (let i = 0; i < 6 && pendingSends.length < 1; i += 1) { + await Promise.resolve(); + } + assert.equal(pendingSends.length, 1); + assert.equal(pendingSends[0].email, 'a@affine.pro'); + assert.equal(pendingSends[0].token, 'tok-a1'); + assert.equal(els.get('resend-otp-btn').disabled, true); + + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(page.getStep(), 'email'); + assert.equal(turnstileResets, 1); + assert.equal(els.get('submit-button').disabled, true); + + els.get('email').value = 'b@affine.pro'; + els.get('email').listeners.get('input')(); + deliverCaptchaToken?.('tok-b1'); + // Continue button for B must be enabled immediately even while A's send is still in flight. + assert.equal(els.get('submit-button').disabled, false); + assert.equal(page.getCaptchaToken(), 'tok-b1'); + + // 2. Submit B while A is still in flight: B sends its own OTP with tok-b1, and A finishing + // late must neither reset Turnstile nor clear B's in-flight resend lock, yet MUST record A's 60s cooldown. + const submitB = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + for (let i = 0; i < 6 && pendingSends.length < 2; i += 1) { + await Promise.resolve(); + } + assert.equal(pendingSends.length, 2); + assert.equal(pendingSends[1].email, 'b@affine.pro'); + assert.equal(pendingSends[1].token, 'tok-b1'); + assert.equal(page.getStep(), 'otp'); + assert.equal(els.get('resend-otp-btn').disabled, true); + + deliverCaptchaToken?.('tok-b2'); + pendingSends[0].resolve({ ok: true, status: 200 }); + await submitA; + assert.equal(turnstileResets, 1); + assert.equal(page.getCaptchaToken(), 'tok-b2'); + assert.equal(els.get('resend-otp-btn').disabled, true); + assert.equal(page.getResendCooldown(), 0); + + pendingSends[1].resolve({ ok: false, status: 500 }); + await submitB; + assert.equal(turnstileResets, 2); + assert.equal(page.getResendCooldown(), 0); + assert.equal( + els.get('auth-status').textContent, + 'Failed to send code (500).' + ); + + // 3. Re-enter A within 60s: A's late success recorded cooldown so NO second /api/auth/sign-in is sent. + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(turnstileResets, 3); + deliverCaptchaToken?.('tok-a2'); + assert.equal(els.get('submit-button').disabled, false); + + els.get('email').value = 'a@affine.pro'; + els.get('email').listeners.get('input')(); + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'otp'); + assert.equal(pendingSends.length, 2); + assert.equal(page.getResendCooldown(), 60); + assert.equal(els.get('resend-otp-btn').textContent, 'Resend in 60s'); + assert.equal(els.get('resend-otp-btn').disabled, true); + assert.equal(turnstileResets, 3); + assert.equal(page.getCaptchaToken(), 'tok-a2'); + + // 4. Late failure after Back does NOT record cooldown: start C, click Back, reject C, re-enter C -> sends again. + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(turnstileResets, 4); + deliverCaptchaToken?.('tok-c1'); + els.get('email').value = 'c@affine.pro'; + els.get('email').listeners.get('input')(); + const submitC1 = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + for (let i = 0; i < 6 && pendingSends.length < 3; i += 1) { + await Promise.resolve(); + } + assert.equal(pendingSends.length, 3); + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(turnstileResets, 5); + deliverCaptchaToken?.('tok-c2'); + pendingSends[2].reject(new Error('offline-c')); + await submitC1; + assert.equal(turnstileResets, 5); + assert.equal(page.getCaptchaToken(), 'tok-c2'); + + const submitC2 = els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + for (let i = 0; i < 6 && pendingSends.length < 4; i += 1) { + await Promise.resolve(); + } + assert.equal(pendingSends.length, 4); + assert.equal(pendingSends[3].email, 'c@affine.pro'); + + // 5. Click Back from C2 while C2 is STILL in flight, and immediately re-enter C BEFORE C2 settles: + // C2 finishing must preserve tok-c3 while starting C's 60s countdown. + els.get('back-from-otp-btn').listeners.get('click')(); + assert.equal(turnstileResets, 6); + deliverCaptchaToken?.('tok-c3'); + await els.get('sign-in-form').listeners.get('submit')({ + preventDefault() {}, + }); + assert.equal(page.getStep(), 'otp'); + assert.equal(pendingSends.length, 4); + assert.equal(els.get('resend-otp-btn').disabled, true); + pendingSends[3].resolve({ ok: true, status: 200 }); + await submitC2; + assert.equal(turnstileResets, 6); + assert.equal(page.getCaptchaToken(), 'tok-c3'); + assert.equal(page.getResendCooldown(), 60); + + page.dispose(); +}); diff --git a/packages/frontend/hosts/web/tests/web-host.test.mjs b/packages/frontend/hosts/web/tests/web-host.test.mjs new file mode 100644 index 0000000000..c343b6709f --- /dev/null +++ b/packages/frontend/hosts/web/tests/web-host.test.mjs @@ -0,0 +1,5422 @@ +import assert from 'node:assert/strict'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { stageCanaryDualShell } from '../scripts/stage-canary-dual-shell.mjs'; +import { stageVerificationBundle } from '../scripts/verify-canary-dual-shell-e2e.mjs'; +import { verifyZeroThirdPartyJs } from '../scripts/verify-zero-third-party-js.mjs'; +import { createA11yTree } from '../src/a11y.js'; +import { + bootWebHost, + buildLegacyFallbackUrl, + createGpuRecoveryController, + createSafeAreaTracker, + createSandboxedEmbedIframe, + detectGraphicsSupport, + flushBeforeNavigation, + flushPendingBeforeRedirect, + focusImeInGesture, + hideRuntimeFatal, + isLegacyShellUrl, + observeSafeAreaProbe, + removeBootSkeleton, + sanitizeEmbedSandbox, + showBootFatal, + validateEmbedSrc, +} from '../src/host.js'; +import { createIdbWorkspaceStorage } from '../src/idb-storage.js'; +import { + buildPdfPageCacheKey, + createPdfPreviewClient, +} from '../src/pdf-client.js'; +import { + attachImeSelectionGuard, + computeSelectionOverlayLayout, + createSelectionOverlayController, + drawSelectionOverlay, + executeClipboardAction, + resolveSelectionLocale, + SELECTION_MENU_FONT, +} from '../src/selection-overlay.js'; +import { + bootSignInPage, + classifyAuthRoute, + isAllowedRedirectTarget, + maybeLoadTurnstile, + submitSignInForm, + TURNSTILE_SCRIPT_URL, +} from '../src/sign-in.js'; +import { + buildWorkerBootstrapSource, + createWorkerLoader, +} from '../src/worker-loader.js'; +import { startPreviewWorker } from '../src/workers/preview-worker-core.js'; +import { writeWasmFixture } from './dual-shell-wasm-fixture.mjs'; + +const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const HOSTS_ROOT = resolve(WEB_ROOT, '..'); + +async function drainMicrotasks(ticks = 16) { + for (let i = 0; i < ticks; i += 1) { + await Promise.resolve(); + } +} + +function walkFiles(dir) { + const out = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + out.push(...walkFiles(full)); + } else if (entry.isFile()) { + out.push(full); + } + } + return out; +} + +void test('static gate: zero package.json, wasm-safe CSP, and DOM whitelist', () => { + const hostFiles = walkFiles(HOSTS_ROOT); + const forbiddenPkg = hostFiles.filter( + file => file.endsWith('/package.json') || file.endsWith('/yarn.lock') + ); + assert.deepEqual(forbiddenPkg, []); + + const srcDir = join(WEB_ROOT, 'src'); + const srcFiles = walkFiles(srcDir).filter(file => file.endsWith('.js')); + assert.ok(srcFiles.length >= 3); + + const importRe = /^\s*import\s+[^'"]*from\s+['"]([^'"]+)['"]/gm; + const createElRe = /createElement\(\s*['"]([^'"]+)['"]\s*\)/g; + const allowedTags = new Set(['canvas', 'iframe', 'script', 'div', 'button']); + + for (const file of srcFiles) { + const text = readFileSync(file, 'utf8'); + for (const match of text.matchAll(importRe)) { + const specifier = match[1]; + assert.ok( + specifier.startsWith('./') || specifier.startsWith('../'), + `${file}: external import "${specifier}" is forbidden` + ); + } + for (const match of text.matchAll(createElRe)) { + const tag = match[1].toLowerCase(); + assert.ok(allowedTags.has(tag), `${file}: unexpected created tag ${tag}`); + if (tag === 'script') { + assert.ok( + file.endsWith('/sign-in.js'), + `script creation is only allowed in sign-in.js, found in ${file}` + ); + } + if (tag === 'button') { + assert.ok( + file.endsWith('/sign-in.js') || file.endsWith('/host.js'), + `button creation is only allowed in sign-in.js or host.js, found in ${file}` + ); + } + if (tag === 'div') { + assert.ok( + file.endsWith('/a11y.js') || file.endsWith('/host.js'), + `div creation is only allowed in a11y.js or host.js, found in ${file}` + ); + } + } + } + + const indexHtml = readFileSync(join(WEB_ROOT, 'index.html'), 'utf8'); + assert.match( + indexHtml, + /script-src 'self' 'wasm-unsafe-eval' 'sha256-[\w+/]{43}=';/ + ); + assert.ok(!indexHtml.includes('challenges.cloudflare.com')); + assert.ok(indexHtml.includes('')); + assert.ok( + indexHtml.includes( + '
' + ) + ); + assert.ok(indexHtml.includes('"mermaid"')); + assert.ok(indexHtml.includes('"math"')); + assert.ok(indexHtml.includes('"typst"')); + assert.ok(indexHtml.includes('"pdf"')); + assert.ok(!indexHtml.includes('.woff2')); + assert.ok( + indexHtml.includes('') + ); + assert.equal( + new URL( + '/src/host.js', + 'https://app.affine.pro/workspace/ws-1/doc-2' + ).toString(), + 'https://app.affine.pro/src/host.js' + ); + + const signInHtml = readFileSync(join(WEB_ROOT, 'sign-in.html'), 'utf8'); + assert.ok(signInHtml.includes('autocomplete="username"')); + assert.ok(signInHtml.includes('autocomplete="current-password"')); + assert.ok(signInHtml.includes('autocomplete="one-time-code"')); + assert.ok( + signInHtml.includes('') + ); + assert.ok( + !signInHtml.includes(''), + ['inline executable script is forbidden'], + ], + ]) { + writeFileSync(index, page); + const { violations } = verifyZeroThirdPartyJs({ + webRoot, + hostsRoot: webRoot, + }); + assert.equal(violations.length, expected.length, violations.join('\n')); + for (const message of expected) { + assert.ok(violations.some(v => v.includes(`index.html: ${message}`))); + } + } +}); + +void test('verifyZeroThirdPartyJs passes on repo and catches forbidden imports, scripts, and manifests', () => { + const realReport = verifyZeroThirdPartyJs(); + assert.equal( + realReport.ok, + true, + `Expected 0 violations, got: ${realReport.violations.join('; ')}` + ); + assert.ok(realReport.checkedFiles >= 8); + + const tmp = mkdtempSync(join(tmpdir(), 'affine-zero-js-gate-')); + try { + const fakeWeb = join(tmp, 'web'); + mkdirSync(join(fakeWeb, 'src'), { recursive: true }); + writeFileSync(join(tmp, 'package.json'), '{"name":"bad"}'); + writeFileSync( + join(fakeWeb, 'src/bad.js'), + "import {\n useState,\n} from 'react';\nexport {\n debounce,\n} from 'lodash';\nconst s = document.createElement('script');\ns.src = 'https://evil.example/a.js';\n" + ); + writeFileSync( + join(fakeWeb, 'index.html'), + '
' + ); + const badReport = verifyZeroThirdPartyJs({ + webRoot: fakeWeb, + hostsRoot: tmp, + }); + assert.equal(badReport.ok, false); + assert.ok(badReport.violations.some(v => v.includes('package.json'))); + assert.ok(badReport.violations.some(v => v.includes('react'))); + assert.ok(badReport.violations.some(v => v.includes('lodash'))); + assert.ok(badReport.violations.some(v => v.includes('cdn.evil.com'))); + assert.ok(badReport.violations.some(v => v.includes('floating-menu'))); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +void test('gpu recovery single-flight mutex blocks late restore, deduplicates concurrent losses, pauses timer when hidden, and recreates runtime #boot retry UI', async () => { + const tick = () => new Promise(r => setTimeout(r, 0)); + + // 1. Late webglcontextrestored while fallback flush is in flight must not resume input or overwrite state. + for (const flushOk of [true, false]) { + let resolveFlush; + const log = []; + const ctrl = createGpuRecoveryController({ + getHref: () => 'https://app.affine.pro/workspace/ws-1', + isOAuthCodeConsumed: () => false, + pauseInput: () => log.push('pause'), + resumeInput: () => log.push('resume'), + freezeFrameLoop: () => log.push('freeze'), + unfreezeFrameLoop: () => log.push('unfreeze'), + flushPendingWrites: () => + new Promise(r => { + log.push('flush-start'); + resolveFlush = () => + r({ ok: flushOk, pendingCount: flushOk ? 0 : 1 }); + }), + navigate: url => log.push(`nav:${new URL(url).search}`), + showFatal: (_msg, opts) => + log.push(`fatal:retry=${Boolean(opts?.retryable)}`), + onContextRestored: () => true, + }); + + const fallbackPromise = ctrl.triggerFallback('context-restore-timeout'); + assert.equal(ctrl.getState().status, 'fallback-pending'); + + const lateRestore = await ctrl.handleWebGlContextRestored(); + assert.equal(lateRestore.recovered, false); + assert.equal(ctrl.getState().status, 'fallback-pending'); + assert.equal(ctrl.getState().inputPaused, true); + assert.equal(log.includes('resume'), false); + + // Concurrent loss events during fallback-pending must not start extra flushes. + ctrl.handleWebGlContextLost({ preventDefault() {} }); + ctrl.handleWebGlContextLost({ preventDefault() {} }); + resolveFlush(); + await fallbackPromise; + await tick(); + + assert.equal(log.filter(x => x === 'flush-start').length, 1); + assert.equal(log.filter(x => x.startsWith('nav:')).length, flushOk ? 1 : 0); + assert.equal( + ctrl.getState().status, + flushOk ? 'fallback-navigated' : 'fallback-blocked' + ); + } + + // 2. Visibility hidden pauses restore timeout; visible resumes it. + let hidden = true; + let timerCallbacks = []; + const visCtrl = createGpuRecoveryController({ + getHref: () => 'https://app.affine.pro/doc/1', + isOAuthCodeConsumed: () => false, + isDocumentHidden: () => hidden, + pauseInput() {}, + resumeInput() {}, + flushPendingWrites: async () => ({ ok: true, pendingCount: 0 }), + navigate() {}, + setTimer: fn => { + timerCallbacks.push(fn); + return timerCallbacks.length; + }, + clearTimer() { + timerCallbacks = []; + }, + }); + visCtrl.handleWebGlContextLost({ preventDefault() {} }); + assert.equal(timerCallbacks.length, 0); + hidden = false; + visCtrl.handleVisibilityChange(false); + assert.equal(timerCallbacks.length, 1); + + // 3. Post-boot showBootFatal recreates #boot on doc.body with clickable #gpu-fallback-retry. + const elements = new Map(); + const makeNode = tag => { + const node = { + tag, + id: '', + dataset: {}, + style: {}, + textContent: '', + disabled: false, + onclick: null, + children: [], + setAttribute() {}, + append(child) { + this.children.push(child); + if (child.id) elements.set(child.id, child); + }, + remove() { + if (this.id) elements.delete(this.id); + for (const c of this.children) { + if (c.id) elements.delete(c.id); + } + }, + }; + return node; + }; + const body = makeNode('body'); + const bootInit = makeNode('div'); + bootInit.id = 'boot'; + elements.set('boot', bootInit); + const fakeDoc = { + body, + createElement: makeNode, + getElementById: id => elements.get(id) || null, + querySelectorAll: () => [], + }; + + removeBootSkeleton(/** @type {any} */ (fakeDoc)); + assert.equal(fakeDoc.getElementById('boot'), null); + + let retryClicked = 0; + showBootFatal( + /** @type {any} */ (fakeDoc), + 'Unable to save pending edits. Tap Retry to try again.', + { + retryable: true, + onRetry: () => { + retryClicked += 1; + }, + } + ); + assert.ok(fakeDoc.getElementById('boot')); + assert.equal( + fakeDoc.getElementById('boot-message')?.textContent, + 'Unable to save pending edits. Tap Retry to try again.' + ); + const retryBtn = fakeDoc.getElementById('gpu-fallback-retry'); + assert.ok(retryBtn); + retryBtn.onclick(); + assert.equal(retryClicked, 1); + hideRuntimeFatal(/** @type {any} */ (fakeDoc)); + assert.equal(fakeDoc.getElementById('boot'), null); +}); + +void test('pdf client keeps at most 8 documents open, waits for room, rejects out-of-range sizes, and reopens after a failed open', async () => { + /** @type {any[]} */ + const posted = []; + /** @type {Set<(ev: { data: any }) => void>} */ + const listeners = new Set(); + const client = createPdfPreviewClient({ + workerLoader: { + loadWorker: () => ({ + postMessage(msg) { + posted.push(msg); + }, + addEventListener(type, fn) { + if (type === 'message') listeners.add(fn); + }, + removeEventListener(type, fn) { + if (type === 'message') listeners.delete(fn); + }, + terminate() {}, + }), + }, + }); + const answer = (msg, data) => { + for (const fn of listeners) fn({ data: { id: msg.id, ...data } }); + }; + const opens = () => posted.filter(msg => msg.op === 'pdf_open'); + // Runs every pending promise reaction before the next check. + const tick = () => new Promise(resolve => setImmediate(resolve)); + + const counts = Array.from({ length: 9 }, (_, i) => + client.getPageCount({ docKey: `doc-${i}`, pdfBytes: Uint8Array.of(i + 1) }) + ); + assert.equal(opens().length, 8, 'the ninth open waits for room'); + assert.equal(client.getStats().openDocs, 8); + + // An answered open frees its document: the ninth one replaces it. + answer(opens()[0], { ok: true, result: { pageCount: 1 } }); + assert.equal(await counts[0], 1); + await tick(); + assert.deepEqual( + posted.slice(8).map(msg => [msg.op, msg.docId]), + [ + ['pdf_close', 1], + ['pdf_open', 9], + ] + ); + assert.equal(client.getStats().openDocs, 8); + + // A failed open frees its slot and the next request opens the bytes again. + answer(opens()[1], { ok: false, error: 'Decryption(PasswordProtected)' }); + await assert.rejects(counts[1], /PasswordProtected/); + await tick(); + assert.equal(client.getStats().openDocs, 7); + const retry = client.getPageCount({ + docKey: 'doc-1', + pdfBytes: Uint8Array.of(2), + }); + assert.deepEqual([posted.at(-1).op, posted.at(-1).docId], ['pdf_open', 10]); + answer(posted.at(-1), { ok: true, result: { pageCount: 4 } }); + assert.equal(await retry, 4); + + const before = posted.length; + for (const pdfBytes of [ + new Uint8Array(0), + { byteLength: 256 * 1024 * 1024 + 1 }, + ]) { + await assert.rejects( + client.getPageCount({ + docKey: 'bad', + pdfBytes: /** @type {any} */ (pdfBytes), + }), + /worker limit/ + ); + await assert.rejects( + client.renderPage({ + docKey: 'bad', + pdfBytes: /** @type {any} */ (pdfBytes), + pageIndex: 0, + }), + /worker limit/ + ); + } + assert.equal( + posted.length, + before, + 'out-of-range sizes never reach the worker' + ); + client.dispose(); + await Promise.allSettled(counts); +}); + +void test('pdf client recovers from worker error by spawning a fresh worker and protects cached RGBA buffers from caller transfer', async () => { + let spawnCount = 0; + let respond = false; + let currentListeners = null; + const sentScales = []; + + const makeMockWorker = () => { + const listeners = { message: new Set(), error: new Set() }; + currentListeners = listeners; + return { + postMessage(msg) { + sentScales.push(msg.scale); + if (!respond) return; + queueMicrotask(() => { + const rgba = new Uint8Array(64).fill(42); + for (const fn of listeners.message) { + fn({ + data: { + id: msg.id, + ok: true, + result: { pageCount: 2, widthPx: 4, heightPx: 4, rgba }, + }, + }); + } + }); + }, + addEventListener: (t, fn) => listeners[t]?.add(fn), + removeEventListener: (t, fn) => listeners[t]?.delete(fn), + terminate() {}, + }; + }; + + const client = createPdfPreviewClient({ + workerLoader: { + loadWorker() { + spawnCount += 1; + return makeMockWorker(); + }, + terminateWorker() { + return true; + }, + }, + }); + + const pdfBytes = new Uint8Array(16); + const failed = client.renderPage({ docKey: 'd1', pdfBytes, pageIndex: 0 }); + for (const fn of currentListeners.error) { + fn({ message: 'worker crashed' }); + } + await assert.rejects(failed, /worker crashed/); + assert.equal(spawnCount, 1); + + // Next request spawns a fresh worker and succeeds; concurrent dedup returns independent buffers. + respond = true; + const [pA, pB] = await Promise.all([ + client.renderPage({ docKey: 'd1', pdfBytes, pageIndex: 0, scale: 8 }), + client.renderPage({ docKey: 'd1', pdfBytes, pageIndex: 0, scale: 4 }), + ]); + assert.equal(spawnCount, 2); + assert.equal(pA.scale, 4); + assert.equal(pB.scale, 4); + assert.equal(client.getStats().dedupHits, 1); + assert.notEqual(pA.rgba, pB.rgba); + + // Transferring caller A's buffer must NOT empty caller B's buffer or the cached entry. + structuredClone(pA.rgba.buffer, { transfer: [pA.rgba.buffer] }); + assert.equal(pA.rgba.byteLength, 0); + assert.equal(pB.rgba.byteLength, 64); + + const cached = await client.renderPage({ + docKey: 'd1', + pdfBytes, + pageIndex: 0, + scale: 8, + }); + assert.equal(cached.fromCache, true); + assert.equal(cached.scale, 4); + assert.equal(cached.rgba.byteLength, 64); + assert.equal(cached.rgba[0], 42); + + // Scale below 0.25 clamps to 0.25 before cache lookup and worker RPC. + const lowScale = await client.renderPage({ + docKey: 'd1', + pdfBytes, + pageIndex: 1, + scale: 0.1, + }); + assert.equal(lowScale.scale, 0.25); + assert.equal(sentScales.at(-1), 0.25); + client.dispose(); +}); + +void test('stale async restore epoch cannot overwrite fallback-pending, async Cut aborts when selection changes, and WebGPU setScene presents frames', async () => { + // 1. Stale async onContextRestored resolving after a newer contextlost tripped fallback-pending. + let resolveRestore; + let resolveFlush; + const events = []; + const ctrl = createGpuRecoveryController({ + getHref: () => 'https://app.affine.pro/workspace/ws-1/doc-1', + isOAuthCodeConsumed: () => false, + pauseInput: () => events.push('pause'), + resumeInput: () => events.push('resume'), + freezeFrameLoop: () => events.push('freeze'), + unfreezeFrameLoop: () => events.push('unfreeze'), + onContextRestored: () => + new Promise(r => { + resolveRestore = () => r(true); + }), + flushPendingWrites: () => + new Promise(r => { + events.push('flush-start'); + resolveFlush = () => r({ ok: true, pendingCount: 0 }); + }), + navigate: url => events.push(`nav:${new URL(url).search}`), + maxContextLosses: 2, + }); + + ctrl.handleWebGlContextLost({ preventDefault() {} }); + const staleRestorePromise = ctrl.handleWebGlContextRestored(); + // Second loss arrives before async restore finishes -> trips fallback-pending. + ctrl.handleWebGlContextLost({ preventDefault() {} }); + assert.equal(ctrl.getState().status, 'fallback-pending'); + + // Stale restore now resolves true -> must NOT revert status or resume input. + resolveRestore(); + const staleResult = await staleRestorePromise; + assert.equal(staleResult.recovered, false); + assert.equal(ctrl.getState().status, 'fallback-pending'); + assert.equal(ctrl.getState().inputPaused, true); + assert.equal(events.includes('resume'), false); + + resolveFlush(); + await new Promise(r => setTimeout(r, 0)); + assert.equal(ctrl.getState().status, 'fallback-navigated'); + + // 2. Async Cut aborts deleteSelection when selection moves from "A" to "B" mid-write. + let docText = 'AB'; + let selectedRange = 'A'; + let selectionToken = 'sel-0-1'; + let resolveWrite; + const cutPromise = executeClipboardAction({ + action: 'cut', + getSelectedText: () => selectedRange, + getSelectionToken: () => selectionToken, + deleteSelection: () => { + docText = docText.replace(selectedRange, ''); + }, + isSecureContext: true, + clipboard: { + writeText: () => + new Promise(r => { + resolveWrite = r; + }), + }, + }); + selectedRange = 'B'; + selectionToken = 'sel-1-2'; + resolveWrite(); + const cutRes = await cutPromise; + assert.equal(cutRes.ok, false); + assert.equal(cutRes.reason, 'selection-changed-during-cut'); + assert.equal(docText, 'AB'); + + // 3. Sandwiched bare side-effect import before semicolon is caught by verifyZeroThirdPartyJs. + const tmp = mkdtempSync(join(tmpdir(), 'affine-zero-js-semi-')); + try { + const fakeWeb = join(tmp, 'web'); + mkdirSync(join(fakeWeb, 'src'), { recursive: true }); + writeFileSync( + join(fakeWeb, 'src/sandwich.js'), + "import 'evil-polyfill';\nimport { ok } from './ok.js';\nexport const v = ok;\n" + ); + writeFileSync( + join(fakeWeb, 'index.html'), + '
' + ); + const report = verifyZeroThirdPartyJs({ webRoot: fakeWeb, hostsRoot: tmp }); + assert.equal(report.ok, false); + assert.ok(report.violations.some(v => v.includes('evil-polyfill'))); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } + + // 4. WebGPU first frame followed by setScene presents a second frame and returns true. + let submitCount = 0; + let copyCalls = 0; + const webGpuCanvas = { + id: 'app-canvas', + width: 390, + height: 844, + getContext(kind) { + if (kind === 'webgpu') { + return { + configure() {}, + getCurrentTexture: () => ({ createView: () => ({}) }), + }; + } + return null; + }, + addEventListener() {}, + removeEventListener() {}, + }; + const fakeGpuNav = { + gpu: { + getPreferredCanvasFormat: () => 'bgra8unorm', + requestAdapter: async () => ({ + requestDevice: async () => ({ + lost: new Promise(() => {}), + createCommandEncoder: () => ({ + beginRenderPass: () => ({ end() {} }), + finish: () => ({}), + }), + queue: { + copyExternalImageToTexture: () => { + copyCalls += 1; + }, + submit: () => { + submitCount += 1; + }, + }, + }), + }), + }, + }; + const indexHtml = readFileSync(join(WEB_ROOT, 'index.html'), 'utf8'); + const manifestJson = indexHtml + .match( + /