diff --git a/.github/workflows/package-ios.yml b/.github/workflows/package-ios.yml index cb0b3e9..e57e3b4 100644 --- a/.github/workflows/package-ios.yml +++ b/.github/workflows/package-ios.yml @@ -1,16 +1,23 @@ name: package-ios -# Manual only. A macOS runner is required and this file does not run on push. +# Manual, or called by package.yml. A macOS runner is required. +# unsigned: device IPA with no Apple signature, for TrollStore or a jailbroken device only. on: workflow_dispatch: inputs: target: - description: simulator builds a .app for the iOS Simulator. device exports an IPA only when signing secrets are set. + description: unsigned = device IPA without an Apple signature (TrollStore / jailbreak sideload). simulator = .app for the iOS Simulator. device = signed IPA, only when signing secrets are set. type: choice options: + - unsigned - simulator - device - default: simulator + default: unsigned + workflow_call: + inputs: + target: + type: string + default: unsigned permissions: contents: read @@ -18,6 +25,7 @@ permissions: jobs: ios: runs-on: macos-latest + timeout-minutes: 90 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable @@ -31,9 +39,23 @@ jobs: - uses: Swatinem/rust-cache@v2 with: workspaces: src-tauri - - name: CocoaPods - run: brew install cocoapods + - name: Build tools + run: | + brew install cocoapods xcodegen + brew install ldid || echo "ldid is unavailable; the IPA will carry no ad-hoc signature." - run: npm ci + - name: Unsigned IPA + if: inputs.target == 'unsigned' + run: bash scripts/package-ios.sh --unsigned + - name: Check the unsigned IPA + if: inputs.target == 'unsigned' + run: | + cd packaging/out + ls -l + shasum -a 256 -c SHA256SUMS + ipa="$(ls *-ios-unsigned.ipa)" + unzip -l "$ipa" | grep -E 'Payload/[^/]+\.app/(Info\.plist|AppIcon)' | head -20 + cat PROVENANCE-ios.txt - name: Simulator app if: inputs.target == 'simulator' run: bash scripts/package-ios.sh --simulator @@ -48,10 +70,19 @@ jobs: APPLE_API_KEY_PATH: ${{ secrets.APPLE_API_KEY_PATH }} run: bash scripts/package-ios.sh --device - uses: actions/upload-artifact@v4 - if: always() && hashFiles('packaging/out/**') != '' + if: inputs.target == 'unsigned' with: name: mathscrap-ios + path: | + packaging/out/*.ipa + packaging/out/PROVENANCE-ios.txt + packaging/out/SHA256SUMS + if-no-files-found: error + - uses: actions/upload-artifact@v4 + if: always() && inputs.target != 'unsigned' && hashFiles('packaging/out/**') != '' + with: + name: mathscrap-ios-${{ inputs.target }} path: | packaging/out/* src-tauri/gen/apple/**/*.app - if-no-files-found: warn + if-no-files-found: warn \ No newline at end of file diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 6ff01ff..90620c8 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -1,5 +1,12 @@ name: package +# Change-aware CI. The scope job classifies the diff (scripts/ci-scope.mjs): +# docs consistency checks only; no math suite, no packages +# version consistency checks; packages build on push to main (release bump) +# packaging consistency checks plus real package builds (also on pull requests); no math suite +# full the whole math suite, then packages on push to main +# Mixed or unclassified changes are full. ci-ok is the single status to require: +# skipped jobs pass it, failed or cancelled jobs fail it. on: push: branches: @@ -15,9 +22,13 @@ on: type: boolean default: false sign_android: - description: Sign the release APK with ANDROID_KEY_* + description: Sign the release APK with ANDROID_KEY_* type: boolean default: false + build_ios: + description: Build the unsigned iOS IPA (TrollStore / jailbreak sideload only) + type: boolean + default: true permissions: contents: read @@ -27,8 +38,10 @@ concurrency: cancel-in-progress: true jobs: - test: + scope: runs-on: ubuntu-latest + outputs: + mode: ${{ steps.scope.outputs.mode }} steps: - uses: actions/checkout@v4 with: @@ -36,7 +49,6 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - cache: npm - name: Classify changes id: scope env: @@ -48,22 +60,58 @@ jobs: PR_NUMBER: ${{ github.event.pull_request.number }} PUSH_BEFORE: ${{ github.event.before }} run: node scripts/ci-scope.mjs + + # Lightweight consistency checks. They run for every change, in seconds. + checks: + needs: scope + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 - name: Check recorded versions - if: steps.scope.outputs.mode == 'light' run: node scripts/ci-version-check.mjs + - name: Classifier regression + run: node scripts/ci-scope-smoke.mjs + - name: Packaging script syntax + run: | + for f in scripts/package-*.sh; do bash -n "$f"; echo "ok $f"; done + for f in scripts/*.mjs; do node --check "$f"; done + set +e + bash scripts/package-ios.sh --unsigned > /tmp/ios.txt 2>&1 + code=$? + set -e + if [ "$code" -ne 3 ]; then cat /tmp/ios.txt; echo "package-ios.sh on Linux should stop with exit 3, got $code"; exit 1; fi + - name: Workflow YAML + run: | + python3 - <<'PY' + import glob, yaml + for path in sorted(glob.glob('.github/workflows/*.yml')): + with open(path, encoding='utf-8') as fh: + doc = yaml.safe_load(fh) + assert isinstance(doc, dict) and doc.get('jobs'), path + print('ok', path) + PY + + # The math suite. Only for full changes. + test: + needs: scope + if: needs.scope.outputs.mode == 'full' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm - uses: dtolnay/rust-toolchain@stable - if: steps.scope.outputs.mode == 'full' with: toolchain: 1.90.0 - uses: Swatinem/rust-cache@v2 - if: steps.scope.outputs.mode == 'full' with: workspaces: crates/mathcore - - name: Classifier regression - if: steps.scope.outputs.mode == 'full' - run: node scripts/ci-scope-smoke.mjs - name: Chrome for sheet end-to-end - if: steps.scope.outputs.mode == 'full' run: | if ! command -v google-chrome >/dev/null 2>&1 && ! command -v google-chrome-stable >/dev/null 2>&1; then sudo apt-get update @@ -72,29 +120,20 @@ jobs: fi (google-chrome --version || google-chrome-stable --version) - run: npm ci - if: steps.scope.outputs.mode == 'full' - run: npm run lint - if: steps.scope.outputs.mode == 'full' - run: npm run test:rust - if: steps.scope.outputs.mode == 'full' - name: Packaged MCP protocol - if: steps.scope.outputs.mode == 'full' run: cargo test --manifest-path crates/mcpserve/Cargo.toml - run: npm run smoke - if: steps.scope.outputs.mode == 'full' - run: npm run smoke:ocr - if: steps.scope.outputs.mode == 'full' - name: Real CoMER smoke - if: steps.scope.outputs.mode == 'full' run: npx tsx scripts/ocr-real-smoke.ts - run: npm run smoke:ai - if: steps.scope.outputs.mode == 'full' - run: npm run test:pack - if: steps.scope.outputs.mode == 'full' - run: npm run smoke:ink - if: steps.scope.outputs.mode == 'full' + - name: Ink unit tests + run: npx tsx --test src/ink/*.test.ts - name: Start the dev server - if: steps.scope.outputs.mode == 'full' run: | npm run dev > dev-server.log 2>&1 & echo $! > dev-server.pid @@ -108,17 +147,14 @@ jobs: cat dev-server.log exit 1 - name: Sheet end-to-end - if: steps.scope.outputs.mode == 'full' env: SHOTS: e2e-shots run: npm run e2e:sheet - name: Ink gestures - if: steps.scope.outputs.mode == 'full' env: SHOTS: e2e-shots run: npm run e2e:ink - name: Per-formula plot end-to-end - if: steps.scope.outputs.mode == 'full' env: SHOTS: e2e-plots run: npm run e2e @@ -134,8 +170,13 @@ jobs: if-no-files-found: ignore web: - needs: test - if: github.event_name != 'pull_request' + needs: [scope, checks, test] + if: >- + !cancelled() && needs.scope.result == 'success' && needs.checks.result == 'success' && + (needs.test.result == 'success' || needs.test.result == 'skipped') && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'push' && needs.scope.outputs.mode != 'docs') || + (github.event_name == 'pull_request' && needs.scope.outputs.mode == 'packaging')) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -152,8 +193,13 @@ jobs: if-no-files-found: error android: - needs: test - if: github.event_name != 'pull_request' + needs: [scope, checks, test] + if: >- + !cancelled() && needs.scope.result == 'success' && needs.checks.result == 'success' && + (needs.test.result == 'success' || needs.test.result == 'skipped') && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'push' && needs.scope.outputs.mode != 'docs') || + (github.event_name == 'pull_request' && needs.scope.outputs.mode == 'packaging')) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -174,7 +220,7 @@ jobs: workspaces: src-tauri - run: npm ci - name: Debug APK - if: github.event_name != 'workflow_dispatch' || inputs.sign_android == false + if: github.event_name != 'workflow_dispatch' || !inputs.sign_android run: bash scripts/package-android.sh --debug --install-sdk - name: Release APK if: github.event_name == 'workflow_dispatch' && inputs.sign_android @@ -192,8 +238,13 @@ jobs: if-no-files-found: error windows: - needs: test - if: github.event_name != 'pull_request' + needs: [scope, checks, test] + if: >- + !cancelled() && needs.scope.result == 'success' && needs.checks.result == 'success' && + (needs.test.result == 'success' || needs.test.result == 'skipped') && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'push' && needs.scope.outputs.mode != 'docs') || + (github.event_name == 'pull_request' && needs.scope.outputs.mode == 'packaging')) runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -238,3 +289,68 @@ jobs: packaging/out/*.msi packaging/out/SHA256SUMS if-no-files-found: error + + ios: + needs: [scope, checks, test] + if: >- + !cancelled() && needs.scope.result == 'success' && needs.checks.result == 'success' && + (needs.test.result == 'success' || needs.test.result == 'skipped') && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'push' && needs.scope.outputs.mode != 'docs') || + (github.event_name == 'pull_request' && needs.scope.outputs.mode == 'packaging')) && + (github.event_name != 'workflow_dispatch' || inputs.build_ios) + uses: ./.github/workflows/package-ios.yml + with: + target: unsigned + + # One SHA256SUMS over every package, next to the per-job sums. + checksums: + needs: [android, windows, ios] + if: >- + !cancelled() && needs.android.result == 'success' && needs.windows.result == 'success' && + (needs.ios.result == 'success' || needs.ios.result == 'skipped') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/download-artifact@v4 + with: + pattern: mathscrap-* + path: artifacts + - name: Verify per-job sums and combine + run: | + mkdir -p release + for d in artifacts/mathscrap-android artifacts/mathscrap-windows artifacts/mathscrap-ios; do + [ -d "$d" ] || continue + (cd "$d" && sha256sum -c --ignore-missing SHA256SUMS) + find "$d" -maxdepth 1 -type f ! -name SHA256SUMS ! -name 'PROVENANCE*' -exec cp {} release/ \; + done + node scripts/checksum-artifacts.mjs release + - uses: actions/upload-artifact@v4 + with: + name: mathscrap-release-checksums + path: release/SHA256SUMS + if-no-files-found: error + + # The one status to require on main. Skipped jobs pass; failed or cancelled jobs fail. + ci-ok: + if: always() + needs: [scope, checks, test, web, android, windows, ios, checksums] + runs-on: ubuntu-latest + steps: + - name: Summarize + env: + NEEDS: ${{ toJSON(needs) }} + run: | + node -e ' + const needs = JSON.parse(process.env.NEEDS) + let bad = 0 + for (const [name, job] of Object.entries(needs)) { + console.log(name.padEnd(10), job.result) + if (job.result === "failure" || job.result === "cancelled") bad++ + } + if (needs.scope.result !== "success") bad++ + process.exit(bad ? 1 : 0) + ' diff --git a/README.md b/README.md index 4b2aa02..f4bf6c1 100644 --- a/README.md +++ b/README.md @@ -154,9 +154,9 @@ The dev server forwards the browser's model request through `POST /__mathscrap/a ## Packages -外壳是 Tauri 2。它把 `dist/` 放进系统 WebView。安装之后不连接 Vite,也不从公共 CDN 拉数学库或 OCR。标识是 `app.mathscrap`,版本 `0.0.1`。图标用纸面的牛皮色 `#c9a473`。 +外壳是 Tauri 2。它把 `dist/` 放进系统 WebView。安装之后不连接 Vite,也不从公共 CDN 拉数学库或 OCR。标识是 `app.mathscrap`,版本 `0.0.2`。图标用纸面的牛皮色 `#c9a473`。 -The shell is Tauri 2. It puts `dist/` in the system WebView. After install it does not connect to Vite and does not fetch the math library or OCR from a public CDN. The identifier is `app.mathscrap`, version `0.0.1`. The icon uses the kraft color `#c9a473`. +The shell is Tauri 2. It puts `dist/` in the system WebView. After install it does not connect to Vite and does not fetch the math library or OCR from a public CDN. The identifier is `app.mathscrap`, version `0.0.2`. The icon uses the kraft color `#c9a473`. | 命令 Command | 在哪里跑 / Where it runs | 得到什么 / What you get | | --- | --- | --- | @@ -173,9 +173,9 @@ Android 调试包用 SDK 的 debug keystore 签名。正式签名要已有的 ke The Android debug package is signed with the SDK debug keystore. A release signature needs an existing keystore: `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`, `ANDROID_KEY_BASE64`. The script does not generate a keystore. -iOS 最低系统是 16.4。能装到别人手机上的 IPA 需要 Apple Developer 证书和描述文件:`IOS_CERTIFICATE`、`IOS_CERTIFICATE_PASSWORD`、`IOS_MOBILE_PROVISION`,或 `APPLE_API_ISSUER`、`APPLE_API_KEY`、`APPLE_API_KEY_PATH`。这里不注册开发者账号,不上传 TestFlight 或 App Store,也没有在 iPhone 上安装过。 +iOS 最低系统是 15.0(arm64,例如 iPad Air 2 的 iPadOS 15)。笔迹和数学引擎在 15.x 上可用;手写识别在 iOS 16.4 以上用 WebAssembly SIMD;更旧的系统(没有 SIMD)自动改用 onnxruntime-web 1.18 的非 SIMD 兼容运行时,结果相同但慢数倍,自动识别暂停、改为手动点「识别」。兼容路径只在 Chromium 里模拟过,未在 iPad 真机验证。能装到别人手机上的 IPA 需要 Apple Developer 证书和描述文件:`IOS_CERTIFICATE`、`IOS_CERTIFICATE_PASSWORD`、`IOS_MOBILE_PROVISION`,或 `APPLE_API_ISSUER`、`APPLE_API_KEY`、`APPLE_API_KEY_PATH`。这里不注册开发者账号,不上传 TestFlight 或 App Store,也没有在 iPhone 上安装过。 -The iOS minimum is 16.4. An IPA that installs on someone else's phone needs an Apple Developer certificate and profile: `IOS_CERTIFICATE`, `IOS_CERTIFICATE_PASSWORD`, `IOS_MOBILE_PROVISION`, or `APPLE_API_ISSUER`, `APPLE_API_KEY`, `APPLE_API_KEY_PATH`. This repository does not enroll a developer account, does not upload to TestFlight or the App Store, and has not been installed on an iPhone. +The iOS minimum is 15.0 (arm64, for example iPadOS 15 on an iPad Air 2). Ink and the math engine work on 15.x; handwriting recognition uses WebAssembly SIMD on iOS 16.4 and later; older systems (no SIMD) fall back to onnxruntime-web 1.18's non-SIMD runtime, with the same results several times slower, automatic reading paused and Recognize done by hand. The fallback has been exercised in Chromium only, not on an iPad. An IPA that installs on someone else's phone needs an Apple Developer certificate and profile: `IOS_CERTIFICATE`, `IOS_CERTIFICATE_PASSWORD`, `IOS_MOBILE_PROVISION`, or `APPLE_API_ISSUER`, `APPLE_API_KEY`, `APPLE_API_KEY_PATH`. This repository does not enroll a developer account, does not upload to TestFlight or the App Store, and has not been installed on an iPhone. `.github/workflows/package.yml` 在推送到 `main` 或 `cursor/mathscrap-packaging-*` 时,以及指向 `main` 的 pull request 上运行。`test` 作业没有额外的跳过条件:这三种情况都会在 `ubuntu-latest` 上跑 `npm run lint`、`npm run test:rust`、`npm run smoke`、`npm run smoke:ocr`、`npm run smoke:ai`、`npm run test:pack`、`npm run smoke:ink`,然后拉起 dev 服务器,依次跑 `npm run e2e:sheet`、`npm run e2e:ink` 和 `npm run e2e`(逐条作图)。失败时上传 `e2e-shots`、`e2e-plots` 和 `dev-server.log`。这些步骤不需要密钥。网页、debug APK 和未签名 Windows 安装程序仍只在 push 上、并且 `test` 通过之后构建;pull request 不打安装包。`.github/workflows/package-ios.yml` 只在手动启动时使用 macOS runner。这些 workflow 不创建 GitHub Release。本文件不提供下载地址。 diff --git a/crates/mathcore/Cargo.lock b/crates/mathcore/Cargo.lock index b5c531b..218dd4e 100644 --- a/crates/mathcore/Cargo.lock +++ b/crates/mathcore/Cargo.lock @@ -22,7 +22,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "mathcore" -version = "0.0.1" +version = "0.0.2" dependencies = [ "serde", "serde_json", diff --git a/crates/mathcore/Cargo.toml b/crates/mathcore/Cargo.toml index 90a7898..9eec346 100644 --- a/crates/mathcore/Cargo.toml +++ b/crates/mathcore/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mathcore" -version = "0.0.1" +version = "0.0.2" edition = "2021" description = "Fast math helpers (parse, sample, solve, geometry inference) for the MathScrap kraft notebook, compiled to WASM." # wasm-pack copies this field into src/wasm/pkg/package.json. Keep both Apache-2.0. diff --git a/docs/release-check.md b/docs/release-check.md index 3a60171..96d6456 100644 --- a/docs/release-check.md +++ b/docs/release-check.md @@ -16,6 +16,10 @@ MathScrap-0.0.1-windows-x64.exe MathScrap-0.0.1-android-arm64-v8a.apk ``` +从 0.0.2 起,CI 还会产出 `MathScrap-<版本>-ios-unsigned.ipa`。它没有苹果签名,也没有描述文件,只能用 TrollStore 或在已越狱的设备上安装,普通 iOS 会拒绝安装。如果构建机上有 `ldid`,包里只有一个 ad-hoc 伪签名,用来保留 entitlements,不是苹果签名。最低系统是 iOS 15.0(arm64)。iPadOS 15 上笔迹和数学引擎可用;手写识别在 iOS 16.4 起用 WebAssembly SIMD;iPadOS 15 没有 SIMD,会改用非 SIMD 兼容运行时(onnxruntime-web 1.18,结果相同、慢数倍、只手动识别),这一点还没有真机验证。它的 SHA-256 和其他包一起写在 `SHA256SUMS` 里,核对方法相同。iOS 版不启动本机 MCP 监听,Android 也一样。 + +图标:Windows、macOS、Linux 和网页的图标是由 `packaging/logo/app-icon.png` 生成的圆角版本(`packaging/logo/app-icon-rounded.png`,四角透明)。iOS 用不透明的方形原图,系统自己裁成圆角;如果预先做成透明圆角,会被裁两次或在角上露出黑色。Android 保留自适应图标和圆形图标。 + Git 标签 `v0.0.1` 的签名可以在本地用随包的公钥检查。签名 UID 是 `DNT_OF`,UID 上没有邮箱。标签对象里的 tagger 邮箱是 `3174600270@qq.com`。这是两个不同的字段。签名有效不等于 GitHub 上显示 Verified。 # After you install @@ -34,6 +38,10 @@ MathScrap-0.0.1-windows-x64.exe MathScrap-0.0.1-android-arm64-v8a.apk ``` +Starting with 0.0.2, CI also produces `MathScrap--ios-unsigned.ipa`. It has no Apple signature and no provisioning profile. It installs only through TrollStore or on a jailbroken device; stock iOS refuses it. When `ldid` is on the builder, the app carries an ad-hoc fake signature that only preserves entitlements; it is not an Apple signature. The minimum OS is iOS 15.0 (arm64). On iPadOS 15, ink and the math engine work; handwriting recognition uses WebAssembly SIMD from iOS 16.4; iPadOS 15 has no SIMD and falls back to a non-SIMD runtime (onnxruntime-web 1.18: same results, several times slower, manual Recognize only). This has not been verified on a device. Its SHA-256 is listed in `SHA256SUMS` with the other packages and is checked the same way. The iOS build, like Android, does not start the local MCP listener. + +Icons: Windows, macOS, Linux and the web favicon use a rounded-corner icon generated from `packaging/logo/app-icon.png` (`packaging/logo/app-icon-rounded.png`, transparent corners). iOS uses the opaque square master and applies its own rounded mask; baked transparent corners would be masked twice or show black corners. Android keeps its adaptive and round launcher icons. + The `v0.0.1` tag signature can be checked locally with the published public key. The signing UID is `DNT_OF` and that UID has no email. The tagger email stored on the tag object is `3174600270@qq.com`. Those are different fields. A valid signature is not the same as a GitHub Verified badge. The packaged WebView still allows `https:` in `connect-src`, because a configured AI endpoint is fetched by the page itself. `script-src` keeps `wasm-unsafe-eval` for ONNX and drops `'unsafe-eval'`. That CSP line has not been executed inside a packaged WebView in this change, and CORS for a packaged build has not been run. The dev bridge requires an HttpOnly session cookie. Forged `Origin` and `Sec-Fetch-Site` headers do not grant it. The browser receives the cookie on a document load. The stdio client reads a mode 0600 file and does not print it. A LAN peer gets a cookie only by posting the operator's share token to `/__mathscrap/join`; a short or placeholder token does not turn sharing on. A process on the same machine that forges a document navigation can still receive the cookie, and a same-user process can read the session file. diff --git a/docs/releases/v0.0.2.md b/docs/releases/v0.0.2.md new file mode 100644 index 0000000..e25e50b --- /dev/null +++ b/docs/releases/v0.0.2.md @@ -0,0 +1,47 @@ +# MathScrap 0.0.2(草稿 / draft) + +这份说明是发布草稿。合并、打标签和发布都还没有做。 + +This is a draft. Nothing has been merged, tagged, or published yet. + +## 笔迹手感原型(默认关闭) + +新增 `src/ink/`:平滑(去近点 + 中点贝塞尔)、预测尾迹(可选浅色)、扫掠胶囊橡皮、按指针类型的容差、湿墨增量重绘,以及 `?ink-debug=1` 调试面板。所有开关默认关闭;关闭时纸面行为与 0.0.1 相同。数据来自合成轨迹回放,还没有真机笔迹或 iPad 实测结论。 + +## iOS 未签名 IPA + +新增 `MathScrap-0.0.2-ios-unsigned.ipa`。它没有苹果签名和描述文件,只能用 TrollStore 或在已越狱的设备上安装;普通 iOS 会拒绝。构建机上有 `ldid` 时,包里带一个 ad-hoc 伪签名,只用来保留 entitlements。最低 iOS 15.0,设备切片是纯 arm64(A8X 起,例如 iPadOS 15 的 iPad Air 2)。iPadOS 15 上笔迹和数学引擎可用。手写识别依赖的 onnxruntime-web 只有 WebAssembly SIMD 版本,而 WebKit 从 iOS 16.4 才支持 SIMD,所以在 iPadOS 15 上点「识别」会提示不可用,不会下载模型或崩溃;这一点和 16.4 以上设备上的识别都还没有真机验证。iOS 和 Android 不启动本机 MCP 监听。 + +## 圆角图标 + +Windows、macOS、Linux 和网页图标改为由 `packaging/logo/app-icon.png` 生成的圆角版本(`packaging/logo/app-icon-rounded.png`,四角透明)。iOS 继续用不透明的方形原图,由系统裁成圆角;预先做透明圆角会被裁两次或露出黑角。Android 保留自适应图标和圆形图标。 + +## 按改动范围跑 CI + +`package` 工作流先分类改动:只改文档的 PR 只跑一致性检查(版本号、分类器回归、打包脚本语法、工作流 YAML);只改版本字段同样不跑数学测试,但推到 main 时照常打包;只改打包脚本或图标时实际构建安装包而不跑数学测试;混合或无法归类的改动跑全量。新增文档文件(例如 `CONTRIBUTING.md`)不再触发全量。`ci-ok` 是唯一需要设为必需的状态。打包任务额外生成一份覆盖 Android、Windows 和 iOS 的 `SHA256SUMS`。 + +## 核对 + +在自己的电脑上计算 SHA-256,与发布页的 `SHA256SUMS` 比较。Windows 和 Android 的签名方式与 0.0.1 相同(见 `signing/v0.0.1/` 和 `docs/release-check.md`)。iOS 包未签名。 + +--- + +## Ink-feel prototype (off by default) + +Adds `src/ink/`: smoothing (near-point drop + midpoint Bezier), a predicted tail (optionally a translucent ghost), a swept capsule eraser, per-pointer-type tolerance, incremental wet-ink redraw, and a `?ink-debug=1` panel. Every flag is off by default; with them off the sheet behaves as in 0.0.1. The numbers come from synthetic trace replay, not from real handwriting or an iPad. + +## Unsigned iOS IPA + +Adds `MathScrap-0.0.2-ios-unsigned.ipa`. It has no Apple signature and no provisioning profile and installs only through TrollStore or on a jailbroken device; stock iOS refuses it. When `ldid` is on the builder, the app carries an ad-hoc fake signature that only preserves entitlements. Minimum iOS 15.0 with a plain arm64 device slice (A8X and later, for example an iPad Air 2 on iPadOS 15). On iPadOS 15, ink and the math engine work. Handwriting recognition uses onnxruntime-web, which ships only WebAssembly SIMD builds, and WebKit has SIMD only from iOS 16.4, so on iPadOS 15 Recognize reports that recognition is unavailable instead of downloading the models or crashing. Neither that path nor recognition on 16.4+ has been verified on a device. iOS and Android do not start the local MCP listener. + +## Rounded icon + +Windows, macOS, Linux and the web favicon now use a rounded-corner icon generated from `packaging/logo/app-icon.png` (`packaging/logo/app-icon-rounded.png`, transparent corners). iOS keeps the opaque square master and applies its own mask; baked transparent corners would be masked twice or show black corners. Android keeps its adaptive and round launcher icons. + +## Change-aware CI + +The `package` workflow classifies each change first. Docs-only PRs run only consistency checks (versions, classifier regression, packaging script syntax, workflow YAML). Version-only changes also skip the math suite but still package on push to main. Packaging-only changes build the packages instead of running the math suite. Mixed or unclassified changes run the full suite. Adding a docs file such as `CONTRIBUTING.md` no longer forces the full suite. `ci-ok` is the single status to require. The packaging run also writes one `SHA256SUMS` across Android, Windows and iOS. + +## Verify + +Hash the files on your own computer and compare with `SHA256SUMS` on the release page. Windows and Android signing follow 0.0.1 (see `signing/v0.0.1/` and `docs/release-check.md`). The iOS package is unsigned. \ No newline at end of file diff --git a/experiments/2026-11-12-ink-prediction/README.md b/experiments/2026-11-12-ink-prediction/README.md new file mode 100644 index 0000000..0b8ffb4 --- /dev/null +++ b/experiments/2026-11-12-ink-prediction/README.md @@ -0,0 +1,165 @@ +# MathScrap 墨迹手感原型(预测 + 平滑 + 扫掠胶囊橡皮 + 按指针类型容差) + +日期:2026-11-12 / 2026-11-13(第二、三、四轮)· 分支:`experiment/ink-prediction-20261112`(基于本地 main `67b785a`)· worktree:`MathScrap-ink-proto` + +目的:参考对希沃白板 5.2.4 的只读逆向**结论**(只学思路,不复制其代码/常量表/资源),在 MathScrap 里做默认关闭的墨迹手感原型:去近点 + 中点二次贝塞尔平滑、短时程预测显示、扫掠胶囊橡皮、按指针类型容差、湿墨增量重绘。不引入任何新依赖(未 vendor ink-stroke-modeler,仅参考其公开论文/思路)。 + +## 现状(main 分支) + +- 采集:`src/board/Board.tsx` `onPointerMove`(draw 分支)——已用 `getCoalescedEvents()`,逐事件转世界坐标后丢弃与笔尖距离 <0.8 屏幕 px 的近点,`pts` 平铺为 `[x, y, pressure, ...]`(世界坐标,无真实压感时恒 0.5,`types.ts`)。 +- 渲染:`src/board/strokes.tsx` `StrokeShape`——`ink` 样式走 perfect-freehand 轮廓(streamline 0.45),其它样式走 `centerPath`(**已经是**中点二次贝塞尔 Q 曲线)。湿墨(live)与干墨同一条渲染路径。 +- 橡皮:`Board.tsx` `eraseAt`——每个 move 事件单点 `hitStroke`(半径固定 `12/scale` 世界单位),**没有**事件间的扫掠,快速移动会漏擦。 +- 容差:不区分指针类型(鼠标/触摸/笔同一阈值)。 +- 测试:仓库没有单测框架;`tsx` + Node 内置 `node:test` 可用(Node 24)。 + +## 方案(全部默认关闭) + +新增 `src/ink/` 纯函数模块 + `Board.tsx`/`App.tsx` 最小集成。开关存在 `localStorage['mathscrap.ink-flags.v1']`(JSON),URL 参数优先,并可由调试面板实时切换(响应式 store + `useSyncExternalStore`)。 + +| 开关 | URL 参数 | 功能 | +|---|---|---| +| `smoothing` | `ink-smooth=1` | 采集去近点阈值 0.8→0.5 DIP(`appendStrokePoint`);抬笔时把中点二次贝塞尔采样折线烘焙进保存的 `pts`(端点精确不变,点数 <3 不处理);湿墨实时按同一函数渲染,湿/干一致 | +| `prediction` | `ink-predict=1` | 湿墨尾部显示外推点:优先 `getPredictedEvents()`(Chromium),不可用则自研兜底——每轴 2 状态常速卡尔曼。**步长/时程按 rAF 估计的刷新率自适应**(60Hz≈33ms/8.3ms 步长、120Hz≈16.7ms/4.2ms 步长,见 `frameAdaptivePrediction`),直线满时程 ≈2 帧、曲线减半、绝对上限 36ms;门控 `gateSamples`:速度 <0.04px/ms(idle)、单次转角 >65°(sharp)、两次反向大转角或 ≥3 次摆动(jitter)时关闭。**预测点绝不写入保存数据**,下一帧真实点即替换;采样历史窗口上限 96 | +| `predictionGhost` | `ink-ghost=1` | 预测子选项:预测尾从实墨路径拆出,用独立半透明路径(opacity 0.4,`predictionTailPath` 从笔画末端起笔)渲染,避免把预测误读为实际墨迹;关闭时维持第二轮融资的合并渲染 | +| `capsuleEraser` | `ink-capsule=1` | `hitSweep`:上一位置到当前位置的扫掠胶囊(线段-线段距离 + `hitStroke` 同款宽度余量:ink/pencil ×0.8,marker/washi ×2.5);按住起点仍是原单点测试 | +| `pointerTolerance` | `ink-tolerance=1` | 橡皮半径按指针类型取命中容差(鼠标/触摸/笔 = 3/10/5 DIP ÷ 缩放);**点按折叠看双条件**——整笔位移 < 该类型拖动阈值(1/16/4 DIP ÷ 缩放)**且**按下时长 ≤250ms(`TAP_MAX_DURATION_MS`)才折叠成落笔点圆点,慢速刻意短笔画保留为笔画。`hasRealPressure`:恒 0.5/0 视为无压感设备 | +| `wetIncremental` | `ink-wet-inc=1` | 平滑子选项:湿墨增量重绘。中点贝塞尔每段只依赖 P[i-1..i+1],段一旦生成即不再变化——`updateIncrementalSmooth` 每个事件只补算新确定的 1 段 + 端点(复用共享的 `pushSegmentSamples`),与抬笔时的整笔烘焙**逐位一致**(单测保证),2000 点笔画每帧平滑成本 182.7µs → 0.5µs | + +调试面板 `src/ink/InkDebugPanel.tsx`:`?ink-debug=1` 强制显示(`=0` 隐藏),否则仅**开发构建且任一实验开关打开**时显示(生产无参数不可见)。面板可实时切换六个开关,显示 pointerType、是否有真实压力、`getPredictedEvents` 可用性、最近预测点数及来源(native/self/off)、move 处理耗时、rAF 帧间隔与刷新率估计(Hz)、当前笔画点数。 + +集成点:`Board.tsx`(响应式 flags、`pointerTypeRef`、`eraseRadius()`、`finishStroke` 点按折叠(位移+时长)、`updatePrediction` 自适应步长 + 统计、draw 分支增量湿墨 + 计时、渲染处 `liveDisplay`/`tailDisplay` 分离)与 `App.tsx`(仅挂载面板一处)。`strokes.tsx`、OCR(`src/ocr/**`)、签名、版本号均未改动。 + +开关全关时:draw 循环经 `appendStrokePoint(…, 0.8, …)`(单测证明与 main 内联循环逐事件等价),橡皮半径 12/scale、无折叠/预测/平滑/增量,行为与 main 完全一致。 + +## 风险 + +- 平滑与点按折叠会改变保存的 `pts` 几何(切角/折叠),开启后影响 OCR/几何推理输入形状(本 worktree 未动 OCR 代码,但输入墨迹会变)。默认关闭。 +- 点按折叠现含时长条件(≤250ms),大幅降低"吃掉刻意短笔画"的风险,但快速描点式书写(连续快短笔)仍可能被折叠——原型取舍,已记录。 +- 卡尔曼/门控/自适应常数为按手写速度量级手调,**未在真机验证手感**;rAF 估计在后台标签页会暂时失真(已 clamp 4-33ms)。 +- `getPredictedEvents` 仅 Chromium 提供;Firefox/Safari 走自研兜底,兜底在浏览器中未实测。 +- ghost 预测尾对 marker/washi 等宽笔会渲染成半透明宽带,视觉是否合适待实机确认。 +- 增量湿墨与整笔烘焙的一致性由单测逐位保证,但 React 渲染时序(state 批处理)下的实际表现待实机确认。 + +## 改动文件(本 worktree,未提交) + +- `src/ink/flags.ts`:六开关解析/加载 + 响应式 store + 面板门控 +- `src/ink/smooth.ts`:去近点、`pushSegmentSamples`(整笔/增量共享采样)、`midpointBezierPolyline`、`createIncrementalSmooth`/`updateIncrementalSmooth`(增量缓存) +- `src/ink/predict.ts`:门控 + 卡尔曼 + native 预测 + 历史窗口上限 + `frameAdaptivePrediction`(刷新率自适应,可选 framesAhead/curveFraction)+ `predictionTailPath`(ghost 独立路径)+ `PredictOptions.qAcc/measVar`(回放调参旋钮,默认不变)+ 门控噪声鲁棒性修复(翻转只看最近 12 对、曲线判定用中位数转角) +- `src/ink/replay.ts`(合成轨迹生成 + 回放指标,纯 Node)、`src/ink/replay.test.ts`(回放单测) +- `experiments/2026-11-12-ink-prediction/replay.ts`(回放 runner)、`replay-output.txt`(第四轮结果存档) +- `src/ink/capsule.ts`(扫掠胶囊)、`src/ink/tolerance.ts`(指针类型容差/无压感判定/位移+时长点按判定)、`src/ink/debug.ts`(面板数据暂存)、`src/ink/InkDebugPanel.tsx`(调试面板,六开关 + 刷新率行) +- 测试 `src/ink/{smooth,predict,capsule,flags,integration,tolerance}.test.ts`(顶部 `/// `,因 tsconfig.app.json `types:["vite/client"]` 不含 node 类型;未改 tsconfig) +- `src/board/Board.tsx`:集成六个开关 + 统计上报(唯一被改的既有组件) +- `src/App.tsx`:挂载调试面板(一处) +- `experiments/2026-11-12-ink-prediction/bench.ts`(微基准)、本 README + +未改动:`strokes.tsx`、`src/ocr/**`、`src/wasm/**`、`package.json`、版本号、签名、默认引擎。 + +## 测试 + +命令(在 `MathScrap-ink-proto` 下,轻量、无构建/打包/推理): + +``` +npx tsx --test src/ink/*.test.ts # 55 tests, 55 pass / 0 fail +npx tsc -p tsconfig.app.json # 类型检查通过(0 错误) +npx oxlint src/ink src/board src/App.tsx # src/ink 0 警告;board=6、App=3 与 main 基线完全相同 +``` + +覆盖要点:平滑端点不变/无 NaN/压感在邻域内、flag-off 与 main 采集循环等价;门控(直线/曲线/急转/抖动/停笔/样本不足)、预测尾时程 ≤36ms 与输入不可变;**预测点永不进入保存笔画**;胶囊快速移动命中、退化成圆、宽度余量;指针类型映射与三档阈值 ÷ 缩放、无压感判定;**点按 = 位移且时长双条件**(慢速刻意短笔画保留);**刷新率自适应**(60/120/144Hz 步长与时程单调、绝对上限、退化 clamp);**增量平滑在每个前缀上与整笔重采样逐位一致**、冷启动、no-op、输入不变性;ghost 路径从笔画末端起笔且不改输入;开关默认全关、解析优先级、store 稳定性、面板门控。 + +## 性能微基准(Node 24 / tsx,单线程,与 OCR 任务并存时测得) + +`npx tsx experiments/2026-11-12-ink-prediction/bench.ts`: + +| 项目 | 单次耗时 | +|---|---| +| 平滑 200 点(整笔重采样,每湿墨帧) | 13.1 µs | +| 平滑 2000 点(整笔,压力测试) | 328.5 µs | +| **增量平滑每事件(2000 点笔画全程)** | **0.5 µs/事件(全程 0.91ms,比整笔快 ~399×)** | +| 整笔重采样每事件(2000 点全程均值) | 182.7 µs/事件(全程 364.98ms) | +| 门控 20 / 96 样本窗口 | 1.6 / 7.8 µs | +| 预测 20 / 96 样本 → 33ms | 1.8 / 6.6 µs | +| 胶囊命中 miss 200 / 2000 点 | 3.7 / 33.8 µs | +| 采集追加到 2000 点笔画 | 10.7 µs | +| 橡皮一帧:扫掠 20×200 点全 miss | 77.3 µs | + +**结论:满足每帧 <1ms。** 真实帧(200 点湿墨平滑 + 96 样本门控/预测 + 20×200 点橡皮扫掠)≈ **0.105ms**;开 `wetIncremental` 后 ≈ **0.092ms**;压力帧(2000 点整笔重采样)≈ **0.420ms**,增量模式下平滑项 329µs → 0.5µs。湿/干形状一致性由单测保证(非基准断言)。 + +## 第四轮:离线回放评估(合成轨迹,2026-11-13) + +**⚠ 全部为合成轨迹**(确定性 mulberry32 种子 + 高斯噪声 0.6px,只加在采样上、真值精确),不代表真实笔迹;下表常数只作为 **iPad 实测的初值候选**,本轮未改任何默认常数。工具: + +``` +npx tsx experiments/2026-11-12-ink-prediction/replay.ts # 完整表格,输出已存档 replay-output.txt +``` + +- 轨迹(`src/ink/replay.ts`):直线 600px/s、快弧(r=25 v=600,写 e/圈的极端情形)、急转(直行 600ms 后 90°)、抖动(±60° 交替锯齿)、停笔(300ms 保持上报)、慢短笔(6px/500ms),各 60Hz 与 120Hz 两档。 +- 指标:在每次有足够历史的采样点上走与 Board 相同的门控+卡尔曼管线,预测尾**末端**与其自身时间戳上的精确真值比较 → errMean/errP95/errMax;过冲 = 误差在行进方向上的分量(+超前/−滞后);pred% = 门控放行占比。 +- 候选:A=现行默认(65/30/12,q=9e6,r=2,2 帧);B=更响应(55/25/10,q=2e6,r=1,1.5 帧);C=更激进(75/35/15,q=2.5e7,r=4,2.5 帧);D=更保守(55/25/14,q=4e6,r=2,1.5 帧)。 + +各场景等权平均 errMean(完整逐场景表见 `replay-output.txt`): + +| 候选 | 60Hz | 120Hz | +|---|---|---| +| **A-现行默认** | 3.41px | 2.09px | +| **B-更响应** | **2.70px** | **1.76px** | +| C-更激进 | 3.45px | 3.05px | +| D-更保守 | 2.86px | 2.04px | + +典型场景(errMean):快弧 60Hz A=11.3px vs C=10.2px(KF 速度在急弯上滞后是主项,过冲 −2~−6px 即"滞后于切线");急转 60Hz A errMax=28px vs B/D=21px;停笔 60Hz A errMax=20px(停笔瞬间尾甩出,1.5 帧候选减半);慢短笔全程 0% pred(idle 门控符合设计:不给刻意慢笔画外推)。 + +**回放发现并修复的两个门控真问题**(属于 prediction 实验内部的噪声鲁棒性修复,常数默认值未动): +1. 抖动翻转规则原本在**整个窗口**累计 ≥3 次 ≥10° 的变号转角——真实尺度的指针噪声让直线全程被判 jitter、预测完全失效;改为只看**最近 12 对**转角、需两侧 ≥ jitterTurnDeg/2 且 ≥3 次翻转。 +2. 曲线/直线判定原用窗口内**最大**转角——96 样本窗口的噪声几乎必然把最大值顶过阈值,直线永远读成"曲线";改用**中位数**转角(急转判定仍用最大值,单个大转角仍立即关断)。 + +**结论**:B-更响应(更严门控 + 更低 q + 1.5 帧)在两类刷新率上都最优;"更多帧"(C)在弯曲轨迹上放大误差、不可取。120Hz 下直线 pred% 从 100%→58%(A),说明 idle/翻转阈值需要随刷新率与噪声自适应——列入 iPad 调参项,本轮不改。 + +## iPad 实测步骤(两种方式,均临时启动、测完即停) + +### 方式 A:iPad 作为笔记本的外接手写屏(spacedesk / Duet Display 等) + +1. Windows 笔记本安装 spacedesk(免费)或 Duet Display,iPad 装对应 App,连接后 iPad 成为 Windows 扩展屏。 +2. Windows 浏览器打开 dev 页(先按方式 B 的第 1-2 步启动本地 dev,或直接 `npm run dev` 后访问 http://localhost:5173),把窗口拖到 iPad 那块屏。 +3. 用 Apple Pencil 在该屏书写。注意:转发软件通常把 Pencil 映射成 Windows 触摸/笔,**面板里先看 pointerType 实际是什么**(决定走哪档容差),且此类方案会引入额外传输延迟,手感结论只做参考,不与方式 B 横比。 +4. 测试完关闭转发软件。 + +### 方式 B:iPad 浏览器访问局域网 dev 服务器(推荐:真实 PointerEvent 与延迟) + +1. Windows 上 `ipconfig` 查局域网 IPv4(下例 `192.168.1.23`),iPad 与笔记本同一 Wi-Fi。 +2. 临时启动(显式绑定该 IP,**不改 vite.config 默认值,不绑 0.0.0.0**): + `npm run dev -- --host 192.168.1.23` +3. Windows 防火墙弹窗选"允许(专用网络)";iPad Safari 打开: + `http://192.168.1.23:5173/?ink-debug=1&ink-smooth=1&ink-predict=1&ink-ghost=1&ink-capsule=1&ink-tolerance=1&ink-wet-inc=1` +4. **不要启动 `npm run mcp`,MCP 端点不暴露**;只跑这一个 dev 进程。 +5. 测完在笔记本 Ctrl+C 停掉服务器(不常驻、不写进任何配置)。 + +### 手感验收清单(开着面板逐项看) + +1. **跟笔延迟**:预测开 vs 关画长直线/快弧线,墨迹前缘与笔尖的分离应明显减小;急转弯/停顿时预测应自动消失,不得出现"墨迹甩尾"(对应门控 sharp/jitter/idle)。 +2. **预测尾观感(新)**:`ink-ghost=1` 时预测尾应是半透明浅色独立路径、从笔尖伸出,与实墨明显可区分;关闭 ghost 时与实墨同色。两种观感各试快/慢笔画。 +3. **刷新率自适应(新)**:面板看"帧间隔 ≈ xx Hz";iPad(通常 60Hz)下预测尾约 2 帧长度,步长不再是固定 11ms 的颗粒感;急转/慢速时尾应收缩或消失。 +4. **平滑**:快速画锯齿线,毛刺减少;起笔/收笔端点仍在笔尖起止位置(端点精确保持)。 +5. **湿/干一致(新)**:`ink-wet-inc=1` 开关下画长笔画(尽量 1000+ 点),抬笔瞬间墨迹形状**不应有任何跳变**(增量与烘焙逐位一致);再对比关闭增量时画同样笔画,观感应相同。 +6. **点按 vs 短笔画(新)**:快速轻点 → 圆点;放慢速度画一条刻意短 tick(约 0.5s)→ 应保留为短笔画而不是被折叠成点(位移+时长双条件)。 +7. **橡皮**:快速横扫细线条,胶囊开时无漏擦;容差开关开时,手指擦除比鼠标明显更"宽容"(10 vs 3 DIP),笔居中(5 DIP)。 +8. **缩放**:2×/4× 放大后重复橡皮与轻点,屏幕手感应一致(阈值按缩放换算)。 +9. **压感**:面板显示"无压感(恒 0.5/0)"时笔画宽度不随力度变化;有真实压感的设备显示"真实压力"。 +10. **性能**:面板帧间隔 <16.7ms(60Hz)且 move 处理耗时 <1ms(基准显示 ~0.01-0.4ms);快速画超长笔画(2000+ 点)不卡顿,增量开启时尤其应平稳。 +11. **回归**:六个开关全关(或无参数的普通链接)时,书写/橡皮与 main 完全一致。 + +## 未验证 + +- iPad 实测(方式 A/B 均未在本会话执行——按约束不自动启动服务器);spacedesk/Duet 把 Apple Pencil 映射成哪种 pointerType 未知。 +- 真机手感:ghost 预测尾的透明度(0.4 为拍脑袋值)与宽笔观感、自适应步长在真实 60/120Hz 屏上的颗粒感、增量湿墨在 React 批处理下的实际表现。 +- 回放评估全部基于**合成轨迹**(高斯噪声、理想参数曲线):真实 Apple Pencil 采样噪声分布、压力、掌部抑制等未建模;候选常数(B/D 组)只是初值候选,未经真机验证。 +- rAF 刷新率估计在 iPad Safari(省电模式降帧)与后台切换时的行为(代码已 clamp,未实测)。 +- Firefox/Safari 的自研预测兜底在真实浏览器中的表现。 +- 打包体积/生产构建(按约束未跑);与同机 OCR 计时任务的相互干扰未测量。 + +## 建议下一步 + +1. 用方式 B 在 iPad 上跑一遍验收清单,按面板数字手调常数:`predict.ts`(门控角度、卡尔曼 q/r、`ADAPTIVE_FRAMES_AHEAD`)、`tolerance.ts` 三档与 `TAP_MAX_DURATION_MS`、ghost 的 opacity。回放结论支持从 **B-更响应** 组起步。 +2. 门控阈值随刷新率/噪声自适应(120Hz 回放显示直线被过度门控:idle 与翻转阈值应按帧间隔换算)。 +3. 若 ghost 观感成立,考虑给预测尾再加"长度随速度缩放"(快笔画更长、慢笔画更短)。 +4. 增量湿墨验证后,可把"湿墨分段增量重绘"进一步推进到 DOM 层(只更新新增 path 而非重建整个 StrokeShape),当前实现的收益主要在平滑计算,DOM 更新仍是整笔。 +5. 若采纳平滑/容差,把实验开关转为正式设置项并评估默认值(笔=开、触摸=保守)。 diff --git a/experiments/2026-11-12-ink-prediction/bench.ts b/experiments/2026-11-12-ink-prediction/bench.ts new file mode 100644 index 0000000..c4676b7 --- /dev/null +++ b/experiments/2026-11-12-ink-prediction/bench.ts @@ -0,0 +1,115 @@ +/** + * Light micro-benchmark for the ink prototype modules (Node + tsx, single thread). + * + * npx tsx experiments/2026-11-12-ink-prediction/bench.ts + * + * Deliberately CPU-light (a few seconds total, no GPU, no build) — safe to run + * next to the OCR timing job. Numbers are per single call; the "frame budget" + * section adds up the calls one rendered frame would actually make. + */ +import { hitSweep } from '../../src/ink/capsule' +import { gateSamples, predictTail, type InkSample } from '../../src/ink/predict' +import { appendStrokePoint, createIncrementalSmooth, midpointBezierPolyline, updateIncrementalSmooth } from '../../src/ink/smooth' +import type { Stroke } from '../../src/board/types' + +const now = () => performance.now() + +function bench(name: string, fn: () => unknown, minIter: number, budgetMs: number): number { + for (let i = 0; i < 5; i++) fn() // warmup + let iter = 0 + const t0 = now() + let elapsed = 0 + do { + fn() + iter++ + elapsed = now() - t0 + } while (elapsed < budgetMs || iter < minIter) + const perCallUs = (elapsed / iter) * 1000 + console.log(`${name.padEnd(56)} ${perCallUs.toFixed(1).padStart(9)} µs/call (${String(iter)} iters)`) + return perCallUs +} + +/** synthetic handwriting-ish stroke: gentle waves, flat [x, y, pressure, ...] */ +function makeStrokePts(n: number): number[] { + const pts: number[] = [] + for (let i = 0; i < n; i++) { + const t = i / (n - 1 || 1) + pts.push(t * 800, 300 + Math.sin(t * Math.PI * 6) * 120 + Math.sin(t * Math.PI * 23) * 8, 0.5) + } + return pts +} + +const strokeOf = (pts: number[]): Stroke => ({ id: 'bench', pts, color: '#000', width: 4, style: 'ink', createdAt: 0 }) + +/** slightly curving drag, 8 ms sampling */ +function makeSamples(n: number): InkSample[] { + let x = 0 + let y = 0 + let heading = 0 + return Array.from({ length: n }, (_, i) => { + heading += 0.03 + x += Math.cos(heading) * 5.6 + y += Math.sin(heading) * 5.6 + return { x, y, t: 1000 + i * 8 } + }) +} + +console.log('--- ink prototype micro-benchmark (Node, single thread) ---') +const pts200 = makeStrokePts(200) +const pts2000 = makeStrokePts(2000) + +const tSmooth200 = bench('smooth: midpointBezierPolyline 200 pts (per wet frame)', () => midpointBezierPolyline(pts200), 50, 400) +const tSmooth2000 = bench('smooth: midpointBezierPolyline 2000 pts (stress)', () => midpointBezierPolyline(pts2000), 20, 600) + +const samples20 = makeSamples(20) +const samples96 = makeSamples(96) +bench('predict: gateSamples (20-sample window)', () => gateSamples(samples20), 100, 200) +const tGate96 = bench('predict: gateSamples (96-sample window = cap)', () => gateSamples(samples96), 100, 200) +bench('predict: predictTail (20 samples → 33 ms)', () => predictTail(samples20, { horizonMs: 33 }), 100, 200) +const tPredict96 = bench('predict: predictTail (96 samples → 33 ms)', () => predictTail(samples96, { horizonMs: 33 }), 100, 200) + +const stroke200 = strokeOf(pts200) +const stroke2000 = strokeOf(pts2000) +bench('eraser: hitSweep miss on 200-pt stroke', () => hitSweep(stroke200, -50, 500, -40, 520, 12), 100, 300) +bench('eraser: hitSweep miss on 2000-pt stroke', () => hitSweep(stroke2000, -50, 500, -40, 520, 12), 20, 400) +const hitX = pts2000[999 * 3] +const hitY = pts2000[999 * 3 + 1] +bench('eraser: hitSweep hit mid-stroke on 2000-pt stroke', () => hitSweep(stroke2000, hitX, hitY, hitX + 2, hitY + 2, 12), 20, 400) +bench('capture: appendStrokePoint onto 2000-pt stroke', () => appendStrokePoint(pts2000, { x: 1e6, y: 1e6, pressure: 0.5 }, 0.5, 1), 100, 300) + +const docStrokes = Array.from({ length: 20 }, () => strokeOf(makeStrokePts(200))) +const tEraseFrame = bench('eraser frame: sweep over 20 × 200-pt strokes (all miss)', () => { + for (const s of docStrokes) hitSweep(s, -50, 500, -40, 520, 12) +}, 20, 400) + +console.log('\n--- wet-ink redraw: full resample vs incremental (2000-point stroke) ---') +// model the Board: the pts array grows by one sample per pointer event and the +// smoother reads it in place (no extra copying on either side) +const fullPts: number[] = [] +const fullStart = now() +for (let k = 1; k <= 2000; k++) { + fullPts.push(k, 300 + Math.sin(k / 200) * 100, 0.5) + if (k >= 3) midpointBezierPolyline(fullPts) +} +const fullMs = now() - fullStart +const incPts: number[] = [] +const incState = createIncrementalSmooth() +const incStart = now() +for (let k = 1; k <= 2000; k++) { + incPts.push(k, 300 + Math.sin(k / 200) * 100, 0.5) + if (k >= 3) updateIncrementalSmooth(incState, incPts) +} +const incMs = now() - incStart +const fullPerEventUs = (fullMs / 1998) * 1000 +const incPerEventUs = (incMs / 1998) * 1000 +console.log(`full resample every event: ${fullMs.toFixed(2)} ms total, ${fullPerEventUs.toFixed(1)} µs/event avg (last event ≈ ${tSmooth2000.toFixed(0)} µs)`) +console.log(`incremental per event: ${incMs.toFixed(2)} ms total, ${incPerEventUs.toFixed(1)} µs/event avg (${(fullMs / Math.max(incMs, 0.001)).toFixed(0)}× faster)`) +console.log(`wet/dry shape equality is asserted by unit tests, not here`) + +console.log('\n--- per-frame budget (target: < 1 ms) ---') +const realistic = tSmooth200 + tGate96 + tPredict96 + tEraseFrame +const stress = tSmooth2000 + tGate96 + tPredict96 + tEraseFrame +const realisticInc = incPerEventUs + tGate96 + tPredict96 + tEraseFrame +console.log(`realistic frame (200-pt live stroke) = ${(realistic / 1000).toFixed(3)} ms ${realistic < 1000 ? '✓ under budget' : '✗ over budget'}`) +console.log(`realistic frame with wetIncremental = ${(realisticInc / 1000).toFixed(3)} ms ${realisticInc < 1000 ? '✓ under budget' : '✗ over budget'}`) +console.log(`stress frame (2000-pt live stroke) = ${(stress / 1000).toFixed(3)} ms ${stress < 1000 ? '✓ under budget' : '✗ over budget'}`) diff --git a/experiments/2026-11-12-ink-prediction/replay-output.txt b/experiments/2026-11-12-ink-prediction/replay-output.txt new file mode 100644 index 0000000..28c897b --- /dev/null +++ b/experiments/2026-11-12-ink-prediction/replay-output.txt @@ -0,0 +1,80 @@ +=== 墨迹预测离线回放评估(合成轨迹!仅供 iPad 实测初值候选;默认值未改) === +噪声: 高斯 0.6px(仅加在采样上,真值精确);窗口 96 样本;绝对时程上限 36ms;预测起点 = 第 8 个样本 + +───────── 60Hz(帧间隔 16.7ms)───────── +场景 │ 候选 │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后) +直线 │ A-现行默认 │ 100% │ 1.1px │ 1.9px │ 2.4px │ +0.13px +直线 │ B-更响应 │ 100% │ 0.8px │ 1.5px │ 1.8px │ +0.12px +直线 │ C-更激进 │ 100% │ 1.2px │ 2.1px │ 2.6px │ +0.13px +直线 │ D-更保守 │ 100% │ 0.8px │ 1.5px │ 1.8px │ +0.12px + +快弧(小半径) │ A-现行默认 │ 100% │ 11.3px │ 12.6px │ 12.6px │ -2.29px +快弧(小半径) │ B-更响应 │ 100% │ 9.9px │ 10.8px │ 10.9px │ -5.21px +快弧(小半径) │ C-更激进 │ 100% │ 10.2px │ 11.5px │ 11.6px │ -1.35px +快弧(小半径) │ D-更保守 │ 100% │ 9.9px │ 10.8px │ 10.9px │ -5.21px + +急转 │ A-现行默认 │ 55% │ 2.5px │ 14.8px │ 28.0px │ +1.27px +急转 │ B-更响应 │ 55% │ 1.7px │ 7.5px │ 21.1px │ +0.93px +急转 │ C-更激进 │ 55% │ 2.6px │ 14.8px │ 28.0px │ +1.27px +急转 │ D-更保守 │ 55% │ 1.7px │ 7.5px │ 21.1px │ +0.92px + +抖动 │ A-现行默认 │ 100% │ 3.2px │ 6.7px │ 7.3px │ +0.02px +抖动 │ B-更响应 │ 100% │ 2.2px │ 4.7px │ 5.3px │ -0.16px +抖动 │ C-更激进 │ 100% │ 4.3px │ 7.7px │ 8.7px │ +0.49px +抖动 │ D-更保守 │ 100% │ 3.0px │ 5.0px │ 5.3px │ +0.01px + +停笔 │ A-现行默认 │ 32% │ 2.4px │ 10.9px │ 20.1px │ +1.45px +停笔 │ B-更响应 │ 32% │ 1.6px │ 5.6px │ 15.1px │ +1.03px +停笔 │ C-更激进 │ 32% │ 2.4px │ 11.0px │ 20.0px │ +1.45px +停笔 │ D-更保守 │ 32% │ 1.7px │ 5.6px │ 15.1px │ +1.02px + +慢短笔 │ A-现行默认 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ C-更激进 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px + + [60Hz 汇总 | 各场景等权平均 errMean] + A-现行默认 3.41px + B-更响应 2.70px + C-更激进 3.45px + D-更保守 2.86px + +───────── 120Hz(帧间隔 8.3ms)───────── +场景 │ 候选 │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后) +直线 │ A-现行默认 │ 58% │ 0.6px │ 1.2px │ 1.7px │ +0.04px +直线 │ B-更响应 │ 35% │ 0.5px │ 0.9px │ 1.0px │ +0.17px +直线 │ C-更激进 │ 69% │ 0.7px │ 1.3px │ 2.1px │ +0.02px +直线 │ D-更保守 │ 35% │ 0.5px │ 1.0px │ 1.2px │ +0.19px + +快弧(小半径) │ A-现行默认 │ 100% │ 8.5px │ 9.3px │ 11.8px │ -4.01px +快弧(小半径) │ B-更响应 │ 82% │ 9.2px │ 10.0px │ 11.0px │ -6.35px +快弧(小半径) │ C-更激进 │ 100% │ 13.0px │ 15.2px │ 15.4px │ -3.31px +快弧(小半径) │ D-更保守 │ 82% │ 10.4px │ 14.4px │ 14.5px │ -6.74px + +急转 │ A-现行默认 │ 32% │ 0.7px │ 1.0px │ 7.9px │ +0.17px +急转 │ B-更响应 │ 16% │ 0.4px │ 0.6px │ 0.6px │ +0.09px +急转 │ C-更激进 │ 40% │ 1.4px │ 4.7px │ 18.8px │ +0.51px +急转 │ D-更保守 │ 16% │ 0.4px │ 0.7px │ 0.7px │ +0.09px + +抖动 │ A-现行默认 │ 30% │ 2.0px │ 3.2px │ 3.3px │ -0.20px +抖动 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +抖动 │ C-更激进 │ 66% │ 2.0px │ 3.2px │ 3.2px │ -0.35px +抖动 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px + +停笔 │ A-现行默认 │ 23% │ 0.7px │ 1.0px │ 4.4px │ +0.17px +停笔 │ B-更响应 │ 12% │ 0.5px │ 2.1px │ 2.1px │ +0.22px +停笔 │ C-更激进 │ 26% │ 1.2px │ 6.8px │ 11.7px │ +0.61px +停笔 │ D-更保守 │ 12% │ 0.9px │ 7.0px │ 7.0px │ +0.63px + +慢短笔 │ A-现行默认 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ B-更响应 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ C-更激进 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px +慢短笔 │ D-更保守 │ 0% │ 0.0px │ 0.0px │ 0.0px │ +0.00px + + [120Hz 汇总 | 各场景等权平均 errMean] + A-现行默认 2.09px + B-更响应 1.76px + C-更激进 3.05px + D-更保守 2.04px + +提醒:以上均为合成轨迹上的离线数字;候选常数只在 iPad 真机手感验证后才可能被采纳,本轮未改任何默认值。 diff --git a/experiments/2026-11-12-ink-prediction/replay.ts b/experiments/2026-11-12-ink-prediction/replay.ts new file mode 100644 index 0000000..9e25a43 --- /dev/null +++ b/experiments/2026-11-12-ink-prediction/replay.ts @@ -0,0 +1,51 @@ +/** + * Replay-eval runner: synthetic trajectories × candidate constant sets → table. + * + * npx tsx experiments/2026-11-12-ink-prediction/replay.ts + * + * ⚠ 全部为合成轨迹(高斯噪声 ≠ 真实笔迹)。结果只作为 iPad 实测的初值候选, + * 本工具不修改任何默认常数。 + */ +import { makeTrajectory, replayTrajectory, SCENARIO_LABELS, type ReplayCandidate, type TrajectoryScenario } from '../../src/ink/replay' + +const SCENARIOS: TrajectoryScenario[] = ['straight', 'fastArc', 'sharpTurn', 'jitter', 'pause', 'slowTick'] +const RATES = [60, 120] + +const CANDIDATES: ReplayCandidate[] = [ + { name: 'A-现行默认' }, // gate 65/30/12, KF q=9e6 r=2, 2 frames ahead + { name: 'B-更响应', gate: { sharpTurnDeg: 55, jitterTurnDeg: 25, curveTurnDeg: 10 }, qAcc: 2e6, measVar: 1, framesAhead: 1.5 }, + { name: 'C-更激进', gate: { sharpTurnDeg: 75, jitterTurnDeg: 35, curveTurnDeg: 15 }, qAcc: 2.5e7, measVar: 4, framesAhead: 2.5 }, + { name: 'D-更保守', gate: { sharpTurnDeg: 55, jitterTurnDeg: 25, curveTurnDeg: 14 }, qAcc: 4e6, measVar: 2, framesAhead: 1.5 }, +] + +console.log('=== 墨迹预测离线回放评估(合成轨迹!仅供 iPad 实测初值候选;默认值未改) ===') +console.log('噪声: 高斯 0.6px(仅加在采样上,真值精确);窗口 96 样本;绝对时程上限 36ms;预测起点 = 第 8 个样本\n') + +for (const rateHz of RATES) { + console.log(`───────── ${rateHz}Hz(帧间隔 ${(1000 / rateHz).toFixed(1)}ms)─────────`) + console.log( + `${'场景'.padEnd(10)} │ ${'候选'.padEnd(11)} │ pred% │ errMean │ errP95 │ errMax │ 过冲(±=超前/滞后)`, + ) + for (const scenario of SCENARIOS) { + const traj = makeTrajectory(scenario, { rateHz, noisePx: 0.6, seed: 42 }) + for (const cand of CANDIDATES) { + const s = replayTrajectory(traj, cand, rateHz) + const predPct = s.moments ? ((s.predicted / s.moments) * 100).toFixed(0).padStart(3) : ' 0' + console.log( + `${SCENARIO_LABELS[scenario].padEnd(9)} │ ${cand.name.padEnd(11)} │ ${predPct}% │ ${s.meanErr.toFixed(1).padStart(6)}px │ ${s.p95Err + .toFixed(1) + .padStart(5)}px │ ${s.maxErr.toFixed(1).padStart(5)}px │ ${(s.meanOvershoot >= 0 ? '+' : '') + s.meanOvershoot.toFixed(2)}px`, + ) + } + console.log('') + } + // grand summary per candidate: mean err across scenarios (equal weight) + console.log(` [${rateHz}Hz 汇总 | 各场景等权平均 errMean]`) + for (const cand of CANDIDATES) { + const means = SCENARIOS.map((sc) => replayTrajectory(makeTrajectory(sc, { rateHz, noisePx: 0.6, seed: 42 }), cand, rateHz).meanErr) + const grand = means.reduce((a, b) => a + b, 0) / means.length + console.log(` ${cand.name.padEnd(11)} ${grand.toFixed(2)}px`) + } + console.log('') +} +console.log('提醒:以上均为合成轨迹上的离线数字;候选常数只在 iPad 真机手感验证后才可能被采纳,本轮未改任何默认值。') diff --git a/mcp/server.ts b/mcp/server.ts index 764d2ca..a0b8c39 100644 --- a/mcp/server.ts +++ b/mcp/server.ts @@ -42,7 +42,7 @@ async function bridgeCall(name: string, args: Record) { return data.result } -const server = new Server({ name: 'mathscrap', version: '0.0.1' }, { capabilities: { tools: {} } }) +const server = new Server({ name: 'mathscrap', version: '0.0.2' }, { capabilities: { tools: {} } }) server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOL_SPECS.map((tool) => ({ diff --git a/package-lock.json b/package-lock.json index 396d1ca..47fca77 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mathscrap", - "version": "0.0.1", + "version": "0.0.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mathscrap", - "version": "0.0.1", + "version": "0.0.2", "license": "Apache-2.0", "dependencies": { "@base-ui/react": "^1.9.0", @@ -22,6 +22,7 @@ "katex": "^0.19.1", "lucide-react": "^1.65.0", "onnxruntime-web": "^1.22.0", + "onnxruntime-web-nosimd": "npm:onnxruntime-web@1.18.0", "perfect-freehand": "^1.2.3", "plotly.js-dist-min": "^4.2.0", "react": "^19.3.1", @@ -5582,6 +5583,33 @@ "protobufjs": "^7.2.4" } }, + "node_modules/onnxruntime-web-nosimd": { + "name": "onnxruntime-web", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.18.0.tgz", + "integrity": "sha512-o1UKj4ABIj1gmG7ae0RKJ3/GT+3yoF0RRpfDfeoe0huzRW4FDRLfbkDETmdFAvnJEXuYDE0YT+hhkia0352StQ==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^1.12.0", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.18.0", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web-nosimd/node_modules/flatbuffers": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", + "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", + "license": "SEE LICENSE IN LICENSE.txt" + }, + "node_modules/onnxruntime-web-nosimd/node_modules/onnxruntime-common": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.18.0.tgz", + "integrity": "sha512-lufrSzX6QdKrktAELG5x5VkBpapbCeS3dQwrXbN0eD9rHvU0yAWl7Ztju9FvgAKWvwd/teEKJNj3OwM6eTZh3Q==", + "license": "MIT" + }, "node_modules/open": { "version": "11.0.4", "resolved": "https://registry.npmjs.org/open/-/open-11.0.4.tgz", diff --git a/package.json b/package.json index 9209e7a..77aea2f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mathscrap", "private": true, - "version": "0.0.1", + "version": "0.0.2", "type": "module", "scripts": { "dev": "vite", @@ -42,6 +42,7 @@ "katex": "^0.19.1", "lucide-react": "^1.65.0", "onnxruntime-web": "^1.22.0", + "onnxruntime-web-nosimd": "npm:onnxruntime-web@1.18.0", "perfect-freehand": "^1.2.3", "plotly.js-dist-min": "^4.2.0", "react": "^19.3.1", diff --git a/packaging/logo/SHA256SUMS.txt b/packaging/logo/SHA256SUMS.txt index 0d88221..b5855fd 100644 --- a/packaging/logo/SHA256SUMS.txt +++ b/packaging/logo/SHA256SUMS.txt @@ -1 +1,2 @@ b61b9160596a0f4e7fa1a9a9296d341687b3a158e24fdf082f24c1bb208c57bf app-icon.png +a84717bac33d0e3a566e025e77a51e8c2bd40cbb487dec26090d9dd4d5339509 app-icon-rounded.png diff --git a/packaging/logo/app-icon-rounded.png b/packaging/logo/app-icon-rounded.png new file mode 100644 index 0000000..da17fb9 Binary files /dev/null and b/packaging/logo/app-icon-rounded.png differ diff --git a/public/favicon.png b/public/favicon.png index 7f597db..4ed9167 100644 Binary files a/public/favicon.png and b/public/favicon.png differ diff --git a/public/models/comer/NOTICE.md b/public/models/comer/NOTICE.md index 7a7793b..902f67e 100644 --- a/public/models/comer/NOTICE.md +++ b/public/models/comer/NOTICE.md @@ -5,3 +5,8 @@ are the handwritten-math weights distributed by [ink-on](https://github.com/kims MathScrap does not train these files. The same two ONNX files are what a native ONNX Runtime build should load. + +`decoder_int8_compat.onnx` is the same decoder with its one `Trilu` (causal mask) replaced by +`ConstantOfShape`/`CumSum`/`Greater`, built by `scripts/make-compat-decoder.py`. Weights are unchanged. +The non-SIMD onnxruntime-web 1.18 fallback (WebKit before iOS / iPadOS 16.4) loads it because that +runtime has no `Trilu` kernel. diff --git a/public/models/comer/decoder_int8_compat.onnx b/public/models/comer/decoder_int8_compat.onnx new file mode 100644 index 0000000..3926bb9 Binary files /dev/null and b/public/models/comer/decoder_int8_compat.onnx differ diff --git a/scripts/ci-scope-smoke.mjs b/scripts/ci-scope-smoke.mjs index 3f7bd0a..30e29d3 100644 --- a/scripts/ci-scope-smoke.mjs +++ b/scripts/ci-scope-smoke.mjs @@ -2,7 +2,7 @@ * Regression cases for the CI scope classifier and the light version check. */ import { execFileSync } from 'node:child_process' -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs' +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { classifyEntries, classifyGit } from './ci-scope.mjs' @@ -36,7 +36,7 @@ check('version fields only', classifyEntries([ entry('crates/mathcore/Cargo.toml', '[package]\nname = "mathcore"\nversion = "0.0.1"\n\n[dependencies]\nserde = { version = "1" }\n', '[package]\nname = "mathcore"\nversion = "0.0.2"\n\n[dependencies]\nserde = { version = "1" }\n'), entry('package-lock.json', JSON.stringify({ version: '0.0.1', packages: { '': { version: '0.0.1', dependencies: { react: '^19.0.0' } }, react: { version: '19.0.0' } } }), JSON.stringify({ version: '0.0.2', packages: { '': { version: '0.0.2', dependencies: { react: '^19.0.0' } }, react: { version: '19.0.0' } } })), entry('src-tauri/Cargo.lock', '[[package]]\nname = "mathscrap"\nversion = "0.0.1"\n', '[[package]]\nname = "mathscrap"\nversion = "0.0.2"\n'), -]).mode, 'light') +]).mode, 'version') check('version plus function', classifyEntries([ entry('package.json', pkg('0.0.1'), pkg('0.0.2')), @@ -74,23 +74,98 @@ check('unknown', classifyEntries([ entry('src/new-file.ts', 'a\n', 'b\n'), ]).mode, 'full') -check('delete', classifyEntries([ - { status: 'D', oldMode: '100644', newMode: '000000', path: 'README.md', oldText: 'a\n', newText: null }, +check('delete code', classifyEntries([ + { status: 'D', oldMode: '100644', newMode: '000000', path: 'src/old.ts', oldText: 'a\n', newText: null }, ]).mode, 'full') -check('rename', classifyEntries([ - { status: 'R100', oldMode: '100644', newMode: '100644', oldPath: 'README.md', path: 'docs/README.md', oldText: null, newText: null }, +check('rename code', classifyEntries([ + { status: 'R100', oldMode: '100644', newMode: '100644', oldPath: 'src/a.ts', path: 'src/b.ts', oldText: null, newText: null }, +]).mode, 'full') + +check('rename docs into code', classifyEntries([ + { status: 'R100', oldMode: '100644', newMode: '100644', oldPath: 'docs/a.md', path: 'src/a.md', oldText: null, newText: null }, ]).mode, 'full') +check('delete docs', classifyEntries([ + { status: 'D', oldMode: '100644', newMode: '000000', path: 'README.md', oldText: 'a\n', newText: null }, +]).mode, 'docs') + +check('rename docs', classifyEntries([ + { status: 'R100', oldMode: '100644', newMode: '100644', oldPath: 'README.md', path: 'docs/README.md', oldText: null, newText: null }, +]).mode, 'docs') + check('docs only', classifyEntries([ entry('README.md', '版本 `0.0.1`\n', '版本 `0.0.1`\n\n更多说明。\n'), -]).mode, 'light') +]).mode, 'docs') + +check('new CONTRIBUTING is docs', classifyEntries([ + { status: 'A', oldMode: '000000', newMode: '100644', path: 'CONTRIBUTING.md', oldText: null, newText: '# hi\n' }, +]).mode, 'docs') + +check('docs screenshot', classifyEntries([ + { status: 'A', oldMode: '000000', newMode: '100644', path: 'docs/shot.png', oldText: null, newText: '\0' }, +]).mode, 'docs') + +check('binary readme is full', classifyEntries([ + entry('README.md', 'a\n', '\0'), +]).mode, 'full') + +check('docs plus version', classifyEntries([ + entry('README.md', 'a\n', 'b\n'), + entry('package.json', pkg('0.0.1'), pkg('0.0.2')), +]).mode, 'version') + +check('packaging script', classifyEntries([ + entry('scripts/package-ios.sh', 'echo a\n', 'echo b\n'), +]).mode, 'packaging') + +check('ios workflow', classifyEntries([ + entry('.github/workflows/package-ios.yml', 'name: a\n', 'name: b\n'), +]).mode, 'packaging') + +check('new icon', classifyEntries([ + { status: 'A', oldMode: '000000', newMode: '100644', path: 'src-tauri/icons/ios/AppIcon-1.png', oldText: null, newText: '\0' }, +]).mode, 'packaging') + +check('packaging plus docs plus version', classifyEntries([ + entry('scripts/package-android.sh', 'a\n', 'b\n'), + entry('docs/release-check.md', 'a\n', 'b\n'), + entry('package.json', pkg('0.0.1'), pkg('0.0.2')), +]).mode, 'packaging') + +check('packaging plus code', classifyEntries([ + entry('scripts/package-ios.sh', 'a\n', 'b\n'), + entry('src/board/Board.tsx', 'a\n', 'b\n'), +]).mode, 'full') + +check('docs plus code', classifyEntries([ + entry('README.md', 'a\n', 'b\n'), + entry('src/ink/flags.ts', 'a\n', 'b\n'), +]).mode, 'full') + +check('main package workflow stays full', classifyEntries([ + entry('.github/workflows/package.yml', 'name: a\n', 'name: b\n'), +]).mode, 'full') + +check('new workflow is full', classifyEntries([ + { status: 'A', oldMode: '000000', newMode: '100644', path: '.github/workflows/new.yml', oldText: null, newText: 'name: x\n' }, +]).mode, 'full') + +check('tauri shell is full', classifyEntries([ + entry('src-tauri/src/lib.rs', 'a\n', 'b\n'), +]).mode, 'full') + +check('experiment code is full', classifyEntries([ + entry('experiments/2026-11-12-ink-prediction/bench.ts', 'a\n', 'b\n'), +]).mode, 'full') + +check('missing path is full', classifyEntries([{ status: 'M', oldMode: '100644', newMode: '100644' }]).mode, 'full') check('invalid json is full', classifyEntries([ entry('package.json', pkg('0.0.1'), '{'), ]).mode, 'full') -check('empty diff', classifyEntries([]).mode, 'light') +check('empty diff', classifyEntries([]).mode, 'docs') function git(cwd, args) { execFileSync('git', args, { cwd, stdio: 'ignore' }) @@ -109,7 +184,7 @@ git(repo, ['commit', '-q', '-am', 'version one']) writeFileSync(join(repo, 'package.json'), pkg('0.0.3')) git(repo, ['commit', '-q', '-am', 'version two']) const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim() -check('multi commit version', classifyGit(repo, base, head).mode, 'light') +check('multi commit version', classifyGit(repo, base, head).mode, 'version') writeFileSync(join(repo, 'src-note.ts'), 'export const n = 1\n') git(repo, ['add', 'src-note.ts']) git(repo, ['commit', '-q', '-m', 'code']) @@ -162,7 +237,7 @@ try { check('illegal semver fails', illegal, true) rmSync(tree, { recursive: true, force: true }) -check('repo versions agree', checkVersions(`${process.cwd()}/`), '0.0.1') +check('repo versions agree', checkVersions(`${process.cwd()}/`), JSON.parse(readFileSync('package.json', 'utf8')).version) if (failed) { console.error(`${failed} failed`) diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs index 66d1818..814aad4 100644 --- a/scripts/ci-scope.mjs +++ b/scripts/ci-scope.mjs @@ -1,6 +1,10 @@ /** - * Decide whether a diff needs the full test job or a version check. - * Unknown, renamed, deleted, added, or unreadable changes are full. + * Decide which CI path a diff needs. + * docs documentation only: consistency checks only + * version whitelisted version fields (optionally plus docs): consistency checks, packages still build on push + * packaging packaging scripts, icons, the iOS workflow (optionally plus docs/version): packaging validation, no math suite + * full anything else, including mixed or unclassified changes: the whole test suite + * Added, deleted, or renamed files are allowed only when every path involved is documentation or packaging. * A broken baseline fails the process instead of passing. */ import { execFileSync } from 'node:child_process' @@ -21,8 +25,40 @@ const VERSION_FILES = new Set([ 'mcp/server.ts', ]) +const DOC_ROOT_FILES = new Set(['README.md', 'CONTRIBUTING.md', 'NOTICE', 'LICENSE']) + export function isDocsPath(path) { - return path === 'README.md' || path.startsWith('docs/') || path.startsWith('signing/') && path.endsWith('.md') + if (typeof path !== 'string' || !path) return false + if (DOC_ROOT_FILES.has(path)) return true + if (path.startsWith('docs/')) return true + if (path.startsWith('signing/') && path.endsWith('.md')) return true + if (path.startsWith('experiments/') && path.endsWith('.md')) return true + if (path.startsWith('.github/ISSUE_TEMPLATE/')) return true + if (/^\.github\/[^/]+\.md$/.test(path)) return true + return false +} + +/** Binary files are accepted as documentation only under docs/ (screenshots). */ +function docsBinaryOk(path) { + return path.startsWith('docs/') +} + +const PACKAGING_FILES = new Set([ + '.github/workflows/package-ios.yml', + 'scripts/checksum-artifacts.mjs', + 'scripts/android-release-signing.mjs', + 'scripts/compact-debug-apk.py', + 'scripts/make-icon.mjs', + 'scripts/make-rounded-icon.mjs', +]) + +export function isPackagingPath(path) { + if (typeof path !== 'string' || !path) return false + if (PACKAGING_FILES.has(path)) return true + if (/^scripts\/package-[\w-]+\.sh$/.test(path)) return true + if (path.startsWith('packaging/')) return true + if (path.startsWith('src-tauri/icons/')) return true + return false } function canon(value) { @@ -117,43 +153,55 @@ export function versionFieldOnly(path, oldText, newText) { return false } +const RANK = { docs: 0, version: 1, packaging: 2, full: 3 } + +const REASONS = { + docs: ['变化都是文档。', 'Every change is documentation.'], + version: ['变化都在文档或版本字段白名单内。', 'Every change is documentation or a whitelisted version field.'], + packaging: ['变化只涉及打包脚本、图标或 iOS 打包流程(可含文档和版本字段)。', 'The changes only touch packaging scripts, icons, or the iOS packaging workflow (plus documentation or version fields).'], +} + +function hasNul(text) { + return (text || '').includes('\0') +} + +/** Category of a single entry: docs, version, packaging, or full. */ +function classifyEntry(entry) { + const status = entry.status || '' + const paths = [entry.oldPath, entry.path].filter(Boolean) + if (!paths.length) return ['full', '(unknown) 无法识别'] + const label = paths.join(' -> ') + if (paths.every(isDocsPath)) { + const binary = hasNul(entry.oldText) || hasNul(entry.newText) + if (binary && !paths.every(docsBinaryOk)) return ['full', `${label} 无法按文档文本识别`] + return ['docs', `${label} 只是文档`] + } + if (paths.every(isPackagingPath)) return ['packaging', `${label} 只是打包`] + if (status.startsWith('R') || status.startsWith('C') || status === 'T') return ['full', `${label} 被重命名或改变类型`] + if (status === 'D' || status === 'A') return ['full', `${entry.path} 被${status === 'D' ? '删除' : '新增'}`] + if (status !== 'M' || entry.oldMode !== entry.newMode) return ['full', `${entry.path || '(unknown)'} 无法按字段识别`] + if (VERSION_FILES.has(entry.path) && versionFieldOnly(entry.path, entry.oldText, entry.newText)) { + return ['version', `${entry.path} 只有版本字段变化`] + } + return ['full', `${entry.path} 含有版本字段以外的变化`] +} + export function classifyEntries(entries) { if (!Array.isArray(entries)) { return { mode: 'full', reasonZh: '分类输入无法读取,改走全量。', reasonEn: 'The classifier input could not be read, so the full test runs.' } } if (entries.length === 0) { - return { mode: 'light', reasonZh: '基线之间没有文件变化。', reasonEn: 'There are no file changes between the baselines.' } + return { mode: 'docs', reasonZh: '基线之间没有文件变化。', reasonEn: 'There are no file changes between the baselines.' } } + let mode = 'docs' const notes = [] + const heavy = [] for (const entry of entries) { - const status = entry.status || '' - if (status.startsWith('R') || status.startsWith('C') || status === 'T') { - notes.push(`${entry.path || entry.oldPath} 被重命名或改变类型`) - continue - } - if (status === 'D' || status === 'A') { - notes.push(`${entry.path} 被${status === 'D' ? '删除' : '新增'}`) - continue - } - if (status !== 'M' || entry.oldMode !== entry.newMode) { - notes.push(`${entry.path || '(unknown)'} 无法按字段识别`) - continue - } - if (isDocsPath(entry.path)) { - if ((entry.oldText || '').includes('\0') || (entry.newText || '').includes('\0')) { - notes.push(`${entry.path} 无法按文档文本识别`) - continue - } - notes.push(`${entry.path} 只是文档`) - continue - } - if (VERSION_FILES.has(entry.path) && versionFieldOnly(entry.path, entry.oldText, entry.newText)) { - notes.push(`${entry.path} 只有版本字段变化`) - continue - } - notes.push(`${entry.path} 含有版本字段以外的变化`) + const [kind, note] = classifyEntry(entry || {}) + notes.push(note) + if (kind === 'full') heavy.push(note) + if (RANK[kind] > RANK[mode]) mode = kind } - const heavy = notes.filter((note) => !note.endsWith('只是文档') && !note.endsWith('只有版本字段变化')) if (heavy.length) { return { mode: 'full', @@ -162,9 +210,9 @@ export function classifyEntries(entries) { } } return { - mode: 'light', - reasonZh: `变化都在文档或版本字段白名单内:${notes.join(';')}。`, - reasonEn: `Every change is documentation or a whitelisted version field: ${notes.join('; ')}.`, + mode, + reasonZh: `${REASONS[mode][0]}${notes.join(';')}。`, + reasonEn: `${REASONS[mode][1]} ${notes.join('; ')}.`, } } @@ -241,23 +289,30 @@ export function classifyGit(cwd, base, head) { return { mergeBase, ...classifyEntries(entries) } } +const MODE_NAMES = { + docs: '文档 / docs', + version: '版本 / version', + packaging: '打包 / packaging', + full: '全量 / full', +} + function writeSummary(result) { const summaryPath = process.env.GITHUB_STEP_SUMMARY - const modeName = result.mode === 'light' ? '轻量 / light' : '全量 / full' + const full = result.mode === 'full' const body = [ - `### CI 范围:${modeName}`, + `### CI 范围:${MODE_NAMES[result.mode] || result.mode}`, '', result.reasonZh, '', result.reasonEn, '', - result.mode === 'light' - ? '轻量路径只核对各处版本号一致,并且都是 x.y.z。不一致就失败,不会记成通过。全量的 lint、Rust、smoke 和端到端测试这次不跑。' - : '全量路径会跑原有的 lint、Rust 测试、smoke,以及纸面、笔迹和公式的端到端测试。', + full + ? '全量路径会跑原有的 lint、Rust 测试、smoke,以及纸面、笔迹和公式的端到端测试。' + : '这次不跑数学测试套件(lint、Rust、smoke、端到端)。一致性检查照常运行:版本号一致且都是 x.y.z、分类器回归、打包脚本语法和工作流 YAML。不一致就失败,不会记成通过。' + (result.mode === 'packaging' ? '打包路径会实际构建安装包来验证。' : ''), '', - result.mode === 'light' - ? 'The light path only checks that the recorded versions match and are x.y.z. A mismatch fails this check. Lint, Rust, smoke, and end-to-end tests do not run.' - : 'The full path runs the existing lint, Rust tests, smoke tests, and the sheet, ink, and plot end-to-end tests.', + full + ? 'The full path runs the existing lint, Rust tests, smoke tests, and the sheet, ink, and plot end-to-end tests.' + : 'The math suite (lint, Rust, smoke, end-to-end) does not run. Consistency checks still run: matching x.y.z versions, the classifier regression, packaging script syntax, and workflow YAML. A failure fails the run.' + (result.mode === 'packaging' ? ' The packaging path builds the packages to validate them.' : ''), '', ].join('\n') console.log(body) diff --git a/scripts/e2e-ipad-compat.ts b/scripts/e2e-ipad-compat.ts new file mode 100644 index 0000000..8752cd7 --- /dev/null +++ b/scripts/e2e-ipad-compat.ts @@ -0,0 +1,206 @@ +/** + * iPad (iPadOS 15) behaviour in Chromium, against `npm run preview` (or APP_URL): + * + * 1. OCR without WASM SIMD. The SIMD probe is forced to fail (as on WebKit before 16.4); the page must + * load the non-SIMD compat runtime (`/ort-compat/`, never `/ort/`) and still read handwriting. + * `?ocr-compat=1` forces the same path. Without either, the SIMD runtime stays the default. + * 2. Pen or touch double-taps with the pen tool never open the formula composer; a mouse still does. + * Real (CDP) taps in the pen tool produce no synthesised click. + * 3. Board text selection and the iOS callout are off; the composer textarea can still select. + * + * Chromium is not WebKit and has SIMD; this approximates the iPad, it does not replace a device test. + * + * npm run build && npx vite preview & # 127.0.0.1:47322 + * npx tsx scripts/e2e-ipad-compat.ts + */ +import { chromium, type Page } from 'playwright-core' +import { resolveBrowser } from './browser-path.ts' +import { inkFixtures } from '../src/ocr/comer/samples.ts' + +const BASE = process.env.APP_URL ?? 'http://127.0.0.1:47322/' +const BROWSER = resolveBrowser() +const problems: string[] = [] +const check = (ok: boolean, what: string) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`) + if (!ok) problems.push(what) +} + +interface Board { + left: number + top: number + vx: number + vy: number + scale: number +} + +async function board(page: Page): Promise { + return page.evaluate(() => { + const el = document.querySelector('.kraft-page') as HTMLElement + const world = [...el.children].find((c) => (c as HTMLElement).style.transform.includes('scale')) as HTMLElement + const m = new DOMMatrixReadOnly(getComputedStyle(world).transform) + const r = el.getBoundingClientRect() + return { left: r.left, top: r.top, vx: m.e, vy: m.f, scale: m.a } + }) +} + +async function pageRead(page: Page) { + return page.evaluate(() => (window as unknown as { mathscrap: { tools: { call: (n: string, a: object) => { formulas: { text: string }[]; strokes: number } } } }).mathscrap.tools.call('page_read', {})) +} + +async function open(page: Page, query: string, noSimd: boolean) { + await page.addInitScript((noSimd) => { + localStorage.setItem('mathscrap.lang', 'zh') + localStorage.setItem('mathscrap.prefs.v2', JSON.stringify({ penOnly: false, showGrid: false, showHints: false, autoOcr: false })) + localStorage.removeItem('mathscrap.doc.v2') + if (noSimd) { + // WebKit before 16.4: the 31-byte SIMD probe does not validate. Everything else is untouched. + const real = WebAssembly.validate.bind(WebAssembly) + WebAssembly.validate = (bytes: BufferSource) => ((bytes as ArrayBufferView).byteLength === 31 ? false : real(bytes)) + } + }, noSimd) + const errors: string[] = [] + page.on('pageerror', (e) => errors.push(e.message)) + await page.goto(`${BASE}${query}`, { waitUntil: 'networkidle' }) + await page.waitForFunction(() => !!(window as unknown as { mathscrap?: unknown }).mathscrap) + await page.keyboard.press('p') + return errors +} + +/** Draw the y = 2 fixture with the mouse in world coordinates, offset into the sheet. */ +async function writeY2(page: Page) { + const b = await board(page) + const sample = inkFixtures(3).find((s) => s.name === 'y-eq-2')! + for (const stroke of sample.strokes) { + const pts = stroke.points.map((p) => ({ x: b.left + b.vx + (p.x + 120) * b.scale, y: b.top + b.vy + (p.y + 160) * b.scale })) + await page.mouse.move(pts[0]!.x, pts[0]!.y) + await page.mouse.down() + for (const p of pts.slice(1)) await page.mouse.move(p.x, p.y, { steps: 4 }) + await page.mouse.up() + await page.waitForTimeout(30) + } +} + +async function recognizeRun(page: Page, label: string, expectCompat: boolean) { + const urls: string[] = [] + page.on('request', (r) => urls.push(new URL(r.url()).pathname)) + await writeY2(page) + const t0 = Date.now() + await page.keyboard.press('r') + await page.waitForFunction(() => document.documentElement.dataset.ocr === 'idle', null, { timeout: 120_000 }) + const ms = Date.now() - t0 + const read = await pageRead(page) + const texts = read.formulas.map((f) => f.text) + const simd = urls.some((u) => u.startsWith('/ort/')) + const compat = urls.some((u) => u.startsWith('/ort-compat/')) + check(expectCompat ? compat && !simd : simd && !compat, `${label}: runtime ${expectCompat ? 'non-SIMD compat (/ort-compat/, no /ort/)' : 'SIMD (/ort/)'}`) + check(urls.includes(expectCompat ? '/models/comer/decoder_int8_compat.onnx' : '/models/comer/decoder_int8.onnx'), `${label}: ${expectCompat ? 'Trilu-free' : 'original'} decoder fetched`) + check(texts.some((t) => /^[yY]\s*=\s*2$/.test(t)), `${label}: handwriting read as y = 2 in ${ms} ms (${texts.join(' | ') || 'nothing'})`) +} + +const browser = await chromium.launch({ executablePath: BROWSER.executablePath, headless: true }) +try { + // 1a. no SIMD, detected (no flag) + { + const page = await browser.newPage({ viewport: { width: 1180, height: 820 } }) + const errors = await open(page, '', true) + await recognizeRun(page, 'no-SIMD WebView', true) + const toast = await page.locator('[data-sonner-toast]').allInnerTexts() + check(toast.some((t) => t.includes('兼容模式')), 'no-SIMD WebView: one toast explains compatibility mode') + check(errors.length === 0, `no-SIMD WebView: no page errors (${errors.join('; ')})`) + await page.close() + } + // 1b. dev flag + { + const page = await browser.newPage({ viewport: { width: 1180, height: 820 } }) + const errors = await open(page, '?ocr-compat=1', false) + await recognizeRun(page, '?ocr-compat=1', true) + check(errors.length === 0, `?ocr-compat=1: no page errors (${errors.join('; ')})`) + await page.close() + } + // 1c. default stays SIMD + { + const page = await browser.newPage({ viewport: { width: 1180, height: 820 } }) + const errors = await open(page, '', false) + await recognizeRun(page, 'SIMD default', false) + check(errors.length === 0, `SIMD default: no page errors (${errors.join('; ')})`) + await page.close() + } + // 2 + 3. composer, taps, selection + { + const context = await browser.newContext({ viewport: { width: 1180, height: 820 }, hasTouch: true }) + const page = await context.newPage() + await open(page, '', false) + const composerOpen = () => page.evaluate(() => document.activeElement instanceof HTMLTextAreaElement) + const b = await board(page) + const x = Math.round(b.left + 420) + const y = Math.round(b.top + 300) + for (const pointerType of ['touch', 'pen'] as const) { + await page.evaluate( + ({ x, y, pointerType }) => { + const el = document.querySelector('.kraft-page')! + for (let i = 0; i < 2; i++) { + el.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerId: 9, pointerType, clientX: x, clientY: y, button: 0, buttons: 1, isPrimary: true })) + el.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, cancelable: true, pointerId: 9, pointerType, clientX: x, clientY: y, button: 0, buttons: 0, isPrimary: true })) + } + el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true, clientX: x, clientY: y, detail: 2 })) + }, + { x, y, pointerType }, + ) + await page.waitForTimeout(150) + check(!(await composerOpen()), `pen tool: a ${pointerType} double-tap does not open the formula composer`) + } + // real touch taps through CDP: the board must cancel them, so no click is synthesised + await page.evaluate(() => { + const w = window as unknown as { clicks: number } + w.clicks = 0 + document.addEventListener('click', () => (w.clicks += 1), true) + }) + const session = await context.newCDPSession(page) + for (let i = 0; i < 2; i++) { + await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: x + 40, y, id: 3, radiusX: 2, radiusY: 2, force: 0.5 }] }) + await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) + await page.waitForTimeout(60) + } + await page.waitForTimeout(400) + const clicks = await page.evaluate(() => (window as unknown as { clicks: number }).clicks) + check(clicks === 0, `pen tool: real touch taps on the board synthesise no click (${clicks})`) + check(!(await composerOpen()), 'pen tool: real touch taps do not open the formula composer') + const style = await page.evaluate(() => { + const s = getComputedStyle(document.querySelector('.kraft-page')!) as CSSStyleDeclaration & { webkitUserSelect?: string; webkitTouchCallout?: string } + return { userSelect: s.userSelect || s.webkitUserSelect, touchAction: s.touchAction } + }) + check(style.userSelect === 'none' && style.touchAction === 'none', `board: user-select ${style.userSelect}, touch-action ${style.touchAction}`) + const blocked = await page.evaluate(() => { + const el = document.querySelector('.kraft-page')! + const span = document.createElement('span') + span.textContent = 'text' + el.appendChild(span) + const ev = new Event('selectstart', { bubbles: true, cancelable: true }) + span.firstChild!.dispatchEvent(ev) + span.remove() + return ev.defaultPrevented + }) + check(blocked, 'board: selectstart on text inside the board is cancelled') + // mouse double-click still opens the composer, and its textarea can select + await page.mouse.dblclick(x, y + 80) + await page.waitForTimeout(200) + check(await composerOpen(), 'pen tool: a mouse double-click still opens the composer (desktop unchanged)') + const fieldOk = await page.evaluate(() => { + const ta = document.activeElement as HTMLTextAreaElement + const ev = new Event('selectstart', { bubbles: true, cancelable: true }) + ta.dispatchEvent(ev) + return !ev.defaultPrevented && getComputedStyle(ta).userSelect !== 'none' + }) + check(fieldOk, 'composer textarea keeps text selection') + await session.detach() + await context.close() + } +} finally { + await browser.close() +} + +if (problems.length) { + console.error(`\n${problems.length} problem(s)`) + process.exit(1) +} +console.log('\ne2e ipad-compat ok') diff --git a/scripts/make-compat-decoder.py b/scripts/make-compat-decoder.py new file mode 100644 index 0000000..28eae63 --- /dev/null +++ b/scripts/make-compat-decoder.py @@ -0,0 +1,62 @@ +""" +Build public/models/comer/decoder_int8_compat.onnx for the non-SIMD OCR fallback. + +onnxruntime-web 1.18 (the last release with a non-SIMD `ort-wasm.wasm`) has no Trilu kernel. +The decoder uses one Trilu to build its causal mask: Trilu(ones[L, L] bool, k=1, upper=1), +i.e. mask[i, j] = j > i. This swaps it for ops 1.18 ships: + + f = ConstantOfShape(shape, 1.0f) # [L, L] + col = CumSum(f, axis=1) # j + 1 + row = CumSum(f, axis=0) # i + 1 + mask = Greater(col, row) # j > i (bool, same as the Trilu output) + +Weights and every other node are untouched. Requires `pip install onnx`. + + python scripts/make-compat-decoder.py +""" +import sys + +import numpy as np +import onnx +from onnx import helper, numpy_helper + +SRC = 'public/models/comer/decoder_int8.onnx' +DST = 'public/models/comer/decoder_int8_compat.onnx' + +model = onnx.load(SRC) +graph = model.graph +nodes = list(graph.node) +trilu = [n for n in nodes if n.op_type == 'Trilu'] +if len(trilu) != 1: + sys.exit(f'expected one Trilu, found {len(trilu)}') +tri = trilu[0] +upper = next((a.i for a in tri.attribute if a.name == 'upper'), 1) +produced = {o: n for n in nodes for o in n.output} +src_ones = produced[tri.input[0]] +k_node = produced[tri.input[1]] +fill = numpy_helper.to_array(src_ones.attribute[0].t) +k = int(numpy_helper.to_array(k_node.attribute[0].t)) +if src_ones.op_type != 'ConstantOfShape' or fill.dtype != np.bool_ or not bool(fill.reshape(-1)[0]) or k != 1 or upper != 1: + sys.exit('decoder mask is not Trilu(ones bool, k=1, upper=1); refusing to rewrite') + +shape = src_ones.input[0] +p = '/decoder/compat_mask' +axis1 = numpy_helper.from_array(np.array(1, dtype=np.int64), f'{p}/axis1') +axis0 = numpy_helper.from_array(np.array(0, dtype=np.int64), f'{p}/axis0') +graph.initializer.extend([axis0, axis1]) +replacement = [ + helper.make_node('ConstantOfShape', [shape], [f'{p}/ones'], name=f'{p}/ones', value=numpy_helper.from_array(np.array([1.0], dtype=np.float32))), + helper.make_node('CumSum', [f'{p}/ones', axis1.name], [f'{p}/col'], name=f'{p}/col'), + helper.make_node('CumSum', [f'{p}/ones', axis0.name], [f'{p}/row'], name=f'{p}/row'), + helper.make_node('Greater', [f'{p}/col', f'{p}/row'], [tri.output[0]], name=f'{p}/greater'), +] +idx = nodes.index(tri) +out = nodes[:idx] + replacement + nodes[idx + 1 :] +# drop the bool ConstantOfShape and k Constant if nothing else reads them +used = {i for n in out for i in n.input} +out = [n for n in out if not (n in (src_ones, k_node) and not any(o in used for o in n.output))] +del graph.node[:] +graph.node.extend(out) +onnx.checker.check_model(model) +onnx.save(model, DST) +print(f'wrote {DST}') diff --git a/scripts/make-rounded-icon.mjs b/scripts/make-rounded-icon.mjs new file mode 100644 index 0000000..9aedcc4 --- /dev/null +++ b/scripts/make-rounded-icon.mjs @@ -0,0 +1,41 @@ +/** + * Rounded-corner desktop icon master from packaging/logo/app-icon.png. + * Corners outside the rounded square become transparent (4x4 supersampled edge). + * Windows, macOS, Linux and the web favicon use this. iOS keeps the opaque square + * master because iOS masks it itself; Android keeps its own adaptive/round icons. + * + * node scripts/make-rounded-icon.mjs + * npx tauri icon packaging/logo/app-icon-rounded.png -o (then copy the desktop files) + */ +import { PNG } from 'pngjs' +import { readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const src = PNG.sync.read(readFileSync(path.join(root, 'packaging/logo/app-icon.png'))) +const size = src.width +if (src.height !== size) throw new Error('app-icon.png must be square') +// Corner radius as a share of the edge, close to the macOS / iOS app icon corner. +const radius = size * 0.2237 +const out = new PNG({ width: size, height: size }) +const SS = 4 +function inside(x, y) { + const cx = Math.min(Math.max(x, radius), size - radius) + const cy = Math.min(Math.max(y, radius), size - radius) + return (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius +} +for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + const i = (y * size + x) * 4 + let hits = 0 + for (let sy = 0; sy < SS; sy++) for (let sx = 0; sx < SS; sx++) if (inside(x + (sx + 0.5) / SS, y + (sy + 0.5) / SS)) hits++ + out.data[i] = src.data[i] + out.data[i + 1] = src.data[i + 1] + out.data[i + 2] = src.data[i + 2] + out.data[i + 3] = Math.round((src.data[i + 3] * hits) / (SS * SS)) + } +} +const dest = path.join(root, 'packaging/logo/app-icon-rounded.png') +writeFileSync(dest, PNG.sync.write(out)) +console.log(dest) \ No newline at end of file diff --git a/scripts/ocr-live.ts b/scripts/ocr-live.ts index 689c77a..e0cec65 100644 --- a/scripts/ocr-live.ts +++ b/scripts/ocr-live.ts @@ -19,19 +19,26 @@ import { classifyInk } from '../src/ocr/gate.ts' import { OCR_ACCEPT } from '../src/ocr/threshold.ts' import { arrowLetter, inkFixtures, isolatedSigma, pointPair, proseNote, sumBar, sumGlyph } from '../src/ocr/comer/samples.ts' import { vocabFromJson } from '../src/ocr/comer/source.ts' +import { loadCompatOrt } from './ort-compat-node.ts' -const ort = await import('onnxruntime-web/wasm') -const dist = path.resolve('node_modules/onnxruntime-web/dist') -ort.env.wasm.numThreads = 1 -ort.env.wasm.simd = true -ort.env.wasm.wasmPaths = pathToFileURL(`${dist}/`).href +// MATHSCRAP_OCR_COMPAT=1 runs the non-SIMD fallback (onnxruntime-web 1.18 `ort-wasm.wasm`) +// that WebKit before iOS / iPadOS 16.4 loads. Same models, same decode path. +const compat = process.env.MATHSCRAP_OCR_COMPAT === '1' +const compatRt = compat ? await loadCompatOrt() : null +const ort = compatRt ? compatRt.ort : await import('onnxruntime-web/wasm') +if (!compatRt) { + ort.env.wasm.numThreads = 1 + ort.env.wasm.simd = true + ort.env.wasm.wasmPaths = pathToFileURL(`${path.resolve('node_modules/onnxruntime-web/dist')}/`).href +} +console.log(`runtime: onnxruntime-web ${ort.env.versions?.web ?? '?'} ${compat ? 'non-SIMD compat' : 'SIMD'}`) const vocab = vocabFromJson(JSON.parse(readFileSync('public/models/comer/vocab.json', 'utf8'))) const opts = { executionProviders: ['wasm' as const] } -const [encoder, decoder] = await Promise.all([ - ort.InferenceSession.create(readFileSync('public/models/comer/encoder_int8.onnx'), opts).then(wrap), - ort.InferenceSession.create(readFileSync('public/models/comer/decoder_int8.onnx'), opts).then(wrap), -]) +const open = (file: string) => (compatRt ? compatRt.create(readFileSync(file)) : ort.InferenceSession.create(readFileSync(file), opts)) +const encoder = wrap(await open('public/models/comer/encoder_int8.onnx')) +// 1.18 has no Trilu kernel; the compat decoder builds the same causal mask without it. +const decoder = wrap(await open(compat ? 'public/models/comer/decoder_int8_compat.onnx' : 'public/models/comer/decoder_int8.onnx')) const outDir = '/tmp/mathscrap-ocr' mkdirSync(outDir, { recursive: true }) @@ -80,7 +87,8 @@ const pointHits = await recognizeStrokes(pointPair(), encoder, decoder, vocab, 2 console.log('point', pointHits.map((h) => `${h.text} (${h.confidence.toFixed(2)})`).join(' | ') || '(empty)') assert.match(pointHits[0]?.text ?? '', /^A\(2, 2\)$/) -console.log('ocr live ok') +compatRt?.close() +console.log(`ocr live ok (${compat ? 'non-SIMD compat' : 'SIMD'})`) function loose(name: string) { if (name === 'y-eq-2') return /^[yY] = 2$/ diff --git a/scripts/ocr-model-pins.json b/scripts/ocr-model-pins.json index 4b4f5e7..ffadded 100644 --- a/scripts/ocr-model-pins.json +++ b/scripts/ocr-model-pins.json @@ -1,5 +1,6 @@ { "encoder_int8.onnx": "272f17c7b120db61db6cd8d77e695d0139144044abd57d9b23284435a5d916fa", "decoder_int8.onnx": "658901d81ca3aa4b62b0da262e8fe67ebcfdac19cfb52ca2cfd076bebd481088", - "vocab.json": "1d75cbbea3bed558683d7e9c3b3c72069ef2143a155d5f8c610f85a281af000c" + "vocab.json": "1d75cbbea3bed558683d7e9c3b3c72069ef2143a155d5f8c610f85a281af000c", + "decoder_int8_compat.onnx": "cd829ff31cf632c458b7a6765aaf5080015e28c5b1fa5b2a23715e7146de923f" } diff --git a/scripts/ocr-real-smoke.ts b/scripts/ocr-real-smoke.ts index c328972..52aafd0 100644 --- a/scripts/ocr-real-smoke.ts +++ b/scripts/ocr-real-smoke.ts @@ -18,6 +18,7 @@ import { recognizeStrokes } from '../src/ocr/comer/engine.ts' import { vocabFromJson } from '../src/ocr/comer/source.ts' import type { ComerSession, ComerTensor } from '../src/ocr/comer/decode.ts' import { OCR_ACCEPT } from '../src/ocr/threshold.ts' +import { loadCompatOrt } from './ort-compat-node.ts' const modelDir = 'public/models/comer' const pins = JSON.parse(readFileSync('scripts/ocr-model-pins.json', 'utf8')) as Record @@ -87,6 +88,21 @@ const pointHits = await recognizeStrokes(pointPair(), encoder, decoder, vocab, 2 console.log('synthetic point', pointHits.map((h) => `${h.text} (${h.confidence.toFixed(2)})`).join(' | ') || '(empty)') assert.match(pointHits[0]?.text ?? '', /^A\(2, 2\)$/) assert.equal(ran, 4) + +// Non-SIMD fallback (WebKit before iOS / iPadOS 16.4): onnxruntime-web 1.18 `ort-wasm.wasm` with the +// Trilu-free decoder must read the same fixtures the same way as the SIMD runtime. +const compatRt = await loadCompatOrt() +const compatEncoder = wrapWith(compatRt.ort, await compatRt.create(readFileSync(path.join(modelDir, 'encoder_int8.onnx')))) +const compatDecoder = wrapWith(compatRt.ort, await compatRt.create(readFileSync(path.join(modelDir, 'decoder_int8_compat.onnx')))) +for (const strokes of [...['y-eq-2', 'y-eq-x', 'frac', 'a2-eq-b'].map((name) => fixtures.find((item) => item.name === name)!.strokes), sumGlyph(), pointPair()]) { + const want = await recognizeStrokes(strokes, encoder, decoder, vocab, 2) + const t0 = Date.now() + const got = await recognizeStrokes(strokes, compatEncoder, compatDecoder, vocab, 2) + console.log(`compat ${got[0]?.text ?? '(empty)'} ${Date.now() - t0}ms`) + assert.deepEqual(got.map((h) => h.text), want.map((h) => h.text), 'compat runtime reads like the SIMD runtime') + for (let i = 0; i < got.length; i++) assert.ok(Math.abs(got[i]!.confidence - want[i]!.confidence) < 1e-3, 'compat confidence') +} +compatRt.close() console.log('ocr-real-smoke ok (synthetic strokes; confidence is not accuracy; no handwriting scan in the repo)') function boom(): ComerSession { @@ -106,12 +122,16 @@ function copyData(data: ArrayBufferView): Float32Array | Uint8Array | BigInt64Ar return new Uint8Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) } -function wrap(session: { run: (feeds: Record) => Promise void }>> }): ComerSession { +function wrap(session: Parameters[1]): ComerSession { + return wrapWith(ort, session) +} + +function wrapWith(rt: typeof ort, session: { run: (feeds: Record) => Promise void }>> }): ComerSession { return { async run(feeds) { const mapped: Record void }> = {} for (const [name, tensor] of Object.entries(feeds)) { - mapped[name] = new ort.Tensor(tensor.type, tensor.data as never, tensor.dims) + mapped[name] = new rt.Tensor(tensor.type, tensor.data as never, tensor.dims) } const out = await session.run(mapped) for (const value of Object.values(mapped)) value.dispose?.() diff --git a/scripts/ocr-smoke.ts b/scripts/ocr-smoke.ts index 4387e19..b062f8a 100644 --- a/scripts/ocr-smoke.ts +++ b/scripts/ocr-smoke.ts @@ -590,3 +590,27 @@ assert.equal(tokensToSource(['\\ln', '(', 'x', ')']).replace(/\s+/g, ''), 'ln(x) assert.equal(tokensToSource(['\\log', '_', '{', '2', '}', '(', 'x', ')']).replace(/\s+/g, ''), 'log_2(x)') assert.equal(tokensToSource(['\\lg', '(', 'x', ')']).replace(/\s+/g, ''), 'lg(x)') console.log('ocr log source ok') + +// Runtime choice: SIMD WebViews keep onnxruntime-web 1.22; no SIMD (WebKit before 16.4) gets the +// non-SIMD compat runtime instead of "unavailable"; no WebAssembly at all is the only "none". +{ + const { pickOcrRuntime } = await import('../src/ocr/support.ts') + const simdProbe = (bytes: Uint8Array) => bytes.length > 8 && bytes.includes(253) + const desktop = { validate: () => true } + const ipad15 = { validate: (bytes: Uint8Array) => !simdProbe(bytes) } + const throws = { + validate: () => { + throw new Error('boom') + }, + } + assert.equal(pickOcrRuntime(desktop, false), 'simd') + assert.equal(pickOcrRuntime(desktop, true), 'compat', '?ocr-compat=1 forces the fallback for testing') + assert.equal(pickOcrRuntime(ipad15, false), 'compat') + assert.equal(pickOcrRuntime(undefined, false), 'none') + assert.equal(pickOcrRuntime(throws, false), 'none', 'a throwing probe never crashes the app') + assert.equal(pickOcrRuntime((globalThis as { WebAssembly?: { validate: (b: Uint8Array) => boolean } }).WebAssembly, false), 'simd', 'this Node has SIMD') + const web = readFileSync('src/ocr/comer/web.ts', 'utf8') + assert.match(web, /onnxruntime-web-nosimd\/wasm/) + assert.match(web, /decoder_int8_compat\.onnx/) + console.log('ocr runtime choice ok') +} diff --git a/scripts/ort-compat-node.ts b/scripts/ort-compat-node.ts new file mode 100644 index 0000000..1b190a1 --- /dev/null +++ b/scripts/ort-compat-node.ts @@ -0,0 +1,48 @@ +/** + * Load the non-SIMD CoMER fallback (onnxruntime-web 1.18 `ort-wasm.wasm`) under Node for smokes. + * + * 1.18's web build stubs `fs`/`path`, so its Node branch cannot read the WASM. While the runtime + * initialises, Node is hidden from Emscripten and the file is fetched from a 127.0.0.1-only + * server, the same fetch + instantiate path WebKit takes. The browser app never uses this file. + */ +import { createServer } from 'node:http' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import type { AddressInfo } from 'node:net' +import path from 'node:path' + +type Ort = typeof import('onnxruntime-web/wasm') + +export const COMPAT_WASM = 'ort-wasm.wasm' + +export async function loadCompatOrt(): Promise<{ ort: Ort; create: (bytes: Uint8Array) => ReturnType; close: () => void }> { + const ort = createRequire(import.meta.url)('onnxruntime-web-nosimd/wasm') as Ort + const wasm = readFileSync(path.resolve('node_modules/onnxruntime-web-nosimd/dist', COMPAT_WASM)) + const server = createServer((req, res) => { + if (req.url !== `/${COMPAT_WASM}`) { + res.statusCode = 404 + res.end() + return + } + res.setHeader('content-type', 'application/wasm') + res.end(wasm) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const { port } = server.address() as AddressInfo + ort.env.wasm.numThreads = 1 + ort.env.wasm.simd = false + ort.env.wasm.proxy = false + ort.env.wasm.wasmPaths = `http://127.0.0.1:${port}/` + let ready: Promise | null = null + const create = async (bytes: Uint8Array) => { + if (!ready) { + const desc = Object.getOwnPropertyDescriptor(process.versions, 'node')! + Object.defineProperty(process.versions, 'node', { value: undefined, configurable: true }) + ready = ort.InferenceSession.create(bytes, { executionProviders: ['wasm'] }).finally(() => Object.defineProperty(process.versions, 'node', desc)) + return ready as ReturnType + } + await ready.catch(() => undefined) + return ort.InferenceSession.create(bytes, { executionProviders: ['wasm'] }) + } + return { ort, create, close: () => server.close() } +} diff --git a/scripts/package-ios.sh b/scripts/package-ios.sh index 4f7a7a2..e50e2e8 100755 --- a/scripts/package-ios.sh +++ b/scripts/package-ios.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# iOS Simulator .app, or a signed IPA when Apple signing inputs are present. +# iOS Simulator .app, a signed IPA when Apple signing inputs are present, +# or (--unsigned) an unsigned device IPA for TrollStore / jailbroken sideloading. # This script never enrolls in the Apple Developer Program and never creates a certificate. set -euo pipefail cd "$(dirname "$0")/.." @@ -9,9 +10,10 @@ for arg in "$@"; do case "$arg" in --simulator) target="simulator" ;; --device) target="device" ;; + --unsigned) target="unsigned" ;; *) echo "Unknown argument: $arg" >&2 - echo "Usage: scripts/package-ios.sh [--simulator|--device]" >&2 + echo "Usage: scripts/package-ios.sh [--simulator|--device|--unsigned]" >&2 exit 2 ;; esac @@ -56,7 +58,8 @@ What each command actually produces: APPLE_API_KEY_PATH path to the AuthKey .p8 already on that Mac Then: npm run pack:ios -- --device -Minimum OS for the packaged shell is iOS 16.4 (WebAssembly SIMD for CoMER). +Minimum OS for the packaged shell is iOS 15.0 (arm64). CoMER uses WebAssembly SIMD on iOS 16.4+; +older systems fall back to the slower non-SIMD runtime (onnxruntime-web 1.18), manual Recognize only. The bundle id is app.mathscrap. It must match the App ID inside the profile. EOF exit 3 @@ -71,6 +74,27 @@ if [[ ! -d src-tauri/gen/apple ]]; then npx tauri ios init --ci fi +# The generated project starts with the template icon. Copy the committed opaque +# square icons (made from packaging/logo/app-icon.png) over it. iOS applies the +# rounded mask itself, so no transparent corners are baked in. +iconset="src-tauri/gen/apple/Assets.xcassets/AppIcon.appiconset" +if [[ -d "$iconset" ]]; then + copied=0 + for png in "$iconset"/*.png; do + [[ -e "$png" ]] || continue + src="src-tauri/icons/ios/$(basename "$png")" + if [[ -f "$src" ]]; then + cp "$src" "$png" + copied=$((copied + 1)) + fi + done + if [[ "$copied" -eq 0 ]]; then + echo "No AppIcon file in $iconset matched src-tauri/icons/ios. Refusing to ship the template icon." >&2 + exit 4 + fi + echo "app icon: copied $copied files from src-tauri/icons/ios" +fi + version="$(node -p "require('./package.json').version")" mkdir -p packaging/out @@ -82,6 +106,61 @@ if [[ "$target" == "simulator" ]]; then exit 0 fi +if [[ "$target" == "unsigned" ]]; then + # Archive without code signing; tauri wraps Payload/MathScrap.app into an .ipa. + npx tauri ios build --target aarch64 --no-sign --ci + built="$(find src-tauri/gen/apple/build -type f -name '*.ipa' | sort | head -1)" + if [[ -z "$built" ]]; then + echo "tauri ios build --no-sign finished but no .ipa was found under src-tauri/gen/apple/build." >&2 + exit 1 + fi + work="$(mktemp -d)" + unzip -q "$built" -d "$work" + app="$(find "$work/Payload" -maxdepth 1 -type d -name '*.app' | head -1)" + if [[ -z "$app" ]]; then + echo "The IPA has no Payload/*.app." >&2 + exit 1 + fi + exe="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app/Info.plist")" + minos="$(/usr/libexec/PlistBuddy -c 'Print :MinimumOSVersion' "$app/Info.plist" 2>/dev/null || echo unknown)" + bundle_id="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Info.plist")" + archs="$(lipo -archs "$app/$exe")" + echo "bundle $bundle_id executable $exe MinimumOSVersion $minos archs $archs" + if [[ "$archs" != "arm64" ]]; then + echo "Expected a plain arm64 device slice (A8X and later, no arm64e), got: $archs" >&2 + exit 1 + fi + # Optional ad-hoc "fake" signature so TrollStore keeps the entitlements. Not an Apple signature. + fakesign="none" + if command -v ldid >/dev/null 2>&1; then + ent="$(find src-tauri/gen/apple -maxdepth 2 -name '*.entitlements' | head -1)" + if [[ -n "$ent" ]]; then + ldid -S"$ent" "$app/$exe" + else + ldid -S "$app/$exe" + fi + fakesign="ldid" + fi + dest="packaging/out/MathScrap-${version}-ios-unsigned.ipa" + rm -f "$dest" + (cd "$work" && zip -qry "$OLDPWD/$dest" Payload) + rm -rf "$work" + { + echo "ios_ipa=$(basename "$dest")" + echo "ios_signing=unsigned (no Apple certificate or provisioning profile)" + echo "ios_fakesign=$fakesign" + echo "ios_bundle_id=$bundle_id" + echo "ios_minimum_os=$minos" + echo "ios_archs=$archs" + echo "ios_ocr=WebAssembly SIMD on iOS 16.4+; older systems use the slower non-SIMD compat runtime (manual Recognize)" + echo "ios_install=TrollStore or a jailbroken device only; stock iOS refuses it" + } > packaging/out/PROVENANCE-ios.txt + node scripts/checksum-artifacts.mjs packaging/out + echo "artifact $dest" + echo "This IPA is unsigned. It installs only through TrollStore or on a jailbroken device." + exit 0 +fi + signed=0 if [[ -n "${IOS_CERTIFICATE:-}" && -n "${IOS_CERTIFICATE_PASSWORD:-}" && -n "${IOS_MOBILE_PROVISION:-}" ]]; then signed=1 diff --git a/scripts/verify-packaged-dist.mjs b/scripts/verify-packaged-dist.mjs index fcaa564..c4249cd 100644 --- a/scripts/verify-packaged-dist.mjs +++ b/scripts/verify-packaged-dist.mjs @@ -25,6 +25,7 @@ if (!existsSync(dist)) fail('dist/ is missing. Run npm run build first. This che need('index.html', 100) need('models/comer/encoder_int8.onnx', 1_000_000) need('models/comer/decoder_int8.onnx', 1_000_000) +need('models/comer/decoder_int8_compat.onnx', 1_000_000) need('models/comer/vocab.json', 100) need('models/comer/LICENSE', 100) need('models/comer/NOTICE.md', 50) @@ -41,6 +42,9 @@ if (!ort.some((name) => name === 'ort-wasm-simd.wasm')) { console.log('note: ort-wasm-simd.wasm (non-threaded) is not in this onnxruntime-web build; the threaded file is the one the page requests with numThreads = 1') } +// non-SIMD fallback (onnxruntime-web 1.18) for WebKit before iOS / iPadOS 16.4 +need('ort-compat/ort-wasm.wasm', 1_000_000) + const assets = path.join(dist, 'assets') const wasm = existsSync(assets) ? readdirSync(assets).filter((name) => name.endsWith('.wasm')) : [] if (!wasm.length) fail('mathcore WASM was not emitted under dist/assets') diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 483ecc1..167774d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1732,7 +1732,7 @@ dependencies = [ [[package]] name = "mathscrap" -version = "0.0.1" +version = "0.0.2" dependencies = [ "mcpserve", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 877e955..0b514a8 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mathscrap" -version = "0.0.1" +version = "0.0.2" description = "Kraft-paper math scrapbook: Freeform-like sheet, shared plot, geometry inference (Rust/WASM)." authors = ["DNTOF"] license = "Apache-2.0" diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png index 0a13f9d..187b8de 100644 Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/src-tauri/icons/128x128@2x.png index 7f597db..4ed9167 100644 Binary files a/src-tauri/icons/128x128@2x.png and b/src-tauri/icons/128x128@2x.png differ diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png index bc34692..b26080e 100644 Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png index 1d0c8d9..1763de8 100644 Binary files a/src-tauri/icons/64x64.png and b/src-tauri/icons/64x64.png differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png index 7683c57..c9b0369 100644 Binary files a/src-tauri/icons/Square107x107Logo.png and b/src-tauri/icons/Square107x107Logo.png differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png index 265e7a7..c1864e6 100644 Binary files a/src-tauri/icons/Square142x142Logo.png and b/src-tauri/icons/Square142x142Logo.png differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png index 9d360b4..aa27c97 100644 Binary files a/src-tauri/icons/Square150x150Logo.png and b/src-tauri/icons/Square150x150Logo.png differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png index 23e4358..9490cf0 100644 Binary files a/src-tauri/icons/Square284x284Logo.png and b/src-tauri/icons/Square284x284Logo.png differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png index 3a3a49f..ba9c8fa 100644 Binary files a/src-tauri/icons/Square30x30Logo.png and b/src-tauri/icons/Square30x30Logo.png differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png index eeb0043..d8cd870 100644 Binary files a/src-tauri/icons/Square310x310Logo.png and b/src-tauri/icons/Square310x310Logo.png differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png index 146224c..efa6428 100644 Binary files a/src-tauri/icons/Square44x44Logo.png and b/src-tauri/icons/Square44x44Logo.png differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png index c62a00d..60271bd 100644 Binary files a/src-tauri/icons/Square71x71Logo.png and b/src-tauri/icons/Square71x71Logo.png differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png index 8998968..684bc22 100644 Binary files a/src-tauri/icons/Square89x89Logo.png and b/src-tauri/icons/Square89x89Logo.png differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png index 083c2cc..736d9c0 100644 Binary files a/src-tauri/icons/StoreLogo.png and b/src-tauri/icons/StoreLogo.png differ diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns index 09b68c3..32ab3e1 100644 Binary files a/src-tauri/icons/icon.icns and b/src-tauri/icons/icon.icns differ diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico index d48d910..f7bff8a 100644 Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png index 4161784..ece992d 100644 Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 54d56c1..4d2b52c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,7 +3,9 @@ use mcpserve::Hub; pub fn mcp_stdio() { mcpserve::stdio_main(); } -use tauri::{Emitter, Manager}; +#[cfg(desktop)] +use tauri::Emitter; +use tauri::Manager; fn close_mcp(app: &impl Manager) { if let Some(hub) = app.try_state::() { @@ -38,9 +40,15 @@ pub fn run() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_fs::init()) .setup(|app| { - let handle = app.handle().clone(); - let dispatch = std::sync::Arc::new(move |job: serde_json::Value| handle.emit("mcp-call", job).is_ok()); - let hub = Hub::start(dispatch).unwrap_or_else(|_| Hub::disabled()); + // The loopback MCP listener is a desktop feature. iOS and Android never open it. + #[cfg(desktop)] + let hub = { + let handle = app.handle().clone(); + let dispatch = std::sync::Arc::new(move |job: serde_json::Value| handle.emit("mcp-call", job).is_ok()); + Hub::start(dispatch).unwrap_or_else(|_| Hub::disabled()) + }; + #[cfg(mobile)] + let hub = Hub::disabled(); app.manage(hub); Ok(()) }) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9278906..8c5db23 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "MathScrap", - "version": "0.0.1", + "version": "0.0.2", "identifier": "app.mathscrap", "build": { "beforeDevCommand": "npm run dev", @@ -42,7 +42,7 @@ "minSdkVersion": 24 }, "iOS": { - "minimumSystemVersion": "16.4" + "minimumSystemVersion": "15.0" }, "windows": { "webviewInstallMode": { diff --git a/src/App.tsx b/src/App.tsx index 32c5900..0e79dd1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -25,6 +25,9 @@ import { pageGroups } from '@/math/page' import { summarizeCard } from '@/math/scene' import { parseCard } from '@/math/statements' import { clusterStrokes, mockRecognizer, OCR_ACCEPT } from '@/ocr/recognizer' +import { ocrRuntime, ocrSupported } from '@/ocr/support' +import { InkDebugPanel } from '@/ink/InkDebugPanel' +import { inkFlagsStore, shouldShowDebugPanel } from '@/ink/flags' import { PlotButton } from '@/plot/PlotButton' import { PlotPanel } from '@/plot/PlotPanel' import { PlotPane } from '@/plot/PlotPane' @@ -135,6 +138,7 @@ export default function App() { const [confirmClear, setConfirmClear] = useState(false) const ocrGen = useRef(0) const ocrSettled = useRef(new Set()) + const compatNoted = useRef(false) const dragBase = useRef(null) const textareaRef = useRef(null) const sheetRef = useRef(null) @@ -286,12 +290,24 @@ export default function App() { [commitRecognized, docRef], ) + const noteCompat = useCallback(() => { + if (compatNoted.current) return + compatNoted.current = true + toast(t('ocrCompat')) + }, [t]) + const recognize = useCallback(() => { const pool = unmarkedInk(docRef) if (!pool.length) { toast(t('writeFirst')) return } + if (!ocrSupported()) { + toast(t('ocrUnsupported')) + return + } + // no WASM SIMD (WebKit before 16.4): the slower compat runtime reads it; say so once + if (ocrRuntime() === 'compat') noteCompat() const clusters = clusterStrokes(pool) if (!clusters.length) return document.documentElement.dataset.ocr = 'run' @@ -310,12 +326,18 @@ export default function App() { } }) } - }, [acceptInk, docRef, t]) + }, [acceptInk, docRef, noteCompat, t]) // Settled ink is read on its own. A confident reading is written onto the sheet and the // corner plot updates. Nothing is drawn over the paper while that happens. useEffect(() => { if (!prefs.autoOcr || composer.open) return + // The compat runtime takes seconds per formula on the main thread; reading after every pause + // would stall the pen. On those WebViews recognition is manual (Recognize / R). + if (ocrRuntime() === 'compat') { + noteCompat() + return + } const fresh = doc.strokes.filter((s) => !s.recognized && s.style !== 'marker') if (!fresh.length) { document.documentElement.dataset.ocr = 'idle' @@ -347,7 +369,7 @@ export default function App() { }) }, 900) return () => clearTimeout(t) - }, [doc.strokes, prefs.autoOcr, composer.open, acceptInk, docRef]) + }, [doc.strokes, prefs.autoOcr, composer.open, acceptInk, docRef, noteCompat]) const writeSample = (blocks: string[]) => { const placed = writeBlocks(blocks) @@ -470,6 +492,8 @@ export default function App() { const floated = plot.open && !plot.details && !plot.full const docked = plot.open && plot.details && !plot.full && !compact const modal = plot.open && (plot.full || (plot.details && compact)) + // ink debug panel: ?ink-debug=1 (or a dev build with any ink experiment on) — production never shows it + const inkDebugVisible = shouldShowDebugPanel(window.location.search, import.meta.env.DEV, inkFlagsStore.get()) return (
@@ -515,6 +539,8 @@ export default function App() { + {inkDebugVisible && } + (null) const lastErase = useRef<{ x: number; y: number } | null>(null) + // ink-feel experiment switches — all opt-in, off by default (see src/ink/flags.ts); + // live via the flags store so the debug panel can toggle them mid-stroke + const flags = useSyncExternalStore(inkFlagsStore.subscribe, inkFlagsStore.get) + const [predTail, setPredTail] = useState([]) + const samplesRef = useRef([]) + const pointerTypeRef = useRef('mouse') + const [wetPts, setWetPts] = useState(null) + const incSmoothRef = useRef(null) + const frameMsRef = useRef(ADAPTIVE_DEFAULT_FRAME_MS) const toWorld = useCallback((cx: number, cy: number) => { const r = ref.current!.getBoundingClientRect() @@ -73,9 +105,13 @@ export function Board(props: Props) { mode.current = null active.current = null pointers.current.clear() + samplesRef.current = [] + incSmoothRef.current = null if (!busy) return setLive(null) setErasing(new Set()) + setPredTail([]) + setWetPts(null) }, []) useEffect(() => { @@ -118,6 +154,56 @@ export function Board(props: Props) { return () => el.removeEventListener('wheel', onWheel) }, [setView]) + // Touch WebKit (iPad): pointer events fire first, then touch events. Cancelling the touches that + // became ink, erasing or a pinch stops iOS from synthesising click/dblclick (which opened the + // composer), starting a text selection, or showing the callout / loupe. Text fields keep theirs. + const toolRef = useRef(tool) + useLayoutEffect(() => { + toolRef.current = tool + }, [tool]) + useEffect(() => { + const el = ref.current! + const held = new Set() + const elementOf = (t: EventTarget | null) => (t instanceof Node && !(t instanceof Element) ? t.parentElement : t) + const onTouchStart = (e: TouchEvent) => { + if (!suppressBoardTouch(toolRef.current, mode.current?.kind ?? null, elementOf(e.target))) return + for (const t of Array.from(e.changedTouches)) held.add(t.identifier) + if (e.cancelable) e.preventDefault() + } + const onTouchMove = (e: TouchEvent) => { + if (!held.size) return + if (Array.from(e.changedTouches).some((t) => held.has(t.identifier)) && e.cancelable) e.preventDefault() + } + const onTouchEnd = (e: TouchEvent) => { + let mine = false + for (const t of Array.from(e.changedTouches)) mine = held.delete(t.identifier) || mine + if (mine && e.cancelable) e.preventDefault() + } + const onSelectStart = (e: Event) => { + if (blockBoardSelection(elementOf(e.target))) e.preventDefault() + } + // A stroke that wanders over the toolbar or a panel must not select it either. + const onDocSelectStart = (e: Event) => { + const kind = mode.current?.kind + if ((kind === 'draw' || kind === 'erase' || kind === 'pinch') && blockBoardSelection(elementOf(e.target))) e.preventDefault() + } + const opts = { passive: false } as const + el.addEventListener('touchstart', onTouchStart, opts) + el.addEventListener('touchmove', onTouchMove, opts) + el.addEventListener('touchend', onTouchEnd, opts) + el.addEventListener('touchcancel', onTouchEnd, opts) + el.addEventListener('selectstart', onSelectStart) + document.addEventListener('selectstart', onDocSelectStart) + return () => { + el.removeEventListener('touchstart', onTouchStart) + el.removeEventListener('touchmove', onTouchMove) + el.removeEventListener('touchend', onTouchEnd) + el.removeEventListener('touchcancel', onTouchEnd) + el.removeEventListener('selectstart', onSelectStart) + document.removeEventListener('selectstart', onDocSelectStart) + } + }, []) + // A gesture that is cancelled, loses capture, or is interrupted must not become ink. // Layout, not a passive effect: the tool button updates before this returns, and pointerup must already see an empty gesture. useLayoutEffect(() => { @@ -130,6 +216,22 @@ export function Board(props: Props) { return () => window.removeEventListener('blur', onBlur) }, [abortLive]) + // estimate the display refresh from rAF deltas so the prediction step/horizon + // can scale with the panel (only runs while the prediction experiment is on) + useEffect(() => { + if (!flags.prediction) return + let raf = 0 + let last = performance.now() + const loop = (t: number) => { + const d = t - last + last = t + if (d > 0 && d < 100) frameMsRef.current = frameMsRef.current * 0.8 + d * 0.2 + raf = requestAnimationFrame(loop) + } + raf = requestAnimationFrame(loop) + return () => cancelAnimationFrame(raf) + }, [flags.prediction]) + // a lone dot waits a moment before it is inked, so the two clicks of a double-click leave no marks const pendingDots = useRef<{ s: Stroke; t: ReturnType }[]>([]) const [dots, setDots] = useState([]) @@ -137,14 +239,29 @@ export function Board(props: Props) { const s = liveRef.current liveRef.current = null setLive(null) + samplesRef.current = [] + incSmoothRef.current = null + if (predTail.length) setPredTail([]) // predicted points are display-only, never saved + if (wetPts) setWetPts(null) if (!s || s.pts.length < 3) return - if (s.pts.length > 3) return props.onAddStroke(s) + let stroke = s + // pointer-tolerance experiment: a quick press whose whole gesture stays + // within the per-type drag threshold (÷ zoom) is a tap — collapse it to the + // pen-down point. Slow deliberate ticks keep their (short) stroke. + if (flags.pointerTolerance && stroke.pts.length > 3 && isTapStroke(stroke.pts, dragThresholdWorld(toPointerKind(pointerTypeRef.current), viewRef.current.scale), Date.now() - stroke.createdAt)) { + stroke = { ...stroke, pts: [stroke.pts[0], stroke.pts[1], stroke.pts[2]] } + } + // bake the midpoint-Bézier smoothing into the saved stroke (dots and + // two-point strokes come back unchanged from midpointBezierPolyline) + const smooth = flags.smoothing ? midpointBezierPolyline(stroke.pts) : stroke.pts + const final = smooth === stroke.pts ? stroke : { ...stroke, pts: smooth } + if (final.pts.length > 3) return props.onAddStroke(final) const t = setTimeout(() => { - pendingDots.current = pendingDots.current.filter((d) => d.s !== s) + pendingDots.current = pendingDots.current.filter((d) => d.s !== final) setDots(pendingDots.current.map((d) => d.s)) - props.onAddStroke(s) + props.onAddStroke(final) }, 320) - pendingDots.current.push({ s, t }) + pendingDots.current.push({ s: final, t }) setDots(pendingDots.current.map((d) => d.s)) } const dropDots = () => { @@ -161,9 +278,14 @@ export function Board(props: Props) { if (ids.length) props.onErase(ids) } + // eraser radius: main's eraserWorldRadius, or the per-pointer-type hit + // tolerance (DIP ÷ zoom) under the pointerTolerance experiment + const eraseRadius = () => + flags.pointerTolerance ? hitToleranceWorld(toPointerKind(pointerTypeRef.current), viewRef.current.scale) : eraserWorldRadius(viewRef.current.scale) + const eraseAt = (cx: number, cy: number) => { const w = toWorld(cx, cy) - const r = eraserWorldRadius(viewRef.current.scale) + const r = eraseRadius() const prev = lastErase.current lastErase.current = w let changed = false @@ -186,8 +308,65 @@ export function Board(props: Props) { } } + // capsule the eraser swept through since the previous position, so fast motion + // cannot skip over a stroke the point test would miss + const eraseSweep = (x0: number, y0: number, x1: number, y1: number) => { + const r = eraseRadius() + let changed = false + for (const s of doc.strokes) { + if (!erasingRef.current.has(s.id) && hitSweep(s, x0, y0, x1, y1, r)) { + erasingRef.current.add(s.id) + changed = true + } + } + if (changed) setErasing(new Set(erasingRef.current)) + } + + /** display-only extrapolated tail for the live stroke; never touches the stroke data */ + const updatePrediction = (e: React.PointerEvent, list: PointerEvent[]): number => { + const hist = samplesRef.current + for (const ev of list) { + const last = hist[hist.length - 1] + if (ev.timeStamp >= (last ? last.t : -Infinity)) hist.push({ x: ev.clientX, y: ev.clientY, t: ev.timeStamp }) + } + if (hist.length > PREDICTION_HISTORY_CAP) hist.splice(0, hist.length - PREDICTION_HISTORY_CAP) + const gate = gateSamples(hist) + let screen: { x: number; y: number }[] = [] + let source: InkDebugStats['predictedSource'] = 'off' + if (gate.predict) { + const native = nativePredictedTail(e.nativeEvent).map((p) => ({ x: p.clientX, y: p.clientY })) + if (native.length) { + screen = native + source = 'native' + } else { + // step/horizon scale with the display's frame interval (rAF estimate), + // absolute cap preserved inside predictTail + const adapt = frameAdaptivePrediction(frameMsRef.current) + const horizon = gate.verdict === 'curve' ? adapt.curveHorizonMs : adapt.horizonMs + screen = predictTail(hist, { horizonMs: horizon, stepMs: adapt.stepMs }).map((s) => ({ x: s.x, y: s.y })) + source = 'self' + } + } + inkDebugStats.predictedCount = screen.length + inkDebugStats.predictedSource = source + if (!screen.length || !liveRef.current) { + if (predTail.length) setPredTail([]) + return screen.length + } + const pressure = liveRef.current.pts[liveRef.current.pts.length - 1] ?? 0.5 + const flat: number[] = [] + for (const p of screen) { + const w = toWorld(p.x, p.y) + flat.push(w.x, w.y, pressure) + } + setPredTail(flat) + return screen.length + } + const onPointerDown = (e: React.PointerEvent) => { if ((e.target as HTMLElement).closest('[data-no-board]')) return + pointerTypeRef.current = e.pointerType + inkDebugStats.pointerType = e.pointerType if (e.pointerType === 'pen' && !penSeen.current) { penSeen.current = true props.onPenDetected() @@ -203,6 +382,9 @@ export function Board(props: Props) { erasingRef.current = new Set() setErasing(new Set()) lastErase.current = null + incSmoothRef.current = null + if (predTail.length) setPredTail([]) + if (wetPts) setWetPts(null) const [a, b] = touches pinch.current = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, view: viewRef.current } mode.current = { kind: 'pinch' } @@ -230,7 +412,8 @@ export function Board(props: Props) { capture(e) active.current = e.pointerId if (tool === 'eraser') { - mode.current = { kind: 'erase' } + const w = toWorld(e.clientX, e.clientY) + mode.current = { kind: 'erase', lx: w.x, ly: w.y } lastErase.current = null eraseAt(e.clientX, e.clientY) return @@ -246,6 +429,9 @@ export function Board(props: Props) { } liveRef.current = s setLive(s) + incSmoothRef.current = null + if (wetPts) setWetPts(null) + if (flags.prediction) samplesRef.current = [{ x: e.clientX, y: e.clientY, t: e.nativeEvent.timeStamp }] mode.current = { kind: 'draw' } } @@ -280,26 +466,50 @@ export function Board(props: Props) { return } if (m.kind === 'erase') { - const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : [] - const list = evs.length ? evs : [e.nativeEvent] - for (const ev of list) eraseAt(ev.clientX, ev.clientY) + if (flags.capsuleEraser) { + const w = toWorld(e.clientX, e.clientY) + eraseSweep(m.lx, m.ly, w.x, w.y) + m.lx = w.x + m.ly = w.y + } else { + const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : [] + const list = evs.length ? evs : [e.nativeEvent] + for (const ev of list) eraseAt(ev.clientX, ev.clientY) + } return } if (m.kind === 'draw' && liveRef.current) { + const t0 = performance.now() const evs = typeof e.nativeEvent.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : [] const list = evs.length ? evs : [e.nativeEvent] - const pts = liveRef.current.pts.slice() + // flags off → the exact main behaviour: looser 0.8 px near-point threshold, no prediction + const minDist = flags.smoothing ? SMOOTH_MIN_DIST_DIP : 0.8 + let pts = liveRef.current.pts.slice() for (const ev of list) { const w = toWorld(ev.clientX, ev.clientY) - const lx = pts[pts.length - 3] - const ly = pts[pts.length - 2] - if (Math.hypot(w.x - lx, w.y - ly) * viewRef.current.scale < 0.8) continue - pts.push(w.x, w.y, ev.pointerType === 'pen' ? ev.pressure || 0.5 : 0.5) + pts = appendStrokePoint(pts, { x: w.x, y: w.y, pressure: ev.pointerType === 'pen' ? ev.pressure || 0.5 : 0.5 }, minDist, viewRef.current.scale) } const next = { ...liveRef.current, pts } liveRef.current = next // A deferred pointermove must not resurrect a stroke that an interruption already dropped. setLive(() => (liveRef.current === next ? next : null)) + // wet-ink incremental redraw: extend the cached smooth polyline by the one + // newly-final segment instead of resampling the whole stroke per frame + if (flags.smoothing && flags.wetIncremental) { + const st = incSmoothRef.current ?? (incSmoothRef.current = createIncrementalSmooth()) + updateIncrementalSmooth(st, pts) + setWetPts(st.pts) + } else if (wetPts) { + setWetPts(null) + } + if (flags.prediction) updatePrediction(e, list) + else if (predTail.length) setPredTail([]) + // debug-panel bookkeeping (hidden unless ?ink-debug=1; no behaviour change) + inkDebugStats.nativePredicted = typeof e.nativeEvent.getPredictedEvents === 'function' + inkDebugStats.hasPressure = hasRealPressure(liveRef.current.pts) + inkDebugStats.strokePoints = liveRef.current.pts.length / 3 + inkDebugStats.handlerMs = performance.now() - t0 + inkDebugStats.lastMoveAt = t0 } } @@ -343,6 +553,21 @@ export function Board(props: Props) { } const drawing = tool === 'pen' || tool === 'marker' || tool === 'eraser' + // wet-ink display: smoothing and the predicted tail are overlays on the live + // stroke only — they never mutate liveRef, which is what gets saved + const PREDICTION_GHOST_OPACITY = 0.4 + const wetBase = live ? (flags.smoothing ? (flags.wetIncremental && wetPts ? wetPts : midpointBezierPolyline(live.pts)) : live.pts) : null + const liveDisplay = (() => { + if (!live || wetBase == null) return null + const merged = flags.prediction && predTail.length && !flags.predictionGhost + if (!merged) return wetBase === live.pts ? live : { ...live, pts: wetBase } + return { ...live, pts: [...wetBase, ...predTail] } + })() + // ghost tail: the prediction rendered as its own translucent path, starting at the stroke tip + const tailDisplay = (() => { + if (!live || wetBase == null || !flags.prediction || !flags.predictionGhost || !predTail.length) return null + return { ...live, pts: predictionTailPath(wetBase, predTail) } + })() const fingerSelects = penOnly || penSeen.current const passThrough = useCallback( (e: React.PointerEvent) => (drawing || space) && !(e.pointerType === 'touch' && fingerSelects), @@ -352,6 +577,9 @@ export function Board(props: Props) { const onDoubleClick = (e: React.MouseEvent) => { if ((e.target as HTMLElement).closest('[data-no-board]')) return + // iOS turns two quick taps or short marks (a dot, the bars of "=") into a dblclick. With an ink + // tool only a mouse double-click opens the composer; a pen or capacitive stylus (touch) never does. + if (ignoreBoardDoubleClick(tool, pointerTypeRef.current)) return dropDots() // pointer capture makes the board the click target even when the pointer is over a formula const hit = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-formula]') @@ -368,7 +596,7 @@ export function Board(props: Props) {
))} - + {doc.strokes.map((s) => ( @@ -413,7 +641,12 @@ export function Board(props: Props) { {dots.map((s) => ( ))} - {live && } + {liveDisplay && } + {tailDisplay && ( + + + + )}
diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index dd81e01..0c9c4e8 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -342,6 +342,8 @@ export const zh = { needView: '需要 x/y 范围、z、camera、mode、only/show/hide 或 fit', vocabBad: '词表格式不对', modelFiles: '手写模型文件缺失', + ocrUnsupported: '这台设备的 WebView 不支持 WebAssembly,手写识别不可用。笔迹照常可用。', + ocrCompat: '这台设备的 WebView 没有 WebAssembly SIMD(iOS 16.4 以前),识别改用兼容模式:结果相同,但每条公式要几秒。自动识别已暂停,点「识别」手动识别。', encoderEmpty: '编码器没有返回特征', decoderEmpty: '解码器没有返回 logits', parseFailed: '解析失败', @@ -694,6 +696,8 @@ export const en: { [K in MessageKey]: string } = { needView: 'Provide x/y ranges, z, camera, mode, only/show/hide, or fit', vocabBad: 'The vocabulary file is not in the expected shape', modelFiles: 'The handwriting model files are missing', + ocrUnsupported: 'This WebView has no WebAssembly, so handwriting recognition is unavailable. Ink still works.', + ocrCompat: 'This WebView has no WebAssembly SIMD (before iOS 16.4), so recognition runs in compatibility mode: same results, a few seconds per formula. Automatic reading is paused; tap Recognize to read ink.', encoderEmpty: 'The encoder returned no features', decoderEmpty: 'The decoder returned no logits', parseFailed: 'Could not parse', diff --git a/src/ink/InkDebugPanel.tsx b/src/ink/InkDebugPanel.tsx new file mode 100644 index 0000000..44374d3 --- /dev/null +++ b/src/ink/InkDebugPanel.tsx @@ -0,0 +1,87 @@ +import { useEffect, useState, useSyncExternalStore } from 'react' +import { inkDebugStats } from './debug' +import { inkFlagsStore, type InkFlags } from './flags' + +/** + * Opt-in debug panel for the ink-feel experiments — toggles the flags live and + * shows pointer/prediction/frame info. Never rendered unless + * `shouldShowDebugPanel()` says so: `?ink-debug=1`, or a dev build with any + * experiment switched on. Production without the parameter never sees it. + */ + +const SWITCHES: { key: keyof InkFlags; label: string }[] = [ + { key: 'smoothing', label: 'Smoothing (near-point drop + midpoint Bezier)' }, + { key: 'prediction', label: 'Prediction' }, + { key: 'predictionGhost', label: 'Prediction ghost tail' }, + { key: 'capsuleEraser', label: 'Swept capsule eraser' }, + { key: 'pointerTolerance', label: 'Per-pointer tolerance' }, + { key: 'wetIncremental', label: 'Incremental wet ink' }, +] + +const Row = ({ k, v }: { k: string; v: string }) => ( +
+ {k} + {v} +
+) + +export function InkDebugPanel() { + const flags = useSyncExternalStore(inkFlagsStore.subscribe, inkFlagsStore.get) + const [snap, setSnap] = useState(() => ({ ...inkDebugStats })) + const [frameMs, setFrameMs] = useState(0) + + useEffect(() => { + const poll = setInterval(() => setSnap({ ...inkDebugStats }), 250) + // frame interval measured on the panel's own rAF — same display pipeline as the board + let raf = 0 + let last = performance.now() + let acc = 0 + let n = 0 + const loop = (t: number) => { + acc += t - last + last = t + if (++n >= 30) { + setFrameMs(acc / n) + acc = 0 + n = 0 + } + raf = requestAnimationFrame(loop) + } + raf = requestAnimationFrame(loop) + return () => { + clearInterval(poll) + cancelAnimationFrame(raf) + } + }, []) + + return ( +
+
Ink experiments (?ink-debug=1)
+
+ {SWITCHES.map(({ key, label }) => ( + + ))} +
+
+ + + + + + 0 ? ` ≈ ${(1000 / frameMs).toFixed(0)} Hz` : ''}`} /> + +
+
+ ) +} diff --git a/src/ink/capsule.test.ts b/src/ink/capsule.test.ts new file mode 100644 index 0000000..995c1eb --- /dev/null +++ b/src/ink/capsule.test.ts @@ -0,0 +1,60 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { hitSweep, segSegDist2 } from './capsule' +import type { Stroke } from '@/board/types' + +const strokeOf = (pts: number[], width = 4, style: Stroke['style'] = 'ink'): Stroke => ({ + id: 's1', + pts, + color: '#000', + width, + style, + createdAt: 0, +}) + +test('capsule catches what the point test misses during fast motion', () => { + // a vertical stroke at x=100 (the same segment-distance rule the main eraser + // applies per pointer event, tested from the two event positions) + const stroke = strokeOf([100, 0, 0.5, 100, 200, 0.5]) + const r = 12 + const e1 = { x: 40, y: 50 } + const e2 = { x: 160, y: 50 } + // both pointer events sit 60 px away from the stroke → point tests miss + assert.ok(segSegDist2(e1, e1, { x: 100, y: 0 }, { x: 100, y: 200 }) > r * r) + assert.ok(segSegDist2(e2, e2, { x: 100, y: 0 }, { x: 100, y: 200 }) > r * r) + // the swept capsule between them crosses the stroke → hit + assert.equal(hitSweep(stroke, e1.x, e1.y, e2.x, e2.y, r), true) +}) + +test('capsule degenerates to a disc for a stationary eraser', () => { + const stroke = strokeOf([0, 0, 0.5, 50, 0, 0.5]) + // tip 13 px above the line: radius 12 (+3.2 width pad → 15.2) → hit; radius 8 (+3.2 → 11.2) → miss + assert.equal(hitSweep(stroke, 25, 13, 25, 13, 12), true) + assert.equal(hitSweep(stroke, 25, 13, 25, 13, 8), false) +}) + +test('capsule keeps the same width padding as hitStroke', () => { + // vertical stroke at x=100, radius 12 → ink pad = 4*0.8 = 3.2 → reach 15.2 + const ink = strokeOf([100, 0, 0.5, 100, 100, 0.5], 4, 'ink') + assert.equal(hitSweep(ink, 85, 10, 85, 90, 12), true) // 15 ≤ 15.2 + assert.equal(hitSweep(ink, 84, 10, 84, 90, 12), false) // 16 > 15.2 + // marker pad = 10*2.5 = 25 → reach 37 + const marker = strokeOf([100, 0, 0.5, 100, 100, 0.5], 10, 'marker') + assert.equal(hitSweep(marker, 64, 10, 64, 90, 12), true) // 36 ≤ 37 + assert.equal(hitSweep(marker, 62, 10, 62, 90, 12), false) // 38 > 37 +}) + +test('capsule hits single-point strokes and later segments', () => { + const dot = strokeOf([500, 500, 0.5]) + assert.equal(hitSweep(dot, 495, 495, 494, 494, 12), true) + const multi = strokeOf([0, 0, 0.5, 30, 30, 0.5, 60, 0, 0.5]) + // sweep passing only over the second segment + assert.equal(hitSweep(multi, 40, 5, 50, 5, 12), true) + // well below the V shape → no segment within reach (width 4 → reach 9.2) + assert.equal(hitSweep(multi, 45, 40, 55, 40, 6), false) +}) + +test('capsule: empty stroke never hits', () => { + assert.equal(hitSweep(strokeOf([]), 0, 0, 50, 50, 12), false) +}) diff --git a/src/ink/capsule.ts b/src/ink/capsule.ts new file mode 100644 index 0000000..bbc4e7a --- /dev/null +++ b/src/ink/capsule.ts @@ -0,0 +1,82 @@ +/** + * Swept-capsule eraser hit testing — pure functions. + * + * Idea learned from studying established whiteboards (not their code): test the + * capsule the eraser swept through since the previous pointer position, not just + * the point it sits on now, so fast motion cannot skip over a stroke. + */ +import type { Stroke } from '@/board/types' + +export interface Pt { + x: number + y: number +} + +const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v) + +/** Squared distance between segments p1p2 and q1q2; degenerate segments count as points. */ +export function segSegDist2(p1: Pt, p2: Pt, q1: Pt, q2: Pt): number { + const d1x = p2.x - p1.x + const d1y = p2.y - p1.y + const d2x = q2.x - q1.x + const d2y = q2.y - q1.y + const rx = p1.x - q1.x + const ry = p1.y - q1.y + const a = d1x * d1x + d1y * d1y + const e = d2x * d2x + d2y * d2y + const f = d2x * rx + d2y * ry + let s: number + let t: number + if (a <= 1e-12 && e <= 1e-12) { + s = 0 + t = 0 + } else if (a <= 1e-12) { + s = 0 + t = clamp01(f / e) + } else { + const c = d1x * rx + d1y * ry + if (e <= 1e-12) { + t = 0 + s = clamp01(-c / a) + } else { + const b = d1x * d2x + d1y * d2y + const denom = a * e - b * b + s = denom > 1e-12 ? clamp01((b * f - c * e) / denom) : 0 + t = (b * s + f) / e + if (t < 0) { + t = 0 + s = clamp01(-c / a) + } else if (t > 1) { + t = 1 + s = clamp01((b - c) / a) + } + } + } + const cx = p1.x + s * d1x - (q1.x + t * d2x) + const cy = p1.y + s * d1y - (q1.y + t * d2y) + return cx * cx + cy * cy +} + +/** Same width padding rule as hitStroke() in board/strokes.tsx. */ +const sweepPad = (s: Stroke) => s.width * (s.style === 'marker' || s.style === 'washi' ? 2.5 : 0.8) + +/** + * Does the capsule swept from (x0,y0) to (x1,y1) with radius r touch the stroke? + * A stationary test (x0==x1, y0==y1) degenerates to the usual disc check. + */ +export function hitSweep(s: Stroke, x0: number, y0: number, x1: number, y1: number, r: number): boolean { + const rr = r + sweepPad(s) + const r2 = rr * rr + const p = s.pts + const n = p.length / 3 + if (n === 0) return false + const a1: Pt = { x: x0, y: y0 } + const a2: Pt = { x: x1, y: y1 } + if (n === 1) return segSegDist2(a1, a2, { x: p[0], y: p[1] }, { x: p[0], y: p[1] }) <= r2 + for (let i = 0; i < n - 1; i++) { + const b1: Pt = { x: p[i * 3], y: p[i * 3 + 1] } + const b2: Pt = { x: p[(i + 1) * 3], y: p[(i + 1) * 3 + 1] } + if (segSegDist2(a1, a2, b1, b2) <= r2) return true + } + return false +} diff --git a/src/ink/debug.ts b/src/ink/debug.ts new file mode 100644 index 0000000..24b315c --- /dev/null +++ b/src/ink/debug.ts @@ -0,0 +1,33 @@ +/** + * Shared scratchpad the Board writes and the (opt-in) ink debug panel reads. + * Deliberately a plain mutable object — the panel polls it, so pointer-move + * handling never triggers extra React renders for debug bookkeeping. + */ +export interface InkDebugStats { + /** pointerType of the last board pointer event */ + pointerType: string + /** does the current stroke carry any real pressure (vs constant 0.5/0) */ + hasPressure: boolean + /** is PointerEvent.getPredictedEvents available in this browser */ + nativePredicted: boolean + /** predicted points shown for the last move, and where they came from */ + predictedCount: number + predictedSource: 'off' | 'native' | 'self' + /** Board pointer-move handling cost for the last draw move (ms) */ + handlerMs: number + /** samples in the live stroke */ + strokePoints: number + /** performance.now() of the last recorded move */ + lastMoveAt: number +} + +export const inkDebugStats: InkDebugStats = { + pointerType: '', + hasPressure: false, + nativePredicted: false, + predictedCount: 0, + predictedSource: 'off', + handlerMs: 0, + strokePoints: 0, + lastMoveAt: 0, +} diff --git a/src/ink/flags.test.ts b/src/ink/flags.test.ts new file mode 100644 index 0000000..4ffc37e --- /dev/null +++ b/src/ink/flags.test.ts @@ -0,0 +1,94 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { parseInkFlags, DEFAULT_INK_FLAGS, INK_FLAGS_STORAGE_KEY, createInkFlagsStore, shouldShowDebugPanel, type InkFlags } from './flags' + +const ALL_OFF: InkFlags = { + smoothing: false, + prediction: false, + predictionGhost: false, + capsuleEraser: false, + pointerTolerance: false, + wetIncremental: false, +} + +test('flags: defaults are all off', () => { + assert.deepEqual(parseInkFlags('', null), ALL_OFF) + assert.deepEqual(DEFAULT_INK_FLAGS, ALL_OFF) +}) + +test('flags: persisted JSON (partial) is honoured', () => { + const stored = JSON.stringify({ smoothing: true }) + assert.deepEqual(parseInkFlags('', stored), { ...ALL_OFF, smoothing: true }) +}) + +test('flags: URL params override the store; 0/false clears', () => { + const stored = JSON.stringify({ smoothing: true, prediction: true }) + assert.deepEqual(parseInkFlags('?ink-smooth=0&ink-capsule=1', stored), { ...ALL_OFF, prediction: true, capsuleEraser: true }) + assert.deepEqual(parseInkFlags('?ink-predict=1&ink-tolerance=1&ink-ghost=1&ink-wet-inc=1', null), { + ...ALL_OFF, + prediction: true, + pointerTolerance: true, + predictionGhost: true, + wetIncremental: true, + }) + assert.equal(parseInkFlags('?ink-smooth=false', null).smoothing, false) +}) + +test('flags: broken store falls back to defaults, URL still applies', () => { + assert.deepEqual(parseInkFlags('?ink-smooth=1', '{oops'), { ...ALL_OFF, smoothing: true }) +}) + +test('flags: unknown keys and junk values are ignored', () => { + const stored = JSON.stringify({ smoothing: true, evil: 'x', prediction: 'yes' }) + assert.deepEqual(parseInkFlags('', stored), { ...ALL_OFF, smoothing: true }) +}) + +test('flags: the storage key is stable', () => { + assert.equal(INK_FLAGS_STORAGE_KEY, 'mathscrap.ink-flags.v1') +}) + +test('flags store: get is stable, set merges + notifies + persists', () => { + let persisted: InkFlags | null = null + const store = createInkFlagsStore({ ...ALL_OFF }, (f) => (persisted = { ...f })) + const a = store.get() + assert.deepEqual(a, ALL_OFF) + assert.equal(store.get(), a) // stable identity between sets (useSyncExternalStore-safe) + + let notified = 0 + const unsub = store.subscribe(() => notified++) + store.set({ smoothing: true }) + assert.equal(notified, 1) + assert.deepEqual(store.get(), { ...ALL_OFF, smoothing: true }) + assert.notEqual(store.get(), a) // new identity after set + assert.deepEqual(persisted, store.get()) + + store.set({ prediction: true, smoothing: false }) + assert.equal(notified, 2) + assert.deepEqual(store.get(), { ...ALL_OFF, prediction: true }) + + unsub() + store.set({ capsuleEraser: true }) + assert.equal(notified, 2) // no notification after unsubscribe + assert.equal(store.get().capsuleEraser, true) +}) + +test('flags store: persist throwing is swallowed', () => { + const store = createInkFlagsStore( + { ...ALL_OFF }, + () => { + throw new Error('no storage') + }, + ) + assert.doesNotThrow(() => store.set({ smoothing: true })) + assert.equal(store.get().smoothing, true) +}) + +test('debug panel gating: explicit param wins, otherwise dev + any flag on', () => { + const on = { ...ALL_OFF, smoothing: true } + assert.equal(shouldShowDebugPanel('?ink-debug=1', false, ALL_OFF), true) // explicit param even in prod + assert.equal(shouldShowDebugPanel('?ink-debug=0', true, on), false) // explicit hide wins + assert.equal(shouldShowDebugPanel('', true, on), true) // dev + experiment on + assert.equal(shouldShowDebugPanel('', true, ALL_OFF), false) // dev but nothing on + assert.equal(shouldShowDebugPanel('', false, on), false) // prod without param +}) diff --git a/src/ink/flags.ts b/src/ink/flags.ts new file mode 100644 index 0000000..676584c --- /dev/null +++ b/src/ink/flags.ts @@ -0,0 +1,124 @@ +/** + * Experiment switches for the ink-feel prototype (prediction + smoothing + capsule eraser). + * Everything here is opt-in: with the flags off the board behaves exactly like main. + * + * Learnings are borrowed as *ideas* from studying how established whiteboard apps + * feel (Seewo-style tolerances, midpoint Bézier smoothing, short-horizon gated + * prediction) — no third-party code or resources were copied. + */ + +export interface InkFlags { + /** near-point dedupe (0.5 DIP) + midpoint quadratic-Bézier smoothing of saved strokes */ + smoothing: boolean + /** live predicted-tail display while drawing (display-only, never persisted) */ + prediction: boolean + /** render the predicted tail as its own translucent ghost path instead of merging it into the ink (needs prediction) */ + predictionGhost: boolean + /** swept-capsule eraser hit testing (catches strokes skipped during fast motion) */ + capsuleEraser: boolean + /** per-pointer-type drag thresholds and eraser hit tolerances (mouse/touch/pen, DIP ÷ zoom) */ + pointerTolerance: boolean + /** wet ink draws from an incremental segment cache instead of resampling the whole stroke per frame (needs smoothing) */ + wetIncremental: boolean +} + +export const DEFAULT_INK_FLAGS: InkFlags = { + smoothing: false, + prediction: false, + predictionGhost: false, + capsuleEraser: false, + pointerTolerance: false, + wetIncremental: false, +} + +export const INK_FLAGS_STORAGE_KEY = 'mathscrap.ink-flags.v1' + +/** URL param per flag, e.g. `?ink-smooth=1&ink-predict=1&ink-ghost=1` (0/false clears). */ +const PARAMS: Record = { + smoothing: 'ink-smooth', + prediction: 'ink-predict', + predictionGhost: 'ink-ghost', + capsuleEraser: 'ink-capsule', + pointerTolerance: 'ink-tolerance', + wetIncremental: 'ink-wet-inc', +} + +const parseParam = (v: string | null): boolean | undefined => + v == null || v === '' ? undefined : !(v === '0' || v === 'false' || v === 'off') + +/** Pure: defaults ← persisted JSON ← URL params. Bad input quietly falls back. */ +export function parseInkFlags(search: string, stored: string | null): InkFlags { + const flags: InkFlags = { ...DEFAULT_INK_FLAGS } + if (stored) { + try { + const obj = JSON.parse(stored) as Record + for (const k of Object.keys(PARAMS) as (keyof InkFlags)[]) if (typeof obj[k] === 'boolean') flags[k] = obj[k] as boolean + } catch { + // unparseable store → keep defaults, URL overrides still apply + } + } + const qs = new URLSearchParams(search) + for (const k of Object.keys(PARAMS) as (keyof InkFlags)[]) { + const v = parseParam(qs.get(PARAMS[k])) + if (v !== undefined) flags[k] = v + } + return flags +} + +/** Browser loader (safe when localStorage/location are unavailable). */ +export function loadInkFlags(): InkFlags { + try { + const stored = typeof localStorage !== 'undefined' ? localStorage.getItem(INK_FLAGS_STORAGE_KEY) : null + const search = typeof location !== 'undefined' ? location.search : '' + return parseInkFlags(search, stored) + } catch { + return { ...DEFAULT_INK_FLAGS } + } +} + +export interface InkFlagsStore { + /** stable snapshot object (identity changes only on set) — useSyncExternalStore-safe */ + get: () => InkFlags + /** merge a patch, persist (best-effort) and notify subscribers */ + set: (patch: Partial) => void + subscribe: (listener: () => void) => () => void +} + +export function createInkFlagsStore(initial: InkFlags, persist?: (flags: InkFlags) => void): InkFlagsStore { + let current = { ...initial } + const listeners = new Set<() => void>() + return { + get: () => current, + set: (patch) => { + current = { ...current, ...patch } + try { + persist?.(current) + } catch { + // persistence is best-effort; flags stay in memory + } + listeners.forEach((l) => l()) + }, + subscribe: (l) => { + listeners.add(l) + return () => { + listeners.delete(l) + } + }, + } +} + +const persistFlags = (flags: InkFlags) => { + if (typeof localStorage !== 'undefined') localStorage.setItem(INK_FLAGS_STORAGE_KEY, JSON.stringify(flags)) +} + +/** Module-level store: seeded from localStorage + URL, live-toggled by the debug panel. */ +export const inkFlagsStore = createInkFlagsStore(loadInkFlags(), persistFlags) + +export const DEBUG_PANEL_PARAM = 'ink-debug' + +/** Show the ink debug panel: `?ink-debug=1` forces it on (`=0` hides), else dev builds with any experiment on. */ +export function shouldShowDebugPanel(search: string, isDev: boolean, flags: InkFlags): boolean { + const v = parseParam(new URLSearchParams(search).get(DEBUG_PANEL_PARAM)) + if (v !== undefined) return v + return isDev && Object.values(flags).some(Boolean) +} diff --git a/src/ink/inputGuard.test.ts b/src/ink/inputGuard.test.ts new file mode 100644 index 0000000..a734fc6 --- /dev/null +++ b/src/ink/inputGuard.test.ts @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { blockBoardSelection, ignoreBoardDoubleClick, isEditableTarget, isInteractiveTarget, suppressBoardTouch } from './inputGuard' + +/** Minimal `closest`: the element "matches" when any of its tags appears in the selector list. */ +function el(...tags: string[]) { + return { + closest(selector: string) { + const parts = selector.split(',').map((s) => s.trim()) + return tags.some((tag) => parts.includes(tag)) ? {} : null + }, + } +} + +const paper = el('div') +const textarea = el('textarea') +const button = el('button') +const noBoard = el('[data-no-board]') +const editable = el('[contenteditable="true"]') + +test('pen / touch double-tap in ink tools never opens the composer; mouse still does', () => { + for (const tool of ['pen', 'marker', 'eraser'] as const) { + assert.equal(ignoreBoardDoubleClick(tool, 'touch'), true, `${tool} touch (capacitive stylus)`) + assert.equal(ignoreBoardDoubleClick(tool, 'pen'), true, `${tool} pen`) + assert.equal(ignoreBoardDoubleClick(tool, null), true, `${tool} unknown pointer`) + assert.equal(ignoreBoardDoubleClick(tool, 'mouse'), false, `${tool} mouse keeps desktop double-click`) + } + assert.equal(ignoreBoardDoubleClick('type', 'touch'), false, 'the type tool is an explicit choice') + assert.equal(ignoreBoardDoubleClick('select', 'pen'), false) +}) + +test('board touches that draw, erase or pinch cancel the browser default; controls keep it', () => { + assert.equal(suppressBoardTouch('pen', 'draw', paper), true) + assert.equal(suppressBoardTouch('eraser', 'erase', paper), true) + assert.equal(suppressBoardTouch('select', 'pinch', paper), true) + assert.equal(suppressBoardTouch('pen', 'pan', paper), true, 'palm rejection in an ink tool still blocks selection') + assert.equal(suppressBoardTouch('pen', null, paper), true) + assert.equal(suppressBoardTouch('select', 'pan', paper), false, 'select tool keeps taps for cards') + assert.equal(suppressBoardTouch('type', 'pan', paper), false) + for (const target of [textarea, button, noBoard, editable]) assert.equal(suppressBoardTouch('pen', 'draw', target), false) +}) + +test('selection starts only in text fields', () => { + assert.equal(blockBoardSelection(paper), true) + assert.equal(blockBoardSelection(null), true) + assert.equal(blockBoardSelection(textarea), false) + assert.equal(blockBoardSelection(editable), false) + assert.equal(isEditableTarget(button), false) + assert.equal(isInteractiveTarget(button), true) + assert.equal(isInteractiveTarget({}), false, 'non-elements (text nodes, window) are not controls') +}) diff --git a/src/ink/inputGuard.ts b/src/ink/inputGuard.ts new file mode 100644 index 0000000..1299ac9 --- /dev/null +++ b/src/ink/inputGuard.ts @@ -0,0 +1,68 @@ +/** + * Keep pen and finger strokes from turning into browser gestures on touch WebKit (iPad). + * + * iOS synthesises `click` / `dblclick` after a short, still touch, and starts text selection or the + * callout on a long press. On the board, two quick taps or short marks (a dot, the bars of "=") + * became a `dblclick`, which opened the formula composer while the pen was selected, and a held + * stroke selected page text. A capacitive stylus reports `pointerType: 'touch'`, not `'pen'`. + * + * Rules: + * - In ink tools (pen / marker / eraser) only a mouse double-click opens the composer. Pen and + * touch never do; the type tool, the toolbar button and keyboard shortcuts still do. + * - Touches the board turns into ink, erasing or pinch are `preventDefault`ed, which stops click + * synthesis, selection, the callout and the loupe. Real controls and text fields are left alone. + */ +import type { Tool } from '../board/types' + +export const INK_TOOLS: ReadonlySet = new Set(['pen', 'marker', 'eraser']) + +export function isInkTool(tool: Tool): boolean { + return INK_TOOLS.has(tool) +} + +interface Closest { + closest?: (selector: string) => unknown +} + +const EDITABLE = 'input, textarea, select, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]' +const INTERACTIVE = `${EDITABLE}, button, a[href], [role="button"], [data-no-board]` + +function matches(target: unknown, selector: string): boolean { + const el = target as Closest | null + if (!el || typeof el.closest !== 'function') return false + try { + return el.closest(selector) != null + } catch { + return false + } +} + +/** A text field (or inside one) where selection and the keyboard must keep working. */ +export function isEditableTarget(target: unknown): boolean { + return matches(target, EDITABLE) +} + +/** A control that needs its own click: buttons, links, fields, anything marked `data-no-board`. */ +export function isInteractiveTarget(target: unknown): boolean { + return matches(target, INTERACTIVE) +} + +/** Board `dblclick`: true when it must not open or edit a formula. */ +export function ignoreBoardDoubleClick(tool: Tool, lastPointerType: string | null): boolean { + if (!isInkTool(tool)) return false + return lastPointerType !== 'mouse' +} + +export type BoardModeKind = 'draw' | 'erase' | 'pan' | 'pinch' | null + +/** Native `touchstart` on the board: true when its default (click, selection, callout) must be cancelled. */ +export function suppressBoardTouch(tool: Tool, mode: BoardModeKind, target: unknown): boolean { + if (isInteractiveTarget(target)) return false + if (mode === 'draw' || mode === 'erase' || mode === 'pinch') return true + return isInkTool(tool) +} + +/** `selectstart` on the board: only text fields may start a selection. */ +export function blockBoardSelection(target: unknown): boolean { + return !isEditableTarget(target) +} diff --git a/src/ink/integration.test.ts b/src/ink/integration.test.ts new file mode 100644 index 0000000..e97d75e --- /dev/null +++ b/src/ink/integration.test.ts @@ -0,0 +1,49 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { appendStrokePoint, midpointBezierPolyline } from './smooth' +import { gateSamples, predictTail } from './predict' + +/** + * Board-level contract, exercised through the pure modules the Board calls: + * predicted points only ever flow through the display path + * ([...smoothedRealPts, ...predTail]); the saved stroke is built exclusively + * from real samples via appendStrokePoint + the finish-time bake, so no + * predicted coordinate can ever enter stroke data. + */ +test('predicted points never enter the saved stroke', () => { + // a quick straight stroke: real pointer/coalesced samples + const real: { x: number; y: number; t: number }[] = [] + for (let i = 0; i < 12; i++) real.push({ x: 10 + i * 5.8, y: 20 + i * 1.2, t: 1000 + i * 8 }) + + // capture: only real samples are appended (this is the only stroke-mutating call in Board) + let strokePts: number[] = [] + for (const s of real) strokePts = appendStrokePoint(strokePts, { x: s.x, y: s.y, pressure: 0.5 }, 0.5, 1) + + // prediction: gate + tail from the same real history + const gate = gateSamples(real) + assert.equal(gate.predict, true) + const tail = predictTail(real, { horizonMs: gate.horizonMs }) + assert.ok(tail.length > 0) + // the tail lives beyond the last real sample + const last = real[real.length - 1] + assert.ok(Math.hypot(tail[tail.length - 1].x - last.x, tail[tail.length - 1].y - last.y) > 0) + + // what the renderer shows this frame (display path)… + const displayPts = [...midpointBezierPolyline(strokePts), ...tail.flatMap((p) => [p.x, p.y, 0.5])] + // …vs what finishStroke saves (the bake sees only the real capture) + const saved = midpointBezierPolyline(strokePts) + assert.deepEqual(saved, midpointBezierPolyline(strokePts)) + assert.equal(displayPts.length, saved.length + tail.length * 3) + // the saved data contains none of the predicted coordinates + const triples: number[][] = [] + for (let i = 0; i < saved.length; i += 3) triples.push([saved[i], saved[i + 1]]) + for (const p of tail) { + assert.ok( + !triples.some(([x, y]) => Math.abs(x - p.x) < 1e-9 && Math.abs(y - p.y) < 1e-9), + `predicted point ${p.x},${p.y} leaked into saved stroke`, + ) + } + // and the bake is a pure function of the real capture alone + assert.equal(saved.length, (1 + (strokePts.length / 3 - 2) * 6 + 1) * 3) +}) diff --git a/src/ink/predict.test.ts b/src/ink/predict.test.ts new file mode 100644 index 0000000..2d244ae --- /dev/null +++ b/src/ink/predict.test.ts @@ -0,0 +1,193 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { + ADAPTIVE_MAX_STEP_MS, + ADAPTIVE_MIN_STEP_MS, + DEFAULT_GATE_OPTIONS, + frameAdaptivePrediction, + gateSamples, + kfInit, + kfPredict, + kfUpdate, + nativePredictedTail, + predictionTailPath, + predictTail, + PREDICTION_MAX_HORIZON_MS, + type InkSample, +} from './predict' + +/** straight drag to the right at constant speed */ +const straight = (n = 8, dt = 8, speed = 0.6): InkSample[] => + Array.from({ length: n }, (_, i) => ({ x: 100 + i * speed * dt, y: 200, t: 1000 + i * dt })) + +test('gate: steady straight stroke predicts with the full horizon', () => { + const g = gateSamples(straight()) + assert.equal(g.verdict, 'straight') + assert.equal(g.predict, true) + assert.equal(g.horizonMs, DEFAULT_GATE_OPTIONS.straightHorizonMs) +}) + +test('gate: gentle curve predicts with a shorter horizon', () => { + // heading rotates ~15° per step at constant speed (above curveTurnDeg=12, well below sharp=65) + const samples: InkSample[] = [] + let x = 0 + let y = 0 + let heading = 0 + for (let i = 0; i < 8; i++) { + samples.push({ x, y, t: 1000 + i * 8 }) + heading += (15 * Math.PI) / 180 + x += Math.cos(heading) * 4.8 + y += Math.sin(heading) * 4.8 + } + const g = gateSamples(samples) + assert.equal(g.verdict, 'curve') + assert.equal(g.predict, true) + assert.equal(g.horizonMs, DEFAULT_GATE_OPTIONS.curveHorizonMs) + assert.ok(g.horizonMs < DEFAULT_GATE_OPTIONS.straightHorizonMs) +}) + +test('gate: sharp turn disables prediction', () => { + const samples: InkSample[] = [] + for (let i = 0; i < 6; i++) samples.push({ x: i * 5, y: 0, t: 1000 + i * 8 }) + for (let i = 0; i < 3; i++) samples.push({ x: 25, y: i * 5, t: 1024 + i * 8 }) // hard 90° turn + const g = gateSamples(samples) + assert.equal(g.verdict, 'sharp') + assert.equal(g.predict, false) + assert.equal(g.horizonMs, 0) +}) + +test('gate: jitter (zig-zag waveform) disables prediction', () => { + // gentle zig-zag: ~53° alternating turns → not a single "sharp" turn, but oscillation + const samples: InkSample[] = [] + for (let i = 0; i < 10; i++) samples.push({ x: i * 4, y: i % 2 === 0 ? 0 : 2, t: 1000 + i * 8 }) + const g = gateSamples(samples) + assert.equal(g.verdict, 'jitter') + assert.equal(g.predict, false) +}) + +test('gate: parked pen (idle) and too-few samples do not predict', () => { + assert.equal(gateSamples([{ x: 1, y: 2, t: 0 }, { x: 1.001, y: 2, t: 8 }]).verdict, 'idle') + assert.equal(gateSamples([{ x: 1, y: 2, t: 0 }]).verdict, 'sparse') + assert.equal(gateSamples([]).verdict, 'sparse') + const idle = gateSamples([{ x: 1, y: 2, t: 0 }, { x: 1.001, y: 2, t: 8 }]) + assert.equal(idle.predict, false) +}) + +test('gate: pure — input samples are never mutated', () => { + const frozen = Object.freeze(straight().map(Object.freeze)) as readonly InkSample[] + assert.doesNotThrow(() => gateSamples(frozen as InkSample[])) +}) + +test('predictTail: constant velocity is extrapolated within tolerance', () => { + const samples = straight(20, 8, 0.6) // 0.6 px/ms ≈ 600 px/s + const tail = predictTail(samples, { horizonMs: 33, stepMs: 11 }) + assert.equal(tail.length, 3) + const last = samples[samples.length - 1] + const expected = last.x + 0.6 * 33 + assert.ok(Math.abs(tail[2].x - expected) / expected < 0.15, `got ${tail[2].x}, want ≈ ${expected}`) + // y barely moves → prediction stays put + assert.ok(Math.abs(tail[2].y - last.y) < 3) + assert.equal(tail[2].t, last.t + 33) +}) + +test('predictTail: horizon is capped at 36 ms and input stays untouched', () => { + const samples = straight() + const snapshot = JSON.stringify(samples) + const tail = predictTail(samples, { horizonMs: 500, stepMs: 11 }) + assert.ok(tail.length > 0) + const last = samples[samples.length - 1] + assert.ok(tail[tail.length - 1].t - last.t <= PREDICTION_MAX_HORIZON_MS + 1e-9) + assert.equal(JSON.stringify(samples), snapshot) +}) + +test('predictTail: degenerate inputs return an empty tail', () => { + assert.deepEqual(predictTail([]), []) + assert.deepEqual(predictTail([{ x: 1, y: 1, t: 5 }]), []) + assert.deepEqual(predictTail([{ x: 1, y: 1, t: 5 }, { x: 2, y: 1, t: 5 }]), []) // no time span +}) + +test('KF converges on constant velocity input', () => { + let k = kfInit(0) + for (let i = 1; i <= 20; i++) k = kfUpdate(kfPredict(k, 8), i * 0.6 * 8) + assert.ok(Math.abs(k.v - 600) / 600 < 0.1, `velocity estimate ${k.v}`) +}) + +test('nativePredictedTail: prefers the browser, falls back cleanly', () => { + const provider = { + getPredictedEvents: () => [ + { clientX: 1, clientY: 2, pressure: 0.5 }, + { clientX: 3, clientY: 4, pressure: 0.5 }, + ], + } + const tail = nativePredictedTail(provider) + assert.deepEqual(tail, [{ clientX: 1, clientY: 2 }, { clientX: 3, clientY: 4 }]) + // missing API → empty (caller uses the self-extrapolation fallback) + assert.deepEqual(nativePredictedTail({}), []) + assert.deepEqual(nativePredictedTail({ getPredictedEvents: () => [] }), []) + // throws → empty + assert.deepEqual( + nativePredictedTail({ + getPredictedEvents: () => { + throw new Error('boom') + }, + }), + [], + ) + // capped + const many = nativePredictedTail({ + getPredictedEvents: () => Array.from({ length: 9 }, (_, i) => ({ clientX: i, clientY: i })), + }) + assert.equal(many.length, 4) +}) + +test('frameAdaptivePrediction: scales with the refresh rate, caps preserved', () => { + const a60 = frameAdaptivePrediction(16.7) + const a120 = frameAdaptivePrediction(8.3) + const a144 = frameAdaptivePrediction(6.9) + // ~2 frames ahead on a straight verdict, half of that on curves + assert.ok(Math.abs(a60.horizonMs - 33.4) < 0.01) + assert.ok(Math.abs(a60.stepMs - 8.35) < 0.01) + assert.ok(Math.abs(a60.curveHorizonMs - a60.horizonMs / 2) < 0.01) + // higher refresh → finer step and shorter tail + assert.ok(a120.stepMs < a60.stepMs) + assert.ok(a120.horizonMs < a60.horizonMs) + assert.ok(a144.stepMs < a120.stepMs) + assert.ok(a144.horizonMs < a120.horizonMs) + for (const a of [a60, a120, a144]) { + assert.ok(a.horizonMs <= PREDICTION_MAX_HORIZON_MS + 1e-9, 'absolute horizon cap') + assert.ok(a.stepMs >= ADAPTIVE_MIN_STEP_MS && a.stepMs <= ADAPTIVE_MAX_STEP_MS) + assert.ok(a.curveHorizonMs <= a.horizonMs + 1e-9) + } +}) + +test('frameAdaptivePrediction: degenerate intervals clamp into range', () => { + for (const f of [0, -5, NaN, Infinity, 500]) { + const a = frameAdaptivePrediction(f) + assert.ok(a.stepMs >= ADAPTIVE_MIN_STEP_MS && a.stepMs <= ADAPTIVE_MAX_STEP_MS) + assert.ok(a.horizonMs >= a.stepMs) + assert.ok(a.horizonMs <= PREDICTION_MAX_HORIZON_MS) + } + // at the clamps: a very slow / very fast panel still yields sane numbers + const slow = frameAdaptivePrediction(40) + assert.equal(slow.stepMs, ADAPTIVE_MAX_STEP_MS) + assert.equal(slow.horizonMs, PREDICTION_MAX_HORIZON_MS) + const fast = frameAdaptivePrediction(2) + assert.equal(fast.stepMs, ADAPTIVE_MIN_STEP_MS) + assert.equal(fast.horizonMs, 8) +}) + +test('predictionTailPath: ghost path starts at the stroke tip, inputs untouched', () => { + const base = [0, 0, 0.5, 10, 0, 0.5, 20, 0, 0.5] + const tail = [30, 0, 0.5, 40, 0, 0.5] + const snapshot = JSON.stringify({ base, tail }) + const path = predictionTailPath(base, tail) + assert.equal(path.length, 3 + tail.length) + assert.deepEqual(path.slice(0, 3), [20, 0, 0.5]) // last smoothed point === real stroke tip + assert.deepEqual(path.slice(3), tail) + assert.equal(JSON.stringify({ base, tail }), snapshot) + // degenerate base (no full triple yet): tail alone + assert.deepEqual(predictionTailPath([], tail), tail) + // a single full triple IS a valid tip + assert.deepEqual(predictionTailPath([1, 2, 0.5], tail), [1, 2, 0.5, ...tail]) +}) diff --git a/src/ink/predict.ts b/src/ink/predict.ts new file mode 100644 index 0000000..7ef474c --- /dev/null +++ b/src/ink/predict.ts @@ -0,0 +1,293 @@ +/** + * Pen-position prediction for the live stroke — pure functions. + * + * Idea learned from studying established whiteboards (not their code): predict + * only a very short horizon (~one frame up to 36 ms) from x/y/time alone, gate + * the prediction off on sharp turns and jitter, and treat predicted points as + * display-only — the next real sample replaces them and they never enter the + * saved stroke. + * + * Two sources, in order of preference: + * 1. `PointerEvent.getPredictedEvents()` (browser-native, Chromium). + * 2. A tiny per-axis constant-velocity Kalman filter as fallback. + */ + +export interface InkSample { + /** screen px */ + x: number + y: number + /** ms, monotonic (event.timeStamp) */ + t: number +} + +export type GateVerdict = 'sparse' | 'idle' | 'straight' | 'curve' | 'sharp' | 'jitter' + +export interface GateResult { + verdict: GateVerdict + /** false → show no prediction at all */ + predict: boolean + /** extrapolation budget this frame (0 when predict is false) */ + horizonMs: number +} + +export interface GateOptions { + minSamples?: number + /** px/ms below which the pen counts as parked (jitter zone) */ + idleSpeedPxPerMs?: number + /** single turn above this (deg) kills prediction */ + sharpTurnDeg?: number + /** oscillating turns above this (deg) count as jitter */ + jitterTurnDeg?: number + /** mean turn above this (deg) shortens the horizon */ + curveTurnDeg?: number + straightHorizonMs?: number + curveHorizonMs?: number +} + +export const DEFAULT_GATE_OPTIONS: Required = { + minSamples: 2, + idleSpeedPxPerMs: 0.04, + sharpTurnDeg: 65, + jitterTurnDeg: 30, + curveTurnDeg: 12, + straightHorizonMs: 33, + curveHorizonMs: 17, +} + +export const PREDICTION_MAX_HORIZON_MS = 36 +export const PREDICTION_STEP_MS = 11 + +/** Gating and the KF only need the recent gesture — cap the sample history so a long stroke costs the same as a short one. */ +export const PREDICTION_HISTORY_CAP = 96 + +const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v) + +/** + * Decide whether the current stroke moment may be extrapolated, and by how much. + * Pure; never mutates `samples`. + */ +export function gateSamples(samples: InkSample[], o: GateOptions = {}): GateResult { + const opt = { ...DEFAULT_GATE_OPTIONS, ...o } + const none: GateResult = { verdict: 'sparse', predict: false, horizonMs: 0 } + if (samples.length < opt.minSamples) return none + + const vx: number[] = [] + const vy: number[] = [] + const speeds: number[] = [] + for (let i = 1; i < samples.length; i++) { + const dt = samples[i].t - samples[i - 1].t + if (dt <= 0) continue + const dx = samples[i].x - samples[i - 1].x + const dy = samples[i].y - samples[i - 1].y + vx.push(dx / dt) + vy.push(dy / dt) + speeds.push(Math.hypot(dx, dy) / dt) + } + if (!speeds.length) return none + if (speeds[speeds.length - 1] < opt.idleSpeedPxPerMs) return { verdict: 'idle', predict: false, horizonMs: 0 } + + // signed turn angles (deg) between successive velocity vectors + const turns: number[] = [] + for (let i = 1; i < vx.length; i++) { + const a = Math.hypot(vx[i - 1], vy[i - 1]) + const b = Math.hypot(vx[i], vy[i]) + if (a < 1e-9 || b < 1e-9) continue + const cos = clamp((vx[i - 1] * vx[i] + vy[i - 1] * vy[i]) / (a * b), -1, 1) + const cross = vx[i - 1] * vy[i] - vy[i - 1] * vx[i] + turns.push((cross < 0 ? -1 : 1) * Math.acos(cos) * (180 / Math.PI)) + } + const maxTurn = turns.length ? Math.max(...turns.map(Math.abs)) : 0 + if (maxTurn > opt.sharpTurnDeg) return { verdict: 'sharp', predict: false, horizonMs: 0 } + + // jitter: large zig-zag (two consecutive opposite-sign turns) or sustained + // recent oscillation. Flips only count in the last ~12 pairs and need BOTH + // turns above jitterTurnDeg/2 — pointer noise produces small random turns + // whose flips accumulate harmlessly over a long window (replay-eval finding). + const flipDeg = opt.jitterTurnDeg / 2 + const recent = turns.slice(-12) + let flips = 0 + for (let i = 1; i < recent.length; i++) { + if (Math.abs(recent[i]) > opt.jitterTurnDeg && Math.abs(recent[i - 1]) > opt.jitterTurnDeg && recent[i] * recent[i - 1] < 0) + return { verdict: 'jitter', predict: false, horizonMs: 0 } + if (Math.abs(recent[i]) >= flipDeg && Math.abs(recent[i - 1]) >= flipDeg && recent[i] * recent[i - 1] < 0) flips++ + } + if (flips >= 3) return { verdict: 'jitter', predict: false, horizonMs: 0 } + + // curve vs straight on a ROBUST statistic: the median turn, not the max — + // a noisy window always contains one large random turn, so a max-based test + // read every straight stroke as a curve (replay-eval finding) + const abs = turns.map(Math.abs).sort((a, b) => a - b) + const medianTurn = abs.length ? abs[abs.length >> 1] : 0 + if (medianTurn > opt.curveTurnDeg) return { verdict: 'curve', predict: true, horizonMs: opt.curveHorizonMs } + return { verdict: 'straight', predict: true, horizonMs: opt.straightHorizonMs } +} + +/** Minimal per-axis constant-velocity Kalman filter (state [p, v], measurement [p]). */ +export interface KF1D { + p: number + /** px/s */ + v: number + p00: number + p01: number + p10: number + p11: number +} + +/** Spectral density of the acceleration noise, px²/s⁴ — tuned for handwriting snaps. */ +export const KF_ACCEL_VAR = 9e6 +/** Pointer measurement variance, px². */ +export const KF_MEAS_VAR = 2 + +export function kfInit(pos: number): KF1D { + // generous velocity prior so the filter adopts real speed within a few samples + return { p: pos, v: 0, p00: 40, p01: 0, p10: 0, p11: 1e5 } +} + +export function kfPredict(s: KF1D, dtMs: number, accelVar = KF_ACCEL_VAR): KF1D { + const dt = dtMs / 1000 + const q = accelVar + return { + p: s.p + s.v * dt, + v: s.v, + p00: s.p00 + 2 * dt * s.p01 + dt * dt * s.p11 + (q * dt ** 4) / 4, + p01: s.p01 + dt * s.p11 + (q * dt ** 3) / 2, + p10: s.p10 + dt * s.p11 + (q * dt ** 3) / 2, + p11: s.p11 + q * dt * dt, + } +} + +export function kfUpdate(s: KF1D, z: number, measVar = KF_MEAS_VAR): KF1D { + const y = z - s.p + const k0 = s.p00 / (s.p00 + measVar) + const k1 = s.p10 / (s.p00 + measVar) + return { + p: s.p + k0 * y, + v: s.v + k1 * y, + p00: (1 - k0) * s.p00, + p01: (1 - k0) * s.p01, + p10: s.p10 - k1 * s.p00, + p11: s.p11 - k1 * s.p01, + } +} + +export interface PredictOptions { + /** extrapolation budget, capped at PREDICTION_MAX_HORIZON_MS */ + horizonMs?: number + stepMs?: number + /** KF acceleration noise override (default KF_ACCEL_VAR) — replay-eval knob, defaults unchanged */ + qAcc?: number + /** KF measurement variance override (default KF_MEAS_VAR) — replay-eval knob, defaults unchanged */ + measVar?: number +} + +/** + * Fallback predictor: run the per-axis KF over the recent real samples, then + * step forward `horizonMs`. Pure — the input samples are never mutated, the + * result is a fresh array of display-only points beyond the last real sample. + */ +export function predictTail(samples: InkSample[], o: PredictOptions = {}): InkSample[] { + const horizonMs = Math.min(o.horizonMs ?? DEFAULT_GATE_OPTIONS.straightHorizonMs, PREDICTION_MAX_HORIZON_MS) + const stepMs = o.stepMs ?? PREDICTION_STEP_MS + const n = samples.length + if (n < 2) return [] + if (!(samples[n - 1].t > samples[0].t)) return [] + + let kx = kfInit(samples[0].x) + let ky = kfInit(samples[0].y) + let t = samples[0].t + for (let i = 1; i < n; i++) { + const dt = samples[i].t - t + if (dt <= 0) continue // non-monotonic guard: keep the filter on the last good time + kx = kfUpdate(kfPredict(kx, dt, o.qAcc), samples[i].x, o.measVar) + ky = kfUpdate(kfPredict(ky, dt, o.qAcc), samples[i].y, o.measVar) + t = samples[i].t + } + const out: InkSample[] = [] + for (let d = stepMs; d <= horizonMs + 1e-9; d += stepMs) { + out.push({ x: kfPredict(kx, d).p, y: kfPredict(ky, d).p, t: t + d }) + } + return out +} + +export interface PredictedEventLike { + clientX: number + clientY: number +} + +export type PredictedProvider = { + getPredictedEvents?: () => PredictedEventLike[] +} + +/** + * Native predicted events when the platform offers them (Chromium), else []. + * Coordinates stay in screen space; count is capped — the tail is a hint, not a + * path to commit. + */ +export function nativePredictedTail(e: PredictedProvider, maxPoints = 4): PredictedEventLike[] { + const fn = e.getPredictedEvents + if (typeof fn !== 'function') return [] + let evs: PredictedEventLike[] + try { + evs = fn.call(e) + } catch { + return [] + } + if (!Array.isArray(evs) || !evs.length) return [] + return evs.slice(0, maxPoints).map((ev) => ({ clientX: ev.clientX, clientY: ev.clientY })) +} + +// --- refresh-rate adaptive step/horizon ------------------------------------- + +export const ADAPTIVE_MIN_FRAME_MS = 4 +export const ADAPTIVE_MAX_FRAME_MS = 33 +/** fall back to a 60 Hz assumption until rAF deltas come in */ +export const ADAPTIVE_DEFAULT_FRAME_MS = 16.7 +export const ADAPTIVE_MIN_STEP_MS = 3 +export const ADAPTIVE_MAX_STEP_MS = PREDICTION_STEP_MS // never coarser than the static 11 ms +/** how many frames of lag the tail aims to cover */ +export const ADAPTIVE_FRAMES_AHEAD = 2 +/** curve verdicts get this fraction of the straight-line horizon */ +export const ADAPTIVE_CURVE_FRACTION = 0.5 + +export interface AdaptiveOptions { + /** how many frames of lag the tail aims to cover (replay-eval knob, default ADAPTIVE_FRAMES_AHEAD) */ + framesAhead?: number + /** curve verdicts get this fraction of the straight-line horizon (default ADAPTIVE_CURVE_FRACTION) */ + curveFraction?: number +} + +export interface AdaptivePrediction { + stepMs: number + horizonMs: number + curveHorizonMs: number +} + +/** + * Scale the prediction step and horizon to the display's frame interval + * (estimated from rAF deltas): a 120 Hz panel gets a finer, shorter tail than a + * 60 Hz one, both under the absolute PREDICTION_MAX_HORIZON_MS cap. Degenerate + * intervals (first frame, background tab) clamp into a sane range. + */ +export function frameAdaptivePrediction(frameIntervalMs: number, o: AdaptiveOptions = {}): AdaptivePrediction { + const ahead = o.framesAhead ?? ADAPTIVE_FRAMES_AHEAD + const curveFraction = o.curveFraction ?? ADAPTIVE_CURVE_FRACTION + const f = + Number.isFinite(frameIntervalMs) && frameIntervalMs > 0 + ? Math.min(ADAPTIVE_MAX_FRAME_MS, Math.max(ADAPTIVE_MIN_FRAME_MS, frameIntervalMs)) + : ADAPTIVE_DEFAULT_FRAME_MS + const stepMs = Math.min(ADAPTIVE_MAX_STEP_MS, Math.max(ADAPTIVE_MIN_STEP_MS, f / 2)) + const horizonMs = Math.min(PREDICTION_MAX_HORIZON_MS, Math.max(stepMs, f * ahead)) + const curveHorizonMs = Math.max(stepMs, horizonMs * curveFraction) + return { stepMs, horizonMs, curveHorizonMs } +} + +/** + * Display-only ghost path for the separately-rendered prediction tail: starts at + * the stroke tip (last smoothed point) and runs through the predicted points. + * Pure — neither input is mutated, and nothing here ever reaches saved data. + */ +export function predictionTailPath(basePts: number[], tail: number[]): number[] { + const n = basePts.length + if (n < 3) return tail.slice() + return [basePts[n - 3], basePts[n - 2], basePts[n - 1], ...tail] +} diff --git a/src/ink/replay.test.ts b/src/ink/replay.test.ts new file mode 100644 index 0000000..6d66b81 --- /dev/null +++ b/src/ink/replay.test.ts @@ -0,0 +1,65 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { makeTrajectory, mulberry32, replayTrajectory, type ReplayCandidate } from './replay' + +test('mulberry32: deterministic and seed-sensitive', () => { + const a = mulberry32(42) + const b = mulberry32(42) + const seqA = Array.from({ length: 5 }, () => a()) + const seqB = Array.from({ length: 5 }, () => b()) + assert.deepEqual(seqA, seqB) + assert.notEqual(seqA[0], mulberry32(7)()) +}) + +test('makeTrajectory: reproducible, monotonic time, noise bounded around exact truth', () => { + const t1 = makeTrajectory('straight', { rateHz: 60, noisePx: 0.6, seed: 42 }) + const t2 = makeTrajectory('straight', { rateHz: 60, noisePx: 0.6, seed: 42 }) + assert.deepEqual(t1.samples, t2.samples) + assert.equal(t1.samples.length, Math.round(1500 * 0.06) + 1) // duration × rate + 1 + for (let i = 1; i < t1.samples.length; i++) assert.ok(t1.samples[i].t > t1.samples[i - 1].t) + for (const s of t1.samples) { + const truth = t1.truthAt(s.t) + // ~4σ bound for a 0.6px Gaussian + assert.ok(Math.hypot(s.x - truth.x, s.y - truth.y) < 0.6 * 4, 'sample strayed too far from truth') + } +}) + +test('replayTrajectory: deterministic and counts moments', () => { + const traj = makeTrajectory('straight', { rateHz: 60, seed: 42 }) + const cand: ReplayCandidate = { name: 'A-current-default' } + const s1 = replayTrajectory(traj, cand, 60) + const s2 = replayTrajectory(traj, cand, 60) + assert.deepEqual(s1, s2) + assert.equal(s1.predicted + s1.gated, s1.moments) + assert.equal(s1.moments, traj.samples.length - 8) + assert.ok(s1.predicted > s1.moments * 0.6, `straight stroke should mostly predict (got ${s1.predicted}/${s1.moments})`) + assert.ok(s1.meanErr >= 0 && Number.isFinite(s1.meanErr)) +}) + +test('replayTrajectory: a never-predict candidate gates everything away', () => { + const traj = makeTrajectory('straight', { rateHz: 60, seed: 42 }) + const s = replayTrajectory(traj, { name: 'off', gate: { minSamples: 1e9 } }, 60) + assert.equal(s.predicted, 0) + assert.equal(s.gated, s.moments) + assert.equal(s.meanErr, 0) + assert.equal(s.meanOvershoot, 0) +}) + +test('replayTrajectory: sharp turns and pauses get gated, slow ticks mostly gated', () => { + const turn = replayTrajectory(makeTrajectory('sharpTurn', { rateHz: 60, seed: 42 }), { name: 'A' }, 60) + assert.ok(turn.gated > 0, 'sharp turn should suppress prediction sometimes') + const pause = replayTrajectory(makeTrajectory('pause', { rateHz: 60, seed: 42 }), { name: 'A' }, 60) + assert.ok(pause.gated > 0, 'paused pen should be gated (idle)') + const tick = replayTrajectory(makeTrajectory('slowTick', { rateHz: 60, seed: 42 }), { name: 'A' }, 60) + assert.ok(tick.predicted < tick.moments * 0.5, `slow tick should mostly stay gated (predicted ${tick.predicted}/${tick.moments})`) +}) + +test('replayTrajectory: candidate knobs change the outcome', () => { + const traj = makeTrajectory('fastArc', { rateHz: 60, seed: 42 }) + const a = replayTrajectory(traj, { name: 'A' }, 60) + const c = replayTrajectory(traj, { name: 'C', gate: { sharpTurnDeg: 75, jitterTurnDeg: 35, curveTurnDeg: 15 }, framesAhead: 2.5 }, 60) + assert.ok(a.predicted > 0) + // the aggressive set covers more lag → strictly larger horizon, not identical stats + assert.notDeepEqual(a, c) +}) diff --git a/src/ink/replay.ts b/src/ink/replay.ts new file mode 100644 index 0000000..d5d9d27 --- /dev/null +++ b/src/ink/replay.ts @@ -0,0 +1,202 @@ +/** + * Offline replay evaluation for the ink-prediction experiment — pure Node, no DOM. + * + * SYNTHETIC, reproducible handwriting-like trajectories are replayed sample by + * sample through the exact gate + Kalman pipeline the Board uses; every + * predicted tail end is compared against the trajectory's exact (noise-free) + * ground truth at the tail's own timestamp. + * + * The numbers are STARTING-POINT CANDIDATES for on-device (iPad) tuning only — + * nothing here changes any default, and synthetic noise is not real ink. + */ +import { frameAdaptivePrediction, gateSamples, PREDICTION_HISTORY_CAP, predictTail, type GateOptions, type InkSample } from './predict' + +/** tiny deterministic PRNG (mulberry32) so every replay run is reproducible */ +export function mulberry32(seed: number): () => number { + let a = seed >>> 0 + return () => { + a = (a + 0x6d2b79f5) | 0 + let t = Math.imul(a ^ (a >>> 15), 1 | a) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +export type TrajectoryScenario = 'straight' | 'fastArc' | 'sharpTurn' | 'jitter' | 'pause' | 'slowTick' + +export const SCENARIO_LABELS: Record = { + straight: 'straight line', + fastArc: 'fast arc (small radius)', + sharpTurn: 'sharp turn', + jitter: 'jitter', + pause: 'pause', + slowTick: 'slow short tick', +} + +const SCENARIO_DURATION_MS: Record = { + straight: 1500, + fastArc: 600, + sharpTurn: 1000, + jitter: 800, + pause: 1300, + slowTick: 500, +} + +export interface ReplayTrajectory { + scenario: TrajectoryScenario + samples: InkSample[] + /** exact, noise-free position at time t (ms) */ + truthAt: (t: number) => { x: number; y: number } +} + +export interface TrajectoryOptions { + rateHz?: number + noisePx?: number + seed?: number +} + +/** + * Build one synthetic trajectory. Ground truth stays parametric and exact; + * Gaussian noise is added to the samples only, like pointer-reporting jitter. + */ +export function makeTrajectory(scenario: TrajectoryScenario, o: TrajectoryOptions = {}): ReplayTrajectory { + const rateHz = o.rateHz ?? 60 + const noisePx = o.noisePx ?? 0.6 + const rnd = mulberry32(o.seed ?? 42) + const gauss = () => { + const u = Math.max(rnd(), 1e-9) + const v = rnd() + return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v) + } + const dt = 1000 / rateHz + const duration = SCENARIO_DURATION_MS[scenario] + + let truthAt: (t: number) => { x: number; y: number } + switch (scenario) { + case 'straight': + // 600 px/s to the right for 1.5 s + truthAt = (t) => ({ x: 120 + 0.6 * t, y: 200 }) + break + case 'fastArc': + // tight fast arc (like the loop of a handwritten "e"): r=25, v=600 px/s + truthAt = (t) => { + const theta = (600 / 25) * (t / 1000) + return { x: 300 + 25 * Math.cos(theta), y: 240 + 25 * Math.sin(theta) } + } + break + case 'sharpTurn': + // 600 ms straight, then a hard 90° turn downwards + truthAt = (t) => (t < 600 ? { x: 120 + 0.6 * t, y: 200 } : { x: 480, y: 200 + 0.6 * (t - 600) }) + break + case 'jitter': + // horizontal drag under a fast triangular wobble (alternating ~60° turns) + truthAt = (t) => { + const phase = (t % 80) / 80 + return { x: 120 + 0.5 * t, y: 200 + 6 * (phase < 0.5 ? phase * 2 : 2 - phase * 2) } + } + break + case 'pause': + // write, hold still for 300 ms (device keeps reporting), write again + truthAt = (t) => { + if (t < 500) return { x: 120 + 0.6 * t, y: 200 } + if (t < 800) return { x: 420, y: 200 } + return { x: 420 + 0.6 * (t - 800), y: 200 } + } + break + case 'slowTick': + // a slow deliberate short tick: ~6 px over 500 ms (idle-speed territory) + truthAt = (t) => ({ x: 100 + 0.012 * t, y: 300 + 0.0024 * t }) + break + } + + const n = Math.round((duration * rateHz) / 1000) + 1 + const samples: InkSample[] = [] + for (let i = 0; i < n; i++) { + const t = i * dt + const p = truthAt(t) + samples.push({ x: p.x + gauss() * noisePx, y: p.y + gauss() * noisePx, t }) + } + return { scenario, samples, truthAt } +} + +export interface ReplayCandidate { + name: string + /** gate angle/horizon overrides (defaults = current constants) */ + gate?: GateOptions + /** KF acceleration-noise override (default KF_ACCEL_VAR) */ + qAcc?: number + /** KF measurement-variance override (default KF_MEAS_VAR) */ + measVar?: number + /** frames of lag the tail covers (default ADAPTIVE_FRAMES_AHEAD) */ + framesAhead?: number +} + +export interface ReplayStats { + candidate: string + scenario: TrajectoryScenario + rateHz: number + /** evaluated moments (one per sample with enough history) */ + moments: number + /** moments where the gate allowed a prediction */ + predicted: number + /** moments where the gate suppressed the tail */ + gated: number + /** |predicted tail end − ground truth| at the tail's own timestamp (px) */ + meanErr: number + p95Err: number + maxErr: number + /** signed overshoot: error component along the travel direction, + = ahead of the true point (px) */ + meanOvershoot: number +} + +const MIN_HISTORY = 8 + +/** Replay one trajectory under one candidate constant set. Pure w.r.t. inputs. */ +export function replayTrajectory(traj: ReplayTrajectory, cand: ReplayCandidate, rateHz: number): ReplayStats { + const frameMs = 1000 / rateHz + const adapt = frameAdaptivePrediction(frameMs, { framesAhead: cand.framesAhead }) + const errs: number[] = [] + const overshoots: number[] = [] + let predicted = 0 + let gated = 0 + const samples = traj.samples + for (let i = MIN_HISTORY; i < samples.length; i++) { + const hist = samples.slice(Math.max(0, i - PREDICTION_HISTORY_CAP + 1), i + 1) + const gate = gateSamples(hist, cand.gate) + const last = hist[hist.length - 1] + if (!gate.predict) { + gated++ + continue + } + const horizon = gate.verdict === 'curve' ? adapt.curveHorizonMs : adapt.horizonMs + const tail = predictTail(hist, { horizonMs: horizon, stepMs: adapt.stepMs, qAcc: cand.qAcc, measVar: cand.measVar }) + if (!tail.length) { + gated++ + continue + } + predicted++ + const end = tail[tail.length - 1] + const truth = traj.truthAt(end.t) + errs.push(Math.hypot(end.x - truth.x, end.y - truth.y)) + // overshoot = error component along the current travel direction (+ = past the true point) + const prev = hist[hist.length - 2] + const dx = last.x - prev.x + const dy = last.y - prev.y + const len = Math.max(Math.hypot(dx, dy), 1e-6) + overshoots.push(((end.x - truth.x) * dx + (end.y - truth.y) * dy) / len) + } + const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0) + const sorted = [...errs].sort((a, b) => a - b) + return { + candidate: cand.name, + scenario: traj.scenario, + rateHz, + moments: predicted + gated, + predicted, + gated, + meanErr: mean(errs), + p95Err: sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))] : 0, + maxErr: sorted.length ? sorted[sorted.length - 1] : 0, + meanOvershoot: mean(overshoots), + } +} diff --git a/src/ink/smooth.test.ts b/src/ink/smooth.test.ts new file mode 100644 index 0000000..9f52b37 --- /dev/null +++ b/src/ink/smooth.test.ts @@ -0,0 +1,169 @@ +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { + appendStrokePoint, + BEZIER_SAMPLES_PER_CURVE, + createIncrementalSmooth, + midpointBezierPolyline, + SMOOTH_MIN_DIST_DIP, + updateIncrementalSmooth, +} from './smooth' + +const triple = (pts: number[], i: number) => [pts[i * 3], pts[i * 3 + 1], pts[i * 3 + 2]] + +test('appendStrokePoint drops near points (0.5 DIP default)', () => { + const s = appendStrokePoint([], { x: 10, y: 10, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1) + assert.equal(s.length, 3) + // 0.1 screen px away → skipped + const near = appendStrokePoint(s, { x: 10.1, y: 10, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1) + assert.equal(near, s) // same array when skipped + // 2 screen px away → appended + const far = appendStrokePoint(s, { x: 12.1, y: 10, pressure: 0.6 }, SMOOTH_MIN_DIST_DIP, 1) + assert.equal(far.length, 6) + assert.deepEqual(triple(far, 1), [12.1, 10, 0.6]) +}) + +test('appendStrokePoint threshold is in screen px (world × scale)', () => { + const s = [0, 0, 0.5] + // world distance 1 at zoom 4 → 4 screen px → appended even though 1 < 0.5 is false + const at = appendStrokePoint(s, { x: 1, y: 0, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 4) + assert.equal(at.length, 6) + // world distance 0.1 at zoom 1 → 0.1 screen px → skipped + const skipped = appendStrokePoint(s, { x: 0.1, y: 0, pressure: 0.5 }, SMOOTH_MIN_DIST_DIP, 1) + assert.equal(skipped, s) +}) + +test('flag-off equivalence: appendStrokePoint at 0.8 reproduces the main inline loop', () => { + // literal port of the main-branch capture loop for comparison + const mainAppend = (pts: number[], x: number, y: number, pressure: number, scale: number) => { + const out = pts.slice() + const lx = out[out.length - 3] as number + const ly = out[out.length - 2] as number + if (Math.hypot(x - lx, y - ly) * scale < 0.8) return out + out.push(x, y, pressure) + return out + } + const events: [number, number, number, number][] = [ + [0, 0, 1, 1], + [0.3, 0.4, 1, 1], + [0.6, 0.8, 1, 1], + [2, 3, 1, 1], + [2.1, 3.05, 1, 1], + [5, 7, 1, 1], + [5.4, 7.3, 1, 1], + [9, 9, 1, 2], + ] + let a: number[] = [] + let b: number[] = [] + for (const [x, y, pressure, scale] of events) { + a = appendStrokePoint(a, { x, y, pressure }, 0.8, scale) + b = mainAppend(b, x, y, pressure, scale) + } + assert.deepEqual(a, b) +}) + +test('midpointBezierPolyline keeps endpoints exact', () => { + const pts = [0, 0, 0.5, 10, 12, 0.5, 24, 2, 0.5, 40, 30, 0.5] + const out = midpointBezierPolyline(pts) + assert.deepEqual(triple(out, 0), triple(pts, 0)) + const last = out.length / 3 - 1 + assert.deepEqual(triple(out, last), triple(pts, pts.length / 3 - 1)) + // 1 + (n-2)*samples + 1 points + assert.equal(out.length, (1 + 2 * BEZIER_SAMPLES_PER_CURVE + 1) * 3) +}) + +test('midpointBezierPolyline leaves dots and two-point strokes untouched', () => { + const dot = [3, 4, 0.5] + const line = [0, 0, 0.5, 10, 10, 0.7] + assert.equal(midpointBezierPolyline(dot), dot) + assert.equal(midpointBezierPolyline(line), line) +}) + +test('midpointBezierPolyline passes through sample midpoints (no corner cutting to NaN)', () => { + const pts = [0, 0, 0.5, 10, 0, 0.5, 20, 0, 0.5] + const out = midpointBezierPolyline(pts) + for (let i = 0; i < out.length; i++) assert.ok(Number.isFinite(out[i]), `non-finite at ${i}`) + // single curve segment: out[0] = P0, sample s lands at index s → t=0.5 is index 3, + // exactly on the control point (the original sample) + const mid = triple(out, BEZIER_SAMPLES_PER_CURVE / 2) + assert.deepEqual(mid, [10, 0, 0.5]) +}) + +test('smoothing output is NaN-free for nasty finite inputs', () => { + const nasties = [ + [0, 0, 0.5, 5, 5, 0.5, 5, 5, 0.5, 5, 5, 0.5, 20, 20, 0.5], // repeated points + [0, 0, 0, 1, 0, 1, 2, 0, 0, 3, 0, 1, 4, 0, 0], // zig-zag pressure + [1e6, -1e6, 0.5, 1e6 + 0.001, 1e6, 0.5, 2e6, 2e6, 0.5], // huge spans + ] + for (const pts of nasties) { + const out = midpointBezierPolyline(pts) + for (let i = 0; i < out.length; i++) assert.ok(Number.isFinite(out[i]), `non-finite at ${i}`) + } +}) + +test('pressure is interpolated within the neighbouring range', () => { + const pts = [0, 0, 0.2, 10, 0, 0.8, 20, 0, 0.4] + const out = midpointBezierPolyline(pts) + for (let i = 2; i < out.length; i += 3) { + assert.ok(out[i] >= 0.2 && out[i] <= 0.8, `pressure out of range: ${out[i]}`) + } +}) + +// --- incremental wet-ink smoothing --- + +/** synthetic wavy stroke with n points (same shape family as the benchmark) */ +const wavy = (n: number): number[] => { + const pts: number[] = [] + for (let i = 0; i < n; i++) { + const t = i / (n - 1 || 1) + pts.push(t * 800, 300 + Math.sin(t * Math.PI * 6) * 120, 0.5) + } + return pts +} + +test('incremental smoothing matches the full resample at every prefix', () => { + const pts = wavy(200) + const st = createIncrementalSmooth() + for (let k = 1; k <= 200; k++) { + const partial = pts.slice(0, k * 3) + const out = updateIncrementalSmooth(st, partial) + assert.deepEqual(out.pts, midpointBezierPolyline(partial), `wet/dry mismatch at ${k} points`) + assert.equal(out, st) // same state object, mutated in place + } +}) + +test('incremental smoothing: cold start mid-stroke still matches', () => { + const pts = wavy(120) + const st = createIncrementalSmooth() + const out = updateIncrementalSmooth(st, pts) // attached to a stroke already in progress + assert.deepEqual(out.pts, midpointBezierPolyline(pts)) +}) + +test('incremental smoothing: <3 samples pass through by identity, then grow', () => { + const st = createIncrementalSmooth() + const dot = [3, 4, 0.5] + assert.equal(updateIncrementalSmooth(st, dot).pts, dot) + const line = [0, 0, 0.5, 10, 10, 0.5] + assert.equal(updateIncrementalSmooth(st, line).pts, line) + const grown = updateIncrementalSmooth(st, [0, 0, 0.5, 10, 10, 0.5, 20, 4, 0.5]) + assert.deepEqual(grown.pts, midpointBezierPolyline([0, 0, 0.5, 10, 10, 0.5, 20, 4, 0.5])) +}) + +test('incremental smoothing: unchanged stroke is a no-op', () => { + const pts = wavy(50) + const st = createIncrementalSmooth() + updateIncrementalSmooth(st, pts) + const snapshot = st.pts.slice() + const out = updateIncrementalSmooth(st, pts) + assert.equal(out.pts.length, snapshot.length) + assert.deepEqual(out.pts, snapshot) +}) + +test('incremental smoothing: input array is never mutated', () => { + const pts = wavy(30) + const snapshot = pts.slice() + const st = createIncrementalSmooth() + updateIncrementalSmooth(st, pts) + assert.deepEqual(pts, snapshot) +}) diff --git a/src/ink/smooth.ts b/src/ink/smooth.ts new file mode 100644 index 0000000..72701f5 --- /dev/null +++ b/src/ink/smooth.ts @@ -0,0 +1,127 @@ +/** + * Ink smoothing primitives — pure functions. + * + * Approach (idea learned from studying established whiteboard behaviour, not code): + * drop near-duplicate samples, then treat the stroke as the midpoint quadratic + * Bézier — adjacent sample midpoints are the curve ends, the original sample is + * the control point. Endpoints stay pinned so taps and dots are untouched. + */ + +export interface InkPoint { + x: number + y: number + pressure: number +} + +/** Near-point threshold in DIP (CSS px) for the smoothing experiment (main uses a looser 0.8). */ +export const SMOOTH_MIN_DIST_DIP = 0.5 + +/** How many polyline samples each quadratic curve segment is subdivided into. */ +export const BEZIER_SAMPLES_PER_CURVE = 6 + +/** + * Append one real sample to a flat [x, y, pressure, ...] stroke, skipping points + * closer than `minScreenDist` screen px to the current tip (world coords + view + * scale → screen distance, same rule main applies inline with 0.8). + * Pure: returns a new array, or the same array when the point is skipped. + */ +export function appendStrokePoint(pts: number[], p: InkPoint, minScreenDist: number, scale: number): number[] { + const n = pts.length + if (n >= 3) { + const dx = p.x - pts[n - 3] + const dy = p.y - pts[n - 2] + if (Math.hypot(dx, dy) * scale < minScreenDist) return pts + } + return [...pts, p.x, p.y, p.pressure] +} + +const quad = (c0: number, c1: number, c2: number, t: number) => { + const u = 1 - t + return u * u * c0 + 2 * u * t * c1 + t * t * c2 +} + +/** Piecewise-linear pressure between the three control samples of one curve segment. */ +const quadPressure = (p0: number, p1: number, p2: number, t: number) => + t <= 0.5 ? p0 + (p1 - p0) * t * 2 : p1 + (p2 - p1) * (t - 0.5) * 2 + +/** + * Push the samples of curve segment i (control point P[i], ends at the adjacent + * midpoints) into `out`. Shared by the whole-stroke resample and the incremental + * cache, so wet (incremental) and dry (resampled) shapes are identical by + * construction, not just by coincidence of math. + */ +function pushSegmentSamples(pts: number[], i: number, samplesPerCurve: number, out: number[]): void { + const ax = (pts[(i - 1) * 3] + pts[i * 3]) / 2 + const ay = (pts[(i - 1) * 3 + 1] + pts[i * 3 + 1]) / 2 + const bx = (pts[i * 3] + pts[(i + 1) * 3]) / 2 + const by = (pts[(i + 1) * 3 + 1] + pts[(i + 1) * 3 + 1]) / 2 + const cx = pts[i * 3] + const cy = pts[i * 3 + 1] + const pa = pts[(i - 1) * 3 + 2] + const pc = pts[i * 3 + 2] + const pb = pts[(i + 1) * 3 + 2] + for (let s = 1; s <= samplesPerCurve; s++) { + const t = s / samplesPerCurve + out.push(quad(ax, cx, bx, t), quad(ay, cy, by, t), quadPressure(pa, pc, pb, t)) + } +} + +/** + * Sample the midpoint quadratic Bézier through the stroke as a flat + * [x, y, pressure, ...] polyline. The first and last samples are preserved + * exactly (value and identity of the array when there is nothing to smooth); + * pressure is interpolated between samples. Strokes with fewer than 3 samples + * (dots, two-point lines) are returned unchanged. + */ +export function midpointBezierPolyline(pts: number[], samplesPerCurve = BEZIER_SAMPLES_PER_CURVE): number[] { + const n = pts.length / 3 + if (n < 3) return pts + const out: number[] = [pts[0], pts[1], pts[2]] + for (let i = 1; i < n - 1; i++) pushSegmentSamples(pts, i, samplesPerCurve, out) + out.push(pts[(n - 1) * 3], pts[(n - 1) * 3 + 1], pts[(n - 1) * 3 + 2]) + return out +} + +// --- incremental wet-ink smoothing ------------------------------------------- +// +// A midpoint-Bézier segment for control point P[i] only ever depends on +// P[i-1..i+1], so each segment is final the moment P[i+1] arrives: the smoothed +// prefix never changes as the stroke grows. The incremental cache exploits that +// to render wet ink with O(1) work per pointer event instead of resampling the +// whole stroke every frame, while staying bit-identical to the dry bake. + +export interface IncrementalSmoothState { + /** smoothed polyline so far (flat triples); === the input array while < 3 samples */ + pts: number[] + /** curve segments already emitted (segments 1..emitted are final) */ + emitted: number +} + +export function createIncrementalSmooth(): IncrementalSmoothState { + return { pts: [], emitted: 0 } +} + +/** + * Feed the (full, growing) stroke into the cache and return it. The result's + * `pts` equals `midpointBezierPolyline(pts)` for every prefix — wet and dry + * shapes match exactly at every frame. Mutates and returns `state`; `pts` is + * only read. Calling it again with an unchanged stroke is a no-op. + */ +export function updateIncrementalSmooth(state: IncrementalSmoothState, pts: number[], samplesPerCurve = BEZIER_SAMPLES_PER_CURVE): IncrementalSmoothState { + const n = pts.length / 3 + if (n < 3) { + state.pts = pts + state.emitted = 0 + return state + } + if (state.emitted === 0) { + // cold start (also covers being attached to a stroke already in progress) + state.pts = [pts[0], pts[1], pts[2]] + } else { + state.pts.length -= 3 // drop the previous trailing endpoint + } + for (let i = state.emitted + 1; i <= n - 2; i++) pushSegmentSamples(pts, i, samplesPerCurve, state.pts) + state.emitted = n - 2 + state.pts.push(pts[(n - 1) * 3], pts[(n - 1) * 3 + 1], pts[(n - 1) * 3 + 2]) + return state +} diff --git a/src/ink/tolerance.test.ts b/src/ink/tolerance.test.ts new file mode 100644 index 0000000..69d728c --- /dev/null +++ b/src/ink/tolerance.test.ts @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { + DRAG_THRESHOLD_DIP, + HIT_TOLERANCE_DIP, + TAP_MAX_DURATION_MS, + dragThresholdWorld, + hasRealPressure, + hitToleranceWorld, + isTapStroke, + toPointerKind, +} from './tolerance' + +test('pointer kind mapping: mouse / touch / pen, unknown → mouse', () => { + assert.equal(toPointerKind('mouse'), 'mouse') + assert.equal(toPointerKind('touch'), 'touch') + assert.equal(toPointerKind('pen'), 'pen') + assert.equal(toPointerKind(''), 'mouse') + assert.equal(toPointerKind('fingerprint'), 'mouse') +}) + +test('thresholds come in the three flavours (mouse / touch / pen)', () => { + assert.deepEqual(DRAG_THRESHOLD_DIP, { mouse: 1, touch: 16, pen: 4 }) + assert.deepEqual(HIT_TOLERANCE_DIP, { mouse: 3, touch: 10, pen: 5 }) +}) + +test('drag threshold is DIP divided by the current zoom', () => { + assert.equal(dragThresholdWorld('pen', 2), 2) // 4 DIP at zoom 2 → 2 world units → 4 screen px + assert.equal(dragThresholdWorld('mouse', 4), 0.25) // tight at high zoom + assert.equal(dragThresholdWorld('touch', 0.5), 32) // loose when zoomed out +}) + +test('hit tolerance is DIP divided by the current zoom', () => { + assert.equal(hitToleranceWorld('touch', 0.5), 20) + assert.equal(hitToleranceWorld('pen', 1), 5) + assert.equal(hitToleranceWorld('mouse', 2), 1.5) +}) + +test('pressure: constant 0.5 or 0 means a pressure-less device', () => { + assert.equal(hasRealPressure([]), false) + assert.equal(hasRealPressure([0, 0, 0.5, 10, 10, 0.5]), false) + assert.equal(hasRealPressure([0, 0, 0, 10, 10, 0]), false) + assert.equal(hasRealPressure([0, 0, 0, 10, 10, 0.5]), false) // mix of 0 and 0.5 is still pressure-less + assert.equal(hasRealPressure([0, 0, 0.5, 10, 10, 0.72]), true) + assert.equal(hasRealPressure([0, 0, 0.12]), true) +}) + +test('tap detection: whole gesture inside the drag threshold', () => { + const threshold = 4 // pen at zoom 1 + assert.equal(isTapStroke([10, 10, 0.5], threshold), true) // single point + assert.equal(isTapStroke([10, 10, 0.5, 10.5, 10.4, 0.5, 10.9, 10.2, 0.5], threshold), true) // micro jitter + assert.equal(isTapStroke([10, 10, 0.5, 10.5, 10.4, 0.5, 18, 12, 0.5], threshold), false) // real drag + // exactly at the threshold counts as a drag (threshold is exclusive) + assert.equal(isTapStroke([0, 0, 0.5, 4, 0, 0.5], 4), false) + assert.equal(isTapStroke([0, 0, 0.5, 3.99, 0, 0.5], 4), true) +}) + +test('tap detection requires short displacement AND a quick press', () => { + const threshold = 4 + const microJitter = [10, 10, 0.5, 10.5, 10.4, 0.5, 10.9, 10.2, 0.5] + // quick press inside the threshold → tap + assert.equal(isTapStroke(microJitter, threshold, 80), true) + // same tiny displacement but the pen rested: a deliberate tick stays a stroke + assert.equal(isTapStroke(microJitter, threshold, 400), false) + // boundary is inclusive on the duration + assert.equal(isTapStroke(microJitter, threshold, TAP_MAX_DURATION_MS), true) + assert.equal(isTapStroke(microJitter, threshold, TAP_MAX_DURATION_MS + 1), false) + // quick but beyond the drag threshold → drag, not tap + assert.equal(isTapStroke([0, 0, 0.5, 8, 0, 0.5], threshold, 50), false) + // no duration given → old displacement-only rule + assert.equal(isTapStroke(microJitter, threshold), true) +}) diff --git a/src/ink/tolerance.ts b/src/ink/tolerance.ts new file mode 100644 index 0000000..ba26e13 --- /dev/null +++ b/src/ink/tolerance.ts @@ -0,0 +1,66 @@ +/** + * Per-pointer-type tolerances — pure functions. + * + * Idea learned from studying established whiteboard behaviour (not their code): + * mice want tight tolerances, fingers need room, pens sit in between. The drag + * threshold (tap vs. drag) and the eraser hit tolerance each come in three + * flavours, and the drag threshold is specified in DIP so it must be divided by + * the current zoom to become a world-space distance. + */ + +export type PointerKind = 'mouse' | 'touch' | 'pen' + +/** Map a DOM pointerType onto the three kinds; anything unknown behaves like a mouse. */ +export function toPointerKind(pointerType: string): PointerKind { + return pointerType === 'touch' || pointerType === 'pen' ? pointerType : 'mouse' +} + +/** Tap-vs-drag thresholds in DIP (mouse / touch / pen). */ +export const DRAG_THRESHOLD_DIP: Record = { mouse: 1, touch: 16, pen: 4 } + +/** Eraser hit tolerances in DIP (mouse / touch / pen). */ +export const HIT_TOLERANCE_DIP: Record = { mouse: 3, touch: 10, pen: 5 } + +/** + * Drag threshold in world units — DIP divided by the current zoom, so the + * on-screen distance stays constant while zooming. `scale` is the board's view + * scale (clamped to [0.2, 4] by the app). + */ +export function dragThresholdWorld(kind: PointerKind, scale: number): number { + return DRAG_THRESHOLD_DIP[kind] / scale +} + +/** Eraser hit tolerance in world units, same DIP ÷ zoom rule. */ +export function hitToleranceWorld(kind: PointerKind, scale: number): number { + return HIT_TOLERANCE_DIP[kind] / scale +} + +/** + * Does any sample carry a real pressure value? Constant 0.5 (main's "no + * pressure" fill) or constant 0 mean a pressure-less device — render and think + * of the stroke as pressure-free, never as pressure-varying. + */ +export function hasRealPressure(pts: number[]): boolean { + for (let i = 2; i < pts.length; i += 3) if (pts[i] !== 0.5 && pts[i] !== 0) return true + return false +} + +/** A press shorter than this counts as a tap even if it barely moved — deliberate short ticks take longer. */ +export const TAP_MAX_DURATION_MS = 250 + +/** + * Is this stroke a tap rather than a drag? Two conditions, both required: + * every sample stays within `thresholdWorld` of the pen-down point AND the + * press was quick (≤ TAP_MAX_DURATION_MS) — a slow, deliberate short tick stays + * a stroke. `durationMs` is the press duration (pointerdown → pointerup); + * without it the old displacement-only rule applies. Single-point strokes are + * always taps. + */ +export function isTapStroke(pts: number[], thresholdWorld: number, durationMs?: number): boolean { + const x0 = pts[0] + const y0 = pts[1] + for (let i = 0; i < pts.length; i += 3) { + if (Math.hypot(pts[i] - x0, pts[i + 1] - y0) >= thresholdWorld) return false + } + return durationMs === undefined || durationMs <= TAP_MAX_DURATION_MS +} diff --git a/src/ocr/comer/ort-compat.d.ts b/src/ocr/comer/ort-compat.d.ts new file mode 100644 index 0000000..8928436 --- /dev/null +++ b/src/ocr/comer/ort-compat.d.ts @@ -0,0 +1,4 @@ +// Types for the non-SIMD fallback runtime (npm alias of onnxruntime-web 1.18). That release ships +// ambient `declare module 'onnxruntime-web'` typings that would shadow 1.22's, so tsconfig maps the +// alias here. The runtime API used (env.wasm, InferenceSession, Tensor) is the same in both. +export * from 'onnxruntime-web/wasm' diff --git a/src/ocr/comer/web.ts b/src/ocr/comer/web.ts index c969a9c..adccca3 100644 --- a/src/ocr/comer/web.ts +++ b/src/ocr/comer/web.ts @@ -6,9 +6,12 @@ import { vocabFromJson, type Vocab } from './source.ts' import type { InkStroke } from './preprocess.ts' import { assetUrl } from '../../lib/asset.ts' import { t } from '../../i18n/locale.ts' +import { ocrRuntime } from '../support.ts' const ENC = assetUrl('models/comer/encoder_int8.onnx') const DEC = assetUrl('models/comer/decoder_int8.onnx') +// onnxruntime-web 1.18 (non-SIMD fallback) has no Trilu kernel; same weights, Trilu-free causal mask. +const DEC_COMPAT = assetUrl('models/comer/decoder_int8_compat.onnx') const VOCAB_URL = assetUrl('models/comer/vocab.json') let pending: Promise<{ encoder: ComerSession; decoder: ComerSession; vocab: Vocab }> | null = null @@ -37,26 +40,45 @@ function load() { return pending } -async function loadSessions() { +type Ort = typeof import('onnxruntime-web/wasm') + +async function loadRuntime(): Promise<{ ort: Ort; decoderUrl: string; sequential: boolean }> { + const runtime = ocrRuntime() + if (runtime === 'none') throw new Error(t('ocrUnsupported')) + if (runtime === 'compat') { + // WebKit before iOS / iPadOS 16.4: no WASM SIMD. Same models on the plain `ort-wasm.wasm`. + const ort: Ort = await import('onnxruntime-web-nosimd/wasm') + ort.env.wasm.numThreads = 1 + ort.env.wasm.simd = false + ort.env.wasm.proxy = false + ort.env.wasm.wasmPaths = assetUrl('ort-compat/') + return { ort, decoderUrl: DEC_COMPAT, sequential: true } + } const ort = await import('onnxruntime-web/wasm') ort.env.wasm.numThreads = 1 ort.env.wasm.simd = true ort.env.wasm.wasmPaths = assetUrl('ort/') - const [vocabRes, encRes, decRes] = await Promise.all([fetch(VOCAB_URL), fetch(ENC), fetch(DEC)]) + return { ort, decoderUrl: DEC, sequential: false } +} + +async function loadSessions() { + const { ort, decoderUrl, sequential } = await loadRuntime() + const [vocabRes, encRes, decRes] = await Promise.all([fetch(VOCAB_URL), fetch(ENC), fetch(decoderUrl)]) if (!vocabRes.ok || !encRes.ok || !decRes.ok) throw new Error(t('modelFiles')) const vocab = vocabFromJson(await vocabRes.json()) const opts = { executionProviders: ['wasm' as const] } - const [encoder, decoder] = await Promise.all([ - ort.InferenceSession.create(await encRes.arrayBuffer(), opts), - ort.InferenceSession.create(await decRes.arrayBuffer(), opts), - ]) - return { encoder: wrap(encoder as never), decoder: wrap(decoder as never), vocab } + const [encBytes, decBytes] = [await encRes.arrayBuffer(), await decRes.arrayBuffer()] + // compat: one at a time, so the 1.18 runtime initialises its WASM once and peak memory stays low + const [encoder, decoder] = sequential + ? [await ort.InferenceSession.create(encBytes, opts), await ort.InferenceSession.create(decBytes, opts)] + : await Promise.all([ort.InferenceSession.create(encBytes, opts), ort.InferenceSession.create(decBytes, opts)]) + return { encoder: wrap(ort, encoder as never), decoder: wrap(ort, decoder as never), vocab } } -function wrap(session: { run: (feeds: Record) => Promise void }>> }): ComerSession { +function wrap(ort: Ort, session: { run: (feeds: Record) => Promise void }>> }): ComerSession { return { async run(feeds) { - const ort = await import('onnxruntime-web/wasm') + // tensors must come from the same runtime as the session const mapped: Record = {} for (const [name, tensor] of Object.entries(feeds)) { mapped[name] = new ort.Tensor(tensor.type, tensor.data as never, tensor.dims) diff --git a/src/ocr/support.ts b/src/ocr/support.ts new file mode 100644 index 0000000..244ec4f --- /dev/null +++ b/src/ocr/support.ts @@ -0,0 +1,60 @@ +/** + * Which CoMER runtime this WebView can run. + * + * - `simd`: onnxruntime-web 1.22 (SIMD WebAssembly). Desktop, Android and iOS 16.4+. + * - `compat`: WebKit before iOS / iPadOS 16.4 has no WASM SIMD. onnxruntime-web 1.18 is the last + * release with a plain `ort-wasm.wasm`; it runs the same INT8 models (decoder with a Trilu-free + * causal mask), several times slower. Loaded only when the SIMD probe fails, or when forced with + * `?ocr-compat=1` / localStorage `mathscrap.ocr-compat` = `1` for testing. + * - `none`: no WebAssembly at all. Recognition is unavailable; ink and everything else keep working. + */ +export type OcrRuntime = 'simd' | 'compat' | 'none' + +const SIMD_PROBE = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]) +const MVP_PROBE = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) + +export const OCR_COMPAT_PARAM = 'ocr-compat' +export const OCR_COMPAT_STORAGE_KEY = 'mathscrap.ocr-compat' + +interface WasmLike { + validate?: (bytes: Uint8Array) => boolean +} + +const truthy = (v: string | null | undefined) => v != null && v !== '' && !(v === '0' || v === 'false' || v === 'off') + +/** Pure: choose a runtime from the probes and the dev override. */ +export function pickOcrRuntime(wasm: WasmLike | undefined, forceCompat: boolean): OcrRuntime { + const validate = (bytes: Uint8Array) => { + try { + return typeof wasm?.validate === 'function' && wasm.validate(bytes) + } catch { + return false + } + } + if (!validate(MVP_PROBE)) return 'none' + if (forceCompat) return 'compat' + return validate(SIMD_PROBE) ? 'simd' : 'compat' +} + +function forcedCompat(): boolean { + try { + const search = (globalThis as { location?: { search?: string } }).location?.search ?? '' + const param = new URLSearchParams(search).get(OCR_COMPAT_PARAM) + if (param != null) return truthy(param) + return truthy((globalThis as { localStorage?: { getItem: (key: string) => string | null } }).localStorage?.getItem(OCR_COMPAT_STORAGE_KEY)) + } catch { + return false + } +} + +let cached: OcrRuntime | null = null + +export function ocrRuntime(): OcrRuntime { + cached ??= pickOcrRuntime((globalThis as { WebAssembly?: WasmLike }).WebAssembly, forcedCompat()) + return cached +} + +/** False only without WebAssembly. Missing SIMD falls back to the compat runtime. */ +export function ocrSupported(): boolean { + return ocrRuntime() !== 'none' +} diff --git a/src/version.ts b/src/version.ts index c63a6e5..a29c8dc 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,3 @@ /** Installed-app metadata. Keep in step with package.json and src-tauri/tauri.conf.json. */ export const APP_NAME = 'MathScrap' -export const APP_VERSION = '0.0.1' +export const APP_VERSION = '0.0.2' diff --git a/src/wasm/pkg/package.json b/src/wasm/pkg/package.json index 954e73a..add647e 100644 --- a/src/wasm/pkg/package.json +++ b/src/wasm/pkg/package.json @@ -2,7 +2,7 @@ "name": "mathcore", "type": "module", "description": "Fast math helpers (parse, sample, solve, geometry inference) for the MathScrap kraft notebook, compiled to WASM.", - "version": "0.0.1", + "version": "0.0.2", "license": "Apache-2.0", "files": [ "mathcore_bg.wasm", diff --git a/tsconfig.app.json b/tsconfig.app.json index d331d7e..72a8ec2 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -25,6 +25,9 @@ "paths": { "@/*": [ "./src/*" + ], + "onnxruntime-web-nosimd/wasm": [ + "./src/ocr/comer/ort-compat.d.ts" ] } }, diff --git a/tsconfig.node.json b/tsconfig.node.json index f920478..a31b78c 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -12,6 +12,9 @@ "verbatimModuleSyntax": true, "moduleDetection": "force", "noEmit": true, + "paths": { + "onnxruntime-web-nosimd/wasm": ["./src/ocr/comer/ort-compat.d.ts"] + }, /* Linting */ "noUnusedLocals": true, diff --git a/vite.config.ts b/vite.config.ts index e636812..96a905e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -15,18 +15,31 @@ function ortFilesIn(dir: string): string[] { }) } +/** + * Non-SIMD fallback for WebKit before iOS / iPadOS 16.4: onnxruntime-web 1.18's plain `ort-wasm.wasm` + * (npm alias `onnxruntime-web-nosimd`). Fetched only when the SIMD probe fails or `?ocr-compat=1`. + */ +const ORT_COMPAT_FILES = ['ort-wasm.wasm'] + /** Serve ONNX Runtime's WASM next to the page so the recognizer can load it on LAN. */ function ortRuntime(): Plugin { const dist = path.resolve('node_modules/onnxruntime-web/dist') + const compatDist = path.resolve('node_modules/onnxruntime-web-nosimd/dist') const files = () => ortFilesIn(dist) const serve = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => { const url = (req.url ?? '').split('?')[0] ?? '' - if (!url.startsWith('/ort/')) return next() - const name = url.slice('/ort/'.length) - if (!files().includes(name)) return next() + let file: string | null = null + if (url.startsWith('/ort/')) { + const name = url.slice('/ort/'.length) + if (files().includes(name)) file = path.join(dist, name) + } else if (url.startsWith('/ort-compat/')) { + const name = url.slice('/ort-compat/'.length) + if (ORT_COMPAT_FILES.includes(name)) file = path.join(compatDist, name) + } + if (!file) return next() res.statusCode = 200 - res.setHeader('content-type', name.endsWith('.wasm') ? 'application/wasm' : 'text/javascript') - fs.createReadStream(path.join(dist, name)).pipe(res) + res.setHeader('content-type', file.endsWith('.wasm') ? 'application/wasm' : 'text/javascript') + fs.createReadStream(file).pipe(res) } return { name: 'ort-runtime', @@ -37,9 +50,13 @@ function ortRuntime(): Plugin { server.middlewares.use(serve) }, writeBundle(options) { - const dir = path.join(options.dir ?? path.resolve('dist'), 'ort') + const out = options.dir ?? path.resolve('dist') + const dir = path.join(out, 'ort') fs.mkdirSync(dir, { recursive: true }) for (const name of files()) fs.copyFileSync(path.join(dist, name), path.join(dir, name)) + const compat = path.join(out, 'ort-compat') + fs.mkdirSync(compat, { recursive: true }) + for (const name of ORT_COMPAT_FILES) fs.copyFileSync(path.join(compatDist, name), path.join(compat, name)) }, } } @@ -60,6 +77,9 @@ export default defineConfig({ port: 47322, }, build: { + // iOS builds run in WKWebView down to iPadOS 15, so lower syntax and CSS for Safari 15 there. + // Other platforms keep Vite's default target. Tauri sets TAURI_ENV_PLATFORM for beforeBuildCommand. + ...(process.env.TAURI_ENV_PLATFORM === 'ios' ? { target: ['es2020', 'safari15'], cssTarget: ['safari15'] } : {}), // Plotly (~4.6 MB) is its own lazily imported chunk, loaded only when a plot opens. chunkSizeWarningLimit: 5000, },