diff --git a/.github/workflows/adhoc-mac-build.yml b/.github/workflows/adhoc-mac-build.yml index 325ab73a847..03d2c76ccc0 100644 --- a/.github/workflows/adhoc-mac-build.yml +++ b/.github/workflows/adhoc-mac-build.yml @@ -33,6 +33,13 @@ name: Adhoc macOS Dev Build # Contents: Read and write. The secret names below are historical — one App, one # private key, both dev-channel repos — and rotating it stays a single operation. # Provision with `bash config/scripts/setup-hourly-release-token.sh`. +# +# The requested ref is vetted before checkout: it must be a branch or tag of this +# repo, or a commit reachable from one. PR refs are refused outright — this +# workflow runs the checked-out code next to MAC_CERTS and the notary password, +# so "just build that community PR" must not become a way to hand fork code the +# release identity. A branch here always belongs to someone with write access, +# which is the same trust the dispatch button itself already requires. on: workflow_dispatch: @@ -45,7 +52,7 @@ on: # than the one the workflow file itself is read from — normally leave the # picker on main and name your branch here, so a stale copy of this # workflow on an old branch is not what runs. - description: 'Branch, tag, or SHA to build (default: the branch selected above)' + description: 'Branch, tag, or SHA to build — must live in stablyai/orca; PR refs are refused (default: the branch selected above)' required: false default: '' type: string @@ -77,6 +84,14 @@ env: jobs: build-adhoc-mac: if: github.repository == 'stablyai/orca' + # Why an environment: it gives the signing/notary/App secrets somewhere to + # live that a stale copy of this workflow on an old branch cannot reach. + # Referencing it is a no-op until repo settings give it teeth; the intended + # follow-up is to move MAC_CERTS, MAC_CERTS_PASSWORD, APPLE_ID, + # APPLE_APP_SPECIFIC_PASSWORD, APPLE_TEAM_ID, HOURLY_RELEASE_APP_ID, and + # HOURLY_RELEASE_APP_PRIVATE_KEY into it, then pin its deployment branch + # policy to main so only main's copy of this file can read them. + environment: adhoc-mac-build runs-on: blacksmith-6vcpu-macos-15 # Why 150: it must exceed the worst case the retry budgets below can produce # (install 3x10 + publish 2x45 = 120, plus ~25 for checkout/build/verify), or @@ -85,6 +100,57 @@ jobs: env: NODE_OPTIONS: --max-old-space-size=4096 steps: + # Why vet before checkout: everything after this step runs the checked-out + # code with release signing credentials in reach. Branches and tags of this + # repo are the intended audience; refs/pull/* would smuggle in fork code, + # and a raw SHA is only accepted when some branch or tag of this repo can + # actually reach it. Resolving to a pinned SHA here also means the commit + # that was vetted is the commit that gets checked out — a push to the + # branch between the two steps cannot swap it. + - name: Vet the requested ref + id: vetted + shell: bash + env: + REQUESTED_REF: ${{ inputs.ref || github.ref_name }} + REPO_URL: https://github.com/${{ github.repository }} + run: | + set -euo pipefail + case "$REQUESTED_REF" in + refs/pull/*|pull/*) + echo "::error::Refusing to build PR ref '$REQUESTED_REF': this workflow signs with release credentials, so it only builds branches, tags, or commits of stablyai/orca. Push the code to a branch of this repo instead." + exit 1 + ;; + esac + # Bare: a work-tree repo refuses to fetch over its own checked-out + # branch. tree:0 keeps the fetch to the commit graph — no trees, no + # blobs — so this stays cheap next to the build it fronts. + scratch="$RUNNER_TEMP/vet-requested-ref" + git init -q --bare "$scratch" + git -C "$scratch" fetch -q --filter=tree:0 "$REPO_URL" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' + # Branch first to keep actions/checkout's old tie-break: bare + # rev-parse would prefer the tag when a branch shares its name. + sha="" + for cand in "refs/heads/$REQUESTED_REF" "refs/tags/$REQUESTED_REF" "$REQUESTED_REF"; do + if sha="$(git -C "$scratch" rev-parse --verify --quiet "$cand^{commit}")"; then + break + fi + sha="" + done + if [[ -z "$sha" ]]; then + echo "::error::'$REQUESTED_REF' does not resolve to a branch, tag, or commit of stablyai/orca." + exit 1 + fi + # The object resolving locally is not proof a branch or tag reaches + # it: a partial clone can lazily fetch a bare SHA on demand, and + # GitHub serves PR-only commits by SHA. Reachability is the actual + # trust test. + if [[ -z "$(git -C "$scratch" for-each-ref --contains "$sha" refs/heads refs/tags | head -1)" ]]; then + echo "::error::Commit $REQUESTED_REF is not reachable from any branch or tag of stablyai/orca; refusing to build it with release credentials." + exit 1 + fi + echo "Vetted $REQUESTED_REF -> $sha" + echo "sha=$sha" >>"$GITHUB_OUTPUT" + - name: Checkout the requested ref uses: actions/checkout@v6 with: @@ -92,7 +158,7 @@ jobs: # build code that has not landed, and the workflow definition itself # always comes from the dispatch ref — naming the branch here instead # applies main's current copy of this file to an arbitrary branch. - ref: ${{ inputs.ref || github.ref_name }} + ref: ${{ steps.vetted.outputs.sha }} fetch-depth: 0 # This job only reads stablyai/orca and never pushes; every write goes # to the adhoc repo through a minted App token passed by env. Not @@ -146,17 +212,26 @@ jobs: env: REF: ${{ inputs.ref || github.ref_name }} LABEL: ${{ inputs.label }} + MAIN_REPO_TOKEN: ${{ github.token }} run: | set -euo pipefail - # Why this check: the version script is read from the branch being built, + # Why this check: the version scripts are read from the branch being built, # not from main, so a branch cut before the adhoc channel landed has no - # copy of it. Say that plainly instead of failing with a module-not-found. - if [[ ! -f config/scripts/adhoc-build-version.mjs ]]; then - echo "::error::$REF has no config/scripts/adhoc-build-version.mjs; rebase it onto a main that has the adhoc channel." - exit 1 - fi + # copy of them. Say that plainly instead of failing with a module-not-found. + for script in adhoc-build-version dev-channel-base-version; do + if [[ ! -f "config/scripts/$script.mjs" ]]; then + echo "::error::$REF has no config/scripts/$script.mjs; rebase it onto a main that has the adhoc channel." + exit 1 + fi + done echo "head_sha=$(git rev-parse HEAD)" >>"$GITHUB_OUTPUT" - ORCA_ADHOC_LABEL="${LABEL:-$REF}" node config/scripts/adhoc-build-version.mjs \ + # Why the main repo's tags: package.json on a branch is as stale as the + # main it forked from, and stable patches never merge back into it. + published="$(GH_TOKEN="$MAIN_REPO_TOKEN" gh release list \ + --repo "$GITHUB_REPOSITORY" --limit 100 --exclude-drafts \ + --json tagName --jq '.[].tagName' || true)" + ORCA_PUBLISHED_VERSIONS="$published" ORCA_ADHOC_LABEL="${LABEL:-$REF}" \ + node config/scripts/adhoc-build-version.mjs \ >"$RUNNER_TEMP/adhoc-identity.txt" if ! grep -q '^name=' "$RUNNER_TEMP/adhoc-identity.txt"; then echo "::error::adhoc-build-version.mjs emitted no release name; $REF's copy of the script is out of sync with this workflow." diff --git a/.github/workflows/hourly-mac-build.yml b/.github/workflows/hourly-mac-build.yml index ebe544436a6..bc3c5a8afff 100644 --- a/.github/workflows/hourly-mac-build.yml +++ b/.github/workflows/hourly-mac-build.yml @@ -179,6 +179,7 @@ jobs: shell: bash env: GH_TOKEN: ${{ steps.app_token.outputs.token }} + MAIN_REPO_TOKEN: ${{ github.token }} run: | set -euo pipefail # Why read the highest number off existing titles rather than counting @@ -195,7 +196,19 @@ jobs: --jq '[.[] | (.name // "") | capture(" • (?[0-9]+) • ")? | .n | tonumber] | max // 0')" build_number=$(( last_number + 1 )) echo "Hourly build number $build_number (previous high: $last_number)" - ORCA_HOURLY_BUILD_NUMBER="$build_number" node config/scripts/hourly-build-version.mjs \ + # Why the main repo's tags decide the base version rather than + # package.json: main's version only moves on `release:` commits, and + # stable patches are cut from release branches that never merge back, so + # package.json can sit several patches behind what users are running. A + # separate token because GH_TOKEN above is the App's, scoped to the + # hourly repo. Empty on failure — the script then falls back to + # package.json, which is stale but never wrong enough to fail a build. + published="$(GH_TOKEN="$MAIN_REPO_TOKEN" gh release list \ + --repo "$GITHUB_REPOSITORY" --limit 100 --exclude-drafts \ + --json tagName --jq '.[].tagName' || true)" + echo "Highest published tag seen: $(head -1 <<<"$published")" + ORCA_PUBLISHED_VERSIONS="$published" \ + ORCA_HOURLY_BUILD_NUMBER="$build_number" node config/scripts/hourly-build-version.mjs \ >"$RUNNER_TEMP/hourly-identity.txt" # Why check rather than trust: the checkout above pins `ref: main`, but a # workflow_dispatch runs this file from whatever branch was dispatched. A diff --git a/.gitignore b/.gitignore index 2918ae32a69..b1de9292f1a 100644 --- a/.gitignore +++ b/.gitignore @@ -100,6 +100,7 @@ docs/** !docs/reference/headless-linux-server.md !docs/reference/linux-glibc-compatibility.md !docs/reference/relay-grace-time-reconfiguration.md +!docs/reference/windows-setup-shell.md # Stably CLI (only docs/ are tracked) .stably/* diff --git a/AGENTS.md b/AGENTS.md index bfb1617f8ea..6bc54a6f5c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,7 @@ Orca targets macOS, Linux, and Windows. Keep all platform-dependent behavior beh - **Keyboard shortcuts**: Never hardcode `e.metaKey`. Use a platform check (`navigator.userAgent.includes('Mac')`) to pick `metaKey` on Mac and `ctrlKey` on Linux/Windows. Electron menu accelerators should use `CmdOrCtrl`. - **Shortcut labels in UI**: Display `⌘` / `⇧` on Mac and `Ctrl+` / `Shift+` on other platforms. - **File paths**: Use `path.join` or Electron/Node path utilities — never assume `/` or `\`. +- **Windows setup scripts**: the setup/issue-command runner is a `.cmd` batch file unless the script starts with a `#!` line — never derive that from the user's terminal-shell preference, and never launch a `.cmd` runner with a bare `cmd.exe /c` from a Git Bash pane (MSYS rewrites the `/c`). See [`docs/reference/windows-setup-shell.md`](./docs/reference/windows-setup-shell.md). - **Linux native modules**: keep the glibc floor at Ubuntu 20.04 / glibc 2.31. A module compiled from source on a newer runner can reference symbol versions absent on the floor and crash the app on startup. See [`docs/reference/linux-glibc-compatibility.md`](./docs/reference/linux-glibc-compatibility.md); packaging fails if a bundled native binary needs newer glibc. ## SSH Use Case diff --git a/README.md b/README.md index b161a52b71a..670b54e2835 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Monitor and steer your agents from your phone — get notified when an agent finishes and send follow-ups from anywhere. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.36](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.36/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.37](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.37/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -230,7 +230,7 @@ yay -S stably-orca-bin Pair with your desktop app to monitor and steer your agents from your phone. - **iOS:** [Download on the App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) or [join TestFlight](https://testflight.apple.com/join/YjeGMQBA) -- **Android:** [Download APK 0.0.36](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.36/app-release.apk) +- **Android:** [Download APK 0.0.37](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.37/app-release.apk) --- diff --git a/build-plugins/plain-node-entry-guard.ts b/build-plugins/plain-node-entry-guard.ts index a7ad171a402..13499118b65 100644 --- a/build-plugins/plain-node-entry-guard.ts +++ b/build-plugins/plain-node-entry-guard.ts @@ -26,6 +26,23 @@ const PLAIN_NODE_ENTRY_NAMES = [ 'codex/codex-app-server-grant-entry' ] as const +// Entries executed as worker threads of the main process. Electron's module is +// not registered on worker threads, so require("electron") throws +// "Cannot find module 'electron'" there too (verified on Electron 43) and kills +// the worker at startup. These carry hand-written "must stay electron-free" +// comments, which is convention, not enforcement — and the port-scan worker in +// particular sits one import away from a client module that deliberately does +// require electron. +const WORKER_THREAD_ENTRY_NAMES = [ + 'stt-worker', + 'warp-theme-parser-worker', + 'session-scanner-opencode-sqlite-worker-entry', + 'main-thread-hang-watchdog-entry', + 'port-scan-command-worker-entry' +] as const + +type EntryRuntime = 'plain-Node process' | 'worker thread' + const ELECTRON_REQUIRE_RE = /require\(\s*["']electron["']\s*\)/ function collectReachableChunks( @@ -56,13 +73,14 @@ function collectReachableChunks( function assertNoElectronRequire( entryName: string, entry: OutputChunk, - byFileName: Map + byFileName: Map, + runtime: EntryRuntime = 'plain-Node process' ): void { for (const chunk of collectReachableChunks(entry, byFileName)) { if (ELECTRON_REQUIRE_RE.test(chunk.code)) { throw new Error( `[plain-node-entry-guard] "${entryName}" reaches chunk "${chunk.fileName}" that ` + - `requires electron. "${entryName}" runs as a plain-Node process, where ` + + `requires electron. "${entryName}" runs as a ${runtime}, where ` + `require("electron") throws MODULE_NOT_FOUND and kills it at startup (the ` + `v1.4.129-rc.1 daemon outage). Keep electron imports out of its module graph.` ) @@ -125,7 +143,14 @@ export function createPlainNodeEntryGuardPlugin(): Plugin { for (const entryName of PLAIN_NODE_ENTRY_NAMES) { const entry = entryByName.get(entryName) if (entry) { - assertNoElectronRequire(entryName, entry, byFileName) + assertNoElectronRequire(entryName, entry, byFileName, 'plain-Node process') + } + } + + for (const entryName of WORKER_THREAD_ENTRY_NAMES) { + const entry = entryByName.get(entryName) + if (entry) { + assertNoElectronRequire(entryName, entry, byFileName, 'worker thread') } } diff --git a/config/knip.json b/config/knip.json index a48793b7902..cb929266ff3 100644 --- a/config/knip.json +++ b/config/knip.json @@ -10,6 +10,7 @@ "src/main/speech/stt-worker.ts", "src/main/warp-themes/warp-theme-parser-worker.ts", "src/main/ai-vault/session-scanner-opencode-sqlite-worker-entry.ts", + "src/main/ports/port-scan-command-worker-entry.ts", "src/main/ipc/parcel-watcher-process-entry.ts", "src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts", "src/main/codex/codex-app-server-grant-entry.ts", diff --git a/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch b/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch index eab0cd58452..caa96484d89 100644 --- a/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch +++ b/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch @@ -1,28 +1,64 @@ diff --git a/lib/addon-serialize.js b/lib/addon-serialize.js -index d669293d06d801ef472d5c2454ce86876e5c321f..96bb66cdc05289b6a7ce5ed64fc833624c885c57 100644 +index d669293d06d801ef472d5c2454ce86876e5c321f..18f72336a60d498f685e2cc32b7a09dbe16958e5 100644 --- a/lib/addon-serialize.js +++ b/lib/addon-serialize.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SerializeAddon=e():t.SerializeAddon=e()}(globalThis,()=>(()=>{"use strict";var t={992(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_ANSI_COLORS=void 0;const s=r(993);e.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const t=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],e=[0,95,135,175,215,255];for(let r=0;r<216;r++){const i=e[r/36%6|0],n=e[r/6%6|0],o=e[r%6];t.push({css:s.channels.toCss(i,n,o),rgba:s.channels.toRgba(i,n,o)})}for(let e=0;e<24;e++){const r=8+10*e;t.push({css:s.channels.toCss(r,r,r),rgba:s.channels.toRgba(r,r,r)})}return t})())},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=c,e.contrastRatio=f;let r=0,s=0,i=0,n=0;var o,l,a,u,h;function c(t){const e=t.toString(16);return e.length<2?"0"+e:e}function f(t,e){return t>>0},t.toColor=function(e,r,s,i){return{css:t.toCss(e,r,s,i),rgba:t.toRgba(e,r,s,i)}}}(o||(e.channels=o={})),function(t){function e(t,e){return n=Math.round(255*e),[r,s,i]=h.toChannels(t.rgba),{css:o.toCss(r,s,i,n),rgba:o.toRgba(r,s,i,n)}}t.blend=function(t,e){if(n=(255&e.rgba)/255,1===n)return{css:e.css,rgba:e.rgba};const l=e.rgba>>24&255,a=e.rgba>>16&255,u=e.rgba>>8&255,h=t.rgba>>24&255,c=t.rgba>>16&255,f=t.rgba>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),{css:o.toCss(r,s,i),rgba:o.toRgba(r,s,i)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,r){const s=h.ensureContrastRatio(t.rgba,e.rgba,r);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[r,s,i]=h.toChannels(e),{css:o.toCss(r,s,i),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,r){return n=255&t.rgba,e(t,n*r/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(l||(e.color=l={})),function(t){let e,l;try{const t=document.createElement("canvas");t.width=1,t.height=1;const r=t.getContext("2d",{willReadFrequently:!0});r&&(e=r,e.globalCompositeOperation="copy",l=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),o.toColor(r,s,i);case 5:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),n=parseInt(t.slice(4,5).repeat(2),16),o.toColor(r,s,i,n);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const a=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return r=parseInt(a[1],10),s=parseInt(a[2],10),i=parseInt(a[3],10),n=Math.round(255*(void 0===a[5]?1:parseFloat(a[5]))),o.toColor(r,s,i,n);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!l)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=l,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[r,s,i,n]=e.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(r,s,i,n),css:t}}}(a||(e.css=a={})),function(t){function e(t,e,r){const s=t/255,i=e/255,n=r/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(u||(e.rgb=u={})),function(t){function e(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h0||l>0||a>0);)o-=Math.max(0,Math.ceil(.1*o)),l-=Math.max(0,Math.ceil(.1*l)),a-=Math.max(0,Math.ceil(.1*a)),h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));return(o<<24|l<<16|a<<8|255)>>>0}function l(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h>>0}t.blend=function(t,e){if(n=(255&e)/255,1===n)return e;const l=e>>24&255,a=e>>16&255,u=e>>8&255,h=t>>24&255,c=t>>16&255,f=t>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),o.toRgba(r,s,i)},t.ensureContrastRatio=function(t,r,s){const i=u.relativeLuminance(t>>8),n=u.relativeLuminance(r>>8);if(f(i,n)>8));if(of(i,u.relativeLuminance(e>>8))?n:e}return n}const o=l(t,r,s),a=f(i,u.relativeLuminance(o>>8));if(af(i,u.relativeLuminance(n>>8))?o:n}return o}},t.reduceLuminance=e,t.increaseLuminance=l,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(h||(e.rgba=h={}))}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s](n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.HTMLSerializeHandler=t.SerializeAddon=void 0;const e=r(992);function i(t,e,r){return Math.max(e,Math.min(t,r))}class n{constructor(t){this._buffer=t}serialize(t,e){const r=this._buffer.getNullCell(),s=this._buffer.getNullCell();let i=r;const n=t.start.y,o=t.end.y,l=t.start.x,a=t.end.x;this._beforeSerialize(o-n,n,o);for(let e=n;e<=o;e++){const n=this._buffer.getLine(e);if(n){const o=e===t.start.y?l:0,u=e===t.end.y?a:n.length;for(let t=o;t0&&!l(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let r="";if(!e){t-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);const e=this._buffer.getLine(t),s=this._buffer.getLine(t+1);if(s.isWrapped){r="";const i=e.getCell(e.length-1,this._thisRowLastChar),n=e.getCell(e.length-2,this._thisRowLastSecondChar),o=s.getCell(0,this._nextRowFirstChar),a=o.getWidth()>1;let u=!1;(o.getChars()&&a?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||0===i.getWidth())&&l(i,o)&&(u=!0),a&&(n.getChars()||0===n.getWidth())&&l(i,o)&&l(n,o)&&(u=!0)),u||(r="-".repeat(this._nullCellCount+1),r+="",this._nullCellCount>0&&(r+="",r+=`[${e.length-this._nullCellCount}C`,r+=`[${this._nullCellCount}X`,r+=`[${e.length-this._nullCellCount}D`,r+=""),this._lastContentCursorRow=t+1,this._lastContentCursorCol=0,this._lastCursorRow=t+1,this._lastCursorCol=0)}else r="\r\n",this._lastCursorRow=t+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(t,e){const r=[];if(h(t,e))return r;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n)if(t.isAttributeDefault())e.isAttributeDefault()||r.push(0);else{if(s){const e=t.getFgColor();t.isFgRGB()?r.push(38,2,e>>>16&255,e>>>8&255,255&e):t.isFgPalette()?e>=16?r.push(38,5,e):r.push(8&e?90+(7&e):30+(7&e)):r.push(39)}if(i){const e=t.getBgColor();t.isBgRGB()?r.push(48,2,e>>>16&255,e>>>8&255,255&e):t.isBgPalette()?e>=16?r.push(48,5,e):r.push(8&e?100+(7&e):40+(7&e)):r.push(49)}if(n){if(t.isInverse()!==e.isInverse()&&r.push(t.isInverse()?7:27),t.isBold()!==e.isBold()&&r.push(t.isBold()?1:22),a(t,e))t.isUnderline()!==e.isUnderline()&&r.push(t.isUnderline()?4:24);else{const e=t.getUnderlineStyle();if(0===e)r.push(24);else if(1===e&&t.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+e),!t.isUnderlineColorDefault()){const e=t.getUnderlineColor();t.isUnderlineColorRGB()?r.push("58:2::"+(e>>>16&255)+":"+(e>>>8&255)+":"+(255&e)):r.push("58:5:"+e)}}t.isOverline()!==e.isOverline()&&r.push(t.isOverline()?53:55),t.isBlink()!==e.isBlink()&&r.push(t.isBlink()?5:25),t.isInvisible()!==e.isInvisible()&&r.push(t.isInvisible()?8:28),t.isItalic()!==e.isItalic()&&r.push(t.isItalic()?3:23),t.isDim()!==e.isDim()&&r.push(t.isDim()?2:22),t.isStrikethrough()!==e.isStrikethrough()&&r.push(t.isStrikethrough()?9:29)}}return r}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,this._cursorStyle);if(i?!l(this._cursorStyle,t):n.length>0){this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`[${n.join(";")}m`;const t=this._buffer.getLine(r);void 0!==t&&(t.getCell(s,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=s)}i?this._nullCellCount+=t.getWidth():(this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=t.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s+t.getWidth())}_serializeString(t){let e=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(e=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let t=0;t{t>0?r+=`[${t}C`:t<0&&(r+=`[${-t}D`)};(t!==this._lastCursorRow||e!==this._lastCursorCol)&&((s=t-this._lastCursorRow)>0?r+=`[${s}B`:s<0&&(r+=`[${-s}A`),i(e-this._lastCursorCol))}var s;const i=this._terminal._core._inputHandler._curAttrData,n=this._diffStyle(i,this._cursorStyle);return n.length>0&&(r+=`[${n.join(";")}m`),r}}t.SerializeAddon=class{activate(t){this._terminal=t}_serializeBufferByScrollback(t,e,r){const s=e.length,n=void 0===r?s:i(r+t.rows,0,s);return this._serializeBufferByRange(t,e,{start:s-n,end:s-1},!1)}_serializeBufferByRange(t,e,r,s){return new c(e,t).serialize({start:{x:0,y:"number"==typeof r.start?r.start:r.start.line},end:{x:t.cols,y:"number"==typeof r.end?r.end:r.end.line}},s)}_serializeBufferAsHTML(t,e){const r=t.buffer.active,s=new f(r,t,e),n=e.onlySelection??!1,o=e.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:t.cols,y:(o.endLine,o.endLine)}});if(!n){const n=r.length,o=e.scrollback,l=void 0===o?n:i(o+t.rows,0,n);return s.serialize({start:{x:0,y:n-l},end:{x:t.cols,y:n-1}})}const l=this._terminal?.getSelectionPosition();return void 0!==l?s.serialize({start:{x:l.start.x,y:l.start.y},end:{x:l.end.x,y:l.end.y}}):""}_serializeScrollRegion(t){const e=t._core.buffer,r=e.scrollTop,s=e.scrollBottom;return 0!==r||s!==t.rows-1?`[${r+1};${s+1}r`:""}_serializeModes(t){let e="";const r=t.modes;if(r.applicationCursorKeysMode&&(e+="[?1h"),r.applicationKeypadMode&&(e+="[?66h"),r.bracketedPasteMode&&(e+="[?2004h"),r.insertMode&&(e+=""),r.originMode&&(e+="[?6h"),r.reverseWraparoundMode&&(e+="[?45h"),r.sendFocusMode&&(e+="[?1004h"),!1===r.wraparoundMode&&(e+="[?7l"),"none"!==r.mouseTrackingMode)switch(r.mouseTrackingMode){case"x10":e+="[?9h";break;case"vt200":e+="[?1000h";break;case"drag":e+="[?1002h";break;case"any":e+="[?1003h"}return r.showCursor||(e+="[?25l"),e}serialize(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=t?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,t.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,t?.scrollback);return t?.excludeAltBuffer||"alternate"!==this._terminal.buffer.active.type||(e+=`[?1049h${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),t?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,t??{})}dispose(){}};class f extends n{constructor(t,r,s){super(t),this._terminal=r,this._options=s,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=e.DEFAULT_ANSI_COLORS}_beforeSerialize(t,e,r){this._htmlContent+="\x3c!--StartFragment--\x3e
";let s="#000000",i="#ffffff";this._options.includeGlobalBackground&&(s=this._terminal.options.theme?.foreground??"#ffffff",i=this._terminal.options.theme?.background??"#000000");const n=[];n.push("color: "+s+";"),n.push("background-color: "+i+";"),n.push("font-family: "+this._terminal.options.fontFamily+";"),n.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
\x3c!--EndFragment--\x3e"}_rowEnd(t,e){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(t,e){const r=e?t.getFgColor():t.getBgColor();return(e?t.isFgRGB():t.isBgRGB())?"#"+[r>>16&255,r>>8&255,255&r].map(t=>t.toString(16).padStart(2,"0")).join(""):(e?t.isFgPalette():t.isBgPalette())?this._ansiColors[r].css:void 0}_getUnderlineColor(t){if(t.isUnderlineColorDefault())return;const e=t.getUnderlineColor();return t.isUnderlineColorRGB()?"#"+[e>>16&255,e>>8&255,255&e].map(t=>t.toString(16).padStart(2,"0")).join(""):this._ansiColors[e].css}_getUnderlineStyle(t){switch(t.getUnderlineStyle()){case 1:default:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed"}}_diffStyle(t,e){const r=[];if(h(t,e))return;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n){const e=this._getHexColor(t,!0);e&&r.push("color: "+e+";");const s=this._getHexColor(t,!1);s&&r.push("background-color: "+s+";"),t.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),t.isBold()&&r.push("font-weight: bold;");const i=[];if(t.isUnderline()&&i.push(this._getUnderlineStyle(t)),t.isOverline()&&i.push("overline"),t.isStrikethrough()&&i.push("line-through"),t.isBlink()&&i.push("blink"),i.length>0&&r.push("text-decoration: "+i.join(" ")+";"),t.isUnderline()){const e=this._getUnderlineColor(t);e&&r.push("text-decoration-color: "+e+";")}return t.isInvisible()&&r.push("visibility: hidden;"),t.isItalic()&&r.push("font-style: italic;"),t.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,e);n&&(this._currentRow+=0===n.length?"":""),this._currentRow+=i?" ":function(t){switch(t){case"&":return"&";case"<":return"<"}return t}(t.getChars())}_serializeString(){return this._htmlContent}}t.HTMLSerializeHandler=f})(),s})()); -+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SerializeAddon=e():t.SerializeAddon=e()}(globalThis,()=>(()=>{"use strict";var t={992(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_ANSI_COLORS=void 0;const s=r(993);e.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const t=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],e=[0,95,135,175,215,255];for(let r=0;r<216;r++){const i=e[r/36%6|0],n=e[r/6%6|0],o=e[r%6];t.push({css:s.channels.toCss(i,n,o),rgba:s.channels.toRgba(i,n,o)})}for(let e=0;e<24;e++){const r=8+10*e;t.push({css:s.channels.toCss(r,r,r),rgba:s.channels.toRgba(r,r,r)})}return t})())},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=c,e.contrastRatio=f;let r=0,s=0,i=0,n=0;var o,l,a,u,h;function c(t){const e=t.toString(16);return e.length<2?"0"+e:e}function f(t,e){return t>>0},t.toColor=function(e,r,s,i){return{css:t.toCss(e,r,s,i),rgba:t.toRgba(e,r,s,i)}}}(o||(e.channels=o={})),function(t){function e(t,e){return n=Math.round(255*e),[r,s,i]=h.toChannels(t.rgba),{css:o.toCss(r,s,i,n),rgba:o.toRgba(r,s,i,n)}}t.blend=function(t,e){if(n=(255&e.rgba)/255,1===n)return{css:e.css,rgba:e.rgba};const l=e.rgba>>24&255,a=e.rgba>>16&255,u=e.rgba>>8&255,h=t.rgba>>24&255,c=t.rgba>>16&255,f=t.rgba>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),{css:o.toCss(r,s,i),rgba:o.toRgba(r,s,i)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,r){const s=h.ensureContrastRatio(t.rgba,e.rgba,r);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[r,s,i]=h.toChannels(e),{css:o.toCss(r,s,i),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,r){return n=255&t.rgba,e(t,n*r/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(l||(e.color=l={})),function(t){let e,l;try{const t=document.createElement("canvas");t.width=1,t.height=1;const r=t.getContext("2d",{willReadFrequently:!0});r&&(e=r,e.globalCompositeOperation="copy",l=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),o.toColor(r,s,i);case 5:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),n=parseInt(t.slice(4,5).repeat(2),16),o.toColor(r,s,i,n);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const a=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return r=parseInt(a[1],10),s=parseInt(a[2],10),i=parseInt(a[3],10),n=Math.round(255*(void 0===a[5]?1:parseFloat(a[5]))),o.toColor(r,s,i,n);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!l)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=l,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[r,s,i,n]=e.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(r,s,i,n),css:t}}}(a||(e.css=a={})),function(t){function e(t,e,r){const s=t/255,i=e/255,n=r/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(u||(e.rgb=u={})),function(t){function e(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h0||l>0||a>0);)o-=Math.max(0,Math.ceil(.1*o)),l-=Math.max(0,Math.ceil(.1*l)),a-=Math.max(0,Math.ceil(.1*a)),h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));return(o<<24|l<<16|a<<8|255)>>>0}function l(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h>>0}t.blend=function(t,e){if(n=(255&e)/255,1===n)return e;const l=e>>24&255,a=e>>16&255,u=e>>8&255,h=t>>24&255,c=t>>16&255,f=t>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),o.toRgba(r,s,i)},t.ensureContrastRatio=function(t,r,s){const i=u.relativeLuminance(t>>8),n=u.relativeLuminance(r>>8);if(f(i,n)>8));if(of(i,u.relativeLuminance(e>>8))?n:e}return n}const o=l(t,r,s),a=f(i,u.relativeLuminance(o>>8));if(af(i,u.relativeLuminance(n>>8))?o:n}return o}},t.reduceLuminance=e,t.increaseLuminance=l,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(h||(e.rgba=h={}))}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s](n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.HTMLSerializeHandler=t.SerializeAddon=void 0;const e=r(992);function i(t,e,r){return Math.max(e,Math.min(t,r))}class n{constructor(t){this._buffer=t}serialize(t,e){const r=this._buffer.getNullCell(),s=this._buffer.getNullCell();let i=r;const n=t.start.y,o=t.end.y,l=t.start.x,a=t.end.x;this._beforeSerialize(o-n,n,o);for(let e=n;e<=o;e++){const n=this._buffer.getLine(e);if(n){const o=e===t.start.y?l:0,u=e===t.end.y?a:n.length;for(let t=o;t0&&!l(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let r="";if(!e){t-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);const e=this._buffer.getLine(t),s=this._buffer.getLine(t+1);if(s.isWrapped){r="";const i=e.getCell(e.length-1,this._thisRowLastChar),n=e.getCell(e.length-2,this._thisRowLastSecondChar),o=s.getCell(0,this._nextRowFirstChar),a=o.getWidth()>1;let u=!1;(o.getChars()&&a?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||0===i.getWidth())&&l(i,o)&&(u=!0),a&&(n.getChars()||0===n.getWidth())&&l(i,o)&&l(n,o)&&(u=!0)),u||(r="-".repeat(this._nullCellCount+1),r+="",this._nullCellCount>0&&(r+="",r+=`[${e.length-this._nullCellCount}C`,r+=`[${this._nullCellCount}X`,r+=`[${e.length-this._nullCellCount}D`,r+=""),this._lastContentCursorRow=t+1,this._lastContentCursorCol=0,this._lastCursorRow=t+1,this._lastCursorCol=0)}else r="\r\n",this._lastCursorRow=t+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(t,e){const r=[];if(h(t,e))return r;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n)if(t.isAttributeDefault())e.isAttributeDefault()||r.push(0);else{if(s){const e=t.getFgColor();t.isFgRGB()?r.push(38,2,e>>>16&255,e>>>8&255,255&e):t.isFgPalette()?e>=16?r.push(38,5,e):r.push(8&e?90+(7&e):30+(7&e)):r.push(39)}if(i){const e=t.getBgColor();t.isBgRGB()?r.push(48,2,e>>>16&255,e>>>8&255,255&e):t.isBgPalette()?e>=16?r.push(48,5,e):r.push(8&e?100+(7&e):40+(7&e)):r.push(49)}if(n){if(t.isInverse()!==e.isInverse()&&r.push(t.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!t.isBold()||d&&!t.isDim();c&&r.push(22),t.isBold()&&(b||c)&&r.push(1),t.isDim()&&(d||c)&&r.push(2)}})(t.isBold()!==e.isBold(),t.isDim()!==e.isDim()),a(t,e))t.isUnderline()!==e.isUnderline()&&r.push(t.isUnderline()?4:24);else{const e=t.getUnderlineStyle();if(0===e)r.push(24);else if(1===e&&t.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+e),!t.isUnderlineColorDefault()){const e=t.getUnderlineColor();t.isUnderlineColorRGB()?r.push("58:2::"+(e>>>16&255)+":"+(e>>>8&255)+":"+(255&e)):r.push("58:5:"+e)}}t.isOverline()!==e.isOverline()&&r.push(t.isOverline()?53:55),t.isBlink()!==e.isBlink()&&r.push(t.isBlink()?5:25),t.isInvisible()!==e.isInvisible()&&r.push(t.isInvisible()?8:28),t.isItalic()!==e.isItalic()&&r.push(t.isItalic()?3:23),t.isStrikethrough()!==e.isStrikethrough()&&r.push(t.isStrikethrough()?9:29)}}return r}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,this._cursorStyle);if(i?!l(this._cursorStyle,t):n.length>0){this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`[${n.join(";")}m`;const t=this._buffer.getLine(r);void 0!==t&&(t.getCell(s,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=s)}i?this._nullCellCount+=t.getWidth():(this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=t.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s+t.getWidth())}_serializeString(t){let e=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(e=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let t=0;t{t>0?r+=`[${t}C`:t<0&&(r+=`[${-t}D`)};(t!==this._lastCursorRow||e!==this._lastCursorCol)&&((s=t-this._lastCursorRow)>0?r+=`[${s}B`:s<0&&(r+=`[${-s}A`),i(e-this._lastCursorCol))}var s;const i=this._terminal._core._inputHandler._curAttrData,n=this._diffStyle(i,this._cursorStyle);return n.length>0&&(r+=`[${n.join(";")}m`),r}}t.SerializeAddon=class{activate(t){this._terminal=t}_serializeBufferByScrollback(t,e,r){const s=e.length,n=void 0===r?s:i(r+t.rows,0,s);return this._serializeBufferByRange(t,e,{start:s-n,end:s-1},!1)}_serializeBufferByRange(t,e,r,s){return new c(e,t).serialize({start:{x:0,y:"number"==typeof r.start?r.start:r.start.line},end:{x:t.cols,y:"number"==typeof r.end?r.end:r.end.line}},s)}_serializeBufferAsHTML(t,e){const r=t.buffer.active,s=new f(r,t,e),n=e.onlySelection??!1,o=e.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:t.cols,y:(o.endLine,o.endLine)}});if(!n){const n=r.length,o=e.scrollback,l=void 0===o?n:i(o+t.rows,0,n);return s.serialize({start:{x:0,y:n-l},end:{x:t.cols,y:n-1}})}const l=this._terminal?.getSelectionPosition();return void 0!==l?s.serialize({start:{x:l.start.x,y:l.start.y},end:{x:l.end.x,y:l.end.y}}):""}_serializeScrollRegion(t){const e=t._core.buffer,r=e.scrollTop,s=e.scrollBottom;return 0!==r||s!==t.rows-1?`[${r+1};${s+1}r`:""}_serializeModes(t){let e="";const r=t.modes;if(r.applicationCursorKeysMode&&(e+="[?1h"),r.applicationKeypadMode&&(e+="[?66h"),r.bracketedPasteMode&&(e+="[?2004h"),r.insertMode&&(e+=""),r.originMode&&(e+="[?6h"),r.reverseWraparoundMode&&(e+="[?45h"),r.sendFocusMode&&(e+="[?1004h"),!1===r.wraparoundMode&&(e+="[?7l"),"none"!==r.mouseTrackingMode)switch(r.mouseTrackingMode){case"x10":e+="[?9h";break;case"vt200":e+="[?1000h";break;case"drag":e+="[?1002h";break;case"any":e+="[?1003h"}return r.showCursor||(e+="[?25l"),e}serialize(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=t?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,t.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,t?.scrollback);return t?.excludeAltBuffer||"alternate"!==this._terminal.buffer.active.type||(e+=`[?1049h${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),t?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,t??{})}dispose(){}};class f extends n{constructor(t,r,s){super(t),this._terminal=r,this._options=s,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=e.DEFAULT_ANSI_COLORS}_beforeSerialize(t,e,r){this._htmlContent+="\x3c!--StartFragment--\x3e
";let s="#000000",i="#ffffff";this._options.includeGlobalBackground&&(s=this._terminal.options.theme?.foreground??"#ffffff",i=this._terminal.options.theme?.background??"#000000");const n=[];n.push("color: "+s+";"),n.push("background-color: "+i+";"),n.push("font-family: "+this._terminal.options.fontFamily+";"),n.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
\x3c!--EndFragment--\x3e"}_rowEnd(t,e){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(t,e){const r=e?t.getFgColor():t.getBgColor();return(e?t.isFgRGB():t.isBgRGB())?"#"+[r>>16&255,r>>8&255,255&r].map(t=>t.toString(16).padStart(2,"0")).join(""):(e?t.isFgPalette():t.isBgPalette())?this._ansiColors[r].css:void 0}_getUnderlineColor(t){if(t.isUnderlineColorDefault())return;const e=t.getUnderlineColor();return t.isUnderlineColorRGB()?"#"+[e>>16&255,e>>8&255,255&e].map(t=>t.toString(16).padStart(2,"0")).join(""):this._ansiColors[e].css}_getUnderlineStyle(t){switch(t.getUnderlineStyle()){case 1:default:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed"}}_diffStyle(t,e){const r=[];if(h(t,e))return;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n){const e=this._getHexColor(t,!0);e&&r.push("color: "+e+";");const s=this._getHexColor(t,!1);s&&r.push("background-color: "+s+";"),t.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),t.isBold()&&r.push("font-weight: bold;");const i=[];if(t.isUnderline()&&i.push(this._getUnderlineStyle(t)),t.isOverline()&&i.push("overline"),t.isStrikethrough()&&i.push("line-through"),t.isBlink()&&i.push("blink"),i.length>0&&r.push("text-decoration: "+i.join(" ")+";"),t.isUnderline()){const e=this._getUnderlineColor(t);e&&r.push("text-decoration-color: "+e+";")}return t.isInvisible()&&r.push("visibility: hidden;"),t.isItalic()&&r.push("font-style: italic;"),t.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,e);n&&(this._currentRow+=0===n.length?"
":""),this._currentRow+=i?" ":function(t){switch(t){case"&":return"&";case"<":return"<"}return t}(t.getChars())}_serializeString(){return this._htmlContent}}t.HTMLSerializeHandler=f})(),s})()); ++!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SerializeAddon=e():t.SerializeAddon=e()}(globalThis,()=>(()=>{"use strict";var t={992(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_ANSI_COLORS=void 0;const s=r(993);e.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const t=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],e=[0,95,135,175,215,255];for(let r=0;r<216;r++){const i=e[r/36%6|0],n=e[r/6%6|0],o=e[r%6];t.push({css:s.channels.toCss(i,n,o),rgba:s.channels.toRgba(i,n,o)})}for(let e=0;e<24;e++){const r=8+10*e;t.push({css:s.channels.toCss(r,r,r),rgba:s.channels.toRgba(r,r,r)})}return t})())},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=c,e.contrastRatio=f;let r=0,s=0,i=0,n=0;var o,l,a,u,h;function c(t){const e=t.toString(16);return e.length<2?"0"+e:e}function f(t,e){return t>>0},t.toColor=function(e,r,s,i){return{css:t.toCss(e,r,s,i),rgba:t.toRgba(e,r,s,i)}}}(o||(e.channels=o={})),function(t){function e(t,e){return n=Math.round(255*e),[r,s,i]=h.toChannels(t.rgba),{css:o.toCss(r,s,i,n),rgba:o.toRgba(r,s,i,n)}}t.blend=function(t,e){if(n=(255&e.rgba)/255,1===n)return{css:e.css,rgba:e.rgba};const l=e.rgba>>24&255,a=e.rgba>>16&255,u=e.rgba>>8&255,h=t.rgba>>24&255,c=t.rgba>>16&255,f=t.rgba>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),{css:o.toCss(r,s,i),rgba:o.toRgba(r,s,i)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,r){const s=h.ensureContrastRatio(t.rgba,e.rgba,r);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[r,s,i]=h.toChannels(e),{css:o.toCss(r,s,i),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,r){return n=255&t.rgba,e(t,n*r/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(l||(e.color=l={})),function(t){let e,l;try{const t=document.createElement("canvas");t.width=1,t.height=1;const r=t.getContext("2d",{willReadFrequently:!0});r&&(e=r,e.globalCompositeOperation="copy",l=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),o.toColor(r,s,i);case 5:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),n=parseInt(t.slice(4,5).repeat(2),16),o.toColor(r,s,i,n);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const a=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return r=parseInt(a[1],10),s=parseInt(a[2],10),i=parseInt(a[3],10),n=Math.round(255*(void 0===a[5]?1:parseFloat(a[5]))),o.toColor(r,s,i,n);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!l)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=l,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[r,s,i,n]=e.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(r,s,i,n),css:t}}}(a||(e.css=a={})),function(t){function e(t,e,r){const s=t/255,i=e/255,n=r/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(u||(e.rgb=u={})),function(t){function e(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h0||l>0||a>0);)o-=Math.max(0,Math.ceil(.1*o)),l-=Math.max(0,Math.ceil(.1*l)),a-=Math.max(0,Math.ceil(.1*a)),h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));return(o<<24|l<<16|a<<8|255)>>>0}function l(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h>>0}t.blend=function(t,e){if(n=(255&e)/255,1===n)return e;const l=e>>24&255,a=e>>16&255,u=e>>8&255,h=t>>24&255,c=t>>16&255,f=t>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),o.toRgba(r,s,i)},t.ensureContrastRatio=function(t,r,s){const i=u.relativeLuminance(t>>8),n=u.relativeLuminance(r>>8);if(f(i,n)>8));if(of(i,u.relativeLuminance(e>>8))?n:e}return n}const o=l(t,r,s),a=f(i,u.relativeLuminance(o>>8));if(af(i,u.relativeLuminance(n>>8))?o:n}return o}},t.reduceLuminance=e,t.increaseLuminance=l,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(h||(e.rgba=h={}))}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s](n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.HTMLSerializeHandler=t.SerializeAddon=void 0;const e=r(992);function i(t,e,r){return Math.max(e,Math.min(t,r))}class n{constructor(t){this._buffer=t}serialize(t,e){const r=this._buffer.getNullCell(),s=this._buffer.getNullCell();let i=r;const n=t.start.y,o=t.end.y,l=t.start.x,a=t.end.x;this._beforeSerialize(o-n,n,o);for(let e=n;e<=o;e++){const n=this._buffer.getLine(e);if(n){const o=e===t.start.y?l:0,u=e===t.end.y?a:n.length;for(let t=o;t0&&!l(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let r="";if(!e){t-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);const e=this._buffer.getLine(t),s=this._buffer.getLine(t+1);if(s.isWrapped){r="";const i=e.getCell(e.length-1,this._thisRowLastChar),n=e.getCell(e.length-2,this._thisRowLastSecondChar),o=s.getCell(0,this._nextRowFirstChar),a=o.getWidth()>1;let u=!1;(o.getChars()&&(a?this._nullCellCount<=1:this._nullCellCount<=0))&&((i.getChars()||0===i.getWidth())&&l(i,o)&&(u=!0),a&&(n.getChars()||0===n.getWidth())&&l(i,o)&&l(n,o)&&(u=!0)),u||(r="-".repeat(this._nullCellCount+1),r+="",this._nullCellCount>0&&(r+="",e.length-this._nullCellCount>0&&(r+=`[${e.length-this._nullCellCount}C`),r+=`[${this._nullCellCount}X`,e.length-this._nullCellCount>0&&(r+=`[${e.length-this._nullCellCount}D`),r+=""),this._lastContentCursorRow=t+1,this._lastContentCursorCol=0,this._lastCursorRow=t+1,this._lastCursorCol=0)}else r="\r\n",this._lastCursorRow=t+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(t,e){const r=[];if(h(t,e))return r;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n)if(t.isAttributeDefault())e.isAttributeDefault()||r.push(0);else{if(s){const e=t.getFgColor();t.isFgRGB()?r.push(38,2,e>>>16&255,e>>>8&255,255&e):t.isFgPalette()?e>=16?r.push(38,5,e):r.push(8&e?90+(7&e):30+(7&e)):r.push(39)}if(i){const e=t.getBgColor();t.isBgRGB()?r.push(48,2,e>>>16&255,e>>>8&255,255&e):t.isBgPalette()?e>=16?r.push(48,5,e):r.push(8&e?100+(7&e):40+(7&e)):r.push(49)}if(n){if(t.isInverse()!==e.isInverse()&&r.push(t.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!t.isBold()||d&&!t.isDim();c&&r.push(22),t.isBold()&&(b||c)&&r.push(1),t.isDim()&&(d||c)&&r.push(2)}})(t.isBold()!==e.isBold(),t.isDim()!==e.isDim()),a(t,e))t.isUnderline()!==e.isUnderline()&&r.push(t.isUnderline()?4:24);else{const e=t.getUnderlineStyle();if(0===e)r.push(24);else if(1===e&&t.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+e),!t.isUnderlineColorDefault()){const e=t.getUnderlineColor();t.isUnderlineColorRGB()?r.push("58:2::"+(e>>>16&255)+":"+(e>>>8&255)+":"+(255&e)):r.push("58:5:"+e)}}t.isOverline()!==e.isOverline()&&r.push(t.isOverline()?53:55),t.isBlink()!==e.isBlink()&&r.push(t.isBlink()?5:25),t.isInvisible()!==e.isInvisible()&&r.push(t.isInvisible()?8:28),t.isItalic()!==e.isItalic()&&r.push(t.isItalic()?3:23),t.isStrikethrough()!==e.isStrikethrough()&&r.push(t.isStrikethrough()?9:29)}}return r}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),c=i&&t.isInverse()?this._buffer.getLine(r+1):void 0,p=c?.getCell(0,this._nextRowFirstChar),f=s===this._terminal.cols-1&&c?.isWrapped&&(p?.getWidth()??0)>1&&!!p&&h(t,p),a=i&&!!t.isInverse()&&!f,d=a&&(!!t.isUnderline()||!!t.isStrikethrough()||!!t.isOverline()),n=this._diffStyle(t,this._cursorStyle);if(i?a?n.length>0:!l(this._cursorStyle,t):n.length>0){this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`[${n.join(";")}m`;const t=this._buffer.getLine(r);void 0!==t&&(t.getCell(s,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=s)}i&&!a?this._nullCellCount+=t.getWidth():(this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),(a?(d&&(this._currentRow+="\x1B[24;29;55m"),this._currentRow+=" ".repeat(t.getWidth()),d&&(this._currentRow+=`\x1B[0m\x1B[${this._diffStyle(t,this._defaultCell).join(";")}m`)):this._currentRow+=t.getChars()),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s+t.getWidth())}_serializeString(t){let e=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(e=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let t=0;t{t>0?r+=`[${t}C`:t<0&&(r+=`[${-t}D`)};(t!==this._lastCursorRow||e!==this._lastCursorCol)&&((s=t-this._lastCursorRow)>0?r+=`[${s}B`:s<0&&(r+=`[${-s}A`),i(e-this._lastCursorCol))}var s;const i=this._terminal._core._inputHandler._curAttrData,n=this._diffStyle(i,this._cursorStyle);return n.length>0&&(r+=`[${n.join(";")}m`),r}}t.SerializeAddon=class{activate(t){this._terminal=t}_serializeBufferByScrollback(t,e,r){const s=e.length,n=void 0===r?s:i(r+t.rows,0,s);return this._serializeBufferByRange(t,e,{start:s-n,end:s-1},!1)}_serializeBufferByRange(t,e,r,s){return new c(e,t).serialize({start:{x:0,y:"number"==typeof r.start?r.start:r.start.line},end:{x:t.cols,y:"number"==typeof r.end?r.end:r.end.line}},s)}_serializeBufferAsHTML(t,e){const r=t.buffer.active,s=new f(r,t,e),n=e.onlySelection??!1,o=e.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:t.cols,y:(o.endLine,o.endLine)}});if(!n){const n=r.length,o=e.scrollback,l=void 0===o?n:i(o+t.rows,0,n);return s.serialize({start:{x:0,y:n-l},end:{x:t.cols,y:n-1}})}const l=this._terminal?.getSelectionPosition();return void 0!==l?s.serialize({start:{x:l.start.x,y:l.start.y},end:{x:l.end.x,y:l.end.y}}):""}_serializeScrollRegion(t){const e=t._core.buffer,r=e.scrollTop,s=e.scrollBottom;return 0!==r||s!==t.rows-1?`[${r+1};${s+1}r`:""}_serializeModes(t){let e="";const r=t.modes;if(r.applicationCursorKeysMode&&(e+="[?1h"),r.applicationKeypadMode&&(e+="[?66h"),r.bracketedPasteMode&&(e+="[?2004h"),r.insertMode&&(e+=""),r.originMode&&(e+="[?6h"),r.reverseWraparoundMode&&(e+="[?45h"),r.sendFocusMode&&(e+="[?1004h"),!1===r.wraparoundMode&&(e+="[?7l"),"none"!==r.mouseTrackingMode)switch(r.mouseTrackingMode){case"x10":e+="[?9h";break;case"vt200":e+="[?1000h";break;case"drag":e+="[?1002h";break;case"any":e+="[?1003h"}return r.showCursor||(e+="[?25l"),e}serialize(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=t?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,t.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,t?.scrollback);return t?.excludeAltBuffer||"alternate"!==this._terminal.buffer.active.type||(e+=`[?1049h${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),t?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,t??{})}dispose(){}};class f extends n{constructor(t,r,s){super(t),this._terminal=r,this._options=s,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=e.DEFAULT_ANSI_COLORS}_beforeSerialize(t,e,r){this._htmlContent+="\x3c!--StartFragment--\x3e
";let s="#000000",i="#ffffff";this._options.includeGlobalBackground&&(s=this._terminal.options.theme?.foreground??"#ffffff",i=this._terminal.options.theme?.background??"#000000");const n=[];n.push("color: "+s+";"),n.push("background-color: "+i+";"),n.push("font-family: "+this._terminal.options.fontFamily+";"),n.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
\x3c!--EndFragment--\x3e"}_rowEnd(t,e){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(t,e){const r=e?t.getFgColor():t.getBgColor();return(e?t.isFgRGB():t.isBgRGB())?"#"+[r>>16&255,r>>8&255,255&r].map(t=>t.toString(16).padStart(2,"0")).join(""):(e?t.isFgPalette():t.isBgPalette())?this._ansiColors[r].css:void 0}_getUnderlineColor(t){if(t.isUnderlineColorDefault())return;const e=t.getUnderlineColor();return t.isUnderlineColorRGB()?"#"+[e>>16&255,e>>8&255,255&e].map(t=>t.toString(16).padStart(2,"0")).join(""):this._ansiColors[e].css}_getUnderlineStyle(t){switch(t.getUnderlineStyle()){case 1:default:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed"}}_diffStyle(t,e){const r=[];if(h(t,e))return;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n){const e=this._getHexColor(t,!0);e&&r.push("color: "+e+";");const s=this._getHexColor(t,!1);s&&r.push("background-color: "+s+";"),t.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),t.isBold()&&r.push("font-weight: bold;");const i=[];if(t.isUnderline()&&i.push(this._getUnderlineStyle(t)),t.isOverline()&&i.push("overline"),t.isStrikethrough()&&i.push("line-through"),t.isBlink()&&i.push("blink"),i.length>0&&r.push("text-decoration: "+i.join(" ")+";"),t.isUnderline()){const e=this._getUnderlineColor(t);e&&r.push("text-decoration-color: "+e+";")}return t.isInvisible()&&r.push("visibility: hidden;"),t.isItalic()&&r.push("font-style: italic;"),t.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,e);n&&(this._currentRow+=0===n.length?"
":""),this._currentRow+=i?" ":function(t){switch(t){case"&":return"&";case"<":return"<"}return t}(t.getChars())}_serializeString(){return this._htmlContent}}t.HTMLSerializeHandler=f})(),s})()); //# sourceMappingURL=addon-serialize.js.map \ No newline at end of file diff --git a/lib/addon-serialize.mjs b/lib/addon-serialize.mjs -index a5c4c4dd05b7efcc23d0e45661ffd4e42da80f21..475e45b3ed228027531deea5530bd03859f4a4e0 100644 +index a5c4c4dd05b7efcc23d0e45661ffd4e42da80f21..bb46224439629de3845c0b56ab9e4cd397dfe098 100644 --- a/lib/addon-serialize.mjs +++ b/lib/addon-serialize.mjs -@@ -15,5 +15,5 @@ +@@ -14,6 +14,6 @@ + * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ - var m=0,b=0,_=0,p=0;var g;(t=>{function a(r,l,s,i){return i!==void 0?`#${w(r)}${w(l)}${w(s)}${w(i)}`:`#${w(r)}${w(l)}${w(s)}`}t.toCss=a;function n(r,l,s,i=255){return(r<<24|l<<16|s<<8|i)>>>0}t.toRgba=n;function e(r,l,s,i){return{css:t.toCss(r,l,s,i),rgba:t.toRgba(r,l,s,i)}}t.toColor=e})(g||={});var N;(i=>{function a(o,u){if(p=(u.rgba&255)/255,p===1)return{css:u.css,rgba:u.rgba};let f=u.rgba>>24&255,C=u.rgba>>16&255,c=u.rgba>>8&255,h=o.rgba>>24&255,d=o.rgba>>16&255,I=o.rgba>>8&255;m=h+Math.round((f-h)*p),b=d+Math.round((C-d)*p),_=I+Math.round((c-I)*p);let L=g.toCss(m,b,_),E=g.toRgba(m,b,_);return{css:L,rgba:E}}i.blend=a;function n(o){return(o.rgba&255)===255}i.isOpaque=n;function e(o,u,f){let C=B.ensureContrastRatio(o.rgba,u.rgba,f);if(C)return g.toColor(C>>24&255,C>>16&255,C>>8&255)}i.ensureContrastRatio=e;function t(o){let u=(o.rgba|255)>>>0;return[m,b,_]=B.toChannels(u),{css:g.toCss(m,b,_),rgba:u}}i.opaque=t;function r(o,u){return p=Math.round(u*255),[m,b,_]=B.toChannels(o.rgba),{css:g.toCss(m,b,_,p),rgba:g.toRgba(m,b,_,p)}}i.opacity=r;function l(o,u){return p=o.rgba&255,r(o,p*u/255)}i.multiplyOpacity=l;function s(o){return[o.rgba>>24&255,o.rgba>>16&255,o.rgba>>8&255]}i.toColorRGB=s})(N||={});var x;(t=>{let a,n;try{let r=document.createElement("canvas");r.width=1,r.height=1;let l=r.getContext("2d",{willReadFrequently:!0});l&&(a=l,a.globalCompositeOperation="copy",n=a.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),g.toColor(m,b,_);case 5:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),p=parseInt(r.slice(4,5).repeat(2),16),g.toColor(m,b,_,p);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let l=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return m=parseInt(l[1],10),b=parseInt(l[2],10),_=parseInt(l[3],10),p=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),g.toColor(m,b,_,p);if(r==="transparent")return{css:"transparent",rgba:0};if(!a||!n)throw new Error("css.toColor: Unsupported css format");if(a.fillStyle=n,a.fillStyle=r,typeof a.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(a.fillRect(0,0,1,1),[m,b,_,p]=a.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(m,b,_,p),css:r}}t.toColor=e})(x||={});var v;(e=>{function a(t){return n(t>>16&255,t>>8&255,t&255)}e.relativeLuminance=a;function n(t,r,l){let s=t/255,i=r/255,o=l/255,u=s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4),f=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4),C=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4);return u*.2126+f*.7152+C*.0722}e.relativeLuminance2=n})(v||={});var B;(l=>{function a(s,i){if(p=(i&255)/255,p===1)return i;let o=i>>24&255,u=i>>16&255,f=i>>8&255,C=s>>24&255,c=s>>16&255,h=s>>8&255;return m=C+Math.round((o-C)*p),b=c+Math.round((u-c)*p),_=h+Math.round((f-h)*p),g.toRgba(m,b,_)}l.blend=a;function n(s,i,o){let u=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(R(u,f)>8));if(I>8));return I>E?d:L}return d}let c=t(s,i,o),h=R(u,v.relativeLuminance(c>>8));if(h>8));return h>I?c:d}return c}}l.ensureContrastRatio=n;function e(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I0||h>0||d>0);)c-=Math.max(0,Math.ceil(c*.1)),h-=Math.max(0,Math.ceil(h*.1)),d-=Math.max(0,Math.ceil(d*.1)),I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));return(c<<24|h<<16|d<<8|255)>>>0}l.reduceLuminance=e;function t(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I>>0}l.increaseLuminance=t;function r(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}l.toChannels=r})(B||={});function w(a){let n=a.toString(16);return n.length<2?"0"+n:n}function R(a,n){return a{let a=[x.toColor("#2e3436"),x.toColor("#cc0000"),x.toColor("#4e9a06"),x.toColor("#c4a000"),x.toColor("#3465a4"),x.toColor("#75507b"),x.toColor("#06989a"),x.toColor("#d3d7cf"),x.toColor("#555753"),x.toColor("#ef2929"),x.toColor("#8ae234"),x.toColor("#fce94f"),x.toColor("#729fcf"),x.toColor("#ad7fa8"),x.toColor("#34e2e2"),x.toColor("#eeeeec")],n=[0,95,135,175,215,255];for(let e=0;e<216;e++){let t=n[e/36%6|0],r=n[e/6%6|0],l=n[e%6];a.push({css:g.toCss(t,r,l),rgba:g.toRgba(t,r,l)})}for(let e=0;e<24;e++){let t=8+e*10;a.push({css:g.toCss(t,t,t),rgba:g.toRgba(t,t,t)})}return a})());function A(a,n,e){return Math.max(n,Math.min(a,e))}function z(a){switch(a){case"&":return"&";case"<":return"<"}return a}var S=class{constructor(n){this._buffer=n}serialize(n,e){let t=this._buffer.getNullCell(),r=this._buffer.getNullCell(),l=t,s=n.start.y,i=n.end.y,o=n.start.x,u=n.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let C=this._buffer.getLine(f);if(C){let c=f===n.start.y?o:0,h=f===n.end.y?u:C.length;for(let d=c;d0&&!F(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let r="";if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let l=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)r=`\r +-var m=0,b=0,_=0,p=0;var g;(t=>{function a(r,l,s,i){return i!==void 0?`#${w(r)}${w(l)}${w(s)}${w(i)}`:`#${w(r)}${w(l)}${w(s)}`}t.toCss=a;function n(r,l,s,i=255){return(r<<24|l<<16|s<<8|i)>>>0}t.toRgba=n;function e(r,l,s,i){return{css:t.toCss(r,l,s,i),rgba:t.toRgba(r,l,s,i)}}t.toColor=e})(g||={});var N;(i=>{function a(o,u){if(p=(u.rgba&255)/255,p===1)return{css:u.css,rgba:u.rgba};let f=u.rgba>>24&255,C=u.rgba>>16&255,c=u.rgba>>8&255,h=o.rgba>>24&255,d=o.rgba>>16&255,I=o.rgba>>8&255;m=h+Math.round((f-h)*p),b=d+Math.round((C-d)*p),_=I+Math.round((c-I)*p);let L=g.toCss(m,b,_),E=g.toRgba(m,b,_);return{css:L,rgba:E}}i.blend=a;function n(o){return(o.rgba&255)===255}i.isOpaque=n;function e(o,u,f){let C=B.ensureContrastRatio(o.rgba,u.rgba,f);if(C)return g.toColor(C>>24&255,C>>16&255,C>>8&255)}i.ensureContrastRatio=e;function t(o){let u=(o.rgba|255)>>>0;return[m,b,_]=B.toChannels(u),{css:g.toCss(m,b,_),rgba:u}}i.opaque=t;function r(o,u){return p=Math.round(u*255),[m,b,_]=B.toChannels(o.rgba),{css:g.toCss(m,b,_,p),rgba:g.toRgba(m,b,_,p)}}i.opacity=r;function l(o,u){return p=o.rgba&255,r(o,p*u/255)}i.multiplyOpacity=l;function s(o){return[o.rgba>>24&255,o.rgba>>16&255,o.rgba>>8&255]}i.toColorRGB=s})(N||={});var x;(t=>{let a,n;try{let r=document.createElement("canvas");r.width=1,r.height=1;let l=r.getContext("2d",{willReadFrequently:!0});l&&(a=l,a.globalCompositeOperation="copy",n=a.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),g.toColor(m,b,_);case 5:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),p=parseInt(r.slice(4,5).repeat(2),16),g.toColor(m,b,_,p);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let l=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return m=parseInt(l[1],10),b=parseInt(l[2],10),_=parseInt(l[3],10),p=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),g.toColor(m,b,_,p);if(r==="transparent")return{css:"transparent",rgba:0};if(!a||!n)throw new Error("css.toColor: Unsupported css format");if(a.fillStyle=n,a.fillStyle=r,typeof a.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(a.fillRect(0,0,1,1),[m,b,_,p]=a.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(m,b,_,p),css:r}}t.toColor=e})(x||={});var v;(e=>{function a(t){return n(t>>16&255,t>>8&255,t&255)}e.relativeLuminance=a;function n(t,r,l){let s=t/255,i=r/255,o=l/255,u=s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4),f=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4),C=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4);return u*.2126+f*.7152+C*.0722}e.relativeLuminance2=n})(v||={});var B;(l=>{function a(s,i){if(p=(i&255)/255,p===1)return i;let o=i>>24&255,u=i>>16&255,f=i>>8&255,C=s>>24&255,c=s>>16&255,h=s>>8&255;return m=C+Math.round((o-C)*p),b=c+Math.round((u-c)*p),_=h+Math.round((f-h)*p),g.toRgba(m,b,_)}l.blend=a;function n(s,i,o){let u=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(R(u,f)>8));if(I>8));return I>E?d:L}return d}let c=t(s,i,o),h=R(u,v.relativeLuminance(c>>8));if(h>8));return h>I?c:d}return c}}l.ensureContrastRatio=n;function e(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I0||h>0||d>0);)c-=Math.max(0,Math.ceil(c*.1)),h-=Math.max(0,Math.ceil(h*.1)),d-=Math.max(0,Math.ceil(d*.1)),I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));return(c<<24|h<<16|d<<8|255)>>>0}l.reduceLuminance=e;function t(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I>>0}l.increaseLuminance=t;function r(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}l.toChannels=r})(B||={});function w(a){let n=a.toString(16);return n.length<2?"0"+n:n}function R(a,n){return a{let a=[x.toColor("#2e3436"),x.toColor("#cc0000"),x.toColor("#4e9a06"),x.toColor("#c4a000"),x.toColor("#3465a4"),x.toColor("#75507b"),x.toColor("#06989a"),x.toColor("#d3d7cf"),x.toColor("#555753"),x.toColor("#ef2929"),x.toColor("#8ae234"),x.toColor("#fce94f"),x.toColor("#729fcf"),x.toColor("#ad7fa8"),x.toColor("#34e2e2"),x.toColor("#eeeeec")],n=[0,95,135,175,215,255];for(let e=0;e<216;e++){let t=n[e/36%6|0],r=n[e/6%6|0],l=n[e%6];a.push({css:g.toCss(t,r,l),rgba:g.toRgba(t,r,l)})}for(let e=0;e<24;e++){let t=8+e*10;a.push({css:g.toCss(t,t,t),rgba:g.toRgba(t,t,t)})}return a})());function A(a,n,e){return Math.max(n,Math.min(a,e))}function z(a){switch(a){case"&":return"&";case"<":return"<"}return a}var S=class{constructor(n){this._buffer=n}serialize(n,e){let t=this._buffer.getNullCell(),r=this._buffer.getNullCell(),l=t,s=n.start.y,i=n.end.y,o=n.start.x,u=n.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let C=this._buffer.getLine(f);if(C){let c=f===n.start.y?o:0,h=f===n.end.y?u:C.length;for(let d=c;d0&&!F(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let r="";if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let l=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)r=`\r -`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{r="";let i=l.getCell(l.length-1,this._thisRowLastChar),o=l.getCell(l.length-2,this._thisRowLastSecondChar),u=s.getCell(0,this._nextRowFirstChar),f=u.getWidth()>1,C=!1;(u.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&F(i,u)&&(C=!0),f&&(o.getChars()||o.getWidth()===0)&&F(i,u)&&F(o,u)&&(C=!0)),C||(r="-".repeat(this._nullCellCount+1),r+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(r+="\x1B[A",r+=`\x1B[${l.length-this._nullCellCount}C`,r+=`\x1B[${this._nullCellCount}X`,r+=`\x1B[${l.length-this._nullCellCount}D`,r+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let r=[];if(U(e,t))return r;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i)if(e.isAttributeDefault())t.isAttributeDefault()||r.push(0);else{if(l){let o=e.getFgColor();e.isFgRGB()?r.push(38,2,o>>>16&255,o>>>8&255,o&255):e.isFgPalette()?o>=16?r.push(38,5,o):r.push(o&8?90+(o&7):30+(o&7)):r.push(39)}if(s){let o=e.getBgColor();e.isBgRGB()?r.push(48,2,o>>>16&255,o>>>8&255,o&255):e.isBgPalette()?o>=16?r.push(48,5,o):r.push(o&8?100+(o&7):40+(o&7)):r.push(49)}if(i){if(e.isInverse()!==t.isInverse()&&r.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&r.push(e.isBold()?1:22),O(e,t))e.isUnderline()!==t.isUnderline()&&r.push(e.isUnderline()?4:24);else{let o=e.getUnderlineStyle();if(o===0)r.push(24);else if(o===1&&e.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+o),!e.isUnderlineColorDefault()){let u=e.getUnderlineColor();e.isUnderlineColorRGB()?r.push("58:2::"+(u>>>16&255)+":"+(u>>>8&255)+":"+(u&255)):r.push("58:5:"+u)}}e.isOverline()!==t.isOverline()&&r.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&r.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&r.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&r.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&r.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&r.push(e.isStrikethrough()?9:29)}}return r}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(i?!F(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l,this._currentRow+=`\x1B[${o.join(";")}m`;let f=this._buffer.getLine(r);f!==void 0&&(f.getCell(l,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=l)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let i=0;i{c>0?r+=`\x1B[${c}C`:c<0&&(r+=`\x1B[${-c}D`)};u&&((c=>{c>0?r+=`\x1B[${c}B`:c<0&&(r+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(o-this._lastCursorCol))}let l=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(l,this._cursorStyle);return s.length>0&&(r+=`\x1B[${s.join(";")}m`),r}},H=class{activate(n){this._terminal=n}_serializeBufferByScrollback(n,e,t){let r=e.length,l=t===void 0?r:A(t+n.rows,0,r);return this._serializeBufferByRange(n,e,{start:r-l,end:r-1},!1)}_serializeBufferByRange(n,e,t,r){return new y(e,n).serialize({start:{x:0,y:typeof t.start=="number"?t.start:t.start.line},end:{x:n.cols,y:typeof t.end=="number"?t.end:t.end.line}},r)}_serializeBufferAsHTML(n,e){let t=n.buffer.active,r=new D(t,n,e),l=e.onlySelection??!1,s=e.range;if(s)return r.serialize({start:{x:s.startCol,y:(typeof s.startLine=="number",s.startLine)},end:{x:n.cols,y:(typeof s.endLine=="number",s.endLine)}});if(!l){let o=t.length,u=e.scrollback,f=u===void 0?o:A(u+n.rows,0,o);return r.serialize({start:{x:0,y:o-f},end:{x:n.cols,y:o-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?r.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeScrollRegion(n){let e=n._core.buffer,t=e.scrollTop,r=e.scrollBottom;return t!==0||r!==n.rows-1?`\x1B[${t+1};${r+1}r`:""}_serializeModes(n){let e="",t=n.modes;if(t.applicationCursorKeysMode&&(e+="\x1B[?1h"),t.applicationKeypadMode&&(e+="\x1B[?66h"),t.bracketedPasteMode&&(e+="\x1B[?2004h"),t.insertMode&&(e+="\x1B[4h"),t.originMode&&(e+="\x1B[?6h"),t.reverseWraparoundMode&&(e+="\x1B[?45h"),t.sendFocusMode&&(e+="\x1B[?1004h"),t.wraparoundMode===!1&&(e+="\x1B[?7l"),t.mouseTrackingMode!=="none")switch(t.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return t.showCursor||(e+="\x1B[?25l"),e}serialize(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=n?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,n.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,n?.scrollback);if(!n?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let t=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${t}`}return n?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,n??{})}dispose(){}},D=class extends S{constructor(e,t,r){super(e);this._terminal=t;this._options=r;this._currentRow="";this._htmlContent="";t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=k}_beforeSerialize(e,t,r){this._htmlContent+="
";let l="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(l=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+l+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let r=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[r>>16&255,r>>8&255,r&255].map(s=>s.toString(16).padStart(2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[r].css}_getUnderlineColor(e){if(e.isUnderlineColorDefault())return;let t=e.getUnderlineColor();return e.isUnderlineColorRGB()?"#"+[t>>16&255,t>>8&255,t&255].map(l=>l.toString(16).padStart(2,"0")).join(""):this._ansiColors[t].css}_getUnderlineStyle(e){switch(e.getUnderlineStyle()){case 1:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed";default:return"underline"}}_diffStyle(e,t){let r=[];if(U(e,t))return;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i){let o=this._getHexColor(e,!0);o&&r.push("color: "+o+";");let u=this._getHexColor(e,!1);u&&r.push("background-color: "+u+";"),e.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&r.push("font-weight: bold;");let f=[];if(e.isUnderline()&&f.push(this._getUnderlineStyle(e)),e.isOverline()&&f.push("overline"),e.isStrikethrough()&&f.push("line-through"),e.isBlink()&&f.push("blink"),f.length>0&&r.push("text-decoration: "+f.join(" ")+";"),e.isUnderline()){let C=this._getUnderlineColor(e);C&&r.push("text-decoration-color: "+C+";")}return e.isInvisible()&&r.push("visibility: hidden;"),e.isItalic()&&r.push("font-style: italic;"),e.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),i?this._currentRow+=" ":this._currentRow+=z(e.getChars())}_serializeString(){return this._htmlContent}};export{D as HTMLSerializeHandler,H as SerializeAddon}; -+`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{r="";let i=l.getCell(l.length-1,this._thisRowLastChar),o=l.getCell(l.length-2,this._thisRowLastSecondChar),u=s.getCell(0,this._nextRowFirstChar),f=u.getWidth()>1,C=!1;(u.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&F(i,u)&&(C=!0),f&&(o.getChars()||o.getWidth()===0)&&F(i,u)&&F(o,u)&&(C=!0)),C||(r="-".repeat(this._nullCellCount+1),r+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(r+="\x1B[A",r+=`\x1B[${l.length-this._nullCellCount}C`,r+=`\x1B[${this._nullCellCount}X`,r+=`\x1B[${l.length-this._nullCellCount}D`,r+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let r=[];if(U(e,t))return r;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i)if(e.isAttributeDefault())t.isAttributeDefault()||r.push(0);else{if(l){let o=e.getFgColor();e.isFgRGB()?r.push(38,2,o>>>16&255,o>>>8&255,o&255):e.isFgPalette()?o>=16?r.push(38,5,o):r.push(o&8?90+(o&7):30+(o&7)):r.push(39)}if(s){let o=e.getBgColor();e.isBgRGB()?r.push(48,2,o>>>16&255,o>>>8&255,o&255):e.isBgPalette()?o>=16?r.push(48,5,o):r.push(o&8?100+(o&7):40+(o&7)):r.push(49)}if(i){if(e.isInverse()!==t.isInverse()&&r.push(e.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!e.isBold()||d&&!e.isDim();c&&r.push(22),e.isBold()&&(b||c)&&r.push(1),e.isDim()&&(d||c)&&r.push(2)}})(e.isBold()!==t.isBold(),e.isDim()!==t.isDim()),O(e,t))e.isUnderline()!==t.isUnderline()&&r.push(e.isUnderline()?4:24);else{let o=e.getUnderlineStyle();if(o===0)r.push(24);else if(o===1&&e.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+o),!e.isUnderlineColorDefault()){let u=e.getUnderlineColor();e.isUnderlineColorRGB()?r.push("58:2::"+(u>>>16&255)+":"+(u>>>8&255)+":"+(u&255)):r.push("58:5:"+u)}}e.isOverline()!==t.isOverline()&&r.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&r.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&r.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&r.push(e.isItalic()?3:23),e.isStrikethrough()!==t.isStrikethrough()&&r.push(e.isStrikethrough()?9:29)}}return r}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(i?!F(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l,this._currentRow+=`\x1B[${o.join(";")}m`;let f=this._buffer.getLine(r);f!==void 0&&(f.getCell(l,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=l)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let i=0;i{c>0?r+=`\x1B[${c}C`:c<0&&(r+=`\x1B[${-c}D`)};u&&((c=>{c>0?r+=`\x1B[${c}B`:c<0&&(r+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(o-this._lastCursorCol))}let l=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(l,this._cursorStyle);return s.length>0&&(r+=`\x1B[${s.join(";")}m`),r}},H=class{activate(n){this._terminal=n}_serializeBufferByScrollback(n,e,t){let r=e.length,l=t===void 0?r:A(t+n.rows,0,r);return this._serializeBufferByRange(n,e,{start:r-l,end:r-1},!1)}_serializeBufferByRange(n,e,t,r){return new y(e,n).serialize({start:{x:0,y:typeof t.start=="number"?t.start:t.start.line},end:{x:n.cols,y:typeof t.end=="number"?t.end:t.end.line}},r)}_serializeBufferAsHTML(n,e){let t=n.buffer.active,r=new D(t,n,e),l=e.onlySelection??!1,s=e.range;if(s)return r.serialize({start:{x:s.startCol,y:(typeof s.startLine=="number",s.startLine)},end:{x:n.cols,y:(typeof s.endLine=="number",s.endLine)}});if(!l){let o=t.length,u=e.scrollback,f=u===void 0?o:A(u+n.rows,0,o);return r.serialize({start:{x:0,y:o-f},end:{x:n.cols,y:o-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?r.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeScrollRegion(n){let e=n._core.buffer,t=e.scrollTop,r=e.scrollBottom;return t!==0||r!==n.rows-1?`\x1B[${t+1};${r+1}r`:""}_serializeModes(n){let e="",t=n.modes;if(t.applicationCursorKeysMode&&(e+="\x1B[?1h"),t.applicationKeypadMode&&(e+="\x1B[?66h"),t.bracketedPasteMode&&(e+="\x1B[?2004h"),t.insertMode&&(e+="\x1B[4h"),t.originMode&&(e+="\x1B[?6h"),t.reverseWraparoundMode&&(e+="\x1B[?45h"),t.sendFocusMode&&(e+="\x1B[?1004h"),t.wraparoundMode===!1&&(e+="\x1B[?7l"),t.mouseTrackingMode!=="none")switch(t.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return t.showCursor||(e+="\x1B[?25l"),e}serialize(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=n?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,n.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,n?.scrollback);if(!n?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let t=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${t}`}return n?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,n??{})}dispose(){}},D=class extends S{constructor(e,t,r){super(e);this._terminal=t;this._options=r;this._currentRow="";this._htmlContent="";t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=k}_beforeSerialize(e,t,r){this._htmlContent+="
";let l="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(l=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+l+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let r=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[r>>16&255,r>>8&255,r&255].map(s=>s.toString(16).padStart(2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[r].css}_getUnderlineColor(e){if(e.isUnderlineColorDefault())return;let t=e.getUnderlineColor();return e.isUnderlineColorRGB()?"#"+[t>>16&255,t>>8&255,t&255].map(l=>l.toString(16).padStart(2,"0")).join(""):this._ansiColors[t].css}_getUnderlineStyle(e){switch(e.getUnderlineStyle()){case 1:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed";default:return"underline"}}_diffStyle(e,t){let r=[];if(U(e,t))return;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i){let o=this._getHexColor(e,!0);o&&r.push("color: "+o+";");let u=this._getHexColor(e,!1);u&&r.push("background-color: "+u+";"),e.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&r.push("font-weight: bold;");let f=[];if(e.isUnderline()&&f.push(this._getUnderlineStyle(e)),e.isOverline()&&f.push("overline"),e.isStrikethrough()&&f.push("line-through"),e.isBlink()&&f.push("blink"),f.length>0&&r.push("text-decoration: "+f.join(" ")+";"),e.isUnderline()){let C=this._getUnderlineColor(e);C&&r.push("text-decoration-color: "+C+";")}return e.isInvisible()&&r.push("visibility: hidden;"),e.isItalic()&&r.push("font-style: italic;"),e.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),i?this._currentRow+=" ":this._currentRow+=z(e.getChars())}_serializeString(){return this._htmlContent}};export{D as HTMLSerializeHandler,H as SerializeAddon}; ++var m=0,b=0,_=0,p=0;var g;(t=>{function a(r,l,s,i){return i!==void 0?`#${w(r)}${w(l)}${w(s)}${w(i)}`:`#${w(r)}${w(l)}${w(s)}`}t.toCss=a;function n(r,l,s,i=255){return(r<<24|l<<16|s<<8|i)>>>0}t.toRgba=n;function e(r,l,s,i){return{css:t.toCss(r,l,s,i),rgba:t.toRgba(r,l,s,i)}}t.toColor=e})(g||={});var N;(i=>{function a(o,u){if(p=(u.rgba&255)/255,p===1)return{css:u.css,rgba:u.rgba};let f=u.rgba>>24&255,C=u.rgba>>16&255,c=u.rgba>>8&255,h=o.rgba>>24&255,d=o.rgba>>16&255,I=o.rgba>>8&255;m=h+Math.round((f-h)*p),b=d+Math.round((C-d)*p),_=I+Math.round((c-I)*p);let L=g.toCss(m,b,_),E=g.toRgba(m,b,_);return{css:L,rgba:E}}i.blend=a;function n(o){return(o.rgba&255)===255}i.isOpaque=n;function e(o,u,f){let C=B.ensureContrastRatio(o.rgba,u.rgba,f);if(C)return g.toColor(C>>24&255,C>>16&255,C>>8&255)}i.ensureContrastRatio=e;function t(o){let u=(o.rgba|255)>>>0;return[m,b,_]=B.toChannels(u),{css:g.toCss(m,b,_),rgba:u}}i.opaque=t;function r(o,u){return p=Math.round(u*255),[m,b,_]=B.toChannels(o.rgba),{css:g.toCss(m,b,_,p),rgba:g.toRgba(m,b,_,p)}}i.opacity=r;function l(o,u){return p=o.rgba&255,r(o,p*u/255)}i.multiplyOpacity=l;function s(o){return[o.rgba>>24&255,o.rgba>>16&255,o.rgba>>8&255]}i.toColorRGB=s})(N||={});var x;(t=>{let a,n;try{let r=document.createElement("canvas");r.width=1,r.height=1;let l=r.getContext("2d",{willReadFrequently:!0});l&&(a=l,a.globalCompositeOperation="copy",n=a.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),g.toColor(m,b,_);case 5:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),p=parseInt(r.slice(4,5).repeat(2),16),g.toColor(m,b,_,p);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let l=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return m=parseInt(l[1],10),b=parseInt(l[2],10),_=parseInt(l[3],10),p=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),g.toColor(m,b,_,p);if(r==="transparent")return{css:"transparent",rgba:0};if(!a||!n)throw new Error("css.toColor: Unsupported css format");if(a.fillStyle=n,a.fillStyle=r,typeof a.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(a.fillRect(0,0,1,1),[m,b,_,p]=a.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(m,b,_,p),css:r}}t.toColor=e})(x||={});var v;(e=>{function a(t){return n(t>>16&255,t>>8&255,t&255)}e.relativeLuminance=a;function n(t,r,l){let s=t/255,i=r/255,o=l/255,u=s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4),f=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4),C=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4);return u*.2126+f*.7152+C*.0722}e.relativeLuminance2=n})(v||={});var B;(l=>{function a(s,i){if(p=(i&255)/255,p===1)return i;let o=i>>24&255,u=i>>16&255,f=i>>8&255,C=s>>24&255,c=s>>16&255,h=s>>8&255;return m=C+Math.round((o-C)*p),b=c+Math.round((u-c)*p),_=h+Math.round((f-h)*p),g.toRgba(m,b,_)}l.blend=a;function n(s,i,o){let u=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(R(u,f)>8));if(I>8));return I>E?d:L}return d}let c=t(s,i,o),h=R(u,v.relativeLuminance(c>>8));if(h>8));return h>I?c:d}return c}}l.ensureContrastRatio=n;function e(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I0||h>0||d>0);)c-=Math.max(0,Math.ceil(c*.1)),h-=Math.max(0,Math.ceil(h*.1)),d-=Math.max(0,Math.ceil(d*.1)),I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));return(c<<24|h<<16|d<<8|255)>>>0}l.reduceLuminance=e;function t(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I>>0}l.increaseLuminance=t;function r(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}l.toChannels=r})(B||={});function w(a){let n=a.toString(16);return n.length<2?"0"+n:n}function R(a,n){return a{let a=[x.toColor("#2e3436"),x.toColor("#cc0000"),x.toColor("#4e9a06"),x.toColor("#c4a000"),x.toColor("#3465a4"),x.toColor("#75507b"),x.toColor("#06989a"),x.toColor("#d3d7cf"),x.toColor("#555753"),x.toColor("#ef2929"),x.toColor("#8ae234"),x.toColor("#fce94f"),x.toColor("#729fcf"),x.toColor("#ad7fa8"),x.toColor("#34e2e2"),x.toColor("#eeeeec")],n=[0,95,135,175,215,255];for(let e=0;e<216;e++){let t=n[e/36%6|0],r=n[e/6%6|0],l=n[e%6];a.push({css:g.toCss(t,r,l),rgba:g.toRgba(t,r,l)})}for(let e=0;e<24;e++){let t=8+e*10;a.push({css:g.toCss(t,t,t),rgba:g.toRgba(t,t,t)})}return a})());function A(a,n,e){return Math.max(n,Math.min(a,e))}function z(a){switch(a){case"&":return"&";case"<":return"<"}return a}var S=class{constructor(n){this._buffer=n}serialize(n,e){let t=this._buffer.getNullCell(),r=this._buffer.getNullCell(),l=t,s=n.start.y,i=n.end.y,o=n.start.x,u=n.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let C=this._buffer.getLine(f);if(C){let c=f===n.start.y?o:0,h=f===n.end.y?u:C.length;for(let d=c;d0&&!F(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let r="";if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let l=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)r=`\r ++`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{r="";let i=l.getCell(l.length-1,this._thisRowLastChar),o=l.getCell(l.length-2,this._thisRowLastSecondChar),u=s.getCell(0,this._nextRowFirstChar),f=u.getWidth()>1,C=!1;(u.getChars()&&(f?this._nullCellCount<=1:this._nullCellCount<=0))&&((i.getChars()||i.getWidth()===0)&&F(i,u)&&(C=!0),f&&(o.getChars()||o.getWidth()===0)&&F(i,u)&&F(o,u)&&(C=!0)),C||(r="-".repeat(this._nullCellCount+1),r+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(r+="\x1B[A",l.length-this._nullCellCount>0&&(r+=`\x1B[${l.length-this._nullCellCount}C`),r+=`\x1B[${this._nullCellCount}X`,l.length-this._nullCellCount>0&&(r+=`\x1B[${l.length-this._nullCellCount}D`),r+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let r=[];if(U(e,t))return r;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i)if(e.isAttributeDefault())t.isAttributeDefault()||r.push(0);else{if(l){let o=e.getFgColor();e.isFgRGB()?r.push(38,2,o>>>16&255,o>>>8&255,o&255):e.isFgPalette()?o>=16?r.push(38,5,o):r.push(o&8?90+(o&7):30+(o&7)):r.push(39)}if(s){let o=e.getBgColor();e.isBgRGB()?r.push(48,2,o>>>16&255,o>>>8&255,o&255):e.isBgPalette()?o>=16?r.push(48,5,o):r.push(o&8?100+(o&7):40+(o&7)):r.push(49)}if(i){if(e.isInverse()!==t.isInverse()&&r.push(e.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!e.isBold()||d&&!e.isDim();c&&r.push(22),e.isBold()&&(b||c)&&r.push(1),e.isDim()&&(d||c)&&r.push(2)}})(e.isBold()!==t.isBold(),e.isDim()!==t.isDim()),O(e,t))e.isUnderline()!==t.isUnderline()&&r.push(e.isUnderline()?4:24);else{let o=e.getUnderlineStyle();if(o===0)r.push(24);else if(o===1&&e.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+o),!e.isUnderlineColorDefault()){let u=e.getUnderlineColor();e.isUnderlineColorRGB()?r.push("58:2::"+(u>>>16&255)+":"+(u>>>8&255)+":"+(u&255)):r.push("58:5:"+u)}}e.isOverline()!==t.isOverline()&&r.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&r.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&r.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&r.push(e.isItalic()?3:23),e.isStrikethrough()!==t.isStrikethrough()&&r.push(e.isStrikethrough()?9:29)}}return r}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",f=i&&e.isInverse()?this._buffer.getLine(r+1):void 0,g=f?.getCell(0,this._nextRowFirstChar),C=l===this._terminal.cols-1&&f?.isWrapped&&(g?.getWidth()??0)>1&&!!g&&U(e,g),q=i&&!!e.isInverse()&&!C,d=q&&(!!e.isUnderline()||!!e.isStrikethrough()||!!e.isOverline()),o=this._diffStyle(e,this._cursorStyle);if(i?q?o.length>0:!F(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l,this._currentRow+=`\x1B[${o.join(";")}m`;let f=this._buffer.getLine(r);f!==void 0&&(f.getCell(l,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=l)}i&&!q?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),(q?(d&&(this._currentRow+="\x1B[24;29;55m"),this._currentRow+=" ".repeat(e.getWidth()),d&&(this._currentRow+=`\x1B[0m\x1B[${this._diffStyle(e,this._defaultCell).join(";")}m`)):this._currentRow+=e.getChars()),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let i=0;i{c>0?r+=`\x1B[${c}C`:c<0&&(r+=`\x1B[${-c}D`)};u&&((c=>{c>0?r+=`\x1B[${c}B`:c<0&&(r+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(o-this._lastCursorCol))}let l=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(l,this._cursorStyle);return s.length>0&&(r+=`\x1B[${s.join(";")}m`),r}},H=class{activate(n){this._terminal=n}_serializeBufferByScrollback(n,e,t){let r=e.length,l=t===void 0?r:A(t+n.rows,0,r);return this._serializeBufferByRange(n,e,{start:r-l,end:r-1},!1)}_serializeBufferByRange(n,e,t,r){return new y(e,n).serialize({start:{x:0,y:typeof t.start=="number"?t.start:t.start.line},end:{x:n.cols,y:typeof t.end=="number"?t.end:t.end.line}},r)}_serializeBufferAsHTML(n,e){let t=n.buffer.active,r=new D(t,n,e),l=e.onlySelection??!1,s=e.range;if(s)return r.serialize({start:{x:s.startCol,y:(typeof s.startLine=="number",s.startLine)},end:{x:n.cols,y:(typeof s.endLine=="number",s.endLine)}});if(!l){let o=t.length,u=e.scrollback,f=u===void 0?o:A(u+n.rows,0,o);return r.serialize({start:{x:0,y:o-f},end:{x:n.cols,y:o-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?r.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeScrollRegion(n){let e=n._core.buffer,t=e.scrollTop,r=e.scrollBottom;return t!==0||r!==n.rows-1?`\x1B[${t+1};${r+1}r`:""}_serializeModes(n){let e="",t=n.modes;if(t.applicationCursorKeysMode&&(e+="\x1B[?1h"),t.applicationKeypadMode&&(e+="\x1B[?66h"),t.bracketedPasteMode&&(e+="\x1B[?2004h"),t.insertMode&&(e+="\x1B[4h"),t.originMode&&(e+="\x1B[?6h"),t.reverseWraparoundMode&&(e+="\x1B[?45h"),t.sendFocusMode&&(e+="\x1B[?1004h"),t.wraparoundMode===!1&&(e+="\x1B[?7l"),t.mouseTrackingMode!=="none")switch(t.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return t.showCursor||(e+="\x1B[?25l"),e}serialize(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=n?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,n.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,n?.scrollback);if(!n?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let t=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${t}`}return n?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,n??{})}dispose(){}},D=class extends S{constructor(e,t,r){super(e);this._terminal=t;this._options=r;this._currentRow="";this._htmlContent="";t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=k}_beforeSerialize(e,t,r){this._htmlContent+="
";let l="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(l=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+l+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let r=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[r>>16&255,r>>8&255,r&255].map(s=>s.toString(16).padStart(2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[r].css}_getUnderlineColor(e){if(e.isUnderlineColorDefault())return;let t=e.getUnderlineColor();return e.isUnderlineColorRGB()?"#"+[t>>16&255,t>>8&255,t&255].map(l=>l.toString(16).padStart(2,"0")).join(""):this._ansiColors[t].css}_getUnderlineStyle(e){switch(e.getUnderlineStyle()){case 1:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed";default:return"underline"}}_diffStyle(e,t){let r=[];if(U(e,t))return;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i){let o=this._getHexColor(e,!0);o&&r.push("color: "+o+";");let u=this._getHexColor(e,!1);u&&r.push("background-color: "+u+";"),e.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&r.push("font-weight: bold;");let f=[];if(e.isUnderline()&&f.push(this._getUnderlineStyle(e)),e.isOverline()&&f.push("overline"),e.isStrikethrough()&&f.push("line-through"),e.isBlink()&&f.push("blink"),f.length>0&&r.push("text-decoration: "+f.join(" ")+";"),e.isUnderline()){let C=this._getUnderlineColor(e);C&&r.push("text-decoration-color: "+C+";")}return e.isInvisible()&&r.push("visibility: hidden;"),e.isItalic()&&r.push("font-style: italic;"),e.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),i?this._currentRow+=" ":this._currentRow+=z(e.getChars())}_serializeString(){return this._htmlContent}};export{D as HTMLSerializeHandler,H as SerializeAddon}; //# sourceMappingURL=addon-serialize.mjs.map diff --git a/src/SerializeAddon.ts b/src/SerializeAddon.ts -index e1728feb219c362dfa2ecb602ff99f830d520757..672fdd5b86d73d8694446138835bbeccd43cfaae 100644 +index e1728feb219c362dfa2ecb602ff99f830d520757..beaff8dd2c985a1e7378d42683c9940865057d6a 100644 --- a/src/SerializeAddon.ts +++ b/src/SerializeAddon.ts -@@ -310,7 +310,20 @@ class StringSerializeHandler extends BaseSerializeHandler { +@@ -148,6 +148,7 @@ class StringSerializeHandler extends BaseSerializeHandler { + + // this is a null cell for reference for checking whether background is empty or not + private _backgroundCell: IBufferCell = this._buffer.getNullCell(); ++ private _defaultCell: IBufferCell = this._buffer.getNullCell(); + + private _firstRow: number = 0; + private _lastCursorRow: number = 0; +@@ -214,7 +215,7 @@ class StringSerializeHandler extends BaseSerializeHandler { + if ( + // you must output character to cause overflow, control sequence can't do this + nextRowFirstChar.getChars() && +- isNextRowFirstCharDoubleWidth ? this._nullCellCount <= 1 : this._nullCellCount <= 0 ++ (isNextRowFirstCharDoubleWidth ? this._nullCellCount <= 1 : this._nullCellCount <= 0) + ) { + if ( + // the last character can't be null, +@@ -251,9 +252,14 @@ class StringSerializeHandler extends BaseSerializeHandler { + if (this._nullCellCount > 0) { + // do these because we filled the last several null slot, which we shouldn't + rowSeparator += '\u001b[A'; +- rowSeparator += `\u001b[${currentLine.length - this._nullCellCount}C`; ++ const contentCellCount = currentLine.length - this._nullCellCount; ++ if (contentCellCount > 0) { ++ rowSeparator += `\u001b[${contentCellCount}C`; ++ } + rowSeparator += `\u001b[${this._nullCellCount}X`; +- rowSeparator += `\u001b[${currentLine.length - this._nullCellCount}D`; ++ if (contentCellCount > 0) { ++ rowSeparator += `\u001b[${contentCellCount}D`; ++ } + rowSeparator += '\u001b[B'; + } + +@@ -310,7 +316,20 @@ class StringSerializeHandler extends BaseSerializeHandler { } if (flagsChanged) { if (cell.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); } @@ -44,7 +80,7 @@ index e1728feb219c362dfa2ecb602ff99f830d520757..672fdd5b86d73d8694446138835bbecc if (!equalUnderline(cell, oldCell)) { const style = cell.getUnderlineStyle(); if (style === UnderlineStyle.NONE) { -@@ -337,7 +350,7 @@ class StringSerializeHandler extends BaseSerializeHandler { +@@ -337,7 +356,7 @@ class StringSerializeHandler extends BaseSerializeHandler { if (cell.isBlink() !== oldCell.isBlink()) { sgrSeq.push(cell.isBlink() ? 5 : 25); } if (cell.isInvisible() !== oldCell.isInvisible()) { sgrSeq.push(cell.isInvisible() ? 8 : 28); } if (cell.isItalic() !== oldCell.isItalic()) { sgrSeq.push(cell.isItalic() ? 3 : 23); } @@ -53,3 +89,58 @@ index e1728feb219c362dfa2ecb602ff99f830d520757..672fdd5b86d73d8694446138835bbecc if (cell.isStrikethrough() !== oldCell.isStrikethrough()) { sgrSeq.push(cell.isStrikethrough() ? 9 : 29); } } } +@@ -356,12 +375,21 @@ class StringSerializeHandler extends BaseSerializeHandler { + + // this cell don't have content + const isEmptyCell = cell.getChars() === ''; ++ const nextLine = isEmptyCell && cell.isInverse() ? this._buffer.getLine(row + 1) : undefined; ++ const nextRowFirstCell = nextLine?.getCell(0, this._nextRowFirstChar); ++ // A pending wide glyph recreates its own final-column padding during replay. ++ const isWideWrapPadding = col === this._terminal.cols - 1 && ++ nextLine?.isWrapped && ++ (nextRowFirstCell?.getWidth() ?? 0) > 1 && ++ !!nextRowFirstCell && attributesEquals(cell, nextRowFirstCell); ++ // Cursor movement cannot reproduce an inverse cell's visible background. ++ const materializeEmptyCell = isEmptyCell && !!cell.isInverse() && !isWideWrapPadding; + + const sgrSeq = this._diffStyle(cell, this._cursorStyle); + +- // the empty cell style is only assumed to be changed when background changed, because +- // foreground is always 0. +- const styleChanged = isEmptyCell ? !equalBg(this._cursorStyle, cell) : sgrSeq.length > 0; ++ const styleChanged = isEmptyCell ++ ? materializeEmptyCell ? sgrSeq.length > 0 : !equalBg(this._cursorStyle, cell) ++ : sgrSeq.length > 0; + + /** + * handles style change +@@ -395,7 +423,7 @@ class StringSerializeHandler extends BaseSerializeHandler { + /** + * handles actual content + */ +- if (isEmptyCell) { ++ if (isEmptyCell && !materializeEmptyCell) { + this._nullCellCount += cell.getWidth(); + } else { + if (this._nullCellCount > 0) { +@@ -411,7 +439,19 @@ class StringSerializeHandler extends BaseSerializeHandler { + this._nullCellCount = 0; + } + +- this._currentRow += cell.getChars(); ++ if (materializeEmptyCell) { ++ const hasDecoration = !!cell.isUnderline() || !!cell.isStrikethrough() || !!cell.isOverline(); ++ if (hasDecoration) { ++ this._currentRow += '\u001b[24;29;55m'; ++ } ++ this._currentRow += ' '.repeat(cell.getWidth()); ++ if (hasDecoration) { ++ const restoreSgrSeq = this._diffStyle(cell, this._defaultCell); ++ this._currentRow += `\u001b[0m\u001b[${restoreSgrSeq.join(';')}m`; ++ } ++ } else { ++ this._currentRow += cell.getChars(); ++ } + + // update cursor + this._lastContentCursorRow = this._lastCursorRow = row; diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 585640c7b8d..0a010442e1f 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "updatedAt": "2026-08-01", + "updatedAt": "2026-08-03", "policy": { "maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"], "blockingPromotion": { @@ -10,6 +10,101 @@ } }, "gates": [ + { + "id": "editor.restored-sibling-owner-reparent", + "title": "Restored sibling tabs migrate filesystem authority before becoming editable", + "maturity": "experimental", + "protection": "partial", + "owner": "editor-runtime", + "layer": "renderer-store-controller-contract", + "surfaces": [ + "restored editor tabs", + "editor save and autosave", + "filesystem watches and hot-exit persistence" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "ssh", "paired-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local", "ssh", "paired-runtime"], + "coverageNotes": "Deterministic store/controller tests cover local, direct-SSH, paired-runtime identity, folder workspaces, queue quiescence, stale route and connection-generation rejection, authoritative active-workspace projection, owner-derived IDs, drafts and editor maps, tab/group placement, exact watch replacement, change/delete/rename correlation, explicit save, autosave, collision refusal without activation reconciliation, provenance, and restart hot-exit persistence. Live headed/headless paired-runtime and post-establish Electron IPC remain uncollected.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/11304", + "https://github.com/stablyai/orca/pull/11369" + ], + "invariant": "A restored absolute path owned by a same-host sibling workspace cannot read, save, watch, or persist until old saves drain, the exact route and host generations are revalidated, and one authoritative activation transaction installs the sibling owner, target projection, editor state, reconciliation, and first-activation terminal preparation; collisions and stale routes fail before activation preparation or reconciliation.", + "oracle": "Hold an old-owner save in flight, start migration, then remove the sibling, change a folder root, or reconnect SSH and require owner migration to fail closed after quiescence. On a stable route require one coherent target-workspace projection, first-activation terminal generation preparation, destination authority for explicit save and autosave, exact watch replacement, destination-only change/delete/rename handling, owner-derived state rekeys, and hot-exit restart ownership. Seed an invalid destination tab/group model before a collision and require the target projection to remain byte-identical.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/restored-editor-owner-reparent.test.ts src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts src/renderer/src/lib/runtime-workspace-file-route.test.ts" + ], + "testFiles": [ + "src/renderer/src/store/slices/restored-editor-owner-reparent.test.ts", + "src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts", + "src/renderer/src/lib/runtime-workspace-file-route.test.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/store/slices/restored-editor-owner-reparent.test.ts", + "assertions": [ + "one atomic commit rekeys owner-derived editor, preview, draft, cursor, view, tab, group, active, reveal, focus, provenance, and persistence state", + "active reparenting uses the centralized workspace activation transaction for terminal, browser, pending-creation, explorer, first-activation, and post-commit state", + "source watch unsubscribes once, destination watch subscribes once, and only destination change/delete/rename events reach the file", + "dirty and clean destination collisions fail closed without changing either open session or reconciling destination tabs and groups", + "folder and direct-SSH owners retain exact root, host, target, and connection-generation authority" + ] + }, + { + "file": "src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts", + "assertions": [ + "migration waits for the old save queue and routes later explicit and automatic saves through the destination worktree", + "a removed sibling, changed folder root, or changed direct-SSH generation after quiescence rejects migration without changing ownership" + ] + }, + { + "file": "src/renderer/src/lib/runtime-workspace-file-route.test.ts", + "assertions": [ + "same-host runtime, folder, local, and direct-SSH roots resolve without cross-host fallback" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/restored-editor-owner-reparent.test.ts src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts src/renderer/src/lib/runtime-workspace-file-route.test.ts", + "result": "passed", + "durationSeconds": 3, + "summary": "Three deterministic files passed 20 lifecycle, stale-route, activation, ownership, host, collision, persistence, watch, and save tests." + } + ], + "runtimeBudget": { + "p95Seconds": 5, + "scope": "focused renderer store/controller contract on a local development runner" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "One local deterministic run is recorded; CI and soak history have not started." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The final2 verifier's byte-identical post-quiescence lifecycle scope passed 21/21 on 7890271160 and failed 7 tests on f92db196a1; base e08eba674c, published 1bcfe3bcb0, and revert b3627461ab were structurally red. The permanent collision oracle is in test blob ac62a89c671a0c8f081ebf06736715bd2150ce9f (SHA-256 a61970ace80be1cb56f781aee6f878a8446c6c4527f9eb0cd0c151d8df96bf50). The same byte-identical blob is structurally red on base, published, and revert, behaviorally red on rejected final2 candidate 7890271160 because pre-commit reconciliation removes the stale destination tab, and green on implementation b72a838cdc; the full permanent gate passes 20/20." + }, + "performanceBudget": { + "required": true, + "evidence": "Route lookup scans only the already-indexed renderer workspace catalog, while migration is O(open editor files + source/destination tabs/groups) and performs no provider call, Git scan, polling, retry, subprocess, or global fanout beyond the required old/new watch delta." + }, + "promotionCriteria": [ + "Collect two fresh child-verifier decisions against the correction candidate.", + "Collect headed and headless paired-runtime coverage after the post-establish Electron IPC gap is fixed.", + "Collect physical Windows or WSL path/host evidence and CI soak history." + ], + "knownGaps": [ + "Headed Electron post-establish IPC, paired headless, reconnect, and physical Windows/WSL journeys are uncollected.", + "Cold many-repo main-process sibling discovery remains a separately measured follow-up.", + "Registered-workspace symlink policy remains inherited and unchanged." + ], + "demotionRule": "Keep experimental or demote if migration can race a save, retain source authority, fan out watches, lose dirty/editor state, accept an owner-generation change, merge a collision, or the focused contract flakes without a product or harness bug." + }, { "id": "terminal-provider.login-session-retirement", "title": "macOS login-session retirement preserves live daemons through transient rejection bursts", @@ -1031,6 +1126,126 @@ ], "demotionRule": "Demote if any probe can run before lifecycle ownership, if more than one shared heartbeat timer is armed, if first-socket cleanup exceeds one interval, if later-socket cleanup exceeds two intervals, or if close/error cleanup retains listeners or timers." }, + { + "id": "runtime.streaming-subscription-close-delivery", + "title": "Retiring a runtime transport always tells the renderer its streams closed", + "maturity": "experimental", + "protection": "partial", + "owner": "runtime-platform", + "layer": "runtime-subscription-ipc-contract", + "surfaces": [ + "paired remote server", + "runtime environment disconnect and re-pair", + "terminal.multiplex streaming", + "browser screencast streaming", + "parked remote terminal reveal" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["remote-runtime"], + "coverageNotes": "Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "motivatingLinks": [ + "tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts", + "docs/reference/headless-linux-server.md" + ], + "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", + "oracle": "The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments.test.ts", + "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/main/ipc/runtime-environments.test.ts", + "tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/main/ipc/runtime-environments.test.ts", + "assertions": [ + "tells the renderer when retiring the transport closes its streaming subscription (the load-bearing repro; red with the fix reverted)", + "retires an environment's remaining subscriptions when one teardown throws (load-bearing; red without per-subscription isolation)", + "contains a throwing renderer send on a host-initiated close (load-bearing; red without the guarded send, and the only coverage of the unguarded notifyClosed call site)", + "retires remaining subscriptions when a liveness probe inside notifyClosed throws (load-bearing; keeps the isolation structural rather than comment-asserted)", + "suppresses stale payloads from a retired transport but never re-sends its close (forward guard on the retained generation gate, not a repro)" + ] + }, + { + "file": "tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts", + "assertions": [ + "a revealed hidden-but-mounted remote terminal restores, accepts input, and paints live", + "a revealed cold-parked remote terminal restores, accepts input, and paints live", + "a cold-parked remote terminal revealed after a runtime disconnect and reconnect restores, accepts input, and paints live", + "the host PTY grid converges on the revealed pane grid in every scenario" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments.test.ts", + "result": "passed", + "durationSeconds": 0.81, + "summary": "53 runtime environment IPC tests passed, including the new close-delivery, both teardown-isolation, transport-path containment, and stale-payload-suppression contracts." + }, + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 15.5, + "summary": "All three reveal scenarios restored their buffer, delivered typed input to the host PTY, painted live without a tab flip, and converged the PTY on the 135x60 pane grid. Before the fix the reconnect-parked scenario stayed blank at recoveryState connecting with the PTY stranded at the host 128x60 grid." + }, + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 15.5, + "summary": "Repeat run on a clean uninstrumented build; all three scenarios green with identical grids." + }, + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 14.7, + "summary": "Third consecutive pass after the review follow-ups (env save/restore and the hidden-mounted stayed-mounted assertion)." + } + ], + "runtimeBudget": { + "p95Seconds": 60, + "scope": "focused runtime environment IPC tests plus one headed paired-server reveal journey" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "Deterministic IPC coverage plus the three recorded paired-server journey runs, which passed consecutively on macOS at 14.7-15.5s; the spec also passed once on a shared CI runner. Longer soak history is not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "On main the paired-server journey reproduced a blank, non-interactive pane after revealing a cold-parked remote terminal across a reconnect: recoveryState stayed connecting, the xterm buffer stayed empty, typed input never reached the host sink, a tab flip did not recover it, and the PTY stayed at the host 128x60 grid. Renderer instrumentation showed the multiplexer reusing a dead subscription (ensureConnected reuse-ready) and never receiving a subscribed event. Reverting the main-side fix also turns the close-delivery IPC test red; with the fix the multiplexer observes handleClose, reconnects fresh, and every scenario passes." + }, + "performanceBudget": { + "required": true, + "evidence": "The fix adds one boolean latch and at most one extra IPC send per retired subscription, on a path that already tears the subscription down. It introduces no timer, poll, retry, subprocess, or per-frame work, and the close is deduplicated so a transport-driven close after an environment-wide retirement sends nothing." + }, + "promotionCriteria": [ + "Collect at least 100 consecutive CI or soak passes or 14 days without an unexplained flake.", + "Collect live Linux and Windows paired-server reveal evidence.", + "Add real sleep/wake and network-loss transport drops alongside the explicit disconnect trigger." + ], + "knownGaps": [ + "Live paired-server validation currently covers macOS host and client only.", + "The transport drop is an explicit runtime disconnect; real sleep/wake and network partitions are not yet exercised by this gate.", + "Browser screencast subscribers share the fixed contract but have no dedicated reveal journey; the web and mobile clients run parallel transports and are unaffected." + ], + "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." + }, { "id": "editor.live-log-append-stability", "title": "Long live session logs retain their Monaco viewport while appending", @@ -1695,13 +1910,15 @@ "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", "oracle": "Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/methods/session-tabs-schemas.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime-client.test.ts src/shared/remote-runtime-request-connection.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-server-kill-attribution.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/runtime-close-attribution-topology.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/methods/session-tabs-schemas.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime-client.test.ts src/shared/remote-runtime-request-connection.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts", "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ + "src/main/daemon/daemon-server-kill-attribution.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/main/runtime/remote-runtime-request-connection.integration.test.ts", + "src/main/runtime/rpc/runtime-close-attribution-topology.test.ts", "src/main/runtime/rpc/methods/session-tabs.test.ts", "src/main/runtime/rpc/methods/session-tabs-schemas.test.ts", "src/main/runtime/rpc/e2ee-channel.test.ts", @@ -1723,6 +1940,19 @@ "tests/e2e/daemon-generation-legacy-close-safety.spec.ts" ], "assertionRefs": [ + { + "file": "src/main/daemon/daemon-server-kill-attribution.test.ts", + "assertions": [ + "successful and failed daemon kill requests retain the authenticated control-client identity without claiming a failed kill succeeded" + ] + }, + { + "file": "src/main/runtime/rpc/runtime-close-attribution-topology.test.ts", + "assertions": [ + "remote, legacy, reconnect, stale, concurrent, cross-worktree, and unowned close spans retain authoritative runtime, target, requester, decision, and outcome identities without serializing the bearer credential", + "close attribution adds no terminal inventory scan or provider fanout" + ] + }, { "file": "src/main/runtime/remote-runtime-request-connection.integration.test.ts", "assertions": [ @@ -2108,6 +2338,120 @@ ], "demotionRule": "Demote or quarantine if the gate flakes without a product or harness bug, if a Pi handler can again await receiver I/O, or if coalescing allows an older status to overwrite a newer one." }, + { + "id": "agent-status.manual-compact-identity", + "title": "Manual Claude compact completion retires only its exact status generation", + "maturity": "experimental", + "protection": "partial", + "owner": "agent-session", + "layer": "shared-main-relay-contract", + "surfaces": [ + "Claude status hooks", + "manual compact lifecycle", + "last-status persistence", + "SSH relay ingest" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local", "ssh"], + "coverageNotes": "Deterministic listener, loopback HTTP, relay-restart, persisted-restore, and fake-SSH transport contracts run on macOS. Claude Code 2.1.220 captures prove manual PreCompact starts a new prompt UUID and exact PreCompact/PostCompact pairs share it. The shared Node paths are platform-independent; live Linux, Windows, WSL, and paired-runtime journeys remain gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/11352", + "https://github.com/stablyai/orca/pull/11353" + ], + "invariant": "A Claude manual PreCompact may replace only a current Claude row from the same receiving connection and provider session; a manual PostCompact may mark done only when the current authoritative row is its exact manual PreCompact generation, including provider prompt UUID. Missing identity is never a wildcard; later cross-provider work, replay, duplication, pane or tab retirement, and server stop invalidate completion. Automatic Claude and Kimi completion remain fail-closed until their hooks expose independently proven generation identity.", + "oracle": "Run one byte-identical state-machine oracle plus local HTTP, relay-restart, SSH, and persisted-restore streams using Claude's observed different prior-turn and compact prompt UUIDs. Require matching manual completion to emit done while wrong or absent prompt UUID, session-presence mismatch, wrong source or connection, stale replay and duplicate delivery, later Codex work, automatic completion, and lifecycle cleanup cannot retire the current row. Assert both emitted event order and the authoritative lastStatusByPaneKey snapshot.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/shared/manual-compact-prompt-identity.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot", + "Manual Claude Code 2.1.220 interactive compact: isolate UserPromptSubmit, PreCompact, and PostCompact hooks; submit one ordinary prompt then /compact; compare source, trigger, session_id, and prompt_id" + ], + "testFiles": [ + "src/shared/manual-compact-prompt-identity.test.ts", + "src/main/agent-hooks/manual-compact-hook-stream.test.ts", + "src/main/agent-hooks/manual-compact-status-cleanup.test.ts", + "src/shared/agent-hook-listener.test.ts", + "src/shared/agent-hook-relay.test.ts", + "src/relay/agent-hook-server.test.ts", + "src/main/agent-hooks/server.test.ts", + "src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts" + ], + "assertionRefs": [ + { + "file": "src/shared/manual-compact-prompt-identity.test.ts", + "assertions": [ + "matching manual identity settles once", + "stale, duplicate, session-mismatched, malformed, automatic, and unproven provider completion fail closed", + "4,097 rejected pane keys allocate no ownership state" + ] + }, + { + "file": "src/main/agent-hooks/manual-compact-hook-stream.test.ts", + "assertions": [ + "local HTTP and relay-restart streams preserve the distinct prior-turn and compact prompt identities", + "later provider work and wrong transport identity remain authoritative", + "persisted PreCompact restores its prompt" + ] + }, + { + "file": "src/main/agent-hooks/manual-compact-status-cleanup.test.ts", + "assertions": ["pane, tab, and server cleanup revoke compact completion authority"] + }, + { + "file": "src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts", + "assertions": [ + "SSH stamps the receiving connection and forwards source, prompt UUID, session, and manual trigger" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-02", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/shared/manual-compact-prompt-identity.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 2.66, + "summary": "Eight focused files and 435 tests passed with local HTTP, relay, SSH, persistence, adversarial identity, cleanup, and existing provider-regression coverage." + }, + { + "date": "2026-08-02", + "runner": "manual", + "platform": "macos", + "command": "Manual Claude Code 2.1.220 interactive compact: isolate UserPromptSubmit, PreCompact, and PostCompact hooks; submit one ordinary prompt then /compact; compare source, trigger, session_id, and prompt_id", + "result": "passed", + "durationSeconds": 120, + "summary": "A fresh capture proved /compact emits no UserPromptSubmit and its PreCompact uses a new UUID distinct from the preceding user turn; the preserved authenticated capture proved the matching manual PreCompact and PostCompact share that UUID and session. Automatic capture reused one prompt UUID across multiple compact generations, so automatic completion remains disabled." + } + ], + "runtimeBudget": { + "p95Seconds": 20, + "scope": "shared, main-process, relay, persistence, and fake-SSH contract tests" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "New deterministic gate with one local run; CI soak history is not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The byte-identical oracle (SHA-256 24e80c15b467ffa9c47a81099f11bf26dea71293e47b5d950b2fad1497094764) failed 5 of 6 on origin/main@a20165a43d, passed 6 of 6 on the candidate, failed 3 of 6 when only the exact-transition guard was disabled, and passed 6 of 6 after restoration." + }, + "performanceBudget": { + "required": true, + "evidence": "Each compact event performs one O(1) current-status lookup plus bounded UUID, source, connection, session, and event comparisons. Identity lives on the existing status row and is removed by its existing lifecycle; the change adds no owner map, global scan, polling, timer, subprocess, network request, or listener. The 4,097-key adversarial arm retains zero status, prompt, or ownership entries." + }, + "promotionCriteria": [ + "Collect 100 consecutive focused CI passes or 14 days of soak history.", + "Run live manual compact journeys on Linux and Windows and through a real SSH target.", + "Keep automatic compact completion disabled until a generation-unique provider identity is proven." + ], + "knownGaps": [ + "No live Linux, Windows, WSL, paired-runtime, or real-SSH manual compact journey was run.", + "Claude versions before prompt_id support intentionally cannot complete a manual compact row through PostCompact.", + "Automatic Claude and Kimi completion remain intentionally fail-closed because their hooks do not prove an exact compact generation." + ], + "demotionRule": "Demote or quarantine if identity-mismatched completion can retire newer work, cleanup retains compact authority, or the focused gate flakes without a product or harness bug." + }, { "id": "agent-session.provider-ownership", "title": "Provider sessions are resumed once per workspace ownership claim", @@ -6511,15 +6855,16 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh"], - "coverageNotes": "A deterministic service-state-machine oracle now models a current-contract worker and coordinator whose renderer graph identities disappear across an app/runtime update. It exercises the production verifier with restored PTY and hydrated hook commitments, proves authenticated completion replay across a fresh runtime, explicit takeover, ordinary mail routing, remote-attachment process fencing, retained Task/Dispatch/terminal identity, and unchanged fixture marker bytes, and rejects foreign pane evidence. Other deterministic units cover authority-aware legacy formatting, exact legacy worker identity planning, local worker presentation, retained-output reads after adoption, reveal-failure warnings, stable-pane Run/Dispatch routing, the SSH in-process CLI fallback, and federated non-reveal. Two isolated macOS Electron journeys launch fake Codex workers through the real RPC path and record append-only spawn/interruption ledgers. They assert immediate inactive presentation, one live agent PID, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, and no interruption after workspace re-entry; the restart journey additionally removes renderer ownership, marks the Dispatch legacy, retains the daemon process across an app restart, and proves exact background adoption with readable ACK output and no resume replay. Distinct A/B artifacts plus live SSH, WSL, folder, remote-runtime, Linux, and Windows cutover journeys remain explicit gaps.", + "coverageNotes": "A deterministic service-state-machine oracle now models a current-contract worker and coordinator whose renderer graph identities disappear across an app/runtime update. It exercises the production verifier with restored PTY and hydrated hook commitments, proves authenticated completion replay across a fresh runtime, explicit takeover, ordinary mail routing, remote-attachment process fencing, retained Task/Dispatch/terminal identity, and unchanged fixture marker bytes, and rejects foreign pane evidence. Other deterministic units cover authority-aware legacy formatting, exact legacy worker identity planning, local worker presentation, retained-output reads after adoption, reveal-failure warnings, stable-pane Run/Dispatch routing, creator pane/process/Run-generation fencing, indexed retained-Run lookup scaling, the SSH in-process CLI fallback, and federated non-reveal. Two isolated macOS Electron journeys launch fake Codex workers through the real RPC path and record append-only spawn/interruption ledgers. They assert immediate inactive presentation, one live agent PID, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, and no interruption after workspace re-entry; the restart journey additionally removes renderer ownership, marks the Dispatch legacy, retains the daemon process across an app restart, and proves exact background adoption with readable ACK output and no resume replay. Distinct A/B artifacts plus live SSH, WSL, folder, remote-runtime, Linux, and Windows cutover journeys remain explicit gaps.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/11107#discussion_r3663321387"], - "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata, explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", - "oracle": "Drive Run create, Task create, and worker-start through production Electron runtimes with a deterministic Codex fixture. Require append-only ledgers with one still-live PID and no interruption, a visible inactive worker tab while the coordinator stays active, Run delivery through stable pane identity, and stable PTY/incarnation, tab, leaf, worktree, Task, and Dispatch across workspace re-entry. In a restart journey, retain the original daemon PTY and PID, remove renderer ownership, retain sleeping-session evidence, mark the Dispatch legacy, relaunch, and require exact inactive tab adoption, readable ACK output, cleared resume state, one spawn, and no resume argv or Conversation interrupted text after another workspace round trip. The service oracle removes renderer lookup identity from current-contract callers while retaining real restored-PTY and hook commitments, replays authenticated completion and takeover across fresh runtimes, and requires one Task, Dispatch, terminal authority, message, mutation, ordinary-mail delivery, remote process fencing, and unchanged fixture marker bytes while foreign pane evidence remains rejected. Unit tests separately assert authority-specific legacy affordances, exact identity and owner matching, retained-output fallback, pane-stable routing, federated non-activation, and SSH fallback parity.", + "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", + "oracle": "Drive Run create, Task create, and worker-start through production Electron runtimes with a deterministic Codex fixture. Require append-only ledgers with one still-live PID and no interruption, a visible inactive worker tab while the coordinator stays active, Run delivery through stable pane identity, and stable PTY/incarnation, tab, leaf, worktree, Task, and Dispatch across workspace re-entry. In a restart journey, retain the original daemon PTY and PID, remove renderer ownership, retain sleeping-session evidence, mark the Dispatch legacy, relaunch, and require exact inactive tab adoption, readable ACK output, cleared resume state, one spawn, and no resume argv or Conversation interrupted text after another workspace round trip. The service oracle removes renderer lookup identity from current-contract callers while retaining real restored-PTY and hook commitments, replays authenticated completion and takeover across fresh runtimes, and requires one Task, Dispatch, terminal authority, message, mutation, ordinary-mail delivery, remote process fencing, and unchanged fixture marker bytes while foreign pane evidence remains rejected. Unit tests separately remint a creator pane and process from Run A into Run B, require the nested Run A worker to fall back to its current coordinator, require indexed query plans, and bound 300 Task reads with 50,000 retained Runs. They also assert authority-specific legacy affordances, exact identity and owner matching, retained-output fallback, pane-stable routing, federated non-activation, and SSH fallback parity.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/ssh/ssh-remote-orca-cli.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/formatter.test.ts src/main/runtime/rpc/methods/orchestration-federation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts", "pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1" @@ -6528,6 +6873,7 @@ "src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts", "src/main/runtime/orchestration/formatter.test.ts", "src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts", + "src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/cli/handlers/orchestration.test.ts", "src/cli/handlers/orchestration-check-identity.test.ts", @@ -6549,6 +6895,13 @@ "ordinary mail and remote attachments use the same attested pane and process authority" ] }, + { + "file": "src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts", + "assertions": [ + "creator lookup uses the assignee-handle and pane-leaf indexes without a retained-Run scan", + "300 Task reads remain bounded with 50,000 unrelated retained Runs" + ] + }, { "file": "src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts", "assertions": [ @@ -6733,6 +7086,104 @@ ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, + { + "id": "orchestration.settled-worker-terminal-release", + "title": "Settled worker cleanup preserves one exact terminal lease and immutable output", + "maturity": "experimental", + "protection": "partial", + "owner": "orchestration", + "layer": "runtime-sqlite-terminal-lifecycle", + "surfaces": [ + "worker-release", + "worker-retain", + "explicit terminal reuse", + "restart reconciliation", + "worker-read archives", + "orchestration reset" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local"], + "coverageNotes": "Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, conservative schema-v23 backfill, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. Live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps.", + "motivatingLinks": ["https://github.com/stablyai/orca/pull/12355", "STA-905"], + "invariant": "A settled Dispatch may close only its one coordinator-created terminal lease. Explicit reuse, real user input, retain, identity or host change, ambiguity, and another resource for the same exact host/pane/process must fence closure. Output preservation and the requested-to-releasing transition are atomic, archives remain readable without the provider file, retries resume idempotently, and orchestration reset removes archive and authority state.", + "oracle": "Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain and real user input against a controlled archive promise and require no committed archive or close. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-release.test.ts src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/worker-transcript-read.test.ts src/renderer/src/lib/worker-terminal-takeover-report.test.ts --reporter=dot" + ], + "testFiles": [ + "src/main/runtime/rpc/methods/orchestration-worker-release.test.ts", + "src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts", + "src/main/runtime/rpc/orchestration-mutation-ledger.test.ts", + "src/main/runtime/orchestration/worker-transcript-read.test.ts", + "src/renderer/src/lib/worker-terminal-takeover-report.test.ts" + ], + "assertionRefs": [ + { + "file": "src/main/runtime/rpc/methods/orchestration-worker-release.test.ts", + "assertions": [ + "rejects exact reuse after release intent instead of closing the new worker", + "lets an explicit retain cancel a release while output capture is pending", + "retains when the terminal host scope changed instead of closing", + "reads an immutable transcript snapshot after the provider file disappears", + "backfills a legacy creator plus explicit reuser as ambiguous", + "removes terminal authority and archived output on orchestration reset" + ] + }, + { + "file": "src/main/runtime/rpc/orchestration-mutation-ledger.test.ts", + "assertions": ["resumes a pending idempotent worker release after restart"] + }, + { + "file": "src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts", + "assertions": [ + "finishes a requested release after restart-style interruption", + "coalesces overlapping reconciliation passes and closes each resource once", + "keeps live terminals bounded across 50 settled workers while controls survive" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-03", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-release.test.ts src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/worker-transcript-read.test.ts src/renderer/src/lib/worker-terminal-takeover-report.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 3.48, + "summary": "Five focused files passed 56 tests covering lease serialization, reminted-handle transfer, duplicate-identity fencing, retain and takeover races, immutable archives, conservative legacy migration, mutation restart, reset cleanup, bounded accounting, and renderer input reporting." + } + ], + "runtimeBudget": { + "p95Seconds": 8, + "scope": "deterministic runtime, SQLite, transcript, renderer-input, and mutation contracts" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "First local deterministic run only; focused CI and soak history are not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The byte-identical 56-test oracle produced 12 deterministic failures and 44 passes with production restored to exact PR head 4aa66b62e3, including ready reuse during release, unsafe migration, stale archives, mutable transcript output, host/identity close gaps, and mutation replay loss. Candidate 457bc4edd1 passed all 56; restoring the same five production files to 4aa66b62e3 reproduced the same red state." + }, + "performanceBudget": { + "required": true, + "evidence": "Release performs constant-count indexed resource and identity queries plus one bounded archive capture. Worker-list uses two set queries rather than one resource lookup per worker. Reconciliation remains serial and adds no polling, timers, subprocesses, renderer subscriptions, or provider-wide listing." + }, + "promotionCriteria": [ + "Collect 100 consecutive focused CI passes or 14 days of soak history.", + "Add live headed and headless paired-runtime release/reuse journeys.", + "Add Docker SSH reconnect and physical Windows WSL host-scope evidence.", + "Prove provider-close lost acknowledgements converge with an exact durable close receipt." + ], + "knownGaps": [ + "Provider close has no durable cross-process operation receipt, so a crash after host mutation but before SQLite settlement remains release_pending until exact inventory returns.", + "Federated release remains explicitly unsupported and retained.", + "Mobile/direct remote input takeover and live Linux, Windows, WSL, SSH, headed, and headless paired-runtime release are not exercised." + ], + "demotionRule": "Keep experimental or demote if release can overlap exact reuse, close a conflicting lease, lose immutable output, retain reset archives, fan out per worker, or any focused ordering test flakes without a product or harness defect." + }, { "id": "terminal-render.windows-cjk-repaint", "title": "Windows ConPTY wide glyphs and cursor rewrites repaint without stale cells", diff --git a/config/scripts/adhoc-build-version.mjs b/config/scripts/adhoc-build-version.mjs index db7c95676d7..b62f28d1c4f 100644 --- a/config/scripts/adhoc-build-version.mjs +++ b/config/scripts/adhoc-build-version.mjs @@ -2,6 +2,10 @@ import { execFileSync } from 'node:child_process' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { formatReleaseTitleTimestamp } from './release-title-timestamp.mjs' +import { + readPublishedVersionsFromEnv, + resolveDevChannelBaseVersion +} from './dev-channel-base-version.mjs' /** Long enough to name a feature, short enough that a picker row stays readable. */ export const ADHOC_LABEL_MAX_LENGTH = 32 @@ -83,12 +87,13 @@ export function formatAdhocReleaseName(version, label, commit, date) { ].join(' • ') } -export function getAdhocBuildIdentity(now = new Date(), label = '') { +export function getAdhocBuildIdentity(now = new Date(), label = '', publishedVersions = []) { const packageJson = JSON.parse(readFileSync(resolve('package.json'), 'utf8')) const commit = execFileSync('git', ['rev-parse', '--short=12', 'HEAD'], { encoding: 'utf8' }).trim() - const version = createAdhocBuildVersion(packageJson.version, now) + const base = resolveDevChannelBaseVersion(packageJson.version, publishedVersions) + const version = createAdhocBuildVersion(base, now) return { commit, version, @@ -98,7 +103,11 @@ export function getAdhocBuildIdentity(now = new Date(), label = '') { } if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) { - const identity = getAdhocBuildIdentity(new Date(), process.env.ORCA_ADHOC_LABEL ?? '') + const identity = getAdhocBuildIdentity( + new Date(), + process.env.ORCA_ADHOC_LABEL ?? '', + readPublishedVersionsFromEnv() + ) // Consumed by the workflow via $GITHUB_OUTPUT. process.stdout.write( `version=${identity.version}\ncommit=${identity.commit}\nlabel=${identity.label}\nname=${identity.name}\n` diff --git a/config/scripts/build-windows-cli-launcher.test.mjs b/config/scripts/build-windows-cli-launcher.test.mjs index 0d14e2373b6..4bb219a5687 100644 --- a/config/scripts/build-windows-cli-launcher.test.mjs +++ b/config/scripts/build-windows-cli-launcher.test.mjs @@ -1,4 +1,12 @@ -import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import { spawnSync } from 'node:child_process' @@ -6,6 +14,21 @@ import { describe, expect, it } from 'vitest' const itCrossHost = process.platform === 'win32' ? it.skip : it const projectRoot = resolve(import.meta.dirname, '../..') +const WINDOWS_LOCK_CODES = ['EBUSY', 'ENOTEMPTY', 'EPERM'] + +// Why: Windows releases the image handle on a just-executed exe (and finishes the +// AV scan of the freshly compiled one) after the process exits, so tearing down the +// fixture races those locks. Retry, then leave the temp tree rather than reporting a +// teardown lock as a launcher failure. +function removeFixtureTree(path) { + try { + rmSync(path, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) + } catch (error) { + if (process.platform !== 'win32' || !WINDOWS_LOCK_CODES.includes(error?.code)) { + throw error + } + } +} // Why: cold csc.exe startup exceeds Vitest's 5s unit budget on hosted Windows; // keep the larger allowance scoped to the real compiler integration test. function itWindows(name, test) { @@ -27,10 +50,24 @@ describe('Windows CLI launcher', () => { expect(result.stderr).toContain('Windows CLI launcher') expect(result.stderr).toContain('Windows host') } finally { - rmSync(outputRoot, { recursive: true, force: true }) + removeFixtureTree(outputRoot) } }) + itCrossHost('never materializes the child environment block from ProcessStartInfo', () => { + // Why: both ProcessStartInfo env properties copy the process block into a case-insensitive + // dictionary that throws when the inherited block holds PATH and Path (stablyai/orca#12046). + const source = readFileSync( + join(projectRoot, 'native', 'windows-cli-launcher', 'OrcaCliLauncher.cs'), + 'utf8' + ) + const code = source.replace(/^\s*\/\/.*$/gm, '') + + expect(code).not.toContain('EnvironmentVariables') + expect(code).not.toContain('startInfo.Environment') + expect(code).toContain('Environment.SetEnvironmentVariable') + }) + itWindows('preserves a multiline argument from PowerShell through the native launcher', () => { const appRoot = mkdtempSync(join(tmpdir(), 'orca cli launcher ')) try { @@ -86,7 +123,73 @@ describe('Windows CLI launcher', () => { orcaNodeOptions: '--no-warnings' }) } finally { - rmSync(appRoot, { recursive: true, force: true }) + removeFixtureTree(appRoot) + } + }) + + itWindows('survives an inherited environment block containing PATH and Path', () => { + const appRoot = mkdtempSync(join(tmpdir(), 'orca duplicate path launcher ')) + try { + const resourcesPath = join(appRoot, 'resources') + const launcherPath = join(resourcesPath, 'bin', 'orca.exe') + const cliPath = join(resourcesPath, 'app.asar.unpacked', 'out', 'cli', 'index.js') + const outputPath = join(appRoot, 'child-result.json') + const harnessSourcePath = join( + projectRoot, + 'config', + 'scripts', + 'fixtures', + 'DuplicatePathProcessLauncher.cs' + ) + const harnessPath = join(appRoot, 'DuplicatePathLauncher.exe') + mkdirSync(dirname(launcherPath), { recursive: true }) + mkdirSync(dirname(cliPath), { recursive: true }) + copyFileSync(process.execPath, join(appRoot, 'Orca.exe')) + writeFileSync( + cliPath, + `require('node:fs').writeFileSync(process.env.ORCA_TEST_OUTPUT, JSON.stringify({ + electronRunAsNode: process.env.ELECTRON_RUN_AS_NODE, + pathKeys: Object.keys(process.env).filter((key) => key.toLowerCase() === 'path') +}))\n`, + 'utf8' + ) + const build = spawnSync( + process.execPath, + ['config/scripts/build-windows-cli-launcher.mjs', '--output', launcherPath], + { cwd: projectRoot, encoding: 'utf8' } + ) + expect(build.status, `${build.stdout}\n${build.stderr}`).toBe(0) + + const compiler = findFrameworkCompiler() + expect(compiler).not.toBeNull() + const compileHarness = spawnSync( + compiler, + ['/nologo', '/target:exe', `/out:${harnessPath}`, harnessSourcePath], + { encoding: 'utf8' } + ) + expect(compileHarness.status, `${compileHarness.stdout}\n${compileHarness.stderr}`).toBe(0) + + const launch = spawnSync(harnessPath, [launcherPath, outputPath], { encoding: 'utf8' }) + expect(launch.status, `${launch.stdout}\n${launch.stderr}`).toBe(0) + expect(JSON.parse(readFileSync(outputPath, 'utf8'))).toEqual({ + electronRunAsNode: '1', + pathKeys: ['PATH', 'Path'] + }) + } finally { + removeFixtureTree(appRoot) } }) }) + +function findFrameworkCompiler() { + const windowsDirectory = process.env.WINDIR ?? process.env.SystemRoot + if (!windowsDirectory) { + return null + } + return ( + [ + join(windowsDirectory, 'Microsoft.NET', 'Framework64', 'v4.0.30319', 'csc.exe'), + join(windowsDirectory, 'Microsoft.NET', 'Framework', 'v4.0.30319', 'csc.exe') + ].find((candidate) => existsSync(candidate)) ?? null + ) +} diff --git a/config/scripts/dev-channel-base-version.mjs b/config/scripts/dev-channel-base-version.mjs new file mode 100644 index 00000000000..62a28c6a374 --- /dev/null +++ b/config/scripts/dev-channel-base-version.mjs @@ -0,0 +1,66 @@ +const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/ + +function parseVersionTriple(value) { + const match = SEMVER.exec(String(value ?? '').trim()) + if (!match) { + return null + } + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + prerelease: match[4] ?? null + } +} + +function compareTriples(a, b) { + return a.major - b.major || a.minor - b.minor || a.patch - b.patch +} + +/** + * The base `X.Y.Z` an hourly or adhoc build should carry. + * + * Why not package.json alone: main's version only moves on `release:` commits, and + * stable patches are cut from release branches that never merge back. On + * 2026-08-03 main read `1.4.165-rc.0` for twenty hours while 1.4.165, 1.4.166 and + * 1.4.167 all shipped — so hourlies built from that main claimed 1.4.165 while + * carrying code newer than 1.4.167, and sorted *below* the stable their user was + * already running. Published tags are the only honest answer to "what number is + * taken"; package.json is a floor, not a source of truth. + */ +export function resolveDevChannelBaseVersion(packageVersion, publishedVersions = []) { + const fromPackage = parseVersionTriple(packageVersion) + if (!fromPackage) { + throw new Error(`Package version is not valid semver: ${packageVersion}`) + } + + // Unparseable tags are skipped rather than fatal: the main repo carries old tags + // that predate the current scheme, and one of them must not fail every build. + const published = publishedVersions.map(parseVersionTriple).filter(Boolean) + + let base = fromPackage + if (published.length > 0) { + const highest = published.reduce((best, entry) => + compareTriples(entry, best) > 0 ? entry : best + ) + // A shipped stable owns its number, so the next dev build belongs on the patch + // above it. A bare prerelease does not — rc.1 of 1.4.168 means 1.4.168 is still + // the version being worked toward, which is exactly what main is building. + const shipped = published.some( + (entry) => !entry.prerelease && compareTriples(entry, highest) === 0 + ) + const next = shipped ? { ...highest, patch: highest.patch + 1 } : highest + if (compareTriples(next, base) > 0) { + base = next + } + } + + return `${base.major}.${base.minor}.${base.patch}` +} + +/** Tag list the workflow reads out of the main repo, newline separated. */ +export function readPublishedVersionsFromEnv(value = process.env.ORCA_PUBLISHED_VERSIONS) { + return String(value ?? '') + .split(/\s+/) + .filter(Boolean) +} diff --git a/config/scripts/dev-channel-base-version.test.mjs b/config/scripts/dev-channel-base-version.test.mjs new file mode 100644 index 00000000000..d2631eff0e9 --- /dev/null +++ b/config/scripts/dev-channel-base-version.test.mjs @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { + readPublishedVersionsFromEnv, + resolveDevChannelBaseVersion +} from './dev-channel-base-version.mjs' + +describe('dev channel base version', () => { + it('falls back to package.json when no tags are supplied', () => { + expect(resolveDevChannelBaseVersion('1.4.168-rc.1')).toBe('1.4.168') + expect(resolveDevChannelBaseVersion('1.4.168', [])).toBe('1.4.168') + }) + + // The bug this exists for: main sat at 1.4.165-rc.0 for twenty hours while three + // stables shipped, so hourlies claimed a version their users had already passed. + it('climbs past stables that shipped while main stood still', () => { + expect( + resolveDevChannelBaseVersion('1.4.165-rc.0', [ + 'v1.4.165', + 'v1.4.166', + 'v1.4.167', + 'v1.4.165-rc.0' + ]) + ).toBe('1.4.168') + }) + + // Why +1 on a stable but not on a prerelease: 1.4.167 is spent, so the next dev + // build is 1.4.168. But 1.4.168-rc.1 means 1.4.168 is still being built toward, + // which is what main holds — claiming 1.4.169 would jump a release nobody cut. + it('takes the patch above a shipped stable and holds at an open prerelease', () => { + expect(resolveDevChannelBaseVersion('1.4.167', ['v1.4.167'])).toBe('1.4.168') + expect(resolveDevChannelBaseVersion('1.4.168-rc.1', ['v1.4.168-rc.1'])).toBe('1.4.168') + }) + + // Why max and not most-recent: a hotfix on an old line published today would + // otherwise drag every subsequent hourly backwards. + it('reads the highest tag, not the last one listed', () => { + expect(resolveDevChannelBaseVersion('1.4.160', ['v1.4.167', 'v1.3.99', 'v1.4.120'])).toBe( + '1.4.168' + ) + }) + + it('treats package.json as a floor when it leads the tags', () => { + expect(resolveDevChannelBaseVersion('1.5.0-rc.0', ['v1.4.167'])).toBe('1.5.0') + }) + + // Why skipped rather than fatal: the main repo carries legacy tags, and one + // unparseable entry must not fail every hourly build. + it('ignores tags it cannot parse', () => { + expect(resolveDevChannelBaseVersion('1.4.160', ['nightly', '', 'v1.4.167', 'latest'])).toBe( + '1.4.168' + ) + }) + + it('rejects a package version that is not semver', () => { + expect(() => resolveDevChannelBaseVersion('not-a-version')).toThrow(/not valid semver/) + }) + + it('carries major and minor rollovers through the bump', () => { + expect(resolveDevChannelBaseVersion('1.4.0', ['v2.0.0'])).toBe('2.0.1') + }) + + it('splits an env tag list on any whitespace', () => { + expect(readPublishedVersionsFromEnv('v1.4.167\nv1.4.166\n')).toEqual(['v1.4.167', 'v1.4.166']) + expect(readPublishedVersionsFromEnv('')).toEqual([]) + expect(readPublishedVersionsFromEnv(undefined)).toEqual([]) + }) +}) diff --git a/config/scripts/fixtures/DuplicatePathProcessLauncher.cs b/config/scripts/fixtures/DuplicatePathProcessLauncher.cs new file mode 100644 index 00000000000..6b46382103b --- /dev/null +++ b/config/scripts/fixtures/DuplicatePathProcessLauncher.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; + +internal static class DuplicatePathProcessLauncher +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct StartupInfo + { + public int cb; + public string lpReserved; + public string lpDesktop; + public string lpTitle; + public int dwX; + public int dwY; + public int dwXSize; + public int dwYSize; + public int dwXCountChars; + public int dwYCountChars; + public int dwFillAttribute; + public int dwFlags; + public short wShowWindow; + public short cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + private struct ProcessInformation + { + public IntPtr hProcess; + public IntPtr hThread; + public int dwProcessId; + public int dwThreadId; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool CreateProcess( + string applicationName, + StringBuilder commandLine, + IntPtr processAttributes, + IntPtr threadAttributes, + bool inheritHandles, + uint creationFlags, + IntPtr environment, + string currentDirectory, + ref StartupInfo startupInfo, + out ProcessInformation processInformation + ); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode); + + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + private static int Main(string[] args) + { + List entries = new List(); + foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) + { + if (!String.Equals((string)entry.Key, "PATH", StringComparison.OrdinalIgnoreCase)) + { + entries.Add((string)entry.Key + "=" + (string)entry.Value); + } + } + entries.Add("PATH=C:\\live"); + entries.Add("Path=C:\\shadowed"); + entries.Add("ORCA_TEST_OUTPUT=" + args[1]); + + IntPtr environment = Marshal.StringToHGlobalUni(String.Join("\0", entries.ToArray()) + "\0\0"); + StartupInfo startupInfo = new StartupInfo(); + startupInfo.cb = Marshal.SizeOf(startupInfo); + ProcessInformation processInformation; + try + { + bool started = CreateProcess( + args[0], + new StringBuilder("\"" + args[0] + "\""), + IntPtr.Zero, + IntPtr.Zero, + false, + 0x00000400, + environment, + null, + ref startupInfo, + out processInformation + ); + if (!started) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + } + finally + { + Marshal.FreeHGlobal(environment); + } + + try + { + WaitForSingleObject(processInformation.hProcess, 0xffffffff); + uint exitCode; + if (!GetExitCodeProcess(processInformation.hProcess, out exitCode)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + return (int)exitCode; + } + finally + { + CloseHandle(processInformation.hThread); + CloseHandle(processInformation.hProcess); + } + } +} diff --git a/config/scripts/happy-dom-mutation-observer-retention.test.ts b/config/scripts/happy-dom-mutation-observer-retention.test.ts new file mode 100644 index 00000000000..475a84c9b31 --- /dev/null +++ b/config/scripts/happy-dom-mutation-observer-retention.test.ts @@ -0,0 +1,72 @@ +/** @vitest-environment happy-dom */ +import { describe, expect, it } from 'vitest' + +import { + installHappyDomMutationObserverRetention, + retainedMutationCallbackCount +} from './happy-dom-mutation-observer-retention' + +function readListenerCallbacks(target: Node): unknown[] { + const listenersSymbol = Object.getOwnPropertySymbols(target).find( + (candidate) => candidate.description === 'mutationListeners' + ) + const listeners = listenersSymbol + ? (target as unknown as Record)[listenersSymbol] + : [] + if (!Array.isArray(listeners)) { + return [] + } + return listeners.map((listener: { callback?: { deref: () => unknown } }) => + listener.callback?.deref() + ) +} + +describe('happy-dom MutationObserver retention', () => { + it('pins the internal callback that happy-dom only holds weakly', () => { + expect(installHappyDomMutationObserverRetention()).toBe(true) + const target = document.createElement('div') + document.body.append(target) + const observer = new MutationObserver(() => {}) + observer.observe(target, { childList: true, subtree: true }) + + const callbacks = readListenerCallbacks(target) + expect(callbacks.length).toBe(1) + expect(callbacks[0]).toBeTypeOf('function') + expect(retainedMutationCallbackCount(observer)).toBe(1) + + observer.disconnect() + expect(retainedMutationCallbackCount(observer)).toBe(0) + target.remove() + }) + + it('keeps delivering records after the weak callback would have been collected', async () => { + installHappyDomMutationObserverRetention() + const target = document.createElement('div') + document.body.append(target) + let deliveries = 0 + const observer = new MutationObserver(() => { + deliveries += 1 + }) + observer.observe(target, { childList: true, subtree: true }) + + target.replaceChildren(document.createElement('div')) + await Promise.resolve() + expect(deliveries).toBe(1) + + const collectGarbage = (globalThis as { gc?: () => void }).gc + if (collectGarbage) { + for (let round = 0; round < 5; round += 1) { + await new Promise((resolve) => setTimeout(resolve, 1)) + collectGarbage() + } + await new Promise((resolve) => setTimeout(resolve, 1)) + } + + target.replaceChildren(document.createElement('span')) + await Promise.resolve() + expect(deliveries).toBe(2) + + observer.disconnect() + target.remove() + }) +}) diff --git a/config/scripts/happy-dom-mutation-observer-retention.ts b/config/scripts/happy-dom-mutation-observer-retention.ts new file mode 100644 index 00000000000..a315b3d520c --- /dev/null +++ b/config/scripts/happy-dom-mutation-observer-retention.ts @@ -0,0 +1,81 @@ +// Why: happy-dom stores each MutationObserver's internal callback in a WeakRef, so any GC pause +// under parallel test load silently and permanently stops a still-connected observer. Browsers +// keep that callback reachable for as long as the observer observes; mirror that lifetime here so +// DOM-driven tests never lose mutation records mid-run. + +type HappyDomMutationListener = { + callback?: { deref: () => unknown } +} + +type PatchableMutationObserver = { + observe: (target: Node, options?: MutationObserverInit) => void + disconnect: () => void +} + +const MUTATION_LISTENERS_SYMBOL_DESCRIPTION = 'mutationListeners' +const RETENTION_INSTALLED = Symbol.for('orca.happyDomMutationObserverRetention') + +const retainedCallbacks = new WeakMap>() + +function readMutationListeners(target: Node): HappyDomMutationListener[] { + const listenersSymbol = Object.getOwnPropertySymbols(target).find( + (candidate) => candidate.description === MUTATION_LISTENERS_SYMBOL_DESCRIPTION + ) + if (!listenersSymbol) { + return [] + } + const listeners = (target as unknown as Record)[listenersSymbol] + return Array.isArray(listeners) ? (listeners as HappyDomMutationListener[]) : [] +} + +/** Number of internal callbacks pinned for `observer`; drops to 0 once it disconnects. */ +export function retainedMutationCallbackCount(observer: MutationObserver): number { + return retainedCallbacks.get(observer)?.size ?? 0 +} + +export function installHappyDomMutationObserverRetention(): boolean { + const observerClass = (globalThis as { MutationObserver?: typeof MutationObserver }) + .MutationObserver + if (!observerClass) { + return false + } + const prototype = observerClass.prototype as unknown as PatchableMutationObserver & + Record + if (prototype[RETENTION_INSTALLED] === true) { + return true + } + const observe = prototype.observe + const disconnect = prototype.disconnect + + prototype.observe = function patchedObserve( + this: object, + target: Node, + options?: MutationObserverInit + ): void { + const existing = new Set(readMutationListeners(target)) + observe.call(this as unknown as PatchableMutationObserver, target, options) + const pinned = retainedCallbacks.get(this) ?? new Set() + for (const listener of readMutationListeners(target)) { + if (existing.has(listener)) { + continue + } + const callback = listener.callback?.deref() + if (callback) { + pinned.add(callback) + } + } + if (pinned.size > 0) { + retainedCallbacks.set(this, pinned) + } + } + + prototype.disconnect = function patchedDisconnect(this: object): void { + disconnect.call(this as unknown as PatchableMutationObserver) + retainedCallbacks.delete(this) + } + + prototype[RETENTION_INSTALLED] = true + return true +} + +installHappyDomMutationObserverRetention() diff --git a/config/scripts/hourly-build-version.mjs b/config/scripts/hourly-build-version.mjs index f4545af086b..12257c2b4ff 100644 --- a/config/scripts/hourly-build-version.mjs +++ b/config/scripts/hourly-build-version.mjs @@ -2,6 +2,10 @@ import { execFileSync } from 'node:child_process' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { formatReleaseTitleTimestamp } from './release-title-timestamp.mjs' +import { + readPublishedVersionsFromEnv, + resolveDevChannelBaseVersion +} from './dev-channel-base-version.mjs' /** `1.4.160-hourly.202607281400` — UTC to the minute, so tags sort chronologically * by semver and every build is uniquely versioned. */ @@ -45,18 +49,19 @@ export function formatHourlyReleaseName(version, buildNumber, commit, date) { ].join(' • ') } -export function getHourlyBuildIdentity(now = new Date(), buildNumber = 1) { +export function getHourlyBuildIdentity(now = new Date(), buildNumber = 1, publishedVersions = []) { const packageJson = JSON.parse(readFileSync(resolve('package.json'), 'utf8')) const commit = execFileSync('git', ['rev-parse', '--short=12', 'HEAD'], { encoding: 'utf8' }).trim() - const version = createHourlyBuildVersion(packageJson.version, now) + const base = resolveDevChannelBaseVersion(packageJson.version, publishedVersions) + const version = createHourlyBuildVersion(base, now) return { commit, version, name: formatHourlyReleaseName(version, buildNumber, commit, now) } } if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) { const buildNumber = Number(process.env.ORCA_HOURLY_BUILD_NUMBER ?? '1') - const identity = getHourlyBuildIdentity(new Date(), buildNumber) + const identity = getHourlyBuildIdentity(new Date(), buildNumber, readPublishedVersionsFromEnv()) // Consumed by the workflow via $GITHUB_OUTPUT. process.stdout.write( `version=${identity.version}\ncommit=${identity.commit}\nname=${identity.name}\n` diff --git a/config/scripts/locale-cross-locale-key-overrides.mjs b/config/scripts/locale-cross-locale-key-overrides.mjs index 124fb8f32e5..85b937b3244 100644 --- a/config/scripts/locale-cross-locale-key-overrides.mjs +++ b/config/scripts/locale-cross-locale-key-overrides.mjs @@ -134,5 +134,30 @@ export const CROSS_LOCALE_KEY_OVERRIDES = { 'auto.hooks.useSettingsNavigationMetadata.40d80bad8a': { zh: '测试版', ja: 'ベータ' + }, + // Issue/PR state picker; it sits beside 已关闭, so 进行中 is a different state. + 'auto.components.PullRequestPage.7b8f6bf6d8': { + zh: '开放' + }, + // This "Open" is the button that opens the config file, not an issue state. + 'auto.components.settings.McpConfigFileRow.e720c139cd': { + zh: '打开' + }, + // Terminal cursor-color group: the on-screen cursor, not the Cursor editor. + 'auto.components.settings.TerminalWindowSection.c9e1fdf42f': { + ko: '커서', + zh: '光标' + }, + 'auto.components.onboarding.ThemeStep.ab2a583a97': { + ko: '커서', + zh: '光标' + }, + // Tailwind swatch labels: bare 天空 (the sky), 锌 and 空 (the metal, the sky) are not colors. + 'auto.components.sidebar.workspace.status.6437a8c253': { + zh: '天蓝', + ja: '空色' + }, + 'auto.components.sidebar.workspace.status.caabd5ca85': { + zh: '锌灰' } } diff --git a/config/scripts/locale-generic-ui-terms.mjs b/config/scripts/locale-generic-ui-terms.mjs new file mode 100644 index 00000000000..2b41a324ce6 --- /dev/null +++ b/config/scripts/locale-generic-ui-terms.mjs @@ -0,0 +1,102 @@ +// Ordinary UI vocabulary that reads like a brand but is not one. Every locale should translate +// these, so the policy must neither pin the whole value to English nor revert the translation +// inside a sentence. The product-name homonyms (Continue.dev, the agent entries) stay Latin +// through ENGLISH_ONLY_KEY_PREFIXES, which matches on the catalog key rather than the word. + +// Renderings a locale is expected to use. They are translations, never machine-translation +// errors, so a brand revert must leave them alone. Nonsense forms that share the same English +// term (zh 回购 "repurchase agreement", ja 端子 "electrical connector", es "Comprometerse") +// stay in BRAND_MISTRANSLATIONS and keep getting reverted. +const GENERIC_TERM_FAMILIES = [ + { + terms: ['Agent', 'Agents', 'agent', 'agents'], + renderings: { + ko: ['에이전트'], + ja: ['エージェント'], + zh: ['代理', '智能体'], + es: ['Agente', 'agente', 'Agentes', 'agentes'] + } + }, + { + terms: ['Commit', 'Commits', 'commit', 'commits'], + renderings: { + ko: ['커밋'], + ja: ['コミット'], + zh: ['提交'], + es: [ + 'Confirmación', + 'confirmación', + 'Confirmaciones', + 'confirmaciones', + 'Confirmar', + 'confirmar' + ] + } + }, + { + terms: ['Continue'], + renderings: { + ko: ['계속하다', '계속'], + ja: ['続ける', '続行'], + zh: ['继续'], + es: ['Continuar', 'continuar'] + } + }, + { + terms: ['Repo', 'Repos', 'repo', 'repos'], + renderings: { + ko: ['저장소', '레포'], + ja: ['リポジトリ', 'リポ'], + zh: ['存储库', '仓库'], + es: ['Repositorio', 'repositorio', 'Repositorios', 'repositorios'] + } + }, + { + terms: ['Terminal', 'Terminals', 'terminal', 'terminals'], + renderings: { + ko: ['터미널'], + ja: ['ターミナル'], + zh: ['终端'], + es: ['Terminales', 'terminales'] + } + } +] + +export const LOCALIZABLE_GENERIC_TERMS = new Set( + GENERIC_TERM_FAMILIES.flatMap((family) => family.terms) +) + +const RENDERINGS_BY_TERM = new Map( + GENERIC_TERM_FAMILIES.flatMap((family) => family.terms.map((term) => [term, family.renderings])) +) + +export function isLocalizableGenericTerm(term) { + return LOCALIZABLE_GENERIC_TERMS.has(term) +} + +export function isCanonicalGenericRendering(term, locale, form) { + return RENDERINGS_BY_TERM.get(term)?.[locale]?.includes(form) ?? false +} + +export function canonicalGenericRenderings(locale) { + return GENERIC_TERM_FAMILIES.flatMap((family) => + (family.renderings[locale] ?? []).map((form) => ({ form, terms: family.terms })) + ) +} + +function spansOf(value, needle) { + const spans = [] + for (let at = value.indexOf(needle); at !== -1; at = value.indexOf(needle, at + 1)) { + spans.push([at, at + needle.length]) + } + return spans +} + +// Why: zh 终端子进程 ("terminal sub-process") contains 端子, so a blind revert of the +// electrical-connector mistranslation would cut a valid word in half. +export function overlapsCanonicalRendering(term, locale, value, start, end) { + const renderings = RENDERINGS_BY_TERM.get(term)?.[locale] ?? [] + return renderings.some((form) => + spansOf(value, form).some(([from, to]) => start < to && from < end) + ) +} diff --git a/config/scripts/locale-generic-ui-terms.test.mjs b/config/scripts/locale-generic-ui-terms.test.mjs new file mode 100644 index 00000000000..42a7d63d0b3 --- /dev/null +++ b/config/scripts/locale-generic-ui-terms.test.mjs @@ -0,0 +1,174 @@ +import { describe, expect, it } from 'vitest' + +import { LOCALIZABLE_GENERIC_TERMS } from './locale-generic-ui-terms.mjs' +import { NEVER_TRANSLATE_VALUES, repairTranslatedValue } from './locale-translation-policy.mjs' + +// Why: #12113 — repair-locale-catalog rewrote ~2000 translated values back to English because +// generic UI words (agent, terminal, commit, repo, Continue) were treated as brands. These pin +// the boundary: generic words stay translated, real brand names stay Latin. +describe('locale generic UI terms', () => { + it('keeps a translated generic term when the whole value is that term', () => { + expect( + repairTranslatedValue({ + key: 'auto.components.settings.AppearancePane.terminalTitle', + enValue: 'Terminal', + localeValue: '터미널', + locale: 'ko' + }) + ).toBe('터미널') + expect( + repairTranslatedValue({ + key: 'auto.components.settings.QuickCommandsPane.4ccc63da87', + enValue: 'Agent', + localeValue: '에이전트', + locale: 'ko' + }) + ).toBe('에이전트') + expect( + repairTranslatedValue({ + key: 'auto.components.mobile.MobileHero.a8fb43cf1c', + enValue: 'Continue', + localeValue: '继续', + locale: 'zh' + }) + ).toBe('继续') + }) + + it('keeps a translated generic term inside a sentence', () => { + expect( + repairTranslatedValue({ + key: 'auto.components.settings.EditorFontSection.matchTerminal', + enValue: 'Match terminal font', + localeValue: '터미널 글꼴과 동일', + locale: 'ko' + }) + ).toBe('터미널 글꼴과 동일') + expect( + repairTranslatedValue({ + key: 'auto.components.settings.ExperimentalPane.agentDashboard.toggleLabel', + enValue: 'Toggle Agent Dashboard', + localeValue: '에이전트 대시보드 전환', + locale: 'ko' + }) + ).toBe('에이전트 대시보드 전환') + expect( + repairTranslatedValue({ + key: 'components.agentSessionContinuation.dialogTitle', + enValue: 'Continue in New Session', + localeValue: '新しいセッションで続ける', + locale: 'ja' + }) + // 新しい → 新規 is an unrelated phrase fix; 続ける is what must survive. + ).toBe('新規セッションで続ける') + }) + + it('still reverts real brand names that machine translation localized', () => { + expect( + repairTranslatedValue({ + key: 'auto.stats.StatsPane.7d26110cea', + enValue: 'Codex', + localeValue: '사본', + locale: 'ko' + }) + ).toBe('Codex') + expect( + repairTranslatedValue({ + key: 'auto.components.settings.appearance.search.9ae151b26b', + enValue: 'linear', + localeValue: '线性', + locale: 'zh' + }) + ).toBe('Linear') + expect( + repairTranslatedValue({ + key: 'auto.components.settings.NetworkPane.tailscale', + enValue: 'Connect over Tailscale', + localeValue: '通过尾鳞连接', + locale: 'zh' + }) + ).toBe('通过 Tailscale 连接') + }) + + it('still reverts nonsense renderings of a generic term', () => { + // 端子 is an electrical connector, 回购 a repurchase agreement, Comprometerse "to pledge". + expect( + repairTranslatedValue({ + key: 'auto.components.agent.AgentCombobox.986f946354', + enValue: 'Blank Terminal', + localeValue: '空白端子', + locale: 'zh' + }) + ).toBe('空白 Terminal') + expect( + repairTranslatedValue({ + key: 'auto.components.right.sidebar.source.control.primary.action.ed93b4f14f', + enValue: 'Commit', + localeValue: 'Comprometerse', + locale: 'es' + }) + ).toBe('Commit') + expect( + repairTranslatedValue({ + key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', + enValue: 'Markdown', + localeValue: '가격 인하', + locale: 'ko' + }) + ).toBe('Markdown') + }) + + it('does not cut a valid word that contains a nonsense rendering', () => { + // 终端子进程 is "terminal sub-process" — 端子 sits inside 终端 + 子. + expect( + repairTranslatedValue({ + key: 'auto.components.settings.AdvancedNetworkSettingsSection.823e0f15b1', + enValue: 'Proxy URL for Orca network requests and local terminal subprocesses.', + localeValue: '用于 Orca 网络请求和本地终端子进程的代理 URL。', + locale: 'zh' + }) + ).toBe('用于 Orca 网络请求和本地终端子进程的代理 URL。') + }) + + it('still fills in a translation when the catalog holds English', () => { + expect( + repairTranslatedValue({ + key: 'auto.components.feature.wall.BrowserAnimatedVisual.04096318ab', + enValue: 'Terminal 1', + localeValue: 'Terminal 1', + locale: 'ko' + }) + ).toBe('터미널 1') + expect( + repairTranslatedValue({ + key: 'auto.store.slices.worktrees.889487d8bb', + enValue: 'Dismiss', + localeValue: '해고하다', + locale: 'ko' + }) + ).toBe('닫기') + }) + + it('keeps agent catalog product names in English by key, not by word', () => { + expect( + repairTranslatedValue({ + key: 'auto.lib.agent.catalog.9e2a9bb87b', + enValue: 'Continue', + localeValue: '继续', + locale: 'zh' + }) + ).toBe('Continue') + expect( + repairTranslatedValue({ + key: 'auto.lib.agent.catalog.760bc6883d', + enValue: 'Codex', + localeValue: '사본', + locale: 'ko' + }) + ).toBe('Codex') + }) + + it('does not list a generic term as never-translatable', () => { + const pinned = [...LOCALIZABLE_GENERIC_TERMS].filter((term) => NEVER_TRANSLATE_VALUES.has(term)) + expect(pinned).toEqual([]) + }) +}) diff --git a/config/scripts/locale-ja-value-overrides.mjs b/config/scripts/locale-ja-value-overrides.mjs index 7f9eeb60af7..30954473186 100644 --- a/config/scripts/locale-ja-value-overrides.mjs +++ b/config/scripts/locale-ja-value-overrides.mjs @@ -94,7 +94,7 @@ export const JA_VALUE_OVERRIDES = { 'Launch plan': '起動プラン', 'Launch agent': 'エージェントを起動', 'Launch {{value0}} in a new terminal': '新規ターミナルで {{value0}} を起動', - Play: 'Play', + Play: '再生', Action: '操作', Actions: '操作', action: '操作', @@ -135,7 +135,7 @@ export const JA_VALUE_OVERRIDES = { 'Pick a base branch below': '以下のベースブランチを選択', 'Choose floating workspace directory': 'フローティング ワークスペース ディレクトリを選択', 'Local project, Git repo, or folder with many repos': - 'ローカルプロジェクト、Git repo、または多数の repos を含むフォルダー', + 'ローカルプロジェクト、Git リポジトリ、または多数のリポジトリを含むフォルダー', 'Enter passphrase': 'パスフレーズを入力', 'Enter password': 'パスワードを入力', 'Enter the passphrase for': 'のパスフレーズを入力', diff --git a/config/scripts/locale-key-overrides.mjs b/config/scripts/locale-key-overrides.mjs index d0577e80bab..d1b4b853bd7 100644 --- a/config/scripts/locale-key-overrides.mjs +++ b/config/scripts/locale-key-overrides.mjs @@ -162,8 +162,8 @@ const BASE_LOCALE_KEY_OVERRIDES = { ja: 'クローズ' }, 'auto.components.GitHubItemDialog.dc1ca081a8': { - ko: '진행 중', - zh: '进行中', + ko: '열림', + zh: '开放', ja: 'オープン' }, 'auto.components.tab.bar.TabBarCreateEntry.b27864279e': { @@ -176,10 +176,11 @@ const BASE_LOCALE_KEY_OVERRIDES = { zh: '打开 Linear 任务', ja: 'Linear タスクを開く' }, + // Onboarding pill beside Orca Mobile: "New" marks a new feature, not a create action. 'auto.components.sidebar.SidebarNav.c86d83b5c3': { - ko: '새로 만들기', - zh: '新建', - ja: '新規' + ko: '신규', + zh: '新功能', + ja: '新機能' }, 'auto.components.sidebar.SidebarSettingsHelpMenu.eb9884e55b': { ko: 'Discord', diff --git a/config/scripts/locale-ko-key-overrides.json b/config/scripts/locale-ko-key-overrides.json index 9b40ad61f50..e8d13941ffa 100644 --- a/config/scripts/locale-ko-key-overrides.json +++ b/config/scripts/locale-ko-key-overrides.json @@ -752,6 +752,21 @@ "auto.components.contextual.tours.ContextualTourProgressDots.dcd6e6b03e": { "ko": "{{value1}}단계 중 {{value0}}단계" }, + "auto.components.contextual.tours.ContextualTourOverlaySurface.complete": { + "ko": "완료" + }, + "auto.components.contextual.tours.contextual.tour.overlay.measurement.automations.intro.body": { + "ko": "자동화는 일정에 따라 agent 작업을 실행합니다. 이 버튼을 눌러 자동화를 추가하세요." + }, + "auto.components.contextual.tours.contextual.tour.overlay.measurement.automations.intro.title": { + "ko": "자동화란 무엇인가요?" + }, + "auto.components.contextual.tours.contextual.tour.overlay.measurement.automations.results.body": { + "ko": "실행 내역에서 자동화가 언제 실행되었는지, 어떤 일이 발생했는지, 출력을 어디서 확인할 수 있는지 볼 수 있습니다." + }, + "auto.components.contextual.tours.contextual.tour.overlay.measurement.automations.results.title": { + "ko": "결과 확인" + }, "auto.components.crash.report.CrashReportDialog.88fea8e84e": { "ko": "보내지 않음" }, @@ -1868,6 +1883,9 @@ "auto.components.right.sidebar.SourceControl.3a231c845b": { "ko": "알 수 없음" }, + "auto.components.right.sidebar.SourceControl.6d7f2a47e5": { + "ko": "폴더의 변경 사항 취소" + }, "auto.components.right.sidebar.SourceControl.812cb992ee": { "ko": "{{value0}}에서 열기" }, @@ -1880,6 +1898,9 @@ "auto.components.right.sidebar.SourceControl.9bb062a886": { "ko": "commit 되지 않음" }, + "auto.components.right.sidebar.SourceControl.a5e5a11090": { + "ko": "모든 변경 사항 취소 실패 — 취소 전에 파일의 스테이징을 해제하지 못했습니다." + }, "auto.components.right.sidebar.SourceControl.aaf1451654": { "ko": "초안 {{value0}} 만들기" }, @@ -1994,6 +2015,9 @@ "auto.components.right.sidebar.source.control.discard.confirmation.2ae5a785b3": { "ko": "스테이징되지 않은 변경 사항을 모두 삭제하시겠습니까?" }, + "auto.components.right.sidebar.source.control.discard.confirmation.40e9357b2a": { + "ko": "이렇게 하면 HEAD에서 파일을 복원하고 파일 삭제를 취소합니다. 이 작업은 취소할 수 없습니다." + }, "auto.components.right.sidebar.source.control.discard.confirmation.5ddd8cac7f": { "ko": "스테이징된 변경 사항을 모두 삭제하시겠습니까?" }, @@ -2015,6 +2039,9 @@ "auto.components.right.sidebar.source.control.primary.action.1d47e850cf": { "ko": "연결된 리뷰 브랜치에 업데이트 푸시" }, + "auto.components.right.sidebar.source.control.primary.action.5a477d80cb": { + "ko": "모든 변경 사항 스테이징" + }, "auto.components.right.sidebar.source.control.primary.action.a5d1f7b036": { "ko": "{{value0}}을(를) 만들기 전에 commits을 게시하세요." }, @@ -2162,6 +2189,9 @@ "auto.components.settings.AutoRenameBranchFromWorkSetting.a4fa380b67": { "ko": "{assistantMessage}" }, + "auto.components.settings.AutoRenameBranchFromWorkSetting.d9b65054ef": { + "ko": ") 작업을 요약하는 짧은 이름으로 변경됩니다. Orca가 직접 이름 붙인 브랜치만 이름을 바꾸며, 푸시된 후에는 이름을 바꾸지 않습니다." + }, "auto.components.settings.AutoRenameBranchPromptEditor.ebb942a2ec": { "ko": "fix-login-flow" }, @@ -2228,6 +2258,9 @@ "auto.components.settings.DefaultWindowsProjectRuntimeSetting.wslUnavailable": { "ko": "WSL을 사용할 수 없습니다. WSL을 상속하는 프로젝트는 복구가 필요합니다." }, + "auto.components.settings.DevToolsPane.orcaCloudDescription": { + "ko": "자사 클라우드 로그인의 개발자 전용 미리보기. 프로덕션에서는 숨겨집니다. 개발 환경에서는 ORCA_CLOUD_API_URL과 ORCA_CLOUD_CLIENT_ID가 설정되면 사이드바 계정 전환기에도 표시됩니다." + }, "auto.components.settings.DeveloperPermissionsPane.16381e040a": { "ko": "마이크" }, @@ -2255,6 +2288,12 @@ "auto.components.settings.ExperimentalPane.newWorktreeCardStyle.description": { "ko": "업데이트된 워크트리 카드 레이아웃, 메타데이터 배치, 카드 표시 메뉴 옵션 및 상태 표시를 미리 봅니다." }, + "auto.components.settings.EphemeralVmsPane.recipes": { + "ko": "레시피" + }, + "auto.components.settings.EphemeralVmsPane.whatTitle": { + "ko": "이 스킬로 함께 하는 작업" + }, "auto.components.settings.GeneralEditorSettingsSection.45c6e85c4d": { "ko": "편집기" }, @@ -2727,7 +2766,7 @@ "ko": "이 SSH 대상의 원격 릴레이를 강제로 중지합니다. 이 대상의 활성 원격 terminals과 포트 포워딩이 종료됩니다." }, "auto.components.settings.SshTargetForm.137e88ce8d": { - "ko": "연결 해제 후 릴레이가 terminals을 활성 상태로 유지하는 기간입니다. 기본값: 10800(3시간). 최대:" + "ko": "Orca가 이 호스트에서 연결 해제된 뒤에도 원격 터미널은 계속 실행됩니다." }, "auto.components.settings.SshTargetForm.2ee9bcd2e8": { "ko": "server, deploy@server:2222, ssh://server" @@ -3710,6 +3749,9 @@ "auto.components.settings.ssh.search.f9493b80c0": { "ko": "서버" }, + "auto.components.settings.source.control.action.recipe.options.commitMessage": { + "ko": "스테이징된 변경 사항에서 commit 메시지를 생성합니다." + }, "auto.components.settings.task.tracker.integration.cards.1a12e33fe5": { "ko": "Linear 액세스 추가" }, @@ -4683,7 +4725,7 @@ "ko": "중지 중" }, "auto.components.status.bar.WorkspaceSpaceCompactPanel.8ff597593d": { - "ko": "Space" + "ko": "저장 공간" }, "auto.components.status.bar.WorkspaceSpaceCompactPanel.9be86c46a0": { "ko": "확보 가능" @@ -4953,7 +4995,7 @@ "ko": "선택한 리포지토리와 일치하는 비활성 워크스페이스가 없습니다." }, "auto.components.workspace.space.WorkspaceSpacePage.45f6302dbc": { - "ko": "Space" + "ko": "저장 공간" }, "auto.components.workspace.space.WorkspaceSpacePage.8d0048e1cb": { "ko": "워크스페이스 디스크 사용량과 회수 가능한 워크트리 저장 공간." diff --git a/config/scripts/locale-ko-value-overrides.mjs b/config/scripts/locale-ko-value-overrides.mjs index 1d128a67897..19db7c753ec 100644 --- a/config/scripts/locale-ko-value-overrides.mjs +++ b/config/scripts/locale-ko-value-overrides.mjs @@ -209,7 +209,7 @@ export const KO_VALUE_OVERRIDES = { 'Install the Orca skill so agents know to use the Orca CLI.': '에이전트가 Orca CLI를 사용하도록 Orca 스킬을 설치하세요.', 'Local project, Git repo, or folder with many repos': - '로컬 프로젝트, Git repo 또는 repos가 많은 폴더', + '로컬 프로젝트, Git 저장소 또는 저장소가 많은 폴더', 'Linear, GitLab, Bitbucket, Azure DevOps, Gitea, and Jira live in Settings > Integrations.': 'Linear, GitLab, Bitbucket, Azure DevOps, Gitea 및 Jira는 설정 > 연동에 있습니다.', 'changed since you last approved. Re-review before it runs': diff --git a/config/scripts/locale-phrase-fixes.mjs b/config/scripts/locale-phrase-fixes.mjs index fec68ef8b5d..b3c8026cea5 100644 --- a/config/scripts/locale-phrase-fixes.mjs +++ b/config/scripts/locale-phrase-fixes.mjs @@ -371,9 +371,10 @@ export const LOCALE_PHRASE_FIXES = { { pattern: /指挥进展/g, replacement: 'Conductor 进度', whenEnIncludes: 'Conductor Progress' }, { pattern: /指挥评论/g, replacement: 'Conductor 评审', whenEnIncludes: 'Conductor Review' }, { pattern: /指挥完成/g, replacement: 'Conductor 完成', whenEnIncludes: 'Conductor Done' }, - { pattern: /琥珀色/g, replacement: 'Amber', whenEnIncludes: 'Amber' }, - { pattern: /蓝色的/g, replacement: 'Blue', whenEnIncludes: 'Blue' }, - { pattern: /中性的/g, replacement: 'Neutral', whenEnIncludes: 'Neutral' }, + // Swatch labels want the bare color noun, not the adjectival 的 form — and not English. + { pattern: /琥珀色/g, replacement: '琥珀', whenEnIncludes: 'Amber' }, + { pattern: /蓝色的/g, replacement: '蓝色', whenEnIncludes: 'Blue' }, + { pattern: /中性的/g, replacement: '中性', whenEnIncludes: 'Neutral' }, { pattern: /破坏性的/g, replacement: 'destructive', whenEnIncludes: 'destructive' }, { pattern: /注解/g, replacement: '批注', whenEnIncludes: 'Annotation' }, ...ZH_PHRASE_FIXES_ROUND5 diff --git a/config/scripts/locale-prose-term-exemptions.mjs b/config/scripts/locale-prose-term-exemptions.mjs deleted file mode 100644 index fbe2d483fa1..00000000000 --- a/config/scripts/locale-prose-term-exemptions.mjs +++ /dev/null @@ -1,19 +0,0 @@ -const LOCALIZED_PROSE_TERM_KEYS = new Set([ - 'auto.hooks.useMacosTccPromptNotice.description', - 'auto.components.settings.DeveloperPermissionsPane.7ca17b62c8' -]) - -const LOCALIZABLE_PROSE_TERMS = new Set([ - 'Agent', - 'Agents', - 'agent', - 'agents', - 'Terminal', - 'Terminals', - 'terminal', - 'terminals' -]) - -export function isLocalizedProseTermContext(term, key) { - return LOCALIZED_PROSE_TERM_KEYS.has(key) && LOCALIZABLE_PROSE_TERMS.has(term) -} diff --git a/config/scripts/locale-repair-catalog-missing-leaves.test.mjs b/config/scripts/locale-repair-catalog-missing-leaves.test.mjs new file mode 100644 index 00000000000..65e142e5149 --- /dev/null +++ b/config/scripts/locale-repair-catalog-missing-leaves.test.mjs @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' + +import { repairCatalog } from './locale-translation-policy.mjs' + +// Regression: en.json routinely carries keys a locale catalog has not been bootstrapped with yet +// (~190 per locale at the time of writing), which crashed the whole repair run before it did any work. +describe('repairCatalog with un-bootstrapped keys', () => { + const enCatalog = { + auto: { + lib: { agent: { catalog: { '760bc6883d': 'Codex' } } }, + components: { untranslated: 'Continue', nested: { alsoMissing: 'Refresh' } } + } + } + + const translatedOnly = () => ({ auto: { lib: { agent: { catalog: { '760bc6883d': '사본' } } } } }) + + it('skips leaves the locale catalog is missing instead of throwing', () => { + for (const locale of ['ko', 'ja', 'zh', 'es']) { + const localeCatalog = translatedOnly() + expect(() => repairCatalog(enCatalog, localeCatalog, locale), locale).not.toThrow() + expect(localeCatalog.auto.components, locale).toBeUndefined() + } + }) + + it('still repairs the leaves that are present', () => { + const localeCatalog = translatedOnly() + expect(repairCatalog(enCatalog, localeCatalog, 'ko')).toBe(1) + expect(localeCatalog.auto.lib.agent.catalog['760bc6883d']).toBe('Codex') + }) +}) diff --git a/config/scripts/locale-translation-policy-ko-round5.test.mjs b/config/scripts/locale-translation-policy-ko-round5.test.mjs index b3f88e4e141..e03157e0bc6 100644 --- a/config/scripts/locale-translation-policy-ko-round5.test.mjs +++ b/config/scripts/locale-translation-policy-ko-round5.test.mjs @@ -45,7 +45,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '에이전트가 Orca CLI 사용 방법을 알 수 있도록 Orca 기술을 설치합니다.', locale: 'ko' }) - ).toBe('agents가 Orca CLI를 사용하도록 Orca 스킬을 설치하세요.') + ).toBe('에이전트가 Orca CLI를 사용하도록 Orca 스킬을 설치하세요.') expect( repairTranslatedValue({ key: 'auto.components.editor.MarkdownPreview.322afab6ff', @@ -92,7 +92,8 @@ describe('locale-translation-policy ko round 5', () => { ).toBe('파이프라인') }) - it('keeps protected workflow terms in English', () => { + // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Korean. + it('keeps brand names English and generic workflow terms translated', () => { expect( repairTranslatedValue({ key: 'auto.components.feature.wall.BrowserAnimatedVisual.04096318ab', @@ -100,7 +101,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '터미널 1', locale: 'ko' }) - ).toBe('Terminal 1') + ).toBe('터미널 1') expect( repairTranslatedValue({ key: 'auto.components.skills.SkillsPage.38e0951c3a', @@ -108,7 +109,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '에이전트 스킬', locale: 'ko' }) - ).toBe('Agent 스킬') + ).toBe('에이전트 스킬') expect( repairTranslatedValue({ key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', @@ -124,7 +125,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '푸시되지 않은 커밋', locale: 'ko' }) - ).toBe('푸시되지 않은 commits') + ).toBe('푸시되지 않은 커밋') expect( repairTranslatedValue({ key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.0b1766738a', @@ -132,7 +133,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '레포', locale: 'ko' }) - ).toBe('Repo') + ).toBe('레포') expect( repairTranslatedValue({ key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', @@ -140,7 +141,7 @@ describe('locale-translation-policy ko round 5', () => { localeValue: '로컬 프로젝트, Git 저장소 또는 저장소가 많은 폴더', locale: 'ko' }) - ).toBe('로컬 프로젝트, Git repo 또는 repos가 많은 폴더') + ).toBe('로컬 프로젝트, Git 저장소 또는 저장소가 많은 폴더') }) it('re-glues Korean particles after Latin terms without gluing content words', () => { diff --git a/config/scripts/locale-translation-policy.es-round5.test.mjs b/config/scripts/locale-translation-policy.es-round5.test.mjs index b52afceb02d..3bf5a77fb3a 100644 --- a/config/scripts/locale-translation-policy.es-round5.test.mjs +++ b/config/scripts/locale-translation-policy.es-round5.test.mjs @@ -3,7 +3,8 @@ import { describe, expect, it } from 'vitest' import { repairTranslatedValue } from './locale-translation-policy.mjs' describe('locale-translation-policy es round 5', () => { - it('keeps protected workflow terms in English', () => { + // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Spanish. + it('keeps brand names English and generic workflow terms translated', () => { expect( repairTranslatedValue({ key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', @@ -43,7 +44,7 @@ describe('locale-translation-policy es round 5', () => { localeValue: 'mensaje de confirmación', locale: 'es' }) - ).toBe('mensaje de Commit') + ).toBe('mensaje de confirmación') expect( repairTranslatedValue({ key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.0b1766738a', @@ -51,7 +52,7 @@ describe('locale-translation-policy es round 5', () => { localeValue: 'repositorio', locale: 'es' }) - ).toBe('Repo') + ).toBe('repositorio') expect( repairTranslatedValue({ key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', @@ -59,6 +60,6 @@ describe('locale-translation-policy es round 5', () => { localeValue: 'Proyecto local, repositorio de Git o carpeta con muchos repositorios', locale: 'es' }) - ).toBe('Proyecto local, repo de Git o carpeta con muchos repos') + ).toBe('Proyecto local, repositorio de Git o carpeta con muchos repositorios') }) }) diff --git a/config/scripts/locale-translation-policy.ja-round5.test.mjs b/config/scripts/locale-translation-policy.ja-round5.test.mjs index 3100efc3abe..219bc33113b 100644 --- a/config/scripts/locale-translation-policy.ja-round5.test.mjs +++ b/config/scripts/locale-translation-policy.ja-round5.test.mjs @@ -27,7 +27,7 @@ describe('locale-translation-policy ja round 5', () => { localeValue: '遊ぶ', locale: 'ja' }) - ).toBe('Play') + ).toBe('再生') expect( repairTranslatedValue({ key: 'auto.components.TaskPage.8396825a14', @@ -102,7 +102,8 @@ describe('locale-translation-policy ja round 5', () => { ).toBe('まずプロジェクトを追加') }) - it('keeps protected workflow terms in English', () => { + // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Japanese. + it('keeps brand names English and generic workflow terms translated', () => { expect( repairTranslatedValue({ key: 'auto.components.status.bar.WorkspaceSpaceManagerPanel.e9528a89b3', @@ -118,7 +119,7 @@ describe('locale-translation-policy ja round 5', () => { localeValue: 'エージェントのスキル', locale: 'ja' }) - ).toBe('Agent のスキル') + ).toBe('エージェントのスキル') expect( repairTranslatedValue({ key: 'auto.components.tab.bar.TabBar.3d5d6c960d', @@ -134,7 +135,7 @@ describe('locale-translation-policy ja round 5', () => { localeValue: 'コミット', locale: 'ja' }) - ).toBe('commits') + ).toBe('コミット') expect( repairTranslatedValue({ key: 'auto.components.mobile.slides.WorktreeListSlide.22971156df', @@ -142,7 +143,7 @@ describe('locale-translation-policy ja round 5', () => { localeValue: 'リポ', locale: 'ja' }) - ).toBe('Repo') + ).toBe('リポ') expect( repairTranslatedValue({ key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', @@ -151,6 +152,6 @@ describe('locale-translation-policy ja round 5', () => { 'ローカル プロジェクト、Git リポジトリ、または多数のリポジトリを含むフォルダー', locale: 'ja' }) - ).toBe('ローカルプロジェクト、Git repo、または多数の repos を含むフォルダー') + ).toBe('ローカルプロジェクト、Git リポジトリ、または多数のリポジトリを含むフォルダー') }) }) diff --git a/config/scripts/locale-translation-policy.mjs b/config/scripts/locale-translation-policy.mjs index a3feb5f59df..50a490dc184 100644 --- a/config/scripts/locale-translation-policy.mjs +++ b/config/scripts/locale-translation-policy.mjs @@ -1,5 +1,8 @@ import { CJK_LATIN_SPACED_TERMS } from './locale-cjk-latin-spaced-terms.mjs' -import { isLocalizedProseTermContext } from './locale-prose-term-exemptions.mjs' +import { + isCanonicalGenericRendering, + overlapsCanonicalRendering +} from './locale-generic-ui-terms.mjs' import { isScreenCursorContext } from './locale-screen-cursor-exemptions.mjs' import { LOCALE_KEY_OVERRIDES } from './locale-key-overrides.mjs' import { LOCALE_PHRASE_FIXES } from './locale-phrase-fixes.mjs' @@ -17,9 +20,10 @@ const OPEN_IN_APP_CATALOG_PREFIX = 'auto.lib.open.in.app.catalog.' // Why: product names and agent labels stay Latin — MT reads them as common words (Codex→copy, Gemini→zodiac). export const ENGLISH_ONLY_KEY_PREFIXES = [AGENT_CATALOG_PREFIX, OPEN_IN_APP_CATALOG_PREFIX] +// Only genuine brand, product, and code tokens belong here. Ordinary UI words that happen to +// name a product (agent, terminal, commit, repo, Continue) live in locale-generic-ui-terms.mjs +// and are translated; their product sense is pinned by ENGLISH_ONLY_KEY_PREFIXES instead. export const NEVER_TRANSLATE_VALUES = new Set([ - 'Agent', - 'Agents', 'Aider', 'Amp', 'Android', @@ -33,7 +37,6 @@ export const NEVER_TRANSLATE_VALUES = new Set([ 'Codebuff', 'Codex', 'Command Code', - 'Continue', 'Cursor', 'Droid', 'Devin', @@ -60,30 +63,16 @@ export const NEVER_TRANSLATE_VALUES = new Set([ 'Pi', 'PostHog', 'Qwen Code', - 'Repo', - 'Repos', 'Rovo Dev', - 'Commit', - 'Commits', 'Markdown', - 'Terminal', - 'Terminals', 'VS Code', 'Warp', 'Zed', - 'agent', - 'agents', 'android', 'codex', - 'commit', - 'commits', 'gemini', 'claude', 'markdown', - 'repo', - 'repos', - 'terminal', - 'terminals', 'gh', 'idle', 'anthropic', @@ -368,6 +357,18 @@ function includesPreservedLatinTerm(value, term) { return new RegExp(`(^|[^A-Za-z_])${escapeRegExp(term)}($|[^A-Za-z_])`).test(value) } +function replaceMistranslatedForm(value, wrong, brand, locale) { + let result = '' + let cursor = 0 + for (let at = value.indexOf(wrong); at !== -1; at = value.indexOf(wrong, cursor)) { + const end = at + wrong.length + result += value.slice(cursor, at) + result += overlapsCanonicalRendering(brand, locale, value, at, end) ? wrong : brand + cursor = end + } + return result + value.slice(cursor) +} + function applyBrandMistranslationFixes(enValue, localeValue, locale, key = '') { let result = localeValue const mistranslations = BRAND_MISTRANSLATIONS[locale] ?? {} @@ -383,9 +384,6 @@ function applyBrandMistranslationFixes(enValue, localeValue, locale, key = '') { if (isScreenCursorContext(brand, enValue, key)) { continue } - if (isLocalizedProseTermContext(brand, key)) { - continue - } if (includesPreservedLatinTerm(result, brand)) { continue } @@ -393,11 +391,16 @@ function applyBrandMistranslationFixes(enValue, localeValue, locale, key = '') { if (!result.includes(wrong)) { continue } + // Why: #12113 — a generic term's correct translation is not a mistranslation; reverting it + // rewrote ~2000 translated values back to English on every repair run. + if (isCanonicalGenericRendering(brand, locale, wrong)) { + continue + } // Why: "Copy identifier" legitimately uses 사본/复制 — only swap when English names the brand. if (brand === 'Codex' && /\bCopy\b/i.test(enValue)) { continue } - result = result.replaceAll(wrong, brand) + result = replaceMistranslatedForm(result, wrong, brand, locale) } } @@ -548,6 +551,11 @@ export function repairCatalog(enCatalog, localeCatalog, locale) { for (const leaf of leaves) { const current = leaf.key.split('.').reduce((cursor, part) => cursor?.[part], localeCatalog) + // Why: en.json carries keys the locale catalog has not been bootstrapped with yet; repair only + // rewrites values that already exist, so skip instead of crashing on undefined. + if (typeof current !== 'string') { + continue + } const next = repairTranslatedValue({ key: leaf.key, enValue: leaf.value, diff --git a/config/scripts/locale-translation-policy.test.mjs b/config/scripts/locale-translation-policy.test.mjs index 1722f8f946e..d919de96cff 100644 --- a/config/scripts/locale-translation-policy.test.mjs +++ b/config/scripts/locale-translation-policy.test.mjs @@ -80,7 +80,7 @@ describe('locale-translation-policy', () => { localeValue: '壊れた小切手に対して AI エージェントを開始しました。', locale: 'ja' }) - ).toBe('失敗したチェックに対して AI agent を開始しました。') + ).toBe('失敗したチェックに対して AI エージェントを開始しました。') expect( repairTranslatedValue({ key: 'auto.hooks.useSettingsNavigationMetadata.95a1886d94', @@ -88,7 +88,7 @@ describe('locale-translation-policy', () => { localeValue: '電話機からターミナルとエージェントを制御します。', locale: 'ja' }) - ).toBe('スマートフォンから terminals と agents を操作') + ).toBe('スマートフォンからターミナルとエージェントを操作') expect( repairTranslatedValue({ key: 'auto.components.GitHubItemDialog.934add88b6', @@ -267,7 +267,7 @@ describe('locale-translation-policy', () => { localeValue: '未已检测代理', locale: 'zh' }) - ).toBe('未检测到 agents') + ).toBe('未检测到代理') expect( repairTranslatedValue({ key: 'auto.components.skills.SkillsPage.38e0951c3a', @@ -275,7 +275,7 @@ describe('locale-translation-policy', () => { localeValue: '代理技巧', locale: 'zh' }) - ).toBe('Agent 技能') + ).toBe('代理技能') expect( repairTranslatedValue({ key: 'auto.components.settings.appearance.search.9ae151b26b', @@ -358,7 +358,7 @@ describe('locale-translation-policy', () => { localeValue: 'コミットするものは何もありません。 PR はすでに統合されています。', locale: 'ja' }) - ).toBe('commit するものはありません。PR はすでにマージされています。') + ).toBe('コミットするものはありません。PR はすでにマージされています。') expect( repairTranslatedValue({ key: 'auto.components.settings.integrations.search.581844769a', @@ -546,7 +546,7 @@ describe('locale-translation-policy', () => { localeValue: '玩', locale: 'zh' }) - ).toBe('Play') + ).toBe('播放') expect( repairTranslatedValue({ key: 'auto.components.right.sidebar.SourceControlAgentActionDialogForm.1bc0bdbb5e', diff --git a/config/scripts/locale-translation-policy.zh-round5.test.mjs b/config/scripts/locale-translation-policy.zh-round5.test.mjs index 6e451c6d89b..28901fba8d4 100644 --- a/config/scripts/locale-translation-policy.zh-round5.test.mjs +++ b/config/scripts/locale-translation-policy.zh-round5.test.mjs @@ -86,7 +86,9 @@ describe('locale-translation-policy zh round 5', () => { ).toBe('集成') }) - it('keeps Terminal as a product surface term', () => { + // Why: #12113 — 终端 is the correct rendering and survives; only the 端子 ("electrical + // connector") mistranslation still reverts to Latin. + it('keeps terminal translated but reverts the 端子 mistranslation', () => { expect( repairTranslatedValue({ key: 'auto.components.settings.Settings.3de4bbb841', @@ -94,7 +96,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '终端', locale: 'zh' }) - ).toBe('Terminal') + ).toBe('终端') expect( repairTranslatedValue({ key: 'auto.components.feature.wall.BrowserAnimatedVisual.04096318ab', @@ -102,7 +104,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '终端 1', locale: 'zh' }) - ).toBe('Terminal 1') + ).toBe('终端 1') expect( repairTranslatedValue({ key: 'auto.components.agent.AgentCombobox.986f946354', @@ -118,7 +120,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '分体式端子右', locale: 'zh' }) - ).toBe('向右拆分 Terminal') + ).toBe('向右拆分终端') expect( repairTranslatedValue({ key: 'auto.components.settings.TerminalAppearanceSection.abcb4dd019', @@ -126,7 +128,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '终端Cursor', locale: 'zh' }) - ).toBe('Terminal Cursor') + ).toBe('终端 Cursor') expect( repairTranslatedValue({ key: 'auto.components.terminal.FloatingTerminalPanel.3215fc73e9', @@ -137,7 +139,8 @@ describe('locale-translation-policy zh round 5', () => { ).toBe('新 Terminal') }) - it('keeps workflow terms in English', () => { + // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Chinese. + it('keeps brand names English and generic workflow terms translated', () => { expect( repairTranslatedValue({ key: 'auto.components.sidebar.SidebarNav.9c95e1ce91', @@ -145,7 +148,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '代理', locale: 'zh' }) - ).toBe('Agents') + ).toBe('代理') expect( repairTranslatedValue({ key: 'auto.components.GitHubItemDialog.28986b3747', @@ -153,7 +156,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '已启动 AI 代理处理失败的检查。', locale: 'zh' }) - ).toBe('已启动 AI agent 处理失败的检查。') + ).toBe('已启动 AI 代理处理失败的检查。') expect( repairTranslatedValue({ key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', @@ -177,7 +180,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '次提交', locale: 'zh' }) - ).toBe('commits') + ).toBe('次提交') expect( repairTranslatedValue({ key: 'auto.store.slices.worktrees.d1d78a7baa', @@ -187,7 +190,7 @@ describe('locale-translation-policy zh round 5', () => { 'Git 无法安全删除分支“{{value0}}”{{value1}},因此 Orca 保留它以避免丢失本地提交。', locale: 'zh' }) - ).toBe('Git 无法安全删除分支“{{value0}}”{{value1}},因此 Orca 保留它以避免丢失本地 commits。') + ).toBe('Git 无法安全删除分支“{{value0}}”{{value1}},因此 Orca 保留它以避免丢失本地提交。') }) it('does not confuse proxy copy with Agent terminology', () => { @@ -234,7 +237,7 @@ describe('locale-translation-policy zh round 5', () => { localeValue: '本地项目、Git 存储库或包含多个存储库的文件夹', locale: 'zh' }) - ).toBe('本地项目、Git repo 或包含多个 repos 的文件夹') + ).toBe('本地项目、Git 仓库或包含多个仓库的文件夹') }) it('keeps product, provider, code, and shell tokens untranslated', () => { diff --git a/config/scripts/locale-value-overrides.mjs b/config/scripts/locale-value-overrides.mjs index e237bca76b0..ea49d748250 100644 --- a/config/scripts/locale-value-overrides.mjs +++ b/config/scripts/locale-value-overrides.mjs @@ -8,7 +8,7 @@ export const LOCALE_VALUE_OVERRIDES = { 'OpenCode Go': 'OpenCode Go', 'Open in Cursor': 'Abrir en Cursor', 'Local project, Git repo, or folder with many repos': - 'Proyecto local, repo de Git o carpeta con muchos repos' + 'Proyecto local, repositorio de Git o carpeta con muchos repositorios' }, ko: { Save: '저장', @@ -305,7 +305,8 @@ export const LOCALE_VALUE_OVERRIDES = { teams: '团队', passing: '通过', 'opened this issue': '创建了此议题', - Open: '进行中', + // No blanket "Open" override: it is a verb on buttons (打开) and a state next to 已关闭 (开放), + // so a single value-wide mapping is wrong for half the call sites. Per-key catalog values decide. 'Join Discord': '加入 Discord', 'Pull request merged': '拉取请求已合并', 'Agent Skills': '代理技能', diff --git a/config/scripts/locale-zh-value-overrides.mjs b/config/scripts/locale-zh-value-overrides.mjs index d11c747c1df..087091a3f3e 100644 --- a/config/scripts/locale-zh-value-overrides.mjs +++ b/config/scripts/locale-zh-value-overrides.mjs @@ -67,8 +67,8 @@ export const ZH_VALUE_OVERRIDES = { Inline: '内联', thread: '帖子串', destructive: 'destructive', - sheet: 'sheet', - page: 'page', + sheet: '面板', + page: '页面', Annotation: '批注', 'check #': '检查 #', by: '由', @@ -92,16 +92,18 @@ export const ZH_VALUE_OVERRIDES = { '仓库操作方案。在此仓库自定义之前,将使用全局设置。', 'Adds action recipes for Source Control commit, pull request, branch-name, and fix actions.': '为源代码管理的提交、拉取请求、分支命名和修复操作添加操作方案。', - Play: 'Play', - Flag: 'Flag', - Zinc: 'Zinc', - Rose: 'Rose', - Emerald: 'Emerald', - Amber: 'Amber', - Violet: 'Violet', - Sky: 'Sky', - Blue: 'Blue', - Neutral: 'Neutral', + // Workspace status icon and color swatch labels; siblings below are translated, so English + // pins here would leave the picker half-Chinese on the next catalog regeneration. + Play: '播放', + Flag: '标记', + Zinc: '锌灰', + Rose: '玫瑰', + Emerald: '翡翠', + Amber: '琥珀', + Violet: '紫罗兰', + Sky: '天蓝', + Blue: '蓝色', + Neutral: '中性', Dashed: '虚线', Dot: '圆点', Circle: '圆形', @@ -201,8 +203,7 @@ export const ZH_VALUE_OVERRIDES = { '每个已连接的 Linear 工作区都有一个由活动运行时存储的密钥。全权限密钥可覆盖密钥所有者可访问的所有团队;受限密钥可随时更换。', 'Show Linear in the Tasks source picker and sidebar shortcuts.': '在任务源选择器和侧边栏快捷方式中显示 Linear。', - 'Local project, Git repo, or folder with many repos': - '本地项目、Git repo 或包含多个 repos 的文件夹', + 'Local project, Git repo, or folder with many repos': '本地项目、Git 仓库或包含多个仓库的文件夹', 'Staged Changes': '已暂存的更改', Changes: '更改', 'Untracked Files': '未跟踪文件', @@ -210,8 +211,8 @@ export const ZH_VALUE_OVERRIDES = { 'Split Down': '向下拆分', 'Split Left': '向左拆分', 'Split Right': '向右拆分', - 'Split Terminal Down': '向下拆分 Terminal', - 'Split Terminal Right': '向右拆分 Terminal', + 'Split Terminal Down': '向下拆分终端', + 'Split Terminal Right': '向右拆分终端', 'Optional account switching for Claude while preserving shared chat context.': 'Claude 的可选账户切换,同时保留共享聊天上下文。', 'Countdown timer showing time until prompt cache expires (Claude agents).': diff --git a/config/scripts/orchestration-skill-guidance.test.mjs b/config/scripts/orchestration-skill-guidance.test.mjs index 849fe784b46..e869f652e40 100644 --- a/config/scripts/orchestration-skill-guidance.test.mjs +++ b/config/scripts/orchestration-skill-guidance.test.mjs @@ -227,12 +227,79 @@ describe('orchestration skill guidance', () => { expect(agentGuidance).toContain('After sending `worker_done`, end your turn') expect(agentGuidance).toContain('idle at the agent prompt') - expect(agentGuidance).toContain('Do not poll or keep calling `orca orchestration check`') + expect(agentGuidance).toContain( + 'do not start more work, poll, or attempt to close the terminal yourself' + ) expect(agentGuidance).toContain('fresh preamble + TASK block delivered as new terminal input') expect(skill).not.toContain('post-completion polling messages') expect(skill).not.toContain('every 2 minutes') }) + it('makes settled worker terminal release an explicit coordinator step', () => { + const skill = readSkill() + const workerLoop = getSection(skill, 'Preferred Supervised Worker Loop') + const agentGuidance = getSection(skill, 'Agent Guidance') + const nextAction = getSection(skill, 'Next Action') + + expect(workerLoop).toContain( + '# Process every message. For each accepted worker_done that is not immediately reused:\n' + + 'orca orchestration worker-release --dispatch --json' + ) + expect(workerLoop).toContain( + 'Acknowledge only after every message and required release decision is handled' + ) + expect(workerLoop).toContain( + 'read the `worker.agent_terminal_handle` field of `worker-show --dispatch --json`' + ) + expect(workerLoop).toContain( + 'orca orchestration worker-start --task --terminal --json` so Orca ' + + 'transfers cleanup ownership to the new Dispatch' + ) + expect(workerLoop).toContain( + 'Run `worker-release` after both succeeded and failed `worker_done` reports unless the user ' + + 'explicitly asked to keep that worker live.' + ) + expect(workerLoop).toContain('Release is post-completion cleanup, not cancellation') + expect(workerLoop).toContain('orca orchestration worker-retain --dispatch --json') + expect(workerLoop).toContain( + 'the same Dispatch can be passed to `worker-release`, which clears the requested retention' + ) + expect(agentGuidance).toContain( + 'Coordinators must account for every settled worker terminal before waiting again or ending ' + + 'the turn' + ) + expect(agentGuidance).toContain('released workers remain readable through `worker-read`') + expect(nextAction).toContain( + 'After every accepted `worker_done`, either transfer the exact terminal to an immediate ' + + 'follow-up Dispatch or run `worker-release` before the next wait.' + ) + }) + + it('never authorizes release from idle, timeout, or worker-side triggers', () => { + const skill = readSkill() + const workerLoop = getSection(skill, 'Preferred Supervised Worker Loop') + const agentGuidance = getSection(skill, 'Agent Guidance') + + // The prohibition sentence is the guard the negative patterns below rely on. + expect(workerLoop).toContain( + 'Do not release a worker because of a timeout, TUI idle state, heartbeat, status, question, ' + + 'escalation, or rejected/stale `worker_done`.' + ) + expect(workerLoop).toContain( + 'do not substitute `terminal close`; follow the exact recovery action in the receipt' + ) + expect(skill).not.toMatch( + /release[^.]*\bon (?:a |the )?(?:tui-?idle|idle|timeout|heartbeat|question|escalation)\b/iu + ) + expect(skill).not.toMatch( + /\b(?:after|on|upon) (?:a |the )?(?:tui-?idle|idle state|timeout|heartbeat)\b[^.]*\brelease/iu + ) + expect(agentGuidance).toContain( + 'do not start more work, poll, or attempt to close the terminal yourself' + ) + expect(agentGuidance).not.toMatch(/worker-release[^.]*\byourself\b/iu) + }) + it('documents @grok in the Messaging group address list', () => { const skill = readSkill() const messaging = getSection(skill, 'Messaging') diff --git a/config/scripts/plain-node-entry-guard.test.ts b/config/scripts/plain-node-entry-guard.test.ts index a7583e1d470..b9601a67d41 100644 --- a/config/scripts/plain-node-entry-guard.test.ts +++ b/config/scripts/plain-node-entry-guard.test.ts @@ -85,3 +85,91 @@ describe('plain Node entry guard', () => { ) }) }) + +// Why (#11161): Electron's module is not registered on worker threads either — +// require("electron") throws "Cannot find module 'electron'" inside a +// main-process worker and kills it at startup. The worker entries carried only +// hand-written "must stay electron-free" comments, and the port-scan worker sits +// one import away from a client that deliberately does require electron. +describe('worker thread entry guard', () => { + function runWorkerWriteBundle(plugin: Plugin, bundle: Rollup.OutputBundle): void { + const hook = plugin.writeBundle + if (typeof hook !== 'function') { + throw new Error('Expected writeBundle hook') + } + hook.call( + { meta: { watchMode: false } } as never, + { dir: createOutputDir() } as Rollup.NormalizedOutputOptions, + bundle + ) + } + + function workerChunk(name: string, code: string, imports: string[] = []): Rollup.OutputChunk { + return { + type: 'chunk', + code, + dynamicImports: [], + fileName: `${name}.js`, + imports, + isEntry: true, + name + } as Rollup.OutputChunk + } + + it('rejects an Electron require reachable from a worker entry', () => { + const plugin = createPlainNodeEntryGuardPlugin() + const bundle = { + 'port-scan-command-worker-entry.js': workerChunk( + 'port-scan-command-worker-entry', + 'require("electron")' + ) + } as Rollup.OutputBundle + + expect(() => runWorkerWriteBundle(plugin, bundle)).toThrow('requires electron') + }) + + it('names the worker-thread runtime so the failure is actionable', () => { + const plugin = createPlainNodeEntryGuardPlugin() + const bundle = { + 'stt-worker.js': workerChunk('stt-worker', 'require("electron")') + } as Rollup.OutputBundle + + expect(() => runWorkerWriteBundle(plugin, bundle)).toThrow('runs as a worker thread') + }) + + // The real risk is transitive: a worker entry importing a shared chunk that + // reaches the electron-requiring client, not a direct import anyone would spot. + it('follows shared chunks out of a worker entry', () => { + const plugin = createPlainNodeEntryGuardPlugin() + const bundle = { + 'session-scanner-opencode-sqlite-worker-entry.js': workerChunk( + 'session-scanner-opencode-sqlite-worker-entry', + 'require("./chunks/shared.js")', + ['chunks/shared.js'] + ), + 'chunks/shared.js': { + type: 'chunk', + code: 'require("electron")', + dynamicImports: [], + fileName: 'chunks/shared.js', + imports: [], + isEntry: false, + name: 'shared' + } as Rollup.OutputChunk + } as Rollup.OutputBundle + + expect(() => runWorkerWriteBundle(plugin, bundle)).toThrow('chunks/shared.js') + }) + + it('passes a clean worker entry', () => { + const plugin = createPlainNodeEntryGuardPlugin() + const bundle = { + 'warp-theme-parser-worker.js': workerChunk( + 'warp-theme-parser-worker', + 'require("node:worker_threads")' + ) + } as Rollup.OutputBundle + + expect(() => runWorkerWriteBundle(plugin, bundle)).not.toThrow() + }) +}) diff --git a/config/scripts/setup-adhoc-release-repo.sh b/config/scripts/setup-adhoc-release-repo.sh index d239d930717..3e232c5fce8 100755 --- a/config/scripts/setup-adhoc-release-repo.sh +++ b/config/scripts/setup-adhoc-release-repo.sh @@ -39,14 +39,23 @@ else # Why the features are off: this repo holds releases and nothing else. Leaving # issues open invites bug reports against a branch build in a repo nobody # watches, where they are simply lost. + # + # Why --add-readme in a repo with no source: publishing a release creates a tag, + # and a tag needs a commit. Empty repo = "Repository is empty" 25 minutes in. gh repo create "$ADHOC_REPO" \ --public \ --description "Adhoc macOS dev builds of Orca, cut from unlanded branches. Not a source repo." \ + --add-readme \ --disable-issues \ --disable-wiki || fail "Could not create $ADHOC_REPO." fi +# Also checked outside the create branch: a repo made before --add-readme is here. +if ! gh api "repos/$ADHOC_REPO/commits" --jq 'length' >/dev/null 2>&1; then + fail "$ADHOC_REPO has no commits — releases cannot be tagged. Add any file to it first." +fi + echo echo "Granting $APP_SLUG access to $ADHOC_REPO..." diff --git a/config/scripts/verify-localization-catalog.mjs b/config/scripts/verify-localization-catalog.mjs index 901c651798d..d3e25d3fd2c 100644 --- a/config/scripts/verify-localization-catalog.mjs +++ b/config/scripts/verify-localization-catalog.mjs @@ -6,6 +6,9 @@ import process from 'node:process' // TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. import ts from 'typescript-api' +import { canonicalGenericRenderings } from './locale-generic-ui-terms.mjs' +import { repairTranslatedValue } from './locale-translation-policy.mjs' + const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts']) const SKIP_PATH_PARTS = new Set(['.git', 'dist', 'node_modules', 'out', '__snapshots__', 'assets']) const LOCALIZATION_FUNCTION_NAMES = new Set(['t', 'translate', 'translateMain']) @@ -282,9 +285,51 @@ function applyMissingEnglishEntries(catalog, missing) { return changed } +// Why: #12113 — parity checks pass while repair-locale-catalog rewrites translated generic terms +// back to English, so drift only surfaces when someone regenerates the catalog. +export function collectGenericTermRegressions(enEntries, localeEntries, localeName) { + const renderings = canonicalGenericRenderings(localeName) + if (renderings.length === 0) { + return [] + } + + const regressions = [] + for (const [key, enValue] of enEntries) { + const localeValue = localeEntries.get(key) + if (typeof enValue !== 'string' || typeof localeValue !== 'string') { + continue + } + const repaired = repairTranslatedValue({ key, enValue, localeValue, locale: localeName }) + if (repaired === localeValue) { + continue + } + // Why: {{agent}} is an interpolation name, not English copy the reader sees. + const repairedCopy = repaired.replace(PLACEHOLDER_RE, '') + for (const { form, terms } of renderings) { + if (!localeValue.includes(form) || repaired.includes(form)) { + continue + } + if ( + terms.some((term) => new RegExp(`(^|[^A-Za-z])${term}($|[^A-Za-z])`).test(repairedCopy)) + ) { + regressions.push({ key, form, localeValue, repaired }) + break + } + } + } + return regressions +} + +function formatGenericTermRegressions(regressions) { + return regressions + .map((entry) => `${entry.key}: ${entry.form} -> English (${entry.repaired})`) + .join('\n') +} + function verifyLocaleCatalog(enCatalog, localeName, localeCatalog) { const { enEntries, localeEntries, missingInLocale, extraInLocale, interpolationMismatches } = collectLocaleParityIssues(enCatalog, localeCatalog) + const genericTermRegressions = collectGenericTermRegressions(enEntries, localeEntries, localeName) // Why: feature PRs own English declarations; absent target leaves deliberately // use i18next's existing English fallback until a localization PR supplies them. @@ -292,7 +337,11 @@ function verifyLocaleCatalog(enCatalog, localeName, localeCatalog) { `${localeName}.json coverage: ${enEntries.size - missingInLocale.length}/${enEntries.size} translated, ${missingInLocale.length} missing.` ) - if (extraInLocale.length > 0 || interpolationMismatches.length > 0) { + if ( + extraInLocale.length > 0 || + interpolationMismatches.length > 0 || + genericTermRegressions.length > 0 + ) { console.error(`Locale catalog validation failed for ${localeName}.json.`) if (extraInLocale.length > 0) { console.error('') @@ -310,6 +359,18 @@ function verifyLocaleCatalog(enCatalog, localeName, localeCatalog) { console.error(`...and ${interpolationMismatches.length - 20} more interpolation mismatches`) } } + if (genericTermRegressions.length > 0) { + console.error('') + console.error( + 'repair-locale-catalog would rewrite these translated terms back to English.', + 'Treat the term as generic in config/scripts/locale-generic-ui-terms.mjs', + 'instead of listing its translation as a mistranslation.' + ) + console.error(formatGenericTermRegressions(genericTermRegressions.slice(0, 20))) + if (genericTermRegressions.length > 20) { + console.error(`...and ${genericTermRegressions.length - 20} more generic term regressions`) + } + } return 1 } diff --git a/config/scripts/verify-localization-catalog.test.mjs b/config/scripts/verify-localization-catalog.test.mjs index 89e24bc0c0d..4bf3d7d7eba 100644 --- a/config/scripts/verify-localization-catalog.test.mjs +++ b/config/scripts/verify-localization-catalog.test.mjs @@ -4,7 +4,10 @@ import path from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { main as verifyLocalizationCatalog } from './verify-localization-catalog.mjs' +import { + collectGenericTermRegressions, + main as verifyLocalizationCatalog +} from './verify-localization-catalog.mjs' function writeJson(filePath, value) { writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8') @@ -123,4 +126,47 @@ describe('verify-localization-catalog', () => { report.mockRestore() } }) + + // Why: #12113 — parity checks passed while the repair policy rewrote translated terms to English. + it('flags catalog values the repair policy would rewrite back to English', () => { + const enEntries = new Map([['auto.example.commitLabel', 'Commit message']]) + + expect( + collectGenericTermRegressions( + enEntries, + new Map([['auto.example.commitLabel', 'mensaje de confirmación']]), + 'es' + ) + ).toEqual([]) + + // A locale whose committed value is the English term is stable, not a regression. + expect( + collectGenericTermRegressions( + enEntries, + new Map([['auto.example.commitLabel', 'mensaje de Commit']]), + 'es' + ) + ).toEqual([]) + + // 'Comprometerse' is a real mistranslation, so reverting it to Latin is expected. + expect( + collectGenericTermRegressions( + enEntries, + new Map([['auto.example.commitLabel', 'mensaje de Comprometerse']]), + 'es' + ) + ).toEqual([]) + }) + + it('ignores interpolation names when looking for English rewrites', () => { + expect( + collectGenericTermRegressions( + new Map([ + ['components.agentSessionContinuation.originalAgent', 'Original agent: {{agent}}'] + ]), + new Map([['components.agentSessionContinuation.originalAgent', '原智能体:{{agent}}']]), + 'zh' + ) + ).toEqual([]) + }) }) diff --git a/config/vitest.config.ts b/config/vitest.config.ts index 1146cd4a5ca..735e1b2a0af 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -17,6 +17,8 @@ export default defineConfig({ environment: 'node', // Why: Node 26's undefined Web Storage globals prevent Vitest from installing happy-dom's. execArgv: ['--no-experimental-webstorage'], + // Why: happy-dom drops MutationObserver callbacks on GC; keep them alive like a browser does. + setupFiles: [resolve('config/scripts/happy-dom-mutation-observer-retention.ts')], include: [ 'src/**/*.test.ts', 'src/**/*.test.tsx', diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index df51a8732ac..98410899a3d 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 13m + + downloads: 14m @@ -15,7 +15,7 @@ downloads downloads - 13m - 13m + 14m + 14m diff --git a/docs/reference/headless-linux-server.md b/docs/reference/headless-linux-server.md index cdee2a4ca41..2284bcdaa23 100644 --- a/docs/reference/headless-linux-server.md +++ b/docs/reference/headless-linux-server.md @@ -155,6 +155,8 @@ display `:99` when no display exists: Description=Orca runtime server After=network-online.target Wants=network-online.target +StartLimitIntervalSec=300 +StartLimitBurst=5 [Service] Type=simple @@ -165,6 +167,7 @@ ExecStart=/opt/orca/orca-linux.AppImage serve --port 6768 --pairing-address 100. StandardOutput=journal StandardError=journal Restart=on-failure +RestartPreventExitStatus=3 RestartSec=5 [Install] @@ -174,6 +177,19 @@ WantedBy=multi-user.target Replace `100.64.1.20` with the LAN, Tailscale, tunnel, or public hostname that clients should use. +Exit status `3` means another process already owns this userData profile, so +`RestartPreventExitStatus=3` stops the unit instead of retrying a launch that +cannot succeed. Any other permanent startup fault is capped at 5 starts per +5 minutes; systemd's defaults (10s window, 5 starts) can never trip at +`RestartSec=5`, which is how one bad launch could restart thousands of times. +The start limit counts operator-initiated starts too, so once it trips systemd +refuses a plain `systemctl start` until the 5-minute window rolls over. Run +`sudo systemctl reset-failed orca-serve.service` first to clear it — the +[Upgrade](#upgrade-steps) and [Roll back](#roll-back) scripts already do. +On systemd older than 230 those two directives are spelled +`StartLimitInterval=`/`StartLimitBurst=` and belong in `[Service]`; Ubuntu +20.04, Orca's oldest supported base, ships systemd 245. + Enable the service: ```bash @@ -228,6 +244,8 @@ Then add the display dependency to the Orca service: Description=Orca runtime server After=network-online.target orca-xvfb.service Wants=network-online.target orca-xvfb.service +StartLimitIntervalSec=300 +StartLimitBurst=5 [Service] Type=simple @@ -237,6 +255,7 @@ Environment=DISPLAY=:99 Environment=LIBGL_ALWAYS_SOFTWARE=1 ExecStart=/opt/orca/orca-linux.AppImage serve --port 6768 --pairing-address 100.64.1.20 Restart=on-failure +RestartPreventExitStatus=3 RestartSec=5 [Install] @@ -415,6 +434,8 @@ recover_failed_upgrade() { sudo rm -f /opt/orca/orca-linux.AppImage.recovering \ /opt/orca/VERSION.recovering if ((recovery_ok)); then + # A tripped StartLimitBurst refuses a plain start + sudo systemctl reset-failed orca-serve.service || true sudo systemctl start orca-serve.service || true else echo 'Upgrade recovery failed; service remains stopped' >&2 @@ -482,6 +503,8 @@ sudo mv "$ORCA_ROLLBACK_NEW" "$ORCA_ROLLBACK" ORCA_BINARY_PROMOTED=1 sudo mv -f /opt/orca/orca-linux.AppImage.new /opt/orca/orca-linux.AppImage sudo mv -f /opt/orca/VERSION.new /opt/orca/VERSION +# Clears a start-limit hit left by the version being replaced +sudo systemctl reset-failed orca-serve.service sudo systemctl start orca-serve.service ORCA_SERVICE_STOPPED=0 trap - EXIT @@ -614,6 +637,8 @@ restart_after_rollback_error() { fi fi if ((recovery_ok)); then + # A tripped StartLimitBurst refuses a plain start + sudo systemctl reset-failed orca-serve.service || true sudo systemctl start orca-serve.service || true else echo 'Rollback recovery failed; service remains stopped' >&2 @@ -714,6 +739,8 @@ if ((ORCA_ROLLBACK_HAS_VERSION)); then else sudo rm -f /opt/orca/VERSION fi +# The crash-looping build you are rolling back from tripped StartLimitBurst +sudo systemctl reset-failed orca-serve.service sudo systemctl start orca-serve.service ORCA_SERVICE_STOPPED=0 sudo rm -rf -- "$ORCA_RESTORE" @@ -805,9 +832,24 @@ refuse to run there and print the command to run on the machine you want. `orca` user and that `/opt/orca` is readable by that user. - Clients cannot connect: make sure `--pairing-address` is an address reachable from the client, and make sure firewalls allow the selected `--port`. +- Journal shows `Another Orca instance is already running for this userData + profile` and the unit exits `3`: another process already owns the profile, so + `RestartPreventExitStatus=3` leaves the unit `failed` on purpose. Find the + owner with `systemctl status orca-serve` and `pgrep -af orca`. Stop it (or + keep it and leave the unit down), then run + `sudo systemctl reset-failed orca-serve && sudo systemctl start orca-serve` — + `reset-failed` clears the failed state and any start-limit counter. If no owner + exists, the lock is stale (Chromium recorded a pid that + has since been reused): remove `SingletonLock` and `SingletonSocket` from the + userData directory and start again. If an earlier crash-loop already leaked + AppImage mounts, list them with `findmnt -rn -t fuse.orca-linux.AppImage` and + release only the ones with no live owner using `fusermount -uz ` (or + `umount -l `), leaving the running instance's mount alone. - Service crash-loops right after an upgrade: use [Roll back](#roll-back) with the pre-upgrade `.ready` bundle. Do not rerun the upgrade first; doing so would - make the crashing version the next rollback binary. + make the crashing version the next rollback binary. The loop trips + `StartLimitBurst`, so any manual `systemctl start` outside that script needs + `sudo systemctl reset-failed orca-serve.service` first. - Diagnosing other missing libraries: extract the AppImage without launching it with `./orca-linux.AppImage --appimage-extract`, then run `ldd squashfs-root/orca` to list any shared libraries the host is missing. diff --git a/docs/reference/windows-setup-shell.md b/docs/reference/windows-setup-shell.md new file mode 100644 index 00000000000..6c93185b602 --- /dev/null +++ b/docs/reference/windows-setup-shell.md @@ -0,0 +1,86 @@ +# Windows setup-runner shell + +On native Windows, Orca writes the `orca.yaml` setup script (and the issue command) to a generated +runner file and types a launch command into a terminal. The runner is a **`.cmd` batch file by +default**, exactly as it has been since setup hooks shipped. + +A script opts into bash by starting with a `#!` interpreter line: + +```yaml +scripts: + setup: | + #!/usr/bin/env bash + [ -f .env ] || cp .env.example .env + pnpm install +``` + +Without that line the script keeps running under `cmd.exe`: + +```yaml +scripts: + setup: | + copy .env.example .env + xcopy /E assets dist +``` + +## Why the script declares it, not the terminal preference + +`terminalWindowsShell` says which shell *interactive terminals* open in. It says nothing about the +language a project's setup script is written in. Deriving the runner from it had two consequences: + +- Windows users with batch-syntax setup scripts silently switched to bash on upgrade, so `copy`, + `xcopy`, `set VAR=value`, and `if errorlevel 1` stopped working. +- Two people on the same repo got different interpreters for the same `orca.yaml`, so no project + could write a setup script that worked for all of its Windows contributors. + +A `#!` line is per-project, explicit, and identical for everyone who checks the repo out. + +The same rule applies to the per-user setup command in **Settings → repository hooks** +(`repo.hookSettings.scripts.setup`): it is merged into the same script that reaches the runner, so a +POSIX one-liner stored there needs its own `#!` line to run under bash on Windows. + +## What the `#!` line does and does not select + +The generated runner is always executed by bash (`bash `; Git Bash on native Windows), on +every platform. The `#!` line therefore does two things: + +- It declares the script is written for a POSIX shell, which is what selects the bash runner. +- Its option flags are replayed with `set`, so `#!/usr/bin/env -S bash -euo pipefail` really does + get `pipefail`. Without that replay the flags would be silently dropped, because `bash ` + never parses the interpreter line. Only the flags `set` itself accepts + (`[--abefhkmnptuvxBCHP] [-o option]`) are replayed; invocation-only ones such as `-l` are + dropped, because `set -l` exits 2 and would abort the runner before its first line. + +The interpreter name itself is not honored beyond "is this a POSIX shell": `#!/bin/sh` and +`#!/bin/zsh` scripts run under bash, exactly as they already did on macOS and Linux. + +## Requirements for the bash runner + +A `#!` line only takes effect when Orca can actually launch bash from the configured terminal — the +terminal shell must resolve to Git Bash (`resolveWindowsGitBashShellPath`). The generated runner +uses MSYS `/c/...` paths, which Cygwin and the WSL shim do not accept, and the launch command is +typed into whatever shell the terminal opened with. + +When bash is not available (a PowerShell/cmd terminal, or an SSH-to-Windows host, which always uses +the remote's `.cmd` runner) the `#!` script is **not** executed under cmd. The generated `.cmd` +runner prints why and exits 1, because running the interpreter-agnostic prefix of a bash script +(`pnpm install`, `git submodule update`) and only failing at the first bash-only line leaves a +half-set-up worktree that looks finished. + +## Launching a `.cmd` runner from a Git Bash terminal + +The runner format and the shell that types the launch command are independent: a Git Bash terminal +with a batch-syntax setup script gets a `.cmd` runner launched from a bash pane. `cmd.exe /c +"C:\..."` cannot be used there — MSYS rewrites the bare `/c` switch into a drive path, so cmd opens +interactively and the runner never executes (issue #6896). Those launches reuse the PowerShell +`ProcessStartInfo` launcher (`buildWindowsCmdRunnerDelayedLaunchCommand`), which carries the switch +and the runner path outside the command line. `WorktreeSetupLaunch.shell` therefore describes the +launching pane; the runner file's `.cmd`/`.sh` extension describes the format. + +The `wait-for-setup` gate follows the same split. The pane types the gate and already quoted the +agent startup command for itself, so a `.cmd` runner launched from a Git Bash pane still gets the +bash gate — PowerShell's `Invoke-Expression` cannot parse POSIX `'\''` escaping. The gate wraps the +same `ProcessStartInfo` launcher, so the batch runner is never handed to bash. + +WSL worktrees and non-Windows platforms are unaffected: they always use the bash runner. SSH hosts +choose their runner from the remote path format, never from local Windows preferences. diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 39f923cb215..a6e656ac9c6 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -216,6 +216,11 @@ export const electronViteConfig: UserConfig = { 'session-scanner-opencode-sqlite-worker-entry': resolve( 'src/main/ai-vault/session-scanner-opencode-sqlite-worker-entry.ts' ), + // Why: libuv spawns processes inline on the calling loop, so the port + // scan's probe commands run on a worker thread instead of the UI one. + 'port-scan-command-worker-entry': resolve( + 'src/main/ports/port-scan-command-worker-entry.ts' + ), // Why: forked with ELECTRON_RUN_AS_NODE so @parcel/watcher faults // can't take down the main process (issue #7547). 'parcel-watcher-process-entry': resolve('src/main/ipc/parcel-watcher-process-entry.ts'), diff --git a/mobile/.gitignore b/mobile/.gitignore index 449fa3f2439..0428cbb65a9 100644 --- a/mobile/.gitignore +++ b/mobile/.gitignore @@ -1,5 +1,6 @@ node_modules/ src/terminal/terminal-webview-engine.generated.ts +src/components/pr-sidebar/mermaid-webview-engine.generated.ts .expo/ dist/ /android/ diff --git a/mobile/app.json b/mobile/app.json index 413cebc8d28..53654335486 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -2,7 +2,7 @@ "expo": { "name": "Orca", "slug": "orca-mobile", - "version": "0.0.36", + "version": "0.0.37", "orientation": "default", "icon": "./assets/icon.png", "userInterfaceStyle": "automatic", @@ -75,7 +75,7 @@ "allowBackup": false, "permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS"], "package": "com.stably.orca.mobile", - "versionCode": 9 + "versionCode": 10 }, "plugins": [ "expo-router", diff --git a/mobile/app/h/[hostId]/index.tsx b/mobile/app/h/[hostId]/index.tsx index 24da552eafe..b71f171ceb8 100644 --- a/mobile/app/h/[hostId]/index.tsx +++ b/mobile/app/h/[hostId]/index.tsx @@ -164,7 +164,8 @@ export function HostScreen({ const [filters, setFilters] = useState({ filterRepoIds: new Set(), hideSleeping: false, - hideDefaultBranch: false + hideDefaultBranch: false, + alwaysShowDefaultBranch: true }) const [groupMode, setGroupMode] = useState('repo') const [workspaceStatuses, setWorkspaceStatuses] = useState( @@ -195,6 +196,7 @@ export function HostScreen({ sortMode: 'recent', hideSleeping: false, hideDefaultBranch: false, + alwaysShowDefaultBranch: true, filterRepoIds: [], collapsedGroups: [], workspaceStatuses: DEFAULT_MOBILE_WORKSPACE_STATUSES @@ -206,6 +208,7 @@ export function HostScreen({ sortMode, hideSleeping: filters.hideSleeping, hideDefaultBranch: filters.hideDefaultBranch, + alwaysShowDefaultBranch: filters.alwaysShowDefaultBranch !== false, filterRepoIds: [...filters.filterRepoIds], collapsedGroups: [...collapsedGroups], workspaceStatuses @@ -222,7 +225,8 @@ export function HostScreen({ setFilters({ filterRepoIds: new Set(next.filterRepoIds), hideSleeping: next.hideSleeping, - hideDefaultBranch: next.hideDefaultBranch + hideDefaultBranch: next.hideDefaultBranch, + alwaysShowDefaultBranch: next.alwaysShowDefaultBranch }) }, []) @@ -234,6 +238,9 @@ export function HostScreen({ if (!client) { return } + // alwaysShowDefaultBranchWorkspace is deliberately absent: mobile reads it + // but has no toggle, so echoing its local default would silently revert a + // desktop opt-out on the first filter tap before ui.get lands (#8873). const payload: WorkspaceViewSettings = { groupBy: groupModeToDesktop(next.groupMode), sortBy: next.sortMode, diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index 8f6d7ca0c97..97355ee8665 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -107,6 +107,7 @@ import type { TerminalWebViewHandle } from '../../../../src/terminal/terminal-webview-contract' import { isTerminalOscLinkRanges } from '../../../../src/terminal/terminal-osc-link-ranges' +import { computeActiveTerminalKeyboardLift } from '../../../../src/terminal/terminal-keyboard-avoidance-lift' import { useTerminalViewportRefit } from '../../../../src/terminal/terminal-viewport-refit' import { getDefaultTerminalAccessoryBuiltInIds, @@ -195,7 +196,7 @@ import { MobileTerminalLiveInputStatus } from '../../../../src/session/MobileTer import { MobileTerminalInputActions } from '../../../../src/session/MobileTerminalInputActions' import { resolveMobileFileTabDoc } from '../../../../src/files/mobile-file-tab-doc' import { captureMobileFileMutationOwnership } from '../../../../src/files/mobile-file-mutation-ownership' -import { openMobileTerminalFileTap } from '../../../../src/session/mobile-terminal-file-tap-open' +import { useMobileFileTapHandlers } from '../../../../src/session/use-mobile-file-tap-handlers' import { useLiveWorktreeName } from '../../../../src/session/use-live-worktree-name' import { acceptSessionSnapshot, @@ -235,6 +236,11 @@ import { } from '../../../../src/session/mobile-terminal-prune-decision' import { useMobileNativeChatTerminalStream } from '../../../../src/session/use-mobile-native-chat-terminal-stream' import { subscribeMobileTerminalSafely } from '../../../../src/session/mobile-terminal-stream-subscribe' +import { + TerminalViewportResubscribeBudget, + readTerminalViewportDims, + runTerminalViewportFitPass +} from '../../../../src/session/mobile-terminal-viewport-resubscribe' import { activateMobileSessionTab } from '../../../../src/session/mobile-session-tab-activation' import { MobileTerminalDiagnostics } from '../../../../src/session/mobile-terminal-diagnostics' import { runAcceptedMobileSessionTabsEffects } from '../../../../src/session/mobile-session-tabs-accepted-effects' @@ -1030,6 +1036,8 @@ export default function SessionScreen() { const subscribingHandlesRef = useRef>(new Set()) const initializedHandlesRef = useRef>(new Set()) const terminalDiagnosticsRef = useRef(new MobileTerminalDiagnostics()) + // Why: bounds the scrollback→resubscribe fit loop per handle (STA-3337). + const viewportResubscribeBudgetRef = useRef(new TerminalViewportResubscribeBudget()) // Why: don't subscribe until the WebView fires web-ready — iOS may defer JS in hidden WebViews and init() messages would queue unrendered. const webReadyHandlesRef = useRef>(new Set()) const activeHandleRef = useRef(null) @@ -1376,6 +1384,7 @@ export default function SessionScreen() { subscribingHandlesRef.current.clear() initializedHandlesRef.current.clear() terminalDiagnosticsRef.current.clearTerminalCache() + viewportResubscribeBudgetRef.current.clear() webReadyHandlesRef.current.clear() subscribeSeqRef.current.clear() layoutSeqRef.current.clear() @@ -1505,10 +1514,11 @@ export default function SessionScreen() { return } updateTerminalCwdFromStreamEvent(handle, data, terminalCwdRef.current) - const cols = (data.cols as number) || 80 - const rows = (data.rows as number) || 24 - const scrollbackCols = cols - const scrollbackRows = rows + const { hostCols, hostRows } = readTerminalViewportDims(data) + // Why: absent host dims must not be coerced into a comparable size — 80x24 + // never equals a phone viewport and armed a zero-delay resubscribe loop (STA-3337). + const cols = hostCols ?? viewportRef.current?.cols ?? 80 + const rows = hostRows ?? viewportRef.current?.rows ?? 24 const initialData = typeof data.serialized === 'string' && data.serialized.length > 0 ? data.serialized @@ -1527,46 +1537,36 @@ export default function SessionScreen() { ref.init(cols, rows, initialData, false, oscLinks) initializedHandlesRef.current.add(handle) if (data.displayMode) { + const displayMode = data.displayMode as MobileDisplayMode + // Why: same-mode frames must keep the Map identity, or every stream pass re-renders the whole route. setTerminalModes((prev) => - new Map(prev).set(handle, data.displayMode as MobileDisplayMode) + prev.get(handle) === displayMode ? prev : new Map(prev).set(handle, displayMode) ) } // Why: cold-start refit — init()'s fit can run against a transient scrollWidth, so re-fire against a settled DOM. scheduleDelayedAction(() => getTerminalRef(handle)?.resetZoom(), 200) - // Why: first subscribe has no viewport (xterm not loaded yet), so measure after init and resubscribe so the server can phone-fit. - const needsResubscribe = - !viewportMeasuredRef.current || - (viewportRef.current != null && - (scrollbackCols !== viewportRef.current.cols || - scrollbackRows !== viewportRef.current.rows)) - if (needsResubscribe) { - void (async () => { - // Why: wait for init()'s rAF chain before measuring, else the measure races ahead and returns null (log dump 2026-05-06). - await getTerminalRef(handle)?.awaitReady() - if (subscribeSeqRef.current.get(handle) !== seq) { - return - } - const dims = await getTerminalRef(handle)?.measureFitDimensions( - terminalFrameHeightRef.current || undefined - ) - // Why: re-check seq — the awaits may have let a newer subscribe cycle arm; tearing it down would resubscribe a stale generation. - if (subscribeSeqRef.current.get(handle) !== seq) { - return - } - if (!getTerminalRef(handle)) { - return - } - // Why: scrollback came back at cols=80 (server's null-viewport fallback), so this subscriber record has no viewport — resubscribe so the server stores it. - if (dims) { - diagnostics.streamResubscribing(handle, seq, dims) - viewportRef.current = dims - viewportMeasuredRef.current = true - unsubscribeTerminal(handle) - initializedHandlesRef.current.delete(handle) - subscribeToTerminal(handle) - } - })() - } + // Why: first subscribe has no viewport (xterm not loaded yet), so measure after init + // and resubscribe so the server can phone-fit — bounded per handle so a + // non-converging host degrades visibly instead of hot-looping (STA-3337). + runTerminalViewportFitPass({ + handle, + seq, + hostCols, + hostRows, + budget: viewportResubscribeBudgetRef.current, + diagnostics, + viewportRef, + viewportMeasuredRef, + subscribeSeqRef, + initializedHandlesRef, + terminalUnsubsRef, + terminalFrameHeightRef, + getTerminalRef, + unsubscribeTerminal, + subscribeToTerminal, + scheduleDelayedAction, + showToast + }) } else if (data.type === 'metadata') { updateTerminalCwdFromStreamEvent(handle, data, terminalCwdRef.current) } else if (data.type === 'data') { @@ -1591,8 +1591,12 @@ export default function SessionScreen() { } else if (data.type === 'resized') { updateTerminalCwdFromStreamEvent(handle, data, terminalCwdRef.current) // Server resize: reinit xterm on a full-buffer snapshot (width reflow rewraps scrollback), else just resize geometry. - const cols = (data.cols as number) || 80 - const rows = (data.rows as number) || 24 + const viewport = viewportMeasuredRef.current ? viewportRef.current : null + const [cols, rows] = viewportResubscribeBudgetRef.current.observeResize( + handle, + data, + viewport + ) const serialized = typeof data.serialized === 'string' ? data.serialized : null diagnostics.streamResized(handle, seq, eventSeq, data, getTerminalRef(handle) != null) const oscLinks = isTerminalOscLinkRanges(data.oscLinks) ? data.oscLinks : undefined @@ -1602,8 +1606,10 @@ export default function SessionScreen() { getTerminalRef(handle)?.resize(cols, rows) } if (data.displayMode) { + const displayMode = data.displayMode as MobileDisplayMode + // Why: same-mode frames must keep the Map identity, or every stream pass re-renders the whole route. setTerminalModes((prev) => - new Map(prev).set(handle, data.displayMode as MobileDisplayMode) + prev.get(handle) === displayMode ? prev : new Map(prev).set(handle, displayMode) ) } scheduleDelayedAction(() => getTerminalRef(handle)?.resetZoom(), 200) @@ -1619,7 +1625,7 @@ export default function SessionScreen() { } subscribingHandlesRef.current.delete(handle) }, - [client, getTerminalRef, markNativeChatInputLeaseReady, scheduleDelayedAction] + [client, getTerminalRef, markNativeChatInputLeaseReady, scheduleDelayedAction, showToast] ) const nativeChatStream = useMobileNativeChatTerminalStream({ @@ -1720,12 +1726,16 @@ export default function SessionScreen() { unsubscribeTerminal(handle) terminalRefs.current.delete(handle) initializedHandlesRef.current.delete(handle) + viewportResubscribeBudgetRef.current.forget(handle) clearTerminalLiveInputDefault(handle) } setTerminalKeyboardMetrics((prev) => pruneTerminalKeyboardMetrics(prev, shouldPrune)) // Why: a chat-covered handle the host reports again refills its rearm budget, // so an exhausted rearm can't lock the composer until leave-chat. nativeChatStream.notifyListedHandles(liveHandles) + // Why: same absence-gated refill for the viewport-fit budget — a handle that + // left the list and returned may converge now, so it earns fresh attempts. + viewportResubscribeBudgetRef.current.notifyListedHandles(liveHandles) lastKnownTerminalCountRef.current = result.terminals.length // Why: dedupe duplicate handles (rename/split race) to avoid a React duplicate-key throw; keep first for tab-strip order. const seen = new Set() @@ -3182,44 +3192,23 @@ export default function SessionScreen() { }) }, []) - // Tap a terminal file path → resolve on host, open as file tab (mirrors desktop Cmd/Ctrl-click); silent on a miss. - const handleFileTapActivationSeqRef = useRef(0) - const handleFileTap = useCallback( - (handle: string, pathText: string, line: number | null, column: number | null) => { - if (handle !== activeHandleRef.current || !client) { - return - } - const activationSeq = ++handleFileTapActivationSeqRef.current - openMobileTerminalFileTap({ - client, - hostId, - worktreeId, - worktreeName: routeWorktreeName, - terminalHandle: handle, - pathText, - cwd: terminalCwdRef.current.get(handle) ?? null, - line, - column, - pushPreviewRoute: (href) => router.push(href), - openBrowser: (url) => void handleCreateBrowserRef.current?.(url), - triggerOpenFeedback: triggerSelection, - fetchSessionTabs, - getSessionTabs: () => sessionTabsRef.current, - getActiveSessionTabId: () => activeSessionTabIdRef.current, - getActivationState: (activated) => ({ - activated, - activationSeq, - latestActivationSeq: handleFileTapActivationSeqRef.current, - sourceTerminalHandle: handle, - activeTerminalHandle: activeHandleRef.current, - activeTabType: activeSessionTabTypeRef.current - }), - switchSessionTab: (tab) => switchSessionTabRef.current?.(tab), - scheduleDelayedAction - }) - }, - [client, fetchSessionTabs, hostId, routeWorktreeName, router, scheduleDelayedAction, worktreeId] - ) + // Tap a terminal or chat file path → resolve on host, open as file tab/preview. + const { handleFileTap, handleNativeChatFileTap } = useMobileFileTapHandlers({ + client, + hostId, + worktreeId, + worktreeName: routeWorktreeName, + activeHandleRef, + terminalCwdRef, + openBrowser: (url) => void handleCreateBrowserRef.current?.(url), + fetchSessionTabs, + getSessionTabs: () => sessionTabsRef.current, + getActiveSessionTabId: () => activeSessionTabIdRef.current, + getActiveSessionTabType: () => activeSessionTabTypeRef.current, + switchSessionTab: (tab) => switchSessionTabRef.current?.(tab), + scheduleDelayedAction, + reportChatTapFailure: nativeChatSendError.show + }) const handleOpenedFileDiffActivationSeqRef = useRef(0) // Capture active tab at tap time; reading it after openDiff would misread a mid-RPC switch and let the retry steal focus. @@ -3590,6 +3579,7 @@ export default function SessionScreen() { if ( current && current.cursorY === metrics.cursorY && + current.contentBottomRow === metrics.contentBottomRow && current.rows === metrics.rows && current.altScreen === metrics.altScreen ) { @@ -4271,24 +4261,11 @@ export default function SessionScreen() { ? Math.max(0, keyboardHeight - insets.bottom) : keyboardHeight : 0 - const activeTerminalKeyboardLift = (() => { - if (keyboardLift <= 0 || !activeHandle) { - return 0 - } - const metrics = terminalKeyboardMetrics.get(activeHandle) - if (!metrics || metrics.rows <= 0 || terminalFrameHeightRef.current <= 0) { - return keyboardLift - } - if (metrics.altScreen) { - return keyboardLift - } - const rowHeight = terminalFrameHeightRef.current / metrics.rows - const cursorBottom = (metrics.cursorY + 1) * rowHeight - const dockTop = terminalFrameHeightRef.current - keyboardLift - const margin = rowHeight - // Why: only move the terminal when the cursor would sit under the raised input dock; short top output stays put. - return Math.min(keyboardLift, Math.max(0, cursorBottom + margin - dockTop)) - })() + const activeTerminalKeyboardLift = computeActiveTerminalKeyboardLift({ + keyboardLift, + metrics: activeHandle ? terminalKeyboardMetrics.get(activeHandle) : undefined, + terminalFrameHeight: terminalFrameHeightRef.current + }) const toastAnimatedStyle = { opacity: toastOpacityRef.current, transform: [{ translateY: -keyboardLift }] @@ -4752,6 +4729,7 @@ export default function SessionScreen() { ))} void, + setStats: ( + updater: (prev: Record) => Record + ) => void, disposed: () => boolean ) { sendSingleFlightRequest(client, hostId, 'stats.summary') @@ -132,61 +124,13 @@ function fetchStats( return } if (response.ok) { - setStats(response.result as StatsSummary) + // Keyed by host: the header totals every desktop instead of showing whoever replied last. + setStats((prev) => ({ ...prev, [hostId]: response.result as HomeStatsSummary })) } }) .catch(() => {}) } -function fetchWorktreeInfo( - client: RpcClient, - hostId: string, - setInfo: ( - updater: (prev: Record) => Record - ) => void, - disposed: () => boolean -) { - const markUnavailable = () => { - setInfo((prev) => { - const current = prev[hostId] - const next = markHomeWorktreeCatalogUnavailable(current, hostId) - return next === current ? prev : { ...prev, [hostId]: next } - }) - } - - sendSingleFlightRequest(client, hostId, 'worktree.ps', { limit: WORKTREE_PS_FULL_LIMIT }) - .then((response) => { - if (disposed()) { - return - } - if (response.ok) { - const result = response.result as { worktrees: HomeWorktreeSummary[] } - const worktrees = result.worktrees ?? [] - setCachedWorktrees(hostId, worktrees) - const activeStatuses = new Set(['working', 'active', 'permission']) - const active = worktrees.filter((w) => w.status && activeStatuses.has(w.status)) - // Mirror the desktop's focused workspace (see pickResumeWorktree). - const lastActive = pickResumeWorktree(worktrees) - setInfo((prev) => ({ - ...prev, - [hostId]: { - hostId, - totalWorktrees: worktrees.length, - activeCount: active.length, - lastActiveWorktree: lastActive - } - })) - } else { - markUnavailable() - } - }) - .catch(() => { - if (!disposed()) { - markUnavailable() - } - }) -} - function fetchAccountsSnapshot( client: RpcClient, hostId: string, @@ -262,6 +206,7 @@ function repoColor(name: string): string { export default function HomeScreen() { const router = useRouter() + const openMobileHostEdit = useOpenMobileHostEdit() const openMobileTasks = useOpenMobileTasks() const insets = useSafeAreaInsets() // Why: cap/center content on wide/tablet canvases so cards don't stretch edge-to-edge on iPad. @@ -272,7 +217,7 @@ export default function HomeScreen() { const [hostStates, setHostStates] = useState>({}) const [hostAttempts, setHostAttempts] = useState>({}) const [hostLastConnected, setHostLastConnected] = useState>({}) - const [stats, setStats] = useState(null) + const [statsByHost, setStatsByHost] = useState>({}) const [worktreeInfo, setWorktreeInfo] = useState>({}) const [accountsByHost, setAccountsByHost] = useState>({}) const [taskProvidersByHost, setTaskProvidersByHost] = useState>({}) @@ -285,6 +230,8 @@ export default function HomeScreen() { // Why: shared clients from the per-host store, not N independent WebSockets. See docs/mobile-shared-client-per-host.md. const hostIds = useMemo(() => hosts.map((h) => h.id), [hosts]) + // Why: scoped to the paired hosts so an unpaired desktop's cached reply leaves the header total. + const stats = useMemo(() => totalHomeStats(statsByHost, hostIds), [statsByHost, hostIds]) const allClients = useAllHostClients(hostIds) const hostPaths = useMemo( () => Object.fromEntries(allClients.map(({ hostId, path }) => [hostId, path])), @@ -375,8 +322,8 @@ export default function HomeScreen() { }) for (const entry of allClientsRef.current) { if (entry.client.getState() === 'connected') { - fetchStats(entry.client, entry.hostId, setStats, () => stale) - fetchWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => stale) + fetchStats(entry.client, entry.hostId, setStatsByHost, () => stale) + void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => stale) fetchAccountsSnapshot(entry.client, entry.hostId, setAccountsByHost, () => stale) fetchTaskProviders(entry.client, entry.hostId, setTaskProvidersByHost, () => stale) } @@ -457,60 +404,70 @@ export default function HomeScreen() { }) }, [allClients, hosts]) - // Per-host notif/accounts subs + one-shot stats on 'connected'; re-runs per (hostId, client) pair, socket stays open so it's cheap. - useEffect(() => { - const cleanups: Array<() => void> = [] - for (const entry of allClients) { - let unsubNotif: (() => void) | null = null - let unsubAccounts: (() => void) | null = null - let statsFetched = false - const wireUp = (state: ConnectionState) => { - if (state === 'connected') { - if (!unsubNotif) { - unsubNotif = subscribeToDesktopNotifications(entry.client, entry.hostId) - } - if (!unsubAccounts) { - unsubAccounts = entry.client.subscribe('accounts.subscribe', null, (payload) => { - if (!payload || typeof payload !== 'object') { - return + // Notif/accounts subs + a snapshot read per connect for one host. Lives outside the effect body + // because react-doctor's effect-needs-cleanup false-positives on `subscribe` inside one; the + // returned disposer owns every handle allocated here. + const wireHostSubscriptions = (entry: { + hostId: string + client: RpcClient + state: ConnectionState + }) => { + let unsubNotif: (() => void) | null = null + let unsubAccounts: (() => void) | null = null + const refetchGate = createHostConnectRefetchGate() + const wireUp = (state: ConnectionState) => { + const reconnected = refetchGate.observe(state) + if (state === 'connected') { + if (!unsubNotif) { + unsubNotif = subscribeToDesktopNotifications(entry.client, entry.hostId) + } + if (!unsubAccounts) { + unsubAccounts = entry.client.subscribe('accounts.subscribe', null, (payload) => { + if (!payload || typeof payload !== 'object') { + return + } + const evt = payload as { type?: string; snapshot?: unknown } + if (evt.type === 'ready' || evt.type === 'snapshot') { + try { + const snapshot = decodeAccountsSnapshot(evt.snapshot) + setAccountsByHost((prev) => ({ ...prev, [entry.hostId]: snapshot })) + } catch { + // Keep the last proven snapshot; malformed remote data must + // not enter render state or crash the home host cards. } - const evt = payload as { type?: string; snapshot?: unknown } - if (evt.type === 'ready' || evt.type === 'snapshot') { - try { - const snapshot = decodeAccountsSnapshot(evt.snapshot) - setAccountsByHost((prev) => ({ ...prev, [entry.hostId]: snapshot })) - } catch { - // Keep the last proven snapshot; malformed remote data must - // not enter render state or crash the home host cards. - } - } - }) - } - if (!statsFetched) { - statsFetched = true - fetchStats(entry.client, entry.hostId, setStats, () => false) - fetchWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => false) - fetchTaskProviders(entry.client, entry.hostId, setTaskProvidersByHost, () => false) - } - } else { - if (unsubNotif) { - unsubNotif() - unsubNotif = null - } - if (unsubAccounts) { - unsubAccounts() - unsubAccounts = null - } + } + }) + } + // Why: the socket survives backgrounding/handoffs by reconnecting, so re-read the host + // snapshot on every reconnect — a one-shot latch left the card on stale data forever. + if (reconnected) { + fetchStats(entry.client, entry.hostId, setStatsByHost, () => false) + void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => false) + fetchTaskProviders(entry.client, entry.hostId, setTaskProvidersByHost, () => false) + } + } else { + if (unsubNotif) { + unsubNotif() + unsubNotif = null + } + if (unsubAccounts) { + unsubAccounts() + unsubAccounts = null } } - wireUp(entry.state) - const unsubState = entry.client.onStateChange(wireUp) - cleanups.push(() => { - unsubState() - unsubNotif?.() - unsubAccounts?.() - }) } + wireUp(entry.state) + const unsubState = entry.client.onStateChange(wireUp) + return () => { + unsubState() + unsubNotif?.() + unsubAccounts?.() + } + } + + // Re-runs per (hostId, client) pair; the socket stays open so it's cheap. + useEffect(() => { + const cleanups = allClients.map((entry) => wireHostSubscriptions(entry)) return () => { for (const c of cleanups) { c() @@ -750,7 +707,6 @@ export default function HomeScreen() { const state = hostStates[item.id] ?? 'connecting' const attempts = hostAttempts[item.id] ?? 0 const lastConnectedAt = hostLastConnected[item.id] ?? null - const info = worktreeInfo[item.id] const verdict = classifyConnection({ state, reconnectAttempts: attempts, @@ -763,12 +719,7 @@ export default function HomeScreen() { state={state} verdict={verdict} path={hostPaths[item.id] ?? 'lan'} - worktreeCounts={ - info && !info.catalogUnavailable - ? { total: info.totalWorktrees, active: info.activeCount } - : undefined - } - worktreeCountsUnavailable={info?.catalogUnavailable === true} + worktreeInfo={worktreeInfo[item.id]} onPress={() => router.push(`/h/${item.id}`)} onLongPress={() => { triggerMediumImpact() @@ -956,7 +907,7 @@ export default function HomeScreen() { onDismiss: () => setActionTarget(null), onReconnect: (hostId) => void forceReconnectHost(hostId), onDisconnect: closeHostClient, - onEdit: (hostId) => navigateToMobileHostEdit(router, hostId), + onEdit: openMobileHostEdit, onRemove: setConfirmRemove })} onClose={() => setActionTarget(null)} diff --git a/mobile/package.json b/mobile/package.json index 1041b422a34..44feca5f4c5 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -7,7 +7,7 @@ "start": "node scripts/start-expo.mjs", "android": "expo run:android", "ios": "expo run:ios", - "postinstall": "node scripts/build-terminal-webview-engine.mjs", + "postinstall": "node scripts/build-terminal-webview-engine.mjs && node scripts/build-mermaid-webview-engine.mjs", "test": "vitest run", "typecheck": "tsc --noEmit", "lint": "oxlint", @@ -48,6 +48,7 @@ "expo-status-bar": "^55.0.6", "lowlight": "^3.3.0", "lucide-react-native": "^1.14.0", + "mermaid": "11.16.0", "react": "^19.2.6", "react-dom": "19.2.6", "react-native": "^0.83.9", diff --git a/mobile/pnpm-lock.yaml b/mobile/pnpm-lock.yaml index 9788413f925..5530acb4da1 100644 --- a/mobile/pnpm-lock.yaml +++ b/mobile/pnpm-lock.yaml @@ -101,6 +101,9 @@ importers: lucide-react-native: specifier: ^1.14.0 version: 1.14.0(react-native-svg@15.15.4(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + mermaid: + specifier: 11.16.0 + version: 11.16.0 react: specifier: ^19.2.6 version: 19.2.6 @@ -195,6 +198,9 @@ importers: packages: + '@antfu/install-pkg@1.1.0': + resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==} + '@babel/cli@7.28.6': resolution: {integrity: sha512-6EUNcuBbNkj08Oj4gAZ+BUU8yLCgKzgVX4gaTh09Ya2C8ICM4P+G30g4m3akRxSYAp3A/gnWchrNst7px4/nUQ==} engines: {node: '>=6.9.0'} @@ -1178,6 +1184,12 @@ packages: '@bcoe/v8-coverage@0.2.3': resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + '@braintree/sanitize-url@7.1.2': + resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==} + + '@chevrotain/types@11.1.2': + resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==} + '@egjs/hammerjs@2.0.17': resolution: {integrity: sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A==} engines: {node: '>=0.8.0'} @@ -1768,6 +1780,12 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} + '@iconify/types@2.0.0': + resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} + + '@iconify/utils@3.1.4': + resolution: {integrity: sha512-b1S7B1k9ohZ+iNTi2ATxbRYG9fTrJmUT0rc46bvVnNxqNRGW7dyo/vRREwyniI5IRN2RSJHDcm+s3BjWrSAjHw==} + '@isaacs/ttlcache@1.4.1': resolution: {integrity: sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==} engines: {node: '>=12'} @@ -1881,6 +1899,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@mermaid-js/parser@1.2.0': + resolution: {integrity: sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==} + '@napi-rs/wasm-runtime@1.1.6': resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} peerDependencies: @@ -2680,6 +2701,99 @@ packages: '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + '@types/d3-array@3.2.2': + resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} + + '@types/d3-axis@3.0.6': + resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==} + + '@types/d3-brush@3.0.6': + resolution: {integrity: sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==} + + '@types/d3-chord@3.0.6': + resolution: {integrity: sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==} + + '@types/d3-color@3.1.3': + resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} + + '@types/d3-contour@3.0.6': + resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==} + + '@types/d3-delaunay@6.0.4': + resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==} + + '@types/d3-dispatch@3.0.7': + resolution: {integrity: sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==} + + '@types/d3-drag@3.0.7': + resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==} + + '@types/d3-dsv@3.0.7': + resolution: {integrity: sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==} + + '@types/d3-ease@3.0.2': + resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} + + '@types/d3-fetch@3.0.7': + resolution: {integrity: sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==} + + '@types/d3-force@3.0.10': + resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==} + + '@types/d3-format@3.0.4': + resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==} + + '@types/d3-geo@3.1.1': + resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==} + + '@types/d3-hierarchy@3.1.7': + resolution: {integrity: sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==} + + '@types/d3-interpolate@3.0.4': + resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} + + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-polygon@3.0.2': + resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==} + + '@types/d3-quadtree@3.0.6': + resolution: {integrity: sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==} + + '@types/d3-random@3.0.4': + resolution: {integrity: sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==} + + '@types/d3-scale-chromatic@3.1.0': + resolution: {integrity: sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==} + + '@types/d3-scale@4.0.9': + resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} + + '@types/d3-selection@3.0.11': + resolution: {integrity: sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==} + + '@types/d3-shape@3.1.8': + resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==} + + '@types/d3-time-format@4.0.3': + resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==} + + '@types/d3-time@3.0.4': + resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} + + '@types/d3-timer@3.0.2': + resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} + + '@types/d3-transition@3.0.9': + resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==} + + '@types/d3-zoom@3.0.8': + resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==} + + '@types/d3@7.4.3': + resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==} + '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -2689,6 +2803,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + '@types/graceful-fs@4.1.9': resolution: {integrity: sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==} @@ -2741,6 +2858,9 @@ packages: '@types/tough-cookie@4.0.5': resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} @@ -2818,6 +2938,9 @@ packages: '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} + '@upsetjs/venn.js@2.0.0': + resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} + '@vitest/expect@4.1.9': resolution: {integrity: sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==} @@ -3332,6 +3455,10 @@ packages: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} + commander@8.3.0: + resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} + engines: {node: '>= 12'} + compressible@2.0.18: resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} engines: {node: '>= 0.6'} @@ -3353,6 +3480,12 @@ packages: core-js-compat@3.49.0: resolution: {integrity: sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==} + cose-base@1.0.3: + resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==} + + cose-base@2.2.0: + resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==} + create-jest@29.7.0: resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -3392,6 +3525,162 @@ packages: csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + cytoscape-cose-bilkent@4.1.0: + resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape-fcose@2.2.0: + resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape@3.34.0: + resolution: {integrity: sha512-62rNSrioXw93uliKFBwjukeQyeWwH2PqDrTac31r2P6464u3AUvTk0xS4LVvT251g7IgkFunrI48ZEZGjywSOg==} + engines: {node: '>=0.10'} + + d3-array@2.12.1: + resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-axis@3.0.0: + resolution: {integrity: sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==} + engines: {node: '>=12'} + + d3-brush@3.0.0: + resolution: {integrity: sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==} + engines: {node: '>=12'} + + d3-chord@3.0.1: + resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==} + engines: {node: '>=12'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-contour@4.0.2: + resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==} + engines: {node: '>=12'} + + d3-delaunay@6.0.4: + resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==} + engines: {node: '>=12'} + + d3-dispatch@3.0.1: + resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==} + engines: {node: '>=12'} + + d3-drag@3.0.0: + resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==} + engines: {node: '>=12'} + + d3-dsv@3.0.1: + resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==} + engines: {node: '>=12'} + hasBin: true + + d3-ease@3.0.1: + resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==} + engines: {node: '>=12'} + + d3-fetch@3.0.1: + resolution: {integrity: sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==} + engines: {node: '>=12'} + + d3-force@3.0.0: + resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==} + engines: {node: '>=12'} + + d3-format@3.1.2: + resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==} + engines: {node: '>=12'} + + d3-geo@3.1.1: + resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==} + engines: {node: '>=12'} + + d3-hierarchy@3.1.2: + resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-path@1.0.9: + resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} + + d3-path@3.1.0: + resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + engines: {node: '>=12'} + + d3-polygon@3.0.1: + resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==} + engines: {node: '>=12'} + + d3-quadtree@3.0.1: + resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==} + engines: {node: '>=12'} + + d3-random@3.0.1: + resolution: {integrity: sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==} + engines: {node: '>=12'} + + d3-sankey@0.12.3: + resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==} + + d3-scale-chromatic@3.1.0: + resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-selection@3.0.0: + resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==} + engines: {node: '>=12'} + + d3-shape@1.3.7: + resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + + d3-time@3.1.0: + resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} + engines: {node: '>=12'} + + d3-timer@3.0.1: + resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==} + engines: {node: '>=12'} + + d3-transition@3.0.1: + resolution: {integrity: sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==} + engines: {node: '>=12'} + peerDependencies: + d3-selection: 2 - 3 + + d3-zoom@3.0.0: + resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==} + engines: {node: '>=12'} + + d3@7.9.0: + resolution: {integrity: sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==} + engines: {node: '>=12'} + + dagre-d3-es@7.0.14: + resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==} + data-urls@3.0.2: resolution: {integrity: sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==} engines: {node: '>=12'} @@ -3408,6 +3697,9 @@ packages: resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} engines: {node: '>= 0.4'} + dayjs@1.11.21: + resolution: {integrity: sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==} + debug@2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} peerDependencies: @@ -3470,6 +3762,9 @@ packages: resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} engines: {node: '>= 0.4'} + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -3526,6 +3821,9 @@ packages: resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} engines: {node: '>= 4'} + dompurify@3.4.12: + resolution: {integrity: sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==} + domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} @@ -3611,6 +3909,9 @@ packages: resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==} engines: {node: '>= 0.4'} + es-toolkit@1.50.0: + resolution: {integrity: sha512-OyZKhUVvEep9ITEiwHn8GKnMRQIVqoSIX7WnRbkWgJkllCujilqP2rD0u979tkl8wqyc8ICwlc1UBVv/Sl1G6w==} + esbuild@0.25.4: resolution: {integrity: sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q==} engines: {node: '>=18'} @@ -4304,6 +4605,9 @@ packages: resolution: {integrity: sha512-XSt8tMzbW9ymE7687xztkO1ckR7qJNQ3LywY9vlYGhGi3zXrGBHuUo2Cl1ztZaICW+1eAGdkLbj6iwVqDT33kg==} engines: {node: '>=20.0.0'} + hachure-fill@0.5.2: + resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} + has-bigints@1.1.0: resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} engines: {node: '>= 0.4'} @@ -4436,6 +4740,9 @@ packages: engines: {node: '>=8'} hasBin: true + import-meta-resolve@4.2.0: + resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} + imurmurhash@0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} @@ -4458,6 +4765,13 @@ packages: resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} engines: {node: '>= 0.4'} + internmap@1.0.1: + resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + invariant@2.2.4: resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==} @@ -4855,9 +5169,16 @@ packages: resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==} engines: {node: '>=4.0'} + katex@0.16.47: + resolution: {integrity: sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==} + hasBin: true + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + khroma@2.1.0: + resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==} + kleur@3.0.3: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} engines: {node: '>=6'} @@ -4866,6 +5187,12 @@ packages: resolution: {integrity: sha512-ONPnazC96VKDntab9j9JKwIWhZ4ZUceB4A9Epu4Ssg0hYFmtHZSeQ+n15nIwTFmcBUKtExOer8WTJ4GF9MO64A==} hasBin: true + layout-base@1.0.2: + resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==} + + layout-base@2.0.1: + resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==} + leven@3.1.0: resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} engines: {node: '>=6'} @@ -4958,6 +5285,9 @@ packages: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} + lodash-es@4.18.1: + resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} + lodash.debounce@4.0.8: resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} @@ -5018,6 +5348,11 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + marked@16.4.2: + resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==} + engines: {node: '>= 20'} + hasBin: true + marky@1.3.0: resolution: {integrity: sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==} @@ -5041,6 +5376,9 @@ packages: merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + mermaid@11.16.0: + resolution: {integrity: sha512-Zvm3kbstgdpvIJPPItlL7fppIZ3kibvc1oZIGxdvk9t6UFz6flv+Jw7FtRGKwfcI8OckmH04LqG6LlS6X4B1pA==} + metro-babel-transformer@0.83.7: resolution: {integrity: sha512-sBqBkt6kNut/88bv+Ucvm4yqdPetbvAEsHzi3MAgJEifOSYYzX5Z5Kgw3TFOrwf/mHJTOBG2ONlaMHoyfP15TA==} engines: {node: '>=20.19.4'} @@ -5418,6 +5756,9 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} + package-manager-detector@1.8.0: + resolution: {integrity: sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -5437,6 +5778,9 @@ packages: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} + path-data-parser@0.1.0: + resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -5490,6 +5834,12 @@ packages: resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==} engines: {node: '>=4.0.0'} + points-on-curve@0.2.0: + resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} + + points-on-path@0.2.1: + resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -5798,11 +6148,20 @@ packages: deprecated: Rimraf versions prior to v4 are no longer supported hasBin: true + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + rolldown@1.1.3: resolution: {integrity: sha512-1F1eEtUBtFvcGm1HQ9TiUIUHPQG7mSAODrhIzjxoUEFuo8OcbrGLiVLkevNgj84TE4lnHvnumwFjhJO5Eu135g==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + roughjs@4.6.6: + resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} + + rw@1.3.3: + resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + safe-array-concat@1.1.4: resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} engines: {node: '>=0.4'} @@ -6103,6 +6462,9 @@ packages: styleq@0.1.3: resolution: {integrity: sha512-3ZUifmCDCQanjeej1f6kyl/BeP/Vae5EYkQ9iJfUm/QwZvlgnZzyflqAsAWYURdtea8Vkvswu2GrC57h3qffcA==} + stylis@4.4.0: + resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==} + supports-color@5.5.0: resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} engines: {node: '>=4'} @@ -6214,6 +6576,10 @@ packages: peerDependencies: typescript: '>=4.0.0' + ts-dedent@2.3.0: + resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} + engines: {node: '>=6.10'} + ts-jest@29.0.5: resolution: {integrity: sha512-PL3UciSgIpQ7f6XjVOmbi96vmDHUqAyqDr8YxzopDqX3kfgYtX1cuNeBjP+L9sFXi6nzsGGA6R3fP3DDDJyrxA==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -6694,6 +7060,11 @@ packages: snapshots: + '@antfu/install-pkg@1.1.0': + dependencies: + package-manager-detector: 1.8.0 + tinyexec: 1.1.2 + '@babel/cli@7.28.6(@babel/core@7.29.7)': dependencies: '@babel/core': 7.29.7 @@ -7935,6 +8306,10 @@ snapshots: '@bcoe/v8-coverage@0.2.3': {} + '@braintree/sanitize-url@7.1.2': {} + + '@chevrotain/types@11.1.2': {} + '@egjs/hammerjs@2.0.17': dependencies: '@types/hammerjs': 2.0.46 @@ -8637,6 +9012,14 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@iconify/types@2.0.0': {} + + '@iconify/utils@3.1.4': + dependencies: + '@antfu/install-pkg': 1.1.0 + '@iconify/types': 2.0.0 + import-meta-resolve: 4.2.0 + '@isaacs/ttlcache@1.4.1': {} '@istanbuljs/load-nyc-config@1.1.0': @@ -8847,6 +9230,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@mermaid-js/parser@1.2.0': + dependencies: + '@chevrotain/types': 11.1.2 + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: '@emnapi/core': 1.11.1 @@ -9603,12 +9990,131 @@ snapshots: '@types/deep-eql': 4.0.2 assertion-error: 2.0.1 + '@types/d3-array@3.2.2': {} + + '@types/d3-axis@3.0.6': + dependencies: + '@types/d3-selection': 3.0.11 + + '@types/d3-brush@3.0.6': + dependencies: + '@types/d3-selection': 3.0.11 + + '@types/d3-chord@3.0.6': {} + + '@types/d3-color@3.1.3': {} + + '@types/d3-contour@3.0.6': + dependencies: + '@types/d3-array': 3.2.2 + '@types/geojson': 7946.0.16 + + '@types/d3-delaunay@6.0.4': {} + + '@types/d3-dispatch@3.0.7': {} + + '@types/d3-drag@3.0.7': + dependencies: + '@types/d3-selection': 3.0.11 + + '@types/d3-dsv@3.0.7': {} + + '@types/d3-ease@3.0.2': {} + + '@types/d3-fetch@3.0.7': + dependencies: + '@types/d3-dsv': 3.0.7 + + '@types/d3-force@3.0.10': {} + + '@types/d3-format@3.0.4': {} + + '@types/d3-geo@3.1.1': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/d3-hierarchy@3.1.7': {} + + '@types/d3-interpolate@3.0.4': + dependencies: + '@types/d3-color': 3.1.3 + + '@types/d3-path@3.1.1': {} + + '@types/d3-polygon@3.0.2': {} + + '@types/d3-quadtree@3.0.6': {} + + '@types/d3-random@3.0.4': {} + + '@types/d3-scale-chromatic@3.1.0': {} + + '@types/d3-scale@4.0.9': + dependencies: + '@types/d3-time': 3.0.4 + + '@types/d3-selection@3.0.11': {} + + '@types/d3-shape@3.1.8': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time-format@4.0.3': {} + + '@types/d3-time@3.0.4': {} + + '@types/d3-timer@3.0.2': {} + + '@types/d3-transition@3.0.9': + dependencies: + '@types/d3-selection': 3.0.11 + + '@types/d3-zoom@3.0.8': + dependencies: + '@types/d3-interpolate': 3.0.4 + '@types/d3-selection': 3.0.11 + + '@types/d3@7.4.3': + dependencies: + '@types/d3-array': 3.2.2 + '@types/d3-axis': 3.0.6 + '@types/d3-brush': 3.0.6 + '@types/d3-chord': 3.0.6 + '@types/d3-color': 3.1.3 + '@types/d3-contour': 3.0.6 + '@types/d3-delaunay': 6.0.4 + '@types/d3-dispatch': 3.0.7 + '@types/d3-drag': 3.0.7 + '@types/d3-dsv': 3.0.7 + '@types/d3-ease': 3.0.2 + '@types/d3-fetch': 3.0.7 + '@types/d3-force': 3.0.10 + '@types/d3-format': 3.0.4 + '@types/d3-geo': 3.1.1 + '@types/d3-hierarchy': 3.1.7 + '@types/d3-interpolate': 3.0.4 + '@types/d3-path': 3.1.1 + '@types/d3-polygon': 3.0.2 + '@types/d3-quadtree': 3.0.6 + '@types/d3-random': 3.0.4 + '@types/d3-scale': 4.0.9 + '@types/d3-scale-chromatic': 3.1.0 + '@types/d3-selection': 3.0.11 + '@types/d3-shape': 3.1.8 + '@types/d3-time': 3.0.4 + '@types/d3-time-format': 4.0.3 + '@types/d3-timer': 3.0.2 + '@types/d3-transition': 3.0.9 + '@types/d3-zoom': 3.0.8 + '@types/deep-eql@4.0.2': {} '@types/emscripten@1.41.5': {} '@types/estree@1.0.9': {} + '@types/geojson@7946.0.16': {} + '@types/graceful-fs@4.1.9': dependencies: '@types/node': 26.1.1 @@ -9677,6 +10183,9 @@ snapshots: '@types/tough-cookie@4.0.5': {} + '@types/trusted-types@2.0.7': + optional: true + '@types/unist@3.0.3': {} '@types/whatwg-mimetype@3.0.2': {} @@ -9784,6 +10293,11 @@ snapshots: '@ungap/structured-clone@1.3.1': {} + '@upsetjs/venn.js@2.0.0': + optionalDependencies: + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + '@vitest/expect@4.1.9': dependencies: '@standard-schema/spec': 1.1.0 @@ -10407,6 +10921,8 @@ snapshots: commander@7.2.0: {} + commander@8.3.0: {} + compressible@2.0.18: dependencies: mime-db: 1.54.0 @@ -10440,6 +10956,14 @@ snapshots: dependencies: browserslist: 4.28.2 + cose-base@1.0.3: + dependencies: + layout-base: 1.0.2 + + cose-base@2.2.0: + dependencies: + layout-base: 2.0.1 + create-jest@29.7.0(@types/node@26.1.1): dependencies: '@jest/types': 29.6.3 @@ -10496,6 +11020,190 @@ snapshots: csstype@3.2.3: {} + cytoscape-cose-bilkent@4.1.0(cytoscape@3.34.0): + dependencies: + cose-base: 1.0.3 + cytoscape: 3.34.0 + + cytoscape-fcose@2.2.0(cytoscape@3.34.0): + dependencies: + cose-base: 2.2.0 + cytoscape: 3.34.0 + + cytoscape@3.34.0: {} + + d3-array@2.12.1: + dependencies: + internmap: 1.0.1 + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-axis@3.0.0: {} + + d3-brush@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3-chord@3.0.1: + dependencies: + d3-path: 3.1.0 + + d3-color@3.1.0: {} + + d3-contour@4.0.2: + dependencies: + d3-array: 3.2.4 + + d3-delaunay@6.0.4: + dependencies: + delaunator: 5.1.0 + + d3-dispatch@3.0.1: {} + + d3-drag@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-selection: 3.0.0 + + d3-dsv@3.0.1: + dependencies: + commander: 7.2.0 + iconv-lite: 0.6.3 + rw: 1.3.3 + + d3-ease@3.0.1: {} + + d3-fetch@3.0.1: + dependencies: + d3-dsv: 3.0.1 + + d3-force@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-quadtree: 3.0.1 + d3-timer: 3.0.1 + + d3-format@3.1.2: {} + + d3-geo@3.1.1: + dependencies: + d3-array: 3.2.4 + + d3-hierarchy@3.1.2: {} + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-path@1.0.9: {} + + d3-path@3.1.0: {} + + d3-polygon@3.0.1: {} + + d3-quadtree@3.0.1: {} + + d3-random@3.0.1: {} + + d3-sankey@0.12.3: + dependencies: + d3-array: 2.12.1 + d3-shape: 1.3.7 + + d3-scale-chromatic@3.1.0: + dependencies: + d3-color: 3.1.0 + d3-interpolate: 3.0.1 + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.2 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + + d3-selection@3.0.0: {} + + d3-shape@1.3.7: + dependencies: + d3-path: 1.0.9 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.0 + + d3-time-format@4.1.0: + dependencies: + d3-time: 3.1.0 + + d3-time@3.1.0: + dependencies: + d3-array: 3.2.4 + + d3-timer@3.0.1: {} + + d3-transition@3.0.1(d3-selection@3.0.0): + dependencies: + d3-color: 3.1.0 + d3-dispatch: 3.0.1 + d3-ease: 3.0.1 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-timer: 3.0.1 + + d3-zoom@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3@7.9.0: + dependencies: + d3-array: 3.2.4 + d3-axis: 3.0.0 + d3-brush: 3.0.0 + d3-chord: 3.0.1 + d3-color: 3.1.0 + d3-contour: 4.0.2 + d3-delaunay: 6.0.4 + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-dsv: 3.0.1 + d3-ease: 3.0.1 + d3-fetch: 3.0.1 + d3-force: 3.0.0 + d3-format: 3.1.2 + d3-geo: 3.1.1 + d3-hierarchy: 3.1.2 + d3-interpolate: 3.0.1 + d3-path: 3.1.0 + d3-polygon: 3.0.1 + d3-quadtree: 3.0.1 + d3-random: 3.0.1 + d3-scale: 4.0.2 + d3-scale-chromatic: 3.1.0 + d3-selection: 3.0.0 + d3-shape: 3.2.0 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + d3-timer: 3.0.1 + d3-transition: 3.0.1(d3-selection@3.0.0) + d3-zoom: 3.0.0 + + dagre-d3-es@7.0.14: + dependencies: + d3: 7.9.0 + lodash-es: 4.18.1 + data-urls@3.0.2: dependencies: abab: 2.0.6 @@ -10520,6 +11228,8 @@ snapshots: es-errors: 1.3.0 is-data-view: 1.0.2 + dayjs@1.11.21: {} + debug@2.6.9: dependencies: ms: 2.0.0 @@ -10560,6 +11270,10 @@ snapshots: has-property-descriptors: 1.0.2 object-keys: 1.1.1 + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + delayed-stream@1.0.0: {} depd@2.0.0: {} @@ -10602,6 +11316,10 @@ snapshots: dependencies: domelementtype: 2.3.0 + dompurify@3.4.12: + optionalDependencies: + '@types/trusted-types': 2.0.7 + domutils@3.2.2: dependencies: dom-serializer: 2.0.0 @@ -10748,6 +11466,8 @@ snapshots: is-date-object: 1.1.0 is-symbol: 1.1.1 + es-toolkit@1.50.0: {} + esbuild@0.25.4: optionalDependencies: '@esbuild/aix-ppc64': 0.25.4 @@ -11653,6 +12373,8 @@ snapshots: - bufferutil - utf-8-validate + hachure-fill@0.5.2: {} + has-bigints@1.1.0: {} has-flag@3.0.0: {} @@ -11781,6 +12503,8 @@ snapshots: pkg-dir: 4.2.0 resolve-cwd: 3.0.0 + import-meta-resolve@4.2.0: {} + imurmurhash@0.1.4: {} indent-string@4.0.0: {} @@ -11802,6 +12526,10 @@ snapshots: hasown: 2.0.3 side-channel: 1.1.0 + internmap@1.0.1: {} + + internmap@2.0.3: {} + invariant@2.2.4: dependencies: loose-envify: 1.4.0 @@ -12446,14 +13174,24 @@ snapshots: object.assign: 4.1.7 object.values: 1.2.1 + katex@0.16.47: + dependencies: + commander: 8.3.0 + keyv@4.5.4: dependencies: json-buffer: 3.0.1 + khroma@2.1.0: {} + kleur@3.0.3: {} lan-network@0.2.1: {} + layout-base@1.0.2: {} + + layout-base@2.0.1: {} + leven@3.1.0: {} levn@0.4.1: @@ -12527,6 +13265,8 @@ snapshots: dependencies: p-locate: 5.0.0 + lodash-es@4.18.1: {} + lodash.debounce@4.0.8: {} lodash.memoize@4.1.2: {} @@ -12584,6 +13324,8 @@ snapshots: dependencies: tmpl: 1.0.5 + marked@16.4.2: {} + marky@1.3.0: {} math-intrinsics@1.1.0: {} @@ -12600,6 +13342,30 @@ snapshots: merge-stream@2.0.0: {} + mermaid@11.16.0: + dependencies: + '@braintree/sanitize-url': 7.1.2 + '@iconify/utils': 3.1.4 + '@mermaid-js/parser': 1.2.0 + '@types/d3': 7.4.3 + '@upsetjs/venn.js': 2.0.0 + cytoscape: 3.34.0 + cytoscape-cose-bilkent: 4.1.0(cytoscape@3.34.0) + cytoscape-fcose: 2.2.0(cytoscape@3.34.0) + d3: 7.9.0 + d3-sankey: 0.12.3 + dagre-d3-es: 7.0.14 + dayjs: 1.11.21 + dompurify: 3.4.12 + es-toolkit: 1.50.0 + katex: 0.16.47 + khroma: 2.1.0 + marked: 16.4.2 + roughjs: 4.6.6 + stylis: 4.4.0 + ts-dedent: 2.3.0 + uuid: 11.1.1 + metro-babel-transformer@0.83.7: dependencies: '@babel/core': 7.29.7 @@ -13214,6 +13980,8 @@ snapshots: p-try@2.2.0: {} + package-manager-detector@1.8.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -13235,6 +14003,8 @@ snapshots: parseurl@1.3.3: {} + path-data-parser@0.1.0: {} + path-exists@4.0.0: {} path-is-absolute@1.0.1: {} @@ -13272,6 +14042,13 @@ snapshots: pngjs@3.4.0: {} + points-on-curve@0.2.0: {} + + points-on-path@0.2.1: + dependencies: + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + possible-typed-array-names@1.1.0: {} postcss-value-parser@4.2.0: {} @@ -13646,6 +14423,8 @@ snapshots: dependencies: glob: 7.2.3 + robust-predicates@3.0.3: {} + rolldown@1.1.3: dependencies: '@oxc-project/types': 0.137.0 @@ -13667,6 +14446,15 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.1.3 '@rolldown/binding-win32-x64-msvc': 1.1.3 + roughjs@4.6.6: + dependencies: + hachure-fill: 0.5.2 + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + points-on-path: 0.2.1 + + rw@1.3.3: {} + safe-array-concat@1.1.4: dependencies: call-bind: 1.0.9 @@ -13983,6 +14771,8 @@ snapshots: styleq@0.1.3: {} + stylis@4.4.0: {} + supports-color@5.5.0: dependencies: has-flag: 3.0.0 @@ -14084,6 +14874,8 @@ snapshots: picomatch: 4.0.4 typescript: 5.9.3 + ts-dedent@2.3.0: {} + ts-jest@29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.1.1))(typescript@5.9.3): dependencies: bs-logger: 0.2.6 diff --git a/mobile/scripts/build-mermaid-webview-engine.mjs b/mobile/scripts/build-mermaid-webview-engine.mjs new file mode 100644 index 00000000000..bf53ae2f4b8 --- /dev/null +++ b/mobile/scripts/build-mermaid-webview-engine.mjs @@ -0,0 +1,42 @@ +import { readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { createRequire } from 'node:module' + +const require = createRequire(import.meta.url) +const scriptDir = import.meta.dirname +const mobileRoot = path.resolve(scriptDir, '..') +const outputPath = path.join( + mobileRoot, + 'src', + 'components', + 'pr-sidebar', + 'mermaid-webview-engine.generated.ts' +) + +// Why: unlike the terminal engine (esbuilt from source for old-WebView shims), +// mermaid's prebuilt UMD bundle is embedded verbatim — it is the exact artifact +// the diagram WebView previously fetched from a CDN, now pinned and +// integrity-checked through the lockfile and available offline. +async function main() { + const packageJsonPath = require.resolve('mermaid/package.json') + const [packageJson, bundleJs] = await Promise.all([ + readFile(packageJsonPath, 'utf8').then(JSON.parse), + readFile(path.join(path.dirname(packageJsonPath), 'dist', 'mermaid.min.js'), 'utf8') + ]) + + // A literal inside the bundle would close the inline script tag it + // is embedded in; \/ is identical to / in JS strings, regexes, and comments. + const inlineSafeJs = bundleJs.replace(/<\/script/gi, '<\\/script') + + const source = [ + '// Generated by scripts/build-mermaid-webview-engine.mjs.', + `// Package: mermaid@${packageJson.version} (dist/mermaid.min.js, embedded verbatim).`, + '// Do not edit by hand; regenerate via pnpm postinstall.', + `export const MERMAID_ENGINE_JS = ${JSON.stringify(inlineSafeJs)}`, + '' + ].join('\n') + + await writeFile(outputPath, source) +} + +await main() diff --git a/mobile/src/cache/home-snapshot-cache.ts b/mobile/src/cache/home-snapshot-cache.ts index a591bb01d70..bbda033735e 100644 --- a/mobile/src/cache/home-snapshot-cache.ts +++ b/mobile/src/cache/home-snapshot-cache.ts @@ -5,25 +5,12 @@ // WebSocket reconnects and the first responses come back. import AsyncStorage from '@react-native-async-storage/async-storage' import type { AccountsSnapshot } from '../components/AccountUsage' +// Why: the canonical shape, so persisted counts keep carrying countsProvenAt — the home card +// needs it to know whether a rehydrated count is minutes or days old. +import type { HostWorktreeInfo } from '../worktree/home-worktree-info' const STORAGE_KEY = 'orca:home-snapshot:v1' -type WorktreeSummary = { - worktreeId: string - repo: string - branch: string - displayName: string - liveTerminalCount: number - status?: 'working' | 'active' | 'permission' | 'done' | 'inactive' -} - -type HostWorktreeInfo = { - hostId: string - totalWorktrees: number - activeCount: number - lastActiveWorktree: WorktreeSummary | null -} - export type HomeSnapshot = { worktreeInfo: Record accountsByHost: Record diff --git a/mobile/src/components/MobileHostCard.test.tsx b/mobile/src/components/MobileHostCard.test.tsx new file mode 100644 index 00000000000..a1889793982 --- /dev/null +++ b/mobile/src/components/MobileHostCard.test.tsx @@ -0,0 +1,93 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ConnectionVerdict } from '../transport/connection-health' +import type { HostProfile } from '../transport/types' +import { + markHomeWorktreeCatalogUnavailable, + type HostWorktreeInfo +} from '../worktree/home-worktree-info' +import { MobileHostCard } from './MobileHostCard' + +vi.mock('react-native', () => ({ + Pressable: 'Pressable', + StyleSheet: { create: (styles: T) => styles }, + Text: 'Text', + View: 'View' +})) +vi.mock('lucide-react-native', () => ({ ChevronRight: 'ChevronRight', Monitor: 'Monitor' })) +vi.mock('./StatusDot', () => ({ StatusDot: 'StatusDot' })) + +const host: HostProfile = { + id: 'host-1', + name: 'Studio', + endpoint: 'ws://studio.local:8765', + deviceToken: 'token', + publicKeyB64: 'key', + lastConnected: 0 +} +const verdict: ConnectionVerdict = { kind: 'normal', label: 'Connected' } +const loaded: HostWorktreeInfo = { + hostId: 'host-1', + totalWorktrees: 12, + activeCount: 2, + lastActiveWorktree: null, + countsProvenAt: Date.now() +} + +describe('MobileHostCard', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + async function renderCard(worktreeInfo: HostWorktreeInfo | undefined): Promise { + await act(async () => { + renderer = create( + createElement(MobileHostCard, { + host, + state: 'connected', + verdict, + path: 'lan', + worktreeInfo, + onPress: () => {}, + onLongPress: () => {} + }) + ) + }) + return renderer!.root + .findAllByType('Text') + .flatMap((node) => node.children.filter((child) => typeof child === 'string')) + } + + it('renders the counts the host proved', async () => { + expect(await renderCard(loaded)).toContain('12 worktrees · 2 active') + }) + + it('keeps rendering the last proven counts after a failed refresh', async () => { + // The regression this card shipped once: the caller dropped the counts the + // failure path deliberately preserved. + expect(await renderCard(markHomeWorktreeCatalogUnavailable(loaded, 'host-1'))).toContain( + 'Last known: 12 worktrees · 2 active' + ) + }) + + it('never asserts a count for a catalog that failed with nothing proven', async () => { + expect(await renderCard(markHomeWorktreeCatalogUnavailable(undefined, 'host-1'))).toContain( + 'Worktree list unavailable' + ) + }) + + it('shows no worktree line before the first read lands', async () => { + const lines = await renderCard(undefined) + + expect(lines).not.toContain('0 worktrees') + expect(lines).not.toContain('Worktree list unavailable') + }) +}) diff --git a/mobile/src/components/MobileHostCard.tsx b/mobile/src/components/MobileHostCard.tsx index 4e466922f4a..79a58bf760e 100644 --- a/mobile/src/components/MobileHostCard.tsx +++ b/mobile/src/components/MobileHostCard.tsx @@ -6,6 +6,7 @@ import { mobileConnectionPathLabel } from '../transport/mobile-connection-path-l import type { MobileConnectionPath } from '../transport/stable-logical-rpc-client' import type { ConnectionState, HostProfile } from '../transport/types' import { colors, radii, spacing } from '../theme/mobile-theme' +import { homeHostWorktreeSummary, type HostWorktreeInfo } from '../worktree/home-worktree-info' import { StatusDot } from './StatusDot' export function MobileHostCard(props: { @@ -13,20 +14,15 @@ export function MobileHostCard(props: { state: ConnectionState verdict: ConnectionVerdict path: MobileConnectionPath - worktreeCounts?: { total: number; active: number } - // Why (STA-3123): the host is connected but its worktree catalog request failed, - // so the card must say "unavailable" instead of asserting a count of zero. - worktreeCountsUnavailable?: boolean + // Why: the card owns the fresh/stale/unavailable wording so no caller can re-gate the counts + // away (STA-3123 shipped that bug once already). + worktreeInfo?: HostWorktreeInfo onPress: () => void onLongPress: () => void }) { const connected = props.state === 'connected' const isError = ['warning', 'unreachable', 'auth-failed'].includes(props.verdict.kind) - const worktreeSummary = props.worktreeCounts - ? `${props.worktreeCounts.total} worktree${props.worktreeCounts.total === 1 ? '' : 's'}${props.worktreeCounts.active > 0 ? ` · ${props.worktreeCounts.active} active` : ''}` - : props.worktreeCountsUnavailable - ? 'Worktree list unavailable' - : null + const worktreeSummary = homeHostWorktreeSummary(props.worktreeInfo) return ( [styles.card, pressed && styles.cardPressed]} diff --git a/mobile/src/components/MobileMarkdown.file-links.test.ts b/mobile/src/components/MobileMarkdown.file-links.test.ts new file mode 100644 index 00000000000..a8e381865d8 --- /dev/null +++ b/mobile/src/components/MobileMarkdown.file-links.test.ts @@ -0,0 +1,133 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer, type ReactTestInstance } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { MobileMarkdown } from './MobileMarkdown' + +const openURL = vi.fn(() => Promise.resolve()) + +vi.mock('react-native', () => ({ + Linking: { openURL: (url: string) => openURL(url) }, + Pressable: 'Pressable', + ScrollView: 'ScrollView', + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, + Text: 'Text', + View: 'View' +})) +vi.mock('./pr-sidebar/MermaidDiagram', () => ({ MermaidDiagram: 'MermaidDiagram' })) + +function flattenText(node: ReactTestInstance): string { + return node.children + .map((child) => (typeof child === 'string' ? child : flattenText(child))) + .join('') +} + +function pressables(renderer: ReactTestRenderer): ReactTestInstance[] { + return renderer.root.findAll( + (node) => node.type === ('Text' as never) && typeof node.props.onPress === 'function' + ) +} + +function pressByText(renderer: ReactTestRenderer, text: string): void { + const target = pressables(renderer).find((node) => flattenText(node) === text) + expect(target, `no pressable text ${JSON.stringify(text)}`).toBeDefined() + target!.props.onPress() +} + +describe('MobileMarkdown file links', () => { + let renderer: ReactTestRenderer | null = null + const onOpenFile = vi.fn() + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + onOpenFile.mockClear() + openURL.mockClear() + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + function render(content: string): ReactTestRenderer { + act(() => { + renderer = create(createElement(MobileMarkdown, { content, onOpenFile })) + }) + return renderer! + } + + it('opens a tapped POSIX absolute path in prose', () => { + pressByText(render('Edit /Users/me/wt/src/app.tsx now'), '/Users/me/wt/src/app.tsx') + expect(onOpenFile).toHaveBeenCalledWith('/Users/me/wt/src/app.tsx') + }) + + it('opens a tapped path:line citation in prose', () => { + pressByText(render('see src/foo.ts:42 for the fix'), 'src/foo.ts:42') + expect(onOpenFile).toHaveBeenCalledWith('src/foo.ts:42') + }) + + it('routes a relative markdown href to the file opener with its #L line', () => { + pressByText(render('read [the plan](docs/plan.md#L7) first'), 'the plan') + expect(onOpenFile).toHaveBeenCalledWith('docs/plan.md:7') + expect(openURL).not.toHaveBeenCalled() + }) + + it('routes a file: href to the file opener', () => { + pressByText(render('[artifact](file:///tmp/out/result.json)'), 'artifact') + expect(onOpenFile).toHaveBeenCalledWith('/tmp/out/result.json') + }) + + it('keeps web links on the system browser', () => { + pressByText(render('go to [site](https://example.com/docs)'), 'site') + expect(openURL).toHaveBeenCalledWith('https://example.com/docs') + expect(onOpenFile).not.toHaveBeenCalled() + }) + + it('drops unknown-scheme hrefs without opening anything', () => { + pressByText(render('[ide](editor://file/x.ts)'), 'ide') + expect(openURL).not.toHaveBeenCalled() + expect(onOpenFile).not.toHaveBeenCalled() + }) + + it('keeps snake_case paths whole instead of shredding them as emphasis', () => { + const rendered = render('compare src/foo_bar.ts and src/baz_qux.ts now') + pressByText(rendered, 'src/foo_bar.ts') + pressByText(rendered, 'src/baz_qux.ts') + expect(onOpenFile).toHaveBeenNthCalledWith(1, 'src/foo_bar.ts') + expect(onOpenFile).toHaveBeenNthCalledWith(2, 'src/baz_qux.ts') + }) + + it('keeps markdown links between snake_case paths tappable', () => { + pressByText( + render('Updated src/foo_bar.py; see [the PR](https://example.com/x) before src/baz_qux.py'), + 'the PR' + ) + expect(openURL).toHaveBeenCalledWith('https://example.com/x') + }) + + it('opens a dunder path as one link', () => { + pressByText(render('see a/__tests__/x.ts now'), 'a/__tests__/x.ts') + expect(onOpenFile).toHaveBeenCalledExactlyOnceWith('a/__tests__/x.ts') + }) + + it('detects paths inside bold spans', () => { + pressByText(render('changed **src/foo.ts** heavily'), 'src/foo.ts') + expect(onOpenFile).toHaveBeenCalledWith('src/foo.ts') + }) + + it('excludes trailing sentence punctuation from autolinks', () => { + pressByText(render('see https://example.com/a.'), 'https://example.com/a') + expect(openURL).toHaveBeenCalledWith('https://example.com/a') + }) + + it('opens inline-code path:line citations', () => { + pressByText(render('fix `src/foo.ts:42` now'), 'src/foo.ts:42') + expect(onOpenFile).toHaveBeenCalledWith('src/foo.ts:42') + }) + + it('renders paths as plain text without onOpenFile', () => { + act(() => { + renderer = create(createElement(MobileMarkdown, { content: 'Edit src/app/Main.tsx now' })) + }) + expect(pressables(renderer!)).toHaveLength(0) + }) +}) diff --git a/mobile/src/components/MobileMarkdown.test.ts b/mobile/src/components/MobileMarkdown.test.ts index 20a92663a49..5a59e749b20 100644 --- a/mobile/src/components/MobileMarkdown.test.ts +++ b/mobile/src/components/MobileMarkdown.test.ts @@ -1,8 +1,40 @@ import { describe, expect, it } from 'vitest' +import { isMobileMermaidLanguage } from './mobile-mermaid-language' import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html' import { parseMobileMarkdown } from './mobile-markdown-parser' +describe('isMobileMermaidLanguage', () => { + it('matches mermaid case-insensitively after trim', () => { + expect(isMobileMermaidLanguage('mermaid')).toBe(true) + expect(isMobileMermaidLanguage('Mermaid')).toBe(true) + expect(isMobileMermaidLanguage(' MERMAID ')).toBe(true) + }) + + it('rejects non-mermaid languages and missing language', () => { + expect(isMobileMermaidLanguage(undefined)).toBe(false) + expect(isMobileMermaidLanguage('')).toBe(false) + expect(isMobileMermaidLanguage('ts')).toBe(false) + expect(isMobileMermaidLanguage('mermaidx')).toBe(false) + }) +}) + describe('parseMobileMarkdown', () => { + it('parses mermaid fences as code blocks with language mermaid', () => { + expect(parseMobileMarkdown('```mermaid\ngraph TD; A-->B\n```')).toEqual([ + { type: 'code', text: 'graph TD; A-->B', language: 'mermaid', closed: true } + ]) + expect(isMobileMermaidLanguage('mermaid')).toBe(true) + }) + + it('marks an unterminated fence as not closed while it streams', () => { + expect(parseMobileMarkdown('```mermaid\ngraph TD; A-->B')).toEqual([ + { type: 'code', text: 'graph TD; A-->B', language: 'mermaid', closed: false } + ]) + expect(parseMobileMarkdown('```mermaid\ngraph TD; A-->B\n```')[0]).toMatchObject({ + closed: true + }) + }) + it('parses GFM tables into table blocks', () => { expect(parseMobileMarkdown('| Name | State |\n| --- | --- |\n| Orca | Open |')).toEqual([ { diff --git a/mobile/src/components/MobileMarkdown.tsx b/mobile/src/components/MobileMarkdown.tsx index 8e968f604ac..cc88c01e564 100644 --- a/mobile/src/components/MobileMarkdown.tsx +++ b/mobile/src/components/MobileMarkdown.tsx @@ -7,7 +7,14 @@ import { isFilePathCodeSpan, normalizeFilePath } from './markdown-file-path-detection' +import { routeMarkdownHref } from './markdown-href-routing' +import { + isIntrawordUnderscoreToken, + trimAutolinkTrailingPunctuation +} from './markdown-inline-token-rules' +import { isMobileMermaidLanguage } from './mobile-mermaid-language' import { parseMobileMarkdown } from './mobile-markdown-parser' +import { MermaidDiagram } from './pr-sidebar/MermaidDiagram' type Props = { content?: string @@ -15,19 +22,28 @@ type Props = { /** Multiplier for prose font size (paragraphs, lists, quotes). Defaults to 1; * the chat view passes >1 so agent prose reads larger than the compact base. */ textScale?: number - /** When provided, detected file-path tokens render as tappable and invoke this - * with the worktree-relative path. Omitted on screens with no file viewer, where + /** When provided, detected file paths and file-target hrefs render as tappable + * and invoke this with the path text (worktree-relative or absolute, with an + * optional :line(:col) suffix). Omitted on screens with no file viewer, where * paths render as plain text (no behavior change). */ - onOpenFile?: (relativePath: string) => void + onOpenFile?: (pathText: string) => void } const MAX_TABLE_ROWS = 40 const MAX_TABLE_COLUMNS = 8 +/** Prose base size — passed to MermaidDiagram fallback mono text. */ +const MERMAID_BASE = 13 -function openMarkdownUrl(url: string): void { - const trimmed = url.trim() - if (/^(https?:|mailto:)/i.test(trimmed)) { - void Linking.openURL(trimmed).catch(() => {}) +// Web/mail hrefs open the system handler; file-target hrefs (file: URIs and +// scheme-less paths — the entire desktop file-link contract) go to onOpenFile. +function openMarkdownHref(href: string, onOpenFile?: (pathText: string) => void): void { + const route = routeMarkdownHref(href) + if (route.kind === 'web') { + void Linking.openURL(route.url).catch(() => {}) + return + } + if (route.kind === 'file' && onOpenFile) { + onOpenFile(route.pathText) } } @@ -36,7 +52,7 @@ function openMarkdownUrl(url: string): void { function renderTextRun( text: string, keyPrefix: string, - onOpenFile?: (relativePath: string) => void + onOpenFile?: (pathText: string) => void ): ReactNode { if (!onOpenFile) { return text @@ -61,39 +77,54 @@ function renderTextRun( }) } -function renderInline(text: string, onOpenFile?: (relativePath: string) => void): ReactNode[] { +function renderInline(text: string, onOpenFile?: (pathText: string) => void): ReactNode[] { const parts: ReactNode[] = [] const pattern = /(!\[[^\]]*\]\([^)]+\)|`[^`]+`|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\n]+\*|_[^_\n]+_|\[[^\]]+\]\([^)]+\)|https?:\/\/[^\s<]+)/g - let lastIndex = 0 + let pendingStart = 0 let match: RegExpExecArray | null while ((match = pattern.exec(text))) { - if (match.index > lastIndex) { - parts.push(renderTextRun(text.slice(lastIndex, match.index), `t${lastIndex}`, onOpenFile)) - } const token = match[0] + // Intraword `_` runs (snake_case, dunder tails) are literal text per + // CommonMark; leaving them unflushed keeps surrounding file paths whole + // for detection in the eventual text run. + if (token.startsWith('_') && isIntrawordUnderscoreToken(text, match.index, token)) { + // Resume after the opener so real tokens inside the rejected span are still scanned. + pattern.lastIndex = match.index + 1 + continue + } + if (match.index > pendingStart) { + parts.push( + renderTextRun(text.slice(pendingStart, match.index), `t${pendingStart}`, onOpenFile) + ) + } + pendingStart = pattern.lastIndex const key = `${match.index}:${token}` const image = token.match(/^!\[([^\]]*)\]\(([^)]+)\)$/) const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/) if (image) { parts.push( - openMarkdownUrl(image[2]!)}> + openMarkdownHref(image[2]!, onOpenFile)}> {image[1] || 'image'} ) } else if (link) { parts.push( - openMarkdownUrl(link[2]!)}> + openMarkdownHref(link[2]!, onOpenFile)}> {link[1]} ) } else if (/^https?:\/\//i.test(token)) { + const { url, trailing } = trimAutolinkTrailingPunctuation(token) parts.push( - openMarkdownUrl(token)}> - {token} + openMarkdownHref(url, onOpenFile)}> + {url} ) + if (trailing) { + parts.push({trailing}) + } } else if (token.startsWith('`')) { const code = token.slice(1, -1) if (onOpenFile && isFilePathCodeSpan(code)) { @@ -116,27 +147,26 @@ function renderInline(text: string, onOpenFile?: (relativePath: string) => void) } else if (token.startsWith('~~')) { parts.push( - {token.slice(2, -2)} + {renderTextRun(token.slice(2, -2), `${key}i`, onOpenFile)} ) } else if (token.startsWith('**') || token.startsWith('__')) { parts.push( - {token.slice(2, -2)} + {renderTextRun(token.slice(2, -2), `${key}i`, onOpenFile)} ) } else { parts.push( - {token.slice(1, -1)} + {renderTextRun(token.slice(1, -1), `${key}i`, onOpenFile)} ) } - lastIndex = pattern.lastIndex } - if (lastIndex < text.length) { - parts.push(renderTextRun(text.slice(lastIndex), `t${lastIndex}`, onOpenFile)) + if (pendingStart < text.length) { + parts.push(renderTextRun(text.slice(pendingStart), `t${pendingStart}`, onOpenFile)) } return parts } @@ -153,6 +183,7 @@ function MobileMarkdownInner({ content, fallback = '', textScale = 1, onOpenFile if (!text) { return fallback ? {fallback} : null } + const mermaidSourceOccurrences = new Map() return ( @@ -175,6 +206,20 @@ function MobileMarkdownInner({ content, fallback = '', textScale = 1, onOpenFile ) } if (block.type === 'code') { + // Mermaid fences render as diagrams (WebView), not as raw code — same as PR sidebar. + // Unclosed fences are still streaming: mounting the WebView per tick would + // reload its document up to 20x/sec, so they stay raw code until terminated. + if (isMobileMermaidLanguage(block.language) && block.closed) { + const occurrence = mermaidSourceOccurrences.get(block.text) ?? 0 + mermaidSourceOccurrences.set(block.text, occurrence + 1) + return ( + + ) + } return ( {block.language ? {block.language} : null} @@ -187,7 +232,7 @@ function MobileMarkdownInner({ content, fallback = '', textScale = 1, onOpenFile openMarkdownUrl(block.url)} + onPress={() => openMarkdownHref(block.url, onOpenFile)} > {block.alt || 'Open image'} diff --git a/mobile/src/components/markdown-file-path-detection.test.ts b/mobile/src/components/markdown-file-path-detection.test.ts index f75da01efdc..19e608ec413 100644 --- a/mobile/src/components/markdown-file-path-detection.test.ts +++ b/mobile/src/components/markdown-file-path-detection.test.ts @@ -2,7 +2,8 @@ import { describe, expect, it } from 'vitest' import { detectFilePathSegments, isFilePathCodeSpan, - normalizeFilePath + normalizeFilePath, + splitFilePathLineSuffix } from './markdown-file-path-detection' describe('detectFilePathSegments', () => { @@ -64,6 +65,69 @@ describe('detectFilePathSegments', () => { ]) }) + it('detects POSIX absolute paths', () => { + expect(detectFilePathSegments('Wrote /Users/me/wt/src/app.tsx today')).toEqual([ + { type: 'text', value: 'Wrote ' }, + { type: 'file', value: '/Users/me/wt/src/app.tsx', path: '/Users/me/wt/src/app.tsx' }, + { type: 'text', value: ' today' } + ]) + expect(detectFilePathSegments('/repo/src/index.ts')).toEqual([ + { type: 'file', value: '/repo/src/index.ts', path: '/repo/src/index.ts' } + ]) + expect(detectFilePathSegments('/root.ts')).toEqual([ + { type: 'file', value: '/root.ts', path: '/root.ts' } + ]) + }) + + it('detects files directly under explicit Windows and relative roots', () => { + expect(detectFilePathSegments(String.raw`C:\root.ts`)).toEqual([ + { type: 'file', value: String.raw`C:\root.ts`, path: String.raw`C:\root.ts` } + ]) + expect(detectFilePathSegments('./root.ts')).toEqual([ + { type: 'file', value: './root.ts', path: 'root.ts' } + ]) + expect(detectFilePathSegments('../root.ts')).toEqual([ + { type: 'file', value: '../root.ts', path: '../root.ts' } + ]) + }) + + it('detects paths with :line and :line:col suffixes', () => { + expect(detectFilePathSegments('see src/foo.ts:42 here')).toEqual([ + { type: 'text', value: 'see ' }, + { type: 'file', value: 'src/foo.ts:42', path: 'src/foo.ts:42' }, + { type: 'text', value: ' here' } + ]) + expect( + detectFilePathSegments('/wt/src/app.tsx:120:7 and C:\\repo\\a.ts:3').filter( + (s) => s.type === 'file' + ) + ).toEqual([ + { type: 'file', value: '/wt/src/app.tsx:120:7', path: '/wt/src/app.tsx:120:7' }, + { type: 'file', value: 'C:\\repo\\a.ts:3', path: 'C:\\repo\\a.ts:3' } + ]) + }) + + it('keeps a non-line colon tail out of the match', () => { + expect(detectFilePathSegments('edit src/foo.ts: then run')).toEqual([ + { type: 'text', value: 'edit ' }, + { type: 'file', value: 'src/foo.ts', path: 'src/foo.ts' }, + { type: 'text', value: ': then run' } + ]) + }) + + it('does not partially parse numeric-looking non-line tails', () => { + expect(detectFilePathSegments('log src/app.ts:1e3 oops')).toEqual([ + { type: 'text', value: 'log ' }, + { type: 'file', value: 'src/app.ts', path: 'src/app.ts' }, + { type: 'text', value: ':1e3 oops' } + ]) + expect(detectFilePathSegments('coverage src/app.ts:80% of lines')).toEqual([ + { type: 'text', value: 'coverage ' }, + { type: 'file', value: 'src/app.ts', path: 'src/app.ts' }, + { type: 'text', value: ':80% of lines' } + ]) + }) + it('does not match bare filenames without a slash', () => { expect(detectFilePathSegments('open Main.tsx please')).toEqual([ { type: 'text', value: 'open Main.tsx please' } @@ -74,6 +138,15 @@ describe('detectFilePathSegments', () => { expect(detectFilePathSegments('https://example.com/path/file.ts')).toEqual([ { type: 'text', value: 'https://example.com/path/file.ts' } ]) + expect(detectFilePathSegments('see https://example.com/path/file.ts:42 now')).toEqual([ + { type: 'text', value: 'see https://example.com/path/file.ts:42 now' } + ]) + }) + + it('does not match protocol-relative URLs', () => { + expect(detectFilePathSegments('load //cdn.example.com/lib/app.js')).toEqual([ + { type: 'text', value: 'load //cdn.example.com/lib/app.js' } + ]) }) it('does not match version numbers', () => { @@ -171,12 +244,61 @@ describe('isFilePathCodeSpan', () => { expect(isFilePathCodeSpan('node_modules/@scope/pkg/file.ts')).toBe(true) }) + it('accepts POSIX absolute paths and :line citations', () => { + expect(isFilePathCodeSpan('/Users/me/wt/src/app.tsx')).toBe(true) + expect(isFilePathCodeSpan('src/foo.ts:42')).toBe(true) + expect(isFilePathCodeSpan('src/foo.ts:42:7')).toBe(true) + expect(isFilePathCodeSpan('MobileNativeChatComposer.tsx:23')).toBe(true) + expect(isFilePathCodeSpan(String.raw`C:\repo\Main.tsx:12`)).toBe(true) + }) + it('rejects emails and git URLs with a mid-token @', () => { expect(isFilePathCodeSpan('git@github.com:user/repo.git')).toBe(false) expect(isFilePathCodeSpan('user@host.com/path/file.txt')).toBe(false) }) }) +describe('splitFilePathLineSuffix', () => { + it('splits :line and :line:col suffixes', () => { + expect(splitFilePathLineSuffix('src/foo.ts:42')).toEqual({ + path: 'src/foo.ts', + line: 42, + column: null + }) + expect(splitFilePathLineSuffix('src/foo.ts:42:7')).toEqual({ + path: 'src/foo.ts', + line: 42, + column: 7 + }) + }) + + it('keeps Windows drive colons intact', () => { + expect(splitFilePathLineSuffix(String.raw`C:\repo\a.ts`)).toEqual({ + path: String.raw`C:\repo\a.ts`, + line: null, + column: null + }) + expect(splitFilePathLineSuffix(String.raw`C:\repo\a.ts:12`)).toEqual({ + path: String.raw`C:\repo\a.ts`, + line: 12, + column: null + }) + }) + + it('ignores non-numeric and zero suffixes', () => { + expect(splitFilePathLineSuffix('src/foo.ts')).toEqual({ + path: 'src/foo.ts', + line: null, + column: null + }) + expect(splitFilePathLineSuffix('src/foo.ts:0')).toEqual({ + path: 'src/foo.ts:0', + line: null, + column: null + }) + }) +}) + describe('normalizeFilePath', () => { it('strips a leading ./', () => { expect(normalizeFilePath('./a/b.ts')).toBe('a/b.ts') diff --git a/mobile/src/components/markdown-file-path-detection.ts b/mobile/src/components/markdown-file-path-detection.ts index a33c0dceae4..5e320a3f10c 100644 --- a/mobile/src/components/markdown-file-path-detection.ts +++ b/mobile/src/components/markdown-file-path-detection.ts @@ -83,9 +83,11 @@ const FILE_EXTENSIONS = [ const EXTENSION_SET = new Set(FILE_EXTENSIONS) // Accept the host's native separator because transcript paths originate on the -// connected runtime, which may be Windows even when the phone is not. +// connected runtime, which may be Windows even when the phone is not. Leading +// alternatives cover Windows drives, UNC, and POSIX absolute roots; the optional +// tail captures only bounded agent-style :line(:col) citations. const CANDIDATE_PATTERN = - /(?:[A-Za-z]:[\\/]|\\\\)?(?:\.{1,2}[\\/])?(?:[\w.@~+-]+[\\/])+[\w.@+-]+\.[A-Za-z0-9]+/g + /(?:(?:[A-Za-z]:[\\/]|\\\\|[\\/]|\.{1,2}[\\/])(?:[\w.@~+-]+[\\/])*|(?:[\w.@~+-]+[\\/])+)[\w.@+-]+\.[A-Za-z0-9]+(?::[1-9]\d*(?::[1-9]\d*)?(?![\w@%]))?/g // A path candidate in chat prose is short; a much longer run can't hold one worth // linkifying but can push CANDIDATE_PATTERN into super-linear backtracking, so we @@ -99,7 +101,31 @@ function hasMidTokenAt(candidate: string): boolean { return /[^\\/]@/.test(candidate) } -function isOpenablePath(candidate: string): boolean { +const LINE_SUFFIX_PATTERN = /^(.+?):([1-9]\d*)(?::([1-9]\d*))?$/ + +/** + * Split an agent-style `path:line(:col)` citation into its parts. Windows drive + * colons are safe: only a trailing all-digit suffix is treated as a line ref. + */ +export function splitFilePathLineSuffix(pathText: string): { + path: string + line: number | null + column: number | null +} { + const match = LINE_SUFFIX_PATTERN.exec(pathText) + if (!match) { + return { path: pathText, line: null, column: null } + } + return { + path: match[1]!, + line: Number.parseInt(match[2]!, 10), + column: match[3] ? Number.parseInt(match[3], 10) : null + } +} + +function isOpenablePath(pathText: string): boolean { + // A :line(:col) tail is part of the citation, not the file name. + const { path: candidate } = splitFilePathLineSuffix(pathText) // Reject anything URL-ish or scheme-bearing — those are handled as web links. if (candidate.includes('://') || hasMidTokenAt(candidate)) { return false @@ -153,10 +179,11 @@ export function detectFilePathSegments(text: string): FilePathSegment[] { while ((match = CANDIDATE_PATTERN.exec(text))) { const candidate = match[0] - // Skip candidates that are part of a URL (preceded by a scheme colon or an - // alphanumeric/host char that would make this a domain tail, not a path). + // Skip candidates that are part of a URL: a scheme colon, a domain tail, or + // a preceding slash (the leading slash of an absolute path is part of the + // match itself, so prev '/' means a '://' or '//' remainder, not a path). const prev = match.index > 0 ? text[match.index - 1]! : '' - if (prev === ':' || prev === '/' || /[\w.@]/.test(prev)) { + if (prev === ':' || prev === '/' || prev === '\\' || /[\w.@]/.test(prev)) { continue } if (!isOpenablePath(candidate)) { @@ -195,16 +222,18 @@ export function isFilePathCodeSpan(code: string): boolean { if (isOpenablePath(trimmed)) { return true } - // Separator-less code span: accept a clean name.ext with a known extension. - if (/[\\/]/.test(trimmed)) { + // Separator-less code span: accept a clean name.ext (with an optional + // :line(:col) citation tail) and a known extension. + const { path } = splitFilePathLineSuffix(trimmed) + if (/[\\/]/.test(path)) { return false } - const dot = trimmed.lastIndexOf('.') + const dot = path.lastIndexOf('.') if (dot <= 0) { return false } - const name = trimmed.slice(0, dot) - const ext = trimmed.slice(dot + 1).toLowerCase() + const name = path.slice(0, dot) + const ext = path.slice(dot + 1).toLowerCase() if (/[^\w.@+-]/.test(name)) { return false } diff --git a/mobile/src/components/markdown-href-routing.test.ts b/mobile/src/components/markdown-href-routing.test.ts new file mode 100644 index 00000000000..7117a2ecbc8 --- /dev/null +++ b/mobile/src/components/markdown-href-routing.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from 'vitest' +import { routeMarkdownHref } from './markdown-href-routing' + +describe('routeMarkdownHref', () => { + it('routes web and mail links to the system handler', () => { + expect(routeMarkdownHref('https://example.com/docs')).toEqual({ + kind: 'web', + url: 'https://example.com/docs' + }) + expect(routeMarkdownHref('http://localhost:3000/')).toEqual({ + kind: 'web', + url: 'http://localhost:3000/' + }) + expect(routeMarkdownHref(' mailto:dev@example.com ')).toEqual({ + kind: 'web', + url: 'mailto:dev@example.com' + }) + }) + + it('routes relative hrefs to the file opener', () => { + expect(routeMarkdownHref('src/foo.ts')).toEqual({ kind: 'file', pathText: 'src/foo.ts' }) + expect(routeMarkdownHref('./docs/plan.md')).toEqual({ + kind: 'file', + pathText: './docs/plan.md' + }) + }) + + it('carries a #L fragment as a :line suffix', () => { + expect(routeMarkdownHref('docs/plan.md#L42')).toEqual({ + kind: 'file', + pathText: 'docs/plan.md:42' + }) + expect(routeMarkdownHref('docs/plan.md?plain=1#line-7')).toEqual({ + kind: 'file', + pathText: 'docs/plan.md:7' + }) + expect(routeMarkdownHref('docs/plan.md#usage')).toEqual({ + kind: 'file', + pathText: 'docs/plan.md' + }) + }) + + it('decodes percent-encoded href paths', () => { + expect(routeMarkdownHref('docs/release%20notes.md')).toEqual({ + kind: 'file', + pathText: 'docs/release notes.md' + }) + }) + + it('routes file: URIs to the file opener', () => { + expect(routeMarkdownHref('file:///Users/me/wt/src/app.tsx')).toEqual({ + kind: 'file', + pathText: '/Users/me/wt/src/app.tsx' + }) + expect(routeMarkdownHref('file:///Users/me/wt/src/app.tsx#L12')).toEqual({ + kind: 'file', + pathText: '/Users/me/wt/src/app.tsx:12' + }) + expect(routeMarkdownHref('file:///C:/repo/src/index.ts')).toEqual({ + kind: 'file', + pathText: 'C:/repo/src/index.ts' + }) + }) + + it('keeps Windows drive paths out of the scheme filter', () => { + expect(routeMarkdownHref(String.raw`C:\repo\src\index.ts`)).toEqual({ + kind: 'file', + pathText: String.raw`C:\repo\src\index.ts` + }) + }) + + it('drops anchors, unknown schemes, and empty hrefs', () => { + expect(routeMarkdownHref('#section')).toEqual({ kind: 'none' }) + expect(routeMarkdownHref('')).toEqual({ kind: 'none' }) + expect(routeMarkdownHref('editor://file/x.ts')).toEqual({ kind: 'none' }) + expect(routeMarkdownHref('javascript:alert(1)')).toEqual({ kind: 'none' }) + expect(routeMarkdownHref('data:text/plain,hi')).toEqual({ kind: 'none' }) + }) +}) diff --git a/mobile/src/components/markdown-href-routing.ts b/mobile/src/components/markdown-href-routing.ts new file mode 100644 index 00000000000..61531f937a5 --- /dev/null +++ b/mobile/src/components/markdown-href-routing.ts @@ -0,0 +1,18 @@ +import { routeNativeChatHref } from '../../../src/shared/native-chat-href-routing' + +export type MarkdownHrefRoute = + | { kind: 'web'; url: string } + | { kind: 'file'; pathText: string } + | { kind: 'none' } + +function withLineSuffix(pathText: string, line: number | null): string { + return line === null ? pathText : `${pathText}:${line}` +} + +export function routeMarkdownHref(href: string): MarkdownHrefRoute { + const route = routeNativeChatHref(href) + if (route.kind !== 'file') { + return route + } + return { kind: 'file', pathText: withLineSuffix(route.pathText, route.line) } +} diff --git a/mobile/src/components/markdown-inline-token-rules.test.ts b/mobile/src/components/markdown-inline-token-rules.test.ts new file mode 100644 index 00000000000..27d44a36d9c --- /dev/null +++ b/mobile/src/components/markdown-inline-token-rules.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import { + isIntrawordUnderscoreToken, + trimAutolinkTrailingPunctuation +} from './markdown-inline-token-rules' + +describe('isIntrawordUnderscoreToken', () => { + it('rejects snake_case emphasis spans', () => { + const text = 'src/foo_bar.ts and src/baz_qux.ts' + const index = text.indexOf('_') + const token = text.slice(index, text.lastIndexOf('_') + 1) + expect(isIntrawordUnderscoreToken(text, index, token)).toBe(true) + }) + + it('keeps standalone emphasis', () => { + expect(isIntrawordUnderscoreToken('say _hello_ now', 4, '_hello_')).toBe(false) + expect(isIntrawordUnderscoreToken('_hello_.', 0, '_hello_')).toBe(false) + }) + + it('rejects emphasis closed against a following word', () => { + expect(isIntrawordUnderscoreToken('_foo_s bar', 0, '_foo_')).toBe(true) + }) + + it('rejects dunder emphasis inside a path', () => { + expect(isIntrawordUnderscoreToken('src/__init__.py', 4, '__init__')).toBe(true) + expect(isIntrawordUnderscoreToken(String.raw`src\__init__.py`, 4, '__init__')).toBe(true) + }) + + it('ignores non-underscore tokens', () => { + expect(isIntrawordUnderscoreToken('a*b*c', 1, '*b*')).toBe(false) + }) +}) + +describe('trimAutolinkTrailingPunctuation', () => { + it('splits sentence punctuation off the URL', () => { + expect(trimAutolinkTrailingPunctuation('https://x.com/a.')).toEqual({ + url: 'https://x.com/a', + trailing: '.' + }) + expect(trimAutolinkTrailingPunctuation('https://x.com/a,')).toEqual({ + url: 'https://x.com/a', + trailing: ',' + }) + expect(trimAutolinkTrailingPunctuation('https://x.com/a?!')).toEqual({ + url: 'https://x.com/a', + trailing: '?!' + }) + }) + + it('keeps balanced parens and strips unbalanced ones', () => { + expect(trimAutolinkTrailingPunctuation('https://x.com/a_(b)')).toEqual({ + url: 'https://x.com/a_(b)', + trailing: '' + }) + expect(trimAutolinkTrailingPunctuation('https://x.com/a).')).toEqual({ + url: 'https://x.com/a', + trailing: ').' + }) + }) + + it('handles long unmatched closing-parenthesis tails', () => { + const url = 'https://x.com/a_(b)' + const trailing = ')'.repeat(4096) + expect(trimAutolinkTrailingPunctuation(`${url}${trailing}`)).toEqual({ url, trailing }) + }) + + it('leaves clean URLs untouched', () => { + expect(trimAutolinkTrailingPunctuation('https://x.com/a')).toEqual({ + url: 'https://x.com/a', + trailing: '' + }) + }) +}) diff --git a/mobile/src/components/markdown-inline-token-rules.ts b/mobile/src/components/markdown-inline-token-rules.ts new file mode 100644 index 00000000000..1afa8477fbb --- /dev/null +++ b/mobile/src/components/markdown-inline-token-rules.ts @@ -0,0 +1,55 @@ +// Post-checks for inline markdown tokens that a single-pass tokenizer regex +// cannot express on its own. + +const INTRAWORD_FLANK_PATTERN = /[\w\\/]/ + +/** + * True when a `_…_` / `__…__` token sits inside a word (snake_case, dunder + * tails). CommonMark treats intraword underscores as literal text; path + * separators count as flanks so dunder path segments also stay whole. + */ +export function isIntrawordUnderscoreToken(text: string, index: number, token: string): boolean { + if (!token.startsWith('_')) { + return false + } + const prev = index > 0 ? text[index - 1]! : '' + const next = text[index + token.length] ?? '' + return INTRAWORD_FLANK_PATTERN.test(prev) || INTRAWORD_FLANK_PATTERN.test(next) +} + +/** + * Split sentence punctuation off an autolinked URL tail ("see https://x.com/a."), + * keeping a trailing ')' only when the URL itself opened a paren. + */ +export function trimAutolinkTrailingPunctuation(url: string): { url: string; trailing: string } { + let end = url.length + let parenthesisCountsReady = false + let openParentheses = 0 + let closeParentheses = 0 + while (end > 0) { + const char = url[end - 1]! + if ('.,;:!?'.includes(char)) { + end-- + continue + } + if (char === ')') { + if (!parenthesisCountsReady) { + for (let index = 0; index < end; index++) { + if (url[index] === '(') { + openParentheses++ + } else if (url[index] === ')') { + closeParentheses++ + } + } + parenthesisCountsReady = true + } + if (closeParentheses > openParentheses) { + end-- + closeParentheses-- + continue + } + } + break + } + return { url: url.slice(0, end), trailing: url.slice(end) } +} diff --git a/mobile/src/components/mobile-markdown-mermaid-routing.test.ts b/mobile/src/components/mobile-markdown-mermaid-routing.test.ts new file mode 100644 index 00000000000..c89dfa00853 --- /dev/null +++ b/mobile/src/components/mobile-markdown-mermaid-routing.test.ts @@ -0,0 +1,80 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { MobileMarkdown } from './MobileMarkdown' + +vi.mock('react-native', () => ({ + Linking: { openURL: vi.fn() }, + Pressable: 'Pressable', + ScrollView: 'ScrollView', + StyleSheet: { create: (styles: T) => styles, hairlineWidth: 1 }, + Text: 'Text', + View: 'View' +})) +vi.mock('./pr-sidebar/MermaidDiagram', () => ({ MermaidDiagram: 'MermaidDiagram' })) + +let renderer: ReactTestRenderer | undefined + +afterEach(() => { + renderer?.unmount() + renderer = undefined + vi.restoreAllMocks() +}) + +function render(content: string): ReactTestRenderer { + act(() => { + renderer = create(createElement(MobileMarkdown, { content })) + }) + return renderer! +} + +function mermaidCount(tree: ReactTestRenderer): number { + return tree.root.findAllByType('MermaidDiagram' as never).length +} + +function firstMermaid(tree: ReactTestRenderer) { + return tree.root.findByType('MermaidDiagram' as never) +} + +describe('MobileMarkdown mermaid routing', () => { + it('routes a closed mermaid fence to MermaidDiagram', () => { + const tree = render('```mermaid\ngraph TD; A-->B\n```') + expect(mermaidCount(tree)).toBe(1) + }) + + it('keeps a streaming (unterminated) mermaid fence as raw code', () => { + const tree = render('```mermaid\ngraph TD; A-->B') + expect(mermaidCount(tree)).toBe(0) + }) + + it('keeps identical sibling diagrams uniquely keyed', () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const diagram = '```mermaid\ngraph TD; A-->B\n```' + const tree = render(`${diagram}\n\n${diagram}`) + const warnings = consoleError.mock.calls.flat().join(' ') + expect(mermaidCount(tree)).toBe(2) + expect(warnings).not.toContain('same key') + }) + + it('preserves a completed diagram while later prose streams', () => { + const diagram = '```mermaid\ngraph TD; A-->B\n```' + const tree = render(diagram) + const initial = firstMermaid(tree) + act(() => tree.update(createElement(MobileMarkdown, { content: `${diagram}\n\nNext` }))) + expect(firstMermaid(tree)).toBe(initial) + }) + + it('remounts a diagram when its source changes', () => { + const tree = render('```mermaid\ngraph TD; A-->B\n```') + const initial = firstMermaid(tree) + act(() => + tree.update(createElement(MobileMarkdown, { content: '```mermaid\ngraph TD; A-->C\n```' })) + ) + expect(firstMermaid(tree)).not.toBe(initial) + }) + + it('does not route other code fences to MermaidDiagram', () => { + const tree = render('```ts\nconst a = 1\n```') + expect(mermaidCount(tree)).toBe(0) + }) +}) diff --git a/mobile/src/components/mobile-markdown-parser.ts b/mobile/src/components/mobile-markdown-parser.ts index b6375f389c5..fa16b3b9310 100644 --- a/mobile/src/components/mobile-markdown-parser.ts +++ b/mobile/src/components/mobile-markdown-parser.ts @@ -2,7 +2,7 @@ export type MobileMarkdownBlock = | { type: 'paragraph'; text: string } | { type: 'heading'; level: number; text: string } | { type: 'quote'; text: string } - | { type: 'code'; text: string; language?: string } + | { type: 'code'; text: string; language?: string; closed: boolean } | { type: 'list'; ordered: boolean; items: Array<{ text: string; checked?: boolean }> } | { type: 'image'; alt: string; url: string } | { type: 'table'; headers: string[]; rows: string[][] } @@ -42,10 +42,12 @@ export function parseMobileMarkdown(content: string): MobileMarkdownBlock[] { code.push(lines[index] ?? '') index += 1 } - if (index < lines.length) { + // closed=false means the fence is still streaming in (no terminator yet). + const closed = index < lines.length + if (closed) { index += 1 } - blocks.push({ type: 'code', text: code.join('\n'), language: fence[1] }) + blocks.push({ type: 'code', text: code.join('\n'), language: fence[1], closed }) continue } diff --git a/mobile/src/components/mobile-mermaid-language.ts b/mobile/src/components/mobile-mermaid-language.ts new file mode 100644 index 00000000000..8e7811ba167 --- /dev/null +++ b/mobile/src/components/mobile-mermaid-language.ts @@ -0,0 +1,4 @@ +/** True when a fenced code block language should render as a Mermaid diagram. */ +export function isMobileMermaidLanguage(language?: string): boolean { + return language?.trim().toLowerCase() === 'mermaid' +} diff --git a/mobile/src/components/pr-sidebar/MermaidDiagram.tsx b/mobile/src/components/pr-sidebar/MermaidDiagram.tsx index b4c4811c0d3..0df2aa210db 100644 --- a/mobile/src/components/pr-sidebar/MermaidDiagram.tsx +++ b/mobile/src/components/pr-sidebar/MermaidDiagram.tsx @@ -1,7 +1,8 @@ -import { useMemo, useState } from 'react' +import { memo, useMemo, useState } from 'react' import { ScrollView, StyleSheet, Text, View } from 'react-native' import { WebView } from 'react-native-webview' import { colors, radii, spacing, typography } from '../../theme/mobile-theme' +import { MERMAID_ENGINE_JS } from './mermaid-webview-engine.generated' type Props = { source: string @@ -9,11 +10,15 @@ type Props = { } // Renders a ```mermaid fence as a diagram via a sandboxed WebView (mermaid has no -// native RN renderer). Mermaid is loaded from a CDN inside the WebView HTML, the -// SVG is themed dark to match the sidebar, and the WebView posts back its rendered -// height so we can size to content. On any failure (no network, parse error, -// render error) we fall back to the raw source in a labeled mono code box. -export function MermaidDiagram({ source, base }: Props) { +// native RN renderer). Mermaid ships inside the app as a generated bundle embedded +// in the WebView HTML — no network — the SVG is themed dark to match the sidebar, +// and the WebView posts back its rendered height so we can size to content. On any +// failure (parse error, render error) we fall back to the raw source in a labeled +// mono code box. +// memo: both props are primitives; without it every mounted diagram re-renders +// per frame during pinch-to-zoom (textScale updates), marshalling the full HTML +// string across the Fabric boundary each time. +export const MermaidDiagram = memo(function MermaidDiagram({ source, base }: Props) { const [height, setHeight] = useState(0) const [failed, setFailed] = useState(false) const html = useMemo(() => buildHtml(source), [source]) @@ -58,7 +63,7 @@ export function MermaidDiagram({ source, base }: Props) { /> ) -} +}) function MermaidFallback({ source, base }: Props) { return ( @@ -73,21 +78,33 @@ function MermaidFallback({ source, base }: Props) { ) } -// Self-contained HTML: load mermaid from CDN, render the graph, post the body +// JSON.stringify escapes quotes and control chars but leaves `<`, `>`, `&`, and +// the U+2028/U+2029 line separators raw — so a source containing `` +// would close this inline + - +
@@ -114,7 +131,7 @@ function buildHtml(source: string): string { } }); mermaid.run({ querySelector: '.mermaid' }) - .then(reportHeight) + .then(function () { reportHeight(); }) .catch(function () { post('error'); }); } catch (e) { post('error'); diff --git a/mobile/src/components/pr-sidebar/mermaid-diagram-html.test.ts b/mobile/src/components/pr-sidebar/mermaid-diagram-html.test.ts new file mode 100644 index 00000000000..d66d82d9f53 --- /dev/null +++ b/mobile/src/components/pr-sidebar/mermaid-diagram-html.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest' +import { buildHtml } from './MermaidDiagram' +import { MERMAID_ENGINE_JS } from './mermaid-webview-engine.generated' + +vi.mock('react-native', () => ({ + ScrollView: 'ScrollView', + StyleSheet: { create: (styles: T) => styles, hairlineWidth: 1 }, + Text: 'Text', + View: 'View' +})) +vi.mock('react-native-webview', () => ({ WebView: 'WebView' })) + +// The diagram source is untrusted (agent output, PR/chat content). It is embedded +// inside an inline payload break out of the inline script', () => { + const payload = 'graph TD; A-->B' + const countClosers = (html: string) => (html.match(/<\/script>/gi) ?? []).length + // The payload's two must add zero raw closers over a benign render — + // they were neutralized to \u003c instead of closing our inline script. + const benign = countClosers(buildHtml('graph TD; A-->B')) + expect(countClosers(buildHtml(payload))).toBe(benign) + expect(buildHtml(payload)).toContain('\\u003c/script') + }) + + it('escapes the U+2028/U+2029 line separators that would break the JS literal', () => { + const payload = `a${String.fromCharCode(0x2028)}b${String.fromCharCode(0x2029)}c` + const html = buildHtml(payload) + expect(html).toContain('\\u2028') + expect(html).toContain('\\u2029') + expect(html.includes(String.fromCharCode(0x2028))).toBe(false) + expect(html.includes(String.fromCharCode(0x2029))).toBe(false) + }) + + it('still round-trips ordinary source to the exact original string', () => { + const payload = 'graph LR\n A["node & "] --> B' + const html = buildHtml(payload) + const match = html.match(/\.textContent = (".*?");\n {4}mermaid\.initialize/s) + expect(match).not.toBeNull() + expect(JSON.parse(match![1]!)).toBe(payload) + }) + + // Same gate as the terminal document: mermaid is embedded from the lockfile-pinned + // package, so the document itself must load nothing external (offline-safe, no CDN + // supply-chain exposure). The engine's internal URL literals (xmlns, docs links) + // are inert data, so the gate checks the document with the engine stripped out. + it('embeds the mermaid engine and loads no external resource', () => { + const html = buildHtml('graph TD; A-->B') + expect(html).toContain(MERMAID_ENGINE_JS) + expect(html.replace(MERMAID_ENGINE_JS, '')).not.toMatch(/\bhttps?:\/\//) + }) + + it('blocks external resources requested by diagram syntax', () => { + const html = buildHtml('flowchart LR\nA@{ img: "https://example.com/pixel.png" }') + const policy = html.match(/Content-Security-Policy" content="([^"]+)"/)?.[1] + expect(policy).toContain("default-src 'none'") + expect(policy).toContain('img-src data: blob:') + expect(policy).not.toMatch(/https?:/) + }) +}) diff --git a/mobile/src/home-host-edit-navigation-source.test.ts b/mobile/src/home-host-edit-navigation-source.test.ts index 2f6242f7ec1..4597a138e24 100644 --- a/mobile/src/home-host-edit-navigation-source.test.ts +++ b/mobile/src/home-host-edit-navigation-source.test.ts @@ -5,8 +5,7 @@ const homeSource = readFileSync(new URL('../app/index.tsx', import.meta.url), 'u describe('Home host edit navigation wiring', () => { it('uses the cold-navigator-safe edit transition', () => { - expect(homeSource).toMatch( - /onEdit:\s*\(hostId\)\s*=>\s*navigateToMobileHostEdit\(router,\s*hostId\)/ - ) + expect(homeSource).toMatch(/const openMobileHostEdit = useOpenMobileHostEdit\(\)/) + expect(homeSource).toMatch(/onEdit:\s*openMobileHostEdit/) }) }) diff --git a/mobile/src/session/MobileNativeChatAsk.tsx b/mobile/src/session/MobileNativeChatAsk.tsx index b485818970c..86fcb0dc4a2 100644 --- a/mobile/src/session/MobileNativeChatAsk.tsx +++ b/mobile/src/session/MobileNativeChatAsk.tsx @@ -282,6 +282,7 @@ const styles = StyleSheet.create({ }, option: { flexDirection: 'row', + alignItems: 'center', gap: spacing.sm, padding: spacing.sm, borderRadius: radii.card, @@ -299,8 +300,7 @@ const styles = StyleSheet.create({ borderWidth: 1.5, borderColor: colors.textMuted, alignItems: 'center', - justifyContent: 'center', - marginTop: 1 + justifyContent: 'center' }, checkCircle: { borderRadius: 9 diff --git a/mobile/src/session/MobileNativeChatOverlay.test.ts b/mobile/src/session/MobileNativeChatOverlay.test.ts new file mode 100644 index 00000000000..2680064c94b --- /dev/null +++ b/mobile/src/session/MobileNativeChatOverlay.test.ts @@ -0,0 +1,193 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NativeChatMessage } from '../../../src/shared/native-chat-types' +import { MobileNativeChatOverlay } from './MobileNativeChatOverlay' +import type { MobileNativeChatController } from './use-mobile-native-chat-controller' + +vi.mock('react-native', () => ({ + StyleSheet: { create: (styles: unknown) => styles, absoluteFillObject: {} }, + View: 'View' +})) + +vi.mock('./MobileNativeChatView', () => ({ MobileNativeChatView: 'ChatView' })) + +function assistantTurn(id: string, text: string): NativeChatMessage { + return { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp: 0, source: 'hook' } +} + +function suppressRendererWarning(): () => void { + const original = console.error + const spy = vi.spyOn(console, 'error').mockImplementation((...args) => { + if (typeof args[0] === 'string' && args[0].includes('react-test-renderer is deprecated')) { + return + } + original(...args) + }) + return () => spy.mockRestore() +} + +/** One render of the route: chat visible or not, the transcript it currently + * holds, and the agent-status stream behind it. */ +type Tick = { + show?: boolean + messages?: NativeChatMessage[] + streamingText?: string + streamLive?: boolean + identity?: string +} + +function overlayElement(tick: Tick): ReturnType { + const controller = { + showNativeChat: tick.show ?? true, + nativeChatSession: { messages: tick.messages ?? [], status: 'ready' }, + nativeChatAgent: 'claude', + nativeChatAgentWorking: tick.streamLive ?? false, + nativeChatStreamingText: tick.streamingText, + nativeChatStreamLive: tick.streamLive ?? false, + nativeChatStreamScopeKey: tick.identity ?? 'tab-a', + chatPending: [], + chatComposerText: '', + setChatComposerText: vi.fn() + } as unknown as MobileNativeChatController + return createElement(MobileNativeChatOverlay, { + controller, + images: {} as never, + onMicPress: vi.fn(), + micActive: false, + dictationMode: 'toggle', + onMicPressIn: vi.fn(), + onMicPressOut: vi.fn(), + inputLockReason: null, + sendErrorMessage: null, + onClearSendError: vi.fn(), + keyboardInset: 0 + }) +} + +describe('MobileNativeChatOverlay streaming gate', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + async function render(tick: Tick): Promise { + const restore = suppressRendererWarning() + try { + await act(async () => { + renderer = create(overlayElement(tick)) + }) + } finally { + restore() + } + } + + async function update(tick: Tick): Promise { + await act(async () => { + renderer?.update(overlayElement(tick)) + }) + } + + /** The bubble text handed to the chat list, or `'hidden'` when chat is off. */ + function streaming(): string | null | 'hidden' { + const views = renderer!.root.findAll((node) => node.type === 'ChatView') + return views.length === 0 ? 'hidden' : (views[0].props.streaming as string | null) + } + + it('keeps streaming a reply that repeats the previous turn as a prefix', async () => { + const prior = [assistantTurn('a1', 'The tests pass.')] + await render({ messages: prior }) + expect(streaming()).toBeNull() + + await update({ messages: prior, streamingText: 'The tests', streamLive: true }) + + expect(streaming()).toBe('The tests') + }) + + it('drops the streaming bubble once the reply lands as its own turn', async () => { + const prior = [assistantTurn('a1', 'Done.')] + await render({ messages: prior }) + await update({ messages: prior, streamingText: 'Done.', streamLive: true }) + expect(streaming()).toBe('Done.') + + await update({ + messages: [...prior, assistantTurn('a2', 'Done.')], + streamingText: 'Done.', + streamLive: true + }) + + expect(streaming()).toBeNull() + }) + + it('keeps the bubble across a peek at the terminal view', async () => { + // Toggling to the terminal unmounts the chat list and unsubscribes its + // transcript. The gate lives above that boundary, so the baseline survives + // and the repeated-prefix reply keeps streaming on the way back. + const prior = [assistantTurn('a1', 'Done.')] + await render({ messages: prior }) + await update({ messages: prior, streamingText: 'Done.', streamLive: true }) + expect(streaming()).toBe('Done.') + + await update({ show: false, messages: [], streamLive: true }) + expect(streaming()).toBe('hidden') + // Back on chat the session withholds its transcript until a fresh read + // settles, so the throttled stream text returns a round trip ahead of it. + await update({ messages: [], streamLive: true }) + await update({ messages: [], streamingText: 'Done.', streamLive: true }) + await update({ messages: prior, streamingText: 'Done.', streamLive: true }) + + expect(streaming()).toBe('Done.') + }) + + it('keeps the bubble across a peek at the terminal taken between turns', async () => { + // Same toggle, but taken while idle: the transcript empties before the next + // turn starts, so the gate has to reject that empty tail as a baseline. + const prior = [assistantTurn('a1', 'Done.')] + await render({ messages: prior }) + + await update({ show: false, messages: [] }) + await update({ show: false, messages: [], streamLive: true }) + await update({ messages: [], streamLive: true }) + await update({ messages: [], streamingText: 'Done.', streamLive: true }) + await update({ messages: prior, streamingText: 'Done.', streamLive: true }) + + expect(streaming()).toBe('Done.') + }) + + it('hides a repeated part whose own turn landed during a mid-turn gap', async () => { + // Between parts the status frame carries no assistant text (a tool call), so + // the stream goes textless while the turn is still live and the part that + // just finished lands in the transcript. Re-anchoring on that tick would + // adopt it as history and render it a second time. + const prior = [assistantTurn('a1', 'Done.')] + await render({ messages: prior }) + await update({ messages: prior, streamingText: 'Done.', streamLive: true }) + expect(streaming()).toBe('Done.') + + const landed = [...prior, assistantTurn('a2', 'Done.')] + await update({ messages: landed, streamLive: true }) + await update({ messages: landed, streamingText: 'Done.', streamLive: true }) + + expect(streaming()).toBeNull() + }) + + it("does not carry one chat's baseline into another stream identity", async () => { + const prior = [assistantTurn('a1', 'Shared answer text')] + await render({ messages: prior, identity: 'tab-a' }) + + await update({ + messages: prior, + streamingText: 'Shared answer', + streamLive: true, + identity: 'tab-b' + }) + + expect(streaming()).toBeNull() + }) +}) diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index d03d9543388..58318810e50 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -1,10 +1,16 @@ +import { useMemo } from 'react' import { StyleSheet, View } from 'react-native' import { MobileNativeChatView, type MobileNativeChatInputLockReason } from './MobileNativeChatView' +import { foldMobileNativeChatMessages } from './mobile-native-chat-render-data' import type { MobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' import type { MobileNativeChatController } from './use-mobile-native-chat-controller' +import { useMobileNativeChatStreamingBubble } from './use-mobile-native-chat-streaming-bubble' type Props = { controller: MobileNativeChatController + /** Opens a tapped file reference (worktree-relative or absolute, optional + * :line(:col) suffix) through the shared tap-to-open flow. */ + onOpenFile: (pathText: string) => void /** Native-chat image attachments: picking adds a composer chip, and sending * rides the pending images along with the message text (desktop parity). */ images: MobileNativeChatImageAttachments @@ -22,9 +28,12 @@ type Props = { } /** Keeps the terminal mounted underneath chat so its PTY subscription survives - * view toggles while the native surface owns the visible composer. */ + * view toggles while the native surface owns the visible composer. Also owns + * the streaming gate: this component stays mounted across those toggles, while + * the chat list below it does not. */ export function MobileNativeChatOverlay({ controller, + onOpenFile, images, onMicPress, micActive, @@ -36,19 +45,27 @@ export function MobileNativeChatOverlay({ onClearSendError, keyboardInset }: Props): React.JSX.Element | null { + const session = controller.nativeChatSession + const folded = useMemo(() => foldMobileNativeChatMessages(session.messages), [session.messages]) + const streaming = useMobileNativeChatStreamingBubble( + folded, + controller.nativeChatStreamingText, + controller.nativeChatStreamScopeKey, + controller.nativeChatStreamLive + ) if (!controller.showNativeChat) { return null } - const session = controller.nativeChatSession return ( ({ @@ -58,6 +59,9 @@ vi.mock('./MobileNativeChatComposer', async () => { }) type Overrides = { + messages?: Parameters[0]['messages'] + folded?: Parameters[0]['folded'] + streaming?: string | null sendErrorMessage?: string | null onClearSendError?: () => void inputLockReason?: 'disconnected' | 'waiting' | null @@ -75,7 +79,25 @@ function suppressRendererWarning(): () => void { return () => spy.mockRestore() } -describe('MobileNativeChatView send-error banner', () => { +function assistantTurn(id: string, text: string): NativeChatMessage { + return { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp: 0, source: 'hook' } +} + +function chatViewElement(overrides: Overrides): ReturnType { + return createElement(MobileNativeChatView, { + messages: [], + folded: [], + status: 'ready', + streaming: null, + onSend: vi.fn().mockResolvedValue(true), + pending: [], + composerText: '', + onComposerTextChange: vi.fn(), + ...overrides + }) +} + +describe('MobileNativeChatView', () => { let renderer: ReactTestRenderer | null = null beforeEach(() => { @@ -91,23 +113,25 @@ describe('MobileNativeChatView send-error banner', () => { const restore = suppressRendererWarning() try { await act(async () => { - renderer = create( - createElement(MobileNativeChatView, { - messages: [], - status: 'ready', - onSend: overrides.onSend ?? vi.fn().mockResolvedValue(true), - pending: [], - composerText: '', - onComposerTextChange: vi.fn(), - ...overrides - }) - ) + renderer = create(chatViewElement(overrides)) }) } finally { restore() } } + async function update(overrides: Overrides = {}): Promise { + await act(async () => { + renderer?.update(chatViewElement(overrides)) + }) + } + + /** Ids of the rows the list is currently rendering. */ + function listIds(): string[] { + const list = renderer!.root.find((node) => node.type === 'FlatList') + return (list.props.data as { id: string }[]).map((row) => row.id) + } + function banners(): ReactTestInstance[] { return renderer!.root.findAll((node) => node.props.accessibilityRole === 'alert') } @@ -161,4 +185,16 @@ describe('MobileNativeChatView send-error banner', () => { expect(onClearSendError).toHaveBeenCalledOnce() }) + + // The gate that decides `streaming` lives in MobileNativeChatOverlay, which + // outlives this view; see MobileNativeChatOverlay.test.ts. + it('appends the gated streaming bubble after the folded transcript', async () => { + const folded = [assistantTurn('a1', 'The tests pass.')] + await render({ folded }) + expect(listIds()).toEqual(['a1']) + + await update({ folded, streaming: 'The tests' }) + + expect(listIds()).toEqual(['a1', 'streaming']) + }) }) diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index a4b63e80f38..98ae01c3c28 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -16,7 +16,6 @@ import { colors } from '../theme/mobile-theme' import { styles } from './mobile-native-chat-view-styles' import { buildMobileNativeChatTransientData, - foldMobileNativeChatMessages, mobileNativeChatEmptyState, type MobileNativeChatPendingItem } from './mobile-native-chat-render-data' @@ -40,7 +39,10 @@ import type { MobileNativeChatStatus } from './use-mobile-native-chat-session' export type MobileNativeChatInputLockReason = 'disconnected' | 'waiting' type Props = { + /** Raw transcript, only for telling "still loading" from "loaded and empty". */ messages: NativeChatMessage[] + /** `messages` with noise stripped and tool turns folded in, from the overlay. */ + folded: NativeChatMessage[] status: MobileNativeChatStatus error?: string /** Resolved agent for this chat; names the empty-state copy (desktop parity). */ @@ -48,9 +50,9 @@ type Props = { agentWorking?: boolean /** Interrupt the agent mid-turn (shown as a Stop button on the working bar). */ onStop?: () => void - /** Live partial assistant text while a turn is still streaming (from the agent - * status hook). Shown as an in-progress bubble until the transcript catches up. */ - streamingText?: string + /** Live partial assistant text to show as an in-progress bubble, already gated + * by the overlay against the transcript catching up. */ + streaming: string | null hasMore?: boolean loadingEarlier?: boolean onLoadEarlier?: () => void @@ -105,12 +107,13 @@ type Props = { export function MobileNativeChatView({ messages, + folded, status, error, agent, agentWorking, onStop, - streamingText, + streaming, hasMore, loadingEarlier, onLoadEarlier, @@ -169,10 +172,9 @@ export function MobileNativeChatView({ // `data` is the list source: folded transcript + synthetic streaming bubble + // route-owned optimistic queued messages. Memoize on the same deps so the // downstream autoscroll effects/`renderItem` keep referential stability. - const foldedMessages = useMemo(() => foldMobileNativeChatMessages(messages), [messages]) const { data } = useMemo( - () => buildMobileNativeChatTransientData({ folded: foldedMessages, streamingText, pending }), - [foldedMessages, streamingText, pending] + () => buildMobileNativeChatTransientData({ folded, streaming, pending }), + [folded, streaming, pending] ) // Follow the tail as the conversation grows and keep the newest message above @@ -276,6 +278,9 @@ export function MobileNativeChatView({ keyExtractor={(item) => item.id} renderItem={renderItem} contentContainerStyle={styles.listContent} + // Let link/file taps land while the composer keyboard is up + // instead of being swallowed by the dismiss gesture. + keyboardShouldPersistTaps="handled" onScroll={onScroll} scrollEventThrottle={32} onContentSizeChange={() => { diff --git a/mobile/src/session/mobile-terminal-file-tap-open.test.ts b/mobile/src/session/mobile-file-tap-open.test.ts similarity index 65% rename from mobile/src/session/mobile-terminal-file-tap-open.test.ts rename to mobile/src/session/mobile-file-tap-open.test.ts index fec1b5b663c..d2a324d2c12 100644 --- a/mobile/src/session/mobile-terminal-file-tap-open.test.ts +++ b/mobile/src/session/mobile-file-tap-open.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { openMobileTerminalFileTap } from './mobile-terminal-file-tap-open' +import { openMobileFileTap } from './mobile-file-tap-open' function ok(result: unknown) { return { ok: true, result, _meta: { runtimeId: 'runtime-1' } } @@ -22,7 +22,7 @@ function activeTerminalState(activated: boolean) { } } -describe('openMobileTerminalFileTap', () => { +describe('openMobileFileTap', () => { it('opens absolute terminal artifacts through the grant-backed preview route', async () => { const client = createClient([ ok({ @@ -42,7 +42,7 @@ describe('openMobileTerminalFileTap', () => { const pushPreviewRoute = vi.fn() const triggerOpenFeedback = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -106,7 +106,7 @@ describe('openMobileTerminalFileTap', () => { const openedTab = { id: 'tab-2', relativePath: 'src/index.ts' } const switchSessionTab = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -135,6 +135,56 @@ describe('openMobileTerminalFileTap', () => { expect(switchSessionTab).toHaveBeenCalledWith(openedTab) }) + it('opens a sibling terminal path through the resolved owning worktree', async () => { + const client = createClient([ + ok({ + worktree: 'wt-2', + relativePath: 'docs/readme.md', + absolutePath: '/repo-b/docs/readme.md', + exists: true, + isDirectory: false, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath: 'docs/readme.md', + absolutePath: '/repo-b/docs/readme.md' + } + }) + ]) + const pushPreviewRoute = vi.fn() + + openMobileFileTap({ + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pathText: '/repo-b/docs/readme.md', + line: null, + column: null, + pushPreviewRoute, + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: activeTerminalState, + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn() + }) + await Promise.resolve() + await Promise.resolve() + + expect(pushPreviewRoute).toHaveBeenCalledWith({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: expect.objectContaining({ + hostId: 'host-1', + worktreeId: 'wt-2', + source: 'worktree', + relativePath: 'docs/readme.md' + }) + }) + expect(client.sendRequest).not.toHaveBeenCalledWith('files.open', expect.anything()) + }) + it('opens worktree-contained line references through the preview route', async () => { const client = createClient([ ok({ @@ -154,7 +204,7 @@ describe('openMobileTerminalFileTap', () => { const pushPreviewRoute = vi.fn() const triggerOpenFeedback = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -208,7 +258,7 @@ describe('openMobileTerminalFileTap', () => { ]) const openBrowser = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -249,7 +299,7 @@ describe('openMobileTerminalFileTap', () => { ok({ opened: true }) ]) - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -296,7 +346,7 @@ describe('openMobileTerminalFileTap', () => { ]) const openBrowser = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -337,7 +387,7 @@ describe('openMobileTerminalFileTap', () => { let activeTerminalHandle: string | null = 'terminal-1' const pushPreviewRoute = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', @@ -381,6 +431,180 @@ describe('openMobileTerminalFileTap', () => { expect(pushPreviewRoute).not.toHaveBeenCalled() }) + it('reports a failed files.open through onOpenFailed', async () => { + const client = createClient([ + ok({ + worktree: 'wt-1', + relativePath: 'src/index.ts', + absolutePath: '/repo/src/index.ts', + exists: true, + isDirectory: false, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath: 'src/index.ts', + absolutePath: '/repo/src/index.ts' + } + }), + { ok: false, error: { message: 'nope' } } + ]) + const onOpenFailed = vi.fn() + + openMobileFileTap({ + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pathText: 'src/index.ts', + line: null, + column: null, + pushPreviewRoute: vi.fn(), + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: activeTerminalState, + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + onOpenFailed + }) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + + expect(onOpenFailed).toHaveBeenCalledTimes(1) + }) + + it('reports an unsupported file when files.open declines it', async () => { + const client = createClient([ + ok({ + worktree: 'wt-1', + relativePath: 'dist/app.zip', + absolutePath: '/repo/dist/app.zip', + exists: true, + isDirectory: false, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath: 'dist/app.zip', + absolutePath: '/repo/dist/app.zip' + } + }), + ok({ worktree: 'wt-1', relativePath: 'dist/app.zip', kind: 'binary', opened: false }) + ]) + const onOpenFailed = vi.fn() + const scheduleDelayedAction = vi.fn() + + openMobileFileTap({ + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pathText: 'dist/app.zip', + line: null, + column: null, + pushPreviewRoute: vi.fn(), + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: activeTerminalState, + switchSessionTab: vi.fn(), + scheduleDelayedAction, + onOpenFailed + }) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + + expect(onOpenFailed).toHaveBeenCalledTimes(1) + expect(scheduleDelayedAction).not.toHaveBeenCalled() + }) + + it('does not report a stale failure after a newer tap supersedes it', async () => { + const client = createClient([ + ok({ + worktree: 'wt-1', + relativePath: null, + absolutePath: null, + exists: false, + isDirectory: false + }) + ]) + const onOpenFailed = vi.fn() + + openMobileFileTap({ + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pathText: 'gone/missing.ts', + line: null, + column: null, + pushPreviewRoute: vi.fn(), + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: (activated) => ({ + ...activeTerminalState(activated), + latestActivationSeq: 2 + }), + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + onOpenFailed + }) + await Promise.resolve() + await Promise.resolve() + + expect(onOpenFailed).not.toHaveBeenCalled() + }) + + it('does not report a failure when the user left the source tab mid-resolve', async () => { + const client = createClient([ + ok({ + worktree: 'wt-1', + relativePath: 'src/index.ts', + absolutePath: '/repo/src/index.ts', + exists: true, + isDirectory: false, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath: 'src/index.ts', + absolutePath: '/repo/src/index.ts' + } + }) + ]) + const onOpenFailed = vi.fn() + + openMobileFileTap({ + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pathText: 'src/index.ts', + line: null, + column: null, + pushPreviewRoute: vi.fn(), + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: (activated) => ({ + ...activeTerminalState(activated), + activeTerminalHandle: 'terminal-2' + }), + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + onOpenFailed + }) + await Promise.resolve() + await Promise.resolve() + + expect(onOpenFailed).not.toHaveBeenCalled() + }) + it('does not activate a worktree file tab after a newer tap supersedes it', async () => { const client = createClient([ ok({ @@ -402,7 +626,7 @@ describe('openMobileTerminalFileTap', () => { const openedTab = { id: 'tab-2', relativePath: 'src/index.ts' } const switchSessionTab = vi.fn() - openMobileTerminalFileTap({ + openMobileFileTap({ client, hostId: 'host-1', worktreeId: 'wt-1', diff --git a/mobile/src/session/mobile-terminal-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts similarity index 69% rename from mobile/src/session/mobile-terminal-file-tap-open.ts rename to mobile/src/session/mobile-file-tap-open.ts index 31a5c892d75..00b98ce214d 100644 --- a/mobile/src/session/mobile-terminal-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -1,4 +1,7 @@ -import type { RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types' +import type { + RuntimeFileOpenResult, + RuntimeTerminalPathResolution +} from '../../../src/shared/runtime-types' import { filesystemPathToFileUri } from '../../../src/shared/file-uri-path' import { createMobileFilePreviewHref } from '../files/mobile-file-preview-route' import { classifyMobileArtifact } from './mobile-artifact-kind' @@ -6,12 +9,12 @@ import type { RpcClient } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' import { shouldActivateOpenedMobileSessionTab } from './opened-mobile-session-tab' -type TerminalFileTapSessionTab = { +export type FileTapSessionTab = { id: string relativePath?: string } -type OpenMobileTerminalFileTapOptions = { +export type OpenMobileFileTapOptions = { client: Pick hostId: string worktreeId: string @@ -37,19 +40,34 @@ type OpenMobileTerminalFileTapOptions = { } switchSessionTab: (tab: T) => void scheduleDelayedAction: (callback: () => void, delayMs: number) => unknown + /** Invoked when the tap cannot open anything (resolve miss, directory, or a + * failed open). Omitted on surfaces that keep the historical silent miss. */ + onOpenFailed?: () => void } -export function openMobileTerminalFileTap( - options: OpenMobileTerminalFileTapOptions +export function openMobileFileTap( + options: OpenMobileFileTapOptions ): void { - void openMobileTerminalFileTapAsync(options).catch(() => { - // Terminal file taps are best-effort: a failed host resolution should leave - // terminal focus/input untouched, matching the existing silent miss behavior. + void openMobileFileTapAsync(options).catch(() => { + // File taps are best-effort: a failed host resolution should leave terminal + // focus/input untouched. Surfaces that want feedback pass onOpenFailed. + reportOpenFailure(options) }) } -async function openMobileTerminalFileTapAsync( - options: OpenMobileTerminalFileTapOptions +function reportOpenFailure( + options: OpenMobileFileTapOptions +): void { + if ( + options.onOpenFailed && + shouldActivateOpenedMobileSessionTab(options.getActivationState(false)) + ) { + options.onOpenFailed() + } +} + +async function openMobileFileTapAsync( + options: OpenMobileFileTapOptions ): Promise { const worktree = `id:${options.worktreeId}` const response = await options.client.sendRequest( @@ -65,22 +83,29 @@ async function openMobileTerminalFileTapAsync( - options: OpenMobileTerminalFileTapOptions, +function scheduleOpenedWorktreeTabActivation( + options: OpenMobileFileTapOptions, openedPath: string ): void { let activated = false diff --git a/mobile/src/session/mobile-native-chat-open-file.test.ts b/mobile/src/session/mobile-native-chat-open-file.test.ts index 2f8ceb936a7..c79878e92d1 100644 --- a/mobile/src/session/mobile-native-chat-open-file.test.ts +++ b/mobile/src/session/mobile-native-chat-open-file.test.ts @@ -1,93 +1,153 @@ import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc-client' -import { - openMobileNativeChatFile, - resolveMobileNativeChatWorktreePath -} from './mobile-native-chat-open-file' +import { openMobileNativeChatFileTap } from './mobile-native-chat-open-file' -describe('resolveMobileNativeChatWorktreePath', () => { - it('resolves an absolute tool path to a worktree-relative open target', async () => { - const sendRequest = vi.fn().mockResolvedValue({ - ok: true, - result: { - exists: true, - isDirectory: false, - openTarget: { kind: 'worktree-file', relativePath: 'src/app.ts' } - } - }) - await expect( - resolveMobileNativeChatWorktreePath({ - client: { sendRequest } as unknown as RpcClient, - worktreeId: 'worktree', - pathText: '/repo/src/app.ts', - terminal: 'terminal' - }) - ).resolves.toBe('src/app.ts') - expect(sendRequest).toHaveBeenCalledWith('files.resolveTerminalPath', { - worktree: 'id:worktree', - pathText: '/repo/src/app.ts', - terminal: 'terminal' - }) +function ok(result: unknown) { + return { ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +function activationState(activated: boolean) { + return { + activated, + activationSeq: 1, + latestActivationSeq: 1, + sourceTerminalHandle: 'terminal-1', + activeTerminalHandle: 'terminal-1', + activeTabType: 'terminal' + } +} + +function baseOptions(client: { sendRequest: ReturnType }) { + return { + client, + hostId: 'host-1', + worktreeId: 'wt-1', + pushPreviewRoute: vi.fn(), + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: activationState, + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + onOpenFailed: vi.fn() + } +} + +function worktreeFileResolution(relativePath: string) { + return ok({ + worktree: 'wt-1', + relativePath, + absolutePath: `/repo/${relativePath}`, + exists: true, + isDirectory: false, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath, + absolutePath: `/repo/${relativePath}` + } + }) +} + +describe('openMobileNativeChatFileTap', () => { + it('resolves against the worktree root: no terminal handle and no cwd', async () => { + const sendRequest = vi.fn(async () => worktreeFileResolution('src/app.ts')) + const options = baseOptions({ sendRequest }) + + openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) + await Promise.resolve() + + expect(sendRequest).toHaveBeenCalledWith( + 'files.resolveTerminalPath', + { worktree: 'id:wt-1', pathText: 'src/app.ts' }, + { timeoutMs: 10_000 } + ) }) - it('opens only the resolved worktree-relative target', async () => { - const sendRequest = vi - .fn() - .mockResolvedValueOnce({ - ok: true, - result: { - exists: true, - isDirectory: false, - openTarget: { kind: 'worktree-file', relativePath: 'src/app.ts' } - } + it('parses a :line:col citation and opens the mobile preview route', async () => { + const sendRequest = vi.fn(async () => worktreeFileResolution('src/app.ts')) + const options = baseOptions({ sendRequest }) + + openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts:120:7' }) + await Promise.resolve() + + expect(sendRequest).toHaveBeenCalledWith( + 'files.resolveTerminalPath', + { worktree: 'id:wt-1', pathText: 'src/app.ts' }, + { timeoutMs: 10_000 } + ) + expect(options.triggerOpenFeedback).toHaveBeenCalledTimes(1) + expect(options.pushPreviewRoute).toHaveBeenCalledWith({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: expect.objectContaining({ + source: 'worktree', + relativePath: 'src/app.ts', + line: '120', + column: '7' }) - .mockResolvedValueOnce({ ok: true, result: {} }) - - await openMobileNativeChatFile({ - client: { sendRequest } as unknown as RpcClient, - worktreeId: 'worktree', - pathText: '../repo/src/app.ts', - terminal: 'terminal' - }) - - expect(sendRequest).toHaveBeenLastCalledWith('files.open', { - worktree: 'id:worktree', - relativePath: 'src/app.ts' }) + expect(options.onOpenFailed).not.toHaveBeenCalled() }) - it('resolves null when the resolve request rejects', async () => { - const sendRequest = vi.fn().mockRejectedValue(new Error('Request timed out')) - await expect( - resolveMobileNativeChatWorktreePath({ - client: { sendRequest } as unknown as RpcClient, - worktreeId: 'worktree', - pathText: 'src/app.ts', - terminal: null + it('surfaces a resolve miss instead of a silent no-op', async () => { + const sendRequest = vi.fn(async () => + ok({ + worktree: 'wt-1', + relativePath: null, + absolutePath: null, + exists: false, + isDirectory: false }) - ).resolves.toBeNull() + ) + const options = baseOptions({ sendRequest }) + + openMobileNativeChatFileTap({ ...options, pathText: 'gone/missing.ts' }) + await Promise.resolve() + await Promise.resolve() + + expect(options.onOpenFailed).toHaveBeenCalledTimes(1) + expect(options.pushPreviewRoute).not.toHaveBeenCalled() + expect(options.triggerOpenFeedback).not.toHaveBeenCalled() }) - it('does not reject when the open request fails', async () => { - const sendRequest = vi - .fn() - .mockResolvedValueOnce({ - ok: true, - result: { - exists: true, - isDirectory: false, - openTarget: { kind: 'worktree-file', relativePath: 'src/app.ts' } - } - }) - .mockRejectedValueOnce(new Error('connection interrupted')) + it('surfaces a rejected resolve request', async () => { + const sendRequest = vi.fn(async () => { + throw new Error('Request timed out') + }) + const options = baseOptions({ sendRequest }) - await expect( - openMobileNativeChatFile({ - client: { sendRequest } as unknown as RpcClient, - worktreeId: 'worktree', - pathText: 'src/app.ts', - terminal: null - }) - ).resolves.toBeUndefined() + openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) + await Promise.resolve() + await Promise.resolve() + + expect(options.onOpenFailed).toHaveBeenCalledTimes(1) + }) + + it('opens a plain path through files.open with tab activation', async () => { + const responses: unknown[] = [worktreeFileResolution('src/app.ts'), ok({ opened: true })] + const sendRequest = vi.fn(async () => responses.shift()) + const openedTab = { id: 'tab-2', relativePath: 'src/app.ts' } + const switchSessionTab = vi.fn() + const options = { + ...baseOptions({ sendRequest }), + getSessionTabs: () => [openedTab], + getActiveSessionTabId: () => 'terminal-tab', + switchSessionTab, + scheduleDelayedAction: vi.fn((callback: () => void) => callback()) + } + + openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) + await Promise.resolve() + await Promise.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(sendRequest).toHaveBeenCalledWith( + 'files.open', + { worktree: 'id:wt-1', relativePath: 'src/app.ts' }, + { timeoutMs: 15_000 } + ) + expect(switchSessionTab).toHaveBeenCalledWith(openedTab) + expect(options.onOpenFailed).not.toHaveBeenCalled() }) }) diff --git a/mobile/src/session/mobile-native-chat-open-file.ts b/mobile/src/session/mobile-native-chat-open-file.ts index 44d6d23c066..3de6755b4b3 100644 --- a/mobile/src/session/mobile-native-chat-open-file.ts +++ b/mobile/src/session/mobile-native-chat-open-file.ts @@ -1,51 +1,30 @@ -import type { RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types' -import type { RpcClient } from '../transport/rpc-client' +import { splitFilePathLineSuffix } from '../components/markdown-file-path-detection' +import { + openMobileFileTap, + type FileTapSessionTab, + type OpenMobileFileTapOptions +} from './mobile-file-tap-open' -export async function resolveMobileNativeChatWorktreePath(args: { - client: RpcClient - worktreeId: string - pathText: string - terminal: string | null -}): Promise { - try { - const response = await args.client.sendRequest('files.resolveTerminalPath', { - worktree: `id:${args.worktreeId}`, - pathText: args.pathText, - ...(args.terminal ? { terminal: args.terminal } : {}) - }) - if (!response.ok) { - return null - } - const resolved = response.result as RuntimeTerminalPathResolution - if (!resolved.exists || resolved.isDirectory) { - return null - } - return resolved.openTarget?.kind === 'worktree-file' - ? resolved.openTarget.relativePath - : (resolved.relativePath ?? null) - } catch { - // Callers fire-and-forget file opens; a disconnect/timeout must not become - // an unhandled rejection. - return null - } -} +export type OpenMobileNativeChatFileTapOptions = Omit< + OpenMobileFileTapOptions, + 'terminalHandle' | 'cwd' | 'line' | 'column' +> -export async function openMobileNativeChatFile(args: { - client: RpcClient - worktreeId: string - pathText: string - terminal: string | null -}): Promise { - const relativePath = await resolveMobileNativeChatWorktreePath(args) - if (relativePath) { - try { - await args.client.sendRequest('files.open', { - worktree: `id:${args.worktreeId}`, - relativePath - }) - } catch { - // Best-effort open; failures surface as a no-op rather than an - // unhandled rejection. - } - } +/** + * Open a file reference tapped in native chat: same haptic / preview-route / + * tab-activation flow as terminal taps, but chat paths are worktree-root + * relative (or absolute), so resolution deliberately passes no terminal handle + * and no cwd — a terminal's live cwd (e.g. `/mobile`) would misplace + * them. Agent-style `path:line(:col)` citations carry their location through. + */ +export function openMobileNativeChatFileTap( + options: OpenMobileNativeChatFileTapOptions +): void { + const { path, line, column } = splitFilePathLineSuffix(options.pathText) + openMobileFileTap({ + ...options, + pathText: path, + line, + column + }) } diff --git a/mobile/src/session/mobile-native-chat-permission-send.test.ts b/mobile/src/session/mobile-native-chat-permission-send.test.ts index 1b595683112..253f8c8b85a 100644 --- a/mobile/src/session/mobile-native-chat-permission-send.test.ts +++ b/mobile/src/session/mobile-native-chat-permission-send.test.ts @@ -13,6 +13,11 @@ import { markMobileNativeChatInputStale, resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite, + resetMobileNativeChatTerminalWritesForTests +} from './mobile-native-chat-terminal-write-lock' describe('sendMobileNativeChatPermissionResponse', () => { it('writes an approval as raw bytes without appending Return', async () => { @@ -64,6 +69,7 @@ describe('useMobileNativeChatPermissionSend', () => { beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true resetMobileNativeChatStaleInputForTests() + resetMobileNativeChatTerminalWritesForTests() }) afterEach(() => { @@ -102,4 +108,42 @@ describe('useMobileNativeChatPermissionSend', () => { expect(sendRequest.mock.calls[0]?.[1]).toMatchObject({ text: '1', enter: false }) expect(isMobileNativeChatInputStale('terminal')).toBe(true) }) + + it('rejects a choice while another composed write holds the terminal, then recovers', async () => { + const onSendError = vi.fn() + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { send: { handle: 'terminal', accepted: true, bytesWritten: 1 } } + }) + function Harness(): null { + respond = useMobileNativeChatPermissionSend({ + client: { sendRequest } as unknown as RpcClient, + enabled: true, + handleRef: { current: 'terminal' }, + deviceTokenRef: { current: null }, + onSendError + }) + return null + } + act(() => { + renderer = create(createElement(Harness)) + }) + + // An image paste sequence is mid-flight into the same PTY: the choice + // keystroke must not interleave into it. + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(true) + await act(async () => { + await expect(respond?.('1')).resolves.toBe(false) + }) + expect(sendRequest).not.toHaveBeenCalled() + expect(onSendError).toHaveBeenCalledWith('Response not sent') + + releaseMobileNativeChatTerminalWrite('terminal') + await act(async () => { + await expect(respond?.('1')).resolves.toBe(true) + }) + // The choice released its own hold on the way out. + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(true) + releaseMobileNativeChatTerminalWrite('terminal') + }) }) diff --git a/mobile/src/session/mobile-native-chat-permission-send.ts b/mobile/src/session/mobile-native-chat-permission-send.ts index b06ff88fe48..7f58b0ab44e 100644 --- a/mobile/src/session/mobile-native-chat-permission-send.ts +++ b/mobile/src/session/mobile-native-chat-permission-send.ts @@ -4,6 +4,10 @@ import { sendMobileNativeChatMessageWithOutcome, type MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite +} from './mobile-native-chat-terminal-write-lock' export function sendMobileNativeChatPermissionResponse(args: { client: RpcClient @@ -36,15 +40,26 @@ export function useMobileNativeChatPermissionSend(args: { args.onSendError('Response not sent (disconnected)') return false } + // A choice keystroke must not interleave into a mid-flight composed write + // (image paste, paced answer) on the same PTY. + if (!acquireMobileNativeChatTerminalWrite(terminal)) { + args.onSendError('Response not sent') + return false + } // No stale-input heal here (unlike the text/ask sends): a choice is an // `enter: false` key for an active overlay that swallows the clear, so it // would consume the marker still protecting the next real message. - const outcome = await sendMobileNativeChatPermissionResponse({ - client: args.client, - terminal, - deviceToken: args.deviceTokenRef.current, - text - }) + let outcome: MobileNativeChatSendOutcome + try { + outcome = await sendMobileNativeChatPermissionResponse({ + client: args.client, + terminal, + deviceToken: args.deviceTokenRef.current, + text + }) + } finally { + releaseMobileNativeChatTerminalWrite(terminal) + } if (outcome === 'unknown') { // Why: the response may have been delivered (ack lost / path cutover) — // a definite "not sent" would invite a double answer. diff --git a/mobile/src/session/mobile-native-chat-render-data.test.ts b/mobile/src/session/mobile-native-chat-render-data.test.ts index 4dabff8f600..b4a273d31ca 100644 --- a/mobile/src/session/mobile-native-chat-render-data.test.ts +++ b/mobile/src/session/mobile-native-chat-render-data.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' import { - buildMobileNativeChatData, + buildMobileNativeChatTransientData, + foldMobileNativeChatMessages, mobileNativeChatEmptyState } from './mobile-native-chat-render-data' @@ -50,13 +51,22 @@ describe('mobileNativeChatEmptyState', () => { }) }) -describe('buildMobileNativeChatData', () => { +/** Mirrors the view: fold the raw transcript, then assemble the list. */ +function build( + messages: NativeChatMessage[], + streaming: string | null, + pending: Parameters[0]['pending'] +): NativeChatMessage[] { + return buildMobileNativeChatTransientData({ + folded: foldMobileNativeChatMessages(messages), + streaming, + pending + }).data +} + +describe('buildMobileNativeChatTransientData', () => { it('appends pending optimistic messages at the tail as user turns', () => { - const { data } = buildMobileNativeChatData({ - messages: [assistant('a1', 'hello')], - streamingText: undefined, - pending: [{ id: 'p1', text: 'queued' }] - }) + const data = build([assistant('a1', 'hello')], null, [{ id: 'p1', text: 'queued' }]) const last = data[data.length - 1] expect(last.id).toBe('p1') expect(last.role).toBe('user') @@ -64,10 +74,9 @@ describe('buildMobileNativeChatData', () => { }) it('renders a pending send with images as text followed by image-ref thumbnails', () => { - const { data } = buildMobileNativeChatData({ - messages: [], - pending: [{ id: 'p1', text: 'look', images: ['file:///a.jpg', 'file:///b.jpg'] }] - }) + const data = build([], null, [ + { id: 'p1', text: 'look', images: ['file:///a.jpg', 'file:///b.jpg'] } + ]) const last = data[data.length - 1] expect(last.role).toBe('user') expect(last.blocks).toEqual([ @@ -78,10 +87,7 @@ describe('buildMobileNativeChatData', () => { }) it('renders an image-only pending send (no text) as just the thumbnail', () => { - const { data } = buildMobileNativeChatData({ - messages: [], - pending: [{ id: 'p1', text: '', images: ['file:///a.jpg'] }] - }) + const data = build([], null, [{ id: 'p1', text: '', images: ['file:///a.jpg'] }]) expect(data[data.length - 1].blocks).toEqual([{ type: 'image-ref', url: 'file:///a.jpg' }]) }) @@ -89,14 +95,15 @@ describe('buildMobileNativeChatData', () => { // Claude records an attached image as `[Image: source: /path]` + an // `[Image #1] `-prefixed caption turn; the fold must merge them into one // user turn with an image-ref block instead of showing raw marker text. - const { data } = buildMobileNativeChatData({ - messages: [ + const data = build( + [ user('u1', '[Image: source: /tmp/a.png]'), user('u2', '[Image #1] look at this'), assistant('a1', 'nice photo') ], - pending: [] - }) + null, + [] + ) const merged = data.find((message) => message.role === 'user') expect(merged?.blocks).toEqual([ { type: 'image-ref', path: '/tmp/a.png' }, @@ -105,49 +112,20 @@ describe('buildMobileNativeChatData', () => { }) it('renders a lone image marker turn (no caption) as an image-ref block', () => { - const { data } = buildMobileNativeChatData({ - messages: [user('u1', '[Image: source: /tmp/a.png]')], - pending: [] - }) + const data = build([user('u1', '[Image: source: /tmp/a.png]')], null, []) expect(data[0]?.blocks).toEqual([{ type: 'image-ref', path: '/tmp/a.png' }]) }) - it('adds a synthetic streaming bubble while the partial text leads the transcript', () => { - const { streaming, data } = buildMobileNativeChatData({ - messages: [user('u1', 'hi')], - streamingText: 'thinking out loud', - pending: [] - }) - expect(streaming).toBe('thinking out loud') - expect(data.some((m) => m.id === 'streaming')).toBe(true) + it('appends a synthetic bubble for gated streaming text, between transcript and pending', () => { + // Whether text streams at all is the gate's call + // (`mobile-native-chat-streaming-gate.test.ts`); this only places it. + const data = build([user('u1', 'hi')], 'thinking out loud', [{ id: 'p1', text: 'queued' }]) + expect(data.map((message) => message.id)).toEqual(['u1', 'streaming', 'p1']) + expect(data[1].blocks).toEqual([{ type: 'text', text: 'thinking out loud' }]) }) - it('shows a short new streaming reply even after a longer previous turn', () => { - // The last folded turn is a long completed reply; a short new stream must not - // be suppressed just for being shorter than the prior turn. - const { streaming, data } = buildMobileNativeChatData({ - messages: [assistant('a1', 'This is a long completed previous answer that ran on a while')], - streamingText: 'Ok', - pending: [] - }) - expect(streaming).toBe('Ok') - expect(data.some((m) => m.id === 'streaming')).toBe(true) - }) - - it('drops the streaming bubble once the real assistant turn already contains it', () => { - const { streaming, data } = buildMobileNativeChatData({ - messages: [assistant('a1', 'done answer')], - streamingText: 'done', - pending: [] - }) - expect(streaming).toBeNull() - expect(data.some((m) => m.id === 'streaming')).toBe(false) - }) - - it('returns no streaming bubble for empty/whitespace streaming text', () => { - expect( - buildMobileNativeChatData({ messages: [], streamingText: ' ', pending: [] }).streaming - ).toBeNull() - expect(buildMobileNativeChatData({ messages: [], pending: [] }).streaming).toBeNull() + it('omits the bubble when the gate withheld the streaming text', () => { + const data = build([assistant('a1', 'done answer')], null, []) + expect(data.some((message) => message.id === 'streaming')).toBe(false) }) }) diff --git a/mobile/src/session/mobile-native-chat-render-data.ts b/mobile/src/session/mobile-native-chat-render-data.ts index 068050fc43d..e11b9ac56f4 100644 --- a/mobile/src/session/mobile-native-chat-render-data.ts +++ b/mobile/src/session/mobile-native-chat-render-data.ts @@ -43,41 +43,25 @@ export type MobileNativeChatPendingItem = { images?: string[] } -/** Derive the list data from the raw transcript: fold tool turns into the - * assistant turn, optionally append a synthetic streaming bubble, then the - * route-owned optimistic "queued" messages at the tail. Returns the - * intermediate `folded`/`streaming` so the caller can memoize on them. */ -export function buildMobileNativeChatData({ - messages, - streamingText, - pending -}: { - messages: NativeChatMessage[] - streamingText?: string - pending: MobileNativeChatPendingItem[] -}): { folded: NativeChatMessage[]; streaming: string | null; data: NativeChatMessage[] } { - const folded = foldMobileNativeChatMessages(messages) - return buildMobileNativeChatTransientData({ folded, streamingText, pending }) -} - export function foldMobileNativeChatMessages(messages: NativeChatMessage[]): NativeChatMessage[] { // Normalize first (desktop assembler parity): image marker turns fold into // image-ref blocks instead of rendering as raw `[Image: …]` text. return foldToolMessages(stripNoiseMessages(normalizeImageTranscriptMessages(messages))) } +/** Assemble the list data the chat renders: the folded transcript, then a + * synthetic bubble for the streaming text the gate let through, then the + * route-owned optimistic "queued" messages at the tail. */ export function buildMobileNativeChatTransientData({ folded, - streamingText, + streaming, pending }: { folded: NativeChatMessage[] - streamingText?: string + /** Streaming bubble text, already gated by `deriveMobileNativeChatStreaming`. */ + streaming: string | null pending: MobileNativeChatPendingItem[] }): { folded: NativeChatMessage[]; streaming: string | null; data: NativeChatMessage[] } { - // Only show the streaming bubble while its text leads the transcript — once the - // real assistant turn lands with the same text, drop the synthetic one. - const streaming = deriveStreaming(folded, streamingText) const data: NativeChatMessage[] = [ ...folded, ...(streaming @@ -106,26 +90,3 @@ export function buildMobileNativeChatTransientData({ ] return { folded, streaming, data } } - -function deriveStreaming(folded: NativeChatMessage[], streamingText?: string): string | null { - const text = streamingText?.trim() - if (!text) { - return null - } - const last = folded[folded.length - 1] - const lastText = - last?.role === 'assistant' - ? last.blocks - .filter((b) => b.type === 'text') - .map((b) => (b.type === 'text' ? b.text : '')) - .join('') - .trim() - : '' - // Hide the synthetic bubble only once the real turn has landed leading with the - // streamed text. A bare length compare would suppress a short new reply behind a - // longer previous turn; a completed prior turn won't start with the new prefix. - if (lastText.startsWith(text)) { - return null - } - return text -} diff --git a/mobile/src/session/mobile-native-chat-streaming-gate.test.ts b/mobile/src/session/mobile-native-chat-streaming-gate.test.ts new file mode 100644 index 00000000000..312be591ca9 --- /dev/null +++ b/mobile/src/session/mobile-native-chat-streaming-gate.test.ts @@ -0,0 +1,238 @@ +import { describe, expect, it } from 'vitest' +import type { NativeChatMessage } from '../../../src/shared/native-chat-types' +import { + createMobileNativeChatStreamingGate, + deriveMobileNativeChatStreaming, + type MobileNativeChatStreamingGate +} from './mobile-native-chat-streaming-gate' + +function assistant(id: string, text: string): NativeChatMessage { + return { + id, + role: 'assistant', + blocks: [{ type: 'text', text }], + timestamp: 0, + source: 'transcript' + } +} + +/** Run a sequence of (folded, streamingText) ticks through one gate. */ +function run(ticks: { folded: NativeChatMessage[]; text?: string; live?: boolean }[]): { + gate: MobileNativeChatStreamingGate + results: (string | null)[] +} { + let gate = createMobileNativeChatStreamingGate() + const results: (string | null)[] = [] + for (const tick of ticks) { + const step = deriveMobileNativeChatStreaming(gate, tick.folded, tick.text, { + streamLive: tick.live + }) + gate = step.gate + results.push(step.streaming) + } + return { gate, results } +} + +describe('deriveMobileNativeChatStreaming', () => { + it('shows a genuine reply that repeats the previous turn as a prefix', () => { + const prior = [assistant('a1', 'The tests pass.')] + const { results } = run([ + { folded: prior }, // idle tick anchors the pre-stream tail + { folded: prior, text: 'The' }, + { folded: prior, text: 'The tests' }, + { folded: prior, text: 'The tests pass.' } + ]) + expect(results).toEqual([null, 'The', 'The tests', 'The tests pass.']) + }) + + it('hides the bubble once the real turn lands leading with the streamed text', () => { + const prior = [assistant('a1', 'earlier turn')] + const landed = [...prior, assistant('a2', 'fresh answer with a tail')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'fresh answer' }, + { folded: landed, text: 'fresh answer' } + ]) + expect(results).toEqual([null, 'fresh answer', null]) + }) + + it('suppresses an identical repeated reply once its own turn lands', () => { + const prior = [assistant('a1', 'Done.')] + const landed = [...prior, assistant('a2', 'Done.')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'Done.' }, // repeated-prefix reply stays visible + { folded: landed, text: 'Done.' } // its own turn landed — hide + ]) + expect(results).toEqual([null, 'Done.', null]) + }) + + it('keeps hiding for the rest of a segment after the turn lands', () => { + const prior = [assistant('a1', 'earlier')] + const landed = [...prior, assistant('a2', 'answer body')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'answer' }, + { folded: landed, text: 'answer' }, + { folded: landed, text: 'answer bo' } + ]) + expect(results).toEqual([null, 'answer', null, null]) + }) + + it('keeps the segment baseline through textless ticks while the turn is live', () => { + // Chat is hidden mid-stream: the transcript unsubscribes and the status + // stops reaching the gate, but the turn has not ended. Coming back, the + // stream text returns before the re-read transcript does. + const prior = [assistant('a1', 'Done.')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'Done.', live: true }, + { folded: [], live: true }, + { folded: [], text: 'Done.', live: true }, + { folded: prior, text: 'Done.', live: true } + ]) + expect(results).toEqual([null, 'Done.', null, 'Done.', 'Done.']) + }) + + it('still hides after a hidden gap once the reply landed as its own turn', () => { + const prior = [assistant('a1', 'Done.')] + const landed = [...prior, assistant('a2', 'Done.')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'Done.', live: true }, + { folded: [], live: true }, + { folded: landed, text: 'Done.', live: true } + ]) + expect(results).toEqual([null, 'Done.', null, null]) + }) + + it('hides a reply whose own turn landed before its status text arrived', () => { + // The pane stays `working` past the reply (a subagent or a background task + // is still live), and the transcript push beats the throttled status text. + // Anchoring on that textless tick would adopt the reply as pre-stream + // history and render it a second time as a bubble. + const prior = [assistant('a1', 'Done.')] + const landed = [...prior, assistant('a2', 'Done.')] + const { results } = run([ + { folded: prior, live: true }, + { folded: landed, live: true }, + { folded: landed, text: 'Done.', live: true }, + { folded: landed, text: 'Done.', live: true } + ]) + expect(results).toEqual([null, null, null, null]) + }) + + it('keeps the pre-stream baseline across a hidden gap taken between turns', () => { + // Peeking at the terminal while idle tears the transcript down to empty. An + // empty tail is not history: adopting it strands the baseline and swallows + // the repeated-prefix reply that arrives next. + const prior = [assistant('a1', 'Done.')] + const { results } = run([ + { folded: prior }, + { folded: [] }, + { folded: [], live: true }, + { folded: prior, text: 'Done.', live: true } + ]) + expect(results).toEqual([null, null, null, 'Done.']) + }) + + it('anchors on the first tail it sees when mounted mid-turn', () => { + // Opening a workspace whose agent is already working: that first textless + // tick is the only pre-stream history the gate will ever get. + const prior = [assistant('a1', 'Done.')] + const { results } = run([ + { folded: prior, live: true }, + { folded: prior, text: 'Done.', live: true } + ]) + expect(results).toEqual([null, 'Done.']) + }) + + it('anchors on a textless tick once the turn ends', () => { + const prior = [assistant('a1', 'first answer')] + const landed = [...prior, assistant('a2', 'second answer')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'second answer', live: true }, + { folded: landed }, + { folded: landed, text: 'second answer', live: true } + ]) + expect(results).toEqual([null, 'second answer', null, 'second answer']) + }) + + it('does not treat the previous turn as a segment start after re-anchoring', () => { + // The textless anchor clears the remembered text too. Keeping it would read + // the next turn's opener as a new segment, re-anchor onto the reply that + // just landed, and render it a second time as a bubble. + const prior = [assistant('a1', 'context')] + const firstLanded = [...prior, assistant('a2', 'Alpha done')] + const secondLanded = [...firstLanded, assistant('a3', 'Beta reply')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'Alpha', live: true }, + { folded: firstLanded }, // turn ended — re-anchor onto a2 + { folded: secondLanded, text: 'Beta', live: true } // a3 already landed + ]) + expect(results).toEqual([null, 'Alpha', null, null]) + }) + + it('re-anchors when a new reply part replaces the stream mid-turn', () => { + const prior = [assistant('a1', 'context')] + const partOneLanded = [...prior, assistant('a2', 'part one full text')] + const { results } = run([ + { folded: prior }, + { folded: prior, text: 'part one' }, + { folded: partOneLanded, text: 'part one' }, // caught up — hide + // Part two is not an extension of part one: new segment, new baseline. + { folded: partOneLanded, text: 'part' } + ]) + expect(results).toEqual([null, 'part one', null, 'part']) + }) + + it('falls back to suppress-on-prefix when text arrives on the first tick', () => { + // No tail ever observed before the text: a duplicate bubble is worse than + // briefly hiding a mount-coincident repeated reply. + const landed = [assistant('a1', 'flushed part still streaming in status')] + const { results } = run([{ folded: landed, text: 'flushed part' }]) + expect(results).toEqual([null]) + }) + + it('is idempotent for a repeated tick', () => { + const prior = [assistant('a1', 'The tests pass.')] + const first = run([{ folded: prior }, { folded: prior, text: 'The tests' }]) + const again = deriveMobileNativeChatStreaming(first.gate, prior, 'The tests') + expect(again.streaming).toBe('The tests') + expect(again.gate).toBe(first.gate) + }) + + it('drops a prior chat baseline when the stream identity changes', () => { + // The other chat's tail must not license showing a bubble here — a swapped + // scope resets to the mid-stream fallback rather than reusing its baseline. + const repeatedId = [assistant('a1', 'new answer landed')] + let gate = createMobileNativeChatStreamingGate('tab-a') + gate = deriveMobileNativeChatStreaming(gate, repeatedId, undefined, { scopeKey: 'tab-a' }).gate + + const switched = deriveMobileNativeChatStreaming(gate, repeatedId, 'new answer', { + scopeKey: 'tab-b' + }) + + expect(switched.streaming).toBeNull() + expect(switched.gate.scopeKey).toBe('tab-b') + expect(switched.gate.baselineTailId).toBeNull() + }) + + it('returns null for empty or whitespace streaming text', () => { + const prior = [assistant('a1', 'x')] + expect(run([{ folded: prior, text: ' ' }]).results).toEqual([null]) + expect(run([{ folded: prior }]).results).toEqual([null]) + }) + + it('shows the first reply of an empty chat and hides it once the turn lands', () => { + const landed = [assistant('a1', 'Hello there')] + const { results } = run([ + { folded: [] }, + { folded: [], text: 'Hello' }, + { folded: landed, text: 'Hello' } + ]) + expect(results).toEqual([null, 'Hello', null]) + }) +}) diff --git a/mobile/src/session/mobile-native-chat-streaming-gate.ts b/mobile/src/session/mobile-native-chat-streaming-gate.ts new file mode 100644 index 00000000000..a857803214c --- /dev/null +++ b/mobile/src/session/mobile-native-chat-streaming-gate.ts @@ -0,0 +1,93 @@ +import type { NativeChatMessage } from '../../../src/shared/native-chat-types' + +/** Decides whether the live streaming preview should render as a synthetic + * bubble. Text alone can't tell "the transcript caught up with this stream" + * from "a new reply happens to repeat the previous turn's prefix" — the old + * prefix test swallowed genuine repeated-prefix replies. The gate keeps the + * transcript tail observed when the current stream segment began: the bubble + * hides only when the tail MOVED during the segment and leads with the + * streamed text (the real turn landed), never for an older identical turn. */ +export type MobileNativeChatStreamingGate = { + /** Chat/session identity this baseline belongs to. */ + scopeKey: string | null + /** Streamed text seen on the previous tick ('' while idle). */ + prevText: string + /** Folded tail message id when the current segment began; null while the + * gate has never observed a transcript tail (text arrived on its very first + * tick), where the legacy suppress-on-prefix rule applies. */ + baselineTailId: string | null +} + +export function createMobileNativeChatStreamingGate( + scopeKey: string | null = null +): MobileNativeChatStreamingGate { + return { scopeKey, prevText: '', baselineTailId: null } +} + +function assistantTailText(tail: NativeChatMessage | undefined): string { + if (!tail || tail.role !== 'assistant') { + return '' + } + return tail.blocks + .filter((block) => block.type === 'text') + .map((block) => (block.type === 'text' ? block.text : '')) + .join('') + .trim() +} + +// Reuses the incoming gate object when nothing moved, so a caller can detect +// "no change" by reference (and a render-time state adjustment can settle). +function advanceGate( + gate: MobileNativeChatStreamingGate, + prevText: string, + baselineTailId: string | null +): MobileNativeChatStreamingGate { + return gate.prevText === prevText && gate.baselineTailId === baselineTailId + ? gate + : { ...gate, prevText, baselineTailId } +} + +/** Advance the gate one tick and derive the visible streaming text (null hides + * the bubble). Pure and idempotent for a repeated (text, tail) pair, so a + * re-render without new data cannot flip the decision. */ +export function deriveMobileNativeChatStreaming( + gate: MobileNativeChatStreamingGate, + folded: readonly NativeChatMessage[], + streamingText: string | undefined, + options: { + scopeKey?: string | null + /** Whether the agent is still mid-turn. A textless tick then means "no + * observation this render", not "the stream ended". */ + streamLive?: boolean + } = {} +): { gate: MobileNativeChatStreamingGate; streaming: string | null } { + const scopeKey = options.scopeKey === undefined ? gate.scopeKey : options.scopeKey + const scopedGate = + gate.scopeKey === scopeKey ? gate : createMobileNativeChatStreamingGate(scopeKey) + const text = streamingText?.trim() ?? '' + const tail = folded.at(-1) + const tailId = tail?.id ?? null + if (!text) { + // Only a textless tick that carries a real tail and is outside a live turn + // is trustworthy pre-stream history. Mid-turn gaps (a tool call, a throttle + // lull, the transcript landing the reply before its status text) would + // otherwise adopt that reply as history and render it a second time as a + // bubble; a torn-down transcript carries no tail at all. The exception is a + // gate that has never anchored — mounted mid-turn, the first real tail it + // sees is the best pre-stream history it will ever get. + const canAnchor = tailId !== null && (!options.streamLive || scopedGate.baselineTailId === null) + return { gate: canAnchor ? advanceGate(scopedGate, '', tailId) : scopedGate, streaming: null } + } + // A stream that is not an extension of the previous tick is a new segment + // (next reply part); re-anchor to the tail that predates it. + const segmentStart = scopedGate.prevText !== '' && !text.startsWith(scopedGate.prevText) + const baselineTailId = segmentStart ? tailId : scopedGate.baselineTailId + const tailLeadsWithStream = assistantTailText(tail).startsWith(text) + // A null baseline (text on the very first tick, no tail ever seen) is unequal + // to every real tail id, so this degrades to the legacy suppress-on-prefix rule. + const caughtUp = tailLeadsWithStream && tailId !== baselineTailId + return { + gate: advanceGate(scopedGate, text, baselineTailId), + streaming: caughtUp ? null : text + } +} diff --git a/mobile/src/session/mobile-native-chat-terminal-write-lock.test.ts b/mobile/src/session/mobile-native-chat-terminal-write-lock.test.ts new file mode 100644 index 00000000000..c15ce3c826e --- /dev/null +++ b/mobile/src/session/mobile-native-chat-terminal-write-lock.test.ts @@ -0,0 +1,20 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite, + resetMobileNativeChatTerminalWritesForTests +} from './mobile-native-chat-terminal-write-lock' + +describe('mobile-native-chat-terminal-write-lock', () => { + afterEach(resetMobileNativeChatTerminalWritesForTests) + + it('allows composed writes on different terminals to proceed concurrently', () => { + expect(acquireMobileNativeChatTerminalWrite('terminal-a')).toBe(true) + + expect(acquireMobileNativeChatTerminalWrite('terminal-b')).toBe(true) + expect(acquireMobileNativeChatTerminalWrite('terminal-a')).toBe(false) + + releaseMobileNativeChatTerminalWrite('terminal-a') + releaseMobileNativeChatTerminalWrite('terminal-b') + }) +}) diff --git a/mobile/src/session/mobile-native-chat-terminal-write-lock.ts b/mobile/src/session/mobile-native-chat-terminal-write-lock.ts new file mode 100644 index 00000000000..5624a384ed3 --- /dev/null +++ b/mobile/src/session/mobile-native-chat-terminal-write-lock.ts @@ -0,0 +1,25 @@ +// Serializes composed native-chat write sequences (clear/paste/settle/submit, +// paced answer keystrokes) per HOST terminal. Two concurrent sequences into one +// PTY interleave their bytes; a second sender must be rejected up front, not +// woven in. Module scope for the same reason as the stale-input marker: the +// terminal outlives any one screen, and independent hooks share the same PTY. +const writeInFlightTerminals = new Set() + +/** Claim the terminal for one composed write sequence. False = another + * sequence is mid-flight; the caller must reject its send. */ +export function acquireMobileNativeChatTerminalWrite(terminal: string): boolean { + if (writeInFlightTerminals.has(terminal)) { + return false + } + writeInFlightTerminals.add(terminal) + return true +} + +export function releaseMobileNativeChatTerminalWrite(terminal: string): void { + writeInFlightTerminals.delete(terminal) +} + +/** Test-only: module scope outlives a single test's hooks. */ +export function resetMobileNativeChatTerminalWritesForTests(): void { + writeInFlightTerminals.clear() +} diff --git a/mobile/src/session/mobile-terminal-diagnostics.ts b/mobile/src/session/mobile-terminal-diagnostics.ts index 8695928ed03..6ee636fb9f4 100644 --- a/mobile/src/session/mobile-terminal-diagnostics.ts +++ b/mobile/src/session/mobile-terminal-diagnostics.ts @@ -141,12 +141,35 @@ export class MobileTerminalDiagnostics { }) } - streamResubscribing(handle: string, seq: number, dims: { cols: number; rows: number }): void { + streamResubscribing( + handle: string, + seq: number, + dims: { cols: number; rows: number }, + attempt: number, + delayMs: number + ): void { logMobileTerminalDiagnostic('stream-resubscribe-for-viewport', { handle: shortenMobileTerminalDiagnosticId(handle), seq, cols: dims.cols, - rows: dims.rows + rows: dims.rows, + attempt, + delayMs + }) + } + + streamResubscribeHeld(handle: string, seq: number): void { + logMobileTerminalDiagnostic('stream-resubscribe-held-absent-dims', { + handle: shortenMobileTerminalDiagnosticId(handle), + seq + }) + } + + streamResubscribeExhausted(handle: string, seq: number, attempts: number): void { + logMobileTerminalDiagnostic('stream-resubscribe-exhausted', { + handle: shortenMobileTerminalDiagnosticId(handle), + seq, + attempts }) } diff --git a/mobile/src/session/mobile-terminal-viewport-resubscribe.test.ts b/mobile/src/session/mobile-terminal-viewport-resubscribe.test.ts new file mode 100644 index 00000000000..35aac89f6f8 --- /dev/null +++ b/mobile/src/session/mobile-terminal-viewport-resubscribe.test.ts @@ -0,0 +1,472 @@ +import { describe, expect, it, vi } from 'vitest' +import { + MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS, + TerminalViewportResubscribeBudget, + readTerminalViewportDims, + resolveTerminalViewportResubscribe, + runTerminalViewportFitPass, + shouldResubscribeAfterViewportMeasure, + type TerminalViewportFitPassArgs +} from './mobile-terminal-viewport-resubscribe' + +const PHONE = { cols: 40, rows: 50 } + +describe('readTerminalViewportDims', () => { + it('accepts only usable numeric host dimensions', () => { + expect(readTerminalViewportDims({ cols: 40, rows: 50 })).toEqual({ + hostCols: 40, + hostRows: 50 + }) + expect(readTerminalViewportDims({ cols: Number.NaN, rows: 0 })).toEqual({ + hostCols: null, + hostRows: null + }) + }) +}) + +describe('resolveTerminalViewportResubscribe', () => { + it('resubscribes immediately on the first pass when the viewport is unmeasured', () => { + expect( + resolveTerminalViewportResubscribe({ + hostCols: 80, + hostRows: 24, + viewportMeasured: false, + viewport: null, + attempts: 0 + }) + ).toEqual({ kind: 'resubscribe', delayMs: 0 }) + }) + + it('caps even the unmeasured pass once the budget is spent', () => { + expect( + resolveTerminalViewportResubscribe({ + hostCols: 80, + hostRows: 24, + viewportMeasured: false, + viewport: null, + attempts: MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS + }) + ).toEqual({ kind: 'exhausted' }) + }) + + it('holds on absent host dims instead of resubscribing (STA-3337 regression)', () => { + for (const [hostCols, hostRows] of [ + [null, null], + [80, null], + [null, 24] + ] as const) { + expect( + resolveTerminalViewportResubscribe({ + hostCols, + hostRows, + viewportMeasured: true, + viewport: PHONE, + attempts: 0 + }) + ).toEqual({ kind: 'hold' }) + } + }) + + it('keeps holding on absent dims across repeated frames without spending budget', () => { + for (let frame = 0; frame < 50; frame += 1) { + expect( + resolveTerminalViewportResubscribe({ + hostCols: null, + hostRows: null, + viewportMeasured: true, + viewport: PHONE, + attempts: 0 + }).kind + ).toBe('hold') + } + }) + + it('converges when host dims match the measured viewport', () => { + expect( + resolveTerminalViewportResubscribe({ + hostCols: PHONE.cols, + hostRows: PHONE.rows, + viewportMeasured: true, + viewport: PHONE, + attempts: 2 + }) + ).toEqual({ kind: 'converged' }) + }) + + it('backs off across mismatch attempts and then exhausts', () => { + const delays = [0, 1, 2].map((attempts) => { + const decision = resolveTerminalViewportResubscribe({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + attempts + }) + if (decision.kind !== 'resubscribe') { + throw new Error(`expected resubscribe at attempt ${attempts}, got ${decision.kind}`) + } + return decision.delayMs + }) + expect(delays[0]).toBe(0) + expect(delays[1]).toBeGreaterThan(0) + expect(delays[2]).toBeGreaterThan(delays[1]) + expect( + resolveTerminalViewportResubscribe({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + attempts: MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS + }) + ).toEqual({ kind: 'exhausted' }) + }) +}) + +describe('shouldResubscribeAfterViewportMeasure', () => { + it('always resubscribes when the viewport was never measured (server must learn it)', () => { + expect( + shouldResubscribeAfterViewportMeasure({ + hostCols: PHONE.cols, + hostRows: PHONE.rows, + measured: PHONE, + viewportWasMeasured: false + }) + ).toBe(true) + }) + + it('skips the resubscribe when the fresh measure already matches the host', () => { + expect( + shouldResubscribeAfterViewportMeasure({ + hostCols: PHONE.cols, + hostRows: PHONE.rows, + measured: PHONE, + viewportWasMeasured: true + }) + ).toBe(false) + }) + + it('resubscribes when the host still disagrees with the fresh measure', () => { + expect( + shouldResubscribeAfterViewportMeasure({ + hostCols: 80, + hostRows: 24, + measured: PHONE, + viewportWasMeasured: true + }) + ).toBe(true) + }) +}) + +describe('TerminalViewportResubscribeBudget', () => { + const exhaust = (budget: TerminalViewportResubscribeBudget, handle: string) => { + for (let i = 0; i < MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS; i += 1) { + budget.chargeAttempt(handle) + } + } + + it('starts at zero and counts charged attempts per handle', () => { + const budget = new TerminalViewportResubscribeBudget() + expect(budget.attempts('t1')).toBe(0) + budget.chargeAttempt('t1') + budget.chargeAttempt('t1') + expect(budget.attempts('t1')).toBe(2) + expect(budget.attempts('t2')).toBe(0) + }) + + it('resets attempts and re-arms the announcement on convergence', () => { + const budget = new TerminalViewportResubscribeBudget() + exhaust(budget, 't1') + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + budget.markConverged('t1') + expect(budget.attempts('t1')).toBe(0) + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + }) + + it('announces exhaustion exactly once', () => { + const budget = new TerminalViewportResubscribeBudget() + exhaust(budget, 't1') + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + expect(budget.shouldAnnounceExhaustion('t1')).toBe(false) + }) + + it('does not refill an exhausted handle that stayed listed', () => { + const budget = new TerminalViewportResubscribeBudget() + exhaust(budget, 't1') + for (let refresh = 0; refresh < 5; refresh += 1) { + budget.notifyListedHandles(new Set(['t1'])) + } + expect(budget.attempts('t1')).toBe(MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS) + }) + + it('refills only after the exhausted handle went absent and came back', () => { + const budget = new TerminalViewportResubscribeBudget() + exhaust(budget, 't1') + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + budget.notifyListedHandles(new Set()) + // Still exhausted while absent — the refill lands on the return. + expect(budget.attempts('t1')).toBe(MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS) + budget.notifyListedHandles(new Set(['t1'])) + expect(budget.attempts('t1')).toBe(0) + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + }) + + it('leaves below-cap handles untouched by list refreshes', () => { + const budget = new TerminalViewportResubscribeBudget() + budget.chargeAttempt('t1') + budget.notifyListedHandles(new Set()) + budget.notifyListedHandles(new Set(['t1'])) + expect(budget.attempts('t1')).toBe(1) + }) + + it('forget clears one handle, clear clears everything', () => { + const budget = new TerminalViewportResubscribeBudget() + exhaust(budget, 't1') + exhaust(budget, 't2') + budget.forget('t1') + expect(budget.attempts('t1')).toBe(0) + expect(budget.attempts('t2')).toBe(MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS) + budget.clear() + expect(budget.attempts('t2')).toBe(0) + }) +}) + +describe('runTerminalViewportFitPass', () => { + const HANDLE = 't1' + + function makeHarness(overrides: { + hostCols?: number | null + hostRows?: number | null + viewportMeasured?: boolean + viewport?: { cols: number; rows: number } | null + measured?: { cols: number; rows: number } | null + budget?: TerminalViewportResubscribeBudget + }) { + const budget = overrides.budget ?? new TerminalViewportResubscribeBudget() + const diagnostics = { + streamResubscribing: vi.fn(), + streamResubscribeHeld: vi.fn(), + streamResubscribeExhausted: vi.fn() + } + const terminalUnsubsRef = { current: new Map void>([[HANDLE, () => {}]]) } + const scheduled: { fn: () => void; ms: number }[] = [] + const webView = { + awaitReady: () => Promise.resolve(), + measureFitDimensions: () => Promise.resolve(overrides.measured ?? PHONE) + } + const unsubscribeTerminal = vi.fn((handle: string) => { + terminalUnsubsRef.current.delete(handle) + }) + // Mimic the real subscribe path: arming registers an unsubscribe handle. + const subscribeToTerminal = vi.fn((handle: string) => { + terminalUnsubsRef.current.set(handle, () => {}) + }) + const showToast = vi.fn() + const args: TerminalViewportFitPassArgs = { + handle: HANDLE, + seq: 1, + hostCols: overrides.hostCols ?? null, + hostRows: overrides.hostRows ?? null, + budget, + diagnostics, + viewportRef: { current: overrides.viewport ?? null }, + viewportMeasuredRef: { current: overrides.viewportMeasured ?? false }, + subscribeSeqRef: { current: new Map([[HANDLE, 1]]) }, + initializedHandlesRef: { current: new Set([HANDLE]) }, + terminalUnsubsRef, + terminalFrameHeightRef: { current: 0 }, + getTerminalRef: () => webView, + unsubscribeTerminal, + subscribeToTerminal, + scheduleDelayedAction: (fn, ms) => scheduled.push({ fn, ms }), + showToast + } + return { + args, + budget, + diagnostics, + scheduled, + subscribeToTerminal, + unsubscribeTerminal, + showToast + } + } + + const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + + it('holds without any teardown when host dims are absent (STA-3337 regression)', async () => { + const h = makeHarness({ viewportMeasured: true, viewport: PHONE }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.unsubscribeTerminal).not.toHaveBeenCalled() + expect(h.subscribeToTerminal).not.toHaveBeenCalled() + expect(h.diagnostics.streamResubscribeHeld).toHaveBeenCalledTimes(1) + }) + + it('measures and resubscribes immediately on the first pass, charging one attempt', async () => { + const h = makeHarness({ hostCols: 80, hostRows: 24 }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.unsubscribeTerminal).toHaveBeenCalledTimes(1) + expect(h.subscribeToTerminal).toHaveBeenCalledTimes(1) + expect(h.args.viewportRef.current).toEqual(PHONE) + expect(h.args.viewportMeasuredRef.current).toBe(true) + expect(h.budget.attempts(HANDLE)).toBe(1) + }) + + it('treats an equal fresh measure as convergence instead of resubscribing', async () => { + const budget = new TerminalViewportResubscribeBudget() + budget.chargeAttempt(HANDLE) + // Stale cached viewport disagrees with the host, but the fresh measure matches it. + const h = makeHarness({ + hostCols: PHONE.cols, + hostRows: PHONE.rows, + viewportMeasured: true, + viewport: { cols: 30, rows: 20 }, + measured: PHONE, + budget + }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.subscribeToTerminal).not.toHaveBeenCalled() + expect(h.budget.attempts(HANDLE)).toBe(0) + }) + + it('defers later attempts through the backoff scheduler while keeping the stream up', async () => { + const budget = new TerminalViewportResubscribeBudget() + budget.chargeAttempt(HANDLE) + const h = makeHarness({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + budget + }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.scheduled).toHaveLength(1) + expect(h.scheduled[0].ms).toBeGreaterThan(0) + // The stream must still be up until the deferred retry fires. + expect(h.unsubscribeTerminal).not.toHaveBeenCalled() + h.scheduled[0].fn() + expect(h.unsubscribeTerminal).toHaveBeenCalledTimes(1) + expect(h.subscribeToTerminal).toHaveBeenCalledTimes(1) + expect(h.budget.attempts(HANDLE)).toBe(2) + }) + + it('drops a deferred retry whose subscribe generation went stale', async () => { + const budget = new TerminalViewportResubscribeBudget() + budget.chargeAttempt(HANDLE) + const h = makeHarness({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + budget + }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.scheduled).toHaveLength(1) + h.args.subscribeSeqRef.current.set(HANDLE, 2) + h.scheduled[0].fn() + expect(h.unsubscribeTerminal).not.toHaveBeenCalled() + expect(h.budget.attempts(HANDLE)).toBe(1) + }) + + it('drops a deferred retry after the live stream converges', async () => { + const budget = new TerminalViewportResubscribeBudget() + budget.chargeAttempt(HANDLE) + const h = makeHarness({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + budget + }) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.scheduled).toHaveLength(1) + expect(h.budget.observeResize(HANDLE, PHONE, PHONE)).toEqual([PHONE.cols, PHONE.rows]) + h.scheduled[0].fn() + expect(h.unsubscribeTerminal).not.toHaveBeenCalled() + expect(h.subscribeToTerminal).not.toHaveBeenCalled() + expect(h.budget.attempts(HANDLE)).toBe(0) + }) + + it('announces exhaustion once and stops touching the stream', async () => { + const budget = new TerminalViewportResubscribeBudget() + for (let i = 0; i < MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS; i += 1) { + budget.chargeAttempt(HANDLE) + } + const h = makeHarness({ + hostCols: 80, + hostRows: 24, + viewportMeasured: true, + viewport: PHONE, + budget + }) + runTerminalViewportFitPass(h.args) + runTerminalViewportFitPass(h.args) + await settle() + expect(h.unsubscribeTerminal).not.toHaveBeenCalled() + expect(h.subscribeToTerminal).not.toHaveBeenCalled() + expect(h.showToast).toHaveBeenCalledTimes(1) + expect(h.diagnostics.streamResubscribeExhausted).toHaveBeenCalledTimes(2) + }) +}) + +describe('STA-3337 stream shapes', () => { + it('empty scrollback with absent dims settles after a single register pass', () => { + const budget = new TerminalViewportResubscribeBudget() + // Pass 1: no viewport yet — measure and resubscribe so the server learns it. + const first = resolveTerminalViewportResubscribe({ + hostCols: null, + hostRows: null, + viewportMeasured: false, + viewport: null, + attempts: budget.attempts('t1') + }) + expect(first).toEqual({ kind: 'resubscribe', delayMs: 0 }) + budget.chargeAttempt('t1') + // Pass 2+: host still reports no dims — the stream must be left alone. + for (let frame = 0; frame < 10; frame += 1) { + expect( + resolveTerminalViewportResubscribe({ + hostCols: null, + hostRows: null, + viewportMeasured: true, + viewport: PHONE, + attempts: budget.attempts('t1') + }).kind + ).toBe('hold') + } + expect(budget.attempts('t1')).toBe(1) + }) + + it('non-converging numeric dims degrade after the bounded backoff run', () => { + const budget = new TerminalViewportResubscribeBudget() + const kinds: string[] = [] + for (let frame = 0; frame < 6; frame += 1) { + const decision = resolveTerminalViewportResubscribe({ + hostCols: 80, + hostRows: 24, + viewportMeasured: frame > 0, + viewport: frame > 0 ? PHONE : null, + attempts: budget.attempts('t1') + }) + kinds.push(decision.kind) + if (decision.kind === 'resubscribe') { + budget.chargeAttempt('t1') + } + } + expect(kinds).toEqual([ + 'resubscribe', + 'resubscribe', + 'resubscribe', + 'exhausted', + 'exhausted', + 'exhausted' + ]) + expect(budget.shouldAnnounceExhaustion('t1')).toBe(true) + expect(budget.shouldAnnounceExhaustion('t1')).toBe(false) + }) +}) diff --git a/mobile/src/session/mobile-terminal-viewport-resubscribe.ts b/mobile/src/session/mobile-terminal-viewport-resubscribe.ts new file mode 100644 index 00000000000..8ad3c99c13e --- /dev/null +++ b/mobile/src/session/mobile-terminal-viewport-resubscribe.ts @@ -0,0 +1,293 @@ +/** Bounds the scrollback→measure→resubscribe fit loop (STA-3337): a host whose + * frame dims can never equal the phone viewport must not re-arm the stream + * forever — it broke gesture recognition and drained battery at ~25 cycles/s. */ + +import type { MobileTerminalDiagnostics } from './mobile-terminal-diagnostics' + +export const MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS = 3 + +/** Attempt-indexed teardown delay. Attempt 0 is the ordinary first fit pass + * (server learns the viewport) and must stay immediate; later attempts mean + * the server answered with non-matching dims, so probe at a decaying rate. */ +const TERMINAL_VIEWPORT_RESUBSCRIBE_BACKOFF_MS = [0, 750, 3000] as const + +export type TerminalViewportDims = { readonly cols: number; readonly rows: number } + +function readPositiveDimension(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null +} + +export function readTerminalViewportDims(data: Readonly>): { + readonly hostCols: number | null + readonly hostRows: number | null +} { + return { + hostCols: readPositiveDimension(data.cols), + hostRows: readPositiveDimension(data.rows) + } +} + +export type TerminalViewportResubscribeDecision = + | { readonly kind: 'resubscribe'; readonly delayMs: number } + | { readonly kind: 'converged' } + | { readonly kind: 'hold' } + | { readonly kind: 'exhausted' } + +function resubscribeDelayMs(attempts: number): number { + return TERMINAL_VIEWPORT_RESUBSCRIBE_BACKOFF_MS[ + Math.min(attempts, TERMINAL_VIEWPORT_RESUBSCRIBE_BACKOFF_MS.length - 1) + ] +} + +export function resolveTerminalViewportResubscribe(args: { + hostCols: number | null + hostRows: number | null + viewportMeasured: boolean + viewport: TerminalViewportDims | null + attempts: number +}): TerminalViewportResubscribeDecision { + const overBudget = args.attempts >= MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS + // First subscribe carries no viewport; resubscribing is how the server learns it. + if (!args.viewportMeasured || args.viewport == null) { + return overBudget ? { kind: 'exhausted' } : { kind: 'resubscribe', delayMs: 0 } + } + // Why: a host that doesn't report PTY dims can never converge — resubscribing + // replays the identical frame, so keep the stream instead of probing it. + if (args.hostCols == null || args.hostRows == null) { + return { kind: 'hold' } + } + if (args.hostCols === args.viewport.cols && args.hostRows === args.viewport.rows) { + return { kind: 'converged' } + } + return overBudget + ? { kind: 'exhausted' } + : { kind: 'resubscribe', delayMs: resubscribeDelayMs(args.attempts) } +} + +/** Post-measure re-check: the pre-measure mismatch may have been a stale cached + * viewport. Resubscribing is only productive when the server still disagrees + * with the fresh measure, or was never told the viewport at all. */ +export function shouldResubscribeAfterViewportMeasure(args: { + hostCols: number | null + hostRows: number | null + measured: TerminalViewportDims + viewportWasMeasured: boolean +}): boolean { + if (!args.viewportWasMeasured) { + return true + } + return args.hostCols !== args.measured.cols || args.hostRows !== args.measured.rows +} + +/** Per-handle resubscribe budget, mirroring the chat-side rearm bound: attempts + * refill only when the handle actually left terminal.list and came back. A + * still-listed non-converging handle re-funded on every list refresh would undo + * the bound this class exists to enforce. */ +export class TerminalViewportResubscribeBudget { + private readonly attemptsByHandle = new Map() + private readonly absentSinceExhaustion = new Set() + private readonly announcedExhaustion = new Set() + private readonly retryGenerationByHandle = new Map() + + attempts(handle: string): number { + return this.attemptsByHandle.get(handle) ?? 0 + } + + chargeAttempt(handle: string): void { + this.attemptsByHandle.set(handle, this.attempts(handle) + 1) + } + + retryGeneration(handle: string): object { + const existing = this.retryGenerationByHandle.get(handle) + if (existing) { + return existing + } + const generation = {} + this.retryGenerationByHandle.set(handle, generation) + return generation + } + + isRetryGenerationCurrent(handle: string, generation: object): boolean { + return this.retryGenerationByHandle.get(handle) === generation + } + + observeResize( + handle: string, + data: Readonly>, + viewport: TerminalViewportDims | null + ): readonly [number, number] { + const { hostCols, hostRows } = readTerminalViewportDims(data) + const cols = hostCols ?? 80 + const rows = hostRows ?? 24 + if (viewport?.cols === cols && viewport.rows === rows) { + this.markConverged(handle) + } + return [cols, rows] + } + + markConverged(handle: string): void { + this.forget(handle) + } + + /** True exactly once per exhaustion so the degraded state is announced, not spammed. */ + shouldAnnounceExhaustion(handle: string): boolean { + if (this.announcedExhaustion.has(handle)) { + return false + } + this.announcedExhaustion.add(handle) + return true + } + + notifyListedHandles(liveHandles: ReadonlySet): void { + for (const handle of Array.from(this.attemptsByHandle.keys())) { + if (this.attempts(handle) < MAX_TERMINAL_VIEWPORT_RESUBSCRIBE_ATTEMPTS) { + continue + } + if (!liveHandles.has(handle)) { + this.absentSinceExhaustion.add(handle) + continue + } + // Why: only an absence marker buys a refill — the handle's PTY may be live + // again, so a fresh budget (and a fresh degrade announcement) is warranted. + if (this.absentSinceExhaustion.delete(handle)) { + this.forget(handle) + } + } + } + + forget(handle: string): void { + this.attemptsByHandle.delete(handle) + this.absentSinceExhaustion.delete(handle) + this.announcedExhaustion.delete(handle) + this.retryGenerationByHandle.delete(handle) + } + + clear(): void { + this.attemptsByHandle.clear() + this.absentSinceExhaustion.clear() + this.announcedExhaustion.clear() + this.retryGenerationByHandle.clear() + } +} + +type MutableRef = { current: T } + +type TerminalFitWebView = { + awaitReady: () => Promise + measureFitDimensions: (frameHeight?: number) => Promise +} + +export type TerminalViewportFitPassArgs = { + handle: string + seq: number + hostCols: number | null + hostRows: number | null + budget: TerminalViewportResubscribeBudget + diagnostics: Pick< + MobileTerminalDiagnostics, + 'streamResubscribing' | 'streamResubscribeHeld' | 'streamResubscribeExhausted' + > + viewportRef: MutableRef + viewportMeasuredRef: MutableRef + subscribeSeqRef: MutableRef> + initializedHandlesRef: MutableRef> + terminalUnsubsRef: MutableRef void>> + terminalFrameHeightRef: MutableRef + getTerminalRef: (handle: string | null) => TerminalFitWebView | undefined + unsubscribeTerminal: (handle: string) => void + subscribeToTerminal: (handle: string) => void + scheduleDelayedAction: (fn: () => void, ms: number) => void + showToast: (message: string, durationMs?: number) => void +} + +/** One bounded fit pass per scrollback frame: converge, hold, degrade visibly, + * or measure and resubscribe (backing off) so the server can phone-fit. */ +export function runTerminalViewportFitPass(args: TerminalViewportFitPassArgs): void { + const { handle, seq, hostCols, hostRows, budget, diagnostics } = args + const retryGeneration = budget.retryGeneration(handle) + const decision = resolveTerminalViewportResubscribe({ + hostCols, + hostRows, + viewportMeasured: args.viewportMeasuredRef.current, + viewport: args.viewportRef.current, + attempts: budget.attempts(handle) + }) + if (decision.kind === 'converged') { + budget.markConverged(handle) + return + } + if (decision.kind === 'hold') { + diagnostics.streamResubscribeHeld(handle, seq) + return + } + if (decision.kind === 'exhausted') { + diagnostics.streamResubscribeExhausted(handle, seq, budget.attempts(handle)) + if (budget.shouldAnnounceExhaustion(handle)) { + args.showToast("Couldn't fit the terminal to this screen", 4000) + } + return + } + const viewportWasMeasured = args.viewportMeasuredRef.current + void (async () => { + // Why: wait for init()'s rAF chain before measuring, else the measure races ahead and returns null (log dump 2026-05-06). + await args.getTerminalRef(handle)?.awaitReady() + if ( + args.subscribeSeqRef.current.get(handle) !== seq || + !budget.isRetryGenerationCurrent(handle, retryGeneration) + ) { + return + } + const dims = await args + .getTerminalRef(handle) + ?.measureFitDimensions(args.terminalFrameHeightRef.current || undefined) + // Why: re-check seq — the awaits may have let a newer subscribe cycle arm; tearing it down would resubscribe a stale generation. + if ( + args.subscribeSeqRef.current.get(handle) !== seq || + !budget.isRetryGenerationCurrent(handle, retryGeneration) + ) { + return + } + if (!args.getTerminalRef(handle) || !dims) { + return + } + args.viewportRef.current = dims + args.viewportMeasuredRef.current = true + if ( + !shouldResubscribeAfterViewportMeasure({ + hostCols, + hostRows, + measured: dims, + viewportWasMeasured + }) + ) { + // Why: the pre-measure mismatch was a stale cached viewport; the server already agrees. + budget.markConverged(handle) + return + } + const resubscribe = (): void => { + if ( + args.subscribeSeqRef.current.get(handle) !== seq || + !budget.isRetryGenerationCurrent(handle, retryGeneration) + ) { + return + } + if (!args.getTerminalRef(handle)) { + return + } + diagnostics.streamResubscribing(handle, seq, dims, budget.attempts(handle), decision.delayMs) + args.unsubscribeTerminal(handle) + args.initializedHandlesRef.current.delete(handle) + args.subscribeToTerminal(handle) + // Why: only a resubscribe that actually armed spends budget; one turned away by its own gates never reached the host. + if (args.terminalUnsubsRef.current.has(handle)) { + budget.chargeAttempt(handle) + } + } + if (decision.delayMs > 0) { + // Why: keep the live stream up through the backoff so input keeps flowing; teardown happens only when the retry fires. + args.scheduleDelayedAction(resubscribe, decision.delayMs) + } else { + resubscribe() + } + })() +} diff --git a/mobile/src/session/use-mobile-file-tap-handlers.test.ts b/mobile/src/session/use-mobile-file-tap-handlers.test.ts new file mode 100644 index 00000000000..a795d8d9ed6 --- /dev/null +++ b/mobile/src/session/use-mobile-file-tap-handlers.test.ts @@ -0,0 +1,134 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useMobileFileTapHandlers } from './use-mobile-file-tap-handlers' + +const push = vi.fn() + +vi.mock('expo-router', () => ({ useRouter: () => ({ push }) })) +vi.mock('../platform/haptics', () => ({ triggerSelection: vi.fn() })) + +type Handlers = ReturnType + +function ok(result: unknown) { + return { ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +describe('useMobileFileTapHandlers', () => { + let renderer: ReactTestRenderer | null = null + let handlers: Handlers | null = null + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + push.mockClear() + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + handlers = null + }) + + function createOptions(sendRequest: ReturnType) { + return { + client: { sendRequest }, + hostId: 'host-1', + worktreeId: 'wt-1', + worktreeName: 'Orca', + activeHandleRef: { current: 'terminal-1' as string | null }, + terminalCwdRef: { current: new Map([['terminal-1', '/repo/sub']]) }, + openBrowser: vi.fn(), + fetchSessionTabs: vi.fn(async () => {}), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActiveSessionTabType: () => 'terminal', + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + reportChatTapFailure: vi.fn() + } + } + + function Harness({ options }: { options: ReturnType }): null { + handlers = useMobileFileTapHandlers(options) + return null + } + + it('keeps handler identities stable across rerenders', () => { + const options = createOptions(vi.fn()) + act(() => { + renderer = create(createElement(Harness, { options })) + }) + const first = handlers + act(() => { + renderer!.update(createElement(Harness, { options: { ...options } })) + }) + expect(handlers!.handleFileTap).toBe(first!.handleFileTap) + expect(handlers!.handleNativeChatFileTap).toBe(first!.handleNativeChatFileTap) + }) + + it('dispatches through the latest options after a rerender', () => { + const firstSendRequest = vi.fn() + const firstOptions = createOptions(firstSendRequest) + act(() => { + renderer = create(createElement(Harness, { options: firstOptions })) + }) + + const latestSendRequest = vi.fn(async () => ok({ exists: false, isDirectory: false })) + act(() => { + renderer!.update( + createElement(Harness, { + options: { ...firstOptions, client: { sendRequest: latestSendRequest } } + }) + ) + }) + handlers!.handleFileTap('terminal-1', 'index.ts', null, null) + + expect(firstSendRequest).not.toHaveBeenCalled() + expect(latestSendRequest).toHaveBeenCalledTimes(1) + }) + + it('resolves terminal taps with the terminal handle and cwd', async () => { + const sendRequest = vi.fn(async () => ok({ exists: false, isDirectory: false })) + act(() => { + renderer = create(createElement(Harness, { options: createOptions(sendRequest) })) + }) + + handlers!.handleFileTap('terminal-1', 'index.ts', null, null) + await act(async () => {}) + + expect(sendRequest).toHaveBeenCalledWith( + 'files.resolveTerminalPath', + { worktree: 'id:wt-1', pathText: 'index.ts', terminal: 'terminal-1', cwd: '/repo/sub' }, + { timeoutMs: 10_000 } + ) + }) + + it('ignores terminal taps from a non-active handle', () => { + const sendRequest = vi.fn() + act(() => { + renderer = create(createElement(Harness, { options: createOptions(sendRequest) })) + }) + + handlers!.handleFileTap('terminal-2', 'index.ts', null, null) + + expect(sendRequest).not.toHaveBeenCalled() + }) + + it('resolves chat taps against the worktree root and reports a miss', async () => { + const sendRequest = vi.fn(async () => ok({ exists: false, isDirectory: false })) + const options = createOptions(sendRequest) + act(() => { + renderer = create(createElement(Harness, { options })) + }) + + handlers!.handleNativeChatFileTap('mobile/src/x.ts:12') + await act(async () => {}) + + expect(sendRequest).toHaveBeenCalledWith( + 'files.resolveTerminalPath', + { worktree: 'id:wt-1', pathText: 'mobile/src/x.ts' }, + { timeoutMs: 10_000 } + ) + expect(options.reportChatTapFailure).toHaveBeenCalledWith("Couldn't open mobile/src/x.ts:12") + }) +}) diff --git a/mobile/src/session/use-mobile-file-tap-handlers.ts b/mobile/src/session/use-mobile-file-tap-handlers.ts new file mode 100644 index 00000000000..276be5b566f --- /dev/null +++ b/mobile/src/session/use-mobile-file-tap-handlers.ts @@ -0,0 +1,174 @@ +import { useCallback, useLayoutEffect, useRef, type MutableRefObject } from 'react' +import { useRouter } from 'expo-router' +import { triggerSelection } from '../platform/haptics' +import type { RpcClient } from '../transport/rpc-client' +import { openMobileFileTap, type FileTapSessionTab } from './mobile-file-tap-open' +import { openMobileNativeChatFileTap } from './mobile-native-chat-open-file' + +type MobileFileTapHandlerOptions = { + client: Pick | null + hostId: string + worktreeId: string + worktreeName?: string + activeHandleRef: MutableRefObject + terminalCwdRef: MutableRefObject> + openBrowser: (url: string) => void + fetchSessionTabs: () => Promise + getSessionTabs: () => readonly T[] + getActiveSessionTabId: () => string | null + getActiveSessionTabType: () => string | null + switchSessionTab: (tab: T) => void + scheduleDelayedAction: (callback: () => void, delayMs: number) => unknown + reportChatTapFailure: (message: string) => void +} + +/** + * Tap-to-open handlers for file references, shared by the terminal (link taps + * with the terminal's cwd) and native chat (worktree-root-relative paths, with + * failure feedback). Handlers are identity-stable and read the latest options at + * dispatch time; the shared activation seq lets a newer tap on either surface + * supersede an in-flight one. + */ +export function useMobileFileTapHandlers( + options: MobileFileTapHandlerOptions +): { + handleFileTap: ( + handle: string, + pathText: string, + line: number | null, + column: number | null + ) => void + handleNativeChatFileTap: (pathText: string) => void +} { + const { + activeHandleRef, + client, + fetchSessionTabs, + getActiveSessionTabId, + getActiveSessionTabType, + getSessionTabs, + hostId, + openBrowser, + scheduleDelayedAction, + reportChatTapFailure, + switchSessionTab, + terminalCwdRef, + worktreeId, + worktreeName + } = options + const router = useRouter() + const routerRef = useRef(router) + const optionsRef = useRef(options) + const activationSeqRef = useRef(0) + + useLayoutEffect(() => { + routerRef.current = router + optionsRef.current = { + activeHandleRef, + client, + fetchSessionTabs, + getActiveSessionTabId, + getActiveSessionTabType, + getSessionTabs, + hostId, + openBrowser, + scheduleDelayedAction, + reportChatTapFailure, + switchSessionTab, + terminalCwdRef, + worktreeId, + worktreeName + } + }, [ + activeHandleRef, + client, + fetchSessionTabs, + getActiveSessionTabId, + getActiveSessionTabType, + getSessionTabs, + hostId, + openBrowser, + router, + scheduleDelayedAction, + reportChatTapFailure, + switchSessionTab, + terminalCwdRef, + worktreeId, + worktreeName + ]) + + const handleFileTap = useCallback( + (handle: string, pathText: string, line: number | null, column: number | null) => { + const current = optionsRef.current + if (handle !== current.activeHandleRef.current || !current.client) { + return + } + const activationSeq = ++activationSeqRef.current + openMobileFileTap({ + client: current.client, + hostId: current.hostId, + worktreeId: current.worktreeId, + worktreeName: current.worktreeName, + terminalHandle: handle, + pathText, + cwd: current.terminalCwdRef.current.get(handle) ?? null, + line, + column, + pushPreviewRoute: (href) => routerRef.current.push(href), + openBrowser: current.openBrowser, + triggerOpenFeedback: triggerSelection, + fetchSessionTabs: current.fetchSessionTabs, + getSessionTabs: current.getSessionTabs, + getActiveSessionTabId: current.getActiveSessionTabId, + getActivationState: (activated) => ({ + activated, + activationSeq, + latestActivationSeq: activationSeqRef.current, + sourceTerminalHandle: handle, + activeTerminalHandle: current.activeHandleRef.current, + activeTabType: current.getActiveSessionTabType() + }), + switchSessionTab: current.switchSessionTab, + scheduleDelayedAction: current.scheduleDelayedAction + }) + }, + [] + ) + + const handleNativeChatFileTap = useCallback((pathText: string) => { + const current = optionsRef.current + // The chat overlay rides on its backing terminal tab; that handle anchors + // the activation gate even though resolution ignores the terminal's cwd. + const sourceTerminalHandle = current.activeHandleRef.current + if (!current.client || !sourceTerminalHandle) { + return + } + const activationSeq = ++activationSeqRef.current + openMobileNativeChatFileTap({ + client: current.client, + hostId: current.hostId, + worktreeId: current.worktreeId, + worktreeName: current.worktreeName, + pathText, + pushPreviewRoute: (href) => routerRef.current.push(href), + openBrowser: current.openBrowser, + triggerOpenFeedback: triggerSelection, + fetchSessionTabs: current.fetchSessionTabs, + getSessionTabs: current.getSessionTabs, + getActiveSessionTabId: current.getActiveSessionTabId, + getActivationState: (activated) => ({ + activated, + activationSeq, + latestActivationSeq: activationSeqRef.current, + sourceTerminalHandle, + activeTerminalHandle: current.activeHandleRef.current, + activeTabType: current.getActiveSessionTabType() + }), + switchSessionTab: current.switchSessionTab, + scheduleDelayedAction: current.scheduleDelayedAction, + onOpenFailed: () => current.reportChatTapFailure(`Couldn't open ${pathText}`) + }) + }, []) + + return { handleFileTap, handleNativeChatFileTap } +} diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.test.ts b/mobile/src/session/use-mobile-native-chat-answer-send.test.ts index 8f22884145e..b296ea4851b 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.test.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.test.ts @@ -11,7 +11,13 @@ import { markMobileNativeChatInputStale, resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite, + resetMobileNativeChatTerminalWritesForTests +} from './mobile-native-chat-terminal-write-lock' import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' +import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' type AnswerSend = ReturnType @@ -40,17 +46,24 @@ describe('useMobileNativeChatAnswerSend', () => { let mountedClient: RpcClient | null = null let mountedOnSendError: ((message: string) => void) | null = null let mountedAgent: AgentType = 'claude' + // The route sends through useNativeChatAcceptedAction, whose accepted callback + // retires the shared send-error banner (use-mobile-native-chat-controller.ts). + let acceptedAnswerAsk: AnswerSend['answerAsk'] | null = null + let onAccepted = vi.fn() beforeEach(() => { + onAccepted = vi.fn() vi.useFakeTimers() globalThis.IS_REACT_ACT_ENVIRONMENT = true resetMobileNativeChatStaleInputForTests() + resetMobileNativeChatTerminalWritesForTests() }) afterEach(() => { act(() => renderer?.unmount()) renderer = null answerSend = null + acceptedAnswerAsk = null mountedClient = null mountedOnSendError = null mountedAgent = 'claude' @@ -68,6 +81,7 @@ describe('useMobileNativeChatAnswerSend', () => { streamIdentity: 'host\0worktree\0tab\0session', onSendError: mountedOnSendError! }) + acceptedAnswerAsk = useNativeChatAcceptedAction(answerSend.answerAsk, onAccepted) return null } @@ -396,4 +410,517 @@ describe('useMobileNativeChatAnswerSend', () => { await expect(result).resolves.toBe(false) expect(sendRequest).toHaveBeenCalledTimes(1) }) + + it('rejects an answer while another composed write holds the terminal', async () => { + const onSendError = vi.fn() + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + // An image paste sequence is mid-flight into the same PTY. + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(true) + await expect(answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }])).resolves.toBe(false) + expect(sendRequest).not.toHaveBeenCalled() + expect(onSendError).toHaveBeenCalledWith('Answer not sent') + + // Once that sequence releases, answers flow again. + releaseMobileNativeChatTerminalWrite('terminal') + await expect(answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }])).resolves.toBe(true) + }) + + it('answers again on the same handle after an earlier answer already landed', async () => { + const onSendError = vi.fn() + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + await expect(answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }])).resolves.toBe(true) + // A landed answer resolves its turn FALSE — correct for a queued successor, + // fatal if the turn outlives the chain. Leaving it parked in the slot fences + // every later answer on this handle for the life of the hook, not just an + // overlapping one, so the ask card dies after its first use. + await expect(answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }])).resolves.toBe(true) + expect(sendRequest).toHaveBeenCalledTimes(2) + expect(onSendError).not.toHaveBeenCalled() + }) + + it('fences a superseding answer after the cancelled chain moved the selector', async () => { + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + const prompt: AskPrompt = { + questions: [ + { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, + { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } + ] + } + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(prompt, [{ indices: [0] }, { indices: [0] }]) + }) + // The first digit already advanced Claude to q2. Replaying a from-q1 key + // plan now would answer the wrong question. + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + }) + await act(async () => vi.runAllTimersAsync()) + + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + // Both chains unwound: the terminal is free for the next composed write. + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(true) + releaseMobileNativeChatTerminalWrite('terminal') + }) + + it('does not write a successor after the prior in-flight key is accepted', async () => { + let resolveFirst: (response: unknown) => void = () => undefined + const sendRequest = vi + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve + }) + ) + .mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + const prompt: AskPrompt = { + questions: [ + { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, + { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } + ] + } + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(prompt, [{ indices: [0] }, { indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + + // The successor is queued behind the in-flight key, not racing it. + expect(sendRequest).toHaveBeenCalledTimes(1) + await act(async () => { + resolveFirst(acceptedResponse()) + await Promise.resolve() + }) + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + }) + + it('lets a queued successor continue after the prior key is definitely rejected', async () => { + let resolveFirst: (response: unknown) => void = () => undefined + const sendRequest = vi + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve + }) + ) + .mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + resolveFirst({ + ...acceptedResponse(), + result: { send: { accepted: false } } + }) + await Promise.resolve() + }) + + // Nothing landed, so the selector never moved — the successor is safe. + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(true) + expect(sendRequest).toHaveBeenCalledTimes(2) + }) + + it('does not write a successor after the prior delivery becomes ambiguous', async () => { + let rejectFirst: (error: Error) => void = () => undefined + const sendRequest = vi + .fn() + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectFirst = reject + }) + ) + .mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + rejectFirst(markRpcDeliveryUnknown(new Error('Connection closed'))) + await Promise.resolve() + }) + + // The key may have landed; a blind successor could double-step the selector. + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + }) + + it('tells the user when a queued answer is fenced instead of dropping it silently', async () => { + const onSendError = vi.fn() + let rejectFirst: (error: Error) => void = () => undefined + const sendRequest = vi + .fn() + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectFirst = reject + }) + ) + .mockResolvedValue(acceptedResponse()) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + rejectFirst(markRpcDeliveryUnknown(new Error('Connection closed'))) + await Promise.resolve() + }) + + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + // The card re-enables on a false result, so an unreported fence looks exactly + // like a dead button. The superseded chain stays quiet — the newest answer + // owns the error surface, and it is the one the user is waiting on. + expect(onSendError).toHaveBeenCalledTimes(1) + expect(onSendError).toHaveBeenCalledWith('Answer not sent — check chat before retrying') + }) + + it('tells the user when a dropped lease fences a queued answer whose predecessor landed', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + // A transport blip, not a user cancel: unlike Stop and ask-cancel, the lost + // input lease writes no Escape, so the card stays up with Submit re-enabled. + await setEnabled(false) + await act(async () => { + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + + expect(sendRequest).toHaveBeenCalledTimes(1) + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + // The first option key LANDED, so the live selector already moved. Reporting + // nothing invites a retry that double-steps it. + expect(onSendError).toHaveBeenCalledTimes(1) + expect(onSendError).toHaveBeenCalledWith('Answer not sent — check chat before retrying') + }) + + it('keeps the terminal locked while a queued successor writes', async () => { + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + expect(sendRequest).toHaveBeenCalledTimes(1) + + // Nothing landed, so the successor is cleared to write. + await act(async () => { + settle[0]!({ ...acceptedResponse(), result: { send: { accepted: false } } }) + await Promise.resolve() + }) + expect(sendRequest).toHaveBeenCalledTimes(2) + // The successor's key is on the wire. The superseded chain unwinding behind it + // must NOT free the terminal, or an image paste interleaves into this sequence. + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(false) + + await act(async () => { + settle[1]!(acceptedResponse()) + await Promise.resolve() + }) + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(true) + expect(acquireMobileNativeChatTerminalWrite('terminal')).toBe(true) + releaseMobileNativeChatTerminalWrite('terminal') + }) + + it('does not retire the fence banner when the superseded answer lands', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + // The healthy path: the first answer LANDS, which is also the case that fences + // hardest — its key moved the live selector. + await act(async () => { + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + expect(onSendError).toHaveBeenCalledWith('Answer not sent — check chat before retrying') + // A superseded chain reporting success would clear the banner it just raised — + // the accepted hook runs after the fence, so the user would see nothing at all. + expect(onAccepted).not.toHaveBeenCalled() + expect(sendRequest).toHaveBeenCalledTimes(1) + }) + + it('does not retire the fence banner when a superseded pasted answer lands', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError, 'grok') + + let first: Promise | undefined + let second: Promise | undefined + await act(async () => { + first = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + + // The pasted shape commits with Enter, so a superseded chain is doubly unsafe + // to report as accepted — the answer it committed is not the one on screen. + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + expect(onAccepted).not.toHaveBeenCalled() + expect(onSendError).toHaveBeenCalledWith('Answer not sent — check chat before retrying') + }) + + it('reports a landed answer that Stop cancelled with no successor waiting', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + let first: Promise | undefined + await act(async () => { + first = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + // Stop, an ask cancel, and a dropped input lease all bump the generation with + // NO successor chain behind them. + await act(async () => { + answerSend?.cancelPending() + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + + // The key is on the PTY and nobody else owns the surface. Calling that a + // non-send leaves the card up and silent (fail() never runs on an accepted + // write), and the retry double-steps the selector this key already moved. + await expect(first).resolves.toBe(true) + expect(onAccepted).toHaveBeenCalledTimes(1) + expect(onSendError).not.toHaveBeenCalled() + }) + + it('reports a landed pasted answer that Stop cancelled with no successor', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError, 'grok') + + let first: Promise | undefined + await act(async () => { + first = acceptedAnswerAsk?.(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + answerSend?.cancelPending() + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + + // The pasted shape already committed with Enter, so suppressing the success + // strands an answered card the user is invited to submit a second time. + await expect(first).resolves.toBe(true) + expect(onAccepted).toHaveBeenCalledTimes(1) + expect(onSendError).not.toHaveBeenCalled() + }) + + it('fences a third answer behind an already-fenced successor, reporting once', async () => { + const onSendError = vi.fn() + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, onSendError) + + let first: Promise | undefined + let second: Promise | undefined + let third: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + await act(async () => { + third = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + expect(sendRequest).toHaveBeenCalledTimes(1) + + await act(async () => { + settle[0]!(acceptedResponse()) + await Promise.resolve() + }) + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + await expect(third).resolves.toBe(false) + // The middle chain sent nothing, so only the verdict it INHERITED can stop the + // third from replaying a from-scratch plan onto the advanced selector. + expect(sendRequest).toHaveBeenCalledTimes(1) + // Only the newest chain owns the error surface. + expect(onSendError).toHaveBeenCalledTimes(1) + expect(onSendError).toHaveBeenCalledWith('Answer not sent — check chat before retrying') + }) + + it('queues a late third answer behind the successor already on the wire', async () => { + const settle: Array<(response: unknown) => void> = [] + const sendRequest = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + settle.push(resolve) + }) + ) + await mount({ sendRequest } as unknown as RpcClient, vi.fn()) + + let first: Promise | undefined + let second: Promise | undefined + let third: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + }) + await act(async () => { + second = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [1] }]) + await Promise.resolve() + }) + // Nothing landed, so the successor is cleared and puts its own key on the wire. + await act(async () => { + settle[0]!({ ...acceptedResponse(), result: { send: { accepted: false } } }) + await Promise.resolve() + }) + expect(sendRequest).toHaveBeenCalledTimes(2) + + await act(async () => { + third = answerSend?.answerAsk(TABS_OR_SPACES, [{ indices: [0] }]) + await Promise.resolve() + await Promise.resolve() + }) + // The first chain unwound while the second was mid-write: it must not have + // dropped the second's turn, or this one writes into the same PTY concurrently. + expect(sendRequest).toHaveBeenCalledTimes(2) + + await act(async () => { + settle[1]!(acceptedResponse()) + await Promise.resolve() + }) + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBe(false) + await expect(third).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(2) + }) }) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index 11a3a030788..b893f7ae071 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -14,6 +14,10 @@ import { sendMobileNativeChatMessageWithOutcome } from './mobile-native-chat-send' import { healMobileNativeChatStaleInput } from './mobile-native-chat-stale-input' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite +} from './mobile-native-chat-terminal-write-lock' import { resolveNativeChatTranscriptAgent, shouldStepNativeChatAskAnswer @@ -72,6 +76,12 @@ export function useMobileNativeChatAnswerSend(args: { const generationRef = useRef(0) const activeRouteRef = useRef({ client, enabled, sessionId, streamIdentity }) activeRouteRef.current = { client, enabled, sessionId, streamIdentity } + // Per-terminal count of this hook's chains sharing one write-lock hold: a + // superseding answer inherits the cancelled chain's hold (it re-enters before + // the old chain unwinds), and only the last chain out releases the lock. + const writeHoldsRef = useRef(new Map()) + // Successors wait for the prior RPC and inherit any delivery ambiguity. + const writeTurnsRef = useRef(new Map>()) const delaysRef = useRef< Set<{ timer: ReturnType; resolve: (completed: boolean) => void }> >(new Set()) @@ -103,125 +113,191 @@ export function useMobileNativeChatAnswerSend(args: { if (!hasAskAnswer(prompt, selections)) { return false } + // One composed write sequence per terminal: an answer landing mid-flight + // in an image paste (or vice versa) would interleave bytes into the PTY. + // A superseding answer shares the cancelled chain's hold on this terminal + // (that chain has not unwound to its release yet). + const holds = writeHoldsRef.current + const heldCount = holds.get(handle) ?? 0 + if (heldCount === 0 && !acquireMobileNativeChatTerminalWrite(handle)) { + onSendError('Answer not sent') + return false + } + holds.set(handle, heldCount + 1) + const previousTurn = writeTurnsRef.current.get(handle) ?? Promise.resolve(true) + let finishTurn: (safeToContinue: boolean) => void = () => undefined + const turn = new Promise((resolve) => { + finishTurn = resolve + }) + writeTurnsRef.current.set(handle, turn) // A new answer supersedes any still-pending keystroke writes. cancelPending() const generation = generationRef.current let sawUnknownOutcome = false let sawAcceptedGroup = false - // One budget for the whole answer instead of a fresh timeout per keystroke - // group, which let an N-group selector hold the card for N × the send timeout. - // It bounds transport time only: each deliberate pacing wait is credited back - // below, so a long multi-question answer still gets a full budget to write in. - let deadline = openMobileNativeChatSendBudget() - const sendTerminal = async (body: string, enter: boolean): Promise => { - const activeRoute = activeRouteRef.current - if ( - !activeRoute.enabled || - activeRoute.client !== client || - activeRoute.sessionId !== sessionId || - activeRoute.streamIdentity !== streamIdentity || - handleRef.current !== handle - ) { - return false - } - const outcome = await sendMobileNativeChatMessageWithOutcome({ - client, - terminal: handle, - text: body, - enter, - deadline, - ...(deviceTokenRef.current - ? { mobileClient: { id: deviceTokenRef.current, type: 'mobile' } } - : {}) - }) - if (outcome === 'unknown') { - sawUnknownOutcome = true - } - if (outcome === 'accepted') { - sawAcceptedGroup = true - } - return outcome === 'accepted' - } - const wait = (ms: number): Promise => - new Promise((resolve) => { - const delay = { - timer: setTimeout(() => { - delaysRef.current.delete(delay) - resolve(generationRef.current === generation) - }, ms), - resolve - } - delaysRef.current.add(delay) - }) - const fail = (): false => { - if (generationRef.current === generation) { - // Why: keystrokes that may have landed (ack lost / path cutover) must - // not read as a definite failure — a blind resend could double-step - // the selector. An earlier group that WAS accepted is the same hazard - // in definite form: a multi-question answer whose shared budget ran out - // mid-sequence left the remote selector half-stepped, and telling the - // user nothing was sent invites a retry on top of the advanced state. - onSendError( - sawAcceptedGroup - ? 'Answer partly sent — check chat before retrying' - : sawUnknownOutcome - ? 'Answer unconfirmed — check chat before retrying' - : 'Answer not sent' - ) - } - return false - } - // Grok commits pasted labels; Claude and Codex need their selector-specific - // keystrokes paced so each step renders before the next lands. - if (!shouldStepNativeChatAskAnswer(agentRef.current)) { - // This shape pastes the label into the composer and commits it, so an - // orphaned image paste would be submitted along with the answer (#10228). - // The selector shapes below deliberately skip the heal: their keys are - // `enter: false` for an active overlay, and a single-select answer is a - // bare option digit that cannot submit the line at all, so clearing there - // would consume the marker still protecting the next real message. - // Desktop splits it identically — use-native-chat-interactive-send.ts - // routes only the pasted-label shape through the clearing sender. - if ( - !(await healMobileNativeChatStaleInput({ - client, - terminal: handle, - deviceToken: deviceTokenRef.current, - deadline - })) - ) { - if (generationRef.current === generation) { - onSendError('Answer not sent') + let predecessorSafe = true + try { + predecessorSafe = await previousTurn + if (!predecessorSafe) { + // Fenced. Report it: the card re-enables on a false result, so silence + // here is indistinguishable from a dead button. "Check chat" rather than + // a bare "not sent" because the PREVIOUS answer's keys may have landed. + // Gate on the turn slot, not the generation: a dropped input lease bumps + // the generation without writing the Escape that Stop and ask-cancel do, + // so the card is still up and silence there strands an advanced selector. + if (writeTurnsRef.current.get(handle) === turn) { + onSendError('Answer not sent — check chat before retrying') } return false } + // Superseded by a newer answer, which owns the error surface from here. if (generationRef.current !== generation) { return false } - return (await sendTerminal(formatAskAnswer(prompt, selections), true)) || fail() - } - const groups = - resolveNativeChatTranscriptAgent(agentRef.current) === 'codex' - ? buildCodexAskAnswerKeys(prompt, selections) - : buildAskAnswerKeys(prompt, selections) - for (let index = 0; index < groups.length; index += 1) { - if (generationRef.current !== generation) { - return false - } - const group = groups[index]! - const body = 'raw' in group ? group.raw : sanitizeAskFreeText(group.text) - if (!(await sendTerminal(body, false))) { - return fail() - } - if (index < groups.length - 1) { - if (!(await wait(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS))) { + // One budget for the whole answer instead of a fresh timeout per keystroke + // group, which let an N-group selector hold the card for N × the send timeout. + // It bounds transport time only: each deliberate pacing wait is credited back + // below, so a long multi-question answer still gets a full budget to write in. + let deadline = openMobileNativeChatSendBudget() + const sendTerminal = async (body: string, enter: boolean): Promise => { + const activeRoute = activeRouteRef.current + if ( + !activeRoute.enabled || + activeRoute.client !== client || + activeRoute.sessionId !== sessionId || + activeRoute.streamIdentity !== streamIdentity || + handleRef.current !== handle + ) { return false } - // Pacing is deliberate, not transport latency — don't charge it to the budget. - deadline += MOBILE_NATIVE_CHAT_QUESTION_STEP_MS + const outcome = await sendMobileNativeChatMessageWithOutcome({ + client, + terminal: handle, + text: body, + enter, + deadline, + ...(deviceTokenRef.current + ? { mobileClient: { id: deviceTokenRef.current, type: 'mobile' } } + : {}) + }) + if (outcome === 'unknown') { + sawUnknownOutcome = true + } + if (outcome === 'accepted') { + sawAcceptedGroup = true + } + return outcome === 'accepted' + } + const wait = (ms: number): Promise => { + // Already superseded: don't hold the successor for a full pacing step + // waiting on a timer whose only job is to report the cancellation. + if (generationRef.current !== generation) { + return Promise.resolve(false) + } + return new Promise((resolve) => { + const delay = { + timer: setTimeout(() => { + delaysRef.current.delete(delay) + resolve(generationRef.current === generation) + }, ms), + resolve + } + delaysRef.current.add(delay) + }) + } + const fail = (): false => { + if (generationRef.current === generation) { + // Why: keystrokes that may have landed (ack lost / path cutover) must + // not read as a definite failure — a blind resend could double-step + // the selector. An earlier group that WAS accepted is the same hazard + // in definite form: a multi-question answer whose shared budget ran out + // mid-sequence left the remote selector half-stepped, and telling the + // user nothing was sent invites a retry on top of the advanced state. + onSendError( + sawAcceptedGroup + ? 'Answer partly sent — check chat before retrying' + : sawUnknownOutcome + ? 'Answer unconfirmed — check chat before retrying' + : 'Answer not sent' + ) + } + return false + } + // Grok commits pasted labels; Claude and Codex need their selector-specific + // keystrokes paced so each step renders before the next lands. + if (!shouldStepNativeChatAskAnswer(agentRef.current)) { + // This shape pastes the label into the composer and commits it, so an + // orphaned image paste would be submitted along with the answer (#10228). + // The selector shapes below deliberately skip the heal: their keys are + // `enter: false` for an active overlay, and a single-select answer is a + // bare option digit that cannot submit the line at all, so clearing there + // would consume the marker still protecting the next real message. + // Desktop splits it identically — use-native-chat-interactive-send.ts + // routes only the pasted-label shape through the clearing sender. + if ( + !(await healMobileNativeChatStaleInput({ + client, + terminal: handle, + deviceToken: deviceTokenRef.current, + deadline + })) + ) { + if (generationRef.current === generation) { + onSendError('Answer not sent') + } + return false + } + if (generationRef.current !== generation) { + return false + } + // A chain a successor took over from must not report success either: an + // accepted answer retires the shared send-error banner, wiping the + // successor's fence. Test the turn slot, not the generation counter — + // Stop, ask-cancel and a dropped lease all bump the generation with no + // successor, and there a landed answer IS a success. + const sent = (await sendTerminal(formatAskAnswer(prompt, selections), true)) || fail() + return sent && writeTurnsRef.current.get(handle) === turn + } + const groups = + resolveNativeChatTranscriptAgent(agentRef.current) === 'codex' + ? buildCodexAskAnswerKeys(prompt, selections) + : buildAskAnswerKeys(prompt, selections) + for (let index = 0; index < groups.length; index += 1) { + if (generationRef.current !== generation) { + return false + } + const group = groups[index]! + const body = 'raw' in group ? group.raw : sanitizeAskFreeText(group.text) + if (!(await sendTerminal(body, false))) { + return fail() + } + if (index < groups.length - 1) { + if (!(await wait(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS))) { + return false + } + // Pacing is deliberate, not transport latency — don't charge it to the budget. + deadline += MOBILE_NATIVE_CHAT_QUESTION_STEP_MS + } + } + // Taken over on the last key: same as above, the successor owns the surface. + return groups.length > 0 && writeTurnsRef.current.get(handle) === turn + } finally { + // Any accepted key changed the live selector, so a queued replacement + // cannot safely apply its from-scratch key plan to that new position. + finishTurn(predecessorSafe && !sawUnknownOutcome && !sawAcceptedGroup) + if (writeTurnsRef.current.get(handle) === turn) { + writeTurnsRef.current.delete(handle) + } + // Last chain out releases; a superseded chain unwinding late must not + // free the lock out from under the successor sharing its hold. + const remaining = (holds.get(handle) ?? 1) - 1 + if (remaining <= 0) { + holds.delete(handle) + releaseMobileNativeChatTerminalWrite(handle) + } else { + holds.set(handle, remaining) } } - return groups.length > 0 }, [ agentRef, diff --git a/mobile/src/session/use-mobile-native-chat-controller.test.ts b/mobile/src/session/use-mobile-native-chat-controller.test.ts index 2b4fb0e9d0f..35318d7e7f2 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.test.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.test.ts @@ -47,8 +47,12 @@ vi.mock('./use-mobile-native-chat-drafts', () => ({ vi.mock('./use-mobile-native-chat-prompts', () => ({ useMobileNativeChatPrompts: () => ({ permission: null, question: null, ask: null }) })) +const answerSendArgs: { streamIdentity?: string }[] = [] vi.mock('./use-mobile-native-chat-answer-send', () => ({ - useMobileNativeChatAnswerSend: () => ({ answerAsk: vi.fn(), cancelPending: vi.fn() }) + useMobileNativeChatAnswerSend: (args: { streamIdentity?: string }) => { + answerSendArgs.push(args) + return { answerAsk: vi.fn(), cancelPending: vi.fn() } + } })) vi.mock('./mobile-native-chat-permission-send', () => ({ useMobileNativeChatPermissionSend: () => vi.fn() @@ -421,3 +425,99 @@ describe('useMobileNativeChatController launch-draft wiring', () => { expect(draftsArgs.at(-1)).toMatchObject({ launchDraft: null, chatActive: true }) }) }) + +describe('useMobileNativeChatController streaming scope', () => { + let renderer: ReactTestRenderer | null = null + let controller: MobileNativeChatController | null = null + const clientStub = { sendRequest: vi.fn() } + + const workingTab = { + type: 'terminal', + id: 'tab-1', + terminal: 'term-1', + launchAgent: 'claude', + agentStatus: { + state: 'working', + agentType: 'claude', + providerSession: { id: 'session-1' } + }, + isActive: true + } + + function Harness(): null { + controller = useMobileNativeChatController({ + client: clientStub as unknown as RpcClient, + connState: 'connected', + hostId: 'h', + worktreeId: 'w', + activeSessionTab: workingTab as never, + activeSessionTabId: 'tab-1', + activeHandleRef: { current: 'term-1' }, + deviceTokenRef: { current: null }, + nativeChatTranscriptIsLocalReadable: true, + nativeChatInputLeaseReady: true, + onSendError: vi.fn(), + onSendResolved: vi.fn() + }) + return null + } + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + viewMode.isTabChatView = () => true + const original = console.error + const spy = vi.spyOn(console, 'error').mockImplementation((...a) => { + if (typeof a[0] === 'string' && a[0].includes('react-test-renderer is deprecated')) { + return + } + original(...a) + }) + try { + act(() => { + renderer = create(createElement(Harness)) + }) + } finally { + spy.mockRestore() + } + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + controller = null + viewMode.isTabChatView = () => true + }) + + it('holds the stream scope and liveness while the user peeks at the terminal', () => { + // Both feed the streaming gate, which lives above the chat view's mount and + // must not be reset by a view toggle. + expect(controller?.showNativeChat).toBe(true) + const scopeKey = controller?.nativeChatStreamScopeKey + expect(scopeKey).toContain('session-1') + expect(controller?.nativeChatStreamLive).toBe(true) + + viewMode.isTabChatView = () => false + act(() => renderer?.update(createElement(Harness))) + + expect(controller?.showNativeChat).toBe(false) + expect(controller?.nativeChatAgentWorking).toBe(false) + expect(controller?.nativeChatStreamScopeKey).toBe(scopeKey) + expect(controller?.nativeChatStreamLive).toBe(true) + }) + + it('keeps the delayed-send route guard view-gated, unlike the stream scope', () => { + // `streamIdentity` fences a delayed answer/stop to the route it was armed + // on, so it must still drop its session when chat closes — the scope key is + // the one that has to survive the toggle. Same string while chat is open. + const before = answerSendArgs.at(-1)?.streamIdentity + expect(before).toBe(controller?.nativeChatStreamScopeKey) + + viewMode.isTabChatView = () => false + act(() => renderer?.update(createElement(Harness))) + + const after = answerSendArgs.at(-1)?.streamIdentity + expect(after).not.toBe(before) + expect(after).not.toContain('session-1') + expect(controller?.nativeChatStreamScopeKey).toBe(before) + }) +}) diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index d6f22015763..7236fc39222 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -17,7 +17,6 @@ import { import { type MobileNativeChatTab, resolveMobileNativeChat } from './mobile-native-chat-eligibility' import { detectAgentPermission } from './mobile-native-chat-permission' import { parseAgentQuestion } from './mobile-native-chat-question' -import { openMobileNativeChatFile } from './mobile-native-chat-open-file' import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' @@ -53,10 +52,13 @@ export type MobileNativeChatController = { nativeChatSession: ReturnType nativeChatAgentWorking: boolean nativeChatStreamingText?: string + /** Agent mid-turn, regardless of whether chat is the visible view. */ + nativeChatStreamLive: boolean + /** Host/workspace/tab/session scope for stateful streaming suppression. */ + nativeChatStreamScopeKey: string nativeChatPermission: ReturnType nativeChatQuestion: ReturnType nativeChatAsk: ReturnType - handleNativeChatOpenFile: (relativePath: string) => void handleNativeChatAnswerAsk: ( prompt: AskPrompt, selections: AskAnswerSelection[] @@ -134,7 +136,12 @@ export function useMobileNativeChatController(args: { }, [activeChatAgent, showNativeChat]) const activeChatSessionId = activeChatResolution?.sessionId ?? null - const streamIdentity = `${hostId}\0${worktreeId}\0${activeSessionTabId ?? ''}\0${activeChatSessionId ?? ''}\0${activeHandleRef.current ?? ''}` + const routeKey = `${hostId}\0${worktreeId}\0${activeSessionTabId ?? ''}` + const streamIdentity = `${routeKey}\0${activeChatSessionId ?? ''}\0${activeHandleRef.current ?? ''}` + // Same chat, but keyed off the tab rather than the view-gated resolution: + // `streamIdentity` goes session-less the moment the user peeks at the terminal, + // and a scope that flips on a view toggle throws the gate's baseline away. + const streamScopeKey = `${routeKey}\0${activeSessionTab?.agentStatus?.providerSession?.id ?? ''}\0${activeHandleRef.current ?? ''}` const nativeChatSession = useMobileNativeChatSession({ client, @@ -170,6 +177,9 @@ export function useMobileNativeChatController(args: { const nativeChatStatus = activeChatResolution ? activeSessionTab?.agentStatus : null const nativeChatAgentWorking = nativeChatStatus?.state === 'working' + // Deliberately not gated on the chat view being visible: the streaming gate + // has to tell "hidden mid-turn" from "the turn ended". + const nativeChatStreamLive = activeSessionTab?.agentStatus?.state === 'working' // Throttle the streaming bubble: OpenCode emits a status frame per streamed // part, and each one re-renders and re-parses the whole accumulated markdown. const nativeChatStreamingText = useThrottledLatestValue( @@ -186,21 +196,6 @@ export function useMobileNativeChatController(args: { messages: nativeChatSession.messages }) - const handleNativeChatOpenFile = useCallback( - (pathText: string) => { - if (!client) { - return - } - void openMobileNativeChatFile({ - client, - worktreeId, - pathText, - terminal: activeHandleRef.current - }) - }, - [activeHandleRef, client, worktreeId] - ) - // Every chat write gates on both: the lease proves the input floor is ours, and // `connState` collapses a render before the lease does on disconnect. const inputSendable = nativeChatInputLeaseReady && connState === 'connected' @@ -310,10 +305,11 @@ export function useMobileNativeChatController(args: { nativeChatSession, nativeChatAgentWorking, nativeChatStreamingText, + nativeChatStreamLive, + nativeChatStreamScopeKey: streamScopeKey, nativeChatPermission, nativeChatQuestion, nativeChatAsk, - handleNativeChatOpenFile, handleNativeChatAnswerAsk: answerAsk, handleNativeChatCancelAsk: cancelAsk, handleNativeChatRespondPermission: respond, diff --git a/mobile/src/session/use-mobile-native-chat-image-attachments.test.ts b/mobile/src/session/use-mobile-native-chat-image-attachments.test.ts index be2f9a3730e..13cb5d96c48 100644 --- a/mobile/src/session/use-mobile-native-chat-image-attachments.test.ts +++ b/mobile/src/session/use-mobile-native-chat-image-attachments.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' import type { RpcResponse, RpcSuccess } from '../transport/types' import { resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' +import { resetMobileNativeChatTerminalWritesForTests } from './mobile-native-chat-terminal-write-lock' import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' // Fully stub the picker so the real expo/react-native chain never loads under @@ -88,9 +89,10 @@ describe('useMobileNativeChatImageAttachments', () => { beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true pick.mockReset() - // Stale markers live at module scope now (they outlive the screen), so they - // also outlive a test. + // Stale markers and write locks live at module scope (they outlive the + // screen), so they also outlive a test. resetMobileNativeChatStaleInputForTests() + resetMobileNativeChatTerminalWritesForTests() }) afterEach(() => { act(() => renderer?.unmount()) diff --git a/mobile/src/session/use-mobile-native-chat-image-attachments.ts b/mobile/src/session/use-mobile-native-chat-image-attachments.ts index a692b11acf1..38f9e462e46 100644 --- a/mobile/src/session/use-mobile-native-chat-image-attachments.ts +++ b/mobile/src/session/use-mobile-native-chat-image-attachments.ts @@ -26,6 +26,10 @@ import { isMobileNativeChatInputStale, markMobileNativeChatInputStale } from './mobile-native-chat-stale-input' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite +} from './mobile-native-chat-terminal-write-lock' type CurrentRef = { readonly current: T } type ShowToast = (message: string, durationMs?: number) => void @@ -127,8 +131,6 @@ export function useMobileNativeChatImageAttachments({ // checked 'connected' at entry, so only a ref can see a mid-upload disconnect. const connStateRef = useRef(connState) connStateRef.current = connState - // Serialize clear/paste/submit ownership per terminal while allowing other tabs to send. - const sendInFlightTerminalsRef = useRef(new Set()) const attachments = (scopeKey ? attachmentsByScope[scopeKey] : undefined) ?? NO_ATTACHMENTS @@ -219,15 +221,15 @@ export function useMobileNativeChatImageAttachments({ const sendNativeChat = useCallback( async (text: string): Promise => { + // Serialize clear/paste/submit ownership per terminal while allowing other + // tabs to send. Shared with the prompt-card writes (answer/permission), so + // a card tap can't interleave into a mid-flight paste sequence either. const operationTerminal = activeHandleRef.current - if (operationTerminal && sendInFlightTerminalsRef.current.has(operationTerminal)) { + if (operationTerminal && !acquireMobileNativeChatTerminalWrite(operationTerminal)) { onError?.() onSendError('Message not sent') return false } - if (operationTerminal) { - sendInFlightTerminalsRef.current.add(operationTerminal) - } // One budget for the whole user action. The paste loop, the settle, and the // text body that follows are a single send from the composer's point of view; // opening a budget per leg let `sending` run to twice the stated ceiling. @@ -347,7 +349,7 @@ export function useMobileNativeChatImageAttachments({ } } finally { if (operationTerminal) { - sendInFlightTerminalsRef.current.delete(operationTerminal) + releaseMobileNativeChatTerminalWrite(operationTerminal) } } }, diff --git a/mobile/src/session/use-mobile-native-chat-message-send.test.ts b/mobile/src/session/use-mobile-native-chat-message-send.test.ts index 71f2a98d99a..0ceda5714da 100644 --- a/mobile/src/session/use-mobile-native-chat-message-send.test.ts +++ b/mobile/src/session/use-mobile-native-chat-message-send.test.ts @@ -19,6 +19,11 @@ vi.mock('./mobile-native-chat-stale-input', () => ({ })) import { useMobileNativeChatMessageSend } from './use-mobile-native-chat-message-send' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite, + resetMobileNativeChatTerminalWritesForTests +} from './mobile-native-chat-terminal-write-lock' import { buildAgentTuiClearInputForText } from '../../../src/shared/agent-tui-input-clear' type Send = ReturnType @@ -33,6 +38,7 @@ describe('useMobileNativeChatMessageSend', () => { const onCommandSend = vi.fn() const commandSendRef = { current: onCommandSend } const agentRef = { current: null as string | null } + let onSendError = vi.fn() const mount = ( readSeededLaunchDraftSeed: () => { text: string; createdAt: number | null } | null, @@ -53,7 +59,7 @@ describe('useMobileNativeChatMessageSend', () => { restoreRejectedDraft: () => {}, acceptSend, holdUnconfirmedSend, - onSendError: () => {} + onSendError }) return null } @@ -83,6 +89,8 @@ describe('useMobileNativeChatMessageSend', () => { holdUnconfirmedSend.mockReset() onCommandSend.mockReset() commandSendRef.current = onCommandSend + onSendError = vi.fn() + resetMobileNativeChatTerminalWritesForTests() }) afterEach(() => { act(() => { @@ -297,4 +305,27 @@ describe('useMobileNativeChatMessageSend', () => { expect(originalRecorder).toHaveBeenCalledWith('/clear') expect(nextRecorder).not.toHaveBeenCalled() }) + + it('rejects a question answer while another composed write holds the terminal', async () => { + mount(() => null) + // An image paste sequence is mid-flight into the same PTY. + expect(acquireMobileNativeChatTerminalWrite('term')).toBe(true) + + let result: boolean | undefined + await act(async () => { + result = await api!.answerQuestion('1') + }) + expect(result).toBe(false) + expect(sendWithOutcome).not.toHaveBeenCalled() + expect(onSendError).toHaveBeenCalledWith('Answer not sent') + + releaseMobileNativeChatTerminalWrite('term') + await act(async () => { + result = await api!.answerQuestion('1') + }) + expect(result).toBe(true) + // The answer released its own hold on the way out. + expect(acquireMobileNativeChatTerminalWrite('term')).toBe(true) + releaseMobileNativeChatTerminalWrite('term') + }) }) diff --git a/mobile/src/session/use-mobile-native-chat-message-send.ts b/mobile/src/session/use-mobile-native-chat-message-send.ts index bde08d9b60e..1d59e25431c 100644 --- a/mobile/src/session/use-mobile-native-chat-message-send.ts +++ b/mobile/src/session/use-mobile-native-chat-message-send.ts @@ -8,6 +8,10 @@ import { } from './mobile-native-chat-send' import { healMobileNativeChatStaleInput } from './mobile-native-chat-stale-input' import { classifyMobileNativeChatSend } from './mobile-native-chat-send-classification' +import { + acquireMobileNativeChatTerminalWrite, + releaseMobileNativeChatTerminalWrite +} from './mobile-native-chat-terminal-write-lock' import type { MobileNativeChatSendOrigin } from './use-mobile-native-chat-drafts' import type { MobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-launch-draft-seed' import { buildAgentTuiClearInputForText } from '../../../src/shared/agent-tui-input-clear' @@ -239,17 +243,46 @@ export function useMobileNativeChatMessageSend(args: { [sendWithOutcome] ) - // A question answer is not composer text, so it never syncs the draft. + // A question answer is not composer text, so it never syncs the draft. It + // reaches this send directly (not through the image hook's locked path), so + // it takes the per-terminal write lock itself: an answer landing mid-flight + // in an image paste sequence would interleave bytes into the PTY. const answerQuestion = useCallback( - async (text: string): Promise => - (await sendMessage(text, undefined, false, true)) !== 'rejected', - [sendMessage] + async (text: string): Promise => { + const terminal = handleRef.current + if (terminal && !acquireMobileNativeChatTerminalWrite(terminal)) { + onSendError('Answer not sent') + return false + } + try { + return (await sendMessage(text, undefined, false, true)) !== 'rejected' + } finally { + if (terminal) { + releaseMobileNativeChatTerminalWrite(terminal) + } + } + }, + [handleRef, onSendError, sendMessage] ) + // A session-option apply writes to the same input line as a send, and the host + // spaces a send's body and its Enter ~500ms apart — so without this lock an + // apply lands between them and is submitted as part of the user's prompt. const dispatchCommand = useCallback( - (text: string): Promise => - sendMessage(text, undefined, false, false), - [sendMessage] + async (text: string): Promise => { + const terminal = handleRef.current + if (terminal && !acquireMobileNativeChatTerminalWrite(terminal)) { + return 'rejected' + } + try { + return await sendMessage(text, undefined, false, false) + } finally { + if (terminal) { + releaseMobileNativeChatTerminalWrite(terminal) + } + } + }, + [handleRef, sendMessage] ) return { send, sendWithOutcome, answerQuestion, dispatchCommand } diff --git a/mobile/src/session/use-mobile-native-chat-session-options.ts b/mobile/src/session/use-mobile-native-chat-session-options.ts index ef9cdfd2640..be6c5b2ec20 100644 --- a/mobile/src/session/use-mobile-native-chat-session-options.ts +++ b/mobile/src/session/use-mobile-native-chat-session-options.ts @@ -1,5 +1,9 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { getAgentSessionOptionCatalog } from '../../../src/shared/agent-session-option-catalog' +import { + getAgentSessionOptionCatalog, + type AgentSessionOptionCatalog, + type CatalogModel +} from '../../../src/shared/agent-session-option-catalog' import type { SessionOptionDescriptor, SessionOptionValue @@ -9,7 +13,10 @@ import { buildNativeChatSessionOptionCommand, recordNativeChatSessionOptionCommand } from '../../../src/shared/native-chat-session-option-commands' -import { buildNativeChatSessionOptionSnapshot } from '../../../src/shared/native-chat-session-option-snapshot' +import { + buildNativeChatSessionOptionSnapshot, + withTrackedNativeChatModel +} from '../../../src/shared/native-chat-session-option-snapshot' import { applyNativeChatReportedSessionOptions, clearNativeChatSessionModel, @@ -73,6 +80,15 @@ export function clearMobileSessionOptionRecordsForTests(): void { const EMPTY_SNAPSHOT: SessionOptionDescriptor[] = [] +/** The model list every consumer must see: the catalog's, plus the tracked model + * when the catalog no longer lists it. Desktop reconciles identically. */ +function activeModels( + catalog: AgentSessionOptionCatalog, + record: NativeChatSessionOptionRecord +): CatalogModel[] { + return withTrackedNativeChatModel(catalog, catalog.models, record) +} + export function useMobileNativeChatSessionOptions(args: { agent: string | null /** Stable per-tab scope (host + worktree + tab), or null when no tab is active. */ @@ -137,10 +153,13 @@ export function useMobileNativeChatSessionOptions(args: { } // Why: `version` invalidates this memo after in-place record mutations. void version + const record = getScopedRecord(scopeKey, agent) return buildNativeChatSessionOptionSnapshot({ catalog, - models: catalog.models, - record: getScopedRecord(scopeKey, agent), + // The snapshot no longer self-heals an unlisted tracked model; every caller + // reconciles it in, so a value the seed dropped keeps its row and options. + models: activeModels(catalog, record), + record, mode: 'live', modelLabel: 'Model' }) @@ -192,7 +211,7 @@ export function useMobileNativeChatSessionOptions(args: { const apply = id === 'model' ? catalog.modelApply - : catalog.models + : activeModels(catalog, record) .find((model) => model.id === previousModelId) ?.options.find((option) => option.id === id)?.apply if (!apply || apply.midSession?.kind === 'agent-picker') { @@ -216,7 +235,7 @@ export function useMobileNativeChatSessionOptions(args: { apply, modelId: previousModelId, catalog, - models: catalog.models, + models: activeModels(catalog, record), record }) if (!command) { @@ -270,7 +289,7 @@ export function useMobileNativeChatSessionOptions(args: { const apply = id === 'model' ? catalog.modelApply - : catalog.models + : activeModels(catalog, record) .find((model) => model.id === modelId) ?.options.find((option) => option.id === id)?.apply const midSession = apply?.midSession @@ -302,7 +321,7 @@ export function useMobileNativeChatSessionOptions(args: { const record = getScopedRecord(scopeKey, agent) const result = recordNativeChatSessionOptionCommand({ catalog, - models: catalog.models, + models: activeModels(catalog, record), record, command }) diff --git a/mobile/src/session/use-mobile-native-chat-streaming-bubble.ts b/mobile/src/session/use-mobile-native-chat-streaming-bubble.ts new file mode 100644 index 00000000000..632fa0b2282 --- /dev/null +++ b/mobile/src/session/use-mobile-native-chat-streaming-bubble.ts @@ -0,0 +1,31 @@ +import { useState } from 'react' +import type { NativeChatMessage } from '../../../src/shared/native-chat-types' +import { + createMobileNativeChatStreamingGate, + deriveMobileNativeChatStreaming +} from './mobile-native-chat-streaming-gate' + +/** Live streaming-bubble text for the chat list. The gate remembers which + * transcript tail predates the current stream segment, so a reply that repeats + * the previous turn's prefix still shows while streaming. Call this from a + * component that outlives the chat list itself: the baseline has to survive the + * view toggles that unmount it, or the next segment reverts to prefix-matching. + * `streamLive` keeps those textless gaps from reading as an idle stream. */ +export function useMobileNativeChatStreamingBubble( + folded: readonly NativeChatMessage[], + streamingText: string | undefined, + scopeKey: string, + streamLive: boolean +): string | null { + const [gate, setGate] = useState(() => createMobileNativeChatStreamingGate(scopeKey)) + const step = deriveMobileNativeChatStreaming(gate, folded, streamingText, { + scopeKey, + streamLive + }) + if (step.gate !== gate) { + // Render-time state adjustment (derived-state pattern): the advance is + // idempotent for a repeated (text, tail) pair, so this settles in one pass. + setGate(step.gate) + } + return step.streaming +} diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts new file mode 100644 index 00000000000..035f6c7476f --- /dev/null +++ b/mobile/src/stats/home-stats-total.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import { totalHomeStats, type HomeStatsSummary } from './home-stats-total' + +function stats(overrides: Partial = {}): HomeStatsSummary { + return { + totalAgentsSpawned: 10, + totalPRsCreated: 2, + totalAgentTimeMs: 60_000, + firstEventAt: 1_700_000_000_000, + ...overrides + } +} + +describe('totalHomeStats', () => { + it('has nothing to show before any host answers', () => { + expect(totalHomeStats({}, ['host-1'])).toBeNull() + }) + + it('passes a single host through unchanged', () => { + expect(totalHomeStats({ 'host-1': stats() }, ['host-1'])).toEqual(stats()) + }) + + it('sums every desktop instead of letting the last reply win', () => { + const total = totalHomeStats( + { + 'host-1': stats(), + 'host-2': stats({ totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 }) + }, + ['host-1', 'host-2'] + ) + + expect(total).toMatchObject({ + totalAgentsSpawned: 15, + totalPRsCreated: 3, + totalAgentTimeMs: 90_000 + }) + }) + + it('drops a removed desktop from the total', () => { + // Replies are cached for the life of the process, so the entry outlives the pairing. + const byHost = { + 'host-1': stats(), + 'host-2': stats({ totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 }) + } + + expect(totalHomeStats(byHost, ['host-1'])).toEqual(stats()) + expect(totalHomeStats(byHost, [])).toBeNull() + }) + + it('keeps the earliest known first event', () => { + const total = totalHomeStats( + { + 'host-1': stats({ firstEventAt: 2_000 }), + 'host-2': stats({ firstEventAt: null }), + 'host-3': stats({ firstEventAt: 1_000 }) + }, + ['host-1', 'host-2', 'host-3'] + ) + + expect(total?.firstEventAt).toBe(1_000) + }) + + it('reports no first event when no host has one', () => { + expect( + totalHomeStats({ 'host-1': stats({ firstEventAt: null }) }, ['host-1'])?.firstEventAt + ).toBeNull() + }) + + it('ignores a malformed reply instead of poisoning the header', () => { + const total = totalHomeStats( + { + 'host-1': stats(), + 'host-2': null as unknown as HomeStatsSummary, + 'host-3': { totalAgentsSpawned: 'lots' } as unknown as HomeStatsSummary + }, + ['host-1', 'host-2', 'host-3'] + ) + + expect(total).toEqual(stats()) + }) +}) diff --git a/mobile/src/stats/home-stats-total.ts b/mobile/src/stats/home-stats-total.ts new file mode 100644 index 00000000000..72264872561 --- /dev/null +++ b/mobile/src/stats/home-stats-total.ts @@ -0,0 +1,51 @@ +export type HomeStatsSummary = { + totalAgentsSpawned: number + totalPRsCreated: number + totalAgentTimeMs: number + firstEventAt: number | null +} + +/** + * Why: the home header shows one lifetime-usage row for every paired desktop. Each host answers + * stats.summary for itself, so a single shared slot made the row flip to whichever host replied + * last — visible churn now that every reconnect re-reads. Sum instead; one host still totals itself. + * + * Summing only `hostIds` keeps an unpaired desktop out of the total: replies are cached per host + * for the life of the process, so an entry outlives the host it describes. + */ +export function totalHomeStats( + byHost: Record, + hostIds: readonly string[] +): HomeStatsSummary | null { + const hosts = hostIds.filter((id) => id in byHost).map((id) => byHost[id]) + if (hosts.length === 0) { + return null + } + const total: HomeStatsSummary = { + totalAgentsSpawned: 0, + totalPRsCreated: 0, + totalAgentTimeMs: 0, + firstEventAt: null + } + for (const host of hosts) { + // The rows come straight off the wire unvalidated; a malformed desktop reply must not + // NaN out or crash the header for every other host. + if (!host || typeof host !== 'object') { + continue + } + total.totalAgentsSpawned += finiteOrZero(host.totalAgentsSpawned) + total.totalPRsCreated += finiteOrZero(host.totalPRsCreated) + total.totalAgentTimeMs += finiteOrZero(host.totalAgentTimeMs) + if (typeof host.firstEventAt === 'number' && Number.isFinite(host.firstEventAt)) { + total.firstEventAt = + total.firstEventAt === null + ? host.firstEventAt + : Math.min(total.firstEventAt, host.firstEventAt) + } + } + return total +} + +function finiteOrZero(value: number): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0 +} diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts new file mode 100644 index 00000000000..4c11320db2e --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from 'vitest' + +import { computeActiveTerminalKeyboardLift } from './terminal-keyboard-avoidance-lift' +import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' +import type { TerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' + +const FRAME_HEIGHT = 800 +const ROWS = 40 +const KEYBOARD_LIFT = 300 + +function metrics( + overrides: Partial = {} +): TerminalKeyboardAvoidanceMetrics { + return { cursorY: 0, contentBottomRow: 0, rows: ROWS, altScreen: false, ...overrides } +} + +describe('computeActiveTerminalKeyboardLift', () => { + it('returns 0 when the keyboard is closed', () => { + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: 0, + metrics: metrics({ cursorY: 30, contentBottomRow: 34 }), + terminalFrameHeight: FRAME_HEIGHT + }) + ).toBe(0) + }) + + it('falls back to the full lift when metrics are missing', () => { + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: undefined, + terminalFrameHeight: FRAME_HEIGHT + }) + ).toBe(KEYBOARD_LIFT) + }) + + it('falls back to the full lift when rows or frame height are unmeasured', () => { + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ rows: 0 }), + terminalFrameHeight: FRAME_HEIGHT + }) + ).toBe(KEYBOARD_LIFT) + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics(), + terminalFrameHeight: 0 + }) + ).toBe(KEYBOARD_LIFT) + }) + + it('lifts fully for alt-screen TUIs', () => { + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ cursorY: 10, contentBottomRow: 10, altScreen: true }), + terminalFrameHeight: FRAME_HEIGHT + }) + ).toBe(KEYBOARD_LIFT) + }) + + it('clears a main-buffer footer while an old payload retains cursor-only behavior', () => { + const candidate = computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ cursorY: 30, contentBottomRow: 34 }), + terminalFrameHeight: FRAME_HEIGHT + }) + const oldPayload = parseTerminalKeyboardAvoidanceMetrics({ cursorY: 30, rows: ROWS }) + const cursorOnly = computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: oldPayload, + terminalFrameHeight: FRAME_HEIGHT + }) + expect({ candidate, cursorOnly }).toEqual({ candidate: 220, cursorOnly: 140 }) + }) + + it('keeps short output near the top put (no lift)', () => { + expect( + computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ cursorY: 2, contentBottomRow: 5 }), + terminalFrameHeight: FRAME_HEIGHT + }) + ).toBe(0) + }) + + it('matches cursor-clearing behavior for a scrolled shell (prompt at the bottom)', () => { + const lift = computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ cursorY: 38, contentBottomRow: 38 }), + terminalFrameHeight: FRAME_HEIGHT + }) + expect(lift).toBe(KEYBOARD_LIFT) + }) + + it('never exceeds the keyboard lift', () => { + const lift = computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ cursorY: 39, contentBottomRow: 39 }), + terminalFrameHeight: FRAME_HEIGHT + }) + expect(lift).toBeLessThanOrEqual(KEYBOARD_LIFT) + }) + + it('uses the platform-adjusted lift proportionally on iOS and Android', () => { + const tuiMetrics = metrics({ cursorY: 30, contentBottomRow: 34 }) + const android = computeActiveTerminalKeyboardLift({ + keyboardLift: 300, + metrics: tuiMetrics, + terminalFrameHeight: FRAME_HEIGHT + }) + const ios = computeActiveTerminalKeyboardLift({ + keyboardLift: 266, + metrics: tuiMetrics, + terminalFrameHeight: FRAME_HEIGHT + }) + expect({ android, ios }).toEqual({ android: 220, ios: 186 }) + }) +}) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts new file mode 100644 index 00000000000..6ada640430d --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts @@ -0,0 +1,29 @@ +import type { TerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' + +type ActiveTerminalKeyboardLiftParams = { + keyboardLift: number + metrics: TerminalKeyboardAvoidanceMetrics | undefined + terminalFrameHeight: number +} + +export function computeActiveTerminalKeyboardLift( + params: ActiveTerminalKeyboardLiftParams +): number { + const { keyboardLift, metrics, terminalFrameHeight } = params + if (keyboardLift <= 0) { + return 0 + } + if (!metrics || metrics.rows <= 0 || terminalFrameHeight <= 0) { + return keyboardLift + } + if (metrics.altScreen) { + return keyboardLift + } + const rowHeight = terminalFrameHeight / metrics.rows + // Main-buffer TUI footer rows can sit below the caret. + const anchorRow = Math.max(metrics.cursorY, metrics.contentBottomRow) + const anchorBottom = (anchorRow + 1) * rowHeight + const dockTop = terminalFrameHeight - keyboardLift + const margin = rowHeight + return Math.min(keyboardLift, Math.max(0, anchorBottom + margin - dockTop)) +} diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-metrics-injected.ts b/mobile/src/terminal/terminal-keyboard-avoidance-metrics-injected.ts new file mode 100644 index 00000000000..a3a29ac61f9 --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-avoidance-metrics-injected.ts @@ -0,0 +1,43 @@ +export const TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS = ` + function lineHasVisibleContent(line, cell) { + if (line.translateToString(true).trim().length > 0) return true; + if (!cell || !line.getCell) return false; + var limit = Math.min(term.cols || 0, line.length || 0); + for (var x = 0; x < limit; x++) { + var current = line.getCell(x, cell); + if (!current) continue; + if (!current.isBgDefault() || current.isInverse()) return true; + if (typeof current.isUnderline === 'function' && current.isUnderline()) return true; + if (typeof current.isStrikethrough === 'function' && current.isStrikethrough()) return true; + if (typeof current.isOverline === 'function' && current.isOverline()) return true; + } + return false; + } + + function computeContentBottomRow() { + if (!term || !term.buffer || !term.buffer.active) return 0; + var buffer = term.buffer.active; + var top = buffer.viewportY || 0; + var cell = buffer.getNullCell ? buffer.getNullCell() : null; + for (var y = (term.rows || 0) - 1; y >= 0; y--) { + try { + var line = buffer.getLine(top + y); + if (line && lineHasVisibleContent(line, cell)) return y; + } catch (e) {} + } + return 0; + } + + function emitKeyboardAvoidanceMetrics() { + if (!term) return; + var alt = false; + try { alt = term.buffer && term.buffer.active && term.buffer.active.type === 'alternate'; } catch (e) {} + notify({ + type: 'keyboard-avoidance-metrics', + cursorY: term.buffer && term.buffer.active ? term.buffer.active.cursorY : 0, + contentBottomRow: alt ? 0 : computeContentBottomRow(), + rows: term.rows || 0, + altScreen: alt + }); + } +` diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts new file mode 100644 index 00000000000..3a09ae3acd4 --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -0,0 +1,215 @@ +import { readFileSync } from 'node:fs' +import { Script } from 'node:vm' +import { Terminal } from '@xterm/xterm' +import { describe, expect, it, vi } from 'vitest' +import { TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS } from './terminal-keyboard-avoidance-metrics-injected' +import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' + +const terminalHtmlSource = readFileSync( + new URL('./terminal-webview-html.ts', import.meta.url), + 'utf8' +) +const reflowSource = readFileSync( + new URL('./terminal-webview-reflow-injected.ts', import.meta.url), + 'utf8' +) + +type Cell = { isBgDefault: () => boolean; isInverse: () => number } +type MetricsNotification = { + type: string + cursorY: number + contentBottomRow: number + rows: number + altScreen: boolean +} + +function makeLine(text = '', styledColumns: number[] = []) { + const styled = new Set(styledColumns) + return { + isWrapped: false, + length: 10, + translateToString: vi.fn(() => text), + getCell: (column: number): Cell => ({ + isBgDefault: () => !styled.has(column), + isInverse: () => 0 + }) + } +} + +function runMetrics(lines: (ReturnType | undefined)[], altScreen = false) { + const notifications: Record[] = [] + const buffer = { + cursorY: 2, + viewportY: 3, + type: altScreen ? 'alternate' : 'normal', + getLine: (index: number) => lines[index - 3], + getNullCell: () => ({}) + } + const context = { + notifications, + notify: (message: Record) => notifications.push(message), + term: { buffer: { active: buffer }, cols: 10, rows: lines.length } + } + new Script( + `${TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS}\nemitKeyboardAvoidanceMetrics();` + ).runInNewContext(context) + return notifications[0] as MetricsNotification +} + +function runTerminalMetrics(term: Terminal) { + const notifications: Record[] = [] + new Script( + `${TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS}\nemitKeyboardAvoidanceMetrics();` + ).runInNewContext({ + notify: (message: Record) => notifications.push(message), + term + }) + return notifications[0] as MetricsNotification +} + +function write(term: Terminal, data: string): Promise { + return new Promise((resolve) => term.write(data, resolve)) +} + +describe('terminal keyboard-avoidance WebView metrics', () => { + it('finds text on wrapped rows using the visible viewport offset', () => { + const lines = [makeLine('header'), makeLine(''), makeLine('wrapped footer')] + lines[2]!.isWrapped = true + expect(runMetrics(lines)).toMatchObject({ contentBottomRow: 2 }) + }) + + it('supports cells without decoration APIs and keeps background-only ANSI chrome visible', () => { + expect(runMetrics([makeLine('header'), makeLine(''), makeLine('')])).toMatchObject({ + contentBottomRow: 0 + }) + expect(runMetrics([makeLine('header'), makeLine(''), makeLine('', [4])])).toMatchObject({ + contentBottomRow: 2 + }) + }) + + it('classifies real xterm text and styled whitespace by rendered visibility', async () => { + const cases = [ + { name: 'default spaces', data: ' ', expected: 0 }, + { name: 'text', data: 'footer', expected: 7 }, + { name: 'background', data: '\x1b[41m \x1b[0m', expected: 7 }, + { name: 'inverse', data: '\x1b[7m \x1b[0m', expected: 7 }, + { name: 'underline', data: '\x1b[4m \x1b[0m', expected: 7 }, + { name: 'strikethrough', data: '\x1b[9m \x1b[0m', expected: 7 }, + { name: 'overline', data: '\x1b[53m \x1b[0m', expected: 7 }, + // Hidden text still reserves TUI layout, so keyboard avoidance treats it as content. + { name: 'invisible text', data: '\x1b[8mfooter\x1b[0m', expected: 7 } + ] + + for (const { name, data, expected } of cases) { + const term = new Terminal({ cols: 10, rows: 8 }) + try { + await write(term, `\x1b[8;1H${data}`) + expect(runTerminalMetrics(term), name).toMatchObject({ contentBottomRow: expected }) + } finally { + term.dispose() + } + } + }) + + it('tracks the real xterm viewport and alternate screen', async () => { + const term = new Terminal({ cols: 10, rows: 4, scrollback: 100 }) + try { + await write(term, 'header\r\n\r\n\r\n\r\nfooter') + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 3, altScreen: false }) + term.scrollLines(-2) + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 0, altScreen: false }) + await write(term, '\x1b[?1049h\x1b[4m \x1b[0m') + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 0, altScreen: true }) + } finally { + term.dispose() + } + }) + + it('follows real xterm resize and reset state', async () => { + const term = new Terminal({ cols: 10, rows: 8 }) + try { + await write(term, '\x1b[8;1Hfooter') + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 7 }) + term.resize(10, 4) + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 3 }) + term.reset() + expect(runTerminalMetrics(term)).toMatchObject({ contentBottomRow: 0 }) + } finally { + term.dispose() + } + }) + + it('keeps real xterm metrics compatible with old payloads', async () => { + const term = new Terminal({ cols: 10, rows: 8 }) + try { + await write(term, '\x1b[8;1Hfooter\x1b[2;1H') + const { cursorY, rows, altScreen } = runTerminalMetrics(term) + expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY, rows, altScreen })).toEqual({ + cursorY: 1, + contentBottomRow: 1, + rows: 8, + altScreen: false + }) + } finally { + term.dispose() + } + }) + + it('releases real xterm metric observers across terminal lifecycles', async () => { + for (let cycle = 0; cycle < 25; cycle += 1) { + const term = new Terminal({ cols: 10, rows: 4 }) + let emissions = 0 + const observer = term.onWriteParsed(() => { + runTerminalMetrics(term) + emissions += 1 + }) + try { + await write(term, `cycle ${cycle}`) + expect(emissions).toBeGreaterThan(0) + observer.dispose() + const disposedAt = emissions + await write(term, ' after dispose') + expect(emissions).toBe(disposedAt) + } finally { + observer.dispose() + term.dispose() + } + } + }) + + it('stops at the first bottom-up match and skips scans on alternate screen', () => { + const footer = makeLine('footer') + const header = makeLine('header') + expect(runMetrics([header, makeLine(''), footer])).toMatchObject({ contentBottomRow: 2 }) + expect(footer.translateToString).toHaveBeenCalledTimes(1) + expect(header.translateToString).not.toHaveBeenCalled() + + footer.translateToString.mockImplementation(() => { + throw new Error('alternate screen must not scan') + }) + expect(runMetrics([header, makeLine(''), footer], true)).toMatchObject({ + altScreen: true, + contentBottomRow: 0 + }) + }) + + it('refreshes metrics after every buffer geometry reset', () => { + const resizeStart = terminalHtmlSource.indexOf(' function resize(cols, rows)') + const resizeEnd = terminalHtmlSource.indexOf('\n // reflow()', resizeStart) + const clearStart = terminalHtmlSource.indexOf("} else if (msg.type === 'clear') {") + const clearEnd = terminalHtmlSource.indexOf("} else if (msg.type === 'measure')", clearStart) + const textScaleStart = terminalHtmlSource.indexOf(' function applyTextScale(scale)') + const textScaleEnd = terminalHtmlSource.indexOf('\n var panX', textScaleStart) + + for (const block of [ + terminalHtmlSource.slice(resizeStart, resizeEnd), + terminalHtmlSource.slice(clearStart, clearEnd), + terminalHtmlSource.slice(textScaleStart, textScaleEnd), + reflowSource + ]) { + expect(block.indexOf('emitKeyboardAvoidanceMetrics()')).toBeGreaterThan( + block.includes('term.resize') ? block.indexOf('term.resize') : block.indexOf('term.reset') + ) + } + }) +}) diff --git a/mobile/src/terminal/terminal-webview-contract.test.ts b/mobile/src/terminal/terminal-webview-contract.test.ts new file mode 100644 index 00000000000..0a3527111e3 --- /dev/null +++ b/mobile/src/terminal/terminal-webview-contract.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest' + +import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' + +describe('parseTerminalKeyboardAvoidanceMetrics', () => { + it('parses a full payload', () => { + expect( + parseTerminalKeyboardAvoidanceMetrics({ + cursorY: 30, + contentBottomRow: 34, + rows: 40, + altScreen: true + }) + ).toEqual({ cursorY: 30, contentBottomRow: 34, rows: 40, altScreen: true }) + }) + + it('defaults contentBottomRow to cursorY when absent (older WebView bundles)', () => { + expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY: 12, rows: 40 })).toEqual({ + cursorY: 12, + contentBottomRow: 12, + rows: 40, + altScreen: false + }) + }) + + it('defaults non-numeric fields to zero', () => { + expect(parseTerminalKeyboardAvoidanceMetrics({})).toEqual({ + cursorY: 0, + contentBottomRow: 0, + rows: 0, + altScreen: false + }) + }) + + it('bounds untrusted numeric fields to the reported viewport', () => { + expect( + parseTerminalKeyboardAvoidanceMetrics({ + cursorY: Number.POSITIVE_INFINITY, + contentBottomRow: 99.8, + rows: 40.7, + altScreen: 'true' + }) + ).toEqual({ cursorY: 0, contentBottomRow: 39, rows: 40, altScreen: false }) + expect( + parseTerminalKeyboardAvoidanceMetrics({ + cursorY: -4, + contentBottomRow: Number.NaN, + rows: -1 + }) + ).toEqual({ cursorY: 0, contentBottomRow: 0, rows: 0, altScreen: false }) + }) +}) diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.ts index 63c155b7a23..c28fd4a5038 100644 --- a/mobile/src/terminal/terminal-webview-contract.ts +++ b/mobile/src/terminal/terminal-webview-contract.ts @@ -14,10 +14,34 @@ export type TerminalModes = { export type TerminalKeyboardAvoidanceMetrics = { cursorY: number + // Main-buffer TUIs can render footer rows below the caret. + contentBottomRow: number rows: number altScreen: boolean } +export function parseTerminalKeyboardAvoidanceMetrics( + msg: Record +): TerminalKeyboardAvoidanceMetrics { + const rows = toNonNegativeInteger(msg.rows) + const maxRow = Math.max(0, rows - 1) + const cursorY = Math.min(toNonNegativeInteger(msg.cursorY), maxRow) + const contentBottomRow = + msg.contentBottomRow === undefined + ? cursorY + : Math.min(toNonNegativeInteger(msg.contentBottomRow), maxRow) + return { + cursorY, + contentBottomRow, + rows, + altScreen: msg.altScreen === true + } +} + +function toNonNegativeInteger(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0 +} + export type MobileTerminalTheme = RuntimeMobileTerminalTheme export type TerminalSelectionEvents = { diff --git a/mobile/src/terminal/terminal-webview-html.ts b/mobile/src/terminal/terminal-webview-html.ts index a7715e4f564..c3ba29bb542 100644 --- a/mobile/src/terminal/terminal-webview-html.ts +++ b/mobile/src/terminal/terminal-webview-html.ts @@ -3,6 +3,7 @@ import type { RuntimeMobileTerminalTheme } from '../../../src/shared/runtime-typ import { colors } from '../theme/mobile-theme' import { TERMINAL_TEXT_SCALES } from '../storage/preferences' import { TERMINAL_PATH_TAP_JS } from './terminal-path-tap-injected' +import { TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS } from './terminal-keyboard-avoidance-metrics-injected' import { XTERM_ENGINE_CSS, XTERM_ENGINE_JS } from './terminal-webview-engine.generated' import { TERMINAL_REFLOW_JS } from './terminal-webview-reflow-injected' import { TERMINAL_SURFACE_SWAP_JS } from './terminal-webview-surface-swap-injected' @@ -287,6 +288,7 @@ window.onerror = function(msg) { if (cols < MIN_FIT_COLS) return; var rows = Math.max(8, Math.floor(window.innerHeight / cellH)); term.resize(cols, rows); + emitKeyboardAvoidanceMetrics(); } applyFitScale('text-scale'); }); @@ -802,6 +804,7 @@ ${TERMINAL_WEBGL_RECOVERY_JS} if (!term) return; initRows = rows || initRows; term.resize(cols || term.cols, rows || term.rows); + emitKeyboardAvoidanceMetrics(); applyFitScale('resize-msg'); notify({ type: 'ready', cols: cols, rows: rows }); } @@ -958,6 +961,7 @@ ${TERMINAL_WEBGL_RECOVERY_JS} initialOscLinkEvictionReady = false; if (term) { term.clear(); term.reset(); } emitModesIfChanged(); + emitKeyboardAvoidanceMetrics(); resetEvictionCounter(); if (selMode === 'select') { notify({ type: 'selection-evicted' }); @@ -1100,17 +1104,7 @@ ${TERMINAL_WEBGL_RECOVERY_JS} sgrMousePixelsMode: false }; - function emitKeyboardAvoidanceMetrics() { - if (!term) return; - var alt = false; - try { alt = term.buffer && term.buffer.active && term.buffer.active.type === 'alternate'; } catch (e) {} - notify({ - type: 'keyboard-avoidance-metrics', - cursorY: term.buffer && term.buffer.active ? term.buffer.active.cursorY : 0, - rows: term.rows || 0, - altScreen: alt - }); - } + ${TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS} function attachTermObservers() { if (!term) return; diff --git a/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts b/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts new file mode 100644 index 00000000000..bcd777a2e8f --- /dev/null +++ b/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest' + +import { dispatchTerminalWebViewNotification } from './terminal-webview-notification-dispatch' + +describe('dispatchTerminalWebViewNotification', () => { + it('preserves bounded keyboard metrics through the dispatcher', () => { + const onKeyboardAvoidanceMetrics = vi.fn() + dispatchTerminalWebViewNotification( + { + type: 'keyboard-avoidance-metrics', + cursorY: 30, + contentBottomRow: 99, + rows: 40, + altScreen: true + }, + { onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() } + ) + expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({ + cursorY: 30, + contentBottomRow: 39, + rows: 40, + altScreen: true + }) + }) + + it('keeps old WebView payloads cursor-compatible', () => { + const onKeyboardAvoidanceMetrics = vi.fn() + dispatchTerminalWebViewNotification( + { type: 'keyboard-avoidance-metrics', cursorY: 12, rows: 40 }, + { onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() } + ) + expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({ + cursorY: 12, + contentBottomRow: 12, + rows: 40, + altScreen: false + }) + }) +}) diff --git a/mobile/src/terminal/terminal-webview-notification-dispatch.ts b/mobile/src/terminal/terminal-webview-notification-dispatch.ts index 372df650fe0..77019d3f996 100644 --- a/mobile/src/terminal/terminal-webview-notification-dispatch.ts +++ b/mobile/src/terminal/terminal-webview-notification-dispatch.ts @@ -1,4 +1,7 @@ -import type { TerminalSelectionEvents } from './terminal-webview-contract' +import { + parseTerminalKeyboardAvoidanceMetrics, + type TerminalSelectionEvents +} from './terminal-webview-contract' export type TerminalWebViewNotificationHandlers = Omit< TerminalSelectionEvents, @@ -63,13 +66,7 @@ export function dispatchTerminalWebViewNotification( handlers.onOpenUrl?.(url) } } else if (msg.type === 'keyboard-avoidance-metrics') { - const cursorY = typeof msg.cursorY === 'number' ? msg.cursorY : 0 - const rows = typeof msg.rows === 'number' ? msg.rows : 0 - handlers.onKeyboardAvoidanceMetrics?.({ - cursorY, - rows, - altScreen: !!msg.altScreen - }) + handlers.onKeyboardAvoidanceMetrics?.(parseTerminalKeyboardAvoidanceMetrics(msg)) } else if (msg.type === 'haptic') { const kind = msg.kind if (kind === 'selection' || kind === 'success' || kind === 'error' || kind === 'edge-bump') { diff --git a/mobile/src/terminal/terminal-webview-reflow-injected.ts b/mobile/src/terminal/terminal-webview-reflow-injected.ts index 4fea62f5107..ef704529e4b 100644 --- a/mobile/src/terminal/terminal-webview-reflow-injected.ts +++ b/mobile/src/terminal/terminal-webview-reflow-injected.ts @@ -28,5 +28,6 @@ export const TERMINAL_REFLOW_JS = ` } applyFitScale('reflow-msg'); updateScrollIndicator(false); + emitKeyboardAvoidanceMetrics(); } ` diff --git a/mobile/src/transport/host-connect-refetch-gate.test.ts b/mobile/src/transport/host-connect-refetch-gate.test.ts new file mode 100644 index 00000000000..17b3d68ae24 --- /dev/null +++ b/mobile/src/transport/host-connect-refetch-gate.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { createHostConnectRefetchGate } from './host-connect-refetch-gate' +import type { ConnectionState } from './types' + +function refetchesFor(states: ConnectionState[]): number { + const gate = createHostConnectRefetchGate() + return states.filter((state) => gate.observe(state)).length +} + +describe('createHostConnectRefetchGate', () => { + it('fetches once on the first connect', () => { + expect(refetchesFor(['connecting', 'handshaking', 'connected'])).toBe(1) + }) + + it('fetches again after a dropped socket comes back', () => { + expect( + refetchesFor(['connected', 'reconnecting', 'connecting', 'handshaking', 'connected']) + ).toBe(2) + }) + + it('does not storm while the connection holds', () => { + expect(refetchesFor(['connected', 'connected', 'connected'])).toBe(1) + }) + + it('never fetches while the host stays down', () => { + expect(refetchesFor(['connecting', 'disconnected', 'reconnecting', 'auth-failed'])).toBe(0) + }) +}) diff --git a/mobile/src/transport/host-connect-refetch-gate.ts b/mobile/src/transport/host-connect-refetch-gate.ts new file mode 100644 index 00000000000..4ce2ba885fc --- /dev/null +++ b/mobile/src/transport/host-connect-refetch-gate.ts @@ -0,0 +1,18 @@ +import type { ConnectionState } from './types' + +// Why: a logical client survives socket drops, so screens that fetch once per client latched +// after the first connect and never refreshed after a background/handoff reconnect. Gate the +// refetch on the transition INTO 'connected' — one read per reconnect, no polling timer. +export function createHostConnectRefetchGate(): { + observe: (state: ConnectionState) => boolean +} { + let connected = false + return { + observe(state) { + const nowConnected = state === 'connected' + const crossedIntoConnected = nowConnected && !connected + connected = nowConnected + return crossedIntoConnected + } + } +} diff --git a/mobile/src/transport/host-edit-navigation.test.ts b/mobile/src/transport/host-edit-navigation.test.ts index 66ca63c5efa..2e3e8a9f5b2 100644 --- a/mobile/src/transport/host-edit-navigation.test.ts +++ b/mobile/src/transport/host-edit-navigation.test.ts @@ -1,29 +1,95 @@ import { describe, expect, it, vi } from 'vitest' -import { mobileHostEditRoute, navigateToMobileHostEdit } from './host-edit-navigation' +import { + mobileHostEditHostRoute, + mobileHostEditRoute, + navigateToMobileHostEdit, + type MobileHostEditNavigationState +} from './host-edit-navigation' -describe('mobileHostEditRoute', () => { - it('keeps the dynamic host segment explicit for a cold host navigator', () => { - expect(mobileHostEditRoute('host-1')).toEqual({ - pathname: '/h/[hostId]/edit', - params: { hostId: 'host-1' } - }) - }) +function navigationHarness(initialState: MobileHostEditNavigationState) { + let stateListener = () => {} + let state = initialState + const unsubscribeState = vi.fn() + const navigation = { + addListener: vi.fn((_event: 'state', listener: () => void) => { + stateListener = listener + return unsubscribeState + }), + getState: () => state + } + return { + navigation, + setState(nextState: MobileHostEditNavigationState) { + state = nextState + stateListener() + }, + unsubscribeState + } +} - it('mounts a cold host navigator before replacing its index with edit', () => { - let nextFrame: FrameRequestCallback | null = null +describe('mobile host edit navigation', () => { + it('waits for the expected host route to commit before replacing it with Edit', () => { + const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) const push = vi.fn() const replace = vi.fn() - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - nextFrame = callback - return 1 - }) - navigateToMobileHostEdit({ push, replace }, 'host-1') - expect(push).toHaveBeenCalledWith('/h/host-1') + navigateToMobileHostEdit(harness.navigation, { push, replace }, 'host/1') + + expect(push).toHaveBeenCalledWith(mobileHostEditHostRoute('host/1')) expect(replace).not.toHaveBeenCalled() - nextFrame?.(0) - expect(replace).toHaveBeenCalledWith(mobileHostEditRoute('host-1')) - vi.unstubAllGlobals() + harness.setState({ + index: 1, + routes: [{ name: 'index' }, { name: 'h', params: { hostId: 'host/1' } }] + }) + + expect(harness.unsubscribeState).toHaveBeenCalledOnce() + expect(replace).toHaveBeenCalledWith(mobileHostEditRoute('host/1')) + }) + + it('does not replace an unrelated host route', () => { + const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) + const replace = vi.fn() + + navigateToMobileHostEdit(harness.navigation, { push: vi.fn(), replace }, 'host-1') + harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-2' } }] }) + + expect(replace).not.toHaveBeenCalled() + }) + + it('cancels a pending replacement when navigation leaves the host flow', () => { + const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) + const replace = vi.fn() + const controller = navigateToMobileHostEdit( + harness.navigation, + { push: vi.fn(), replace }, + 'host-1' + ) + + harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-2' } }] }) + controller.cancel() + harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-1' } }] }) + + expect(harness.unsubscribeState).toHaveBeenCalledOnce() + expect(replace).not.toHaveBeenCalled() + }) + + it('unsubscribes when mounting the host throws synchronously', () => { + const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) + const error = new Error('navigation failed') + + expect(() => + navigateToMobileHostEdit( + harness.navigation, + { + push: () => { + throw error + }, + replace: vi.fn() + }, + 'host-1' + ) + ).toThrow(error) + expect(harness.unsubscribeState).toHaveBeenCalledOnce() }) }) diff --git a/mobile/src/transport/host-edit-navigation.ts b/mobile/src/transport/host-edit-navigation.ts index 19dbf703dec..765e36d7b5a 100644 --- a/mobile/src/transport/host-edit-navigation.ts +++ b/mobile/src/transport/host-edit-navigation.ts @@ -1,8 +1,31 @@ -type HostEditRouter = { +export type MobileHostEditNavigationState = Readonly<{ + index: number + routes: readonly MobileHostEditNavigationRoute[] +}> + +export type MobileHostEditNavigationRoute = Readonly<{ + name: string + params?: Readonly<{ hostId?: unknown }> +}> + +export type MobileHostEditRootNavigation = { + addListener: (event: 'state', listener: () => void) => () => void + getState: () => MobileHostEditNavigationState +} + +export type MobileHostEditRouter = { push: (href: `/h/${string}`) => void replace: (href: ReturnType) => void } +export type MobileHostEditNavigationController = Readonly<{ + cancel: () => void +}> + +export function mobileHostEditHostRoute(hostId: string): `/h/${string}` { + return `/h/${encodeURIComponent(hostId)}` +} + export function mobileHostEditRoute(hostId: string) { return { pathname: '/h/[hostId]/edit' as const, @@ -10,10 +33,49 @@ export function mobileHostEditRoute(hostId: string) { } } -export function navigateToMobileHostEdit(router: HostEditRouter, hostId: string): void { - // Why: a cold nested host navigator resolves a deep push to its index route. - router.push(`/h/${hostId}`) - requestAnimationFrame(() => { +export function navigateToMobileHostEdit( + navigation: MobileHostEditRootNavigation, + router: MobileHostEditRouter, + hostId: string +): MobileHostEditNavigationController { + let active = true + let hostRouteSeen = false + let unsubscribeState = () => {} + const dispose = () => { + if (!active) { + return + } + active = false + unsubscribeState() + } + + // Why: cold Expo deep links resolve to index; target Edit after the host route commits. + const onState = () => { + if (!active) { + return + } + const state = navigation.getState() + const currentRoute = state.routes[state.index] + if (currentRoute?.name !== 'h') { + if (hostRouteSeen) { + dispose() + } + return + } + hostRouteSeen = true + if (currentRoute.params?.hostId !== hostId) { + return + } + dispose() router.replace(mobileHostEditRoute(hostId)) - }) + } + + try { + unsubscribeState = navigation.addListener('state', onState) + router.push(mobileHostEditHostRoute(hostId)) + } catch (error) { + dispose() + throw error + } + return { cancel: dispose } } diff --git a/mobile/src/transport/mobile-direct-return-probe.ts b/mobile/src/transport/mobile-direct-return-probe.ts new file mode 100644 index 00000000000..dfb0572aa38 --- /dev/null +++ b/mobile/src/transport/mobile-direct-return-probe.ts @@ -0,0 +1,83 @@ +import { openAuthenticatedDirectEndpoint } from './mobile-direct-endpoint-probe' +import type { MobileEndpointHysteresis } from './mobile-endpoint-hysteresis' +import type { RpcClient } from './rpc-client' +import type { HostProfile } from './types' +import type { MobileConnectionPath } from './stable-logical-rpc-client' + +const DIRECT_PROBE_INTERVAL_MS = 15_000 + +// While the runtime channel rides the relay, periodically probe the direct +// endpoint and migrate back once hysteresis proves it stable. +export class DirectReturnProbe { + private timer: ReturnType | null = null + + constructor( + private readonly deps: { + now: () => number + setTimer: typeof setTimeout + clearTimer: typeof clearTimeout + openDirect: (endpoint: string) => RpcClient + }, + private readonly hooks: { + hysteresis: MobileEndpointHysteresis + host: () => HostProfile + canSchedule: () => boolean + canAttempt: () => boolean + beginOperation: () => void + migrate: (client: RpcClient, path: MobileConnectionPath) => Promise + onDirectMigrated: () => Promise + afterProbe: () => void + } + ) {} + + schedule(delayMs = DIRECT_PROBE_INTERVAL_MS): void { + if (!this.hooks.canSchedule() || this.timer) { + return + } + this.timer = this.deps.setTimer(() => { + this.timer = null + void this.probe() + }, delayMs) + } + + clear(): void { + if (this.timer) { + this.deps.clearTimer(this.timer) + this.timer = null + } + } + + private async probe(): Promise { + if (!this.hooks.canAttempt() || !this.hooks.hysteresis.canProbe(this.deps.now())) { + this.schedule() + return + } + this.hooks.beginOperation() + let successful: Awaited> = null + try { + successful = await openAuthenticatedDirectEndpoint( + this.hooks.host(), + this.deps.openDirect, + 12_000 + ) + if (!successful) { + this.hooks.hysteresis.recordDirectFailure(this.deps.now()) + return + } + if (!this.hooks.hysteresis.recordDirectSuccess(this.deps.now())) { + successful.client.close() + return + } + await this.hooks.migrate(successful.client, successful.path) + successful = null + this.hooks.hysteresis.recordMigration(this.deps.now()) + await this.hooks.onDirectMigrated() + } finally { + successful?.client.close() + // Why: a relay drop or backoff timer can arrive while the probe owns the + // operation mutex; afterProbe releases it and replays deferred recovery. + this.hooks.afterProbe() + this.schedule() + } + } +} diff --git a/mobile/src/transport/mobile-endpoint-lifecycle.ts b/mobile/src/transport/mobile-endpoint-lifecycle.ts index 57881022a56..d41898152c3 100644 --- a/mobile/src/transport/mobile-endpoint-lifecycle.ts +++ b/mobile/src/transport/mobile-endpoint-lifecycle.ts @@ -90,6 +90,7 @@ function createSupervisor( readBundle: readMobileRelayCredentialBundle, writeBundle: writeMobileRelayCredentialBundle, saveHost, + onLog, now: Date.now, randomBytes: ExpoCrypto.getRandomBytes, setTimer: setTimeout, diff --git a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts index d26e0706f70..0098de6e079 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts @@ -3,7 +3,7 @@ import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bund import type { MobileRelayRpcSession } from './mobile-relay-rpc-session' import type { resolveMobileRelayEndpoint } from './mobile-relay-resume-director' import type { RpcClient } from './rpc-client' -import type { HostProfile } from './types' +import type { ConnectionLogSink, HostProfile } from './types' export type MobileEndpointSupervisorDependencies = { openDirect: (endpoint: string) => RpcClient @@ -20,4 +20,5 @@ export type MobileEndpointSupervisorDependencies = { randomBytes: (length: number) => Uint8Array setTimer: typeof setTimeout clearTimer: typeof clearTimeout + onLog?: ConnectionLogSink } diff --git a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts new file mode 100644 index 00000000000..d483c6536e8 --- /dev/null +++ b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts @@ -0,0 +1,169 @@ +import { vi } from 'vitest' +import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' +import type { MobileRelayRpcSession } from './mobile-relay-rpc-session' +import type { MobileEndpointSupervisorDependencies } from './mobile-endpoint-supervisor' +import type { RpcClient } from './rpc-client' +import type { MobileConnectionPath, StableLogicalRpcClient } from './stable-logical-rpc-client' +import type { ConnectionState, HostProfile, RpcResponse } from './types' + +export class FakeSession implements RpcClient { + readonly sendRequest = vi.fn( + async (_method: string, _params?: unknown): Promise => ({ + id: 'rpc-1', + ok: true, + result: {}, + _meta: { runtimeId: 'runtime-1' } + }) + ) + readonly subscribe = vi.fn(() => () => {}) + readonly updateTerminalSubscriptionViewport = vi.fn() + readonly notifyForeground = vi.fn() + readonly close = vi.fn() + private readonly listeners = new Set<(state: ConnectionState) => void>() + + constructor(private state: ConnectionState) {} + + getState = () => this.state + getReconnectAttempt = () => 0 + getLastConnectedAt = () => null + onStateChange = (listener: (state: ConnectionState) => void) => { + this.listeners.add(listener) + return () => this.listeners.delete(listener) + } + + publishState(state: ConnectionState): void { + this.state = state + for (const listener of this.listeners) { + listener(state) + } + } +} + +export class FakeRelaySession extends FakeSession implements MobileRelayRpcSession { + constructor( + state: ConnectionState, + private readonly failure: Error | null = null, + private readonly resumeExpiry = Date.now() + 30 * 24 * 3_600_000, + private readonly renewed = true + ) { + super(state) + } + // Why: production-realistic defaults — fictional fake values hid three + // live defects in this subsystem (latch, churn, int32 timer overflow). + getAttachDeadlineAt = () => Date.now() + 10_000 + getResumeExpiresAt = () => this.resumeExpiry + getResumeConfirmation = () => ({ + v: 1 as const, + reqId: 'confirm-1', + currentVersion: 2, + acceptedAs: this.renewed ? ('current' as const) : ('grace' as const), + renewed: this.renewed, + resumeExpiresAt: this.resumeExpiry + }) + getFailure = () => this.failure +} + +export class FakeLogicalClient extends FakeSession implements StableLogicalRpcClient { + private path: MobileConnectionPath + private generation = 1 + + constructor(state: ConnectionState, path: MobileConnectionPath) { + super(state) + this.path = path + } + + migrateTo = vi.fn(async (session: RpcClient, path: MobileConnectionPath) => { + if (session.getState() !== 'connected') { + session.close() + throw new Error(`replacement session ${session.getState()}`) + } + this.path = path + this.generation += 1 + this.publishState('connected') + }) + suspendActiveSession = vi.fn(() => this.publishState('disconnected')) + getActivePath = () => this.path + getGeneration = () => this.generation +} + +export const relay = { + v: 1 as const, + directorUrl: 'https://relay.onorca.dev', + cellUrl: 'https://relay-c1.onorca.dev', + assignmentEpoch: 7, + relayHostId: 'AbCdEf0123_-xyZ9', + e2eeFraming: 2 as const +} +export const host: HostProfile = { + id: 'host-1', + name: 'Blue Whale', + endpoint: 'ws://192.168.1.10:6768', + deviceToken: 'device-token', + publicKeyB64: 'A'.repeat(44), + lastConnected: 1, + endpoints: [ + { id: 'direct-primary', kind: 'lan', url: 'ws://192.168.1.10:6768' }, + { id: 'relay-primary', kind: 'relay', url: 'wss://relay-c1.onorca.dev/v1/connect/id' } + ], + relayHostId: relay.relayHostId, + relay +} +export const bundle: MobileRelayCredentialBundle = { + v: 1, + hostId: host.id, + deviceToken: host.deviceToken, + current: { + token: 'A'.repeat(43), + hash: 'B'.repeat(43), + version: 2, + expiresAt: Number.MAX_SAFE_INTEGER + } +} + +export function dependencies( + overrides: Partial = {} +): MobileEndpointSupervisorDependencies { + return { + openDirect: vi.fn(() => new FakeSession('connected')), + openRelay: vi.fn(() => new FakeRelaySession('connected')), + resolveRelay: vi.fn(async ({ relay }) => relay), + readBundle: vi.fn(async () => bundle), + writeBundle: vi.fn(async () => {}), + saveHost: vi.fn(async () => {}), + now: Date.now, + randomBytes: (length) => new Uint8Array(length).fill(1), + setTimer: setTimeout, + clearTimer: clearTimeout, + ...overrides + } +} + +export function mockCredentialRotation(logical: FakeLogicalClient): void { + let installResult: Record | null = null + logical.sendRequest.mockImplementation(async (method, params) => { + const request = params as { installReqId?: string; reqId?: string } + if (method === 'pairing.provisionRelay') { + installResult = { + v: 1, + reqId: request.reqId, + authorizationMode: 'authenticated-direct', + currentVersion: 3, + resumeExpiresAt: Date.now() + 300_000, + graceExpiresAt: Date.now() + 60_000 + } + return { id: 'rpc-2', ok: true, result: installResult, _meta: { runtimeId: 'runtime-1' } } + } + return { + id: 'rpc-1', + ok: true, + result: { + v: 1, + relay, + installStatus: installResult + ? { v: 1, reqId: request.installReqId, state: 'committed', result: installResult } + : { v: 1, reqId: request.installReqId, state: 'not-found' } + }, + _meta: { runtimeId: 'runtime-1' } + } + }) +} diff --git a/mobile/src/transport/mobile-endpoint-supervisor.test.ts b/mobile/src/transport/mobile-endpoint-supervisor.test.ts index 3ec05f5ef1e..d1b8b6918cd 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.test.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.test.ts @@ -2,177 +2,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' import { hashMobileRelayCredential } from './mobile-relay-credential-hash' import { RelayOuterError } from './mobile-relay-e2ee-link' -import type { MobileRelayRpcSession } from './mobile-relay-rpc-session' import { - MobileEndpointSupervisor, - type MobileEndpointSupervisorDependencies -} from './mobile-endpoint-supervisor' -import type { RpcClient } from './rpc-client' -import type { MobileConnectionPath, StableLogicalRpcClient } from './stable-logical-rpc-client' -import type { ConnectionState, HostProfile, RpcResponse } from './types' + bundle, + dependencies, + FakeLogicalClient, + FakeRelaySession, + FakeSession, + host, + mockCredentialRotation, + relay +} from './mobile-endpoint-supervisor-test-fakes' +import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) -class FakeSession implements RpcClient { - readonly sendRequest = vi.fn( - async (_method: string, _params?: unknown): Promise => ({ - id: 'rpc-1', - ok: true, - result: {}, - _meta: { runtimeId: 'runtime-1' } - }) - ) - readonly subscribe = vi.fn(() => () => {}) - readonly updateTerminalSubscriptionViewport = vi.fn() - readonly notifyForeground = vi.fn() - readonly close = vi.fn() - private readonly listeners = new Set<(state: ConnectionState) => void>() - - constructor(private state: ConnectionState) {} - - getState = () => this.state - getReconnectAttempt = () => 0 - getLastConnectedAt = () => null - onStateChange = (listener: (state: ConnectionState) => void) => { - this.listeners.add(listener) - return () => this.listeners.delete(listener) - } - - publishState(state: ConnectionState): void { - this.state = state - for (const listener of this.listeners) { - listener(state) - } - } -} - -class FakeRelaySession extends FakeSession implements MobileRelayRpcSession { - constructor( - state: ConnectionState, - private readonly failure: Error | null = null, - private readonly lease = Date.now() + 120_000 - ) { - super(state) - } - getLeaseExpiresAt = () => this.lease - getResumeConfirmation = () => ({ - v: 1 as const, - reqId: 'confirm-1', - currentVersion: 2, - acceptedAs: 'current' as const, - renewed: true, - resumeExpiresAt: Date.now() + 300_000 - }) - getFailure = () => this.failure -} - -class FakeLogicalClient extends FakeSession implements StableLogicalRpcClient { - private path: MobileConnectionPath - private generation = 1 - - constructor(state: ConnectionState, path: MobileConnectionPath) { - super(state) - this.path = path - } - - migrateTo = vi.fn(async (session: RpcClient, path: MobileConnectionPath) => { - if (session.getState() !== 'connected') { - session.close() - throw new Error(`replacement session ${session.getState()}`) - } - this.path = path - this.generation += 1 - this.publishState('connected') - }) - suspendActiveSession = vi.fn(() => this.publishState('disconnected')) - getActivePath = () => this.path - getGeneration = () => this.generation -} - -const relay = { - v: 1 as const, - directorUrl: 'https://relay.onorca.dev', - cellUrl: 'https://relay-c1.onorca.dev', - assignmentEpoch: 7, - relayHostId: 'AbCdEf0123_-xyZ9', - e2eeFraming: 2 as const -} -const host: HostProfile = { - id: 'host-1', - name: 'Blue Whale', - endpoint: 'ws://192.168.1.10:6768', - deviceToken: 'device-token', - publicKeyB64: 'A'.repeat(44), - lastConnected: 1, - endpoints: [ - { id: 'direct-primary', kind: 'lan', url: 'ws://192.168.1.10:6768' }, - { id: 'relay-primary', kind: 'relay', url: 'wss://relay-c1.onorca.dev/v1/connect/id' } - ], - relayHostId: relay.relayHostId, - relay -} -const bundle: MobileRelayCredentialBundle = { - v: 1, - hostId: host.id, - deviceToken: host.deviceToken, - current: { - token: 'A'.repeat(43), - hash: 'B'.repeat(43), - version: 2, - expiresAt: Number.MAX_SAFE_INTEGER - } -} - -function dependencies( - overrides: Partial = {} -): MobileEndpointSupervisorDependencies { - return { - openDirect: vi.fn(() => new FakeSession('connected')), - openRelay: vi.fn(() => new FakeRelaySession('connected')), - resolveRelay: vi.fn(async ({ relay }) => relay), - readBundle: vi.fn(async () => bundle), - writeBundle: vi.fn(async () => {}), - saveHost: vi.fn(async () => {}), - now: Date.now, - randomBytes: (length) => new Uint8Array(length).fill(1), - setTimer: setTimeout, - clearTimer: clearTimeout, - ...overrides - } -} - -function mockCredentialRotation(logical: FakeLogicalClient): void { - let installResult: Record | null = null - logical.sendRequest.mockImplementation(async (method, params) => { - const request = params as { installReqId?: string; reqId?: string } - if (method === 'pairing.provisionRelay') { - installResult = { - v: 1, - reqId: request.reqId, - authorizationMode: 'authenticated-direct', - currentVersion: 3, - resumeExpiresAt: Date.now() + 300_000, - graceExpiresAt: Date.now() + 60_000 - } - return { id: 'rpc-2', ok: true, result: installResult, _meta: { runtimeId: 'runtime-1' } } - } - return { - id: 'rpc-1', - ok: true, - result: { - v: 1, - relay, - installStatus: installResult - ? { v: 1, reqId: request.installReqId, state: 'committed', result: installResult } - : { v: 1, reqId: request.installReqId, state: 'not-found' } - }, - _meta: { runtimeId: 'runtime-1' } - } - }) -} - describe('mobile endpoint supervisor', () => { beforeEach(() => { vi.useFakeTimers() @@ -716,6 +561,7 @@ describe('mobile endpoint supervisor', () => { .mockReturnValueOnce(new FakeRelaySession('disconnected', new RelayOuterError(4408))) const deps = dependencies({ openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')), resolveRelay: vi.fn(() => resolvePending) }) const supervisor = new MobileEndpointSupervisor(logical, host, deps) @@ -744,12 +590,13 @@ describe('mobile endpoint supervisor', () => { .mockReturnValueOnce(new FakeRelaySession('disconnected', new RelayOuterError(4408))) const deps = dependencies({ openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')), resolveRelay: vi.fn(() => resolvePending) }) const supervisor = new MobileEndpointSupervisor(logical, host, deps) await supervisor.start() - await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(60_000) await vi.waitFor(() => expect(deps.resolveRelay).toHaveBeenCalledOnce()) supervisor.setForeground(false) finishResolve?.(relay) @@ -785,11 +632,14 @@ describe('mobile endpoint supervisor', () => { .fn() .mockReturnValueOnce(new FakeRelaySession('connected', null, Date.now() + 31_000)) .mockImplementation(() => new FakeRelaySession('disconnected', new RelayOuterError(4404))) - const deps = dependencies({ openRelay }) + const deps = dependencies({ + openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')) + }) const supervisor = new MobileEndpointSupervisor(logical, host, deps) await supervisor.start() - await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(60_000) expect(openRelay).toHaveBeenCalledTimes(2) await vi.advanceTimersByTimeAsync(5000) @@ -797,6 +647,27 @@ describe('mobile endpoint supervisor', () => { supervisor.stop() }) + it('skips forced rotation for a session resumed without renewal', async () => { + // Why: renewed=false means a re-resume provably returns the same unchanged + // deadline; rotating anyway churned one session replacement per clamp floor. + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi.fn( + () => new FakeRelaySession('connected', null, Date.now() + 31_000, false) + ) + const deps = dependencies({ + openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')) + }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + expect(openRelay).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(5 * 60_000) + expect(openRelay).toHaveBeenCalledTimes(1) + supervisor.stop() + }) + it('keeps a fatal lease-replacement gate after the active relay later drops', async () => { const logical = new FakeLogicalClient('disconnected', 'lan') const openRelay = vi @@ -808,12 +679,13 @@ describe('mobile endpoint supervisor', () => { .mockImplementation(() => new FakeRelaySession('connected')) const deps = dependencies({ openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')), randomBytes: () => new Uint8Array([128, 0]) }) const supervisor = new MobileEndpointSupervisor(logical, host, deps) await supervisor.start() - await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(60_000) expect(openRelay).toHaveBeenCalledTimes(2) // The old relay can outlive its rejected lease replacement, then close separately. @@ -833,12 +705,13 @@ describe('mobile endpoint supervisor', () => { .mockImplementation(() => new FakeRelaySession('connected')) const deps = dependencies({ openRelay, + openDirect: vi.fn(() => new FakeSession('disconnected')), randomBytes: () => new Uint8Array([128, 0]) }) const supervisor = new MobileEndpointSupervisor(logical, host, deps) await supervisor.start() - await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(60_000) expect(openRelay).toHaveBeenCalledTimes(2) supervisor.setForeground(true) diff --git a/mobile/src/transport/mobile-endpoint-supervisor.ts b/mobile/src/transport/mobile-endpoint-supervisor.ts index c8b3cdbcfb1..be295fdcdda 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.ts @@ -1,5 +1,5 @@ -import { openAuthenticatedDirectEndpoint } from './mobile-direct-endpoint-probe' import type { MobileEndpointSupervisorDependencies } from './mobile-endpoint-supervisor-contract' +import { DirectReturnProbe } from './mobile-direct-return-probe' import { RelayReconnectController } from './mobile-relay-reconnect-controller' import { RelayLeaseRotationTimer } from './mobile-relay-lease-rotation-timer' import { MobileEndpointHysteresis } from './mobile-endpoint-hysteresis' @@ -9,6 +9,8 @@ import { persistRelayHost, toError } from './mobile-endpoint-supervisor-support' +import { selectDialableRelayCredentials } from './mobile-relay-credential-selection' +import { createRelayRecoveryLog, type RelayRecoveryLog } from './mobile-relay-recovery-log' import { applyResumeConfirmation, mobileRelayCredentialNeedsRotation, @@ -20,7 +22,6 @@ import type { HostProfile } from './types' export type { MobileEndpointSupervisorDependencies } from './mobile-endpoint-supervisor-contract' -const DIRECT_PROBE_INTERVAL_MS = 15_000 const DIRECT_OBSERVATION_MS = 30_000 const MINIMUM_DWELL_MS = 60_000 const FAILURE_COOLDOWN_MS = 60_000 @@ -32,11 +33,12 @@ export class MobileEndpointSupervisor { private operationInFlight = false private credentialRotationInFlight = false private relayRotationPending = false - private probeTimer: ReturnType | null = null private unsubscribeState: (() => void) | null = null private readonly hysteresis: MobileEndpointHysteresis private readonly relayReconnect: RelayReconnectController private readonly leaseRotation: RelayLeaseRotationTimer + private readonly logRelay: RelayRecoveryLog + private readonly directProbe: DirectReturnProbe constructor( private readonly logical: StableLogicalRpcClient, @@ -49,24 +51,52 @@ export class MobileEndpointSupervisor { failureCooldownMs: FAILURE_COOLDOWN_MS, minimumDwellMs: MINIMUM_DWELL_MS }) + this.logRelay = createRelayRecoveryLog(dependencies.now, dependencies.onLog) this.relayReconnect = new RelayReconnectController(dependencies, this.recoverRelay.bind(this)) this.leaseRotation = new RelayLeaseRotationTimer(dependencies, () => { this.relayRotationPending = true void this.recoverRelay(true) }) + this.directProbe = new DirectReturnProbe(dependencies, { + hysteresis: this.hysteresis, + host: () => this.host, + canSchedule: () => + !this.stopped && this.foreground && this.logical.getActivePath() === 'relay', + canAttempt: () => !this.stopped && this.foreground && !this.operationInFlight, + beginOperation: () => { + this.operationInFlight = true + }, + migrate: (client, path) => this.logical.migrateTo(client, path), + onDirectMigrated: async () => { + this.leaseRotation.clear() + this.relayRotationPending = false + await this.rotateCredentialIfNeeded(this.relayReconnect.resetForDirectConnection()) + }, + afterProbe: () => { + this.operationInFlight = false + if (this.relayRotationPending || this.logical.getState() !== 'connected') { + void this.recoverRelay(this.relayRotationPending) + } + } + }) } async start(): Promise { this.bundle = await this.dependencies.readBundle(this.host.id).catch(() => null) - if (this.stopped || !this.bundle || !this.host.relay) { + if (this.stopped || !this.host.relay) { return } + if (!this.bundle) { + // Why: a Keychain race at open must not kill relay recovery for the whole + // process lifetime; each recovery attempt re-reads the durable bundle. + this.logRelay('credential bundle unavailable at start; recovery will re-read') + } this.unsubscribeState = this.logical.onStateChange((state) => { if (state === 'connected') { if (this.logical.getActivePath() !== 'relay') { void this.rotateCredentialIfNeeded(this.relayReconnect.resetForDirectConnection()) } - this.scheduleDirectProbe() + this.directProbe.schedule() } else { // Why: the direct client enters reconnecting after its first failed // dial and may never publish disconnected while its retry loop lives. @@ -78,7 +108,7 @@ export class MobileEndpointSupervisor { // are still loading, before the supervisor subscribes to state changes. await this.recoverRelay() } else { - this.scheduleDirectProbe() + this.directProbe.schedule() } } @@ -87,11 +117,11 @@ export class MobileEndpointSupervisor { this.foreground = foreground if (foreground) { this.relayReconnect.handleForeground(this.logical, wasForeground) - this.scheduleDirectProbe(0) + this.directProbe.schedule(0) } else { // Why: background phones must not hold billed relay data splices. this.relayReconnect.suspendActiveRelay(this.logical) - this.clearDirectProbeTimer() + this.directProbe.clear() this.relayReconnect.clear() this.leaseRotation.clear() } @@ -101,7 +131,7 @@ export class MobileEndpointSupervisor { this.stopped = true this.unsubscribeState?.() this.unsubscribeState = null - this.clearDirectProbeTimer() + this.directProbe.clear() this.relayReconnect.clear() this.leaseRotation.clear() } @@ -112,7 +142,6 @@ export class MobileEndpointSupervisor { this.stopped || !this.foreground || this.operationInFlight || - !this.bundle || !this.host.relay || (!forceReplacement && !this.relayReconnect.needsRecovery(this.logical.getState())) ) { @@ -121,23 +150,42 @@ export class MobileEndpointSupervisor { // Why: revival and lease timers can overlap resume failures; one shared cooldown // prevents PEER_DROPPED/LIMIT_EXCEEDED reconnect churn. if (this.relayReconnect.shouldDefer()) { + this.logRelay('recovery deferred by cooldown or gate') return } this.operationInFlight = true let lastError: Error | null = null let retryAfterOperation = false try { - const credentials = this.relayReconnect.eligibleCredentials( - this.bundle.current, - this.bundle.grace - ) - for (const credential of credentials) { + const selection = await selectDialableRelayCredentials({ + bundle: this.bundle, + controller: this.relayReconnect, + readBundle: () => this.dependencies.readBundle(this.host.id), + onAdoptedFresherBundle: () => this.logRelay('adopted fresher durable credential bundle') + }) + this.bundle = selection.bundle + if (selection.credentials.length === 0) { + // Why: "expired" vs "missing" separates a sleep-past-expiry phone + // (needs re-pair or LAN) from a Keychain failure in field reports. + this.logRelay( + selection.bundle + ? 'relay credential expired or rejected; slow reprobe armed' + : 'no relay credential bundle; slow reprobe armed' + ) + this.relayReconnect.armCredentialReprobe() + return + } + for (const credential of selection.credentials) { const result = await this.tryRelayCredential(credential) if (result.ok) { retryAfterOperation = this.logical.getState() !== 'connected' return } lastError = result.error + this.logRelay( + 'relay dial failed', + `${result.error.name}: ${String(result.error.message).slice(0, 80)}` + ) if (this.relayReconnect.shouldTryGraceAfterRelayFailure(result.error)) { // Why: a rejected version stays invalid; retry only the grace credential. this.relayReconnect.recordRejectedCredential(credential.version) @@ -145,12 +193,10 @@ export class MobileEndpointSupervisor { break } } - if (credentials.length > 0) { - // Why: cleanup may happen while a relay dial is awaiting the network; - // record its outcome without recreating a foreground retry timer. - const scheduleRetry = !forceReplacement && this.foreground && !this.stopped - this.relayReconnect.registerFailure(lastError, scheduleRetry) - } + // Why: cleanup may happen while a relay dial is awaiting the network; + // record its outcome without recreating a foreground retry timer. + const scheduleRetry = !forceReplacement && this.foreground && !this.stopped + this.relayReconnect.registerFailure(lastError, scheduleRetry) } finally { this.operationInFlight = false if (forceReplacement && this.relayRotationPending && !this.stopped && this.foreground) { @@ -207,6 +253,7 @@ export class MobileEndpointSupervisor { } this.relayRotationPending = false this.hysteresis.recordMigration(this.dependencies.now()) + this.logRelay('runtime channel migrated to relay') const confirmation = session.getResumeConfirmation() if (confirmation) { this.bundle = applyResumeConfirmation(this.bundle, credential.version, confirmation) @@ -215,71 +262,24 @@ export class MobileEndpointSupervisor { await this.dependencies.writeBundle(this.bundle).catch(() => {}) } // Why: async persistence can finish after stop/background; never recreate a stale timer. + // Why: rotate against the resume credential's expiry, never the hello's + // leaseExpiresAt — that field is the cell's ~10s attach-reservation + // deadline, and using it forced a session replacement every second. + // Why: renewed=false means a re-resume provably returns the same + // unchanged deadline — rotating then just churns one replacement per + // clamp floor until a fresh credential arrives over direct or disk. this.leaseRotation.scheduleFromLease( - this.stopped || !this.foreground ? null : session.getLeaseExpiresAt() + this.stopped || !this.foreground || confirmation?.renewed === false + ? null + : (confirmation?.resumeExpiresAt ?? session.getResumeExpiresAt()) ) - this.scheduleDirectProbe() + this.directProbe.schedule() return { ok: true } } catch (error) { return { ok: false, error: session.getFailure() ?? toError(error) } } } - private scheduleDirectProbe(delayMs = DIRECT_PROBE_INTERVAL_MS): void { - if ( - this.stopped || - !this.foreground || - this.logical.getActivePath() !== 'relay' || - this.probeTimer - ) { - return - } - this.probeTimer = this.dependencies.setTimer(() => { - this.probeTimer = null - void this.probeDirect() - }, delayMs) - } - - private async probeDirect(): Promise { - if ( - this.stopped || - !this.foreground || - this.operationInFlight || - !this.hysteresis.canProbe(this.dependencies.now()) - ) { - this.scheduleDirectProbe() - return - } - this.operationInFlight = true - let successful: Awaited> = null - try { - const openDirect = this.dependencies.openDirect - successful = await openAuthenticatedDirectEndpoint(this.host, openDirect, 12_000) - if (!successful) { - this.hysteresis.recordDirectFailure(this.dependencies.now()) - return - } - if (!this.hysteresis.recordDirectSuccess(this.dependencies.now())) { - successful.client.close() - return - } - await this.logical.migrateTo(successful.client, successful.path) - successful = null - this.hysteresis.recordMigration(this.dependencies.now()) - this.leaseRotation.clear() - this.relayRotationPending = false - await this.rotateCredentialIfNeeded(this.relayReconnect.resetForDirectConnection()) - } finally { - successful?.client.close() - this.operationInFlight = false - // Why: a relay drop or backoff timer can arrive while the direct probe owns the mutex. - if (this.relayRotationPending || this.logical.getState() !== 'connected') { - void this.recoverRelay(this.relayRotationPending) - } - this.scheduleDirectProbe() - } - } - private async rotateCredentialIfNeeded(force = false): Promise { if ( this.stopped || @@ -321,11 +321,4 @@ export class MobileEndpointSupervisor { } } } - - private clearDirectProbeTimer(): void { - if (this.probeTimer) { - this.dependencies.clearTimer(this.probeTimer) - this.probeTimer = null - } - } } diff --git a/mobile/src/transport/mobile-relay-credential-selection.ts b/mobile/src/transport/mobile-relay-credential-selection.ts new file mode 100644 index 00000000000..dcaca2080dd --- /dev/null +++ b/mobile/src/transport/mobile-relay-credential-selection.ts @@ -0,0 +1,42 @@ +import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' +import type { RelayReconnectController } from './mobile-relay-reconnect-controller' + +// Why: pairing recovery, re-pairing, or a raced rotation can land a fresh +// durable bundle after the supervisor snapshotted its copy; a gated retry must +// see it instead of dialing (or refusing to dial) on stale state forever. +// +// Adoption is decided by OUTCOME, not by version: renewals extend expiresAt +// without bumping current.version, and a re-pair restarts the version counter, +// so version comparison cannot tell fresh from stale. The durable bundle is +// adopted exactly when it yields a dialable (unexpired, non-rejected) +// credential while the in-memory one does not — which also means a revoked +// version can never be resurrected from a stale disk copy. +export async function selectDialableRelayCredentials(args: { + bundle: MobileRelayCredentialBundle | null + controller: RelayReconnectController + readBundle: () => Promise + onAdoptedFresherBundle: () => void +}): Promise<{ + bundle: MobileRelayCredentialBundle | null + credentials: MobileRelayCredentialBundle['current'][] +}> { + const memory = args.bundle + const memoryCredentials = memory + ? args.controller.eligibleCredentials(memory.current, memory.grace) + : [] + if (memoryCredentials.length > 0) { + // Why: in-memory can be newer than disk (a resume confirmation whose + // durable write failed); never let a stale disk copy shadow it. + return { bundle: memory, credentials: memoryCredentials } + } + const disk = await args.readBundle().catch(() => null) + if (disk) { + const diskCredentials = args.controller.eligibleCredentials(disk.current, disk.grace) + if (diskCredentials.length > 0) { + args.controller.acceptFreshCredential(disk.current.version) + args.onAdoptedFresherBundle() + return { bundle: disk, credentials: diskCredentials } + } + } + return { bundle: memory ?? disk, credentials: [] } +} diff --git a/mobile/src/transport/mobile-relay-lease-rotation-timer.ts b/mobile/src/transport/mobile-relay-lease-rotation-timer.ts index bf2a3dd4d1c..19aedfe8be1 100644 --- a/mobile/src/transport/mobile-relay-lease-rotation-timer.ts +++ b/mobile/src/transport/mobile-relay-lease-rotation-timer.ts @@ -2,6 +2,13 @@ // little before the deadline (and retry shortly if a forced rotation didn't land) // so the session never lapses. Owns the single lease/rotation timer slot. const LEASE_ROTATION_MARGIN_MS = 30_000 +// Why: both ends must be clamped. The floor bounds any bad deadline to one +// forced rotation per minute instead of a sub-second loop; the ceiling keeps +// the delay far below setTimeout's 32-bit limit (a 30-day resume TTL minus the +// margin overflows int32 and fires at 1ms), at the cost of a harmless +// re-resume every few hours on long-lived sessions. +const LEASE_ROTATION_MIN_DELAY_MS = 60_000 +const LEASE_ROTATION_MAX_DELAY_MS = 6 * 60 * 60 * 1000 export type RelayLeaseRotationDependencies = { now: () => number @@ -23,9 +30,12 @@ export class RelayLeaseRotationTimer { if (!leaseExpiresAt) { return } - const delay = Math.max( - 1000, - leaseExpiresAt - this.dependencies.now() - LEASE_ROTATION_MARGIN_MS + const delay = Math.min( + LEASE_ROTATION_MAX_DELAY_MS, + Math.max( + LEASE_ROTATION_MIN_DELAY_MS, + leaseExpiresAt - this.dependencies.now() - LEASE_ROTATION_MARGIN_MS + ) ) this.arm(delay) } diff --git a/mobile/src/transport/mobile-relay-reconnect-controller.test.ts b/mobile/src/transport/mobile-relay-reconnect-controller.test.ts index d630f0db68b..4f50878c6d5 100644 --- a/mobile/src/transport/mobile-relay-reconnect-controller.test.ts +++ b/mobile/src/transport/mobile-relay-reconnect-controller.test.ts @@ -6,7 +6,9 @@ import { RelayReconnectController } from './mobile-relay-reconnect-controller' import type { StableLogicalRpcClient } from './stable-logical-rpc-client' vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) -vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) +vi.mock('expo-crypto', () => ({ + getRandomBytes: (length: number) => new Uint8Array(length) +})) describe('relay reconnect controller', () => { beforeEach(() => { @@ -47,16 +49,146 @@ describe('relay reconnect controller', () => { expect(onRetry).not.toHaveBeenCalled() }) - it('waits for an external signal after rejected E2EE authentication', () => { + it('reprobes slowly after rejected E2EE authentication instead of parking forever', () => { + // Why: on a relay-only phone a permanent gate is a permanent outage — the + // desktop can commit pairing credentials moments after the first rejection. const onRetry = vi.fn() const reconnect = createController(onRetry) reconnect.registerFailure(new MobileE2EEAuthenticationError()) expect(reconnect.shouldDefer()).toBe(true) - expect(vi.getTimerCount()).toBe(0) - vi.advanceTimersByTime(60_000) expect(onRetry).not.toHaveBeenCalled() + vi.advanceTimersByTime(59_000) + expect(onRetry).not.toHaveBeenCalled() + vi.advanceTimersByTime(1_000) + expect(onRetry).toHaveBeenCalledTimes(1) + // The reprobe tick passes the gate exactly once, then defers again. + expect(reconnect.shouldDefer()).toBe(false) + expect(reconnect.shouldDefer()).toBe(true) + }) + + it('keeps the fresh-credential gate reprobing after each failed gated attempt', () => { + const onRetry = vi.fn() + const reconnect = createController(onRetry) + + reconnect.registerFailure(new RelayOuterError(4401)) + expect(reconnect.shouldDefer()).toBe(true) + + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(1) + expect(reconnect.shouldDefer()).toBe(false) + // The gated attempt fails again with only rejected credentials on hand. + reconnect.registerFailure(new RelayOuterError(4401)) + + // The gated cadence escalates: the second reprobe waits twice as long. + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(2) + }) + + it('resets the gated cadence when the app returns to the foreground', () => { + // Why: reopening the app is the strongest "conditions changed" signal a + // phone produces — it must not wait out an escalated 15-minute tick even + // when it cannot lift the credential gate itself. + const onRetry = vi.fn() + const reconnect = createController(onRetry) + const logical = { getState: () => 'disconnected' } as never + + reconnect.registerFailure(new RelayOuterError(4401)) + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(1) + // A failed gated attempt escalates the next tick beyond the base cadence. + reconnect.registerFailure(new RelayOuterError(4401)) + + reconnect.clear() + reconnect.handleForeground(logical, false) + expect(onRetry).toHaveBeenCalledTimes(2) + + expect(reconnect.shouldDefer()).toBe(true) + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(3) + }) + + it('mints the gate pass when arming a no-bundle reprobe under a held gate', () => { + // Why: an external-signal gate never records rejected versions, so the + // no-dialable-bundle path must still mint the tick's pass token — a plain + // cooldown tick bounces off shouldDefer and doubles the effective cadence. + const onRetry = vi.fn() + const reconnect = createController(onRetry) + + reconnect.registerFailure(new MobileE2EEAuthenticationError()) + expect(reconnect.shouldDefer()).toBe(true) + vi.advanceTimersByTime(60_000) + expect(onRetry).toHaveBeenCalledTimes(1) + expect(reconnect.shouldDefer()).toBe(false) + // The gated attempt finds no dialable credential at all and re-arms. + reconnect.armCredentialReprobe() + + vi.advanceTimersByTime(120_000) + expect(onRetry).toHaveBeenCalledTimes(2) + expect(reconnect.shouldDefer()).toBe(false) + }) + + it('does not arm a gate reprobe timer when the supervisor declined retries', () => { + // Why: scheduleRetry=false means background or stopped — a tick firing + // there wakes nothing useful, and the next foreground resume re-arms. + const onRetry = vi.fn() + const reconnect = createController(onRetry) + const logical = { getState: () => 'disconnected' } as never + + reconnect.registerFailure(new MobileE2EEAuthenticationError(), false) + expect(vi.getTimerCount()).toBe(0) + reconnect.registerFailure(new RelayOuterError(4401), false) + expect(vi.getTimerCount()).toBe(0) + reconnect.registerFailure(new RelayOuterError(4429), false) + expect(vi.getTimerCount()).toBe(0) + vi.runAllTimers() + expect(onRetry).not.toHaveBeenCalled() + + // Resume restores the gated cadence instead of stalling forever. + reconnect.handleForeground(logical, false) + expect(reconnect.shouldDefer()).toBe(true) + expect(vi.getTimerCount()).toBe(1) + }) + + it('does not let an orphaned reprobe timer swallow the next fast backoff', () => { + const onRetry = vi.fn() + const reconnect = createController(onRetry) + const logical = { getState: () => 'disconnected' } as never + + reconnect.registerFailure(new MobileE2EEAuthenticationError()) + // A foreground revival nudge clears the external-signal gate and its timer. + reconnect.handleForeground(logical, true) + expect(onRetry).toHaveBeenCalledTimes(1) + + // A plain transport failure must schedule its own fast retry, not wait + // out a leftover 60s reprobe timer. + reconnect.registerFailure(new RelayOuterError(4429)) + vi.advanceTimersByTime(600) + expect(onRetry).toHaveBeenCalledTimes(2) + }) + + it('lifts the fresh-credential gate when a durable bundle carries a new version', () => { + const onRetry = vi.fn() + const reconnect = createController(onRetry) + + reconnect.recordRejectedCredential(2) + reconnect.armCredentialReprobe() + expect(reconnect.shouldDefer()).toBe(true) + + reconnect.acceptFreshCredential(2) + expect(reconnect.shouldDefer()).toBe(true) + + reconnect.acceptFreshCredential(3) + expect(reconnect.shouldDefer()).toBe(false) + expect( + reconnect.eligibleCredentials( + { token: 'fresh', version: 3, expiresAt: Number.MAX_SAFE_INTEGER }, + null + ) + ).toHaveLength(1) }) it('upgrades host-revival gating to fresh credentials without later downgrading it', () => { diff --git a/mobile/src/transport/mobile-relay-reconnect-controller.ts b/mobile/src/transport/mobile-relay-reconnect-controller.ts index 6f586c17499..9ec5c1398bc 100644 --- a/mobile/src/transport/mobile-relay-reconnect-controller.ts +++ b/mobile/src/transport/mobile-relay-reconnect-controller.ts @@ -6,18 +6,10 @@ import { import type { MobileRelayRpcSession } from './mobile-relay-rpc-session' import { MobileE2EEAuthenticationError } from './mobile-e2ee-v2-physical-channel' import { RelayOuterError } from './mobile-relay-e2ee-link' +import { RELAY_STABLE_CONNECTION_MS, RelayRetryDelays } from './mobile-relay-retry-delays' import type { StableLogicalRpcClient } from './stable-logical-rpc-client' import type { ConnectionState } from './types' -// Why: relay resume closes and silent cellular NAT rebinds otherwise cause -// immediate re-dials that ping-pong the phone between connected and disconnected. -const RELAY_BACKOFF_MIN_MS = 250 -const RELAY_BACKOFF_BASE_MS = 500 -const RELAY_BACKOFF_CEILING_MS = 30_000 -const RELAY_STABLE_CONNECTION_MS = RELAY_BACKOFF_CEILING_MS -const RELAY_HOST_OFFLINE_RETRY_MIN_MS = 5_000 -const RELAY_HOST_OFFLINE_RETRY_MAX_MS = 15_000 - export type RelayReconnectDependencies = { now: () => number randomBytes: (length: number) => Uint8Array @@ -34,21 +26,29 @@ export class RelayReconnectController { private timer: ReturnType | null = null private activeSession: MobileRelayRpcSession | null = null private recoveryGate: RecoveryGate | null = null + private gateReprobePending = false + private gateReprobeStreak = 0 private readonly rejectedCredentialVersions = new Set() + private readonly delays: RelayRetryDelays constructor( private readonly dependencies: RelayReconnectDependencies, private readonly onRetry: (forceReplacement?: boolean) => void - ) {} + ) { + this.delays = new RelayRetryDelays(dependencies.randomBytes) + } handleForeground(logical: StableLogicalRpcClient, wasForeground: boolean): void { if (!wasForeground) { - // Why: an app resume is a fresh signal, unlike repeated network-flap nudges. + // Why: an app resume is a fresh signal, unlike repeated network-flap + // nudges — it resets the gated cadence even when it cannot lift the + // credential gate, so reopening the app never waits out a 15min tick. + this.gateReprobeStreak = 0 if (this.recoveryGate !== 'fresh-credential') { this.reset() } } else if (this.recoveryGate === 'external-signal') { - this.recoveryGate = null + this.liftGate() } if ( wasForeground && @@ -87,8 +87,7 @@ export class RelayReconnectController { this.activeSession = session this.activeRelayConnectedAt = this.dependencies.now() this.nextAttemptAt = 0 - this.recoveryGate = null - this.clearTimer() + this.liftGate() } resetForDirectConnection(): boolean { @@ -97,10 +96,14 @@ export class RelayReconnectController { this.activeSession = null this.activeRelayConnectedAt = null if (needsCredentialRefresh) { - // Why: the rejected credential stays unusable until its replacement is durable. + // Why: the rejected credential stays unusable until its replacement is + // durable. No reprobe timer here — direct is live, rotation over it + // clears the gate, and any later state failure re-arms via shouldDefer. this.consecutiveFailures = 0 this.nextAttemptAt = 0 this.recoveryGate = 'fresh-credential' + this.gateReprobePending = false + this.gateReprobeStreak = 0 this.clearTimer() } else { this.reset() @@ -128,10 +131,43 @@ export class RelayReconnectController { if (eligible.length === 0 && this.rejectedCredentialVersions.size > 0) { this.recoveryGate = 'fresh-credential' this.clearTimer() + this.scheduleGateReprobe() } return eligible } + // For callers that found no dialable credential at all: keep a slow retry + // alive so a later durable write can recover. + armCredentialReprobe(): void { + if (this.rejectedCredentialVersions.size > 0) { + this.recoveryGate = 'fresh-credential' + this.clearTimer() + this.scheduleGateReprobe() + return + } + if (this.recoveryGate) { + // Why: under a held gate the tick must mint its pass token — a plain + // cooldown tick bounces off shouldDefer and doubles the effective cadence. + this.clearTimer() + this.scheduleGateReprobe() + return + } + // Why: a merely missing or expired bundle must not enter the credential + // gate — that gate forces a rotation on the next direct connect. A plain + // cooldown retries the read on the same escalating cadence. + const delay = this.delays.gateReprobeDelayMs(this.gateReprobeStreak) + this.nextAttemptAt = this.dependencies.now() + delay + this.clearTimer() + this.scheduleReprobeTick(delay, false) + } + + // A durable bundle whose current version is not rejected reopens the gate. + acceptFreshCredential(version: number): void { + if (this.recoveryGate === 'fresh-credential' && !this.rejectedCredentialVersions.has(version)) { + this.liftGate() + } + } + recordRejectedCredential(version: number): void { this.rejectedCredentialVersions.add(version) } @@ -154,6 +190,12 @@ export class RelayReconnectController { // re-dial. Arms the self-scheduled retry so recovery still happens on its own. shouldDefer(): boolean { if (this.recoveryGate) { + if (this.gateReprobePending) { + // Why: the slow reprobe tick gets exactly one attempt through the gate. + this.gateReprobePending = false + return false + } + this.scheduleGateReprobe() return true } if (this.dependencies.now() < this.nextAttemptAt) { @@ -173,8 +215,12 @@ export class RelayReconnectController { this.recoveryGate === 'fresh-credential' || (this.recoveryGate === 'external-signal' && recovery?.kind !== 'disable-relay-credential') ) { - // Why: only the gate's external signal can make a known-fatal recovery retryable. + // Why: a failed reprobe stays gated, but the slow cadence must keep going + // — unless the supervisor is backgrounded/stopped; resume re-arms it. this.clearTimer() + if (scheduleRetry) { + this.scheduleGateReprobe() + } return } const now = this.dependencies.now() @@ -189,18 +235,29 @@ export class RelayReconnectController { this.activeRelayConnectedAt = null this.consecutiveFailures += 1 const delay = - recovery?.kind === 'retry-after-host-offline' ? this.hostOfflineDelayMs() : this.delayMs() + recovery?.kind === 'retry-after-host-offline' + ? this.delays.hostOfflineDelayMs() + : this.delays.transportDelayMs(this.consecutiveFailures) this.nextAttemptAt = now + delay if (error instanceof MobileE2EEAuthenticationError) { - // Why: pairing state cannot change on a timer; polling only wakes the radio. + // Why: an E2EE rejection is usually pairing revocation, but it also fires + // transiently right after pairing while the desktop commits credentials — + // reprobe slowly instead of waiting forever for a UI nudge. this.recoveryGate = 'external-signal' this.clearTimer() + if (scheduleRetry) { + this.scheduleGateReprobe() + } return } if (recovery?.kind === 'disable-relay-credential') { - // Why: a rejected outer credential cannot recover until direct connectivity refreshes it. + // Why: never redial a rejected credential fast, but keep a slow reprobe + // alive — the caller re-reads durable state before each gated attempt. this.recoveryGate = 'fresh-credential' this.clearTimer() + if (scheduleRetry) { + this.scheduleGateReprobe() + } return } if (recovery?.kind === 'retry-after-host-offline') { @@ -235,12 +292,12 @@ export class RelayReconnectController { this.consecutiveFailures = 0 this.activeRelayConnectedAt = null this.nextAttemptAt = 0 - this.recoveryGate = null - this.clearTimer() + this.liftGate() } clear(): void { this.clearTimer() + this.gateReprobePending = false this.activeSession = null this.activeRelayConnectedAt = null } @@ -263,20 +320,34 @@ export class RelayReconnectController { }, delay) } - private delayMs(): number { - const exponent = Math.max(0, this.consecutiveFailures - 1) - const cap = Math.min(RELAY_BACKOFF_CEILING_MS, RELAY_BACKOFF_BASE_MS * 2 ** exponent) - // Full jitter (uniform in [0, cap)), floored so retries never busy-loop. - return Math.max(RELAY_BACKOFF_MIN_MS, Math.floor(cap * this.jitterFraction())) + private scheduleGateReprobe(): void { + this.scheduleReprobeTick(this.delays.gateReprobeDelayMs(this.gateReprobeStreak), true) } - private hostOfflineDelayMs(): number { - const range = RELAY_HOST_OFFLINE_RETRY_MAX_MS - RELAY_HOST_OFFLINE_RETRY_MIN_MS - return RELAY_HOST_OFFLINE_RETRY_MIN_MS + Math.floor(range * this.jitterFraction()) + private scheduleReprobeTick(delay: number, mintToken: boolean): void { + if (this.timer) { + return + } + this.timer = this.dependencies.setTimer(() => { + this.timer = null + // Why: the streak advances once per fired tick — arm attempts within one + // cycle recompute the same delay instead of triple-escalating it. + this.gateReprobeStreak = Math.min(this.gateReprobeStreak + 1, 8) + // Why: the tick token is only minted while its gate still holds; a later + // gate must not spend a stale token and bypass its own cooldown. + if (mintToken && this.recoveryGate) { + this.gateReprobePending = true + } + this.onRetry() + }, delay) } - private jitterFraction(): number { - const [high, low] = this.dependencies.randomBytes(2) - return (((high ?? 0) << 8) | (low ?? 0)) / 0x1_00_00 + // Why: clearing a gate must also drop its timer, pending tick, and cadence — + // an orphaned reprobe timer would otherwise swallow the next fast backoff. + private liftGate(): void { + this.recoveryGate = null + this.gateReprobePending = false + this.gateReprobeStreak = 0 + this.clearTimer() } } diff --git a/mobile/src/transport/mobile-relay-recovery-log.ts b/mobile/src/transport/mobile-relay-recovery-log.ts new file mode 100644 index 00000000000..9b373cd112a --- /dev/null +++ b/mobile/src/transport/mobile-relay-recovery-log.ts @@ -0,0 +1,22 @@ +import type { ConnectionLogSink } from './types' + +export type RelayRecoveryLog = (message: string, detail?: string) => void + +// Why: relay recovery failed silently in production for weeks; every decision +// must reach logcat and the in-app connection log. +export function createRelayRecoveryLog( + now: () => number, + onLog?: ConnectionLogSink +): RelayRecoveryLog { + let sequence = 0 + return (message, detail) => { + console.log(`[relay] ${message}`, detail ?? '') + onLog?.({ + id: `relay-${++sequence}`, + ts: now(), + level: 'info', + message: `Relay: ${message}`, + ...(detail ? { detail } : {}) + }) + } +} diff --git a/mobile/src/transport/mobile-relay-retry-delays.ts b/mobile/src/transport/mobile-relay-retry-delays.ts new file mode 100644 index 00000000000..6ff145acdb4 --- /dev/null +++ b/mobile/src/transport/mobile-relay-retry-delays.ts @@ -0,0 +1,45 @@ +// Why: relay resume closes and silent cellular NAT rebinds otherwise cause +// immediate re-dials that ping-pong the phone between connected and disconnected. +const RELAY_BACKOFF_MIN_MS = 250 +const RELAY_BACKOFF_BASE_MS = 500 +const RELAY_BACKOFF_CEILING_MS = 30_000 +export const RELAY_STABLE_CONNECTION_MS = RELAY_BACKOFF_CEILING_MS +const RELAY_HOST_OFFLINE_RETRY_MIN_MS = 5_000 +const RELAY_HOST_OFFLINE_RETRY_MAX_MS = 15_000 +// Why: gates must slow recovery down, never end it — a relay-only phone has no +// direct path to refresh credentials, so a timerless gate is a permanent outage. +// The cadence escalates and jitters so a permanently revoked device is not a +// forever one-minute beacon and a fleet-wide gating event cannot phase-align. +const RELAY_GATE_REPROBE_BASE_MS = 60_000 +const RELAY_GATE_REPROBE_CEILING_MS = 15 * 60_000 + +// Every relay retry delay in one place: transport backoff, known-offline +// polling, and the escalating gated reprobe cadence, all jittered. +export class RelayRetryDelays { + constructor(private readonly randomBytes: (length: number) => Uint8Array) {} + + transportDelayMs(consecutiveFailures: number): number { + const exponent = Math.max(0, consecutiveFailures - 1) + const cap = Math.min(RELAY_BACKOFF_CEILING_MS, RELAY_BACKOFF_BASE_MS * 2 ** exponent) + // Full jitter (uniform in [0, cap)), floored so retries never busy-loop. + return Math.max(RELAY_BACKOFF_MIN_MS, Math.floor(cap * this.jitterFraction())) + } + + hostOfflineDelayMs(): number { + const range = RELAY_HOST_OFFLINE_RETRY_MAX_MS - RELAY_HOST_OFFLINE_RETRY_MIN_MS + return RELAY_HOST_OFFLINE_RETRY_MIN_MS + Math.floor(range * this.jitterFraction()) + } + + gateReprobeDelayMs(streak: number): number { + const base = Math.min( + RELAY_GATE_REPROBE_CEILING_MS, + RELAY_GATE_REPROBE_BASE_MS * 2 ** Math.min(streak, 8) + ) + return Math.floor(base * (0.75 + 0.5 * this.jitterFraction())) + } + + private jitterFraction(): number { + const [high, low] = this.randomBytes(2) + return (((high ?? 0) << 8) | (low ?? 0)) / 0x1_00_00 + } +} diff --git a/mobile/src/transport/mobile-relay-rpc-session.test.ts b/mobile/src/transport/mobile-relay-rpc-session.test.ts index 54ae8387411..f5fa49a785e 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.test.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.test.ts @@ -119,7 +119,7 @@ describe('mobile relay RPC session', () => { }) expect(confirmationRequest.params).not.toHaveProperty('relayDeviceId') expect(confirmationRequest.params).not.toHaveProperty('acceptedCredentialVersion') - expect(session.getLeaseExpiresAt()).toEqual(expect.any(Number)) + expect(session.getAttachDeadlineAt()).toEqual(expect.any(Number)) }) it('rejects a mismatched outer credential version and closes the physical link', () => { diff --git a/mobile/src/transport/mobile-relay-rpc-session.ts b/mobile/src/transport/mobile-relay-rpc-session.ts index a614e833387..ac065012203 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.ts @@ -19,7 +19,10 @@ type PendingRequest = { } export type MobileRelayRpcSession = RpcClient & { - getLeaseExpiresAt(): number | null + // The cell's attach-reservation deadline (~10s). Diagnostics only — never + // schedule anything from it; rotation keys off getResumeExpiresAt(). + getAttachDeadlineAt(): number | null + getResumeExpiresAt(): number | null getResumeConfirmation(): DeviceResumeConfirmed | null getFailure(): Error | null } @@ -40,7 +43,8 @@ export function connectMobileRelayRpcSession(args: { let state: ConnectionState = 'connecting' let requestCounter = 0 let lastConnectedAt: number | null = null - let leaseExpiresAt: number | null = null + let attachDeadlineAt: number | null = null + let resumeExpiresAt: number | null = null let resumeConfirmation: DeviceResumeConfirmed | null = null let failure: Error | null = null let closed = false @@ -65,7 +69,8 @@ export function connectMobileRelayRpcSession(args: { fail(new Error('relay resume credential version mismatch')) return } - leaseExpiresAt = hello.leaseExpiresAt + attachDeadlineAt = hello.leaseExpiresAt + resumeExpiresAt = hello.resumeExpiresAt publishState('handshaking') }, onAuthenticated: () => void confirmResume(), @@ -109,7 +114,8 @@ export function connectMobileRelayRpcSession(args: { streams.clear() publishState('disconnected') }, - getLeaseExpiresAt: () => leaseExpiresAt, + getAttachDeadlineAt: () => attachDeadlineAt, + getResumeExpiresAt: () => resumeExpiresAt, getResumeConfirmation: () => resumeConfirmation, getFailure: () => failure } @@ -131,6 +137,7 @@ export function connectMobileRelayRpcSession(args: { throw new Error('relay resume confirmation missing') } resumeConfirmation = result.resumeConfirmation + resumeExpiresAt = result.resumeConfirmation.resumeExpiresAt lastConnectedAt = Date.now() publishState('connected') } catch (error) { diff --git a/mobile/src/transport/mobile-relay-runtime-failover.test.ts b/mobile/src/transport/mobile-relay-runtime-failover.test.ts new file mode 100644 index 00000000000..dcb8ba194e2 --- /dev/null +++ b/mobile/src/transport/mobile-relay-runtime-failover.test.ts @@ -0,0 +1,454 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { connect, type RpcClient } from './rpc-client' +import { + createStableLogicalRpcClient, + type MobileConnectionPath, + type StableLogicalRpcClient +} from './stable-logical-rpc-client' +import { MobileE2EEAuthenticationError } from './mobile-e2ee-v2-physical-channel' +import { RelayOuterError } from './mobile-relay-e2ee-link' +import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' +import type { MobileRelayRpcSession } from './mobile-relay-rpc-session' +import { + MobileEndpointSupervisor, + type MobileEndpointSupervisorDependencies +} from './mobile-endpoint-supervisor' +import type { ConnectionState, HostProfile, RpcResponse } from './types' + +// Regression suite for the 2026-08 field failure: a phone paired over the +// relay whose direct LAN endpoint is unreachable (Tailscale off) dialed the +// LAN endpoint forever and never recovered a relay runtime session. + +vi.mock('react-native', () => ({ Platform: { OS: 'android' } })) +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' +})) +vi.mock('expo-crypto', () => ({ + getRandomBytes: (length: number) => new Uint8Array(length) +})) + +vi.mock('./e2ee', () => ({ + generateKeyPair: () => ({ + publicKey: new Uint8Array(32), + secretKey: new Uint8Array(32) + }), + deriveSharedKey: () => new Uint8Array(32), + publicKeyFromBase64: () => new Uint8Array(32), + publicKeyToBase64: () => 'client-public-key', + encrypt: (plaintext: string) => plaintext, + decrypt: (raw: string) => raw, + decryptBytes: (bytes: Uint8Array) => bytes +})) + +class FakeSession implements RpcClient { + readonly sendRequest = vi.fn( + async (): Promise => ({ + id: 'rpc-1', + ok: true, + result: {}, + _meta: { runtimeId: 'runtime-1' } + }) + ) + readonly subscribe = vi.fn(() => () => {}) + readonly updateTerminalSubscriptionViewport = vi.fn() + readonly notifyForeground = vi.fn() + readonly close = vi.fn() + private readonly listeners = new Set<(state: ConnectionState) => void>() + + constructor(private state: ConnectionState) {} + + getState = () => this.state + getReconnectAttempt = () => 0 + getLastConnectedAt = () => null + onStateChange = (listener: (state: ConnectionState) => void) => { + this.listeners.add(listener) + return () => this.listeners.delete(listener) + } + + publishState(state: ConnectionState): void { + this.state = state + for (const listener of this.listeners) { + listener(state) + } + } +} + +class FakeRelaySession extends FakeSession implements MobileRelayRpcSession { + constructor( + state: ConnectionState, + private readonly failure: Error | null = null + ) { + super(state) + } + // Why: production-realistic constants — fictional fake values hid three + // live defects in this subsystem (latch, churn, int32 timer overflow). + getAttachDeadlineAt = () => Date.now() + 10_000 + getResumeExpiresAt = () => Date.now() + 30 * 24 * 3_600_000 + getResumeConfirmation = () => null + getFailure = () => this.failure +} + +class FakeLogicalClient extends FakeSession implements StableLogicalRpcClient { + private path: MobileConnectionPath + + constructor(state: ConnectionState, path: MobileConnectionPath) { + super(state) + this.path = path + } + + migrateTo = vi.fn(async (session: RpcClient, path: MobileConnectionPath) => { + if (session.getState() !== 'connected') { + session.close() + throw new Error(`replacement session ${session.getState()}`) + } + this.path = path + this.publishState('connected') + }) + suspendActiveSession = vi.fn(() => this.publishState('disconnected')) + getActivePath = () => this.path +} + +const relay = { + v: 1 as const, + directorUrl: 'https://relay.onorca.dev', + cellUrl: 'https://relay-c1.onorca.dev', + assignmentEpoch: 7, + relayHostId: 'AbCdEf0123_-xyZ9', + e2eeFraming: 2 as const +} + +const DIRECT_ENDPOINT = 'ws://100.88.90.25:6768' + +const host: HostProfile = { + id: 'host-1', + name: 'Blue Whale', + endpoint: DIRECT_ENDPOINT, + deviceToken: 'device-token', + publicKeyB64: 'A'.repeat(44), + lastConnected: 1, + endpoints: [ + { id: 'direct-primary', kind: 'lan', url: DIRECT_ENDPOINT }, + { + id: 'relay-primary', + kind: 'relay', + url: 'wss://relay-c1.onorca.dev/v1/connect/id' + } + ], + relayHostId: relay.relayHostId, + relay +} + +function bundleWith(version: number, expiresAt: number): MobileRelayCredentialBundle { + return { + v: 1, + hostId: host.id, + deviceToken: host.deviceToken, + current: { + token: `token-v${version}`.padEnd(43, 'A'), + hash: 'B'.repeat(43), + version, + expiresAt + } + } +} + +function dependencies( + overrides: Partial = {} +): MobileEndpointSupervisorDependencies { + return { + openDirect: vi.fn(() => new FakeSession('connected')), + openRelay: vi.fn(() => new FakeRelaySession('connected')), + resolveRelay: vi.fn(async ({ relay }) => relay), + readBundle: vi.fn(async () => bundleWith(2, Number.MAX_SAFE_INTEGER)), + writeBundle: vi.fn(async () => {}), + saveHost: vi.fn(async () => {}), + now: Date.now, + randomBytes: (length: number) => new Uint8Array(length), + setTimer: setTimeout, + clearTimer: clearTimeout, + ...overrides + } +} + +describe('relay runtime recovery without direct connectivity', () => { + beforeEach(() => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-08-02T12:00:00Z')) + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('recovers from a rejected outer credential once a fresher bundle is durable', async () => { + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi + .fn() + .mockReturnValueOnce(new FakeRelaySession('disconnected', new RelayOuterError(4401))) + .mockImplementation(() => new FakeRelaySession('connected')) + const readBundle = vi + .fn(async () => bundleWith(3, Number.MAX_SAFE_INTEGER)) + .mockResolvedValueOnce(bundleWith(2, Number.MAX_SAFE_INTEGER)) + const deps = dependencies({ openRelay, readBundle }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledOnce() + + // Pre-fix, the fresh-credential gate latched here with no timer and no exit. + await vi.advanceTimersByTimeAsync(60_000) + expect(openRelay).toHaveBeenCalledTimes(2) + expect(openRelay).toHaveBeenLastCalledWith( + relay, + expect.objectContaining({ version: 3 }), + expect.any(String) + ) + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('recovers when the credential bundle was unreadable at supervisor start', async () => { + const logical = new FakeLogicalClient('disconnected', 'lan') + const readBundle = vi + .fn(async () => bundleWith(2, Number.MAX_SAFE_INTEGER)) + .mockResolvedValueOnce(null) + const deps = dependencies({ readBundle }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + // Pre-fix, a null first read killed relay recovery for the process lifetime. + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + + expect(deps.openRelay).toHaveBeenCalled() + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('recovers from an expired-at-start bundle after a fresh credential lands', async () => { + const logical = new FakeLogicalClient('disconnected', 'lan') + const expired = bundleWith(2, Date.now() - 1) + const readBundle = vi.fn(async () => expired) + const deps = dependencies({ readBundle }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(deps.openRelay).not.toHaveBeenCalled() + + readBundle.mockImplementation(async () => bundleWith(3, Number.MAX_SAFE_INTEGER)) + // Pre-fix, an expired bundle produced a silent no-op with nothing scheduled. + await vi.advanceTimersByTimeAsync(60_000) + + expect(deps.openRelay).toHaveBeenCalledOnce() + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('retries after an E2EE authentication rejection without a UI nudge', async () => { + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi + .fn() + .mockReturnValueOnce( + new FakeRelaySession('disconnected', new MobileE2EEAuthenticationError()) + ) + .mockImplementation(() => new FakeRelaySession('connected')) + const deps = dependencies({ openRelay }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledOnce() + + // Pre-fix, this state waited indefinitely for a foreground/navigation event. + await vi.advanceTimersByTimeAsync(60_000) + expect(openRelay).toHaveBeenCalledTimes(2) + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('adopts a durable renewal that extends expiry without bumping the version', async () => { + // Why: resume confirmations and pairing recovery renew expiresAt while + // keeping current.version — version comparison cannot see this freshness. + const logical = new FakeLogicalClient('disconnected', 'lan') + const expired = bundleWith(2, Date.now() - 1) + const readBundle = vi + .fn(async () => bundleWith(2, Number.MAX_SAFE_INTEGER)) + .mockResolvedValueOnce(expired) + .mockResolvedValueOnce(expired) + const deps = dependencies({ readBundle }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(deps.openRelay).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(60_000) + expect(deps.openRelay).toHaveBeenCalledOnce() + expect(deps.openRelay).toHaveBeenLastCalledWith( + relay, + expect.objectContaining({ version: 2 }), + expect.any(String) + ) + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('adopts a re-paired credential whose version counter restarted', async () => { + // Why: re-pairing overwrites the same keychain slot with a NEW credential + // record whose counter restarts at 1 — lower than the rejected version. + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi + .fn() + .mockReturnValueOnce(new FakeRelaySession('disconnected', new RelayOuterError(4401))) + .mockImplementation(() => new FakeRelaySession('connected')) + const readBundle = vi + .fn(async () => bundleWith(1, Number.MAX_SAFE_INTEGER)) + .mockResolvedValueOnce(bundleWith(4, Number.MAX_SAFE_INTEGER)) + const deps = dependencies({ openRelay, readBundle }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledOnce() + + await vi.advanceTimersByTimeAsync(60_000) + expect(openRelay).toHaveBeenCalledTimes(2) + expect(openRelay).toHaveBeenLastCalledWith( + relay, + expect.objectContaining({ version: 1 }), + expect.any(String) + ) + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('does not churn relay sessions off the cell attach-reservation deadline', async () => { + // Why: the relay-hello's leaseExpiresAt is a ~10s attach deadline. Keying + // rotation off it replaced the session every second, killing any RPC + // slower than the cycle (the field symptom: "Worktree list unavailable"). + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi.fn(() => new FakeRelaySession('connected')) + // Direct stays unreachable, as in the field — return probes must not + // confuse the churn measurement by migrating back to direct. + const openDirect = vi.fn(() => new FakeSession('disconnected')) + const deps = dependencies({ openRelay, openDirect }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledOnce() + + await vi.advanceTimersByTimeAsync(5 * 60_000) + expect(openRelay).toHaveBeenCalledOnce() + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('recovers immediately on a background/foreground cycle after an E2EE rejection', async () => { + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi + .fn() + .mockReturnValueOnce( + new FakeRelaySession('disconnected', new MobileE2EEAuthenticationError()) + ) + .mockImplementation(() => new FakeRelaySession('connected')) + const deps = dependencies({ openRelay }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledOnce() + + supervisor.setForeground(false) + supervisor.setForeground(true) + await vi.advanceTimersByTimeAsync(0) + + expect(openRelay).toHaveBeenCalledTimes(2) + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) +}) + +// The field failure's first symptom: a real direct rpc-client dialing an +// unroutable LAN endpoint (instant 1006) while relay credentials sit unused. +class DeadSocket { + static constructed: string[] = [] + onopen: (() => void) | null = null + onclose: ((event: { code?: number; reason?: string }) => void) | null = null + onerror: ((event: unknown) => void) | null = null + onmessage: ((event: { data: unknown }) => void) | null = null + readyState = 0 + + constructor(readonly url: string) { + DeadSocket.constructed.push(url) + setTimeout(() => { + this.readyState = 3 + this.onclose?.({ code: 1006, reason: '' }) + }, 50) + } + + send(): void {} + close(): void { + this.readyState = 3 + } +} + +describe('failover with a real direct rpc-client', () => { + beforeEach(() => { + DeadSocket.constructed = [] + vi.stubGlobal('WebSocket', DeadSocket) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-08-02T12:00:00Z')) + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('migrates the logical client to relay after the direct dial fails', async () => { + const logical = createStableLogicalRpcClient( + connect(DIRECT_ENDPOINT, host.deviceToken, host.publicKeyB64), + 'tailscale' as MobileConnectionPath + ) + const deps = dependencies() + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + await vi.advanceTimersByTimeAsync(3_000) + + expect(deps.openRelay).toHaveBeenCalled() + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + logical.close() + }) + + it('reaches relay even when the bundle read settles after the first direct failure', async () => { + const logical = createStableLogicalRpcClient( + connect(DIRECT_ENDPOINT, host.deviceToken, host.publicKeyB64), + 'tailscale' as MobileConnectionPath + ) + const deps = dependencies({ + readBundle: vi.fn(async () => { + await new Promise((resolve) => setTimeout(resolve, 200)) + return bundleWith(2, Number.MAX_SAFE_INTEGER) + }) + }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + const started = supervisor.start() + await vi.advanceTimersByTimeAsync(300) + await started + await vi.advanceTimersByTimeAsync(3_000) + + expect(deps.openRelay).toHaveBeenCalled() + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + logical.close() + }) +}) diff --git a/mobile/src/transport/use-open-mobile-host-edit.ts b/mobile/src/transport/use-open-mobile-host-edit.ts new file mode 100644 index 00000000000..68c20c5ae3b --- /dev/null +++ b/mobile/src/transport/use-open-mobile-host-edit.ts @@ -0,0 +1,29 @@ +import { useCallback, useEffect, useRef } from 'react' +import { useNavigation, useRouter } from 'expo-router' +import { + navigateToMobileHostEdit, + type MobileHostEditNavigationController, + type MobileHostEditRootNavigation +} from './host-edit-navigation' + +export function useOpenMobileHostEdit(): (hostId: string) => void { + const navigation = useNavigation() + const router = useRouter() + const pendingRef = useRef(null) + + useEffect( + () => () => { + pendingRef.current?.cancel() + pendingRef.current = null + }, + [] + ) + + return useCallback( + (hostId) => { + pendingRef.current?.cancel() + pendingRef.current = navigateToMobileHostEdit(navigation, router, hostId) + }, + [navigation, router] + ) +} diff --git a/mobile/src/worktree/home-host-worktree-fetch.test.ts b/mobile/src/worktree/home-host-worktree-fetch.test.ts new file mode 100644 index 00000000000..5799de96366 --- /dev/null +++ b/mobile/src/worktree/home-host-worktree-fetch.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it } from 'vitest' +import { createHostConnectRefetchGate } from '../transport/host-connect-refetch-gate' +import type { RpcClient } from '../transport/rpc-client' +import { + createStableLogicalRpcClient, + LogicalClientCutoverError +} from '../transport/stable-logical-rpc-client' +import type { ConnectionState, RpcResponse } from '../transport/types' +import { fetchHomeHostWorktreeInfo } from './home-host-worktree-fetch' +import type { HostWorktreeInfo } from './home-worktree-info' + +type FakeSession = { + client: RpcClient + calls: number + settle: (response: RpcResponse | Error) => void +} + +function fakeSession(): FakeSession { + const pending: Array<(response: RpcResponse | Error) => void> = [] + const fake: FakeSession = { + calls: 0, + settle(response: RpcResponse | Error) { + const next = pending.shift() + next?.(response) + }, + client: { + sendRequest: () => { + fake.calls += 1 + return new Promise((resolve, reject) => { + pending.push((response) => + response instanceof Error ? reject(response) : resolve(response) + ) + }) + }, + subscribe: () => () => {}, + updateTerminalSubscriptionViewport: () => {}, + getState: (): ConnectionState => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + } + return fake +} + +// Drains the promise chain so a retry queued in a .catch has reached the transport. +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) + +function catalogResponse(count: number, active: number): RpcResponse { + const worktrees = Array.from({ length: count }, (_, index) => ({ + worktreeId: `wt-${index}`, + repo: 'orca', + branch: `branch-${index}`, + displayName: `Workspace ${index}`, + liveTerminalCount: 0, + status: index < active ? ('working' as const) : ('done' as const) + })) + return { ok: true, result: { worktrees } } as RpcResponse +} + +function infoStore() { + let state: Record = {} + return { + get current() { + return state + }, + setInfo(updater: (prev: Record) => Record) { + state = updater(state) + } + } +} + +const notDisposed = () => false + +describe('fetchHomeHostWorktreeInfo', () => { + it('keeps the last proven counts when the in-flight read rejects', async () => { + const store = infoStore() + const host = fakeSession() + + const loaded = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(catalogResponse(12, 2)) + await loaded + + const failed = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(new Error('socket closed mid-request')) + await failed + + expect(store.current['host-1']).toEqual({ + hostId: 'host-1', + totalWorktrees: 12, + activeCount: 2, + lastActiveWorktree: expect.objectContaining({ worktreeId: 'wt-0' }), + catalogUnavailable: true, + staleCounts: true, + // Age-stamped so the card can stop calling day-old counts "last known". + countsProvenAt: expect.any(Number) + }) + }) + + it('stamps when the host proved the counts', async () => { + const store = infoStore() + const host = fakeSession() + const before = Date.now() + + const loaded = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(catalogResponse(3, 1)) + await loaded + + const provenAt = store.current['host-1'].countsProvenAt + expect(provenAt).toBeGreaterThanOrEqual(before) + expect(provenAt).toBeLessThanOrEqual(Date.now()) + }) + + it('marks a host whose catalog never loaded as unavailable, not empty', async () => { + const store = infoStore() + const host = fakeSession() + + const failed = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle({ ok: false, error: { code: 'internal' } } as RpcResponse) + await failed + + expect(store.current['host-1']).toMatchObject({ + totalWorktrees: 0, + catalogUnavailable: true + }) + expect(store.current['host-1'].staleCounts).toBeUndefined() + }) + + it('re-reads the catalog on reconnect and clears the stale flag', async () => { + const store = infoStore() + const host = fakeSession() + const gate = createHostConnectRefetchGate() + + const connect = async (response: RpcResponse | Error) => { + if (!gate.observe('connected')) { + return + } + const done = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(response) + await done + } + + await connect(catalogResponse(12, 2)) + // Socket dies mid-poll: counts survive, flagged stale. + const dropped = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(new Error('socket closed mid-request')) + await dropped + gate.observe('reconnecting') + expect(store.current['host-1'].staleCounts).toBe(true) + + await connect(catalogResponse(13, 3)) + + expect(store.current['host-1']).toMatchObject({ + totalWorktrees: 13, + activeCount: 3 + }) + expect(store.current['host-1'].staleCounts).toBeUndefined() + expect(store.current['host-1'].catalogUnavailable).toBeUndefined() + // Two connects + the dropped poll: the gate must not re-read while the link holds. + expect(host.calls).toBe(3) + await connect(catalogResponse(13, 3)) + expect(host.calls).toBe(3) + }) + + it('re-reads through a relay→direct cutover, which never leaves connected', async () => { + const store = infoStore() + const relay = fakeSession() + const direct = fakeSession() + const logical = createStableLogicalRpcClient(relay.client, 'relay') + const gate = createHostConnectRefetchGate() + const gateFires: ConnectionState[] = [] + logical.onStateChange((state) => { + if (gate.observe(state)) { + gateFires.push(state) + } + }) + gate.observe(logical.getState()) + + const loaded = fetchHomeHostWorktreeInfo(logical, 'host-1', store.setInfo, notDisposed) + relay.settle(catalogResponse(12, 2)) + await loaded + + // The supervisor's direct probe migrates while a refresh is on the wire. + const interrupted = fetchHomeHostWorktreeInfo(logical, 'host-1', store.setInfo, notDisposed) + await logical.migrateTo(direct.client, 'lan') + await flush() + + expect(direct.calls).toBe(1) + direct.settle(catalogResponse(13, 3)) + await interrupted + + // The gate can't cover this: migrateTo republishes 'connected' from 'connected'. + expect(gateFires).toEqual([]) + expect(store.current['host-1']).toMatchObject({ totalWorktrees: 13, activeCount: 3 }) + expect(store.current['host-1'].staleCounts).toBeUndefined() + expect(store.current['host-1'].catalogUnavailable).toBeUndefined() + }) + + it('gives up on a host that keeps cutting over so the card still reports the failure', async () => { + const store = infoStore() + const host = fakeSession() + + const loaded = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, notDisposed) + host.settle(catalogResponse(12, 2)) + await loaded + + const cutoverStorm = fetchHomeHostWorktreeInfo( + host.client, + 'host-1', + store.setInfo, + notDisposed + ) + for (let attempt = 0; attempt < 6; attempt += 1) { + host.settle(new LogicalClientCutoverError()) + await flush() + } + await cutoverStorm + + // 1 original + CUTOVER_RETRY_LIMIT retries, then the failure is surfaced. + expect(host.calls).toBe(4) + expect(store.current['host-1'].staleCounts).toBe(true) + }) + + it('ignores a response that lands after the screen is disposed', async () => { + const store = infoStore() + const host = fakeSession() + + const done = fetchHomeHostWorktreeInfo(host.client, 'host-1', store.setInfo, () => true) + host.settle(new Error('socket closed mid-request')) + await done + + expect(store.current['host-1']).toBeUndefined() + }) +}) diff --git a/mobile/src/worktree/home-host-worktree-fetch.ts b/mobile/src/worktree/home-host-worktree-fetch.ts new file mode 100644 index 00000000000..7c6dafe6b14 --- /dev/null +++ b/mobile/src/worktree/home-host-worktree-fetch.ts @@ -0,0 +1,79 @@ +import { setCachedWorktrees } from '../cache/worktree-cache' +import { sendSingleFlightRequest } from '../transport/request-single-flight' +import type { RpcClient } from '../transport/rpc-client' +import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' +import { + markHomeWorktreeCatalogUnavailable, + type HomeWorktreeSummary, + type HostWorktreeInfo +} from './home-worktree-info' +import { pickResumeWorktree } from './resume-worktree' +import { WORKTREE_PS_FULL_LIMIT } from './worktree-catalog-snapshot-client' + +const ACTIVE_STATUSES = new Set(['working', 'active', 'permission']) +// Why: a relay↔direct cutover rejects in-flight reads without ever leaving 'connected', so the +// connect gate never re-arms. Re-issue on the replacement session; cap it so a migration loop +// can't spin. See runtime-capability-probe.ts for the same hazard on status.get. +const CUTOVER_RETRY_LIMIT = 2 + +export type HostWorktreeInfoSetter = ( + updater: (prev: Record) => Record +) => void + +/** Reads one host's worktree catalog for the Home card, preserving proven counts on failure. */ +export function fetchHomeHostWorktreeInfo( + client: RpcClient, + hostId: string, + setInfo: HostWorktreeInfoSetter, + disposed: () => boolean +): Promise { + const markUnavailable = (): void => { + setInfo((prev) => { + const current = prev[hostId] + const next = markHomeWorktreeCatalogUnavailable(current, hostId) + return next === current ? prev : { ...prev, [hostId]: next } + }) + } + + const attempt = (cutoverRetriesLeft: number): Promise => + sendSingleFlightRequest(client, hostId, 'worktree.ps', { limit: WORKTREE_PS_FULL_LIMIT }) + .then((response) => { + if (disposed()) { + return + } + if (!response.ok) { + markUnavailable() + return + } + const result = response.result as { worktrees?: HomeWorktreeSummary[] } + const worktrees = result.worktrees ?? [] + setCachedWorktrees(hostId, worktrees) + const active = worktrees.filter((w) => w.status && ACTIVE_STATUSES.has(w.status)) + // Mirror the desktop's focused workspace (see pickResumeWorktree). + const lastActive = pickResumeWorktree(worktrees) + setInfo((prev) => ({ + ...prev, + [hostId]: { + hostId, + totalWorktrees: worktrees.length, + activeCount: active.length, + lastActiveWorktree: lastActive, + countsProvenAt: Date.now() + } + })) + }) + .catch((error: unknown) => { + if (disposed()) { + return + } + // A cutover raises only after migrateTo installed an authenticated replacement, so the + // read was interrupted, not answered — ask again instead of latching "Last known". + if (cutoverRetriesLeft > 0 && isLogicalClientCutoverError(error)) { + return attempt(cutoverRetriesLeft - 1) + } + // Any other rejection (socket died mid-request) is a failed refresh, not an empty host. + markUnavailable() + }) + + return attempt(CUTOVER_RETRY_LIMIT) +} diff --git a/mobile/src/worktree/home-worktree-info.test.ts b/mobile/src/worktree/home-worktree-info.test.ts index ebbfe379e99..5cb80d007dd 100644 --- a/mobile/src/worktree/home-worktree-info.test.ts +++ b/mobile/src/worktree/home-worktree-info.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { markHomeWorktreeCatalogUnavailable, type HostWorktreeInfo } from './home-worktree-info' +import { + HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS, + homeHostWorktreeSummary, + markHomeWorktreeCatalogUnavailable, + type HostWorktreeInfo +} from './home-worktree-info' describe('markHomeWorktreeCatalogUnavailable', () => { it('marks a host unavailable when no catalog has loaded', () => { @@ -28,7 +33,8 @@ describe('markHomeWorktreeCatalogUnavailable', () => { expect(markHomeWorktreeCatalogUnavailable(current, 'host-1')).toEqual({ ...current, - catalogUnavailable: true + catalogUnavailable: true, + staleCounts: true }) }) @@ -44,3 +50,73 @@ describe('markHomeWorktreeCatalogUnavailable', () => { expect(markHomeWorktreeCatalogUnavailable(current, 'host-1')).toBe(current) }) }) + +describe('homeHostWorktreeSummary', () => { + const provenAt = 1_700_000_000_000 + const loaded: HostWorktreeInfo = { + hostId: 'host-1', + totalWorktrees: 12, + activeCount: 2, + lastActiveWorktree: null, + countsProvenAt: provenAt + } + + it('summarizes a freshly loaded catalog', () => { + expect(homeHostWorktreeSummary(loaded, provenAt)).toBe('12 worktrees · 2 active') + expect( + homeHostWorktreeSummary({ ...loaded, totalWorktrees: 1, activeCount: 0 }, provenAt) + ).toBe('1 worktree') + }) + + it('keeps showing the last proven counts after a failed refresh', () => { + const afterFailure = markHomeWorktreeCatalogUnavailable(loaded, 'host-1') + + expect(homeHostWorktreeSummary(afterFailure, provenAt + 30_000)).toBe( + 'Last known: 12 worktrees · 2 active' + ) + }) + + it('keeps the last proven counts however long ago the refresh failed', () => { + const afterFailure = markHomeWorktreeCatalogUnavailable(loaded, 'host-1') + + // A session that stays connected past the live window then hits one failed refresh is the + // headline case: the counts are history, not nothing. + expect( + homeHostWorktreeSummary(afterFailure, provenAt + HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS + 1) + ).toBe('Last known: 12 worktrees · 2 active') + expect(homeHostWorktreeSummary(afterFailure, provenAt + 3 * 86_400_000)).toBe( + 'Last known: 12 worktrees · 2 active' + ) + }) + + it('stops calling aged-out counts live even while a refresh is only pending', () => { + // A snapshot rehydrated from a previous app session describes a host we have not reached yet. + expect(homeHostWorktreeSummary(loaded, provenAt + HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS)).toBe( + '12 worktrees · 2 active' + ) + expect( + homeHostWorktreeSummary(loaded, provenAt + HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS + 1) + ).toBe('Last known: 12 worktrees · 2 active') + expect(homeHostWorktreeSummary(loaded, provenAt + 3 * 86_400_000)).toBe( + 'Last known: 12 worktrees · 2 active' + ) + }) + + it('treats counts persisted before age stamping as no longer live', () => { + const preUpgrade: HostWorktreeInfo = { ...loaded, countsProvenAt: undefined } + + expect(homeHostWorktreeSummary(preUpgrade, provenAt)).toBe( + 'Last known: 12 worktrees · 2 active' + ) + expect( + homeHostWorktreeSummary(markHomeWorktreeCatalogUnavailable(preUpgrade, 'host-1'), provenAt) + ).toBe('Last known: 12 worktrees · 2 active') + }) + + it('reports unavailable only when no catalog ever loaded', () => { + expect(homeHostWorktreeSummary(markHomeWorktreeCatalogUnavailable(undefined, 'host-1'))).toBe( + 'Worktree list unavailable' + ) + expect(homeHostWorktreeSummary(undefined)).toBeNull() + }) +}) diff --git a/mobile/src/worktree/home-worktree-info.ts b/mobile/src/worktree/home-worktree-info.ts index 867e266e89e..a417636dcaf 100644 --- a/mobile/src/worktree/home-worktree-info.ts +++ b/mobile/src/worktree/home-worktree-info.ts @@ -15,8 +15,17 @@ export type HostWorktreeInfo = { activeCount: number lastActiveWorktree: HomeWorktreeSummary | null catalogUnavailable?: boolean + // The counts are the last proven ones, kept across a failed refresh. + staleCounts?: boolean + // When the host last answered with these counts (ms epoch); absent in snapshots an older + // build persisted, which is why an unstamped count counts as expired rather than fresh. + countsProvenAt?: number } +// Why: the home snapshot is persisted across launches, so counts could otherwise be rendered as +// live while describing a workspace set proven days ago. Past this window they are only history. +export const HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS = 10 * 60_000 + export function markHomeWorktreeCatalogUnavailable( current: HostWorktreeInfo | undefined, hostId: string @@ -25,7 +34,9 @@ export function markHomeWorktreeCatalogUnavailable( return current } if (current) { - return { ...current, catalogUnavailable: true } + // Why: `current` predates this failure, so its counts are proven host truth — a dropped + // socket must not erase them, only flag them as no longer live. + return { ...current, catalogUnavailable: true, staleCounts: true } } return { hostId, @@ -35,3 +46,32 @@ export function markHomeWorktreeCatalogUnavailable( catalogUnavailable: true } } + +/** The host card's worktree line, or null when nothing is known yet. */ +export function homeHostWorktreeSummary( + info: HostWorktreeInfo | undefined, + now: number = Date.now() +): string | null { + if (!info) { + return null + } + // Why (STA-3123): a catalog that never loaded must not assert a count the host has not proven. + if (info.catalogUnavailable && !info.staleCounts) { + return 'Worktree list unavailable' + } + const counts = `${info.totalWorktrees} worktree${info.totalWorktrees === 1 ? '' : 's'}${ + info.activeCount > 0 ? ` · ${info.activeCount} active` : '' + }` + // Age bounds liveness, not the counts themselves: a failed refresh — or a rehydrated snapshot the + // host has not re-confirmed — is still the last thing it told us, so keep it and drop the claim + // that it is current. + return info.staleCounts || !provenRecently(info, now) ? `Last known: ${counts}` : counts +} + +function provenRecently(info: HostWorktreeInfo, now: number): boolean { + // A snapshot written before countsProvenAt existed has an unknowable age; treat it as expired. + return ( + typeof info.countsProvenAt === 'number' && + now - info.countsProvenAt <= HOME_WORKTREE_COUNTS_LIVE_MAX_AGE_MS + ) +} diff --git a/mobile/src/worktree/host-worktree-refresh.test.ts b/mobile/src/worktree/host-worktree-refresh.test.ts index fb7e48a7a48..d0b8cf01dab 100644 --- a/mobile/src/worktree/host-worktree-refresh.test.ts +++ b/mobile/src/worktree/host-worktree-refresh.test.ts @@ -86,8 +86,8 @@ describe('startHostWorktreeRefresh', () => { // Mount force-fetch. expect(fetchRepoMetadata).toHaveBeenCalledTimes(1) - // Foregrounded: repo.list rides the interval as a convergence safety-net for desktop - // Settings edits that never emit a runtime reposChanged (the callee self-throttles). + // Foregrounded: repo.list rides the interval as a convergence safety-net for hosts on an + // older build, whose Settings edits emit no runtime reposChanged (the callee self-throttles). await vi.advanceTimersByTimeAsync(9_000) expect(fetchWorktrees).toHaveBeenCalledTimes(4) expect(fetchRepoMetadata).toHaveBeenCalledTimes(4) diff --git a/mobile/src/worktree/host-worktree-refresh.ts b/mobile/src/worktree/host-worktree-refresh.ts index 264b3c6e266..525fc335b8f 100644 --- a/mobile/src/worktree/host-worktree-refresh.ts +++ b/mobile/src/worktree/host-worktree-refresh.ts @@ -39,11 +39,11 @@ export function startHostWorktreeRefresh({ return } void fetchWorktrees() - // Why: desktop Settings repo edits (icon/color/name, repo removal) notify only the - // renderer IPC, not the runtime clientEvents stream, so `reposChanged` never reaches - // mobile. Keep a periodic repo.list as the convergence safety-net; fetchRepoMetadata - // self-throttles to REPO_METADATA_REFRESH_MS (60s), so this is ~1 request/min while - // foregrounded — the AppState gate is what removes the waste (both stop while backgrounded). + // Why: desktop Settings repo edits (icon/color/name, repo removal) now emit `reposChanged` + // (#11994), but a host on an older build does not; keep this periodic repo.list as the + // convergence safety-net. fetchRepoMetadata self-throttles to REPO_METADATA_REFRESH_MS + // (60s), so this is ~1 request/min while foregrounded — the AppState gate is what removes + // the waste (both stop while backgrounded). void fetchRepoMetadata() }, WORKTREE_REFRESH_MS) const unsubscribe = client.subscribe( diff --git a/mobile/src/worktree/workspace-list-sections.test.ts b/mobile/src/worktree/workspace-list-sections.test.ts index d6d04d43d3e..d1fc267c09f 100644 --- a/mobile/src/worktree/workspace-list-sections.test.ts +++ b/mobile/src/worktree/workspace-list-sections.test.ts @@ -106,6 +106,95 @@ describe('filterWorktrees', () => { ).toEqual([featureNamedMain]) }) + it('keeps a sleeping main worktree visible under hide-sleeping by default (#8873)', () => { + const main = worktree({ worktreeId: 'main', branch: 'main', isMainWorktree: true }) + const feature = worktree({ worktreeId: 'feature', isMainWorktree: false }) + + expect( + filterWorktrees( + [main, feature], + { filterRepoIds: new Set(), hideSleeping: true, hideDefaultBranch: false }, + '' + ) + ).toEqual([main]) + }) + + it('keeps a sleeping folder workspace visible under hide-sleeping', () => { + const folder = worktree({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:workspace-1', + branch: '', + isMainWorktree: true + }) + + expect( + filterWorktrees( + [folder], + { filterRepoIds: new Set(), hideSleeping: true, hideDefaultBranch: false }, + '' + ) + ).toEqual([folder]) + }) + + it('re-hides the sleeping main worktree when the desktop setting is off', () => { + const main = worktree({ worktreeId: 'main', branch: 'main', isMainWorktree: true }) + + expect( + filterWorktrees( + [main], + { + filterRepoIds: new Set(), + hideSleeping: true, + hideDefaultBranch: false, + alwaysShowDefaultBranch: false + }, + '' + ) + ).toEqual([]) + }) + + it('falls back to the branch heuristic for hosts that omit isMainWorktree', () => { + const legacyMain = worktree({ worktreeId: 'legacy-main', branch: 'refs/heads/master' }) + + expect( + filterWorktrees( + [legacyMain], + { filterRepoIds: new Set(), hideSleeping: true, hideDefaultBranch: false }, + '' + ) + ).toEqual([legacyMain]) + }) + + it('keeps a sleeping folder workspace on hosts that omit isMainWorktree', () => { + // A folder workspace has no branch, so the legacy branch heuristic can never + // recognise it — without its own arm, #8873 still reproduces on old desktops. + const legacyFolder = worktree({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:legacy-1', + branch: '' + }) + + expect( + filterWorktrees( + [legacyFolder], + { filterRepoIds: new Set(), hideSleeping: true, hideDefaultBranch: false }, + '' + ) + ).toEqual([legacyFolder]) + }) + + it('lets hide-default-branch still win over the sleeping exemption', () => { + const main = worktree({ worktreeId: 'main', branch: 'main', isMainWorktree: true }) + + expect( + filterWorktrees( + [main], + { filterRepoIds: new Set(), hideSleeping: true, hideDefaultBranch: true }, + '' + ) + ).toEqual([]) + }) + it('keeps folder workspaces when default branch hiding is enabled', () => { const folder = worktree({ workspaceKind: 'folder-workspace', diff --git a/mobile/src/worktree/workspace-list-sections.ts b/mobile/src/worktree/workspace-list-sections.ts index bdb9e4783e3..d798a7fe5fa 100644 --- a/mobile/src/worktree/workspace-list-sections.ts +++ b/mobile/src/worktree/workspace-list-sections.ts @@ -65,6 +65,19 @@ function isDefaultBranchWorkspace(w: Worktree): boolean { return branch === 'main' || branch === 'master' } +/** + * Whether "Hide sleeping" must keep this row — the project's entry point (#8873). + * Falls back to the branch heuristic for hosts that predate isMainWorktree; a + * folder workspace is always its project's entry point, and isDefaultBranchWorkspace + * rejects it by design, so it needs its own legacy arm or #8873 still reproduces. + */ +function isSleepingSweepExempt(w: Worktree, alwaysShowDefaultBranch: boolean | undefined): boolean { + if (alwaysShowDefaultBranch === false) { + return false + } + return w.isMainWorktree ?? (w.workspaceKind === 'folder-workspace' || isDefaultBranchWorkspace(w)) +} + function orderMainWorktreeFirst(worktrees: Worktree[]): Worktree[] { const mainWorktrees = worktrees.filter((worktree) => worktree.isMainWorktree) if (mainWorktrees.length === 0) { @@ -80,7 +93,9 @@ export function filterWorktrees( ): Worktree[] { let result = worktrees.filter((w) => !w.isArchived) if (filters.hideSleeping) { - result = result.filter(isWorktreeActive) + result = result.filter( + (w) => isSleepingSweepExempt(w, filters.alwaysShowDefaultBranch) || isWorktreeActive(w) + ) } if (filters.hideDefaultBranch) { result = result.filter((w) => !isDefaultBranchWorkspace(w)) diff --git a/mobile/src/worktree/workspace-list-types.ts b/mobile/src/worktree/workspace-list-types.ts index 4dfbc74fa53..4ddb135affe 100644 --- a/mobile/src/worktree/workspace-list-types.ts +++ b/mobile/src/worktree/workspace-list-types.ts @@ -52,6 +52,8 @@ export type FilterState = { filterRepoIds: Set hideSleeping: boolean hideDefaultBranch: boolean + /** Absent means on: #8873's exemption must fail open on older host payloads. */ + alwaysShowDefaultBranch?: boolean } export type Section = { key: string; title: string; icon?: 'pin'; data: Worktree[] } diff --git a/mobile/src/worktree/workspace-view-settings.ts b/mobile/src/worktree/workspace-view-settings.ts index 0987915645a..32a4ac73a63 100644 --- a/mobile/src/worktree/workspace-view-settings.ts +++ b/mobile/src/worktree/workspace-view-settings.ts @@ -16,6 +16,7 @@ export type WorkspaceViewSettings = { sortBy?: 'name' | 'smart' | 'recent' | 'repo' | 'manual' hideSleepingWorkspaces?: boolean hideDefaultBranchWorkspace?: boolean + alwaysShowDefaultBranchWorkspace?: boolean filterRepoIds?: string[] collapsedGroups?: string[] workspaceStatuses?: WorkspaceStatusDefinition[] @@ -60,6 +61,7 @@ export type MobileViewState = { sortMode: MobileSortMode hideSleeping: boolean hideDefaultBranch: boolean + alwaysShowDefaultBranch: boolean filterRepoIds: string[] collapsedGroups: string[] workspaceStatuses: readonly WorkspaceStatusDefinition[] @@ -83,6 +85,8 @@ export function applyDesktopViewSettings( sortMode: sortMode ?? current.sortMode, hideSleeping: settings.hideSleepingWorkspaces ?? current.hideSleeping, hideDefaultBranch: settings.hideDefaultBranchWorkspace ?? current.hideDefaultBranch, + alwaysShowDefaultBranch: + settings.alwaysShowDefaultBranchWorkspace ?? current.alwaysShowDefaultBranch, filterRepoIds: settings.filterRepoIds ?? current.filterRepoIds, collapsedGroups: settings.collapsedGroups ?? current.collapsedGroups, workspaceStatuses diff --git a/mobile/vitest.config.ts b/mobile/vitest.config.ts index 9e7e3ecc59d..e39f90eedf1 100644 --- a/mobile/vitest.config.ts +++ b/mobile/vitest.config.ts @@ -9,6 +9,8 @@ export default defineConfig({ oxc: vitestOxcConfig, test: { environment: 'node', - include: ['src/**/*.test.ts'] + // .tsx too: component tests exist (react-test-renderer + mocked react-native) and were + // silently never collected, so render-level regressions shipped untested. + include: ['src/**/*.test.ts', 'src/**/*.test.tsx'] } }) diff --git a/native/windows-cli-launcher/OrcaCliLauncher.cs b/native/windows-cli-launcher/OrcaCliLauncher.cs index 8f89e303413..6261775859b 100644 --- a/native/windows-cli-launcher/OrcaCliLauncher.cs +++ b/native/windows-cli-launcher/OrcaCliLauncher.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Text; @@ -43,18 +42,17 @@ internal static class OrcaCliLauncher // Why: launching without cmd.exe preserves embedded newlines while matching the // packaged batch launcher's Electron-as-Node environment contract. - MoveEnvironmentVariable(startInfo.EnvironmentVariables, "NODE_OPTIONS", "ORCA_NODE_OPTIONS"); - MoveEnvironmentVariable( - startInfo.EnvironmentVariables, - "NODE_REPL_EXTERNAL_MODULE", - "ORCA_NODE_REPL_EXTERNAL_MODULE" + // Why: ProcessStartInfo's env copy rejects duplicate PATH/Path keys; mutating this + // short-lived process preserves the native block for child inheritance (#12046). + MoveEnvironmentVariable("NODE_OPTIONS", "ORCA_NODE_OPTIONS"); + MoveEnvironmentVariable("NODE_REPL_EXTERNAL_MODULE", "ORCA_NODE_REPL_EXTERNAL_MODULE"); + Environment.SetEnvironmentVariable("ELECTRON_RUN_AS_NODE", "1"); + Environment.SetEnvironmentVariable("ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER", "1"); + string requestedCliCommand = Environment.GetEnvironmentVariable("ORCA_CLI_COMMAND"); + Environment.SetEnvironmentVariable( + "ORCA_CLI_COMMAND", + requestedCliCommand == "orca-ide" ? "orca-ide" : "orca" ); - startInfo.EnvironmentVariables["ELECTRON_RUN_AS_NODE"] = "1"; - startInfo.EnvironmentVariables["ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER"] = "1"; - startInfo.EnvironmentVariables["ORCA_CLI_COMMAND"] = - Environment.GetEnvironmentVariable("ORCA_CLI_COMMAND") == "orca-ide" - ? "orca-ide" - : "orca"; using (Process child = Process.Start(startInfo)) { @@ -69,19 +67,12 @@ internal static class OrcaCliLauncher } } - private static void MoveEnvironmentVariable( - StringDictionary environment, - string sourceName, - string targetName - ) + private static void MoveEnvironmentVariable(string sourceName, string targetName) { string value = Environment.GetEnvironmentVariable(sourceName); - environment.Remove(sourceName); - environment.Remove(targetName); - if (value != null) - { - environment[targetName] = value; - } + Environment.SetEnvironmentVariable(sourceName, null); + // Why: a null value clears the target, matching the previous unconditional Remove. + Environment.SetEnvironmentVariable(targetName, value); } private static string BuildArguments(string cliPath, string[] args) diff --git a/package.json b/package.json index 3b7da4f9bdd..e8ec89daae0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca", - "version": "1.4.168-rc.1", + "version": "1.4.169-rc.0", "description": "Next-gen IDE for parallel agentic development", "homepage": "https://github.com/stablyai/orca", "author": "stablyai", @@ -209,7 +209,7 @@ "lowlight": "^3.3.0", "lucide-react": "^0.577.0", "marked": "^17.0.1", - "mermaid": "^11.15.0", + "mermaid": "^11.16.0", "monaco-editor": "^0.55.1", "oxfmt": "^0.52.0", "oxlint": "^1.75.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index edd1f3e41e4..c4d53a979e1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,7 +13,7 @@ patchedDependencies: hash: 47405b9994b5acf1b4e90b49250358c1ca03649854d59560e7732b72fe336920 path: config/patches/@xterm__addon-ligatures@0.11.0-beta.287.patch '@xterm/addon-serialize@0.15.0-beta.287': - hash: 81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9 + hash: 96f70e83261df6a29ad7590feb08b988670655ced7596e77253d524f73f608dd path: config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch '@xterm/addon-webgl@0.20.0-beta.286': hash: 6da7d7770b6427246f2a0d057d97da418040e498068b41d0c2d3c6b20bf49258 @@ -46,7 +46,7 @@ importers: version: 2.5.6 '@xterm/addon-serialize': specifier: 0.15.0-beta.287 - version: 0.15.0-beta.287(patch_hash=81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9)(@xterm/xterm@6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8)) + version: 0.15.0-beta.287(patch_hash=96f70e83261df6a29ad7590feb08b988670655ced7596e77253d524f73f608dd)(@xterm/xterm@6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8)) '@xterm/headless': specifier: 6.1.0-beta.287 version: 6.1.0-beta.287 @@ -283,8 +283,8 @@ importers: specifier: ^17.0.1 version: 17.0.6 mermaid: - specifier: ^11.15.0 - version: 11.15.0 + specifier: ^11.16.0 + version: 11.16.0 monaco-editor: specifier: ^0.55.1 version: 0.55.1 @@ -1041,8 +1041,8 @@ packages: resolution: {integrity: sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==} engines: {node: '>= 10.0.0'} - '@mermaid-js/parser@1.1.1': - resolution: {integrity: sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==} + '@mermaid-js/parser@1.2.0': + resolution: {integrity: sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==} '@modelcontextprotocol/sdk@1.29.0': resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==} @@ -5211,8 +5211,8 @@ packages: resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} engines: {node: '>= 8'} - mermaid@11.15.0: - resolution: {integrity: sha512-pTMbcf3rWdtLiYGpmoTjHEpeY8seiy6sR+9nD7LOs8KfUbHE4lOUAprTRqRAcWSQ6MQpdX+YEsxShtGsINtPtw==} + mermaid@11.16.0: + resolution: {integrity: sha512-Zvm3kbstgdpvIJPPItlL7fppIZ3kibvc1oZIGxdvk9t6UFz6flv+Jw7FtRGKwfcI8OckmH04LqG6LlS6X4B1pA==} micromark-core-commonmark@2.0.3: resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==} @@ -7511,7 +7511,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@mermaid-js/parser@1.1.1': + '@mermaid-js/parser@1.2.0': dependencies: '@chevrotain/types': 11.1.2 @@ -9596,7 +9596,7 @@ snapshots: dependencies: '@xterm/xterm': 6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8) - '@xterm/addon-serialize@0.15.0-beta.287(patch_hash=81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9)(@xterm/xterm@6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8))': + '@xterm/addon-serialize@0.15.0-beta.287(patch_hash=96f70e83261df6a29ad7590feb08b988670655ced7596e77253d524f73f608dd)(@xterm/xterm@6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8))': dependencies: '@xterm/xterm': 6.1.0-beta.287(patch_hash=037272642db6a9bf5242c02acacf8fc41f4c6e91268d8a47ea083c98fb2535b8) @@ -11647,11 +11647,11 @@ snapshots: merge2@1.4.1: {} - mermaid@11.15.0: + mermaid@11.16.0: dependencies: '@braintree/sanitize-url': 7.1.2 '@iconify/utils': 3.1.1 - '@mermaid-js/parser': 1.1.1 + '@mermaid-js/parser': 1.2.0 '@types/d3': 7.4.3 '@upsetjs/venn.js': 2.0.0 cytoscape: 3.33.3 diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index e78652d4198..4c790282bb0 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -224,10 +224,18 @@ Wait until every expected Dispatch settles, not for a fixed number of batches: ```bash orca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json -# Process every message in the returned Delivery, then atomically ack and continue: +# Process every message. For each accepted worker_done that is not immediately reused: +orca orchestration worker-release --dispatch --json +# Acknowledge only after every message and required release decision is handled: orca orchestration check --ack --wait --types worker_done,escalation,question --timeout-ms 900000 --json ``` +After processing each accepted `worker_done`, choose the terminal's next owner before you acknowledge the Delivery or wait again. If the same exact agent has an immediate follow-up Task, read the `worker.agent_terminal_handle` field of `worker-show --dispatch --json`, then run `orca orchestration worker-start --task --terminal --json` so Orca transfers cleanup ownership to the new Dispatch. Otherwise run `orca orchestration worker-release --dispatch --json`. + +Run `worker-release` after both succeeded and failed `worker_done` reports unless the user explicitly asked to keep that worker live. Release is post-completion cleanup, not cancellation: Orca first preserves inspectable output, then closes only the exact agent terminal owned by that settled Dispatch. Reused or pre-existing terminals, setup terminals, coordinators, active workers, user-taken-over terminals, and identities Orca cannot prove are retained. If the user explicitly asks to keep the live terminal for debugging, record that exception with `orca orchestration worker-retain --dispatch --json` instead of silently skipping cleanup. When the user is finished, the same Dispatch can be passed to `worker-release`, which clears the requested retention and releases the terminal. + +Do not release a worker because of a timeout, TUI idle state, heartbeat, status, question, escalation, or rejected/stale `worker_done`. If release returns `release_pending` or `release_unknown`, do not substitute `terminal close`; follow the exact recovery action in the receipt. A replayed Delivery may repeat `worker-release` safely. + Workers report exactly once using the IDs and capability injected by Orca; they do not supply Run/server/terminal identity: ```bash @@ -364,11 +372,12 @@ Wait for `tui-idle` before dispatching. Always pass `--timeout-ms`; real coding - Workers with a valid live preamble must send `worker_done` exactly once from their own terminal with an explicit `--outcome succeeded` or `--outcome failed`: `orca orchestration send --type worker_done --subject "" --body "<3-sentence summary: what you did, what you found, what's left>" --task-id --dispatch-id --outcome succeeded --files-modified "path/a" --report-path "" --json` - A failed outcome is still a terminal report, but Orca records both the Dispatch and Task as failed. Never encode failure only in the subject/body. -- After sending `worker_done`, end your turn and idle at the agent prompt. Do not poll or keep calling `orca orchestration check`; the coordinator re-engages you with a fresh preamble + TASK block delivered as new terminal input. +- After sending `worker_done`, end your turn and idle at the agent prompt. The coordinator may reuse or release this terminal after it processes your report; do not start more work, poll, or attempt to close the terminal yourself. If it reuses you, it re-engages you with a fresh preamble + TASK block delivered as new terminal input. - For long tasks, send heartbeat/status only when the preamble asks for it, including both IDs: `orca orchestration send --type heartbeat --subject "alive" --payload '{"taskId":"","dispatchId":"","phase":"implementing"}' --json` - If blocked before completion, use `ask`; use `escalation` only when ownership is valid and the coordinator must intervene. - Treat preambles inherited through terminal history or full handoffs as stale unless the current prompt explicitly keeps that coordinator in the loop. +- Coordinators must account for every settled worker terminal before waiting again or ending the turn: immediately reuse the exact worker for a new Dispatch, explicitly retain it at the user's request with `worker-retain`, or run `worker-release`. Do not leave a completed worker live merely to inspect output; released workers remain readable through `worker-read`. - Coordinators should use `task-list --ready` as external memory, dispatch parallel waves, and avoid dependency chains deeper than 3-4 steps. ## Example @@ -383,6 +392,6 @@ orca orchestration check --wait --types worker_done,escalation,question --timeou ## Next Action -Coordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology. +Coordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology. After every accepted `worker_done`, either transfer the exact terminal to an immediate follow-up Dispatch or run `worker-release` before the next wait. Worker: if the current prompt contains a live dispatch preamble, do the task, use `ask` for blocking questions, and send `worker_done` once with the required payload. If the preamble is stale or absent, do not send lifecycle messages; inspect state or treat the prompt as an ordinary handoff. diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 748d62dd1a6..0609150c458 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -30,7 +30,7 @@ const ORCA_LINEAR_MARKDOWN = "---\nname: orca-linear\ndescription: >-\n Use Orc const ORCA_PER_WORKSPACE_ENV_MARKDOWN = "---\nname: orca-per-workspace-env\ndescription: >-\n Set up, review, debug, or validate Orca per-workspace environment recipes —\n on-demand, disposable runtimes (cloud sandboxes, VMs, or local) created fresh\n for each workspace. Covers first-time setup (provider prerequisites, the\n reusable base snapshot, the coding-agent auth snapshot, credentials, and\n state), not just the per-workspace lifecycle scripts. Use to stand up\n per-workspace environments, fix an `environmentRecipes` entry in `orca.yaml`, scaffold\n provider lifecycle scripts, or resolve an `orca vm recipe doctor` failure.\n---\n\n# Per-Workspace Environments\n\nHelp a user stand up and maintain a repo-owned per-workspace environment recipe end to end. Each\nworkspace gets its own on-demand, disposable runtime (a cloud sandbox, a VM, or a local one),\ncreated fresh and torn down after.\n\nOrca is a **thin wrapper**: you guide, detect, and scaffold; you never own the user's cloud account,\nbilling, images, or credentials.\n\n- **You DO:** sequence the setup, detect what's detectable (provider CLI present/logged-in? recipe\n present? `doctor` passing?), scaffold provider-templated scripts the user fills in, drive the slow\n snapshot/auth phases with the user, and always show the next action.\n- **You DO NOT:** create accounts, choose plans/regions, invent org/project/scope ids, store or print\n secrets, or run anything that spends money without an explicit user OK.\n\nFirst-time setup has **four phases before the per-workspace recipe runs** — easy to miss, so walk\nthem in order:\n\n1. **Prerequisites** — cloud account, provider CLI, scope/project, plan limits, git token (§2).\n2. **Base snapshot** — reusable image: tools + repo + headless build, snapshotted once (§3).\n3. **Agent-auth snapshot** — boot the base, run interactive device-auth, re-snapshot (§4).\n4. **State** — thread snapshot id / scope / project / port between phases via a state file (§6).\n\nThen the **per-workspace contract** (create/suspend/resume/destroy) runs fast (§8).\n\n**The one branch that shapes everything — connection mode:** **Orca-server** (`create` runs `orca serve`\nin the env and emits a `pairingCode`; §7c/§7f) vs **SSH** (`create` runs no server and emits a\n`connection.type:\"ssh\"` block Orca dials into; §7g/§7h). Settle this first — it changes the `create`\noutput shape and half the templates.\n\n**Quick-start (happy path):** interview the user (connection mode Orca-server vs SSH, provider, agent CLI,\ngit auth — §1.2) + read the provider's CLI docs → scaffold `scripts/orca-vm/` from §7 → run the\nbase-snapshot script, then the auth script (you invoke these by hand; not via `orca.yaml`) → wire\n`environmentRecipes` in `orca.yaml` → `orca vm recipe doctor --json` (free) → then the `--provision`\nself-test loop (§9) until it passes.\n\n---\n\n## 1. Setup workflow\n\nDrive these with the user. **[CHECKPOINT]** steps need explicit confirmation — they spend money, take\na long time, or need the user at the keyboard. Never create an Orca workspace or commit unless asked.\n\n1. **Inspect the repo** for an existing `environmentRecipes` entry, `scripts/orca-vm/`, a state file, or setup\n notes. If a working recipe exists, jump to Doctor (§9) instead of rebuilding.\n2. **Interview the user up front** — gather these choices and confirm them back before scaffolding\n anything. Don't pick for them (§11); don't guess.\n - **Connection mode:** how Orca attaches to the environment — an **Orca server** (the VM runs\n `orca serve` and Orca pairs over its pairing URL; worked example §7f) or **SSH** (Orca connects to\n the host over SSH; §7g). This decides the recipe's connection shape, so settle it first.\n - **Provider:** Vercel Sandbox, Fly, Modal, an existing SSH host, … For non-obvious providers, also\n ask scope/project/region and plan limits (§2). Then **read that provider's CLI/SDK docs** (or\n ` --help`) before scaffolding — you need its exact create/exec/snapshot/remove verbs.\n If a provider advertises `ssh`, verify whether it exposes a real dialable SSH target\n (host/port/user/key or proxy command) or only a provider-mediated interactive shell; Orca SSH mode\n needs the former.\n - **Coding-agent CLI + account:** which agent runs in the VM (`codex`, `claude`, …) and that the user\n has an account for it — it gets logged in during the Phase-3 auth snapshot (§4).\n - **Git auth:** the token source for cloning a private repo (`GH_TOKEN`/`GITHUB_TOKEN` or `gh auth\n token`; §5).\n3. **Check prerequisites (§2)** — detect the provider CLI + auth and confirm the items above are in\n place before any paid step.\n4. **Scaffold scripts + state file** from §7 (worked Vercel example: §7f; SSH host: §7g; Docker SSH:\n §7h; Windows: §7i), filling in the provider's real commands. Make them executable.\n5. **[CHECKPOINT] Build the base snapshot (§3)** — paid, slow.\n6. **[CHECKPOINT] Authenticate the agent (§4)** — interactive; the user follows a URL/code. **You cannot\n drive this step** — you run commands non-interactively, so there's no TTY for `docker exec -it` /\n `ssh -t` to prompt against. The **user** runs the Phase-3 login in their own terminal (or via the\n Claude Code harness bang-prefix — `! `, with the required space after `!`); you scaffold and drive\n the non-interactive phases around it. After kicking it off, **ask the user to report back once the login\n finishes** — you can't observe it completing, and you need that confirmation before resuming the\n non-interactive steps (base/auth commit, doctor, provision).\n7. **Wire the recipe** so `orca.yaml` points create/suspend/resume/destroy at the scripts (§8). The\n workspace composer reads `environmentRecipes` from the project's primary checkout of `orca.yaml`, **not** from\n a feature branch or worktree. So a recipe added only on a branch won't appear as a \"Run on\" option\n until that `orca.yaml` change is committed and merged to the project's primary branch. Tell the user\n this up front: `doctor`/`--provision` validate the scripts from the working copy on any branch, but\n creating a workspace from the recipe in the picker needs it on primary.\n8. **Dry-run doctor** — `orca vm recipe doctor --repo-path --json` (free, static; §9).\n Fix every failure before going live.\n9. **[CHECKPOINT] Live self-test** — get the user's OK once, then run\n `orca vm recipe doctor --provision --json` as a loop: it runs create → validates →\n destroys, and on failure returns a full transcript. Read it, fix the scripts, and re-run yourself until\n it passes (§9). Spends cloud money; the one approval covers the loop.\n10. **[CHECKPOINT] Optional workspace test** — only if asked: create a workspace via the picker, then\n verify sleep/wake/delete.\n\n---\n\n## 2. Phase 1 — Prerequisites\n\nThe user's responsibility; verify what's verifiable, ask for the rest, invent nothing. State which\nitems you verified vs. which the user asserted.\n\n- **Connection mode** (Orca server vs SSH) confirmed with the user — see §1 step 2; it shapes the recipe.\n- **Cloud account + plan** that allows sandboxes/VMs. Ask.\n- **Provider CLI installed + authenticated** — detect (`command -v `), check auth (e.g.\n `vercel whoami`). If missing, point at the provider's docs; don't log them in.\n- **Scope / project / region** the sandboxes live under. Ask; flows into every script via state.\n- **Plan / timeout / RAM caps.** Record them — e.g. Vercel Hobby caps sandbox timeout at **45m**,\n which limits both the base build and per-workspace runtime (see §10).\n- **Git token for private repos** (`GH_TOKEN`/`GITHUB_TOKEN`, or the provider's git auth; can fall back\n to `gh auth token`). See §5.\n- **Coding-agent CLI choice** (`codex`, `claude`…) and that the user has an account — it gets\n authenticated into the VM in Phase 3.\n\n---\n\n## 3. Phase 2 — Base snapshot (the reusable image)\n\nBuild **once**, snapshot, and every workspace boots from it in seconds instead of rebuilding.\nProvisioning + building takes a while (often ~20–30 min), so it runs behind a checkpoint. The script\nshape is §7a; key points:\n\n- Build the **headless Electron main only** (not the renderer) so it fits in plan RAM.\n- Use the VM image's package manager (`apt`/`dnf`/`apk`, per the base distro — not the provider brand).\n- Clone with the git token via `GIT_ASKPASS` (§5).\n- **Trap errors and remove the half-built sandbox** so a crash doesn't leave a paid resource running.\n- Snapshot the stopped sandbox, parse the snapshot id, and write it + scope/project/port/repo to state.\n\n---\n\n## 4. Phase 3 — Agent-auth snapshot (interactive)\n\nThe base snapshot has the agent CLI installed but **not logged in**, and per-workspace VMs are\nephemeral — so authenticate once and bake it into a second snapshot layer. Script shape is §7b:\n\n1. Boot a sandbox from the base `snapshotId` (from state).\n2. Run the agent's login **interactively** (`--interactive --tty`); the user completes the URL/code in\n their browser. On a **headless VM this must be the device-auth flow** (e.g. `codex login --device-auth`),\n **not** plain `codex login`: the default OAuth login starts a loopback callback server on a container\n port the host browser can't reach, so it hangs. Device-auth instead prints a URL + code the user opens\n on the **host**.\n3. Verify login; **refuse to snapshot an unauthenticated VM.** Prefer the status command's **exit code**\n (most agent CLIs exit non-zero when unauthenticated). If you grep instead, agent status often goes to\n **stderr** (e.g. `codex login status` prints \"Logged in using ChatGPT\" there), so **fold stderr first**\n (`... 2>&1 | grep …`) and match the agent's **exact success line** — never `grep -qi 'logged in'`, which\n also matches \"**not** logged in\" and would commit an unauthenticated image.\n4. Re-snapshot, parse the new id, and overwrite `snapshotId` in state to the authenticated image\n (recording `authSourceSnapshotId`). Remove the auth sandbox.\n\n**You can't drive step 2 yourself** (you run commands non-interactively — no TTY). The **user** runs it in\ntheir own terminal, or via the Claude Code harness bang-prefix (`! `, with the required space after\n`!`). You scaffold/boot the sandbox and run steps 3–4, but **you cannot observe the interactive login\nfinishing** — so **ask the user to tell you when it's done** before you verify and re-snapshot.\n\nIf the agent's credentials are short-lived, warn that the snapshot may need periodic re-auth (§10).\n\nFor disposable runtimes, do **not** treat a host agent config directory (for example `~/.codex`) as the\nauth snapshot by bind-mounting or copying it wholesale. Agent homes often contain sqlite state, hook\napproval state, caches, logs, and host-specific env/config. Instead, authenticate/configure the agent\ninside the disposable runtime and snapshot/commit that runtime layer.\n\n---\n\n## 5. Credentials\n\n- **Never** commit secrets or put them in `userData`, recipe JSON, comments, docs, or the state file.\n- **Git token:** read from env (`GH_TOKEN`/`GITHUB_TOKEN`), falling back to `gh auth token`. Pass to the\n VM only via the provider's ephemeral `--env`. Inside the VM, use a `GIT_ASKPASS` helper with\n `x-access-token` (not the token in the clone URL) and `GIT_TERMINAL_PROMPT=0` so a missing token fails\n fast instead of hanging. When you write the helper from inside `bash -lc` under `set -u`, escape the\n positional arg and the token (`\\$1`, `\\$GH_TOKEN`) so they land **literally** and resolve at git-runtime\n — an unescaped `$1` aborts with \"unbound variable\", and a literal `$GH_TOKEN` keeps the real token out of\n the written file. `rm -f` the helper after the clone/fetch.\n- **Provider auth:** rely on the provider CLI's logged-in session, not checked-in keys.\n- **Agent auth:** lives in the authenticated snapshot (Phase 3) — never a file you write or commit.\n- State holds only **non-secret** wiring (snapshot ids, scope, project, port, repo url/ref).\n\n---\n\n## 6. State file\n\nA repo-local JSON file (e.g. `scripts/orca-vm/-state.json`) threads non-secret values between\nphases. Each script resolves values as **env var → state → built-in fallback**, and merges its outputs\nback. Phase 2 writes the base `snapshotId`; Phase 3 overwrites it with the authenticated snapshot;\nper-workspace `create` boots from `snapshotId`.\n\n```json\n{\n \"baseName\": \"orca-base\",\n \"snapshotId\": \"snap_authenticated_image_id\",\n \"authSourceSnapshotId\": \"snap_base_image_id\",\n \"scope\": \"\",\n \"project\": \"\",\n \"port\": 7331,\n \"repoUrl\": \"https://host/org/repo.git\",\n \"repoRef\": \"main\",\n \"projectRoot\": \"/abs/path/on/remote/repo\"\n}\n```\n\n---\n\n## 7. Script templates (provider-agnostic shapes)\n\nScaffold under `scripts/orca-vm/`. These are **shapes** — fill in the provider's real commands. All\nreserve stdout for the final JSON and log progress to stderr. Include a shared `json_value ` /\n`env_value ` reader (env → state → fallback) in each.\n\n**Where each script runs:**\n\n- **Local-side** (`create`/`suspend`/`resume`/`destroy` + the base-snapshot/auth scripts the user\n invokes) runs **on the user's desktop**, so it must run on their OS. macOS/Linux: `#!/usr/bin/env\n bash`, `set -euo pipefail`, quoted paths. **Windows:** a bare `.sh` won't run — scaffold `.ps1`/`.cmd`\n or require WSL/Git-Bash and point `orca.yaml` at the right launcher.\n- **Remote-side** (commands you `exec` *inside* the Linux VM) always runs in the VM's Linux shell, so\n bash is fine there regardless of the user's OS.\n\n### 7a. Base-snapshot (`-base-snapshot.sh`) — Phase 2\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve base_name/repo_url/repo_ref/project_root/port/scope/project/timeout (env→state→fallback)\n# resolve gh token: GH_TOKEN | GITHUB_TOKEN | `gh auth token`\n# 1. provision a sandbox (timeout/vcpus/published port/snapshot retention); trap: remove on error\n# 2. remote exec (long timeout): install pkgs + gh + corepack/pnpm + agent CLI;\n# clone with GIT_ASKPASS(token); write headless main-only build config;\n# dev setup; pnpm install; build CLI; build headless electron main; smoke-check tools\n# 3. snapshot stopped sandbox; parse snapshot id (fail if unparseable)\n# 4. merge { baseName, snapshotId, projectRoot, repoUrl, repoRef, port, scope, project } into state\n# print only the state JSON to stdout\n```\n\nWorked Vercel commands for this phase are in §7f. You run this script by hand (not via `orca.yaml`),\nafter exporting the first-run inputs the state file doesn't have yet — e.g. provider scope/project, the\nrepo URL/ref, and a git token (`GH_TOKEN`); later runs read them back from state.\n\n### 7b. Auth (`-base-auth.sh`) — Phase 3\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# read source snapshot from state.snapshotId (fail if absent); auth_name=\"${base_name}-auth\"\n# 1. boot sandbox from source snapshot; trap: remove on error\n# 2. INTERACTIVE/TTY remote exec: agent login — user completes URL/code. Headless VM: MUST use the\n# device-auth flow (e.g. `codex login --device-auth`) — plain OAuth login binds a loopback callback\n# port the host can't reach and hangs. User runs this themselves (you have no interactive TTY); ask\n# them to report back when it's done before continuing.\n# 3. verify login, then refuse to snapshot if not logged in. Prefer the status command's EXIT CODE (most\n# agent CLIs exit non-zero when unauthenticated) over string-matching. If you must grep, fold stderr\n# first (`status 2>&1 | grep …` — many agents print the success line there) and match the agent's exact\n# success line; never `grep -qi 'logged in'`, which also matches \"not logged in\". Codex example: §7f.\n# 4. snapshot; parse new id\n# 5. merge { snapshotId:, authSourceSnapshotId: } into state; remove auth sandbox\n# print only the state JSON to stdout\n```\n\n### 7c. Create (`-create.sh`) — per workspace\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# read authenticated snapshotId/scope/project/port/repo*/project_root (env→state→fallback)\n# fail clearly if snapshotId is missing (point back to Phases 2–3)\n# name = orca-${ORCA_VM_RECIPE_ID}-${ORCA_VM_INSTANCE_ID} (sanitized, length-capped)\n# 1. boot sandbox from snapshotId with a published port; capture the public URL → pairing address\n# (an externally reachable wss:// URL); trap: remove sandbox on error\n# 2. remote exec: ensure repo at desired commit; rebuild only if commit changed (cache marker)\n# 3. remote exec: start orca serve in the background and read the recipe JSON it writes (see below)\n# 4. print serve's JSON to stdout, optionally enriched with userData:\n# { schemaVersion:1, pairingCode, projectRoot, userData:{ provider, resourceId:name, snapshotId } }\n```\n\n**The exact `orca serve` invocation and its output (verified — do not improvise the flags).** Inside the\nVM, run:\n\n```bash\norca serve \\\n --port \"$PORT\" \\\n --project-root \"$ABS_REPO_PATH_ON_REMOTE\" \\\n --pairing-address \"$EXTERNAL_WSS_URL\" \\\n --recipe-json\n```\n\n**Binary name:** in a VM built from source (the Phase-2 flow), run it as `pnpm exec orca-dev serve …`\nfrom the repo root — `orca-dev` is the in-repo entrypoint and is what the §7f example uses. Plain\n`orca serve …` is the same command when the built CLI is installed on the VM's PATH. The flags/output\nare identical either way.\n\nThere is **no `--host` flag**. `--project-root` must be an absolute directory on the remote. With\n`--recipe-json` the server **stays running** and prints exactly this single object to **stdout**, then\nkeeps serving:\n\n```json\n{ \"schemaVersion\": 1, \"pairingCode\": \"\", \"projectRoot\": \"\" }\n```\n\n`pairingCode` is the pairing URL, already pointing at whatever you passed as `--pairing-address` — so set\n`--pairing-address` to the externally reachable address and **pass `pairingCode` through unchanged; never\nhand-rewrite it**. Because serve runs in the foreground and doesn't exit, redirect its stdout to a file\nand poll until that file parses as JSON (and bail if the process dies — dump its stderr log). Your\n`create` script then prints that JSON (optionally merging `userData`). Concrete pattern: §7f.\n\n### 7d. Suspend / resume / destroy — per workspace\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\npayload=\"$(cat)\" # Orca passes lifecycle JSON on stdin\nresource_id=\"$(node -e 'const d=JSON.parse(process.argv[1]); process.stdout.write(d.recipeResult?.userData?.resourceId ?? \"\")' \"$payload\")\"\n[ -n \"$resource_id\" ] || { echo \"No resource id in lifecycle payload\" >&2; exit 1; }\n# suspend: provider suspend \"$resource_id\"\n# resume: provider resume \"$resource_id\"; then RE-EMIT fresh recipe JSON (pairing may change)\n# destroy: provider remove \"$resource_id\" (or set destroy: none in orca.yaml)\n```\n\n### 7e. State file — scaffold with scope/project/repo filled in and snapshot ids empty (§6).\n\n### 7f. Worked example — Vercel Sandbox (all three phases)\n\nA real, working shape (the Vercel surface is a CLI: `vercel sandbox create|exec|snapshot|remove`). Adapt\nnames; verify flags against `vercel sandbox --help` for the user's CLI version before relying on them.\nThese ground §7a (base snapshot) and §7b (auth), which are otherwise generic skeletons.\n\n**Phase 2 — base snapshot (§7a):** provision → install tools + clone + headless build → snapshot.\n\n```bash\n# provision a fresh build sandbox (retain a couple of snapshots); trap-remove on error\nvercel sandbox create --name \"$base\" --runtime node24 --timeout 30m --vcpus 4 --publish-port \"$port\" \\\n --snapshot-expiration 30d --keep-last-snapshots 2 \"${vercel_args[@]}\" >&2\n# remote build (long timeout): install pkgs+gh+pnpm+agent CLI, clone with GIT_ASKPASS (write the helper\n# with LITERAL \\$1/\\$GH_TOKEN so they resolve at git-runtime, not write-time — see §5/§7f create — then\n# `rm -f /tmp/askpass.sh`), write the headless main-only build config (drop the renderer), dev setup,\n# build CLI + headless main, smoke-check\nvercel sandbox exec \"$base\" \"${vercel_args[@]}\" --timeout 25m --env \"GH_TOKEN=$gh_token\" … -- bash -lc '…build…' >&2\n# snapshot the STOPPED sandbox and parse the id from CLI output (fail if unparseable)\nout=\"$(vercel sandbox snapshot \"$base\" --stop --expiration 30d \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$out\" >&2\nsnapshot_id=\"$(printf '%s\\n' \"$out\" | sed -nE 's/.*(snap_[A-Za-z0-9]+).*/\\1/p' | tail -1)\"\n# merge { baseName, snapshotId, scope, project, port, repoUrl, repoRef, projectRoot } into state; print state JSON\n```\n\n**Phase 3 — agent-auth snapshot (§7b):** boot the base, log the agent in interactively, re-snapshot.\n(`codex` below is an example — substitute the user's chosen agent's login/status verbs, e.g. `claude`.)\n\n```bash\nvercel sandbox create --name \"$auth\" --snapshot \"$snapshot_id\" --timeout 30m --publish-port \"$port\" \"${vercel_args[@]}\" >&2\n# INTERACTIVE — the USER runs this in their own terminal (you have no interactive TTY) and completes the\n# URL/code on the HOST. --device-auth is MANDATORY on a headless VM: plain `codex login` binds a loopback\n# callback port the host browser can't reach and hangs. Ask the user to report back when login finishes.\nvercel sandbox exec --interactive --tty \"$auth\" \"${vercel_args[@]}\" -- bash -lc 'codex login --device-auth'\n# refuse to snapshot an unauthenticated VM — fold stderr, match codex's exact success line (§4)\nvercel sandbox exec \"$auth\" \"${vercel_args[@]}\" --timeout 30s -- bash -lc 'codex login status 2>&1' | grep -Eqi 'Logged in using ChatGPT|Logged in via device' \\\n || { echo \"agent not logged in; not snapshotting\" >&2; exit 1; }\nout=\"$(vercel sandbox snapshot \"$auth\" --stop --expiration 30d \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$out\" >&2\nnew_id=\"$(printf '%s\\n' \"$out\" | sed -nE 's/.*(snap_[A-Za-z0-9]+).*/\\1/p' | tail -1)\"\n# overwrite state.snapshotId = new_id, record authSourceSnapshotId = snapshot_id; remove the auth sandbox\n```\n\n**Per-workspace `create`** (the fast path):\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve from env→state→fallback: snapshot_id, scope, project, port, repo_url, repo_ref, project_root\nvercel_args=(); [ -n \"$scope\" ] && vercel_args+=(--scope \"$scope\"); [ -n \"$project\" ] && vercel_args+=(--project \"$project\")\n[ -n \"$snapshot_id\" ] || { echo \"snapshotId missing — run Phases 2–3 first\" >&2; exit 1; }\ngh_token=\"${GH_TOKEN:-${GITHUB_TOKEN:-$(command -v gh >/dev/null 2>&1 && gh auth token 2>/dev/null || true)}}\"\nname=\"orca-${ORCA_VM_RECIPE_ID:-vercel-sandbox}-${ORCA_VM_INSTANCE_ID:-$(date +%s)}\" # sanitize+cap to 63 chars\n\n# Arm cleanup BEFORE create so a failing create can't leak a half-built paid sandbox.\ncleanup_on_error() { [ \"$?\" -ne 0 ] && vercel sandbox remove \"$name\" \"${vercel_args[@]}\" >/dev/null 2>&1 || true; }\ntrap cleanup_on_error EXIT\n\n# 1. boot from the authenticated snapshot, publish the serve port\ncreate_output=\"$(vercel sandbox create --name \"$name\" --snapshot \"$snapshot_id\" \\\n --timeout 30m --publish-port \"$port\" \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$create_output\" >&2\n# Vercel prints the published https URL; derive the external wss:// pairing address from it\npublic_url=\"$(printf '%s\\n' \"$create_output\" | sed -nE 's#.*(https://[^[:space:]]+\\.vercel\\.run).*#\\1#p' | head -1)\"\n[ -n \"$public_url\" ] || { echo \"no published URL in create output\" >&2; exit 1; }\npairing_ws=\"${public_url/https:\\/\\//wss://}\"\n\n# 2. (remote) ensure the repo is at the right commit; rebuild only if the commit changed (cache marker)\nvercel sandbox exec \"$name\" \"${vercel_args[@]}\" --timeout 20m \\\n --env \"GH_TOKEN=$gh_token\" --env \"ORCA_PROJECT_ROOT=$project_root\" \\\n --env \"ORCA_REPO_URL=$repo_url\" --env \"ORCA_REPO_REF=$repo_ref\" \\\n -- bash -lc 'set -euo pipefail; cd \"$ORCA_PROJECT_ROOT\"; \\\n # Re-establish git auth for the private-repo fetch (why + full rationale: §5); else it hangs on a prompt.\n # Load-bearing escaping: \\$1 and \\$GH_TOKEN must land LITERALLY and resolve at git-runtime. Test after\n # any edit here — reformatting the nested printf/node quoting silently breaks the fetch or leaks the token.\n if [ -n \"${GH_TOKEN:-}\" ]; then \\\n printf \"%s\\n\" \"#!/usr/bin/env bash\" \"case \\\"\\$1\\\" in *Username*) echo x-access-token;; *Password*) echo \\\"\\$GH_TOKEN\\\";; esac\" > /tmp/askpass.sh; \\\n chmod 700 /tmp/askpass.sh; export GIT_ASKPASS=/tmp/askpass.sh GIT_TERMINAL_PROMPT=0; fi; \\\n git fetch origin \"$ORCA_REPO_REF\"; \\\n git checkout -B \"$ORCA_REPO_REF\" FETCH_HEAD; \\\n rm -f /tmp/askpass.sh; \\\n c=\"$(git rev-parse HEAD)\"; [ -f .orca-built ] && [ \"$(cat .orca-built)\" = \"$c\" ] || { \\\n pnpm install --prefer-offline && pnpm run build:cli && \\\n node config/scripts/run-electron-vite-build.mjs --config config/electron-vite.vm-serve.config.ts && \\\n printf \"%s\" \"$c\" > .orca-built; }' >&2\n\n# 3. (remote) start orca serve in the background, writing recipe JSON to a file; poll until it parses\nrecipe_json=\"$(vercel sandbox exec \"$name\" \"${vercel_args[@]}\" --timeout 60s \\\n --env \"ORCA_PORT=$port\" --env \"ORCA_PROJECT_ROOT=$project_root\" --env \"ORCA_PAIRING_ADDRESS=$pairing_ws\" \\\n -- bash -lc 'set -euo pipefail; cd \"$ORCA_PROJECT_ROOT\"; rm -f /tmp/orca-recipe.json /tmp/orca-serve.log; \\\n nohup pnpm exec orca-dev serve --port \"$ORCA_PORT\" --project-root \"$ORCA_PROJECT_ROOT\" \\\n --pairing-address \"$ORCA_PAIRING_ADDRESS\" --recipe-json >/tmp/orca-recipe.json 2>/tmp/orca-serve.log /dev/null 2>&1 && { cat /tmp/orca-recipe.json; exit 0; }; \\\n kill -0 \"$pid\" 2>/dev/null || { cat /tmp/orca-serve.log >&2; exit 1; }; sleep 0.25; \\\n done; cat /tmp/orca-serve.log >&2; echo \"serve recipe JSON timed out\" >&2; exit 1')\"\n\n# 4. print serve's JSON enriched with userData (single object on stdout)\nnode -e 'const p=JSON.parse(process.argv[1]); console.log(JSON.stringify({...p, schemaVersion:1,\n userData:{...p.userData, provider:\"vercel-sandbox\", resourceId:process.argv[2], snapshotId:process.argv[3]}}))' \\\n \"$recipe_json\" \"$name\" \"$snapshot_id\"\ntrap - EXIT\n```\n\n`suspend`/`resume`/`destroy` use `vercel sandbox stop|...|remove \"$resource_id\"` reading\n`userData.resourceId` from stdin (§7d). This is the **Orca-server** connection mode (the recipe emits a\npairing URL). If the user chose **SSH** in the §1 interview, use §7g instead.\n\n### 7g. Worked example — existing SSH host (SSH connection mode)\n\nSSH mode is **fundamentally different from §7c/§7f**, not a relabeling of them:\n\n- **`create` does NOT run `orca serve` and does NOT emit a `pairingCode`.** Orca itself connects to the\n host over its SSH relay, brings up the git + filesystem providers, and imports the repo. The script's\n only job is to make the host ready and **print SSH connection details** Orca will dial.\n- The result uses a `connection` block with `type: \"ssh\"` and a `target`, **not** the flat\n `pairingCode`/`projectRoot` shape. Exact shape (Orca rejects anything else):\n\n```json\n{\n \"schemaVersion\": 1,\n \"connection\": {\n \"type\": \"ssh\",\n \"projectRoot\": \"/abs/path/to/repo/on/host\",\n \"target\": {\n \"label\": \"my-box\",\n \"host\": \"192.0.2.10\",\n \"port\": 22,\n \"username\": \"ubuntu\",\n \"identityFile\": \"~/.ssh/id_ed25519\",\n \"jumpHost\": \"bastion.example.com\",\n \"proxyCommand\": \"cloudflared access ssh --hostname %h\",\n \"relayGracePeriodSeconds\": 0,\n \"portForwards\": []\n }\n }\n}\n```\n\n`label`, `host`, `port`, `username` are required; the rest are optional — omit any you don't need.\n\n**Networking → which `target` fields to set** (how *your desktop* reaches the box — there is no\n`orca serve` URL in SSH mode):\n\n- Public IP / DNS, or a Tailscale/VPN address → `host`; SSH port → `port` (usually 22).\n- Key auth → `identityFile` (add `identitiesOnly: true` if the agent has many keys).\n- Through a bastion → `jumpHost` (a `user@host` ProxyJump) **or** a full `proxyCommand` (e.g. an access\n proxy). Use one, not both.\n- A service port the workspace needs → add entries to `portForwards`.\n- `relayGracePeriodSeconds` (optional): how long Orca keeps the SSH relay alive after the workspace\n detaches before tearing it down; `0` = tear down immediately. Leave it off unless the user wants a\n reconnect grace window.\n\n**Toolchain & agent auth on a persistent (no-snapshot) host — do this ONCE, by hand, before wiring the\nrecipe** (there's no base image to bake; the host *is* the base). Run the §7f Phase-2 install steps and\nthe §7f Phase-3 ` login --device-auth` **directly over SSH on the host** (interactive, e.g.\n`ssh -t user@host ' login --device-auth'`). After that the host stays ready across workspaces.\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve from env→state→fallback (default unset optionals to \"\"): ssh_username, host,\n# ssh_port (default 22), identity_file, jump_host, proxy_command, project_root, repo_url, repo_ref\n: \"${identity_file:=}\"; : \"${jump_host:=}\"; : \"${proxy_command:=}\" # avoid set -u aborts on optionals\ngh_token=\"${GH_TOKEN:-${GITHUB_TOKEN:-$(command -v gh >/dev/null 2>&1 && gh auth token 2>/dev/null || true)}}\"\nssh_target=\"${ssh_username}@${host}\"\nssh_opts=(-p \"$ssh_port\"); [ -n \"$identity_file\" ] && ssh_opts+=(-i \"$identity_file\")\n# Why: a fresh host's key isn't in known_hosts; a StrictHostKeyChecking prompt would HANG a\n# non-interactive create. Pre-add the key (or set the option) so it can't block.\nssh-keyscan -p \"$ssh_port\" \"$host\" >> \"$HOME/.ssh/known_hosts\" 2>/dev/null || true\n\n# 1. ensure the repo is present and at the right commit on the host (NO orca serve here)\nssh \"${ssh_opts[@]}\" \"$ssh_target\" \\\n \"GH_TOKEN='$gh_token' GIT_TERMINAL_PROMPT=0 bash -lc '\n set -euo pipefail\n [ -d \\\"$project_root/.git\\\" ] || git clone \\\"$repo_url\\\" \\\"$project_root\\\"\n cd \\\"$project_root\\\" && git fetch origin \\\"$repo_ref\\\" && git checkout -B \\\"$repo_ref\\\" FETCH_HEAD\n '\" >&2\n\n# 2. print the SSH connection block (NO pairingCode, NO orca serve). host/port/username tell Orca's\n# relay how to dial in; identityFile/jumpHost/proxyCommand/portForwards are emitted when set.\nnode -e 'const [host,port,user,idf,jh,pc,root]=process.argv.slice(1);\n const target={ label:\"per-workspace-host\", host, port:Number(port), username:user };\n if(idf) target.identityFile=idf; if(jh) target.jumpHost=jh; if(pc) target.proxyCommand=pc;\n // add target.portForwards=[...] here if the workspace needs forwarded service ports\n console.log(JSON.stringify({ schemaVersion:1, connection:{ type:\"ssh\", projectRoot:root, target } }))' \\\n \"$host\" \"$ssh_port\" \"$ssh_username\" \"$identity_file\" \"$jump_host\" \"$proxy_command\" \"$project_root\"\n```\n\n`suspend`/`resume`/`destroy`: on a persistent host there's usually nothing to tear down — set\n`destroy: none` and omit suspend/resume. (Orca still disconnects/reconnects its own SSH relay on\nsleep/wake/delete — that's separate from these scripts.)\n\nIf the SSH host is instead an **ephemeral/snapshot-capable VM** (your hypervisor, or a cloud VM with\nimage support), keep the §7f Phase-2/3 base-image model for provisioning, but still emit the\n`connection.type:\"ssh\"` block above instead of starting `orca serve`.\n\n### 7h. Worked example — local Docker SSH (SSH connection mode)\n\nLocal Docker can model an ephemeral SSH VM without cloud cost: build a base image with `sshd`, tools,\nrepo prerequisites, and the agent CLI; run an **interactive auth container** once; then `docker commit`\nthat container as the authenticated image used by per-workspace `create`.\n\nKey points:\n\n- Publish container SSH to a random localhost port (`-p 127.0.0.1::22`) and emit\n `connection.type:\"ssh\"` with `host:\"127.0.0.1\"`, that port, `username`, `identityFile`, and\n `identitiesOnly:true`.\n- Generate a repo-local SSH key if needed, but gitignore the private/public key files.\n- **Bake SSH host keys into the base image** (`ssh-keygen -A` at **build** time; at runtime only generate\n if absent). Ephemeral containers all present the **same** host key, so `known_hosts` on `127.0.0.1`\n doesn't churn as the published port rotates across workspaces (otherwise every container's freshly\n generated key collides on `localhost` and trips host-key-changed warnings).\n- The auth image is the Docker equivalent of Phase 3: the **user** runs the agent login **inside** the\n container (you can't drive it — you have no interactive TTY), configures proxy env/config, approves\n hooks, and you commit once they report it's done. On a headless container use the **device-auth** flow\n (§4). Verify login before committing — exit code, or fold stderr and match the exact success line (§4).\n- Do not bind-mount or copy the host's full agent home into the image. Let each container have writable\n agent state; only the committed auth image should carry reusable authenticated state.\n- If committing from an interactive shell, force the runtime entrypoint back to `sshd`:\n `docker commit --change='ENTRYPOINT [\"/usr/local/bin/orca-docker-ssh-entrypoint\"]' …`.\n- `destroy` should read `recipeResult.userData.resourceId` and run `docker rm -f \"$resource_id\"`.\n\nValidation before wiring/live use:\n\n```bash\ndocker image inspect \"$auth_image\" --format '{{json .Config.Entrypoint}}'\ndocker run -d --name \"$name\" -p 127.0.0.1::22 -e \"ORCA_SSH_PUBLIC_KEY=$pubkey\" \"$auth_image\"\ndocker ps -a --filter \"name=$name\"\ndocker logs \"$name\"\nssh -i \"$key\" -p \"$port\" -o IdentitiesOnly=yes user@127.0.0.1 'codex --version'\n```\n\nIf the container exits immediately, inspect logs before the cleanup trap removes it; a committed\ninteractive image with `ENTRYPOINT [\"bash\"]` is a common cause.\n\nAlso confirm the **host key is stable** across containers: the SSH `ssh -i … 127.0.0.1` dial should not\ntrigger a host-key-changed warning when a second container reuses the port. If it does, the host keys\nweren't baked into the base image (see the `ssh-keygen -A` point above).\n\n### 7i. Windows local-side scripts\n\nThe local-side scripts run on the user's desktop. On **Windows**, a bare `.sh` won't execute. Either\nrequire WSL/Git-Bash (and point `orca.yaml` at e.g. `bash ./scripts/orca-vm/.sh` via a `.cmd`\nlauncher), or scaffold PowerShell equivalents. Minimal PowerShell shape:\n\n```powershell\n#requires -Version 5\n$ErrorActionPreference = 'Stop'\n# resolve env→state→fallback; run the provider CLI / ssh the same way;\n# capture provider output; build the result object for the chosen mode and write ONE line of JSON to stdout.\n# Orca-server mode: @{ schemaVersion=1; pairingCode=$pairingCode; projectRoot=$projectRoot; userData=@{...} }\n# SSH mode: @{ schemaVersion=1; connection=@{ type=\"ssh\"; projectRoot=$projectRoot;\n# target=@{ label=$label; host=$host; port=$port; username=$user } } } (see §7g/§7h)\n($result | ConvertTo-Json -Compress -Depth 6)\n# progress/errors → Write-Error / the error stream, never stdout.\n```\n\nThe remote-side commands you run *inside* the Linux VM stay bash regardless of the desktop OS.\n\n---\n\n## 8. Per-workspace recipe contract (the fast path)\n\nOnce the authenticated snapshot exists, this runs on every workspace create. Define recipes in\n`orca.yaml`:\n\n```yaml\nenvironmentRecipes:\n - id: cloud-sandbox\n name: Cloud Sandbox\n create: ./scripts/orca-vm/cloud-sandbox-create.sh\n suspend: ./scripts/orca-vm/cloud-sandbox-suspend.sh\n resume: ./scripts/orca-vm/cloud-sandbox-resume.sh\n destroy: ./scripts/orca-vm/cloud-sandbox-destroy.sh\n```\n\n`create` runs **locally from the repo root** and prints **one** JSON object to stdout. Its shape depends\non the connection mode chosen in §1:\n\n**Orca-server mode** — boot the env, start `orca serve` in it, and print serve's result:\n\n```json\n{\n \"schemaVersion\": 1,\n \"pairingCode\": \"orca-pairing-code-or-url\",\n \"projectRoot\": \"/absolute/path/to/repo/on/remote\",\n \"userData\": { \"provider\": \"example\", \"resourceId\": \"provider-resource-id\" }\n}\n```\n\nHere `pairingCode` (from `orca serve --recipe-json`) and `projectRoot` are required; `schemaVersion` (`1`)\nand `userData` are optional.\n\n**SSH mode** — do **not** run `orca serve`; print the `connection.type:\"ssh\"` block instead (full shape +\nworked script in §7g). `pairingCode` is **not** used in SSH mode.\n\nLifecycle hooks (all run locally):\n\n- `create`: required. Prints recipe result JSON.\n- `suspend`: optional. Sleep; reads lifecycle payload on stdin.\n- `resume`: optional. Wake; reads payload on stdin and **prints fresh recipe JSON** (pairing may change).\n- `destroy`: optional unless `destroy: none`. Delete/cleanup; reads payload on stdin.\n\nStart Orca remotely with `orca serve --port \"$PORT\" --project-root \"$ABS_ROOT\" --pairing-address\n\"$EXTERNAL_WSS_URL\" --recipe-json` (exact flags + output in §7c). Set `--pairing-address` to the\nexternally reachable address so the emitted `pairingCode` is reachable; tunneling/port mapping is the\nscript's job.\n\nBackward compatibility: `command`→`create`, `cleanup`→`destroy`, `cleanup: none`→`destroy: none`.\nPrefer the lifecycle names.\n\n---\n\n## 9. Doctor and validation\n\nValidate in two stages — the cheap dry run first, then the live self-test.\n\n### Dry run (free, non-destructive) — always do this first\n\n`orca vm recipe doctor --repo-path --json` validates **static wiring only** — it does\n**not** boot anything. It checks: local-host execution (v1), repo path, recipe id exists,\ncreate/destroy/suspend/resume command paths resolve, suspend/resume are paired, and each script is\nexecutable (POSIX exec bit; skipped on Windows). Fix every failure here before spending any cloud money.\n\n### Live self-test (`--provision`) — diagnose and iterate yourself\n\n`orca vm recipe doctor --repo-path --provision --json` actually runs the recipe end\nto end: it executes `create`, validates the returned recipe JSON, then runs `destroy` to **tear the\nenvironment back down** (so the test leaves nothing running, as long as `destroy` works). It spends real\ncloud money, so get the user's OK **once** before starting — that one approval covers the whole loop\nbelow; do not re-ask before each run.\n\nOn failure, the JSON result includes a `provisionTranscript` with the **complete** captured output of\neach stage so you can self-diagnose without asking the user to relay logs:\n\n```json\n{\n \"ok\": false,\n \"checks\": [ { \"id\": \"recipe.provision\", \"status\": \"fail\", \"message\": \"…\" } ],\n \"provisionTranscript\": {\n \"provision\": { \"exitCode\": 0, \"signal\": null, \"stdout\": \"…\", \"stderr\": \"…\", \"parseError\": \"…\" },\n \"destroy\": { \"exitCode\": 0, \"signal\": null, \"stdout\": \"…\", \"stderr\": \"…\" }\n }\n}\n```\n\n**Run it as a loop:** read `provisionTranscript.provision.stderr` / `.stdout` / `.parseError` (and\n`destroy.*`), fix the script, and re-run `--provision` until `ok` is `true` — iterating on your own\nrather than waiting for the user to paste errors. Common reads: a non-empty `stderr` with `exitCode 0`\nplus a `parseError` means `create` ran but printed something other than the single recipe-result JSON on\nstdout (often a stray `echo` — route it to stderr, see §10); a non-zero `exitCode` is a provider/script\nfailure described in `stderr`. Each stream is redacted and capped (head+tail) — large logs keep both the\nsetup context and the failure.\n\nThe self-test cannot see provider-side truth beyond what the scripts print, so still confirm: state has a\npopulated **authenticated** `snapshotId` (Phases 2–3 done), and `destroy` is implemented/tested (or\nexplicitly `none` — in which case the self-test won't tear down, so clean up manually).\n\nFor SSH recipes, also smoke-test the exact emitted target before declaring success: dial the host/port\nwith the identity/proxy settings, run `pwd`, verify the repo path, check the agent binary, and confirm\n`destroy` removes the provider resource/container. For Docker, inspect the auth image entrypoint and do a\nstartup-only `docker run` before the full clone/install path.\n\n---\n\n## 10. Failure modes\n\n- **Build exceeds plan timeout (e.g. Hobby 45m).** Use enough vCPUs and a timeout covering the build;\n else split work or use a higher plan. The cap also limits per-workspace runtime — surface it.\n- **Build exceeds plan RAM.** Build the **headless main only** (drop the renderer) — the biggest fitter.\n- **Private-repo clone hangs/fails.** Wrong/missing token. Use `GIT_ASKPASS` + `GIT_TERMINAL_PROMPT=0`\n so it fails fast instead of prompting.\n- **`GIT_ASKPASS` helper aborts the clone with \"`$1: unbound variable`\".** The `printf`/heredoc that writes\n the helper inside `bash -lc` under `set -u` expanded `$1`/`$GH_TOKEN` at **write** time. Escape them\n (`\\$1`, `\\$GH_TOKEN`) so they land literally and resolve at git-runtime; this also keeps the real token\n out of the file. `rm -f` the helper afterward (§5, §7f).\n- **Agent verified as \"not logged in\" despite a good login.** `codex login status` (and similar) print\n \"Logged in …\" to **stderr**; an stdout-only `grep` misses it. Prefer the status **exit code**; if you\n grep, fold stderr first (`status 2>&1 | grep …`) and match the exact success line — not `grep -qi\n 'logged in'`, which also matches \"not logged in\".\n- **Headless agent login hangs.** Plain OAuth `login` starts a loopback callback server on a VM/container\n port the host browser can't reach. Use the **device-auth** flow (`login --device-auth`) — it prints a\n URL + code the user opens on the host.\n- **`known_hosts` host-key churn on local Docker.** Each ephemeral container regenerating its SSH host key\n collides on `127.0.0.1` as the published port rotates. Bake host keys into the base image at build time\n (`ssh-keygen -A`; runtime generates only if absent) so all containers share one stable key (§7h).\n- **Snapshot expired/evicted.** If `create` hits an unknown snapshot id, rerun Phases 2–3 and update\n `snapshotId`.\n- **Agent auth didn't persist.** Confirm `snapshotId` points at the **authenticated** snapshot; re-run\n Phase 3. Warn that short-lived tokens may need periodic re-auth.\n- **Agent auth copied from the host breaks.** Do not bind-mount/copy a full host agent home; sqlite\n files can be unwritable or host-specific, hooks may need approval again, and config may reference\n local-only env vars. Authenticate inside the runtime and snapshot/commit that layer.\n- **Docker auth image exits immediately.** Inspect `docker image inspect … .Config.Entrypoint` and\n `docker logs`. If the image was committed from an interactive shell, reset the entrypoint to the SSH\n entrypoint during `docker commit`.\n- **Leaked paid resource.** Every long script must trap errors and remove the sandbox it created.\n- **`create` emits non-JSON on stdout.** A stray `echo` corrupts the result — stdout is for the final\n JSON only; everything else to stderr. The `--provision` self-test surfaces this as `exitCode 0` + a\n `parseError` with the offending stdout in `provisionTranscript` (§9).\n\n---\n\n## 11. Boundaries\n\n- Don't create accounts, choose plans/regions, or invent scope/project/org/image/billing ids.\n- Don't invent or store credentials; no secrets in `userData`, state, comments, docs, or commits.\n- Don't run paid/long phases (base snapshot, auth, live test) without an explicit OK.\n- Don't hide provider errors behind generic messages — preserve actionable stderr.\n- Don't make Orca own provider lifecycle beyond invoking the configured scripts.\n- Don't commit or create an Orca workspace unless asked.\n" // oxfmt-ignore -const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Use Orca orchestration for structured multi-agent coordination: threaded\n messages, blocking ask/reply flows, task dispatch, worker_done/escalation\n waits, task DAGs, decision gates, coordinator loops, or decomposing work\n across agents. Use `orca-cli` instead for full ownership handoffs, including\n requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", or \"another worktree\" when the user did not explicitly ask to\n supervise, monitor, wait for results, or coordinate a DAG. Use `orca-cli` for\n ordinary terminal control, lightweight terminal prompts, shell commands, Orca\n worktree management, reading or waiting on terminals, and automation of the\n browser embedded inside Orca. Use Computer Use for browser windows, webviews,\n Orca app UI, or desktop UI outside Orca's embedded browser.\n---\n\n# Orca Inter-Agent Orchestration\n\nOrchestration is Orca's structured coordination layer for agent messages, task ownership, dispatch state, and worker completion tracking.\n\nUse this skill when coordination state matters. For lightweight terminal prompts or basic worktree/terminal/built-in-browser control, use `orca-cli`.\n\n## Tool Boundary\n\nIf a task says to use Orca orchestration, the coordinator must create or bind a Run, create the Task with `orca orchestration task-create`, then attach the worker with either the preferred `orca orchestration worker-start` composition or the low-level `orca orchestration dispatch --inject` path.\n\nDo not substitute non-Orca subagent tools, generic agent-spawn APIs, or chat-only parallel worker features. Those may create useful workers, but they do not create Orca task/dispatch provenance, injected lifecycle preambles, `worker_done` authority, or decision gates.\n\nBefore claiming a worker was orchestrated, verify the task/dispatch exists:\n\n```bash\norca orchestration task-list --json\norca orchestration dispatch-show --task --json\n```\n\nIf the work was accidentally run outside Orca orchestration, say so plainly. To repair provenance, rerun or revalidate the needed work through a fresh Orca terminal plus injected dispatch; do not retroactively describe the external worker as orchestrated.\n\n## When To Use\n\n- Send/reply/ask between agent terminals with persistent messages.\n- Dispatch structured tasks to workers and wait for `worker_done` or `escalation`.\n- Track task DAGs with dependencies.\n- Run coordinator loops or decision gates.\n\nDo not use orchestration merely because the user says \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", or asks for another worktree/agent/model/effort. Those are full ownership transfers unless the user explicitly asks to supervise, monitor, wait for worker completion/results, coordinate a DAG, use decision gates, or keep a blocking ask/reply loop.\n\n## Preconditions\n\n- `orca status --json` should show a running runtime.\n- `orca` must be on PATH (`orca-ide` on Linux).\n- The orchestration experimental feature must be enabled in Settings > Experimental.\n- `orca orchestration` commands are RPC calls to the running Orca runtime.\n\n## Contract Migration\n\nOrca adopts a live pre-update orchestration assignment into an ordinary Run. Adoption preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch; it never restarts or replaces the worker. The retired scheduler is not revived, and a newly created attempt uses the current grammar.\n\nTreat the authority label on injected or formatted messages as definitive:\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported command printed with the message, using the same CLI executable and arguments that the original prompt supplied.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded, at-least-once cutover replay. Process it idempotently and acknowledge it only through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or lifecycle action.\n- An unlabeled current message uses the current guide and current grammar.\n\nAn explicitly selected current Run, attested current Run binding, current Dispatch, or federated attachment takes precedence over legacy fallback. A retained adoption record alone never turns a current command into a legacy call.\n\nDatabase provenance, an old-looking terminal, or a legacy Run ID does not prove mutation authority. If the runtime cannot prove liveness, principal ownership, capability, or the exact legacy contract, it degrades to read-only inspection and must not fall back to local execution. Exact recovery may restore the already-live PTY once in its original inactive background tab. It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal. Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.\n\nCompatibility retries have narrow guarantees. A pending ask, a reply, a final Dispatch settlement, and a consuming check have durable recovery identities. A-era heartbeat and escalation calls remain at-least-once across a manual A-to-B retry because identical later signals may be intentional. If an A-era ask may already have been answered, run the exact non-consuming recovery check printed by the runtime first; after its answer is printed and acknowledged, a new invocation with the same question creates a new question. Never guess among multiple identical question threads.\n\nWhen a compatibility or recovery command returns structured next-step arguments, run those exact arguments with the same CLI executable. The arguments intentionally omit the executable name so the guidance works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command. Do not translate the command from memory, broaden its recipient, or retry it as a current mutation unless the returned guidance explicitly says to.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The initial command durably commits the question, prints its exact `ask --resume ` command, and exits with launcher status `75`; it does not wait for the answer. Run that exact resume command after the launcher or update boundary. Resume is idempotent and read-oriented: it waits for the already-committed question and does not create another one. For a WSL process that received compatibility proof at launch, use the printed executable `orca-ide` WSL resume command so the same distro and packaged launcher authority are preserved; do not substitute a PATH-resolved local CLI. Older WSL processes that never received the hidden launch token remain lifecycle read-only after the update, even while their terminal and filesystem work continue.\n\nLegacy inspection remains available without consuming mail:\n\n```bash\norca orchestration run-list --json\n# run_legacy_local is an empty audit tombstone after adoption.\norca orchestration run-show --id run_legacy_local --json\n# In run-list, find the ordinary Run whose objective is:\n# \"Recovered orchestration work from a contract update\"\norca orchestration run-show --id --json\norca orchestration task-list --run --json\norca orchestration inbox --full --json\norca orchestration check --terminal --peek --format --json\norca terminal read --terminal --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\nIf the original coordinator is unavailable or cannot prove its retained authority, a current coordinator may explicitly take over the adopted Run from its own live agent terminal:\n\n```bash\norca orchestration run-use --id --takeover-legacy --json\norca orchestration check --run --json\n```\n\nTakeover fences only the old coordinator, binds the current one, and moves pending worker mail into current Run Delivery. It is bound to the authenticated invoking terminal; `--from` cannot name another coordinator. Live legacy workers keep their original Tasks, Dispatches, processes, filesystems, and old prompt commands; their later questions, escalations, and completion reports route to the current coordinator. Do not use takeover while the original coordinator is still actively coordinating, because its later lifecycle mutations are rejected.\n\nDo not launch a replacement editor merely because the desktop app or runtime was updated. If adoption cannot prove continuing authority, keep the original worker as the only editor until it reaches a stable handoff point, then use a new current Dispatch in a conflict-free placement for any remaining work.\n\n## Ownership\n\nNew orchestration messages and tasks belong to one explicitly bound Run. A Run is only a durable namespace and coordinator inbox; it never schedules or places workers. Lifecycle authority comes from the active Dispatch, and terminal handles remain routing metadata rather than durable identity. Send `worker_done` and `heartbeat` from the worker's own terminal; Orca routes them to that Dispatch's Run.\n\nClassify inherited context before sending lifecycle messages:\n\n- Coordinated subtask: a live coordinator owns the DAG and waits on this dispatch. Follow the preamble exactly, including `worker_done`, heartbeat/status, `ask`, and `escalation`.\n- Full handoff means ownership transfer, not supervised dispatch. The original actor is not monitoring a DAG, so do not create lifecycle obligations unless the user explicitly asks you to supervise.\n- Classify requests containing \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs by default, even when the user names a custom model or reasoning effort.\n- Use supervised orchestration only when the user explicitly asks you to \"supervise\", \"monitor\", \"wait\", \"track completion\", \"wait for worker_done\", return results, coordinate a DAG, use a decision gate, or manage ask/reply flow.\n- Do not use `orca orchestration dispatch --inject` for full handoffs. It injects a coordinator preamble that tells the worker to send `worker_done`, heartbeat, and `ask` messages, then end its turn under the original terminal's dispatch lifecycle.\n- Do not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. Do not peek at terminal output after prompt delivery to monitor progress.\n- A review-only `worker_done` reports findings; it does not authorize coordinator file edits. After a review-only completion, synthesize findings, ask a decision gate if ownership is unclear, and dispatch or hand off fixes unless the user explicitly asked the coordinator to own fixes.\n- If the user's plan names a next owner agent (for example, \"then use opencode to create a PR\"), post-review corrections and PR prep belong to that named owner. The coordinator routes, synthesizes, asks decision gates when needed, and supervises; the named owner edits files and creates the PR.\n\nIf unclear, inspect orchestration state before sending lifecycle messages:\n\n```bash\norca orchestration task-list --json\norca terminal list --json\n# If inherited context includes a task id:\norca orchestration dispatch-show --task --json\n```\n\n## Messaging\n\n```bash\norca orchestration send --subject [--to ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--json]\norca orchestration check [--terminal ] [--ack ] [--peek|--all] [--types ] [--format] [--wait] [--timeout-ms ] [--json]\norca orchestration reply --id --body [--from ] [--json]\norca orchestration ask (--question |--resume ) [--options ] [--timeout-ms ] [--from ] [--json]\norca orchestration inbox [--limit ] [--json]\n```\n\nRules:\n\n- Omit `--from` unless impersonating another terminal; Orca auto-resolves it from the current terminal.\n- A coordinator `check` returns the bound Run's oldest FIFO Delivery (up to 50 messages) and replays that exact batch until `--ack `. Process every message before acknowledging; `check --ack --wait` acknowledges, checks, and waits in one operation.\n- Use `--peek` and `--all` only for read-only history/debugging. Type filters decide when a waiter wakes; the returned actionable Delivery is still the oldest full batch.\n- Use `dispatch:` for coordinator guidance to one supervised worker. Orca routes that stable address locally or through the connected-server relay; do not substitute a remote terminal handle.\n- Terminal handles remain appropriate for low-level pre-Dispatch messaging. Prefer `agentTerminalHandle` from the create response, fall back to `startupTerminal.handle` for older runtimes, then re-resolve with `orca terminal list --worktree ... --json` if missing or stale. Continue with the replacement handle only; never dual-send to old and new handles.\n- `orca orchestration check --peek --format --json` returns locally formatted unread mail without consuming it; it never writes to terminal input or remotely wakes another terminal. Use `orchestration dispatch --inject` to deliver a tracked task, or `terminal send` when an existing agent needs a free-form prompt.\n- While supervising workers manually, use `check --wait --types worker_done,escalation,question --timeout-ms ` instead of sleep/poll loops. Process the whole Delivery, reply to `question` messages with `orca orchestration reply --id --body --json`, then acknowledge and keep waiting.\n- Treat a `check --wait` timeout or `{count:0}` as a checkpoint, not a worker failure. Long coding tasks routinely run 15-60 minutes; keep using rolling waits unless you receive `worker_done`/`escalation`, the terminal exits or disappears, or the user explicitly asks you to stop.\n- Heartbeats and visible terminal activity mean the worker is alive, not done. Do not stop, close, kill, or restart a worker just because it has not produced a completion message yet.\n- Use `ask` when a worker needs a blocking answer from the coordinator; it defaults to the active Dispatch's Run. Timeout or disconnect leaves the question pending, so resume by its original message ID instead of asking again.\n- `check --wait` returns one bounded Delivery, not every future completion. Process every message, acknowledge it, then keep waiting until every expected Dispatch settles.\n- Group addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`.\n- Message types include `status`, `dispatch`, `worker_done`, `merge_ready`, `escalation`, `handoff`, `question`, `decision_gate` (legacy/gates), and `heartbeat`.\n- Use group addresses only for messages that are genuinely useful to many terminals, such as `status` broadcasts or intentional fan-out questions. Do not send dispatch lifecycle messages to groups.\n- `worker_done` belongs to the active Dispatch and defaults to its Run mailbox; never target a group.\n- A valid `worker_done` for the active `taskId` + `dispatchId` marks the task and dispatch completed automatically. Do not follow it with `task-update --status completed`; reserve manual updates for explicit recovery or overrides.\n- `heartbeat` is also Dispatch-scoped. Include both IDs and omit `--to` so Orca uses the owning Run; use `status` for broad progress updates.\n\n## Tasks And Dispatch\n\nA Run is the namespace/inbox, a Task is the work item, and a Dispatch assigns one Task attempt to a terminal. Create or bind a Run once before the common loop.\n\n```bash\norca orchestration run-create --objective --json\norca orchestration task-create --spec [--deps ] [--parent ] [--json]\norca orchestration task-list [--status ] [--ready] [--brief] [--json]\norca orchestration task-update --id --status [--result ] [--json]\norca orchestration dispatch --task --to [--from ] [--inject] [--json]\norca orchestration dispatch-show --task [--json]\n```\n\nTask statuses: `pending`, `ready`, `dispatched`, `completed`, `failed`, `blocked`.\n\nDispatch rules:\n\n- `--inject` sends the task spec plus preamble into a recognized agent CLI so it can report `worker_done`.\n- If the target is a bare shell, omit `--inject`, dispatch for tracking if needed, then send the prompt manually with `orca terminal send --terminal --text --enter --json`.\n- After 3 consecutive failures on one task, the dispatch context circuit-breaks and the task is marked failed.\n- Use `task-list --brief --json` for coordinator sweeps; it collapses whitespace and caps each echoed spec at 160 characters (`spec_truncated` marks shortened rows). Omit `--brief` when the full spec is required, or when an older CLI rejects it as an unknown flag.\n\n## Preferred Supervised Worker Loop\n\nUse `worker-start` for the normal supervised path. It composes the existing worktree, terminal, readiness, and dispatch primitives while returning exact created/reused effects. Agents still choose placement and concurrency; Orca does not schedule workers or infer conflicts.\n\nCreate the Run and every independent Task first, then start all independent workers before waiting:\n\n```bash\norca orchestration run-create --objective \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration worker-start --task --worktree current --agent codex --json\norca orchestration worker-start --task --worktree current --agent claude --json\n```\n\n`current` and exact existing worktrees create a fresh agent terminal and do not rerun setup. Reuse an existing agent only with `--terminal `.\n\nFor a new worktree, setup runs by default and agent-first creation reuses the returned startup agent terminal:\n\n```bash\norca orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n# Independent/top-level:\norca orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nSetup normally starts alongside the agent. Only a repository explicitly configured with `wait-for-setup` delays agent launch until setup succeeds. Use `--setup skip` or `--setup inherit` only for a concrete reason.\n\nRead the returned receipt before continuing: `ready` plus setup `running` is normal for start-immediately, while wait-for-setup returns setup `succeeded` before accepting task input. A failed or unknown start exits nonzero; inspect its `stage`, `effects`, and `residualResources` instead of guessing or automatically retrying. A wait-for-setup timeout can honestly leave setup `running`, which is not proof of failure.\n\nTo run the worker on another connected Orca server, add `--on `. The Run and Tasks remain authoritative on the current server; later commands route by Dispatch ID, so never repeat `--on`:\n\n```bash\n# Mac Run home -> Windows worker (the reverse is identical from a Windows Run home)\norca orchestration worker-start --task --on windows --worktree new-top-level --repo --name --agent codex --setup run --json\norca orchestration worker-show --dispatch --json\norca orchestration worker-read --dispatch --limit 50 --json\norca orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nRemote `current` and `new-child` are intentionally invalid because those words are ambiguous across servers. Use an exact discovered remote worktree selector or `new-top-level` with an explicit remote repo selector.\n\nThe follow-up is structured inbox mail, not prompt injection. The worker's next\n`orchestration check` receives it even when the Dispatch is on another connected Orca server.\n\n`worker-read` defaults to `--source auto`: Orca returns the exact hook-reported Codex, Claude, OpenClaude, or Grok transcript when it can prove the worker session, otherwise it returns bounded terminal output with `source: \"terminal\"` and a typed `fallbackReason`. Continue with the returned top-level `cursor`; it stays pinned to that exact source. If Orca reports `source_changed`, start a fresh read without the old cursor. Never supply or guess a provider session ID or transcript path.\n\nWait until every expected Dispatch settles, not for a fixed number of batches:\n\n```bash\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n# Process every message in the returned Delivery, then atomically ack and continue:\norca orchestration check --ack --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\nWorkers report exactly once using the IDs and capability injected by Orca; they do not supply Run/server/terminal identity:\n\n```bash\norca orchestration send --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a,path/b\" --json\n# On failure, use --outcome failed; never encode failure only in prose.\n```\n\nA worker question defaults to its owning Run. Timeout leaves it pending:\n\n```bash\norca orchestration ask --question \"\" --options \"yes,no\" --timeout-ms 600000 --json\norca orchestration ask --resume --timeout-ms 600000 --json\n# Coordinator:\norca orchestration reply --id --body \"\" --json\n```\n\nRecovery is conditional, never a fixed destructive sequence:\n\n- `worker-show --dispatch ` says `ready`: keep waiting or read bounded output.\n- It proves `failed` or `stopped`: start a replacement with `worker-start --task --retry-of ` plus an explicit `--on`/`--worktree` and `--agent`/`--terminal` choice. Retry does not silently inherit placement.\n- It remains `outcome_unknown`: either `worker-stop --dispatch ` and inspect again, or explicitly `worker-abandon --dispatch ` while accepting that resources may still be live. Abandon performs no remote, process, or filesystem action.\n- `worker-stop` closes only the exact supervised agent terminal. It never deletes the worktree, setup terminal, configured tabs, or unrelated processes.\n\nLow-level `worktree create`, `terminal create`, and `dispatch --inject` remain valid recipes for custom argv or topology that `worker-start` does not express.\n\n## Gates And Legacy Inspection\n\n```bash\norca orchestration gate-create --task --question [--options ] [--json]\norca orchestration gate-resolve --id --resolution [--json]\norca orchestration gate-list [--task ] [--status ] [--json]\n```\n\nUse `ask` for worker-to-coordinator questions; it creates a `question` message that the coordinator answers with `reply`. Use `gate-create` only for coordinator-managed task DAG decisions, not for answering a worker's `ask`.\n\n`coordinator-start`, `coordinator-stop`, `run`, and `run-stop` are retired scheduler commands. They perform no effects and return the current-skill recovery action. They are not aliases for lightweight Run creation or binding.\n\nRecovery only: `orca orchestration reset --tasks|--messages|--all --json` clears the selected local orchestration database state. Do not run it during active coordination unless explicitly abandoning that state.\n\n## Full Handoffs\n\nFor full ownership transfer, use non-lifecycle terminal/worktree commands and then stop monitoring unless the user asks for supervision.\n\nTreat these as full handoff requests by default: \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"send this to another agent\", \"another agent\", \"another worktree\", or \"launch another agent to own this.\" Custom model or reasoning effort words such as `gpt-5.5`, `high`, or `xhigh` do not make the handoff supervised.\n\nSupervised orchestration remains available only when the user explicitly asks for supervision or coordination: \"supervise\", \"monitor\", \"wait for worker_done\", \"wait for results\", \"track completion\", \"DAG\", \"decision gate\", \"ask/reply\", or \"coordinate workers.\"\n\nDo not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Do not create a `taskId`/`dispatchId`, inject a lifecycle preamble, wait for completion, or read the worker terminal after prompt delivery except to avoid losing the initial prompt.\n\nNew top-level worktree handoff:\n\n```bash\norca worktree create --name --no-parent --agent codex --prompt \"\" --setup run --json\n```\n\nBefore creating a new worktree from an active feature branch, decide and state whether the desired Orca lineage is child or top-level. Use child worktree lineage only when the new work is conceptually stacked under or dependent on the active worktree. For independent repo-wide fixes, standalone feature work, or unrelated follow-up tasks, create a top-level worktree with `--no-parent`.\n\nExisting terminal handoff:\n\n```bash\norca terminal send --terminal --text \"\" --enter --json\n```\n\nCustom Codex model/effort handoff:\n\n`orca worktree create --agent codex --prompt ...` launches the known Codex agent but does not accept Codex-specific `--model` or `-c model_reasoning_effort=...` arguments. When the user asks for a specific Codex model or effort, create the independent worktree first, launch Codex with the requested command in that worktree, wait only for TUI readiness if prompt delivery would otherwise race startup, send the prompt, and stop.\n\nThe two-step custom-argv path cannot enforce a repository's explicit `wait-for-setup` startup policy because the later `terminal create` is not the startup owned by `worktree create`. Use it only when the repository starts agents immediately. If the repository requires `wait-for-setup`, use an agent-first configured launcher that can preserve sequencing, or stop and ask rather than silently bypassing the policy.\n\nNote: when no repo default-terminal configuration supplies a primary terminal, bare create opens a fallback shell before `terminal create` adds the agent. Configured default tabs are materialized instead and may run real commands. Prefer `--agent` whenever custom argv is not required. With the two-step path, target only the agent handle; close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell.\n\nUse the exact full `::` worktree id returned by `orca worktree create --json`; a bare repo id cannot target the new worktree.\n\n```bash\norca worktree create --name --no-parent --setup run --json\norca terminal create --worktree id: --title --command 'codex --model gpt-5.5 -c model_reasoning_effort=\"xhigh\"' --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca terminal send --terminal --text \"\" --enter --json\n```\n\nWait only for `tui-idle` when needed to avoid losing the prompt. Do not monitor task completion.\n\n`--no-parent` only controls Orca lineage; it does not choose the Git base. If the work should start from the repo default base, omit `--base-branch` so Orca uses that default, or explicitly pass the repo default base (`origin/main`, `origin/master`, or the `orca repo show --repo --json` value); never base it on the current feature branch unless the user explicitly asks for stacked work or \"branch from current\". Put current-branch context in the prompt instead.\n\n## Worker Terminals\n\nChoose the worker location before creating a terminal. `Fresh worker` means a fresh agent session, not a new git worktree. For parallel work, create one fresh agent terminal per worker in the same required worktree, falling back to the active worktree when none is named. If the task says current worktree only, depends on uncommitted files/artifacts, or must validate/PR the current branch, keep every worker in the active worktree:\n\n```bash\norca terminal create --worktree active --title --command \"codex\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nReuse an idle agent in the required worktree only if the prompt allows reuse; otherwise create a fresh terminal there. Create a new worktree only when the user explicitly requests one or a concrete checkout or filesystem conflict makes sharing unsafe or impossible; if the user did not request it, state that conflict before running `worktree create`. Independent tasks, parallel execution, convenience, or a preference for separate checkouts are not isolation requirements.\n\nWhen a new worktree is allowed, use child lineage for isolated work that is stacked under or dependent on the active worktree, and use `--no-parent` when it is not stacked. Decide the Git base separately: `--no-parent` makes the worktree top-level in Orca, while omitted `--base-branch` uses the repo default base.\n\nFor every new worktree, pass `--setup run` so any configured repository setup hook runs. This does not mean waiting for setup before agent launch: preserve the repository's startup policy, whose default starts setup and the agent side by side. Use `--setup skip` or `--setup inherit` only when there is a concrete task-specific reason, and state that reason before creating the worktree. This rule does not rerun setup for current or existing worktrees.\n\n```bash\norca worktree create --name --agent codex --setup run --json\n# or: --agent claude | omp | pi | grok | ...\n# Read from agentTerminalHandle, falling back to startupTerminal.handle.\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nFor new-worktree workers, read the id and `agentTerminalHandle` from `worktree create`, falling back to `startupTerminal.handle` for older runtimes. Use that as the sole worker handle when present; otherwise use `terminal list` to resolve the agent handle. Omit `--repo` only inside an Orca-managed worktree; otherwise pass `--repo `.\n\n**For an allowed new worktree, use agent-first:** `--agent` reveals the new worktree and launches the selected agent **in its first terminal**, without adding a separate fallback shell for that worker. Pass `--setup run`; repo setup and default-terminal settings may add intentional tabs or splits. Do **not** run bare `worktree create` and then `terminal create --command ` for the same worker when agent-first create is available: without configured default tabs, that two-step path leaves a fallback shell + agent pair. Only use it when custom agent argv is required (for example Codex model/effort flags) or when an older CLI rejects `--agent`; if you must, message only the agent handle. Configured default tabs are intentional surfaces, so close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell. Do not run `worktree create` when the task must stay in the current worktree.\n\nUse `orca worktree create --prompt ...` or `orca terminal send ...` for full handoffs or untracked/lightweight prompts. Those paths do not attach `taskId`/`dispatchId`; the worker should not send lifecycle messages unless the prompt supplies a live orchestration preamble.\n\nSidebar lineage and orchestration lifecycle are related but not identical. A same-worktree worker may appear as a peer under that worktree in the sidebar while remaining a child dispatch in orchestration state; only an actual child worktree creates visible parent/child worktree lineage.\n\nOther terminal commands coordinators often need:\n\n```bash\norca terminal list [--worktree ] [--json]\norca terminal create [--worktree ] [--title ] [--command ] [--json]\norca terminal split --terminal [--direction horizontal|vertical] [--command ] [--json]\norca terminal wait --terminal --for tui-idle --timeout-ms --json\norca terminal read --terminal --json\norca terminal send --terminal --text --enter --json\n```\n\nIf an older CLI rejects `worktree create --agent`, create the worktree normally, then run `orca terminal create --worktree --command \"codex\" --json` or `--command \"claude\"`.\n\nWait for `tui-idle` before dispatching. Always pass `--timeout-ms`; real coding tasks can take 15-60 minutes. During supervision, use rolling `check --wait` windows. If a window returns no matching message, inspect `task-list`, `terminal read`, or `terminal wait --for tui-idle` as a liveness checkpoint; if the terminal is still working or producing activity, keep waiting instead of retrying the task.\n\n## Agent Guidance\n\n- Workers with a valid live preamble must send `worker_done` exactly once from their own terminal with an explicit `--outcome succeeded` or `--outcome failed`:\n `orca orchestration send --type worker_done --subject \"\" --body \"<3-sentence summary: what you did, what you found, what's left>\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a\" --report-path \"\" --json`\n- A failed outcome is still a terminal report, but Orca records both the Dispatch and Task as failed. Never encode failure only in the subject/body.\n- After sending `worker_done`, end your turn and idle at the agent prompt. Do not poll or keep calling `orca orchestration check`; the coordinator re-engages you with a fresh preamble + TASK block delivered as new terminal input.\n- For long tasks, send heartbeat/status only when the preamble asks for it, including both IDs:\n `orca orchestration send --type heartbeat --subject \"alive\" --payload '{\"taskId\":\"\",\"dispatchId\":\"\",\"phase\":\"implementing\"}' --json`\n- If blocked before completion, use `ask`; use `escalation` only when ownership is valid and the coordinator must intervene.\n- Treat preambles inherited through terminal history or full handoffs as stale unless the current prompt explicitly keeps that coordinator in the loop.\n- Coordinators should use `task-list --ready` as external memory, dispatch parallel waves, and avoid dependency chains deeper than 3-4 steps.\n\n## Example\n\n```bash\norca terminal create --worktree active --title login-css-worker --command \"claude\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration task-create --spec \"Fix the login button CSS\" --json\norca orchestration dispatch --task --to --inject --json\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\n## Next Action\n\nCoordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology.\n\nWorker: if the current prompt contains a live dispatch preamble, do the task, use `ask` for blocking questions, and send `worker_done` once with the required payload. If the preamble is stale or absent, do not send lifecycle messages; inspect state or treat the prompt as an ordinary handoff.\n" +const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Use Orca orchestration for structured multi-agent coordination: threaded\n messages, blocking ask/reply flows, task dispatch, worker_done/escalation\n waits, task DAGs, decision gates, coordinator loops, or decomposing work\n across agents. Use `orca-cli` instead for full ownership handoffs, including\n requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", or \"another worktree\" when the user did not explicitly ask to\n supervise, monitor, wait for results, or coordinate a DAG. Use `orca-cli` for\n ordinary terminal control, lightweight terminal prompts, shell commands, Orca\n worktree management, reading or waiting on terminals, and automation of the\n browser embedded inside Orca. Use Computer Use for browser windows, webviews,\n Orca app UI, or desktop UI outside Orca's embedded browser.\n---\n\n# Orca Inter-Agent Orchestration\n\nOrchestration is Orca's structured coordination layer for agent messages, task ownership, dispatch state, and worker completion tracking.\n\nUse this skill when coordination state matters. For lightweight terminal prompts or basic worktree/terminal/built-in-browser control, use `orca-cli`.\n\n## Tool Boundary\n\nIf a task says to use Orca orchestration, the coordinator must create or bind a Run, create the Task with `orca orchestration task-create`, then attach the worker with either the preferred `orca orchestration worker-start` composition or the low-level `orca orchestration dispatch --inject` path.\n\nDo not substitute non-Orca subagent tools, generic agent-spawn APIs, or chat-only parallel worker features. Those may create useful workers, but they do not create Orca task/dispatch provenance, injected lifecycle preambles, `worker_done` authority, or decision gates.\n\nBefore claiming a worker was orchestrated, verify the task/dispatch exists:\n\n```bash\norca orchestration task-list --json\norca orchestration dispatch-show --task --json\n```\n\nIf the work was accidentally run outside Orca orchestration, say so plainly. To repair provenance, rerun or revalidate the needed work through a fresh Orca terminal plus injected dispatch; do not retroactively describe the external worker as orchestrated.\n\n## When To Use\n\n- Send/reply/ask between agent terminals with persistent messages.\n- Dispatch structured tasks to workers and wait for `worker_done` or `escalation`.\n- Track task DAGs with dependencies.\n- Run coordinator loops or decision gates.\n\nDo not use orchestration merely because the user says \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", or asks for another worktree/agent/model/effort. Those are full ownership transfers unless the user explicitly asks to supervise, monitor, wait for worker completion/results, coordinate a DAG, use decision gates, or keep a blocking ask/reply loop.\n\n## Preconditions\n\n- `orca status --json` should show a running runtime.\n- `orca` must be on PATH (`orca-ide` on Linux).\n- The orchestration experimental feature must be enabled in Settings > Experimental.\n- `orca orchestration` commands are RPC calls to the running Orca runtime.\n\n## Contract Migration\n\nOrca adopts a live pre-update orchestration assignment into an ordinary Run. Adoption preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch; it never restarts or replaces the worker. The retired scheduler is not revived, and a newly created attempt uses the current grammar.\n\nTreat the authority label on injected or formatted messages as definitive:\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported command printed with the message, using the same CLI executable and arguments that the original prompt supplied.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded, at-least-once cutover replay. Process it idempotently and acknowledge it only through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or lifecycle action.\n- An unlabeled current message uses the current guide and current grammar.\n\nAn explicitly selected current Run, attested current Run binding, current Dispatch, or federated attachment takes precedence over legacy fallback. A retained adoption record alone never turns a current command into a legacy call.\n\nDatabase provenance, an old-looking terminal, or a legacy Run ID does not prove mutation authority. If the runtime cannot prove liveness, principal ownership, capability, or the exact legacy contract, it degrades to read-only inspection and must not fall back to local execution. Exact recovery may restore the already-live PTY once in its original inactive background tab. It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal. Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.\n\nCompatibility retries have narrow guarantees. A pending ask, a reply, a final Dispatch settlement, and a consuming check have durable recovery identities. A-era heartbeat and escalation calls remain at-least-once across a manual A-to-B retry because identical later signals may be intentional. If an A-era ask may already have been answered, run the exact non-consuming recovery check printed by the runtime first; after its answer is printed and acknowledged, a new invocation with the same question creates a new question. Never guess among multiple identical question threads.\n\nWhen a compatibility or recovery command returns structured next-step arguments, run those exact arguments with the same CLI executable. The arguments intentionally omit the executable name so the guidance works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command. Do not translate the command from memory, broaden its recipient, or retry it as a current mutation unless the returned guidance explicitly says to.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The initial command durably commits the question, prints its exact `ask --resume ` command, and exits with launcher status `75`; it does not wait for the answer. Run that exact resume command after the launcher or update boundary. Resume is idempotent and read-oriented: it waits for the already-committed question and does not create another one. For a WSL process that received compatibility proof at launch, use the printed executable `orca-ide` WSL resume command so the same distro and packaged launcher authority are preserved; do not substitute a PATH-resolved local CLI. Older WSL processes that never received the hidden launch token remain lifecycle read-only after the update, even while their terminal and filesystem work continue.\n\nLegacy inspection remains available without consuming mail:\n\n```bash\norca orchestration run-list --json\n# run_legacy_local is an empty audit tombstone after adoption.\norca orchestration run-show --id run_legacy_local --json\n# In run-list, find the ordinary Run whose objective is:\n# \"Recovered orchestration work from a contract update\"\norca orchestration run-show --id --json\norca orchestration task-list --run --json\norca orchestration inbox --full --json\norca orchestration check --terminal --peek --format --json\norca terminal read --terminal --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\nIf the original coordinator is unavailable or cannot prove its retained authority, a current coordinator may explicitly take over the adopted Run from its own live agent terminal:\n\n```bash\norca orchestration run-use --id --takeover-legacy --json\norca orchestration check --run --json\n```\n\nTakeover fences only the old coordinator, binds the current one, and moves pending worker mail into current Run Delivery. It is bound to the authenticated invoking terminal; `--from` cannot name another coordinator. Live legacy workers keep their original Tasks, Dispatches, processes, filesystems, and old prompt commands; their later questions, escalations, and completion reports route to the current coordinator. Do not use takeover while the original coordinator is still actively coordinating, because its later lifecycle mutations are rejected.\n\nDo not launch a replacement editor merely because the desktop app or runtime was updated. If adoption cannot prove continuing authority, keep the original worker as the only editor until it reaches a stable handoff point, then use a new current Dispatch in a conflict-free placement for any remaining work.\n\n## Ownership\n\nNew orchestration messages and tasks belong to one explicitly bound Run. A Run is only a durable namespace and coordinator inbox; it never schedules or places workers. Lifecycle authority comes from the active Dispatch, and terminal handles remain routing metadata rather than durable identity. Send `worker_done` and `heartbeat` from the worker's own terminal; Orca routes them to that Dispatch's Run.\n\nClassify inherited context before sending lifecycle messages:\n\n- Coordinated subtask: a live coordinator owns the DAG and waits on this dispatch. Follow the preamble exactly, including `worker_done`, heartbeat/status, `ask`, and `escalation`.\n- Full handoff means ownership transfer, not supervised dispatch. The original actor is not monitoring a DAG, so do not create lifecycle obligations unless the user explicitly asks you to supervise.\n- Classify requests containing \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs by default, even when the user names a custom model or reasoning effort.\n- Use supervised orchestration only when the user explicitly asks you to \"supervise\", \"monitor\", \"wait\", \"track completion\", \"wait for worker_done\", return results, coordinate a DAG, use a decision gate, or manage ask/reply flow.\n- Do not use `orca orchestration dispatch --inject` for full handoffs. It injects a coordinator preamble that tells the worker to send `worker_done`, heartbeat, and `ask` messages, then end its turn under the original terminal's dispatch lifecycle.\n- Do not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. Do not peek at terminal output after prompt delivery to monitor progress.\n- A review-only `worker_done` reports findings; it does not authorize coordinator file edits. After a review-only completion, synthesize findings, ask a decision gate if ownership is unclear, and dispatch or hand off fixes unless the user explicitly asked the coordinator to own fixes.\n- If the user's plan names a next owner agent (for example, \"then use opencode to create a PR\"), post-review corrections and PR prep belong to that named owner. The coordinator routes, synthesizes, asks decision gates when needed, and supervises; the named owner edits files and creates the PR.\n\nIf unclear, inspect orchestration state before sending lifecycle messages:\n\n```bash\norca orchestration task-list --json\norca terminal list --json\n# If inherited context includes a task id:\norca orchestration dispatch-show --task --json\n```\n\n## Messaging\n\n```bash\norca orchestration send --subject [--to ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--json]\norca orchestration check [--terminal ] [--ack ] [--peek|--all] [--types ] [--format] [--wait] [--timeout-ms ] [--json]\norca orchestration reply --id --body [--from ] [--json]\norca orchestration ask (--question |--resume ) [--options ] [--timeout-ms ] [--from ] [--json]\norca orchestration inbox [--limit ] [--json]\n```\n\nRules:\n\n- Omit `--from` unless impersonating another terminal; Orca auto-resolves it from the current terminal.\n- A coordinator `check` returns the bound Run's oldest FIFO Delivery (up to 50 messages) and replays that exact batch until `--ack `. Process every message before acknowledging; `check --ack --wait` acknowledges, checks, and waits in one operation.\n- Use `--peek` and `--all` only for read-only history/debugging. Type filters decide when a waiter wakes; the returned actionable Delivery is still the oldest full batch.\n- Use `dispatch:` for coordinator guidance to one supervised worker. Orca routes that stable address locally or through the connected-server relay; do not substitute a remote terminal handle.\n- Terminal handles remain appropriate for low-level pre-Dispatch messaging. Prefer `agentTerminalHandle` from the create response, fall back to `startupTerminal.handle` for older runtimes, then re-resolve with `orca terminal list --worktree ... --json` if missing or stale. Continue with the replacement handle only; never dual-send to old and new handles.\n- `orca orchestration check --peek --format --json` returns locally formatted unread mail without consuming it; it never writes to terminal input or remotely wakes another terminal. Use `orchestration dispatch --inject` to deliver a tracked task, or `terminal send` when an existing agent needs a free-form prompt.\n- While supervising workers manually, use `check --wait --types worker_done,escalation,question --timeout-ms ` instead of sleep/poll loops. Process the whole Delivery, reply to `question` messages with `orca orchestration reply --id --body --json`, then acknowledge and keep waiting.\n- Treat a `check --wait` timeout or `{count:0}` as a checkpoint, not a worker failure. Long coding tasks routinely run 15-60 minutes; keep using rolling waits unless you receive `worker_done`/`escalation`, the terminal exits or disappears, or the user explicitly asks you to stop.\n- Heartbeats and visible terminal activity mean the worker is alive, not done. Do not stop, close, kill, or restart a worker just because it has not produced a completion message yet.\n- Use `ask` when a worker needs a blocking answer from the coordinator; it defaults to the active Dispatch's Run. Timeout or disconnect leaves the question pending, so resume by its original message ID instead of asking again.\n- `check --wait` returns one bounded Delivery, not every future completion. Process every message, acknowledge it, then keep waiting until every expected Dispatch settles.\n- Group addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`.\n- Message types include `status`, `dispatch`, `worker_done`, `merge_ready`, `escalation`, `handoff`, `question`, `decision_gate` (legacy/gates), and `heartbeat`.\n- Use group addresses only for messages that are genuinely useful to many terminals, such as `status` broadcasts or intentional fan-out questions. Do not send dispatch lifecycle messages to groups.\n- `worker_done` belongs to the active Dispatch and defaults to its Run mailbox; never target a group.\n- A valid `worker_done` for the active `taskId` + `dispatchId` marks the task and dispatch completed automatically. Do not follow it with `task-update --status completed`; reserve manual updates for explicit recovery or overrides.\n- `heartbeat` is also Dispatch-scoped. Include both IDs and omit `--to` so Orca uses the owning Run; use `status` for broad progress updates.\n\n## Tasks And Dispatch\n\nA Run is the namespace/inbox, a Task is the work item, and a Dispatch assigns one Task attempt to a terminal. Create or bind a Run once before the common loop.\n\n```bash\norca orchestration run-create --objective --json\norca orchestration task-create --spec [--deps ] [--parent ] [--json]\norca orchestration task-list [--status ] [--ready] [--brief] [--json]\norca orchestration task-update --id --status [--result ] [--json]\norca orchestration dispatch --task --to [--from ] [--inject] [--json]\norca orchestration dispatch-show --task [--json]\n```\n\nTask statuses: `pending`, `ready`, `dispatched`, `completed`, `failed`, `blocked`.\n\nDispatch rules:\n\n- `--inject` sends the task spec plus preamble into a recognized agent CLI so it can report `worker_done`.\n- If the target is a bare shell, omit `--inject`, dispatch for tracking if needed, then send the prompt manually with `orca terminal send --terminal --text --enter --json`.\n- After 3 consecutive failures on one task, the dispatch context circuit-breaks and the task is marked failed.\n- Use `task-list --brief --json` for coordinator sweeps; it collapses whitespace and caps each echoed spec at 160 characters (`spec_truncated` marks shortened rows). Omit `--brief` when the full spec is required, or when an older CLI rejects it as an unknown flag.\n\n## Preferred Supervised Worker Loop\n\nUse `worker-start` for the normal supervised path. It composes the existing worktree, terminal, readiness, and dispatch primitives while returning exact created/reused effects. Agents still choose placement and concurrency; Orca does not schedule workers or infer conflicts.\n\nCreate the Run and every independent Task first, then start all independent workers before waiting:\n\n```bash\norca orchestration run-create --objective \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration worker-start --task --worktree current --agent codex --json\norca orchestration worker-start --task --worktree current --agent claude --json\n```\n\n`current` and exact existing worktrees create a fresh agent terminal and do not rerun setup. Reuse an existing agent only with `--terminal `.\n\nFor a new worktree, setup runs by default and agent-first creation reuses the returned startup agent terminal:\n\n```bash\norca orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n# Independent/top-level:\norca orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nSetup normally starts alongside the agent. Only a repository explicitly configured with `wait-for-setup` delays agent launch until setup succeeds. Use `--setup skip` or `--setup inherit` only for a concrete reason.\n\nRead the returned receipt before continuing: `ready` plus setup `running` is normal for start-immediately, while wait-for-setup returns setup `succeeded` before accepting task input. A failed or unknown start exits nonzero; inspect its `stage`, `effects`, and `residualResources` instead of guessing or automatically retrying. A wait-for-setup timeout can honestly leave setup `running`, which is not proof of failure.\n\nTo run the worker on another connected Orca server, add `--on `. The Run and Tasks remain authoritative on the current server; later commands route by Dispatch ID, so never repeat `--on`:\n\n```bash\n# Mac Run home -> Windows worker (the reverse is identical from a Windows Run home)\norca orchestration worker-start --task --on windows --worktree new-top-level --repo --name --agent codex --setup run --json\norca orchestration worker-show --dispatch --json\norca orchestration worker-read --dispatch --limit 50 --json\norca orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nRemote `current` and `new-child` are intentionally invalid because those words are ambiguous across servers. Use an exact discovered remote worktree selector or `new-top-level` with an explicit remote repo selector.\n\nThe follow-up is structured inbox mail, not prompt injection. The worker's next\n`orchestration check` receives it even when the Dispatch is on another connected Orca server.\n\n`worker-read` defaults to `--source auto`: Orca returns the exact hook-reported Codex, Claude, OpenClaude, or Grok transcript when it can prove the worker session, otherwise it returns bounded terminal output with `source: \"terminal\"` and a typed `fallbackReason`. Continue with the returned top-level `cursor`; it stays pinned to that exact source. If Orca reports `source_changed`, start a fresh read without the old cursor. Never supply or guess a provider session ID or transcript path.\n\nWait until every expected Dispatch settles, not for a fixed number of batches:\n\n```bash\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n# Process every message. For each accepted worker_done that is not immediately reused:\norca orchestration worker-release --dispatch --json\n# Acknowledge only after every message and required release decision is handled:\norca orchestration check --ack --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\nAfter processing each accepted `worker_done`, choose the terminal's next owner before you acknowledge the Delivery or wait again. If the same exact agent has an immediate follow-up Task, read the `worker.agent_terminal_handle` field of `worker-show --dispatch --json`, then run `orca orchestration worker-start --task --terminal --json` so Orca transfers cleanup ownership to the new Dispatch. Otherwise run `orca orchestration worker-release --dispatch --json`.\n\nRun `worker-release` after both succeeded and failed `worker_done` reports unless the user explicitly asked to keep that worker live. Release is post-completion cleanup, not cancellation: Orca first preserves inspectable output, then closes only the exact agent terminal owned by that settled Dispatch. Reused or pre-existing terminals, setup terminals, coordinators, active workers, user-taken-over terminals, and identities Orca cannot prove are retained. If the user explicitly asks to keep the live terminal for debugging, record that exception with `orca orchestration worker-retain --dispatch --json` instead of silently skipping cleanup. When the user is finished, the same Dispatch can be passed to `worker-release`, which clears the requested retention and releases the terminal.\n\nDo not release a worker because of a timeout, TUI idle state, heartbeat, status, question, escalation, or rejected/stale `worker_done`. If release returns `release_pending` or `release_unknown`, do not substitute `terminal close`; follow the exact recovery action in the receipt. A replayed Delivery may repeat `worker-release` safely.\n\nWorkers report exactly once using the IDs and capability injected by Orca; they do not supply Run/server/terminal identity:\n\n```bash\norca orchestration send --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a,path/b\" --json\n# On failure, use --outcome failed; never encode failure only in prose.\n```\n\nA worker question defaults to its owning Run. Timeout leaves it pending:\n\n```bash\norca orchestration ask --question \"\" --options \"yes,no\" --timeout-ms 600000 --json\norca orchestration ask --resume --timeout-ms 600000 --json\n# Coordinator:\norca orchestration reply --id --body \"\" --json\n```\n\nRecovery is conditional, never a fixed destructive sequence:\n\n- `worker-show --dispatch ` says `ready`: keep waiting or read bounded output.\n- It proves `failed` or `stopped`: start a replacement with `worker-start --task --retry-of ` plus an explicit `--on`/`--worktree` and `--agent`/`--terminal` choice. Retry does not silently inherit placement.\n- It remains `outcome_unknown`: either `worker-stop --dispatch ` and inspect again, or explicitly `worker-abandon --dispatch ` while accepting that resources may still be live. Abandon performs no remote, process, or filesystem action.\n- `worker-stop` closes only the exact supervised agent terminal. It never deletes the worktree, setup terminal, configured tabs, or unrelated processes.\n\nLow-level `worktree create`, `terminal create`, and `dispatch --inject` remain valid recipes for custom argv or topology that `worker-start` does not express.\n\n## Gates And Legacy Inspection\n\n```bash\norca orchestration gate-create --task --question [--options ] [--json]\norca orchestration gate-resolve --id --resolution [--json]\norca orchestration gate-list [--task ] [--status ] [--json]\n```\n\nUse `ask` for worker-to-coordinator questions; it creates a `question` message that the coordinator answers with `reply`. Use `gate-create` only for coordinator-managed task DAG decisions, not for answering a worker's `ask`.\n\n`coordinator-start`, `coordinator-stop`, `run`, and `run-stop` are retired scheduler commands. They perform no effects and return the current-skill recovery action. They are not aliases for lightweight Run creation or binding.\n\nRecovery only: `orca orchestration reset --tasks|--messages|--all --json` clears the selected local orchestration database state. Do not run it during active coordination unless explicitly abandoning that state.\n\n## Full Handoffs\n\nFor full ownership transfer, use non-lifecycle terminal/worktree commands and then stop monitoring unless the user asks for supervision.\n\nTreat these as full handoff requests by default: \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"send this to another agent\", \"another agent\", \"another worktree\", or \"launch another agent to own this.\" Custom model or reasoning effort words such as `gpt-5.5`, `high`, or `xhigh` do not make the handoff supervised.\n\nSupervised orchestration remains available only when the user explicitly asks for supervision or coordination: \"supervise\", \"monitor\", \"wait for worker_done\", \"wait for results\", \"track completion\", \"DAG\", \"decision gate\", \"ask/reply\", or \"coordinate workers.\"\n\nDo not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Do not create a `taskId`/`dispatchId`, inject a lifecycle preamble, wait for completion, or read the worker terminal after prompt delivery except to avoid losing the initial prompt.\n\nNew top-level worktree handoff:\n\n```bash\norca worktree create --name --no-parent --agent codex --prompt \"\" --setup run --json\n```\n\nBefore creating a new worktree from an active feature branch, decide and state whether the desired Orca lineage is child or top-level. Use child worktree lineage only when the new work is conceptually stacked under or dependent on the active worktree. For independent repo-wide fixes, standalone feature work, or unrelated follow-up tasks, create a top-level worktree with `--no-parent`.\n\nExisting terminal handoff:\n\n```bash\norca terminal send --terminal --text \"\" --enter --json\n```\n\nCustom Codex model/effort handoff:\n\n`orca worktree create --agent codex --prompt ...` launches the known Codex agent but does not accept Codex-specific `--model` or `-c model_reasoning_effort=...` arguments. When the user asks for a specific Codex model or effort, create the independent worktree first, launch Codex with the requested command in that worktree, wait only for TUI readiness if prompt delivery would otherwise race startup, send the prompt, and stop.\n\nThe two-step custom-argv path cannot enforce a repository's explicit `wait-for-setup` startup policy because the later `terminal create` is not the startup owned by `worktree create`. Use it only when the repository starts agents immediately. If the repository requires `wait-for-setup`, use an agent-first configured launcher that can preserve sequencing, or stop and ask rather than silently bypassing the policy.\n\nNote: when no repo default-terminal configuration supplies a primary terminal, bare create opens a fallback shell before `terminal create` adds the agent. Configured default tabs are materialized instead and may run real commands. Prefer `--agent` whenever custom argv is not required. With the two-step path, target only the agent handle; close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell.\n\nUse the exact full `::` worktree id returned by `orca worktree create --json`; a bare repo id cannot target the new worktree.\n\n```bash\norca worktree create --name --no-parent --setup run --json\norca terminal create --worktree id: --title --command 'codex --model gpt-5.5 -c model_reasoning_effort=\"xhigh\"' --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca terminal send --terminal --text \"\" --enter --json\n```\n\nWait only for `tui-idle` when needed to avoid losing the prompt. Do not monitor task completion.\n\n`--no-parent` only controls Orca lineage; it does not choose the Git base. If the work should start from the repo default base, omit `--base-branch` so Orca uses that default, or explicitly pass the repo default base (`origin/main`, `origin/master`, or the `orca repo show --repo --json` value); never base it on the current feature branch unless the user explicitly asks for stacked work or \"branch from current\". Put current-branch context in the prompt instead.\n\n## Worker Terminals\n\nChoose the worker location before creating a terminal. `Fresh worker` means a fresh agent session, not a new git worktree. For parallel work, create one fresh agent terminal per worker in the same required worktree, falling back to the active worktree when none is named. If the task says current worktree only, depends on uncommitted files/artifacts, or must validate/PR the current branch, keep every worker in the active worktree:\n\n```bash\norca terminal create --worktree active --title --command \"codex\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nReuse an idle agent in the required worktree only if the prompt allows reuse; otherwise create a fresh terminal there. Create a new worktree only when the user explicitly requests one or a concrete checkout or filesystem conflict makes sharing unsafe or impossible; if the user did not request it, state that conflict before running `worktree create`. Independent tasks, parallel execution, convenience, or a preference for separate checkouts are not isolation requirements.\n\nWhen a new worktree is allowed, use child lineage for isolated work that is stacked under or dependent on the active worktree, and use `--no-parent` when it is not stacked. Decide the Git base separately: `--no-parent` makes the worktree top-level in Orca, while omitted `--base-branch` uses the repo default base.\n\nFor every new worktree, pass `--setup run` so any configured repository setup hook runs. This does not mean waiting for setup before agent launch: preserve the repository's startup policy, whose default starts setup and the agent side by side. Use `--setup skip` or `--setup inherit` only when there is a concrete task-specific reason, and state that reason before creating the worktree. This rule does not rerun setup for current or existing worktrees.\n\n```bash\norca worktree create --name --agent codex --setup run --json\n# or: --agent claude | omp | pi | grok | ...\n# Read from agentTerminalHandle, falling back to startupTerminal.handle.\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nFor new-worktree workers, read the id and `agentTerminalHandle` from `worktree create`, falling back to `startupTerminal.handle` for older runtimes. Use that as the sole worker handle when present; otherwise use `terminal list` to resolve the agent handle. Omit `--repo` only inside an Orca-managed worktree; otherwise pass `--repo `.\n\n**For an allowed new worktree, use agent-first:** `--agent` reveals the new worktree and launches the selected agent **in its first terminal**, without adding a separate fallback shell for that worker. Pass `--setup run`; repo setup and default-terminal settings may add intentional tabs or splits. Do **not** run bare `worktree create` and then `terminal create --command ` for the same worker when agent-first create is available: without configured default tabs, that two-step path leaves a fallback shell + agent pair. Only use it when custom agent argv is required (for example Codex model/effort flags) or when an older CLI rejects `--agent`; if you must, message only the agent handle. Configured default tabs are intentional surfaces, so close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell. Do not run `worktree create` when the task must stay in the current worktree.\n\nUse `orca worktree create --prompt ...` or `orca terminal send ...` for full handoffs or untracked/lightweight prompts. Those paths do not attach `taskId`/`dispatchId`; the worker should not send lifecycle messages unless the prompt supplies a live orchestration preamble.\n\nSidebar lineage and orchestration lifecycle are related but not identical. A same-worktree worker may appear as a peer under that worktree in the sidebar while remaining a child dispatch in orchestration state; only an actual child worktree creates visible parent/child worktree lineage.\n\nOther terminal commands coordinators often need:\n\n```bash\norca terminal list [--worktree ] [--json]\norca terminal create [--worktree ] [--title ] [--command ] [--json]\norca terminal split --terminal [--direction horizontal|vertical] [--command ] [--json]\norca terminal wait --terminal --for tui-idle --timeout-ms --json\norca terminal read --terminal --json\norca terminal send --terminal --text --enter --json\n```\n\nIf an older CLI rejects `worktree create --agent`, create the worktree normally, then run `orca terminal create --worktree --command \"codex\" --json` or `--command \"claude\"`.\n\nWait for `tui-idle` before dispatching. Always pass `--timeout-ms`; real coding tasks can take 15-60 minutes. During supervision, use rolling `check --wait` windows. If a window returns no matching message, inspect `task-list`, `terminal read`, or `terminal wait --for tui-idle` as a liveness checkpoint; if the terminal is still working or producing activity, keep waiting instead of retrying the task.\n\n## Agent Guidance\n\n- Workers with a valid live preamble must send `worker_done` exactly once from their own terminal with an explicit `--outcome succeeded` or `--outcome failed`:\n `orca orchestration send --type worker_done --subject \"\" --body \"<3-sentence summary: what you did, what you found, what's left>\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a\" --report-path \"\" --json`\n- A failed outcome is still a terminal report, but Orca records both the Dispatch and Task as failed. Never encode failure only in the subject/body.\n- After sending `worker_done`, end your turn and idle at the agent prompt. The coordinator may reuse or release this terminal after it processes your report; do not start more work, poll, or attempt to close the terminal yourself. If it reuses you, it re-engages you with a fresh preamble + TASK block delivered as new terminal input.\n- For long tasks, send heartbeat/status only when the preamble asks for it, including both IDs:\n `orca orchestration send --type heartbeat --subject \"alive\" --payload '{\"taskId\":\"\",\"dispatchId\":\"\",\"phase\":\"implementing\"}' --json`\n- If blocked before completion, use `ask`; use `escalation` only when ownership is valid and the coordinator must intervene.\n- Treat preambles inherited through terminal history or full handoffs as stale unless the current prompt explicitly keeps that coordinator in the loop.\n- Coordinators must account for every settled worker terminal before waiting again or ending the turn: immediately reuse the exact worker for a new Dispatch, explicitly retain it at the user's request with `worker-retain`, or run `worker-release`. Do not leave a completed worker live merely to inspect output; released workers remain readable through `worker-read`.\n- Coordinators should use `task-list --ready` as external memory, dispatch parallel waves, and avoid dependency chains deeper than 3-4 steps.\n\n## Example\n\n```bash\norca terminal create --worktree active --title login-css-worker --command \"claude\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration task-create --spec \"Fix the login button CSS\" --json\norca orchestration dispatch --task --to --inject --json\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\n## Next Action\n\nCoordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology. After every accepted `worker_done`, either transfer the exact terminal to an immediate follow-up Dispatch or run `worker-release` before the next wait.\n\nWorker: if the current prompt contains a live dispatch preamble, do the task, use `ask` for blocking questions, and send `worker_done` once with the required payload. If the preamble is stale or absent, do not send lifecycle messages; inspect state or treat the prompt as an ordinary handoff.\n" // Why: no current guide has bundled reference documents, so --full is byte-identical for now. // oxfmt-ignore diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 1cafa87cb95..346105d8732 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -109,6 +109,9 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'orchestration worker-read', 'orchestration worker-stop', 'orchestration worker-abandon', + 'orchestration worker-release', + 'orchestration worker-retain', + 'orchestration worker-list', 'orchestration dispatch', 'orchestration ask', 'orchestration dispatch-show', diff --git a/src/cli/handlers/orchestration.ts b/src/cli/handlers/orchestration.ts index 0b7ccdb7d6b..f9cbdb8a41a 100644 --- a/src/cli/handlers/orchestration.ts +++ b/src/cli/handlers/orchestration.ts @@ -79,6 +79,16 @@ const TASK_STATUS_VALUES = [ 'blocked' ] as const +// Why: mirrors WorkerTerminalListState (orchestration/types.ts) so a bad --terminal-state fails before the RPC. +const WORKER_TERMINAL_LIST_STATES = [ + 'active', + 'reclaimable', + 'retained', + 'release_pending', + 'release_unknown', + 'released' +] as const + type LifecycleSendRejection = { action: 'rejected' code: string @@ -422,6 +432,33 @@ function formatWorkerTranscriptMessage(message: NativeChatMessage): string { return `[${message.role}] ${blocks.join('\n')}`.trimEnd() } +type WorkerReleaseReceipt = { + dispatchId: string + state: string + reason?: string + processAction: string + archive: { source: string | null; status: string | null } | null + recovery?: string + lastError?: string +} + +function formatWorkerRelease(value: WorkerReleaseReceipt): string { + const head = `Worker ${value.dispatchId} terminal [${value.state}]` + const lines = [ + `${head}${value.reason ? ` reason=${value.reason}` : ''} process=${value.processAction}` + ] + if (value.archive) { + lines.push(`archive ${value.archive.source ?? 'none'} [${value.archive.status ?? 'unknown'}]`) + } + if (value.lastError) { + lines.push(value.lastError) + } + if (value.recovery) { + lines.push(value.recovery) + } + return lines.join('\n') +} + function safeJson(value: unknown): string { try { return JSON.stringify(value) @@ -930,6 +967,79 @@ export const ORCHESTRATION_HANDLERS: Record = { ) }, + 'orchestration worker-release': async ({ flags, client, json }) => { + const result = await callMutation( + client, + flags, + 'orchestration.workerRelease', + { dispatch: getRequiredStringFlag(flags, 'dispatch') } + ) + // Why: only an unprovable close is a failure; retained/pending/already-released are settled answers. + if (result.result.state === 'release_unknown') { + process.exitCode = 1 + } + printResult(result, json, formatWorkerRelease) + }, + + 'orchestration worker-retain': async ({ flags, client, json }) => { + const result = await callMutation( + client, + flags, + 'orchestration.workerRetain', + { dispatch: getRequiredStringFlag(flags, 'dispatch') } + ) + if (result.result.state === 'release_unknown') { + process.exitCode = 1 + } + printResult(result, json, formatWorkerRelease) + }, + + 'orchestration worker-list': async ({ flags, client, json }) => { + const terminalState = getOptionalStringFlag(flags, 'terminal-state') + if ( + terminalState && + !WORKER_TERMINAL_LIST_STATES.includes( + terminalState as (typeof WORKER_TERMINAL_LIST_STATES)[number] + ) + ) { + throw new RuntimeClientError( + 'invalid_argument', + `invalid --terminal-state '${terminalState}', expected one of: ${WORKER_TERMINAL_LIST_STATES.join(', ')}` + ) + } + const result = await client.call<{ + workers: { + dispatchId: string + taskId: string + runId: string + workerState: string + dispatchStatus: string + agentTerminalHandle: string | null + terminalState: string | null + resource: unknown + }[] + counts: Record + }>('orchestration.workerList', { + run: getOptionalStringFlag(flags, 'run'), + terminalState + }) + printResult(result, json, (r) => { + if (r.workers.length === 0) { + return 'No workers found.' + } + const rows = r.workers + .map( + (w) => + `${w.dispatchId} task=${w.taskId} [${w.workerState}] terminal=${w.terminalState ?? 'none'}` + ) + .join('\n') + const counts = Object.entries(r.counts) + .map(([state, count]) => `${state}=${count}`) + .join(' ') + return counts ? `${rows}\nTerminals: ${counts}` : rows + }) + }, + 'orchestration dispatch': async ({ flags, client, cwd, json }) => { const from = await resolveCoordinatorTerminalHandle(flags, cwd, client) const dryRun = flags.has('dry-run') ? true : undefined diff --git a/src/cli/handlers/worktree-linear-issue-link.ts b/src/cli/handlers/worktree-linear-issue-link.ts index 2285da4f01a..c8e1020d847 100644 --- a/src/cli/handlers/worktree-linear-issue-link.ts +++ b/src/cli/handlers/worktree-linear-issue-link.ts @@ -1,17 +1,15 @@ -import { parseLinearIssueInput } from '../../shared/linear-links' +import { + buildLinearIssueLinkUpdates, + LINEAR_ISSUE_LINK_CLEARED, + type LinearIssueLinkUpdates +} from '../../shared/linear-links' import { RuntimeClientError } from '../runtime-client' -type LinearIssueLinkParams = { - linkedLinearIssue: string | null - linkedLinearIssueWorkspaceId: string | null - linkedLinearIssueOrganizationUrlKey: string | null -} - export function getOptionalLinearIssueLinkFlag( flags: Map, name: string, options: { allowNull?: boolean } = {} -): LinearIssueLinkParams | undefined { +): LinearIssueLinkUpdates | undefined { const value = getPresentStringFlag(flags, name) if (value === undefined) { return undefined @@ -24,28 +22,22 @@ export function getOptionalLinearIssueLinkFlag( 'Omit --linear-issue on create, or pass a Linear issue identifier or URL.' ) } - return { - linkedLinearIssue: null, - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: null - } + return { ...LINEAR_ISSUE_LINK_CLEARED } } - const parsed = parseLinearIssueInput(value) - if (!parsed) { + // Why: the shared builder treats empty input as "clear", which is right for a + // text field the user can blank but wrong for a flag — `--linear-issue " "` + // is a mistyped argument, not a request to unlink. Only the literal `null` + // clears, and that is handled above. + const updates = value.trim() === '' ? null : buildLinearIssueLinkUpdates(value) + if (!updates) { throw new RuntimeClientError( 'invalid_argument', 'Pass a Linear issue identifier like STA-335, a Linear issue URL, or null to clear.' ) } - return { - linkedLinearIssue: parsed.identifier, - // Why: changing a link must not keep a workspace id from a previous issue. - // The org key from URLs is enough for current-resolution to safely rehydrate it. - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: parsed.organizationUrlKey ?? null - } + return updates } function getPresentStringFlag( diff --git a/src/cli/help.ts b/src/cli/help.ts index d85a318cb39..2ffa3ecd8df 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -111,6 +111,9 @@ Orchestration: orchestration worker-read Read bounded output from one supervised worker orchestration worker-stop Stop one supervised worker orchestration worker-abandon Fence an uncertain worker without claiming it stopped + orchestration worker-release Release a settled worker's terminal after archiving its output + orchestration worker-retain Keep a worker terminal live for debugging + orchestration worker-list Report worker terminal resource accounting orchestration coordinator-start Start the legacy automatic coordinator loop orchestration coordinator-stop Stop the legacy automatic coordinator loop orchestration gate-create Create a decision gate blocking a task @@ -444,6 +447,9 @@ function formatCommandFlagHelp(flag: string, commandPath: string[]): string { if (command === 'orchestration worker-read' && flag === 'cursor') { return '--cursor Opaque cursor returned by a previous worker-read page' } + if (command === 'orchestration worker-list' && flag === 'terminal-state') { + return '--terminal-state Terminal accounting filter: active, reclaimable, retained, release_pending, release_unknown, or released' + } if (command === 'linear list-issues' && flag === 'workspace') { return '--workspace Connected Linear workspace id, or all' } diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 6eb064bee28..2dad82ffdd1 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -362,6 +362,15 @@ describe('orca root help', () => { expect(logSpy.mock.calls[0][0]).toContain( 'orchestration worker-abandon Fence an uncertain worker without claiming it stopped' ) + expect(logSpy.mock.calls[0][0]).toContain( + "orchestration worker-release Release a settled worker's terminal after archiving its output" + ) + expect(logSpy.mock.calls[0][0]).toContain( + 'orchestration worker-retain Keep a worker terminal live for debugging' + ) + expect(logSpy.mock.calls[0][0]).toContain( + 'orchestration worker-list Report worker terminal resource accounting' + ) expect(callMock).not.toHaveBeenCalled() }) @@ -1236,6 +1245,9 @@ describe('orca cli worktree awareness', () => { linkedIssue: undefined, linkedLinearIssue: 'STA-335', linkedLinearIssueWorkspaceId: null, + // Why: a bare identifier carries no org, and the two scoping fields + // describe the issue being replaced. Inheriting a stale org key would + // pin the lookup to a workspace this issue does not live in. linkedLinearIssueOrganizationUrlKey: null, comment: undefined, runHooks: false, diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 2b05853e058..a8d8b2411f5 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -67,5 +67,39 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'orca orchestration worker-abandon --dispatch [--retry-request ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], notes: ['Retains all possibly-live resources and performs no process or filesystem action.'] + }, + { + path: ['orchestration', 'worker-release'], + summary: 'Release the terminal of one settled supervised worker', + usage: + 'orca orchestration worker-release --dispatch [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], + notes: [ + 'Post-completion cleanup for a settled (succeeded or failed) worker; closes only the exact coordinator-owned agent terminal of that worker.', + 'An inspectable output archive is preserved before the terminal closes, so worker-read still returns output afterwards.', + 'Never closes setup terminals, configured tabs, reused or pre-existing terminals, user-taken-over terminals, or unproven identities.', + 'Idempotent: repeating the call reports already_released. Only release_unknown exits 1; retained, release_pending, and already_released exit 0.' + ] + }, + { + path: ['orchestration', 'worker-retain'], + summary: 'Keep one supervised worker terminal live for debugging', + usage: + 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], + notes: [ + 'Records a durable user-requested exception; a later explicit worker-release clears it and releases the terminal.', + 'Performs no process or filesystem action.' + ] + }, + { + path: ['orchestration', 'worker-list'], + summary: 'List supervised worker terminal resource accounting', + usage: + 'orca orchestration worker-list [--run ] [--terminal-state ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'run', 'terminal-state'], + notes: [ + 'Terminal state is process accounting and is reported separately from Task status; a completed Task can still own a live terminal.' + ] } ] diff --git a/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts b/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts new file mode 100644 index 00000000000..14235654d37 --- /dev/null +++ b/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import type { AgentHookEventPayload } from '../../shared/agent-hook-listener' +import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' +import { createHookStatusSessionTabsInvalidator } from './hook-status-session-tabs-invalidation' + +function working( + overrides: Partial = {}, + payload: Partial = {} +): AgentHookEventPayload { + return { + paneKey: 'tab:leaf', + connectionId: null, + payload: { state: 'working', prompt: 'fix the tests', agentType: 'claude', ...payload }, + ...overrides + } +} + +describe('createHookStatusSessionTabsInvalidator', () => { + it('invalidates the first time a pane reports', () => { + const changed = createHookStatusSessionTabsInvalidator() + + expect(changed(working())).toBe(true) + }) + + it('stays quiet while the same status keeps being pinged', () => { + const changed = createHookStatusSessionTabsInvalidator() + changed(working()) + + expect(changed(working())).toBe(false) + }) + + it.each([ + ['state', { state: 'waiting' as const }], + ['prompt', { prompt: 'ship it' }], + ['agentType', { agentType: 'codex' }], + ['toolName', { toolName: 'Bash' }], + ['interactivePrompt', { interactivePrompt: '{"questions":[]}' }], + ['interrupted', { interrupted: true }] + ])('invalidates when %s changes', (_field, payload) => { + const changed = createHookStatusSessionTabsInvalidator() + changed(working()) + + expect(changed(working({}, payload))).toBe(true) + }) + + it('ignores resume-identity rows, which the provider-session path owns', () => { + const changed = createHookStatusSessionTabsInvalidator() + + expect(changed(working({ providerSessionOnly: true }))).toBe(false) + }) + + it('tracks panes independently', () => { + const changed = createHookStatusSessionTabsInvalidator() + changed(working()) + + expect(changed(working({ paneKey: 'tab:other' }))).toBe(true) + expect(changed(working())).toBe(false) + }) + + it('re-arms a forgotten pane so an identical relaunch still invalidates', () => { + const changed = createHookStatusSessionTabsInvalidator() + changed(working()) + changed.forgetPane('tab:leaf') + + expect(changed(working())).toBe(true) + }) + + it("names an SSH host's panes so a disconnect can republish each of them", () => { + const changed = createHookStatusSessionTabsInvalidator() + changed(working({ connectionId: 'conn-1' })) + changed(working({ paneKey: 'tab:remote', connectionId: 'conn-1' })) + changed(working({ paneKey: 'tab:local' })) + + expect(changed.forgetConnection('conn-1').sort()).toEqual(['tab:leaf', 'tab:remote']) + expect(changed(working({ paneKey: 'tab:local' }))).toBe(false) + }) +}) diff --git a/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts b/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts new file mode 100644 index 00000000000..59b259fa849 --- /dev/null +++ b/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts @@ -0,0 +1,52 @@ +import type { AgentHookEventPayload } from '../../shared/agent-hook-listener' +import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' + +type KnownStatus = { connectionId: string | null; payload: ParsedAgentStatusPayload } + +/** Reports whether a hook status event changed anything the `session.tabs` + * projection publishes, so a repeated same-state ping costs no snapshot rebuild. + * Mirrors `retainAgentRowSnapshot`'s change set so both carriers invalidate alike. */ +export function createHookStatusSessionTabsInvalidator(): { + (event: AgentHookEventPayload): boolean + forgetPane: (paneKey: string) => void + forgetConnection: (connectionId: string) => string[] +} { + const known = new Map() + const invalidator = (event: AgentHookEventPayload): boolean => { + // Why: resume-identity rows carry transport placeholders, not status; the + // provider-session invalidator owns their republish. + if (event.providerSessionOnly === true) { + return false + } + const previous = known.get(event.paneKey)?.payload + const next = event.payload + known.set(event.paneKey, { connectionId: event.connectionId, payload: next }) + return ( + !previous || + previous.state !== next.state || + previous.prompt !== next.prompt || + (previous.agentType ?? null) !== (next.agentType ?? null) || + (previous.toolName ?? null) !== (next.toolName ?? null) || + (previous.interactivePrompt ?? null) !== (next.interactivePrompt ?? null) || + (previous.interrupted ?? false) !== (next.interrupted ?? false) + ) + } + // Why: a cleared pane must re-arm, else the memo swallows the first event of the + // next agent when it happens to match the one that just went away. + invalidator.forgetPane = (paneKey: string): void => { + known.delete(paneKey) + } + // Why: an SSH disconnect clears a whole host's rows at once and names no pane, so + // the caller needs the pane list back to republish each affected workspace. + invalidator.forgetConnection = (connectionId: string): string[] => { + const forgotten: string[] = [] + for (const [paneKey, status] of known) { + if (status.connectionId === connectionId) { + known.delete(paneKey) + forgotten.push(paneKey) + } + } + return forgotten + } + return invalidator +} diff --git a/src/main/agent-hooks/manual-compact-hook-stream.test.ts b/src/main/agent-hooks/manual-compact-hook-stream.test.ts new file mode 100644 index 00000000000..22b1b0605c2 --- /dev/null +++ b/src/main/agent-hooks/manual-compact-hook-stream.test.ts @@ -0,0 +1,367 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { RelayAgentHookServer } from '../../relay/agent-hook-server' +import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-relay' +import { makePaneKey } from '../../shared/stable-pane-id' +import { AgentHookServer } from './server' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) + +const PANE_KEY = makePaneKey('manual-compact', '11111111-1111-4111-8111-111111111111') +const PROMPT_ID_1 = '22222222-2222-4222-8222-222222222222' +const PROMPT_ID_2 = '33333333-3333-4333-8333-333333333333' +const SESSION = { key: 'session_id' as const, id: 'session-a' } + +type ClaudeHook = { + hook_event_name: string + prompt?: string + prompt_id: string + session_id: string + trigger?: 'manual' | 'auto' + agent_id?: string + agent_type?: string +} + +function claudeHook( + hookEventName: string, + promptId: string, + extra: Partial = {} +): ClaudeHook { + return { + hook_event_name: hookEventName, + prompt_id: promptId, + session_id: 'session-a', + ...extra + } +} + +function manualEnvelope(hookEventName: string, state: 'working' | 'done') { + return { + source: 'claude' as const, + paneKey: PANE_KEY, + hasExplicitPrompt: hookEventName === 'UserPromptSubmit' ? true : undefined, + hookEventName, + providerPromptId: hookEventName === 'UserPromptSubmit' ? PROMPT_ID_2 : PROMPT_ID_1, + compactTrigger: hookEventName === 'UserPromptSubmit' ? undefined : ('manual' as const), + providerSession: SESSION, + payload: { state, prompt: 'work before compact', agentType: 'claude' as const } + } +} + +function postHook(port: number, token: string, payload: Record) { + return fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token + }, + body: JSON.stringify({ paneKey: PANE_KEY, payload }) + }) +} + +describe('manual Claude compact hook stream', () => { + const servers: { stop: () => void }[] = [] + const temporaryPaths: string[] = [] + + afterEach(() => { + for (const server of servers.splice(0)) { + server.stop() + } + for (const path of temporaryPaths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + }) + + it('settles an exact local HTTP lifecycle and rejects a duplicate completion', async () => { + const server = new AgentHookServer() + servers.push(server) + await server.start({ env: 'production' }) + const env = server.buildPtyEnv() + const events: string[] = [] + const unsubscribe = server.subscribeEnrichedStatus((event) => { + events.push(`${event.hookEventName}:${event.payload.state}`) + }) + + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' }) + ) + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('SubagentStart', PROMPT_ID_1, { + agent_id: 'compact-agent', + agent_type: 'general-purpose' + }) + ) + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('SubagentStop', PROMPT_ID_1, { + agent_id: 'compact-agent', + agent_type: 'general-purpose' + }) + ) + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + await postHook( + Number(env.ORCA_AGENT_HOOK_PORT), + env.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + + expect(events).toEqual([ + 'UserPromptSubmit:working', + 'PreCompact:working', + 'SubagentStart:working', + 'SubagentStop:working', + 'PostCompact:done' + ]) + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + state: 'done', + prompt: 'work before compact', + agentType: 'claude' + }) + ]) + unsubscribe() + }) + + it('preserves the manual identity over relay and rejects stale transport identities', async () => { + const main = new AgentHookServer() + const forwarded: AgentHookRelayEnvelope[] = [] + const emitted: string[] = [] + const connectionId = 'conn-a' + const endpointDir = mkdtempSync(join(tmpdir(), 'orca-compact-relay-')) + temporaryPaths.push(endpointDir) + const relay = new RelayAgentHookServer({ + endpointDir, + token: 'manual-compact-token', + forward: (envelope) => { + forwarded.push(envelope) + main.ingestRemote(envelope, connectionId) + } + }) + servers.push(main, relay) + const unsubscribe = main.subscribeEnrichedStatus((event) => { + emitted.push(`${event.hookEventName}:${event.payload.state}`) + }) + await relay.start({ publishEndpoint: false }) + const coordinates = relay.getCoordinates() + + await postHook( + coordinates.port, + coordinates.token, + claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' }) + ) + // A restarted relay has no prior listener cache; main still owns the status boundary. + relay.clearPaneState(PANE_KEY) + await postHook( + coordinates.port, + coordinates.token, + claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + const validPost = { + ...forwarded.at(-1)!, + hookEventName: 'PostCompact', + payload: { + state: 'done' as const, + prompt: 'work before compact', + agentType: 'claude' as const + } + } + + main.ingestRemote({ ...validPost, providerPromptId: PROMPT_ID_2 }, 'conn-a') + main.ingestRemote({ ...validPost, providerPromptId: undefined }, 'conn-a') + main.ingestRemote({ ...validPost, providerSession: undefined }, 'conn-a') + main.ingestRemote({ ...validPost, source: 'codex' }, 'conn-a') + main.ingestRemote(validPost, 'conn-b') + + expect(emitted).toEqual(['UserPromptSubmit:working', 'PreCompact:working']) + expect(main.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + prompt: 'work before compact' + }) + + await postHook( + coordinates.port, + coordinates.token, + claudeHook('SubagentStart', PROMPT_ID_1, { + agent_id: 'compact-agent', + agent_type: 'general-purpose' + }) + ) + await postHook( + coordinates.port, + coordinates.token, + claudeHook('SubagentStop', PROMPT_ID_1, { + agent_id: 'compact-agent', + agent_type: 'general-purpose' + }) + ) + await postHook( + coordinates.port, + coordinates.token, + claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + + expect(forwarded.at(-1)).toMatchObject({ + source: 'claude', + providerPromptId: PROMPT_ID_1, + compactTrigger: 'manual', + providerSession: SESSION, + hookEventName: 'PostCompact' + }) + expect(emitted.at(-1)).toBe('PostCompact:done') + expect(emitted.slice(-3)).toEqual([ + 'SubagentStart:working', + 'SubagentStop:working', + 'PostCompact:done' + ]) + expect(main.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + prompt: 'work before compact' + }) + unsubscribe() + }) + + it('invalidates a compact completion when later provider work owns the pane', () => { + const server = new AgentHookServer() + servers.push(server) + server.ingestRemote(manualEnvelope('UserPromptSubmit', 'working'), 'conn-a') + server.ingestRemote(manualEnvelope('PreCompact', 'working'), 'conn-a') + server.ingestRemote( + { + source: 'codex', + paneKey: PANE_KEY, + hookEventName: 'UserPromptSubmit', + hasExplicitPrompt: true, + payload: { state: 'working', prompt: 'new work', agentType: 'codex' } + }, + 'conn-a' + ) + server.ingestRemote({ ...manualEnvelope('PreCompact', 'working'), isReplay: true }, 'conn-a') + server.ingestRemote(manualEnvelope('PostCompact', 'done'), 'conn-a') + + expect(server.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + prompt: 'new work', + agentType: 'claude' + }) + expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({ + source: 'codex', + hookEventName: 'UserPromptSubmit' + }) + }) + + it('keeps automatic compact hooks working without settling the turn', async () => { + const main = new AgentHookServer() + const forwarded: AgentHookRelayEnvelope[] = [] + const endpointDir = mkdtempSync(join(tmpdir(), 'orca-auto-compact-relay-')) + temporaryPaths.push(endpointDir) + const relay = new RelayAgentHookServer({ + endpointDir, + forward: (envelope) => { + forwarded.push(envelope) + main.ingestRemote(envelope, 'conn-auto') + } + }) + servers.push(main, relay) + await relay.start({ publishEndpoint: false }) + const { port, token } = relay.getCoordinates() + + await postHook( + port, + token, + claudeHook('UserPromptSubmit', PROMPT_ID_1, { prompt: 'continue the task' }) + ) + await postHook(port, token, claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'auto' })) + await postHook(port, token, claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'auto' })) + + expect(forwarded.map((event) => event.hookEventName)).toEqual([ + 'UserPromptSubmit', + 'PreCompact', + 'PostCompact' + ]) + expect(main.getStatusSnapshot()[0]).toMatchObject({ state: 'working', agentType: 'claude' }) + expect(main._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({ + hookEventName: 'PostCompact', + compactTrigger: undefined + }) + }) + + it('rejects unproven compact sources at the main relay boundary', () => { + const server = new AgentHookServer() + servers.push(server) + server.ingestRemote( + { + ...manualEnvelope('PreCompact', 'working'), + source: 'kimi', + payload: { state: 'working', prompt: '', agentType: 'kimi' } + }, + 'conn-kimi' + ) + server.ingestRemote( + { ...manualEnvelope('PreCompact', 'working'), compactTrigger: undefined }, + 'conn-auto' + ) + + expect(server.getStatusSnapshot()).toEqual([]) + expect(server._getStateForTests().lastStatusByPaneKey.size).toBe(0) + }) + + it('hydrates a manual PreCompact identity and accepts only its exact local completion', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-compact-restore-')) + temporaryPaths.push(userDataPath) + const first = new AgentHookServer() + servers.push(first) + await first.start({ env: 'production', userDataPath }) + const firstEnv = first.buildPtyEnv() + await postHook( + Number(firstEnv.ORCA_AGENT_HOOK_PORT), + firstEnv.ORCA_AGENT_HOOK_TOKEN, + claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' }) + ) + await postHook( + Number(firstEnv.ORCA_AGENT_HOOK_PORT), + firstEnv.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + first.stop() + + const restored = new AgentHookServer() + servers.push(restored) + await restored.start({ env: 'production', userDataPath }) + const restoredEnv = restored.buildPtyEnv() + await postHook( + Number(restoredEnv.ORCA_AGENT_HOOK_PORT), + restoredEnv.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PostCompact', PROMPT_ID_2, { trigger: 'manual' }) + ) + expect(restored.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + + await postHook( + Number(restoredEnv.ORCA_AGENT_HOOK_PORT), + restoredEnv.ORCA_AGENT_HOOK_TOKEN, + claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' }) + ) + expect(restored.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + prompt: 'work before compact', + agentType: 'claude' + }) + }) +}) diff --git a/src/main/agent-hooks/manual-compact-status-cleanup.test.ts b/src/main/agent-hooks/manual-compact-status-cleanup.test.ts new file mode 100644 index 00000000000..71df7f2dfb3 --- /dev/null +++ b/src/main/agent-hooks/manual-compact-status-cleanup.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest' + +import { makePaneKey } from '../../shared/stable-pane-id' +import { AgentHookServer } from './server' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) + +const PANE_KEY = makePaneKey('manual-compact', '11111111-1111-4111-8111-111111111111') + +function compactEvent(hookEventName: string, state: 'working' | 'done') { + return { + source: 'claude' as const, + paneKey: PANE_KEY, + hasExplicitPrompt: hookEventName === 'UserPromptSubmit' ? true : undefined, + hookEventName, + providerPromptId: + hookEventName === 'UserPromptSubmit' + ? '22222222-2222-4222-8222-222222222222' + : '33333333-3333-4333-8333-333333333333', + compactTrigger: hookEventName === 'UserPromptSubmit' ? undefined : ('manual' as const), + providerSession: { key: 'session_id' as const, id: 'session-a' }, + payload: { state, prompt: 'work before compact', agentType: 'claude' as const } + } +} + +describe('manual compact status cleanup', () => { + it('retires authority with pane, tab, and server cleanup', () => { + const server = new AgentHookServer() + const begin = (): void => { + server.ingestRemote(compactEvent('UserPromptSubmit', 'working'), 'conn-a') + server.ingestRemote(compactEvent('PreCompact', 'working'), 'conn-a') + } + + begin() + server.clearPaneState(PANE_KEY) + server.ingestRemote(compactEvent('PostCompact', 'done'), 'conn-a') + expect(server.getStatusSnapshot()).toEqual([]) + + begin() + server.dropStatusEntriesByTabPrefix('manual-compact') + server.ingestRemote(compactEvent('PostCompact', 'done'), 'conn-a') + expect(server.getStatusSnapshot()).toEqual([]) + + server.stop() + expect(server._getStateForTests().lastStatusByPaneKey.size).toBe(0) + }) +}) diff --git a/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts b/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts index 9caf7966c83..9811773eb07 100644 --- a/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts +++ b/src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts @@ -119,6 +119,7 @@ describe('restored subagent liveness sweep', () => { try { expect(paneStatus(server)).toEqual({ state: 'working', subagents: [WORKING_CHILD] }) const previous = server.getStatusSnapshotForPane(PANE)[0] + expect(previous?.restoredUnconfirmed).toBe(true) const previousReceivedAt = previous?.receivedAt ?? 0 const reconciledAt = previousReceivedAt + 1 const now = vi.spyOn(Date, 'now').mockReturnValue(previousReceivedAt) @@ -130,6 +131,8 @@ describe('restored subagent liveness sweep', () => { receivedAt: reconciledAt, stateStartedAt: reconciledAt }) + // Why: the reconciled `done` is process-probe-verified, so it must shed the hydrated-unconfirmed marker. + expect(server.getStatusSnapshotForPane(PANE)[0]?.restoredUnconfirmed).toBeUndefined() now.mockRestore() } finally { server.stop() @@ -163,7 +166,9 @@ describe('restored subagent liveness sweep', () => { state: 'waiting', subagents: undefined, receivedAt: previous?.receivedAt, - stateStartedAt: previous?.stateStartedAt + stateStartedAt: previous?.stateStartedAt, + // Why: a still-nonterminal reconciled row remains unconfirmed — only hooks or a terminal fact confirm it. + restoredUnconfirmed: true }) } finally { server.stop() diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index b3ff89ab355..96bb121c7e7 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -7026,6 +7026,294 @@ describe('Last-status persistence', () => { } }) + it('restores hydrated nonterminal statuses as unconfirmed until a live event lands', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'may finish offline', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.ingestRemote( + { + paneKey: GOOD_PANE, + tabId: 'tab-good', + worktreeId: 'wt-1', + payload: { state: 'done', prompt: 'finished before restart', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + const listener = vi.fn() + server.setListener(listener) + expect(listener).toHaveBeenCalledWith( + expect.objectContaining({ paneKey: PANE, restoredUnconfirmed: true }) + ) + const byPane = new Map(server.getStatusSnapshot().map((entry) => [entry.paneKey, entry])) + expect(byPane.get(PANE)).toMatchObject({ state: 'working', restoredUnconfirmed: true }) + // Why: `done` is a terminal fact — no later transition can have been missed, so it restores confirmed. + expect(byPane.get(GOOD_PANE)?.restoredUnconfirmed).toBeUndefined() + + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'done', prompt: 'confirmed live', agentType: 'codex' } + }, + 'conn-1' + ) + const confirmed = server.getStatusSnapshot().find((entry) => entry.paneKey === PANE) + expect(confirmed).toMatchObject({ + state: 'done', + prompt: 'confirmed live', + agentType: 'codex' + }) + expect(confirmed?.restoredUnconfirmed).toBeUndefined() + } finally { + server.stop() + } + }) + + it('lets an identical live OSC observation confirm a hydrated row', async () => { + const payload = { + state: 'working' as const, + prompt: 'still running', + agentType: 'claude' as const + } + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + payload + }) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + const restored = server.getStatusSnapshot()[0] + if (!restored) { + throw new Error('expected hydrated status') + } + expect(restored?.restoredUnconfirmed).toBe(true) + vi.spyOn(Date, 'now').mockReturnValue(restored.receivedAt - 1_000) + server.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + payload + }) + const confirmed = server.getStatusSnapshot()[0] + expect(confirmed?.restoredUnconfirmed).toBeUndefined() + expect(confirmed?.receivedAt).toBe(restored.receivedAt + 1) + } finally { + server.stop() + } + }) + + it('does not let a hydrated Claude permission suppress the first live working event', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PermissionRequest', + payload: { + state: 'waiting', + prompt: 'review command', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'dangerous command' + } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PreToolUse', + payload: { + state: 'working', + prompt: 'review command', + agentType: 'claude', + toolName: 'Read', + toolInput: 'package.json' + } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + toolName: 'Read' + }) + expect(server.getStatusSnapshot()[0]?.restoredUnconfirmed).toBeUndefined() + } finally { + server.stop() + } + }) + + it('does not inherit a stale tool id from hydrated Claude progress', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PreToolUse', + toolUseId: 'tool-old', + toolAgentType: 'main', + payload: { + state: 'working', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PermissionRequest', + toolAgentType: 'main', + payload: { + state: 'waiting', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'PostToolUse', + toolUseId: 'tool-new', + toolAgentType: 'main', + payload: { + state: 'working', + prompt: 'run tests', + agentType: 'claude', + toolName: 'Bash', + toolInput: 'pnpm test' + } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + } finally { + server.stop() + } + }) + + it('never persists the unconfirmed flag and re-stamps it on every hydrate', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'still running', agentType: 'claude' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const secondServer = new AgentHookServer() + await secondServer.start({ env: 'production', userDataPath }) + secondServer.flushStatusPersistSync() + secondServer.stop() + expect(readFileSync(lastStatusPath(), 'utf8')).not.toContain('restoredUnconfirmed') + + const thirdServer = new AgentHookServer() + await thirdServer.start({ env: 'production', userDataPath }) + try { + expect(thirdServer.getStatusSnapshot()).toEqual([ + expect.objectContaining({ paneKey: PANE, state: 'working', restoredUnconfirmed: true }) + ]) + } finally { + thirdServer.stop() + } + }) + + it('refuses interrupt inference on an unconfirmed hydrated row', async () => { + const firstServer = new AgentHookServer() + await firstServer.start({ env: 'production', userDataPath }) + firstServer.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'long task', agentType: 'codex' } + }, + 'conn-1' + ) + firstServer.flushStatusPersistSync() + firstServer.stop() + + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + const baseline = server.getStatusSnapshot()[0] + expect(baseline).toMatchObject({ paneKey: PANE, restoredUnconfirmed: true }) + const applied = server.inferInterrupt({ + paneKey: PANE, + baselineUpdatedAt: baseline.receivedAt, + baselineStateStartedAt: baseline.stateStartedAt, + baselinePrompt: 'long task', + baselineAgentType: 'codex', + intent: 'plain-escape' + }) + // Why: synthesizing `done` onto a never-confirmed `working` would fabricate a transition from stale disk state. + expect(applied).toBe(false) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + expect(server.getStatusSnapshot()[0]?.interrupted).toBeUndefined() + } finally { + server.stop() + } + }) + it('keeps SSH status ordering monotonic across hydration and clock rollback', async () => { const now = 1_700_000_000_000 vi.spyOn(Date, 'now').mockReturnValue(now) diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 0f99f2cae9d..0f9e0a7812d 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -22,11 +22,14 @@ import { markCodexLeadTurnInterrupted, MAX_PANE_KEY_LEN, movePaneCacheState, + canAcceptClaudeCompactTransition, + normalizeClaudePromptId, normalizeHookPayload, parseFormEncodedBody, readRequestBody, reapRestoredClaudeSubagentsForDeadPane, reconcileRemoteCodexState, + resolveCachedClaudeCompactOwnership, resolveHookSource, preparePendingGrokResultDiscovery, seedClaudeSubagentRosterFromSnapshots, @@ -41,7 +44,11 @@ import { claudeRosterHasWorkingSubagent, claudeRosterToSnapshots } from '../../shared/claude-subagent-roster' -import { restoreShedStatusFields, type AgentHookSource } from '../../shared/agent-hook-relay' +import { + isAgentHookSource, + restoreShedStatusFields, + type AgentHookSource +} from '../../shared/agent-hook-relay' import { CLAUDE_STATUSLINE_PATHNAME, parseClaudeStatusLineBody, @@ -83,6 +90,8 @@ export type { AgentHookSource } type EnrichedAgentHookEventPayload = AgentHookEventPayload & { receivedAt: number stateStartedAt: number + /** Stamped at hydrate for nonterminal states; never persisted (hydrate re-stamps) and cleared by any accepted live event replacing the entry. */ + restoredUnconfirmed?: true } type NormalizedLocalHook = { @@ -92,7 +101,7 @@ type NormalizedLocalHook = { type PersistedAgentHookEventPayload = Omit< EnrichedAgentHookEventPayload, - 'claudeRunningNonAgentTask' | 'launchToken' | 'promptInteractionKey' + 'claudeRunningNonAgentTask' | 'launchToken' | 'promptInteractionKey' | 'restoredUnconfirmed' > & { launchTokenHash?: string } @@ -291,13 +300,23 @@ function sanitizeHydratedEntry( if (providerSessionOnly && !isValidPiProviderSessionOnly(providerSession, payload.agentType)) { return null } + const source = isAgentHookSource(record.source) ? record.source : undefined + const providerPromptId = + source === 'claude' ? normalizeClaudePromptId(record.providerPromptId) : undefined + const compactTrigger = + source === 'claude' && (record.compactTrigger === 'manual' || record.compactTrigger === 'auto') + ? record.compactTrigger + : undefined return { paneKey, + source, tabId: typeof tabId === 'string' ? tabId : undefined, worktreeId: typeof worktreeId === 'string' ? worktreeId : undefined, connectionId, hasExplicitPrompt: record.hasExplicitPrompt === true ? true : undefined, hookEventName: typeof record.hookEventName === 'string' ? record.hookEventName : undefined, + providerPromptId, + compactTrigger, toolUseId: typeof record.toolUseId === 'string' ? record.toolUseId : undefined, toolAgentId: typeof record.toolAgentId === 'string' ? record.toolAgentId : undefined, toolAgentType: typeof record.toolAgentType === 'string' ? record.toolAgentType : undefined, @@ -378,6 +397,7 @@ function toAgentStatusIpcPayload(entry: EnrichedAgentHookEventPayload): AgentSta ...(entry.providerSession ? { providerSession: entry.providerSession } : {}), ...(entry.providerSessionOnly ? { providerSessionOnly: true } : {}), ...(entry.promptInteractionKey ? { promptInteractionKey: entry.promptInteractionKey } : {}), + ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...entry.payload } } @@ -434,6 +454,9 @@ function shouldKeepClaudePermissionVisible( previous: EnrichedAgentHookEventPayload | undefined, next: AgentHookEventPayload ): boolean { + if (previous?.restoredUnconfirmed) { + return false + } if ( previous?.payload.agentType !== 'claude' || previous.payload.state !== 'waiting' || @@ -507,6 +530,7 @@ function shouldInheritClaudeToolUseIdForPermission( next: AgentHookEventPayload ): boolean { if ( + previous?.restoredUnconfirmed || previous?.payload.agentType !== 'claude' || previous.payload.state !== 'working' || previous.hookEventName !== 'PreToolUse' || @@ -563,6 +587,7 @@ export class AgentHookServer { private onAgentStatus: ((payload: EnrichedAgentHookEventPayload) => void) | null = null private onClaudeStatusLine: ((event: ClaudeStatusLineRateLimits) => void) | null = null private onPaneStatusCleared: PaneStatusClearListener | null = null + private paneStatusClearListeners = new Set() private statusChangeListeners = new Set() private providerSessionChangeListeners = new Set() // Why: setListener is a single slot owned by the main-window fanout; the @@ -647,6 +672,29 @@ export class AgentHookServer { this.onPaneStatusCleared = listener } + /** Multi-subscriber tap on pane status clears. Unlike `setPaneStatusClearListener` + * (a single slot the main window owns and drops on close) this survives window + * teardown and exists at all under headless serve, which never opens one. */ + subscribePaneStatusClear(listener: PaneStatusClearListener): () => void { + this.paneStatusClearListeners.add(listener) + return () => { + this.paneStatusClearListeners.delete(listener) + } + } + + private emitPaneStatusCleared(clear: AgentStatusClearIpcPayload): void { + this.onPaneStatusCleared?.(clear) + for (const listener of this.paneStatusClearListeners) { + // Why: callers are pane/connection teardown paths; one throwing subscriber must + // not strand the rest, matching every other fan-out here. + try { + listener(clear) + } catch (err) { + console.error('[agent-hooks] pane-status-clear listener threw', err) + } + } + } + /** Snapshot of cached statuses in IPC shape. Used by `agentStatus:getSnapshot` after tabs hydrate so the * dashboard catches up on hook events that fired during startup. */ getStatusSnapshot(): AgentStatusIpcPayload[] { @@ -728,6 +776,10 @@ export class AgentHookServer { if (existing.providerSessionOnly) { return false } + // Why: inference must not fabricate a `done` onto a row whose `working` was never confirmed this runtime. + if (existing.restoredUnconfirmed) { + return false + } const payload = existing.payload const agentType: AgentType | undefined = payload.agentType // Why: Droid's Ctrl+C exits the CLI (handled by PTY lifecycle) rather than interrupting the current turn. @@ -816,6 +868,10 @@ export class AgentHookServer { if (!existing) { return false } + // Why: inference must not fabricate a transition onto a row whose state was never confirmed this runtime. + if (existing.restoredUnconfirmed) { + return false + } const payload = existing.payload // Why: only Claude's interactive question clears on typed input — tool name (not hook event) discriminates; real permission waits stay sticky. if ( @@ -1069,8 +1125,13 @@ export class AgentHookServer { const connectionClearWatermark = payload.connectionId ? this.connectionTimestampWatermarkById.get(payload.connectionId) : undefined - // Why: Date.now() can repeat across reconnect; a remote replay must sort strictly after its connection's transient clear. - const now = Math.max(Date.now(), (connectionClearWatermark ?? -1) + 1) + // Why: renderer ordering rejects older rows; live evidence must sort after reconnect clears and restored rows across clock rollback. + const restoredStatusWatermark = previous?.restoredUnconfirmed ? previous.receivedAt : undefined + const now = Math.max( + Date.now(), + (connectionClearWatermark ?? -1) + 1, + (restoredStatusWatermark ?? -1) + 1 + ) if (payload.connectionId) { this.connectionTimestampWatermarkById.set(payload.connectionId, now) } @@ -1128,7 +1189,8 @@ export class AgentHookServer { ? { agentType: previous.payload.agentType, state: previous.payload.state, - updatedAt: previous.receivedAt + updatedAt: previous.receivedAt, + restoredUnconfirmed: previous.restoredUnconfirmed } : undefined, incoming: rootContextPreservingPayload.payload.agentType, @@ -1191,7 +1253,8 @@ export class AgentHookServer { if (!identity.inheritedFromActivePane) { this.maybeTrackAgentPromptSent(effectivePayload, previous) } - const enriched = this.attachStatusTiming(effectivePayload, now) + const cachedPayload = resolveCachedClaudeCompactOwnership(previous, effectivePayload) + const enriched = this.attachStatusTiming(cachedPayload, now) this.runtimeObservedStatusPaneKeys.add(enriched.paneKey) this.state.lastStatusByPaneKey.set(enriched.paneKey, enriched) this.scheduleStatusPersist() @@ -1612,7 +1675,7 @@ export class AgentHookServer { this.scheduleStatusPersist() this.notifyStatusChangeListeners() for (const paneKey of clearedStatusPaneKeys) { - this.onPaneStatusCleared?.({ paneKey }) + this.emitPaneStatusCleared({ paneKey }) } } } @@ -1740,6 +1803,7 @@ export class AgentHookServer { | EnrichedAgentHookEventPayload | undefined if ( + !previous?.restoredUnconfirmed && previous?.connectionId === connectionId && previous.tabId === tabId && previous.worktreeId === worktreeId && @@ -1788,6 +1852,9 @@ export class AgentHookServer { hasExplicitPrompt?: boolean promptInteractionKey?: string hookEventName?: string + source?: unknown + providerPromptId?: unknown + compactTrigger?: unknown toolUseId?: string toolAgentId?: string toolAgentType?: string @@ -1849,6 +1916,14 @@ export class AgentHookServer { typeof envelope.hookEventName === 'string' && envelope.hookEventName.trim().length > 0 ? envelope.hookEventName.trim() : undefined + const source = isAgentHookSource(envelope.source) ? envelope.source : undefined + const providerPromptId = + source === 'claude' ? normalizeClaudePromptId(envelope.providerPromptId) : undefined + const compactTrigger = + source === 'claude' && + (envelope.compactTrigger === 'manual' || envelope.compactTrigger === 'auto') + ? envelope.compactTrigger + : undefined const statusDisposition = this.getAgentStatusDisposition(paneKey, { hookEventName, isReplay: envelope.isReplay === true @@ -1884,11 +1959,50 @@ export class AgentHookServer { return } // Why: restore a shed roster only when its digest and turn identity still match the cache. - const normalizedPayload = restoreShedStatusFields( + let normalizedPayload = restoreShedStatusFields( validatedPayload, envelope.shedFields, this.state.lastStatusByPaneKey.get(paneKey)?.payload ) + const previousStatus = this.state.lastStatusByPaneKey.get(paneKey) + if (hookEventName === 'PreCompact' || hookEventName === 'PostCompact') { + if ( + source !== 'claude' || + compactTrigger === undefined || + normalizedPayload.agentType !== source + ) { + return + } + if ( + hookEventName === 'PreCompact' && + envelope.isReplay === true && + (previousStatus?.hookEventName !== 'PreCompact' || + previousStatus.compactTrigger !== compactTrigger || + previousStatus.providerPromptId !== providerPromptId) + ) { + return + } + if ( + !canAcceptClaudeCompactTransition(previousStatus, { + source, + connectionId: trimmedConnectionId, + hookEventName, + providerPromptId, + compactTrigger, + providerSession + }) + ) { + return + } + } + if ( + source === 'claude' && + compactTrigger !== undefined && + normalizedPayload.prompt.length === 0 && + previousStatus?.payload.prompt + ) { + normalizedPayload = { ...normalizedPayload, prompt: previousStatus.payload.prompt } + } if ( envelope.providerSessionOnly === true && !isValidPiProviderSessionOnly(providerSession, normalizedPayload.agentType) @@ -1908,6 +2022,7 @@ export class AgentHookServer { }) const event: AgentHookEventPayload = { paneKey, + source, launchToken: statusDisposition === 'restart' ? undefined : envelope.launchToken, tabId, worktreeId, @@ -1915,6 +2030,8 @@ export class AgentHookServer { hasExplicitPrompt: envelope.hasExplicitPrompt === true ? true : undefined, promptInteractionKey, hookEventName, + providerPromptId, + compactTrigger, toolUseId, toolAgentId, toolAgentType, @@ -2155,7 +2272,7 @@ export class AgentHookServer { this.notifyStatusChangeListeners() } // Why: always send the cutoff even with no matched entry — another host may have overwritten this pane's row. - this.onPaneStatusCleared?.({ + this.emitPaneStatusCleared({ transient: true, connectionId: normalizedConnectionId, clearedAt @@ -2297,7 +2414,7 @@ export class AgentHookServer { this.runtimeObservedStatusPaneKeys.delete(resolvedPaneKey) this.scheduleStatusPersist() this.notifyStatusChangeListeners() - this.onPaneStatusCleared?.({ paneKey: resolvedPaneKey }) + this.emitPaneStatusCleared({ paneKey: resolvedPaneKey }) } } @@ -2371,8 +2488,12 @@ export class AgentHookServer { const reconciledAt = stateChanged ? Math.max(Date.now(), enriched.receivedAt + 1) : enriched.receivedAt + // Why: a reconciled `done` is process-probe-verified, not hydrated guesswork — carrying + // restoredUnconfirmed onto it would make freshness gates suppress a legitimate completion. + const { restoredUnconfirmed, ...reconciledBase } = enriched const reconciled: EnrichedAgentHookEventPayload = { - ...enriched, + ...reconciledBase, + ...(state !== 'done' && restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), receivedAt: reconciledAt, stateStartedAt: stateChanged ? reconciledAt : enriched.stateStartedAt, payload: { ...enriched.payload, state, subagents } @@ -2505,6 +2626,10 @@ export class AgentHookServer { (entry.payload.subagents?.length ?? 0) - (hydratedPayload.subagents?.length ?? 0) entry.payload = hydratedPayload } + if (entry.payload.state !== 'done') { + // Why: the terminal transition may have fired while no receiver was up; restore as unconfirmed, never as live truth. + entry.restoredUnconfirmed = true + } this.state.lastStatusByPaneKey.set(resolvedPaneKey, entry) if (entry.connectionId) { // Why: a restart can see an earlier wall clock; seed ordering so new events stay after disk state. @@ -2621,6 +2746,8 @@ export class AgentHookServer { const { claudeRunningNonAgentTask: _claudeRunningNonAgentTask, promptInteractionKey: _promptInteractionKey, + // Why: never persisted — hydrate re-stamps it, so a stored copy could only drift. + restoredUnconfirmed: _restoredUnconfirmed, launchToken, ...persistedPayload } = payload as EnrichedAgentHookEventPayload diff --git a/src/main/attribution/terminal-attribution-path-env-casing.test.ts b/src/main/attribution/terminal-attribution-path-env-casing.test.ts new file mode 100644 index 00000000000..95ff6fdc2e3 --- /dev/null +++ b/src/main/attribution/terminal-attribution-path-env-casing.test.ts @@ -0,0 +1,169 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { applyTerminalAttributionEnv } from './terminal-attribution' + +describe('applyTerminalAttributionEnv PATH key casing', () => { + let tmpRoot: string | null = null + + afterEach(() => { + if (tmpRoot) { + rmSync(tmpRoot, { force: true, recursive: true }) + tmpRoot = null + } + }) + + function makeTmpRoot(): string { + tmpRoot = mkdtempSync(join(tmpdir(), 'orca-attribution-path-casing-')) + return tmpRoot + } + + // Why: a Windows child that inherits both spellings crashes the packaged orca.exe launcher + // with "Item has already been added. Key in dictionary: 'PATH'" (stablyai/orca#12046). + function pathEnvKeys(env: Record): string[] { + return Object.keys(env).filter((key) => /^path$/i.test(key)) + } + + it('writes back the inherited Windows `Path` spelling instead of adding `PATH`', () => { + const root = makeTmpRoot() + const userDataPath = join(root, 'user-data') + const baseEnv: Record = { + Path: 'C:\\Windows\\system32;C:\\Program Files\\Git\\cmd', + SystemRoot: 'C:\\Windows' + } + + applyTerminalAttributionEnv(baseEnv, { + enabled: true, + platform: 'win32', + shellFamily: 'native-windows', + userDataPath + }) + + const win32Dir = join(userDataPath, 'orca-terminal-attribution', 'win32') + const pathEntries = baseEnv.Path.split(';') + + expect(pathEnvKeys(baseEnv)).toEqual(['Path']) + expect(pathEntries[0]).toBe(win32Dir) + expect(pathEntries).toContain('C:\\Program Files\\Git\\cmd') + }) + + // Why: Win32 resolves a duplicated variable by taking the first match in the block, so the + // shim must land on the first-listed spelling and the shadowed one must keep its value — + // dropping it would promote it the moment anything downstream removes the live key. + it.each([ + { first: 'PATH', second: 'Path' }, + { first: 'Path', second: 'PATH' } + ])( + 'prepends the shim onto the first-listed `$first` and leaves `$second` untouched', + ({ first, second }) => { + const root = makeTmpRoot() + const userDataPath = join(root, 'user-data') + const baseEnv: Record = { + [first]: 'C:\\tools\\bin;C:\\Windows\\system32', + [second]: 'C:\\Windows\\system32' + } + + applyTerminalAttributionEnv(baseEnv, { + enabled: true, + platform: 'win32', + shellFamily: 'native-windows', + userDataPath + }) + + const win32Dir = join(userDataPath, 'orca-terminal-attribution', 'win32') + expect(baseEnv[first].split(';')).toEqual([ + win32Dir, + 'C:\\tools\\bin', + 'C:\\Windows\\system32' + ]) + expect(baseEnv[second]).toBe('C:\\Windows\\system32') + } + ) + + it('keeps a shadowed duplicate when the live spelling strips down to nothing', () => { + const root = makeTmpRoot() + const userDataPath = join(root, 'user-data') + const shimDir = join(userDataPath, 'orca-terminal-attribution', 'win32') + const baseEnv: Record = { Path: shimDir, PATH: 'C:\\Windows\\system32' } + + applyTerminalAttributionEnv(baseEnv, { + enabled: false, + platform: 'win32', + shellFamily: 'native-windows', + userDataPath + }) + + expect(pathEnvKeys(baseEnv)).toEqual(['PATH']) + expect(baseEnv.PATH).toBe('C:\\Windows\\system32') + }) + + it('strips shim entries from the inherited `Path` when attribution is disabled', () => { + const root = makeTmpRoot() + const userDataPath = join(root, 'user-data') + const shimDir = join(userDataPath, 'orca-terminal-attribution', 'win32') + const baseEnv: Record = { Path: `${shimDir};C:\\Windows\\system32` } + + applyTerminalAttributionEnv(baseEnv, { + enabled: false, + platform: 'win32', + shellFamily: 'native-windows', + userDataPath + }) + + expect(pathEnvKeys(baseEnv)).toEqual(['Path']) + expect(baseEnv.Path).toBe('C:\\Windows\\system32') + }) + + // Why: the daemon receives a sparse env patch with no path key and re-merges its own block + // underneath it, so guessing the spelling here hands the child both. + it.each([ + { hostKey: 'PATH', otherKey: 'Path' }, + { hostKey: 'Path', otherKey: 'PATH' } + ])('adopts a host block spelt `$hostKey` on a path-less env', ({ hostKey, otherKey }) => { + const root = makeTmpRoot() + const userDataPath = join(root, 'user-data') + const inherited = { PATH: process.env.PATH, Path: process.env.Path } + delete process.env.PATH + delete process.env.Path + process.env[hostKey] = 'C:\\Windows\\system32' + + try { + const baseEnv: Record = { SystemRoot: 'C:\\Windows' } + + applyTerminalAttributionEnv(baseEnv, { + enabled: true, + platform: 'win32', + shellFamily: 'native-windows', + userDataPath + }) + + expect(pathEnvKeys(baseEnv)).toEqual([hostKey]) + expect(baseEnv[otherKey]).toBeUndefined() + } finally { + delete process.env[hostKey] + for (const [key, value] of Object.entries(inherited)) { + if (value !== undefined) { + process.env[key] = value + } + } + } + }) + + it('leaves a case-sensitive POSIX `Path` variable alone', () => { + const root = makeTmpRoot() + const baseEnv: Record = { + PATH: '/usr/bin:/bin', + Path: '/decoy' + } + + applyTerminalAttributionEnv(baseEnv, { + enabled: true, + platform: 'linux', + userDataPath: join(root, 'user-data') + }) + + expect(baseEnv.Path).toBe('/decoy') + expect(baseEnv.PATH.split(':')).toContain('/usr/bin') + }) +}) diff --git a/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts b/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts new file mode 100644 index 00000000000..810322a53c9 --- /dev/null +++ b/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts @@ -0,0 +1,100 @@ +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { applyTerminalAttributionEnv } from './terminal-attribution' + +// Why (#12046 follow-up): `powershell.exe -File