Merge branch 'main' of https://github.com/stablyai/orca into stop-keep-reconnecting-to-remote

This commit is contained in:
Jinjing
2026-08-03 22:38:47 -07:00
814 changed files with 68710 additions and 7584 deletions
+84 -9
View File
@@ -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."
+14 -1
View File
@@ -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(" • (?<n>[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
+2 -3
View File
@@ -238,10 +238,9 @@ Pair with your desktop app to monitor and steer your agents from your phone.
- **Discord:** Join the community on **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X:** Follow **[@orca_build](https://x.com/orca_build)** for updates and announcements.
- **WeChat:** If group 5 is full, you can join group 6.
- **WeChat:** Scan to join the Orca community WeChat group 7.
<img src="docs/assets/wechat-qr.jpg" alt="WeChat group 5 QR code for the Orca community" width="160" style="margin-right: 16px;" />
<img src="docs/assets/wechat-qr-group6.jpg" alt="WeChat group 6 QR code for the Orca community" width="160" />
<img src="docs/assets/wechat-qr-group7.jpg" alt="WeChat group 7 QR code for the Orca community" width="160" />
- **Feedback &amp; Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues).
- **Privacy:** See the [privacy &amp; telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out.
+71 -20
View File
@@ -44,6 +44,14 @@ const PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM = {
linux: 'watcher-linux',
win32: 'watcher-win32'
}
const ELECTRON_ARCHITECTURE_BY_ENUM = {
0: 'ia32',
1: 'x64',
2: 'arm',
3: 'arm64',
4: 'universal'
}
const PACKAGED_NATIVE_ARCHITECTURES = new Set(['ia32', 'x64', 'arm', 'arm64'])
const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/
const VERSIONED_ONNXRUNTIME_DYLIB_RE = /^libonnxruntime\.\d[\d.]*\.dylib$/
@@ -170,7 +178,7 @@ function collectPackagedRuntimePackages(electronPlatformName = process.platform)
// optionalDependency (e.g. @parcel/watcher-linux-x64-glibc) that the
// dependencies graph above never reaches. Include the ones installed for the
// build's supported architectures; afterPack pruning trims non-target
// platforms. Without this the packaged main bundle's import of
// platform/architecture variants. Without this the packaged main bundle's import of
// '@parcel/watcher' resolves at runtime but throws loading its binary.
const parcelWatcherDir = packages.get('@parcel/watcher')
if (parcelWatcherDir) {
@@ -246,13 +254,44 @@ function verifyPackagedMainRuntimeDeps(resourcesDir, asar = require('@electron/a
}
function normalizeNodePtyWindowsArch(electronArch) {
if (electronArch === 'x64' || electronArch === 1) {
return 'x64'
const architecture = normalizeElectronArchitecture(electronArch)
if (architecture !== 'x64' && architecture !== 'arm64') {
throw new Error(`Unsupported packaged node-pty Windows architecture: ${architecture}`)
}
if (electronArch === 'arm64' || electronArch === 3) {
return 'arm64'
return architecture
}
function normalizeElectronArchitecture(electronArch) {
const architecture =
typeof electronArch === 'number'
? ELECTRON_ARCHITECTURE_BY_ENUM[electronArch]
: electronArch === 'armv7l'
? 'arm'
: electronArch
if (!PACKAGED_NATIVE_ARCHITECTURES.has(architecture)) {
throw new Error(`Unsupported packaged runtime architecture: ${String(electronArch)}`)
}
return architecture
}
function pruneNodePtyNativeDirectories(directory, platformPrefix, electronArch, allowsSuffix) {
if (!existsSync(directory)) {
return
}
const architecture = normalizeElectronArchitecture(electronArch)
const targetPrefix = `${platformPrefix}${architecture}`
const platformPrefixes = Object.values(NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM)
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (!entry.isDirectory() || !platformPrefixes.some((prefix) => entry.name.startsWith(prefix))) {
continue
}
const matchesTarget =
entry.name.startsWith(platformPrefix) &&
(entry.name === targetPrefix || (allowsSuffix && entry.name.startsWith(`${targetPrefix}-`)))
if (!matchesTarget) {
rmSync(join(directory, entry.name), { recursive: true, force: true })
}
}
return process.arch === 'arm64' ? 'arm64' : 'x64'
}
function findNodePtyConptySourceDir(nodePtyDir, windowsArch) {
@@ -308,14 +347,19 @@ function prunePackagedNodePty(resourcesDir, electronPlatformName, electronArch)
const allowedPrebuildPrefix = NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM[electronPlatformName]
if (allowedPrebuildPrefix) {
const prebuildsDir = join(nodePtyDir, 'prebuilds')
if (existsSync(prebuildsDir)) {
for (const entry of readdirSync(prebuildsDir, { withFileTypes: true })) {
if (entry.isDirectory() && !entry.name.startsWith(allowedPrebuildPrefix)) {
rmSync(join(prebuildsDir, entry.name), { recursive: true, force: true })
}
}
}
pruneNodePtyNativeDirectories(
join(nodePtyDir, 'prebuilds'),
allowedPrebuildPrefix,
electronArch,
false
)
// Why: sequential cross-arch rebuilds accumulate ABI-tagged outputs here.
pruneNodePtyNativeDirectories(
join(nodePtyDir, 'bin'),
allowedPrebuildPrefix,
electronArch,
true
)
}
if (electronPlatformName === 'win32') {
@@ -328,7 +372,7 @@ function prunePackagedNodePty(resourcesDir, electronPlatformName, electronArch)
}
}
function prunePackagedParcelWatcher(resourcesDir, electronPlatformName) {
function prunePackagedParcelWatcher(resourcesDir, electronPlatformName, electronArch) {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
if (!existsSync(parcelDir)) {
return
@@ -336,9 +380,11 @@ function prunePackagedParcelWatcher(resourcesDir, electronPlatformName) {
// Why: we package every installed @parcel/watcher-<platform> optional
// subpackage (supportedArchitectures fetches all), but each build only needs
// its own platform's binary. Keep the core package and the matching platform
// subpackages; drop the rest so a Linux serve doesn't ship macOS/Windows .node.
// its own platform/architecture binaries. Keep the core package and matching
// native variants; drop the rest.
const keepPrefix = PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM[electronPlatformName]
const architecture = normalizeElectronArchitecture(electronArch)
const targetPrefix = keepPrefix ? `${keepPrefix}-${architecture}` : null
for (const entry of readdirSync(parcelDir, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === 'watcher') {
continue
@@ -348,7 +394,11 @@ function prunePackagedParcelWatcher(resourcesDir, electronPlatformName) {
if (!entry.name.startsWith('watcher-')) {
continue
}
if (keepPrefix && entry.name.startsWith(keepPrefix)) {
if (
keepPrefix &&
entry.name.startsWith(keepPrefix) &&
(entry.name === targetPrefix || entry.name.startsWith(`${targetPrefix}-`))
) {
continue
}
rmSync(join(parcelDir, entry.name), { recursive: true, force: true })
@@ -395,8 +445,9 @@ function prunePackagedZodSources(resourcesDir) {
}
function prunePackagedRuntimeNodeModules(resourcesDir, electronPlatformName, electronArch) {
prunePackagedNodePty(resourcesDir, electronPlatformName, electronArch)
prunePackagedParcelWatcher(resourcesDir, electronPlatformName)
const architecture = normalizeElectronArchitecture(electronArch)
prunePackagedNodePty(resourcesDir, electronPlatformName, architecture)
prunePackagedParcelWatcher(resourcesDir, electronPlatformName, architecture)
prunePackagedRuntimeTypeDeclarations(resourcesDir)
prunePackagedSherpaOnnx(resourcesDir, electronPlatformName)
prunePackagedZodSources(resourcesDir)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+471 -32
View File
@@ -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": [
@@ -2114,31 +2344,47 @@
"maturity": "experimental",
"protection": "partial",
"owner": "agent-session",
"layer": "renderer-state",
"layer": "cross-boundary",
"surfaces": [
"agent launch",
"workspace activation",
"sleep and hibernate restore",
"provider session dedupe",
"sidebar and mobile identity"
"sidebar and mobile identity",
"runtime-owned background PTY mount and remount"
],
"platforms": ["macos", "linux", "windows"],
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos"],
"coveredProviders": [],
"coverageNotes": "Local macOS evidence over the ownership/dedupe suite on main@1282f5c2d. Queued/pending resume-claim indexing, same-session and wrong-session hook proofs, and Electron repeat-activation coverage arrive with the pending stack (#7008).",
"coveredProviders": ["local", "daemon", "remote-runtime"],
"coverageNotes": "Renderer ownership/dedupe contracts cover provider-session claims. Local and daemon attach-only contracts prove an existing stable-pane owner is adopted without provider creation, while remote-runtime transport contracts preserve adopted ownership through cancellation. The Electron oracle covers a local macOS runtime and daemon with real agent, Setup, and unrelated-canary processes; SSH, WSL, paired-server, Linux, and Windows remain contract-only or unrun.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/6800",
"https://github.com/stablyai/orca/pull/5240",
"https://github.com/stablyai/orca/pull/6411",
"https://github.com/stablyai/orca/pull/6833"
"https://github.com/stablyai/orca/pull/6833",
"https://github.com/stablyai/orca/pull/11789",
"https://github.com/stablyai/orca/pull/11819"
],
"invariant": "Workspace activation, launch, restore, sleep, hibernate, dedupe, clearing, and reconnect code must not replay or resume a provider session id already owned, queued, pending, or live in that workspace.",
"oracle": "The current renderer-state slice asserts provider-session claim keys are owned by preserved active tabs, inactive split leaves, visible non-focused split groups, live records, quit records, worktree-sleep records, queued startup payloads, time-bounded resume bridge claims, and same-session live hook evidence; duplicates clear without launching a second resume command. The provider list is the risk scope, not proof that every provider has a live integration gate.",
"invariant": "Workspace activation, launch, restore, sleep, hibernate, dedupe, clearing, mount, remount, and reconnect code must not replay or resume a provider session id already owned, queued, pending, live, or durably bound to a host PTY in that workspace. A renderer with missing projection state must adopt the exact runtime-owned PTY for the original tab and leaf rather than create a replacement.",
"oracle": "Renderer-state tests assert provider-session ownership across preserved and queued panes. Main/provider contracts assert atomic attach-only adoption, stable host/worktree/tab/leaf identity, no fresh spawn on adoption, and safe paired-runtime cancellation. The Electron oracle creates inactive runtime-owned Codex and Setup PTYs plus an unrelated canary, seeds an exact resumable provider session, removes only the target renderer projections, and activates the workspace. It requires byte-stable handle, PTY, incarnation, tab, leaf, process PID, renderer graph, persisted binding, runtime id, graph epoch, and daemon PID across first mount and reload; PID-specific DOM keyboard I/O must remain live with one launch, zero resume argv, zero signals, zero interruption text, and no canary mutation.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts"
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts src/main/providers/local-pty-provider.test.ts src/main/daemon/terminal-host.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/ipc/pty.test.ts src/main/runtime/orca-runtime.test.ts src/renderer/src/lib/pane-manager/pane-fit.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts",
"pnpm exec electron-vite build --mode e2e && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/live-background-terminal-mount-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
],
"testFiles": [
"src/renderer/src/lib/resume-sleeping-agent-session.test.ts",
"src/main/providers/local-pty-provider.test.ts",
"src/main/daemon/terminal-host.test.ts",
"src/main/daemon/daemon-pty-adapter.test.ts",
"src/main/ipc/pty.test.ts",
"src/main/runtime/orca-runtime.test.ts",
"src/renderer/src/lib/pane-manager/pane-fit.test.ts",
"src/renderer/src/components/terminal-pane/pty-connection.test.ts",
"src/renderer/src/components/terminal-pane/pty-transport.test.ts",
"tests/e2e/live-background-terminal-mount-authority.spec.ts"
],
"testFiles": ["src/renderer/src/lib/resume-sleeping-agent-session.test.ts"],
"assertionRefs": [
{
"file": "src/renderer/src/lib/resume-sleeping-agent-session.test.ts",
@@ -2148,6 +2394,42 @@
"active stable-pane records owned by preserved or visible panes are not resumed again",
"hibernated stable panes with cleared live PTY bindings are skipped"
]
},
{
"file": "src/main/ipc/pty.test.ts",
"assertions": [
"a completed runtime-owned stable pane is adopted with its original PTY and incarnation while renderer resume intent is stripped",
"an exact persisted owner is attach-only adopted when the runtime projection is missing",
"runtime and persisted stable-pane owner conflicts fail closed before provider creation"
]
},
{
"file": "src/renderer/src/lib/pane-manager/pane-fit.test.ts",
"assertions": [
"withheld hidden-window animation frames exhaust the bounded fit retry and release its continuation"
]
},
{
"file": "src/renderer/src/components/terminal-pane/pty-connection.test.ts",
"assertions": [
"same-generation explicit reattach drains the authoritative snapshot before immediate live bytes and ACKs their delivery credit"
]
},
{
"file": "src/renderer/src/components/terminal-pane/pty-transport.test.ts",
"assertions": [
"paired-runtime stable-pane adoption reports reattach without fresh-spawn ownership",
"cancellation after a paired-runtime adoption cannot close the original owner"
]
},
{
"file": "tests/e2e/live-background-terminal-mount-authority.spec.ts",
"assertions": [
"first mount and renderer reload preserve exact agent and Setup handle, PTY, incarnation, tab, leaf, and PID identity",
"PID-specific keyboard input and output remain user-visible in both mounted panes",
"runtime inventory, renderer graph, persisted session, runtime epoch, and daemon PID converge without replacement or resume",
"the unrelated canary remains writable and receives no signal across target projection repair"
]
}
],
"evidenceRuns": [
@@ -2162,30 +2444,32 @@
}
],
"runtimeBudget": {
"p95Seconds": 15,
"scope": "local renderer state test"
"p95Seconds": 180,
"scope": "focused renderer/main/provider contracts plus one isolated Electron mount-and-reload journey"
},
"flakeHistory": {
"status": "unknown",
"evidence": "Registered after targeted tests were found; needs soak history before blocking promotion."
"evidence": "The renderer gate has prior local evidence; the stable-pane Electron oracle is new and needs CI soak before blocking promotion."
},
"redGreenEvidence": {
"status": "partial",
"evidence": "Tests encode provider-session dedupe and ownership claims across active/inactive/visible split records, queued pendingStartupByTabId resume payloads, time-bounded runtime automaticAgentResumeClaimsByTabId bridge claims, live same-session hook evidence, wrong-session hook rejection, and a bounded queued-claim index over many records/tabs. Needs saved red/green artifact for the class-level replay invariant."
"evidence": "Renderer tests encode provider-session dedupe across active, inactive, queued, and live claims. The cross-boundary Electron oracle is constructed for byte-identical latest-main, candidate, and candidate-revert runs; record those three terminal results before promoting this gate."
},
"performanceBudget": {
"required": true,
"evidence": "Current state tests are cheap and assert queued pending-startup provider-session ids are indexed once per activation. PRs adding new ownership scans must show bounded work over records and no hidden-pane wake loop before blocking promotion."
"evidence": "Renderer state tests assert bounded provider-session indexing. Stable-pane adoption is a targeted owner lookup and attach-only call; focused contracts require no provider listing scan, fresh spawn callback, or repeated resume probe. The Electron oracle checks exact launch counts but is not a throughput benchmark."
},
"promotionCriteria": [
"Run in soak for at least 100 consecutive passes or 14 days across required CI platforms.",
"Add bounded-work assertions for delayed hook/status ownership scans if those paths grow.",
"Attach red/green evidence that display/replay evidence alone cannot claim ownership."
"Attach red/green evidence that display/replay evidence alone cannot claim ownership.",
"Record byte-identical latest-main, candidate, and candidate-revert Electron results."
],
"knownGaps": [
"Providers listed on this gate are affected identity surfaces; the current executable command is renderer-state coverage, not live local/daemon/SSH/WSL/remote-runtime coverage.",
"Current command models live same-session and wrong-session hook evidence, but does not run the real hook timing through Electron.",
"Current command does not run a real workspace activation loop repeatedly through Electron."
"Providers listed on this gate are affected identity surfaces; live integration is limited to local macOS while daemon and remote-runtime adoption also have focused contracts.",
"The Electron oracle seeds the production hook-store contract instead of running an authenticated Codex hook end to end.",
"The live Electron topology is local macOS only; folder workspaces, SSH, WSL, paired headed/headless servers, Linux, and Windows are not exercised by that journey.",
"The oracle covers first activation and one renderer reload, not repeated soak activation or an installed-app update."
],
"demotionRule": "Demote or quarantine if failures are non-actionable or if a duplicate resume escape occurs outside the modeled matrix."
},
@@ -6457,21 +6741,25 @@
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos"],
"coveredProviders": ["local", "daemon", "ssh"],
"coverageNotes": "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. 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. 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"
],
"testFiles": [
"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",
@@ -6483,6 +6771,23 @@
"tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts"
],
"assertionRefs": [
{
"file": "src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts",
"assertions": [
"an exact current worker settles once through an app/runtime update even when renderer graph identity is absent",
"only an attested current coordinator may explicitly take over retained live work",
"Task, Dispatch, terminal authority, completion, and filesystem bytes are neither lost nor duplicated",
"foreign pane evidence cannot borrow retained lifecycle authority",
"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": [
@@ -6562,6 +6867,42 @@
}
],
"evidenceRuns": [
{
"date": "2026-08-03",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot",
"result": "failed",
"durationSeconds": 3.07,
"summary": "The byte-identical 5f45c270f1 oracle, applied as the sole tree overlay in 063340a8ba on origin/main@34291f07e9, failed 3 of 5 rows: completion remained dispatched, takeover lacked a stable pane, and remote attachment authority lost process identity."
},
{
"date": "2026-08-03",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot",
"result": "passed",
"durationSeconds": 3.13,
"summary": "The same byte-identical oracle passed 5 tests on candidate@2748b0b29b, exercising the production verifier and fresh-runtime replay while preserving exact DB identity and unchanged fixture bytes."
},
{
"date": "2026-08-03",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot",
"result": "failed",
"durationSeconds": 3.14,
"summary": "With current-authority propagation actually disabled in candidate child 08a7db37bf, the same byte-identical oracle failed 2 of 5 rows: completion remained dispatched and remote attachment authority was rejected."
},
{
"date": "2026-08-03",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot",
"result": "passed",
"durationSeconds": 3.1,
"summary": "After reverting the intentional break in d2a4e2e024, the same byte-identical oracle passed all 5 tests."
},
{
"date": "2026-07-28",
"runner": "local",
@@ -6609,7 +6950,7 @@
},
"redGreenEvidence": {
"status": "partial",
"evidence": "The focused presentation and stale-handle tests failed against the pre-fix implementation. The restart journey additionally failed first on empty retained output while the original PTY/PID remained live, then passed after the scoped recovered-worker snapshot fallback. The live incident and pre-fix Electron topology showed workspace re-entry replaying provider resume against a worker whose tab binding was missing. Saved intentional-break and CI artifacts are still needed."
"evidence": "The byte-identical 5f45c270f1 service oracle is red as the sole overlay 063340a8ba on origin/main@34291f07e9, green on candidate@2748b0b29b, red with current-authority propagation actually disabled in child 08a7db37bf, and green again after revert d2a4e2e024. The focused presentation and stale-handle tests failed against the earlier pre-fix implementation. The restart journey additionally failed first on empty retained output while the original PTY/PID remained live, then passed after the scoped recovered-worker snapshot fallback. The live incident and pre-fix Electron topology showed workspace re-entry replaying provider resume against a worker whose tab binding was missing. Distinct installed A/B and CI artifacts are still needed."
},
"performanceBudget": {
"required": true,
@@ -6631,6 +6972,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",
@@ -7781,8 +8220,8 @@
"https://github.com/stablyai/orca/pull/5787",
"https://github.com/stablyai/orca/pull/8034"
],
"invariant": "After a renderer lifecycle reset (did-start-loading / render-process-gone / destroyed), no surviving PTY remains delivery-gated by pre-reset unacked bytes: main's in-flight counters and pending backlog equal the true state of the new page (zero in-flight, zero pending). Delivery then resumes only once the reloaded page's pty:data dispatcher re-registers and signals pty:rendererDispatcherReady; during the boot window before that handshake main holds all sends (data accrues losslessly in the capped pending backlog) so bytes cannot be dropped into a listener-less page and re-pin the gate. The hold itself cannot become a permanent freeze: a one-shot ~10s watchdog armed on each reset force-opens the gate (incrementing rendererDispatcherReadyForcedCount) if the handshake is lost, and the real handshake or a re-registration cancels it. The reset fires only for a main-frame load: did-start-loading also fires for in-page subframe loads (sandboxed srcDoc iframes in notebook HTML output), which are filtered out via isLoadingMainFrame() so a subframe load never clears accounting or holds the gate on the still-alive page. If a lifecycle-reset edge is missed entirely — a main-frame reload overlapped by an in-page subframe load emits no did-start-loading at all — a backstop still recovers: because the handshake is one-shot per page load, receiving pty:rendererDispatcherReady while the gate is already open proves a reset was missed (or the watchdog force-opened the gate), so the handler reconciles by clearing the stale accounting before re-opening. The renderer sends that handshake exactly once per page load, after its pty:data listener registers.",
"oracle": "Ingest more than 512 KB of PTY output with no renderer ACKs and assert the per-PTY gate closes (sends stop at the 512 KB high-water, remainder accrues as pending). Fire the registered did-start-loading listener and assert rendererInFlightChars and pendingChars are zero and the new diagnostics record the reset (rendererLifecycleResetCount 1, lastLifecycleResetClearedChars 512 KB). Then, before any dispatcher-ready handshake, ingest another chunk and assert it is NOT sent and NOT counted in-flight (held for the boot window, accruing in pending). Finally fire the pty:rendererDispatcherReady handshake and assert the held chunk is delivered to the renderer. Counters-zero without proving both the boot-window hold and that delivery resumes is insufficient. Additional cases prove the boot-window hold also covers the interactive direct-send fast path (input-primed keystroke echo is held, not sent, until the handshake) and that the self-heal watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) when no handshake arrives, while a timely handshake cancels the watchdog and leaves no orphaned timer. A further case fires did-start-loading with isLoadingMainFrame() false (a subframe/iframe load) and asserts accounting is untouched (rendererLifecycleResetCount stays 0, pending preserved, ready stays true) and delivery still drains on ACK — proving an in-page iframe load cannot trigger a spurious freeze. A backstop case saturates the gate, then fires pty:rendererDispatcherReady while the gate is still open (ready true) with no preceding reset — modeling a missed lifecycle edge — and asserts the handler reconciles: in-flight and pending clear, rendererLifecycleResetCount increments, and fresh output flows immediately (a straggler ACK is clamped and cannot underflow). A renderer-side case (pty-dispatcher-pi-routing.test.ts) asserts ensurePtyDispatcher() sends pty:rendererDispatcherReady exactly once across two attach calls — proving the send fires (it is optional-chained) and the one-shot guard holds.",
"invariant": "After a renderer lifecycle reset (main-frame did-start-navigation / render-process-gone / destroyed), no surviving PTY remains delivery-gated by pre-reset unacked bytes: main's in-flight counters and pending backlog equal the true state of the new page (zero in-flight, zero pending). Delivery then resumes only once the reloaded page's pty:data dispatcher re-registers and signals pty:rendererDispatcherReady; during the boot window before that handshake main holds all sends (data accrues losslessly in the capped pending backlog) so bytes cannot be dropped into a listener-less page and re-pin the gate. The hold itself cannot become a permanent freeze: a one-shot ~10s watchdog armed on each reset force-opens the gate (incrementing rendererDispatcherReadyForcedCount) if the handshake is lost, and the real handshake or a re-registration cancels it. The reset fires only for a new-document main-frame navigation: did-start-navigation carries exact frame and same-document details, so overlapping subframe or in-page navigation never clears accounting or holds the gate on the still-alive page. If a renderer lifecycle edge is otherwise missed, a backstop still recovers: because the handshake is one-shot per page load, receiving pty:rendererDispatcherReady while the gate is already open proves a reset was missed (or the watchdog force-opened the gate), so the handler reconciles by clearing the stale accounting before re-opening. The renderer sends that handshake exactly once per page load, after its pty:data listener registers.",
"oracle": "Ingest more than 512 KB of PTY output with no renderer ACKs and assert the per-PTY gate closes (sends stop at the 512 KB high-water, remainder accrues as pending). Fire the registered main-frame did-start-navigation listener and assert rendererInFlightChars and pendingChars are zero and the new diagnostics record the reset (rendererLifecycleResetCount 1, lastLifecycleResetClearedChars 512 KB). Then, before any dispatcher-ready handshake, ingest another chunk and assert it is NOT sent and NOT counted in-flight (held for the boot window, accruing in pending). Finally fire the pty:rendererDispatcherReady handshake and assert the held chunk is delivered to the renderer. Counters-zero without proving both the boot-window hold and that delivery resumes is insufficient. Additional cases prove the boot-window hold also covers the interactive direct-send fast path (input-primed keystroke echo is held, not sent, until the handshake) and that the self-heal watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) when no handshake arrives, while a timely handshake cancels the watchdog and leaves no orphaned timer. A further case opens the new page with a main-frame navigation and dispatcher handshake, then fires an overlapping subframe navigation and asserts the gate stays ready, the reset count stays at exactly one, and fresh output delivers without the watchdog — proving an iframe cannot reclose the live page. A backstop case saturates the gate, then fires pty:rendererDispatcherReady while the gate is still open (ready true) with no preceding reset — modeling a missed lifecycle edge — and asserts the handler reconciles: in-flight and pending clear, rendererLifecycleResetCount increments, and fresh output flows immediately (a straggler ACK is clamped and cannot underflow). A renderer-side case (pty-dispatcher-pi-routing.test.ts) asserts ensurePtyDispatcher() sends pty:rendererDispatcherReady exactly once across two attach calls — proving the send fires (it is optional-chained) and the one-shot guard holds.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts"
],
@@ -7795,12 +8234,12 @@
"file": "src/main/ipc/pty.test.ts",
"assertions": [
"a PTY saturated past the 512 KB per-PTY high-water with no ACKs stops sending and accrues pending output (gate closed)",
"firing the registered did-start-loading listener zeroes rendererInFlightChars and pendingData and records rendererLifecycleResetCount and lastLifecycleResetClearedChars",
"firing the registered main-frame did-start-navigation listener zeroes rendererInFlightChars and pendingData and records rendererLifecycleResetCount and lastLifecycleResetClearedChars",
"after the reset, output ingested during the boot window is NOT sent and NOT counted in-flight until the pty:rendererDispatcherReady handshake fires (held in pending)",
"firing the pty:rendererDispatcherReady handshake releases the held backlog and delivery resumes (delivery gated on the handshake, not just counters cleared)",
"interactive input-primed keystroke echo is also held during the boot window (interactive fast path gated on the handshake) and delivered once it fires",
"when no handshake arrives, the ~10s watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) and the held backlog drains; a timely handshake cancels the watchdog and leaves no orphaned timer",
"a did-start-loading with isLoadingMainFrame() false (in-page subframe/iframe load) does NOT reset accounting (rendererLifecycleResetCount stays 0, pending and in-flight preserved, rendererPtyDispatcherReady stays true) and delivery still drains on ACK",
"an overlapping subframe did-start-navigation after the fresh dispatcher handshake does NOT reclose delivery (rendererLifecycleResetCount stays 1, rendererPtyDispatcherReady stays true, forced count stays 0) and fresh output delivers immediately",
"a pty:rendererDispatcherReady handshake arriving while the gate is still open (ready true, no preceding reset — a missed lifecycle edge) reconciles the stale accounting: in-flight and pending clear, rendererLifecycleResetCount increments, fresh output flows, and a straggler ACK is clamped",
"re-registering handlers (macOS re-activate / new window) cancels the prior registration's armed dispatcher-ready watchdog via the cross-registration bridge, leaving no orphaned ~10s timer to force-open a dead window's gate"
]
@@ -7814,13 +8253,13 @@
],
"evidenceRuns": [
{
"date": "2026-07-09",
"date": "2026-08-02",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts",
"result": "passed",
"durationSeconds": 1,
"summary": "243 tests passed (232 main-process + 11 renderer dispatcher) including the lifecycle-reset, boot-window (dispatcher-ready handshake), interactive-gate hold, watchdog self-heal, main-frame-filter (subframe did-start-loading is ignored), missed-reset reconcile backstop (handshake-while-open), cross-registration watchdog-cancel, and renderer-side one-shot handshake-send regressions. Removing the reset call reproduces the reload freeze (rendererInFlightChars stays 524288); removing the send-hold reproduces the boot-window leak; removing the interactive-path flag check sends keystroke echo into the not-yet-ready page; removing the watchdog arm leaves the gate held forever; removing the watchdog cancel leaves an orphaned timer after the handshake; removing the isLoadingMainFrame filter lets a subframe iframe load run a spurious reset; removing the handshake-while-open reconcile leaves the survivors pinned at 524288 after a missed lifecycle edge."
"durationSeconds": 5,
"summary": "439 tests passed including the lifecycle-reset, boot-window (dispatcher-ready handshake), interactive-gate hold, watchdog self-heal, exact-navigation filter (overlapping subframe navigation is ignored), missed-reset reconcile backstop (handshake-while-open), cross-registration watchdog-cancel, and renderer-side one-shot handshake-send regressions. Removing the reset call reproduces the reload freeze (rendererInFlightChars stays 524288); removing the send-hold reproduces the boot-window leak; removing the interactive-path flag check sends keystroke echo into the not-yet-ready page; removing the watchdog arm leaves the gate held forever; removing the watchdog cancel leaves an orphaned timer after the handshake; switching back to aggregate did-start-loading state lets an overlapping iframe load reclose the gate; removing the handshake-while-open reconcile leaves the survivors pinned at 524288 after a missed lifecycle edge."
}
],
"runtimeBudget": {
@@ -7833,7 +8272,7 @@
},
"redGreenEvidence": {
"status": "partial",
"evidence": "Locally verified red/green on every load-bearing branch: (1) reset call removed -> rendererInFlightChars stays 524288 after did-start-loading; (2) boot-window send-hold removed -> post-reload output is sent into the not-yet-ready page ('NOT sent until handshake' fails); (3) interactive-path flag check removed -> input-primed keystroke echo is sent during the hold; (4) watchdog arm removed -> the gate is never force-opened and the held backlog never drains; (5) watchdog cancel removed -> an orphaned ~10s timer survives the handshake (getTimerCount 1); (6) isLoadingMainFrame filter removed -> a subframe did-start-loading runs a spurious reset (rendererLifecycleResetCount 1, pending cleared, ready dropped) — locally verified red; (7) handshake-while-open reconcile removed -> a pty:rendererDispatcherReady arriving after a missed lifecycle edge leaves the gate pinned (rendererInFlightChars stays 524288, pending 90112, rendererLifecycleResetCount 0) — locally verified red; (8) cross-registration bridge cancel removed (top-of-registerPtyHandlers clearRendererDispatcherReadyWatchdog) -> a prior registration's armed watchdog survives re-registration as an orphaned timer (getTimerCount 1 instead of 0) — locally verified red. With the full fix all eight are green. The performance budget below still holds: the watchdog is a single unref'd one-shot per reset, not per-chunk. Needs a saved CI or intentional-break artifact before blocking promotion."
"evidence": "Locally verified red/green on every load-bearing branch: (1) reset call removed -> rendererInFlightChars stays 524288 after main-frame did-start-navigation; (2) boot-window send-hold removed -> post-reload output is sent into the not-yet-ready page ('NOT sent until handshake' fails); (3) interactive-path flag check removed -> input-primed keystroke echo is sent during the hold; (4) watchdog arm removed -> the gate is never force-opened and the held backlog never drains; (5) watchdog cancel removed -> an orphaned ~10s timer survives the handshake (getTimerCount 1); (6) aggregate did-start-loading classification restored -> an overlapping subframe navigation recloses the gate after the handshake (ready false until watchdog) — deterministically red; (7) handshake-while-open reconcile removed -> a pty:rendererDispatcherReady arriving after a missed lifecycle edge leaves the gate pinned (rendererInFlightChars stays 524288, pending 90112, rendererLifecycleResetCount 0) — locally verified red; (8) cross-registration bridge cancel removed (top-of-registerPtyHandlers clearRendererDispatcherReadyWatchdog) -> a prior registration's armed watchdog survives re-registration as an orphaned timer (getTimerCount 1 instead of 0) — locally verified red. With the full fix all eight are green. The performance budget below still holds: the watchdog is a single unref'd one-shot per reset, not per-chunk. Needs a saved CI or intentional-break artifact before blocking promotion."
},
"performanceBudget": {
"required": true,
+12 -3
View File
@@ -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`
@@ -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'
@@ -31,6 +39,20 @@ describe('Windows CLI launcher', () => {
}
})
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 {
@@ -89,4 +111,70 @@ describe('Windows CLI launcher', () => {
rmSync(appRoot, { recursive: true, force: true })
}
})
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 {
rmSync(appRoot, { recursive: true, force: true })
}
})
})
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
)
}
@@ -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)
}
@@ -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([])
})
})
+65 -25
View File
@@ -420,40 +420,42 @@ describe('electron-builder config', () => {
expect(findAsarEntry(['/out/main/index.js'], 'out/main/index.js')).toBe('/out/main/index.js')
})
it('prunes non-target node-pty prebuilds from packaged runtime resources', async () => {
it('prunes non-target node-pty architecture outputs from packaged runtime resources', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-node-pty-prune-'))
try {
const prebuildsDir = join(resourcesDir, 'node_modules', 'node-pty', 'prebuilds')
const nodePtyDir = join(resourcesDir, 'node_modules', 'node-pty')
const prebuildsDir = join(nodePtyDir, 'prebuilds')
const binDir = join(nodePtyDir, 'bin')
await mkdir(join(prebuildsDir, 'darwin-arm64'), { recursive: true })
await mkdir(join(prebuildsDir, 'darwin-x64'), { recursive: true })
await mkdir(join(prebuildsDir, 'linux-x64'), { recursive: true })
await mkdir(join(prebuildsDir, 'win32-x64'), { recursive: true })
await mkdir(join(resourcesDir, 'node_modules', 'node-pty', 'third_party', 'conpty'), {
recursive: true
})
await mkdir(join(resourcesDir, 'node_modules', 'node-pty', 'deps', 'winpty'), {
await mkdir(join(binDir, 'darwin-arm64-148'), { recursive: true })
await mkdir(join(binDir, 'darwin-x64-148'), { recursive: true })
await mkdir(join(nodePtyDir, 'third_party', 'conpty'), {
recursive: true
})
await mkdir(join(nodePtyDir, 'deps', 'winpty'), { recursive: true })
prunePackagedNodePty(resourcesDir, 'darwin')
prunePackagedNodePty(resourcesDir, 'darwin', 3)
await expect(readdir(prebuildsDir).then((entries) => entries.sort())).resolves.toEqual([
'darwin-arm64',
'darwin-x64'
])
await expect(
readdir(join(resourcesDir, 'node_modules', 'node-pty', 'third_party'))
).resolves.toEqual([])
await expect(
readdir(join(resourcesDir, 'node_modules', 'node-pty', 'deps'))
).resolves.toEqual([])
await expect(readdir(prebuildsDir)).resolves.toEqual(['darwin-arm64'])
await expect(readdir(binDir)).resolves.toEqual(['darwin-arm64-148'])
await expect(readdir(join(nodePtyDir, 'third_party'))).resolves.toEqual([])
await expect(readdir(join(nodePtyDir, 'deps'))).resolves.toEqual([])
expect(() => prunePackagedNodePty(resourcesDir, 'darwin', 4)).toThrow(
'Unsupported packaged runtime architecture: 4'
)
} finally {
await rm(resourcesDir, { recursive: true, force: true })
}
})
it('copies the Windows node-pty ConPTY runtime beside the rebuilt addon', async () => {
for (const arch of ['x64', 'arm64']) {
for (const [arch, electronArch] of [
['x64', 1],
['arm64', 3]
]) {
const resourcesDir = await mkdtemp(join(tmpdir(), `orca-node-pty-conpty-${arch}-`))
try {
const nodePtyDir = join(resourcesDir, 'node_modules', 'node-pty')
@@ -472,7 +474,7 @@ describe('electron-builder config', () => {
)
}
prunePackagedNodePty(resourcesDir, 'win32', arch)
prunePackagedNodePty(resourcesDir, 'win32', electronArch)
await expect(readFile(join(releaseDir, 'conpty', 'conpty.dll'), 'utf8')).resolves.toBe(
`dll payload ${arch}`
@@ -500,7 +502,7 @@ describe('electron-builder config', () => {
).toBe(true)
})
it('prunes non-target @parcel/watcher platform subpackages from packaged runtime resources', async () => {
it('prunes non-target @parcel/watcher architecture subpackages', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-parcel-watcher-prune-'))
try {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
@@ -511,13 +513,15 @@ describe('electron-builder config', () => {
await mkdir(join(parcelDir, 'watcher-linux-arm64-glibc'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-win32-x64'), { recursive: true })
prunePackagedParcelWatcher(resourcesDir, 'linux')
prunePackagedParcelWatcher(resourcesDir, 'linux', 'arm64')
await expect(readdir(parcelDir).then((entries) => entries.sort())).resolves.toEqual([
'watcher',
'watcher-linux-arm64-glibc',
'watcher-linux-x64-glibc'
'watcher-linux-arm64-glibc'
])
expect(() => prunePackagedParcelWatcher(resourcesDir, 'linux', 'universal')).toThrow(
'Unsupported packaged runtime architecture: universal'
)
} finally {
await rm(resourcesDir, { recursive: true, force: true })
}
@@ -533,7 +537,7 @@ describe('electron-builder config', () => {
// A hypothetical future @parcel/* runtime dep that is NOT a watcher subpackage.
await mkdir(join(parcelDir, 'transformer-js'), { recursive: true })
prunePackagedParcelWatcher(resourcesDir, 'linux')
prunePackagedParcelWatcher(resourcesDir, 'linux', 1)
await expect(readdir(parcelDir).then((entries) => entries.sort())).resolves.toEqual([
'transformer-js',
@@ -653,7 +657,8 @@ describe('electron-builder config', () => {
await electronBuilderConfig.afterPack({
appOutDir: join(root, 'linux-unpacked'),
electronPlatformName: 'linux'
electronPlatformName: 'linux',
arch: 1
})
expect((await stat(launcherPath)).mode & 0o111).not.toBe(0)
@@ -662,4 +667,39 @@ describe('electron-builder config', () => {
}
}
)
// Why: the .deb/.rpm update-recovery path keys entirely off the resources/package-type marker that
// app-builder-lib's FpmTarget writes. If packaging silently stops shipping an fpm target, or adds
// one the recovery path does not cover, getLinuxRootPackageType() returns null, autoInstallOnAppQuit
// quietly goes back to true, and no unit test notices.
describe('linux root-package update recovery contract', () => {
// FpmTarget writes resources/package-type only for targets it supports auto-update for.
const MARKER_TARGETS = new Set(['deb', 'rpm', 'pacman'])
const RECOVERABLE_TARGETS = new Set(['deb', 'rpm'])
const linuxTargets = electronBuilderConfig.linux.target.map((entry) =>
typeof entry === 'string' ? entry : entry.target
)
it('still ships an AppImage plus at least one root-package target', () => {
expect(linuxTargets).toContain('AppImage')
expect(linuxTargets.some((target) => MARKER_TARGETS.has(target))).toBe(true)
})
it('ships no root-package target the recovery path cannot recover', () => {
const unrecoverable = linuxTargets.filter(
(target) => MARKER_TARGETS.has(target) && !RECOVERABLE_TARGETS.has(target)
)
expect(unrecoverable).toEqual([])
})
it('accepts exactly the markers electron-updater maps to a root-package updater', async () => {
const source = await readFile(
new URL('../../src/main/linux-update-package-type.ts', import.meta.url),
'utf8'
)
for (const target of linuxTargets.filter((entry) => RECOVERABLE_TARGETS.has(entry))) {
expect(source).toContain(`value === '${target}'`)
}
})
})
})
@@ -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<string> entries = new List<string>();
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);
}
}
}
+8 -3
View File
@@ -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`
@@ -0,0 +1,38 @@
export class BoundedLiveFreezeHistory {
#entries = []
#limit
#nextIndex = 0
#totalCount = 0
constructor(limit) {
if (!Number.isInteger(limit) || limit <= 0) {
throw new Error(`History limit must be a positive integer, got ${limit}`)
}
this.#limit = limit
}
add(entry) {
this.#totalCount += 1
if (this.#entries.length < this.#limit) {
this.#entries.push(entry)
return
}
this.#entries[this.#nextIndex] = entry
this.#nextIndex = (this.#nextIndex + 1) % this.#limit
}
get retainedCount() {
return this.#entries.length
}
get totalCount() {
return this.#totalCount
}
values() {
if (this.#entries.length < this.#limit || this.#nextIndex === 0) {
return [...this.#entries]
}
return [...this.#entries.slice(this.#nextIndex), ...this.#entries.slice(0, this.#nextIndex)]
}
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { BoundedLiveFreezeHistory } from './live-freeze-bounded-history.mjs'
describe('BoundedLiveFreezeHistory', () => {
it('retains the newest entries in insertion order and counts the full run', () => {
const history = new BoundedLiveFreezeHistory(3)
for (let value = 1; value <= 7; value += 1) {
history.add(value)
}
expect(history.values()).toEqual([5, 6, 7])
expect(history.retainedCount).toBe(3)
expect(history.totalCount).toBe(7)
})
it('rejects invalid retention limits', () => {
expect(() => new BoundedLiveFreezeHistory(0)).toThrow('positive integer')
expect(() => new BoundedLiveFreezeHistory(1.5)).toThrow('positive integer')
})
})
@@ -0,0 +1,262 @@
/**
* Pure metrics helpers for the live remote bulk-open freeze harness.
* Kept separate so unit tests can drive the same code the repro uses.
*/
export const DEFAULT_SOFT_MS = 2000
export const DEFAULT_HARD_MS = 5000
export function readFreezeNumberEnv(name, fallback) {
const raw = process.env[name]
if (raw == null || raw.trim() === '') {
return fallback
}
const value = Number(raw)
if (!Number.isFinite(value)) {
throw new Error(`Invalid ${name}: expected a finite number, got ${JSON.stringify(raw)}`)
}
return value
}
export function extractTerminalHandle(result) {
if (!result || typeof result !== 'object') {
return null
}
const candidates = [
result.handle,
result.terminalHandle,
result.agentTerminalHandle,
typeof result.terminal === 'string' ? result.terminal : result.terminal?.handle,
result.startupTerminal?.handle,
result.tab?.terminal,
result.tab?.handle
]
for (const value of candidates) {
if (typeof value === 'string' && value.startsWith('term_')) {
return value
}
}
for (const value of Object.values(result)) {
if (typeof value === 'string' && value.startsWith('term_')) {
return value
}
if (value && typeof value === 'object') {
for (const nested of Object.values(value)) {
if (typeof nested === 'string' && nested.startsWith('term_')) {
return nested
}
}
}
}
return null
}
export function worktreeSelector(wt) {
if (typeof wt?.id === 'string' && wt.id.length > 0) {
return `id:${wt.id}`
}
if (typeof wt?.path === 'string' && wt.path.length > 0) {
return `path:${wt.path}`
}
return null
}
/**
* Peak stall across individual switch latency and concurrent batch wall.
* Hard freeze when peak >= hardMs (default 5000).
*/
export function evaluateFreezeSignals({
maxSwitchMs = 0,
maxBatchWallMs = 0,
statusProbeMs = 0,
memoryProbeMs = null,
softMs = DEFAULT_SOFT_MS,
hardMs = DEFAULT_HARD_MS
}) {
const peakLatencyMs = Math.max(maxSwitchMs, maxBatchWallMs)
const softFreeze =
peakLatencyMs >= softMs ||
statusProbeMs >= softMs ||
(memoryProbeMs != null && memoryProbeMs >= softMs)
const hardFreeze =
peakLatencyMs >= hardMs ||
statusProbeMs >= hardMs ||
(memoryProbeMs != null && memoryProbeMs >= hardMs)
return { peakLatencyMs, softFreeze, hardFreeze }
}
export function shouldCapSwitchTargets(maxSwitchTargets) {
return Number.isFinite(maxSwitchTargets) && maxSwitchTargets > 0
}
export function applySwitchTargetCap(targets, maxSwitchTargets) {
if (!shouldCapSwitchTargets(maxSwitchTargets)) {
return targets
}
return targets.slice(0, maxSwitchTargets)
}
/** Scenarios that model real user recovery, not concurrent CLI pileup. */
export const REALISTIC_SCENARIOS = [
'idle-backlog-open',
'idle-backlog-reconnect-open',
'restart-proxy',
/** Idle + flood + reconnect storm overlapped with concurrent open fan-out. */
'lockup-storm'
]
/**
* Permanent lockup: app/host stops making progress — not a single recovered timeout.
* Distinct from multi-second hard stall that still recovers (status answers, most opens ok).
*/
export function evaluatePermanentLockup({
timedOutOps = 0,
statusHangMs = 0,
consecutiveSwitchFailures = 0,
openFailed = 0,
openTotal = 0,
permanentTimeoutMs = 60_000,
/** Fraction of opens that must fail to count as lockup without status hang. */
failRateThreshold = 0.25,
minTimedOutOps = 3
}) {
const failRate = openTotal > 0 ? openFailed / openTotal : 0
const permanentLockup =
statusHangMs >= permanentTimeoutMs ||
timedOutOps >= minTimedOutOps ||
consecutiveSwitchFailures >= 5 ||
(openTotal >= 8 && failRate >= failRateThreshold)
return {
permanentLockup,
timedOutOps,
statusHangMs,
consecutiveSwitchFailures,
failRate,
recoveredHardStallCandidate:
!permanentLockup && timedOutOps < minTimedOutOps && statusHangMs < permanentTimeoutMs
}
}
/**
* Peak across open latencies + optional reconnect-refresh wall + probes.
* Used by the naturalistic harness (no parallel switch amp).
*/
export function evaluateRealisticFreezeSignals({
maxOpenMs = 0,
firstOpenMs = 0,
reconnectRefreshMs = 0,
statusProbeMs = 0,
memoryProbeMs = null,
softMs = DEFAULT_SOFT_MS,
hardMs = DEFAULT_HARD_MS
}) {
const peakLatencyMs = Math.max(maxOpenMs, firstOpenMs, reconnectRefreshMs)
return evaluateFreezeSignals({
maxSwitchMs: peakLatencyMs,
maxBatchWallMs: 0,
statusProbeMs,
memoryProbeMs,
softMs,
hardMs
})
}
export function humanPaceDelayMs(baseMs, jitterMs = 0) {
const base = Math.max(0, baseMs)
const jitter = Math.max(0, jitterMs)
if (jitter === 0) {
return base
}
return base + Math.floor(Math.random() * (jitter + 1))
}
/** Full-app forever freeze: host RPC dead for a continuous window, not a recovered stall. */
export const DEFAULT_FOREVER_WINDOW_MS = 30_000
export const DEFAULT_STATUS_SLOW_MS = 15_000
/**
* Analyze mid-storm status samples for a continuous unhealthy window.
* Sample: { tMs, ms, ok, hang }
*/
export function evaluateFullAppFreeze({
statusSamples = [],
statusSummary = {},
foreverWindowMs = DEFAULT_FOREVER_WINDOW_MS,
statusSlowMs = DEFAULT_STATUS_SLOW_MS,
killOnlyRecovery = false
}) {
const infrastructureErrors = statusSamples.filter((sample) => sample.infrastructureError)
const infrastructureErrorCount = Math.max(
infrastructureErrors.length,
statusSummary.infrastructureErrorCount ?? 0
)
const maxStatusMs = Math.max(
0,
...statusSamples.map((s) => s.ms || 0),
statusSummary.maxStatusMs ?? 0
)
if (killOnlyRecovery) {
return {
foreverUiLockupObserved: true,
longestUnhealthyWindowMs: foreverWindowMs,
maxStatusMs,
unhealthySampleCount: statusSummary.sampleCount ?? statusSamples.length,
infrastructureErrorCount,
reason: 'kill-only recovery documented'
}
}
const unhealthy = statusSamples.map((s) => {
const hang = !s.infrastructureError && (Boolean(s.hang) || s.ok === false)
const slow = !s.infrastructureError && (s.ms || 0) >= statusSlowMs
return { ...s, unhealthy: hang || slow }
})
let longest = statusSummary.longestUnhealthyWindowMs ?? 0
let runStart = null
for (const s of unhealthy) {
if (s.unhealthy) {
runStart ??= s.tMs ?? 0
const end = (s.tMs ?? 0) + (s.ms || 0)
longest = Math.max(longest, end - runStart)
} else {
runStart = null
}
}
// If timestamps missing, fall back to consecutive unhealthy count * assumed interval.
if (longest === 0 && unhealthy.some((s) => s.unhealthy)) {
let run = 0
for (const s of unhealthy) {
if (s.unhealthy) {
run += 1
longest = Math.max(longest, run)
} else {
run = 0
}
}
// Without wall clock, consecutive count alone is not a ms window.
longest = 0
}
const foreverUiLockupObserved = longest >= foreverWindowMs
const unhealthySampleCount = Math.max(
unhealthy.filter((s) => s.unhealthy).length,
statusSummary.unhealthySampleCount ?? 0
)
return {
foreverUiLockupObserved,
longestUnhealthyWindowMs: longest,
maxStatusMs,
unhealthySampleCount,
infrastructureErrorCount,
reason: foreverUiLockupObserved
? `status unhealthy ≥${foreverWindowMs}ms continuous`
: infrastructureErrorCount > 0
? `status watchdog infrastructure errors: ${infrastructureErrorCount}`
: maxStatusMs >= statusSlowMs
? `status slow peak ${maxStatusMs}ms but no ≥${foreverWindowMs}ms window`
: 'status remained healthy through storm'
}
}
@@ -0,0 +1,239 @@
import { describe, expect, it } from 'vitest'
import {
applySwitchTargetCap,
evaluateFreezeSignals,
evaluateFullAppFreeze,
evaluatePermanentLockup,
evaluateRealisticFreezeSignals,
extractTerminalHandle,
humanPaceDelayMs,
readFreezeNumberEnv,
REALISTIC_SCENARIOS,
shouldCapSwitchTargets,
worktreeSelector
} from './live-remote-bulk-open-freeze-metrics.mjs'
describe('live-remote-bulk-open-freeze-metrics', () => {
it('extracts term_ handles from nested create payloads', () => {
expect(extractTerminalHandle({ handle: 'term_abc' })).toBe('term_abc')
expect(extractTerminalHandle({ terminal: { handle: 'term_nested' } })).toBe('term_nested')
expect(extractTerminalHandle({ tab: { terminal: 'term_tab' } })).toBe('term_tab')
expect(extractTerminalHandle({ startupTerminal: { handle: 'term_start' } })).toBe('term_start')
expect(extractTerminalHandle({ junk: { deep: 'term_deep' } })).toBe('term_deep')
expect(extractTerminalHandle({ handle: 'not-a-term' })).toBeNull()
expect(extractTerminalHandle(null)).toBeNull()
})
it('builds worktree selectors from id/path', () => {
expect(
worktreeSelector({ id: 'repo::C:/Users/neil/orca/orca', path: 'C:/Users/neil/orca/orca' })
).toBe('id:repo::C:/Users/neil/orca/orca')
expect(worktreeSelector({ path: '/tmp/x' })).toBe('path:/tmp/x')
expect(worktreeSelector({})).toBeNull()
})
it('does not cap switch targets when max is 0 (regression for Math.max(2,0) bug)', () => {
expect(shouldCapSwitchTargets(0)).toBe(false)
expect(shouldCapSwitchTargets(-1)).toBe(false)
expect(shouldCapSwitchTargets(2)).toBe(true)
const many = Array.from({ length: 111 }, (_, i) => `term_${i}`)
expect(applySwitchTargetCap(many, 0)).toHaveLength(111)
expect(applySwitchTargetCap(many, 2)).toHaveLength(2)
})
it('classifies hard freeze at >=5000ms peak (individual or batch wall)', () => {
expect(evaluateFreezeSignals({ maxSwitchMs: 3874, maxBatchWallMs: 3874 }).hardFreeze).toBe(
false
)
expect(evaluateFreezeSignals({ maxSwitchMs: 3874, maxBatchWallMs: 3874 }).softFreeze).toBe(true)
const hardIndividual = evaluateFreezeSignals({ maxSwitchMs: 19954, maxBatchWallMs: 1000 })
expect(hardIndividual.hardFreeze).toBe(true)
expect(hardIndividual.peakLatencyMs).toBe(19954)
const hardBatch = evaluateFreezeSignals({ maxSwitchMs: 900, maxBatchWallMs: 20201 })
expect(hardBatch.hardFreeze).toBe(true)
expect(hardBatch.peakLatencyMs).toBe(20201)
})
it('evaluates naturalistic peaks without requiring parallel batch amp', () => {
expect(REALISTIC_SCENARIOS).toContain('idle-backlog-open')
expect(REALISTIC_SCENARIOS).toContain('idle-backlog-reconnect-open')
expect(REALISTIC_SCENARIOS).toContain('lockup-storm')
const soft = evaluateRealisticFreezeSignals({
maxOpenMs: 3200,
firstOpenMs: 2800,
reconnectRefreshMs: 900
})
expect(soft.softFreeze).toBe(true)
expect(soft.hardFreeze).toBe(false)
expect(soft.peakLatencyMs).toBe(3200)
const hardFromReconnect = evaluateRealisticFreezeSignals({
maxOpenMs: 800,
firstOpenMs: 700,
reconnectRefreshMs: 6200
})
expect(hardFromReconnect.hardFreeze).toBe(true)
expect(hardFromReconnect.peakLatencyMs).toBe(6200)
})
it('flags full-app freeze only for continuous unhealthy status window ≥30s', () => {
const healthy = evaluateFullAppFreeze({
statusSamples: [
{ tMs: 0, ms: 150, ok: true },
{ tMs: 2000, ms: 180, ok: true },
{ tMs: 4000, ms: 140, ok: true }
],
foreverWindowMs: 30_000,
statusSlowMs: 15_000
})
expect(healthy.foreverUiLockupObserved).toBe(false)
const forever = evaluateFullAppFreeze({
statusSamples: [
{ tMs: 0, ms: 16_000, ok: true },
{ tMs: 16_000, ms: 16_000, ok: true },
{ tMs: 32_000, ms: 16_000, ok: false, hang: true }
],
foreverWindowMs: 30_000,
statusSlowMs: 15_000
})
expect(forever.foreverUiLockupObserved).toBe(true)
expect(forever.longestUnhealthyWindowMs).toBeGreaterThanOrEqual(30_000)
expect(
evaluateFullAppFreeze({ statusSamples: [], killOnlyRecovery: true }).foreverUiLockupObserved
).toBe(true)
})
it('does not classify watchdog infrastructure errors as an app freeze', () => {
const result = evaluateFullAppFreeze({
statusSamples: Array.from({ length: 25 }, (_, index) => ({
tMs: index * 1500,
ms: 1,
ok: false,
infrastructureError: true,
error: 'spawn ENOENT'
}))
})
expect(result.foreverUiLockupObserved).toBe(false)
expect(result.unhealthySampleCount).toBe(0)
expect(result.infrastructureErrorCount).toBe(25)
})
it('preserves full-run watchdog peaks after sample retention rotates', () => {
const result = evaluateFullAppFreeze({
statusSamples: [{ tMs: 60_000, ms: 100, ok: true }],
statusSummary: {
sampleCount: 40,
maxStatusMs: 16_000,
unhealthySampleCount: 3,
infrastructureErrorCount: 2,
longestUnhealthyWindowMs: 32_000
},
foreverWindowMs: 30_000,
statusSlowMs: 15_000
})
expect(result.foreverUiLockupObserved).toBe(true)
expect(result.longestUnhealthyWindowMs).toBe(32_000)
expect(result.maxStatusMs).toBe(16_000)
expect(result.unhealthySampleCount).toBe(3)
expect(result.infrastructureErrorCount).toBe(2)
})
it('rejects invalid numeric environment values', () => {
process.env.ORCA_FREEZE_TEST_NUMBER = 'not-a-number'
expect(() => readFreezeNumberEnv('ORCA_FREEZE_TEST_NUMBER', 5)).toThrow(
'Invalid ORCA_FREEZE_TEST_NUMBER'
)
delete process.env.ORCA_FREEZE_TEST_NUMBER
expect(readFreezeNumberEnv('ORCA_FREEZE_TEST_NUMBER', 5)).toBe(5)
})
it('distinguishes recovered hard stall from permanent lockup', () => {
// Single reveal timeout with healthy status is NOT permanent app lockup.
expect(
evaluatePermanentLockup({
timedOutOps: 1,
statusHangMs: 0,
consecutiveSwitchFailures: 1,
openFailed: 1,
openTotal: 64
}).permanentLockup
).toBe(false)
expect(
evaluatePermanentLockup({
timedOutOps: 3,
statusHangMs: 0,
consecutiveSwitchFailures: 0,
openFailed: 3,
openTotal: 64
}).permanentLockup
).toBe(true)
expect(
evaluatePermanentLockup({
timedOutOps: 0,
statusHangMs: 60_000,
consecutiveSwitchFailures: 0,
permanentTimeoutMs: 60_000
}).permanentLockup
).toBe(true)
expect(
evaluatePermanentLockup({
timedOutOps: 0,
statusHangMs: 0,
consecutiveSwitchFailures: 5
}).permanentLockup
).toBe(true)
expect(
evaluatePermanentLockup({
timedOutOps: 0,
openFailed: 20,
openTotal: 40
}).permanentLockup
).toBe(true)
})
it('human pace delay stays within base+jitter', () => {
for (let i = 0; i < 20; i += 1) {
const d = humanPaceDelayMs(250, 150)
expect(d).toBeGreaterThanOrEqual(250)
expect(d).toBeLessThanOrEqual(400)
}
expect(humanPaceDelayMs(100, 0)).toBe(100)
})
it('reads the real hard-freeze lab report when present', async () => {
const { readdirSync, readFileSync, existsSync } = await import('node:fs')
const { resolve } = await import('node:path')
const reportDir = resolve(process.cwd(), 'test-results/freeze-repro')
if (!existsSync(reportDir)) {
// Local clones without lab artifacts still pass pure metrics tests above.
return
}
const reportName = readdirSync(reportDir).find(
(name) => name.startsWith('live-bulk-open-freeze-') && name.endsWith('.json')
)
if (reportName == null) {
return
}
const report = JSON.parse(readFileSync(resolve(reportDir, reportName), 'utf8'))
const evaluated = evaluateFreezeSignals({
maxSwitchMs: report.maxSwitchMs,
maxBatchWallMs: report.maxBatchWallMs ?? 0,
statusProbeMs: report.statusProbeMs ?? 0,
memoryProbeMs: report.memoryProbeMs,
softMs: report.softMs,
hardMs: report.hardMs
})
expect(evaluated.hardFreeze).toBe(report.hardFreeze)
expect(evaluated.peakLatencyMs).toBeGreaterThanOrEqual(5000)
expect(typeof report.environment).toBe('string')
expect(report.environment.length).toBeGreaterThan(0)
expect(report.switchTargets).toBeGreaterThan(50)
expect(report.parallel).toBeGreaterThanOrEqual(8)
})
})
@@ -0,0 +1,358 @@
#!/usr/bin/env node
/**
* Live freeze repro against a running Orca desktop + paired remote runtime.
*
* Models bulk-open of remote sessions under multi-worktree load.
*
* Usage:
* node config/scripts/live-remote-bulk-open-freeze-repro.mjs
* ORCA_FREEZE_ENV=paired-remote ORCA_FREEZE_CREATE=12 ORCA_FREEZE_SWITCH_PASSES=5 \
* ORCA_FREEZE_PARALLEL=8 node config/scripts/live-remote-bulk-open-freeze-repro.mjs
*/
import { spawnSync } from 'node:child_process'
import { mkdirSync, writeFileSync, copyFileSync } from 'node:fs'
import path from 'node:path'
import { BoundedLiveFreezeHistory } from './live-freeze-bounded-history.mjs'
import {
applySwitchTargetCap,
DEFAULT_HARD_MS,
DEFAULT_SOFT_MS,
evaluateFreezeSignals,
extractTerminalHandle,
readFreezeNumberEnv,
shouldCapSwitchTargets,
worktreeSelector
} from './live-remote-bulk-open-freeze-metrics.mjs'
import { createOrcaRpc } from './live-remote-freeze-rpc.mjs'
const root = path.resolve(import.meta.dirname, '../..')
const reportDir = path.join(root, 'test-results', 'freeze-repro')
const envName = process.env.ORCA_FREEZE_ENV || 'paired-remote'
const createCount = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_CREATE', 0))
const switchPasses = Math.max(1, readFreezeNumberEnv('ORCA_FREEZE_SWITCH_PASSES', 3))
const parallel = Math.max(1, readFreezeNumberEnv('ORCA_FREEZE_PARALLEL', 1))
// 0 = no cap (use all live terminals). Only positive env values limit targets.
const maxSwitchTargets = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_MAX_SWITCH_TARGETS', 0))
const softMs = readFreezeNumberEnv('ORCA_FREEZE_SOFT_MS', DEFAULT_SOFT_MS)
const hardMs = readFreezeNumberEnv('ORCA_FREEZE_HARD_MS', DEFAULT_HARD_MS)
const createWorktreeSpan = Math.max(1, readFreezeNumberEnv('ORCA_FREEZE_CREATE_WT_SPAN', 16))
const preFloodMs = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_PRE_FLOOD_MS', 3000))
const scratchDir = process.env.ORCA_FREEZE_SCRATCH || ''
const { orcaJsonSync, orcaJsonAsync } = createOrcaRpc({ envName })
async function mapPool(items, concurrency, worker) {
const results = Array.from({ length: items.length })
let next = 0
async function run() {
while (next < items.length) {
const index = next
next += 1
results[index] = await worker(items[index], index)
}
}
const runners = Array.from({ length: Math.min(concurrency, items.length) }, () => run())
await Promise.all(runners)
return results
}
function sampleOrcaIfPossible() {
if (process.platform !== 'darwin') {
return null
}
try {
const status = orcaJsonSync(['status'], { local: true }).result
const pid = status?.app?.pid
if (!pid) {
return null
}
const out = path.join(reportDir, `orca-sample-${Date.now()}.txt`)
const sampled = spawnSync('sample', [String(pid), '5', '-file', out], {
timeout: 20_000,
stdio: 'ignore'
})
return sampled.status === 0 ? out : null
} catch {
return null
}
}
function floodCommand(marker) {
// Continuous 2KB frames @ ~8ms — agent-like remote output.
const script =
"const m=process.argv[1];process.stdout.write('READY:'+m+'\\n');let f=0;const c='A'.repeat(2048);setInterval(()=>{f++;process.stdout.write('BG:'+m+':'+f+':'+c+'\\n')},8);process.stdin.resume()"
return `node -e ${JSON.stringify(script)} ${JSON.stringify(marker)}`
}
async function main() {
mkdirSync(reportDir, { recursive: true })
const notes = []
const timings = new BoundedLiveFreezeHistory(120)
const amplificationSteps = []
console.log(
`[live-freeze] env=${envName} create=${createCount} passes=${switchPasses} parallel=${parallel}`
)
const status = orcaJsonSync(['status'])
notes.push(
`remote version=${status.result?.runtime?.appVersion} state=${status.result?.runtime?.state}`
)
const local = orcaJsonSync(['status'], { local: true })
notes.push(`local version=${local.result?.runtime?.appVersion} pid=${local.result?.app?.pid}`)
const worktrees = orcaJsonSync(['worktree', 'list']).result
const wtList = worktrees?.worktrees || worktrees?.items || worktrees || []
if (!Array.isArray(wtList) || wtList.length === 0) {
throw new Error(`No worktrees on environment ${envName}`)
}
notes.push(`remote worktrees=${wtList.length}`)
amplificationSteps.push(`baseline worktrees=${wtList.length}`)
const targets = wtList.slice(0, Math.min(createWorktreeSpan, wtList.length))
const created = []
// Parallel flood-terminal creates across many worktrees.
if (createCount > 0) {
amplificationSteps.push(`create=${createCount} parallel=${Math.min(parallel, createCount)}`)
const createJobs = Array.from({ length: createCount }, (_, i) => i)
await mapPool(createJobs, Math.min(parallel, createCount), async (i) => {
const wt = targets[i % targets.length]
const selector = worktreeSelector(wt)
if (!selector) {
notes.push(`create ${i} skipped: no selector`)
return
}
const marker = `LIVE_BULK_${Date.now()}_${i}`
try {
const createdTerm = await orcaJsonAsync(
[
'terminal',
'create',
'--worktree',
selector,
'--title',
`freeze-repro-${i}`,
'--command',
floodCommand(marker)
],
{ timeoutMs: 180_000 }
)
timings.add({ op: 'terminal.create', ms: createdTerm.elapsedMs, ok: true, index: i })
const handle = extractTerminalHandle(createdTerm.result)
if (handle) {
created.push({ handle, marker, worktree: selector })
console.log(
`[live-freeze] created ${handle} on ${selector} in ${createdTerm.elapsedMs.toFixed(0)}ms`
)
} else {
notes.push(
`create ${i} missing handle: ${JSON.stringify(createdTerm.result).slice(0, 400)}`
)
}
} catch (error) {
timings.add({ op: 'terminal.create', ms: null, ok: false, error: String(error), index: i })
notes.push(`create ${i} failed: ${String(error).slice(0, 300)}`)
console.warn(`[live-freeze] create failed: ${String(error)}`)
}
})
}
if (preFloodMs > 0 && created.length > 0) {
amplificationSteps.push(`preFloodMs=${preFloodMs}`)
await new Promise((r) => setTimeout(r, preFloodMs))
}
let live = []
try {
const listed = orcaJsonSync(['terminal', 'list'])
const terms = listed.result?.terminals || []
live = terms
.filter(
(t) => typeof t.handle === 'string' && t.handle.startsWith('term_') && t.connected !== false
)
.map((t) => ({ handle: t.handle, title: t.title, worktreeId: t.worktreeId }))
notes.push(`live terminals listed=${live.length}`)
} catch (error) {
notes.push(`terminal list failed: ${String(error).slice(0, 200)}`)
}
let switchTargets = [...created.map((c) => c.handle), ...live.map((t) => t.handle)].filter(
(v, i, a) => typeof v === 'string' && a.indexOf(v) === i
)
if (shouldCapSwitchTargets(maxSwitchTargets) && switchTargets.length > maxSwitchTargets) {
switchTargets = applySwitchTargetCap(switchTargets, maxSwitchTargets)
amplificationSteps.push(`capped switchTargets=${maxSwitchTargets}`)
}
if (switchTargets.length < 2) {
throw new Error(
`Need ≥2 terminals to bulk-switch; got ${switchTargets.length}. notes=${notes.join('; ')}`
)
}
amplificationSteps.push(
`switchTargets=${switchTargets.length} passes=${switchPasses} parallel=${parallel}`
)
console.log(
`[live-freeze] bulk-switching ${switchTargets.length} terminals × ${switchPasses} passes (parallel=${parallel})`
)
let maxSwitchMs = 0
let maxBatchWallMs = 0
let sumSwitchMs = 0
let switchCount = 0
const switchStarted = performance.now()
for (let pass = 0; pass < switchPasses; pass += 1) {
// Chunk targets into concurrent batches — piles load onto client/UI path.
for (let offset = 0; offset < switchTargets.length; offset += parallel) {
const batch = switchTargets.slice(offset, offset + parallel)
const batchStarted = performance.now()
const batchResults = await Promise.all(
batch.map(async (handle) => {
try {
const sw = await orcaJsonAsync(['terminal', 'switch', '--terminal', handle], {
timeoutMs: 90_000
})
return { handle, ms: sw.elapsedMs, ok: true }
} catch (error) {
return { handle, error: String(error), ok: false }
}
})
)
const batchWall = performance.now() - batchStarted
maxBatchWallMs = Math.max(maxBatchWallMs, batchWall)
for (const item of batchResults) {
if (item.ok) {
maxSwitchMs = Math.max(maxSwitchMs, item.ms)
sumSwitchMs += item.ms
switchCount += 1
timings.add({ op: 'terminal.switch', handle: item.handle, ms: item.ms, batchWall })
if (item.ms >= softMs) {
console.warn(`[live-freeze] SOFT lag on switch ${item.handle}: ${item.ms.toFixed(0)}ms`)
}
if (item.ms >= hardMs) {
console.warn(`[live-freeze] HARD lag on switch ${item.handle}: ${item.ms.toFixed(0)}ms`)
}
} else {
timings.add({ op: 'terminal.switch', handle: item.handle, error: item.error })
notes.push(`switch ${item.handle} failed: ${String(item.error).slice(0, 200)}`)
}
}
if (batchWall >= softMs) {
console.warn(`[live-freeze] SOFT batch wall=${batchWall.toFixed(0)}ms size=${batch.length}`)
}
if (batchWall >= hardMs) {
console.warn(`[live-freeze] HARD batch wall=${batchWall.toFixed(0)}ms size=${batch.length}`)
}
}
}
const bulkWallMs = performance.now() - switchStarted
const avgSwitchMs = switchCount ? sumSwitchMs / switchCount : 0
const statusProbe = orcaJsonSync(['status'], { local: true })
let memoryProbeMs = null
try {
const mem = orcaJsonSync(['diagnostics', 'memory'], { local: true, timeoutMs: 120_000 })
memoryProbeMs = mem.elapsedMs
notes.push(`memory diagnostic ms=${mem.elapsedMs.toFixed(0)}`)
} catch (error) {
notes.push(`memory diagnostic failed: ${String(error).slice(0, 200)}`)
}
const { peakLatencyMs, softFreeze, hardFreeze } = evaluateFreezeSignals({
maxSwitchMs,
maxBatchWallMs,
statusProbeMs: statusProbe.elapsedMs,
memoryProbeMs,
softMs,
hardMs
})
let samplePath = null
if (softFreeze || hardFreeze) {
samplePath = sampleOrcaIfPossible()
if (samplePath) {
notes.push(`sample=${samplePath}`)
} else {
notes.push('sample unavailable')
}
}
const report = {
topology: 'live-paired-remote',
environment: envName,
localVersion: local.result?.runtime?.appVersion,
remoteVersion: status.result?.runtime?.appVersion,
remoteWorktreeCount: wtList.length,
createdTerminals: created.length,
switchTargets: switchTargets.length,
switchPasses,
parallel,
maxSwitchMs,
maxBatchWallMs,
peakLatencyMs,
avgSwitchMs,
bulkWallMs,
statusProbeMs: statusProbe.elapsedMs,
memoryProbeMs,
softFreeze,
hardFreeze,
softMs,
hardMs,
amplificationSteps,
notes,
timingCount: timings.totalCount,
timings: timings.values()
}
const outPath = path.join(reportDir, `live-bulk-open-freeze-${envName}.json`)
writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`)
// Also write a stamped peak report so amplification runs don't overwrite history.
const stamped = path.join(reportDir, `live-bulk-open-freeze-${envName}-peak-${Date.now()}.json`)
writeFileSync(stamped, `${JSON.stringify(report, null, 2)}\n`)
console.log(`[live-freeze] report ${outPath}`)
console.log(`[live-freeze] stamped ${stamped}`)
console.log(JSON.stringify(report, null, 2))
if (scratchDir) {
try {
mkdirSync(scratchDir, { recursive: true })
copyFileSync(outPath, path.join(scratchDir, 'live-bulk-open-freeze-report.json'))
writeFileSync(
path.join(scratchDir, 'live-freeze-amplify-summary.json'),
`${JSON.stringify(
{
peakLatencyMs,
hardFreeze,
softFreeze,
amplificationSteps,
stamped
},
null,
2
)}\n`
)
} catch (error) {
notes.push(`scratch copy failed: ${String(error).slice(0, 200)}`)
}
}
if (hardFreeze) {
process.exitCode = 2
console.error('[live-freeze] HARD FREEZE SIGNAL')
} else if (softFreeze) {
process.exitCode = 1
console.error('[live-freeze] SOFT FREEZE SIGNAL')
} else {
console.log('[live-freeze] no freeze signal under thresholds')
}
}
main().catch((error) => {
console.error('[live-freeze] failed', error)
process.exit(3)
})
+241
View File
@@ -0,0 +1,241 @@
import { spawn, spawnSync } from 'node:child_process'
import path from 'node:path'
export const MAX_ORCA_RPC_OUTPUT_BYTES = 20 * 1024 * 1024
export function appendOrcaRpcOutput(output, chunk, bytes, limit = MAX_ORCA_RPC_OUTPUT_BYTES) {
const nextBytes = bytes + Buffer.byteLength(chunk)
return {
output: nextBytes > limit ? output : output + chunk,
bytes: nextBytes,
exceeded: nextBytes > limit
}
}
export function resolveOrcaCliCommand({ env = process.env, platform = process.platform } = {}) {
if (env.ORCA_CLI_COMMAND?.trim()) {
return env.ORCA_CLI_COMMAND.trim()
}
if (env.ORCA_DEV_REPO_ROOT) {
return 'orca-dev'
}
return platform === 'linux' ? 'orca-ide' : 'orca'
}
export function resolveOrcaCliInvocation({
env = process.env,
platform = process.platform,
nodeExecutable = process.execPath
} = {}) {
const command = resolveOrcaCliCommand({ env, platform })
const commandName = platform === 'win32' ? path.win32.basename(command).toLowerCase() : command
if (
platform === 'win32' &&
env.ORCA_DEV_REPO_ROOT &&
(commandName === 'orca-dev' || commandName === 'orca-dev.cmd')
) {
const defaultUserDataPath = path.win32.join(
env.APPDATA ?? path.win32.join(env.USERPROFILE ?? '', 'AppData', 'Roaming'),
'orca-dev'
)
return {
command: nodeExecutable,
prefixArgs: [path.win32.join(env.ORCA_DEV_REPO_ROOT, 'out', 'cli', 'index.js')],
env: {
...env,
ORCA_USER_DATA_PATH:
env.ORCA_USER_DATA_PATH ?? env.ORCA_DEV_USER_DATA_PATH ?? defaultUserDataPath,
ORCA_DEV_CLI_INVOCATION: '1',
ORCA_APP_EXECUTABLE:
env.ORCA_APP_EXECUTABLE ??
path.win32.join(
env.ORCA_DEV_REPO_ROOT,
'node_modules',
'electron',
'dist',
'electron.exe'
),
ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT: '1'
}
}
}
return { command, prefixArgs: [] }
}
export function createOrcaRpc({
envName,
cliCommand,
env = process.env,
platform = process.platform
}) {
const cliInvocation = cliCommand
? { command: cliCommand, prefixArgs: [] }
: resolveOrcaCliInvocation({ env, platform })
const commandLabel = cliCommand ?? resolveOrcaCliCommand({ env, platform })
const commandArgs = (args, local) => [
...cliInvocation.prefixArgs,
...args,
...(local ? [] : ['--environment', envName]),
'--json'
]
function orcaJsonSync(args, opts = {}) {
const started = performance.now()
const result = spawnSync(cliInvocation.command, commandArgs(args, opts.local), {
encoding: 'utf8',
env: cliInvocation.env,
maxBuffer: MAX_ORCA_RPC_OUTPUT_BYTES,
timeout: opts.timeoutMs ?? 120_000
})
const elapsedMs = performance.now() - started
if (result.error) {
throw new Error(`${commandLabel} ${args.join(' ')} failed to start: ${String(result.error)}`)
}
if (result.status !== 0) {
throw new Error(
`${commandLabel} ${args.join(' ')} failed (${result.status}): ${result.stderr || result.stdout}`
)
}
const parsed = JSON.parse(result.stdout)
if (parsed.ok === false) {
throw new Error(`${commandLabel} ${args.join(' ')} ok=false: ${JSON.stringify(parsed)}`)
}
return { parsed, elapsedMs, result: parsed.result }
}
function orcaJsonAsync(args, opts = {}) {
const started = performance.now()
return new Promise((resolve, reject) => {
const child = spawn(cliInvocation.command, commandArgs(args, opts.local), {
env: cliInvocation.env,
stdio: ['ignore', 'pipe', 'pipe']
})
let stdout = ''
let stderr = ''
let outputBytes = 0
let settled = false
let timer
const fail = (error) => {
if (settled) {
return
}
settled = true
clearTimeout(timer)
reject(error)
}
const append = (stream, chunk) => {
if (settled) {
return stream
}
const appended = appendOrcaRpcOutput(stream, chunk, outputBytes)
outputBytes = appended.bytes
if (appended.exceeded) {
child.kill('SIGKILL')
fail(new Error(`${commandLabel} ${args.join(' ')} exceeded 20 MiB output limit`))
return stream
}
return appended.output
}
timer = setTimeout(() => {
child.kill('SIGKILL')
fail(
new Error(
`${commandLabel} ${args.join(' ')} timed out after ${opts.timeoutMs ?? 120_000}ms`
)
)
}, opts.timeoutMs ?? 120_000)
child.stdout.setEncoding('utf8')
child.stderr.setEncoding('utf8')
child.stdout.on('data', (chunk) => {
stdout = append(stdout, chunk)
})
child.stderr.on('data', (chunk) => {
stderr = append(stderr, chunk)
})
child.on('error', fail)
child.on('close', (code) => {
if (settled) {
return
}
clearTimeout(timer)
const elapsedMs = performance.now() - started
if (code !== 0) {
fail(
new Error(
`${commandLabel} ${args.join(' ')} failed (${code}): ${stderr || stdout}`.slice(
0,
800
)
)
)
return
}
try {
const parsed = JSON.parse(stdout)
if (parsed.ok === false) {
fail(
new Error(
`${commandLabel} ${args.join(' ')} ok=false: ${JSON.stringify(parsed)}`.slice(
0,
800
)
)
)
return
}
settled = true
resolve({ parsed, elapsedMs, result: parsed.result })
} catch (error) {
fail(
new Error(
`${commandLabel} parse failed: ${String(error)}; stdout=${stdout.slice(0, 400)}`
)
)
}
})
})
}
async function runReconnectRefreshStorm(notes) {
const started = performance.now()
const jobs = [
() => orcaJsonAsync(['status'], { timeoutMs: 90_000 }),
() => orcaJsonAsync(['worktree', 'list'], { timeoutMs: 120_000 }),
() => orcaJsonAsync(['terminal', 'list'], { timeoutMs: 120_000 }),
() => orcaJsonAsync(['status'], { local: true, timeoutMs: 60_000 }),
() => orcaJsonAsync(['worktree', 'list'], { timeoutMs: 120_000 }),
() => orcaJsonAsync(['terminal', 'list'], { timeoutMs: 120_000 })
]
const results = await Promise.all(
jobs.map(async (job, index) => {
try {
const result = await job()
return { index, ok: true, ms: result.elapsedMs }
} catch (error) {
notes.push(`reconnect-refresh job ${index} failed: ${String(error).slice(0, 200)}`)
return { index, ok: false, ms: null, error: String(error) }
}
})
)
const wallMs = performance.now() - started
const maxJobMs = Math.max(0, ...results.map((result) => result.ms || 0))
notes.push(
`reconnect-refresh wall=${wallMs.toFixed(0)}ms maxJob=${maxJobMs.toFixed(0)}ms ok=${results.filter((result) => result.ok).length}/${results.length}`
)
return { wallMs, maxJobMs, results }
}
async function runRestartProxy(notes) {
const started = performance.now()
try {
const opened = await orcaJsonAsync(['open'], { local: true, timeoutMs: 120_000 })
notes.push(`orca open ms=${opened.elapsedMs.toFixed(0)}`)
} catch (error) {
notes.push(`orca open failed: ${String(error).slice(0, 200)}`)
}
const storm = await runReconnectRefreshStorm(notes)
return { wallMs: performance.now() - started, storm }
}
return { orcaJsonSync, orcaJsonAsync, runReconnectRefreshStorm, runRestartProxy }
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import {
appendOrcaRpcOutput,
resolveOrcaCliCommand,
resolveOrcaCliInvocation
} from './live-remote-freeze-rpc.mjs'
describe('live remote freeze RPC', () => {
it('resolves the Orca CLI for managed, dev, Linux, and default runtimes', () => {
expect(resolveOrcaCliCommand({ env: { ORCA_CLI_COMMAND: 'custom-orca' } })).toBe('custom-orca')
expect(resolveOrcaCliCommand({ env: { ORCA_DEV_REPO_ROOT: '/repo' } })).toBe('orca-dev')
expect(resolveOrcaCliCommand({ env: {}, platform: 'linux' })).toBe('orca-ide')
expect(resolveOrcaCliCommand({ env: {}, platform: 'win32' })).toBe('orca')
})
it('bypasses the Windows dev cmd shim with the built Node CLI', () => {
const invocation = resolveOrcaCliInvocation({
env: {
APPDATA: 'C:\\Users\\dev\\AppData\\Roaming',
ORCA_CLI_COMMAND: 'C:\\repo\\out\\bin\\orca-dev.cmd',
ORCA_DEV_REPO_ROOT: 'C:\\repo'
},
platform: 'win32',
nodeExecutable: 'C:\\Program Files\\nodejs\\node.exe'
})
expect(invocation).toMatchObject({
command: 'C:\\Program Files\\nodejs\\node.exe',
prefixArgs: ['C:\\repo\\out\\cli\\index.js'],
env: {
ORCA_USER_DATA_PATH: 'C:\\Users\\dev\\AppData\\Roaming\\orca-dev',
ORCA_DEV_CLI_INVOCATION: '1',
ORCA_APP_EXECUTABLE: 'C:\\repo\\node_modules\\electron\\dist\\electron.exe',
ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT: '1'
}
})
})
it('caps combined asynchronous output before retaining the overflow chunk', () => {
const first = appendOrcaRpcOutput('', '1234', 0, 5)
expect(first).toEqual({ output: '1234', bytes: 4, exceeded: false })
const overflow = appendOrcaRpcOutput(first.output, '67', first.bytes, 5)
expect(overflow).toEqual({ output: '1234', bytes: 6, exceeded: true })
})
})
@@ -0,0 +1,645 @@
#!/usr/bin/env node
/**
* Naturalistic freeze repro — idle/reconnect recovery stories on large remotes.
*
* Unlike the bulk parallel-switch amplifier, this models:
* 1) agents streaming on remote while user is idle (backlog builds)
* 2) user returns and opens sessions one-by-one (or after reconnect refresh)
*
* Scenarios:
* idle-backlog-open — idle with flood, then human-paced sequential open
* idle-backlog-reconnect-open — same + wake-like metadata refresh storm, then open
* restart-proxy — idle, then orca open + status/list storm + open
* (does NOT kill the desktop; proxies restore work)
*
* Usage:
* ORCA_FREEZE_ENV=paired-remote ORCA_FREEZE_SCENARIO=idle-backlog-open \
* node config/scripts/live-remote-realistic-freeze-repro.mjs
*
* pnpm run repro:live-remote-realistic-freeze
*/
import { spawnSync } from 'node:child_process'
import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { createOrcaRpc } from './live-remote-freeze-rpc.mjs'
import { startStatusWatchdog } from './live-remote-status-watchdog.mjs'
import { BoundedLiveFreezeHistory } from './live-freeze-bounded-history.mjs'
import {
DEFAULT_FOREVER_WINDOW_MS,
DEFAULT_HARD_MS,
DEFAULT_SOFT_MS,
DEFAULT_STATUS_SLOW_MS,
evaluateFullAppFreeze,
evaluatePermanentLockup,
evaluateRealisticFreezeSignals,
extractTerminalHandle,
humanPaceDelayMs,
readFreezeNumberEnv,
REALISTIC_SCENARIOS,
worktreeSelector
} from './live-remote-bulk-open-freeze-metrics.mjs'
const root = path.resolve(import.meta.dirname, '../..')
const reportDir = path.join(root, 'test-results', 'freeze-repro')
const envName = process.env.ORCA_FREEZE_ENV || 'paired-remote'
const scenario = process.env.ORCA_FREEZE_SCENARIO || 'idle-backlog-open'
const createCount = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_CREATE', 0))
const openCount = Math.max(2, readFreezeNumberEnv('ORCA_FREEZE_OPEN_COUNT', 20))
const idleMs = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_IDLE_MS', 45_000))
const paceMs = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_PACE_MS', 250))
const paceJitterMs = Math.max(0, readFreezeNumberEnv('ORCA_FREEZE_PACE_JITTER_MS', 150))
const createWorktreeSpan = Math.max(1, readFreezeNumberEnv('ORCA_FREEZE_CREATE_WT_SPAN', 12))
const softMs = readFreezeNumberEnv('ORCA_FREEZE_SOFT_MS', DEFAULT_SOFT_MS)
const hardMs = readFreezeNumberEnv('ORCA_FREEZE_HARD_MS', DEFAULT_HARD_MS)
/** Concurrent opens during lockup-storm (wake refresh overlaps fan-out). */
const stormParallel = Math.max(1, readFreezeNumberEnv('ORCA_FREEZE_STORM_PARALLEL', 16))
/** Kill a switch if it exceeds this — counts toward permanent lockup. */
const opTimeoutMs = Math.max(10_000, readFreezeNumberEnv('ORCA_FREEZE_OP_TIMEOUT_MS', 60_000))
const permanentTimeoutMs = Math.max(15_000, readFreezeNumberEnv('ORCA_FREEZE_PERMANENT_MS', 60_000))
const foreverWindowMs = Math.max(
10_000,
readFreezeNumberEnv('ORCA_FREEZE_FOREVER_WINDOW_MS', DEFAULT_FOREVER_WINDOW_MS)
)
const statusSlowMs = Math.max(
5_000,
readFreezeNumberEnv('ORCA_FREEZE_STATUS_SLOW_MS', DEFAULT_STATUS_SLOW_MS)
)
const watchdogIntervalMs = Math.max(
500,
readFreezeNumberEnv('ORCA_FREEZE_WATCHDOG_INTERVAL_MS', 1500)
)
const scratchDir = process.env.ORCA_FREEZE_SCRATCH || ''
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
const rpc = createOrcaRpc({ envName })
const { orcaJsonSync, orcaJsonAsync, runReconnectRefreshStorm, runRestartProxy } = rpc
async function mapPool(items, concurrency, worker) {
const results = Array.from({ length: items.length })
let next = 0
async function run() {
while (next < items.length) {
const index = next
next += 1
results[index] = await worker(items[index], index)
}
}
await Promise.all(
Array.from({ length: Math.min(concurrency, Math.max(items.length, 1)) }, () => run())
)
return results
}
function floodCommand(marker) {
const script =
"const m=process.argv[1];process.stdout.write('READY:'+m+'\n');let f=0;const c='A'.repeat(2048);setInterval(()=>{f++;process.stdout.write('BG:'+m+':'+f+':'+c+'\n')},8);process.stdin.resume()"
return `node -e ${JSON.stringify(script)} ${JSON.stringify(marker)}`
}
function sampleOrcaIfPossible() {
if (process.platform !== 'darwin') {
return null
}
try {
const status = orcaJsonSync(['status'], { local: true }).result
const pid = status?.app?.pid
if (!pid) {
return null
}
const out = path.join(reportDir, `orca-sample-realistic-${Date.now()}.txt`)
const sampled = spawnSync('sample', [String(pid), '5', '-file', out], {
timeout: 20_000,
stdio: 'ignore'
})
return sampled.status === 0 ? out : null
} catch {
return null
}
}
function listLiveTerminalHandles() {
const listed = orcaJsonSync(['terminal', 'list'])
const terms = listed.result?.terminals || []
return terms
.filter((t) => typeof t.handle === 'string' && t.handle.startsWith('term_'))
.map((t) => ({
handle: t.handle,
title: t.title,
worktreeId: t.worktreeId,
connected: t.connected
}))
}
async function main() {
if (!REALISTIC_SCENARIOS.includes(scenario)) {
throw new Error(
`Unknown ORCA_FREEZE_SCENARIO=${scenario}. Expected one of: ${REALISTIC_SCENARIOS.join(', ')}`
)
}
mkdirSync(reportDir, { recursive: true })
const notes = []
const phases = []
const openTimings = new BoundedLiveFreezeHistory(100)
console.log(
`[realistic-freeze] scenario=${scenario} env=${envName} create=${createCount} idleMs=${idleMs} openCount=${openCount} paceMs=${paceMs}`
)
const local = orcaJsonSync(['status'], { local: true })
const remote = orcaJsonSync(['status'])
notes.push(
`local version=${local.result?.runtime?.appVersion} pid=${local.result?.app?.pid}`,
`remote version=${remote.result?.runtime?.appVersion} state=${remote.result?.runtime?.state}`
)
const worktrees = orcaJsonSync(['worktree', 'list']).result
const wtList = worktrees?.worktrees || worktrees?.items || worktrees || []
if (!Array.isArray(wtList) || wtList.length === 0) {
throw new Error(`No worktrees on environment ${envName}`)
}
notes.push(`remote worktrees=${wtList.length}`)
phases.push({ phase: 'baseline', worktrees: wtList.length })
// --- Phase: seed flood terminals (agent-like backlog sources) ---
const created = []
if (createCount > 0) {
const targets = wtList.slice(0, Math.min(createWorktreeSpan, wtList.length))
await mapPool(
Array.from({ length: createCount }, (_, i) => i),
Math.min(4, createCount),
async (i) => {
const wt = targets[i % targets.length]
const selector = worktreeSelector(wt)
if (!selector) {
return
}
const marker = `REALISTIC_${Date.now()}_${i}`
try {
const createdTerm = await orcaJsonAsync(
[
'terminal',
'create',
'--worktree',
selector,
'--title',
`realistic-freeze-${i}`,
'--command',
floodCommand(marker)
],
{ timeoutMs: 180_000 }
)
const handle = extractTerminalHandle(createdTerm.result)
if (handle) {
created.push({ handle, marker, worktree: selector })
console.log(
`[realistic-freeze] flood terminal ${handle} (${createdTerm.elapsedMs.toFixed(0)}ms)`
)
} else {
notes.push(
`create ${i} missing handle: ${JSON.stringify(createdTerm.result).slice(0, 300)}`
)
}
} catch (error) {
notes.push(`create ${i} failed: ${String(error).slice(0, 250)}`)
console.warn(`[realistic-freeze] create failed: ${String(error)}`)
}
}
)
phases.push({ phase: 'seed-flood', created: created.length })
}
// Prefer created floods for open pass; fill with existing live terminals.
let live = []
try {
live = listLiveTerminalHandles()
notes.push(`live terminals listed=${live.length}`)
} catch (error) {
notes.push(`terminal list failed: ${String(error).slice(0, 200)}`)
}
const openTargets = [...created.map((c) => c.handle), ...live.map((t) => t.handle)].filter(
(v, i, a) => typeof v === 'string' && a.indexOf(v) === i
)
if (openTargets.length < 2) {
throw new Error(`Need ≥2 terminals; got ${openTargets.length}. ${notes.join('; ')}`)
}
const openList = openTargets.slice(0, Math.min(openCount, openTargets.length))
// --- Phase: park — leave one session focused, rest accumulate flood while "away" ---
try {
const parkHandle = openList[0]
const parked = await orcaJsonAsync(['terminal', 'switch', '--terminal', parkHandle], {
timeoutMs: 60_000
})
notes.push(`park switch ms=${parked.elapsedMs.toFixed(0)} handle=${parkHandle}`)
} catch (error) {
notes.push(`park switch failed: ${String(error).slice(0, 200)}`)
}
console.log(`[realistic-freeze] idle ${idleMs}ms while remotes stream (user away / asleep)`)
const idleStarted = performance.now()
await sleep(idleMs)
phases.push({ phase: 'idle', idleMs, actualMs: performance.now() - idleStarted })
// --- Phase: recovery trigger ---
let reconnectRefreshMs = 0
let timedOutOps = 0
let consecutiveSwitchFailures = 0
let maxConsecutiveSwitchFailures = 0
if (scenario === 'idle-backlog-reconnect-open' || scenario === 'lockup-storm') {
console.log(
'[realistic-freeze] wake/reconnect proxy: parallel status/worktree/terminal refresh'
)
const storm = await runReconnectRefreshStorm(notes)
reconnectRefreshMs = Math.max(storm.wallMs, storm.maxJobMs)
phases.push({
phase: 'reconnect-refresh',
wallMs: storm.wallMs,
maxJobMs: storm.maxJobMs
})
} else if (scenario === 'restart-proxy') {
console.log('[realistic-freeze] restart proxy: orca open + refresh storm (no process kill)')
const restart = await runRestartProxy(notes)
reconnectRefreshMs = Math.max(restart.wallMs, restart.storm.wallMs, restart.storm.maxJobMs)
phases.push({
phase: 'restart-proxy',
wallMs: restart.wallMs,
reconnectWallMs: restart.storm.wallMs
})
}
// --- Phase: open sessions ---
// lockup-storm: overlap a second reconnect storm with concurrent switch fan-out
// (models wake + bulk session restore, not human serial clicks).
let maxOpenMs = 0
let firstOpenMs = 0
let sumOpenMs = 0
let openOk = 0
let maxBatchWallMs = 0
const openStarted = performance.now()
let statusWatch = null
if (scenario === 'lockup-storm') {
console.log(
`[realistic-freeze] LOCKUP STORM: concurrent open parallel=${stormParallel} + overlapping reconnect refresh (timeout=${opTimeoutMs}ms); mid-storm status watchdog every ${watchdogIntervalMs}ms`
)
statusWatch = startStatusWatchdog({
intervalMs: watchdogIntervalMs,
timeoutMs: Math.min(permanentTimeoutMs, foreverWindowMs),
statusSlowMs
})
// Fire reconnect storm again concurrently with first open wave.
const overlapStormPromise = runReconnectRefreshStorm(notes)
for (let offset = 0; offset < openList.length; offset += stormParallel) {
const batch = openList.slice(offset, offset + stormParallel)
const batchStarted = performance.now()
const batchResults = await Promise.all(
batch.map(async (handle, batchIndex) => {
const index = offset + batchIndex
try {
const sw = await orcaJsonAsync(['terminal', 'switch', '--terminal', handle], {
timeoutMs: opTimeoutMs
})
return { handle, index, ms: sw.elapsedMs, ok: true, timedOut: false }
} catch (error) {
const msg = String(error)
const timedOut = /timed out/i.test(msg)
return { handle, index, error: msg, ok: false, timedOut }
}
})
)
const batchWall = performance.now() - batchStarted
maxBatchWallMs = Math.max(maxBatchWallMs, batchWall)
for (const item of batchResults) {
if (item.ok) {
openOk += 1
sumOpenMs += item.ms
maxOpenMs = Math.max(maxOpenMs, item.ms)
if (item.index === 0 || firstOpenMs === 0) {
firstOpenMs = item.ms
}
consecutiveSwitchFailures = 0
openTimings.add({
handle: item.handle,
ms: item.ms,
index: item.index,
batchWall
})
if (item.ms >= hardMs) {
console.warn(
`[realistic-freeze] HARD open #${item.index} ${item.handle}: ${item.ms.toFixed(0)}ms`
)
}
} else {
if (item.timedOut) {
timedOutOps += 1
}
consecutiveSwitchFailures += 1
maxConsecutiveSwitchFailures = Math.max(
maxConsecutiveSwitchFailures,
consecutiveSwitchFailures
)
openTimings.add({
handle: item.handle,
error: item.error,
index: item.index,
timedOut: item.timedOut
})
notes.push(
`open ${item.handle} failed${item.timedOut ? ' (TIMEOUT)' : ''}: ${String(item.error).slice(0, 160)}`
)
console.warn(
`[realistic-freeze] open FAIL #${item.index}${item.timedOut ? ' TIMEOUT' : ''}: ${item.handle}`
)
}
}
if (batchWall >= hardMs) {
console.warn(
`[realistic-freeze] HARD batch wall=${batchWall.toFixed(0)}ms size=${batch.length}`
)
}
}
try {
const overlap = await overlapStormPromise
reconnectRefreshMs = Math.max(reconnectRefreshMs, overlap.wallMs, overlap.maxJobMs)
phases.push({
phase: 'overlap-reconnect-refresh',
wallMs: overlap.wallMs,
maxJobMs: overlap.maxJobMs
})
} catch (error) {
notes.push(`overlap reconnect failed: ${String(error).slice(0, 200)}`)
}
phases.push({
phase: 'lockup-storm-open',
count: openList.length,
ok: openOk,
maxOpenMs,
firstOpenMs,
maxBatchWallMs,
timedOutOps,
parallel: stormParallel
})
} else {
console.log(
`[realistic-freeze] human-paced open of ${openList.length} sessions (pace≈${paceMs}ms + jitter)`
)
for (let i = 0; i < openList.length; i += 1) {
const handle = openList[i]
try {
const sw = await orcaJsonAsync(['terminal', 'switch', '--terminal', handle], {
timeoutMs: opTimeoutMs
})
openOk += 1
sumOpenMs += sw.elapsedMs
maxOpenMs = Math.max(maxOpenMs, sw.elapsedMs)
if (i === 0) {
firstOpenMs = sw.elapsedMs
}
consecutiveSwitchFailures = 0
openTimings.add({ handle, ms: sw.elapsedMs, index: i })
if (sw.elapsedMs >= softMs) {
console.warn(`[realistic-freeze] SOFT open #${i} ${handle}: ${sw.elapsedMs.toFixed(0)}ms`)
}
if (sw.elapsedMs >= hardMs) {
console.warn(`[realistic-freeze] HARD open #${i} ${handle}: ${sw.elapsedMs.toFixed(0)}ms`)
}
} catch (error) {
const msg = String(error)
const timedOut = /timed out/i.test(msg)
if (timedOut) {
timedOutOps += 1
}
consecutiveSwitchFailures += 1
maxConsecutiveSwitchFailures = Math.max(
maxConsecutiveSwitchFailures,
consecutiveSwitchFailures
)
openTimings.add({ handle, error: msg, index: i, timedOut })
notes.push(`open ${handle} failed${timedOut ? ' (TIMEOUT)' : ''}: ${msg.slice(0, 200)}`)
}
if (i < openList.length - 1) {
await sleep(humanPaceDelayMs(paceMs, paceJitterMs))
}
}
phases.push({
phase: 'human-paced-open',
count: openList.length,
ok: openOk,
maxOpenMs,
firstOpenMs,
openWallMs: performance.now() - openStarted
})
}
const openWallMs = performance.now() - openStarted
let midStormWatch = {
samples: [],
durationMs: 0,
sampleCount: 0,
maxStatusMs: 0,
unhealthySampleCount: 0,
infrastructureErrorCount: 0,
longestUnhealthyWindowMs: 0
}
if (statusWatch) {
midStormWatch = await statusWatch.stop()
notes.push(
`mid-storm status samples=${midStormWatch.sampleCount} durationMs=${midStormWatch.durationMs.toFixed(0)}`
)
phases.push({
phase: 'mid-storm-status-watchdog',
samples: midStormWatch.sampleCount,
durationMs: midStormWatch.durationMs,
maxStatusMs: midStormWatch.maxStatusMs
})
}
// Post-storm health: does local status still answer?
let statusProbeMs = null
let statusHangMs = 0
const statusStarted = performance.now()
try {
const statusProbe = await orcaJsonAsync(['status'], {
local: true,
timeoutMs: permanentTimeoutMs
})
statusProbeMs = statusProbe.elapsedMs
} catch (error) {
statusHangMs = performance.now() - statusStarted
notes.push(
`status probe FAILED after ${statusHangMs.toFixed(0)}ms: ${String(error).slice(0, 200)}`
)
console.error(`[realistic-freeze] status probe failed — possible permanent lockup`)
}
let memoryProbeMs = null
try {
const mem = await orcaJsonAsync(['diagnostics', 'memory'], {
local: true,
timeoutMs: permanentTimeoutMs
})
memoryProbeMs = mem.elapsedMs
notes.push(`memory diagnostic ms=${mem.elapsedMs.toFixed(0)}`)
} catch (error) {
notes.push(`memory diagnostic failed: ${String(error).slice(0, 200)}`)
}
const peakForSignals = Math.max(maxOpenMs, firstOpenMs, maxBatchWallMs)
const signals = evaluateRealisticFreezeSignals({
maxOpenMs: peakForSignals,
firstOpenMs,
reconnectRefreshMs,
statusProbeMs: statusProbeMs ?? 0,
memoryProbeMs,
softMs,
hardMs
})
const lockup = evaluatePermanentLockup({
timedOutOps,
statusHangMs,
consecutiveSwitchFailures: maxConsecutiveSwitchFailures,
openFailed: openList.length - openOk,
openTotal: openList.length,
permanentTimeoutMs
})
const fullApp = evaluateFullAppFreeze({
statusSamples: midStormWatch.samples,
statusSummary: midStormWatch,
foreverWindowMs,
statusSlowMs
})
const watchdogInfrastructureErrorCount = midStormWatch.infrastructureErrorCount
if (statusHangMs >= foreverWindowMs) {
fullApp.foreverUiLockupObserved = true
fullApp.longestUnhealthyWindowMs = Math.max(fullApp.longestUnhealthyWindowMs, statusHangMs)
fullApp.reason = `post-storm status hang ${statusHangMs.toFixed(0)}ms`
}
const recoveredHardStall = signals.hardFreeze && !fullApp.foreverUiLockupObserved && openOk > 0
let samplePath = null
if (signals.softFreeze || signals.hardFreeze || fullApp.foreverUiLockupObserved) {
samplePath = sampleOrcaIfPossible()
if (samplePath) {
notes.push(`sample=${samplePath}`)
} else {
notes.push('sample unavailable')
}
}
const storyByScenario = {
'idle-backlog-open': 'User away while remotes stream; returns and opens sessions one-by-one.',
'idle-backlog-reconnect-open':
'User away; wake-like reconnect metadata storm; then opens sessions.',
'restart-proxy': 'User away; restart-proxy discovery; then opens sessions.',
'lockup-storm':
'Idle flood + reconnect refresh + concurrent open + mid-storm status watchdog (full-app freeze bar).'
}
const report = {
topology: 'live-paired-remote-realistic',
scenario,
story: storyByScenario[scenario] || scenario,
environment: envName,
localVersion: local.result?.runtime?.appVersion,
remoteVersion: remote.result?.runtime?.appVersion,
remoteWorktreeCount: wtList.length,
createdFloodTerminals: created.length,
openTargets: openList.length,
idleMs,
paceMs,
paceJitterMs,
stormParallel: scenario === 'lockup-storm' ? stormParallel : 1,
firstOpenMs,
maxOpenMs,
maxBatchWallMs,
avgOpenMs: openOk ? sumOpenMs / openOk : 0,
openWallMs,
openOk,
openFailed: openList.length - openOk,
reconnectRefreshMs,
peakLatencyMs: Math.max(signals.peakLatencyMs, maxBatchWallMs),
statusProbeMs,
statusHangMs,
memoryProbeMs,
softFreeze: signals.softFreeze,
hardFreeze: signals.hardFreeze,
recoveredHardStall,
permanentLockup: lockup.permanentLockup,
foreverUiLockupObserved: fullApp.foreverUiLockupObserved,
foreverFreeze: fullApp,
midStormStatusSamples: midStormWatch.samples,
midStormStatusSampleCount: midStormWatch.sampleCount,
watchdogInfrastructureErrorCount,
timedOutOps,
maxConsecutiveSwitchFailures,
softMs,
hardMs,
foreverWindowMs,
statusSlowMs,
permanentTimeoutMs,
opTimeoutMs,
phases,
notes,
openTimingCount: openTimings.totalCount,
openTimings: openTimings.values()
}
const outPath = path.join(reportDir, `live-realistic-freeze-${envName}-${scenario}.json`)
const stamped = path.join(
reportDir,
`live-realistic-freeze-${envName}-${scenario}-peak-${Date.now()}.json`
)
writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`)
writeFileSync(stamped, `${JSON.stringify(report, null, 2)}\n`)
console.log(`[realistic-freeze] report ${outPath}`)
console.log(JSON.stringify(report, null, 2))
if (scratchDir) {
try {
mkdirSync(scratchDir, { recursive: true })
copyFileSync(outPath, path.join(scratchDir, 'live-realistic-freeze-report.json'))
} catch (error) {
console.warn(`[realistic-freeze] scratch copy failed: ${String(error)}`)
}
}
if (watchdogInfrastructureErrorCount > 0) {
process.exitCode = 3
console.error('[realistic-freeze] WATCHDOG INFRASTRUCTURE FAILURE')
} else if (fullApp.foreverUiLockupObserved) {
process.exitCode = 5
console.error('[realistic-freeze] FULL-APP FOREVER FREEZE (status unhealthy ≥ forever window)')
} else if (lockup.permanentLockup) {
process.exitCode = 4
console.error(
'[realistic-freeze] PERMANENT LOCKUP HEURISTIC (timeouts/fail-rate) — check foreverUiLockupObserved'
)
} else if (signals.hardFreeze) {
process.exitCode = 2
console.error(
'[realistic-freeze] HARD FREEZE SIGNAL (recovered multi-second stall — not forever lockup)'
)
} else if (signals.softFreeze) {
process.exitCode = 1
console.error('[realistic-freeze] SOFT FREEZE SIGNAL')
} else {
console.log('[realistic-freeze] no freeze signal under thresholds')
}
}
main().catch((error) => {
console.error('[realistic-freeze] failed', error)
process.exit(3)
})
@@ -0,0 +1,147 @@
/**
* Mid-storm host health samples for forever-freeze detection.
* Polls `orca status --json` on an interval while a load storm runs.
*/
import { spawn } from 'node:child_process'
import { BoundedLiveFreezeHistory } from './live-freeze-bounded-history.mjs'
import { resolveOrcaCliInvocation } from './live-remote-freeze-rpc.mjs'
/**
* @param {{ intervalMs?: number, timeoutMs?: number, cliCommand?: string, sampleHistoryLimit?: number, statusSlowMs?: number }} opts
*/
export function startStatusWatchdog(opts = {}) {
const intervalMs = opts.intervalMs ?? 2000
const timeoutMs = opts.timeoutMs ?? 30_000
const cliInvocation = opts.cliCommand
? { command: opts.cliCommand, prefixArgs: [] }
: resolveOrcaCliInvocation()
const samples = new BoundedLiveFreezeHistory(opts.sampleHistoryLimit ?? 240)
const statusSlowMs = opts.statusSlowMs ?? 15_000
let stopped = false
let inFlight = false
let infrastructureErrorCount = 0
let longestUnhealthyWindowMs = 0
let maxStatusMs = 0
let runStartMs = null
let unhealthySampleCount = 0
const startedAt = performance.now()
const record = (sample) => {
samples.add(sample)
maxStatusMs = Math.max(maxStatusMs, sample.ms || 0)
if (sample.infrastructureError) {
infrastructureErrorCount += 1
}
const unhealthy =
!sample.infrastructureError &&
(Boolean(sample.hang) || sample.ok === false || (sample.ms || 0) >= statusSlowMs)
if (!unhealthy) {
runStartMs = null
return
}
unhealthySampleCount += 1
runStartMs ??= sample.tMs ?? 0
longestUnhealthyWindowMs = Math.max(
longestUnhealthyWindowMs,
(sample.tMs ?? 0) + (sample.ms || 0) - runStartMs
)
}
const summary = () => ({
sampleCount: samples.totalCount,
maxStatusMs,
unhealthySampleCount,
infrastructureErrorCount,
longestUnhealthyWindowMs
})
const probe = () =>
new Promise((resolve) => {
const t0 = performance.now()
const child = spawn(
cliInvocation.command,
[...cliInvocation.prefixArgs, 'status', '--json'],
{
env: cliInvocation.env,
stdio: ['ignore', 'pipe', 'pipe']
}
)
let settled = false
const finish = (result) => {
if (settled) {
return
}
settled = true
resolve(result)
}
const timer = setTimeout(() => {
child.kill('SIGKILL')
finish({
tMs: t0 - startedAt,
ms: performance.now() - t0,
ok: false,
hang: true
})
}, timeoutMs)
child.stdout.on('data', () => {})
child.stderr.on('data', () => {})
child.on('error', (error) => {
clearTimeout(timer)
finish({
tMs: t0 - startedAt,
ms: performance.now() - t0,
ok: false,
hang: false,
infrastructureError: true,
error: String(error)
})
})
child.on('close', (code) => {
clearTimeout(timer)
finish({
tMs: t0 - startedAt,
ms: performance.now() - t0,
ok: code === 0,
hang: false
})
})
})
const tick = async ({ force = false } = {}) => {
if ((!force && stopped) || inFlight) {
return
}
inFlight = true
try {
const sample = await probe()
record(sample)
} finally {
inFlight = false
}
}
const interval = setInterval(() => {
void tick()
}, intervalMs)
void tick()
return {
stop: async () => {
stopped = true
clearInterval(interval)
// Wait for in-flight probe, then force one final sample.
const deadline = performance.now() + timeoutMs + 1000
while (inFlight && performance.now() < deadline) {
await new Promise((r) => setTimeout(r, 20))
}
await tick({ force: true })
return {
samples: samples.values(),
...summary(),
durationMs: performance.now() - startedAt
}
},
getSamples: () => samples.values(),
getSummary: summary
}
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { startStatusWatchdog } from './live-remote-status-watchdog.mjs'
describe('startStatusWatchdog', () => {
it('collects status samples and stops cleanly', async () => {
// Real path: actually invokes `orca status --json` (must be available in CI/dev with Orca or fail soft).
const watch = startStatusWatchdog({ intervalMs: 50, timeoutMs: 5_000 })
await new Promise((r) => setTimeout(r, 180))
const result = await watch.stop()
expect(result.samples.length).toBeGreaterThanOrEqual(1)
expect(result.durationMs).toBeGreaterThan(0)
for (const s of result.samples) {
expect(typeof s.ms).toBe('number')
expect(typeof s.ok).toBe('boolean')
expect(typeof s.hang).toBe('boolean')
}
})
it('marks CLI spawn failures as infrastructure errors', async () => {
const watch = startStatusWatchdog({
intervalMs: 50,
timeoutMs: 1000,
cliCommand: 'orca-freeze-watchdog-missing-command'
})
const result = await watch.stop()
expect(result.samples.length).toBeGreaterThanOrEqual(1)
expect(result.samples.every((sample) => sample.infrastructureError === true)).toBe(true)
expect(result.samples.every((sample) => sample.hang === false)).toBe(true)
})
it('bounds retained samples while preserving full-run counters', async () => {
const watch = startStatusWatchdog({
intervalMs: 50,
timeoutMs: 1000,
cliCommand: 'orca-freeze-watchdog-missing-command',
sampleHistoryLimit: 1
})
const result = await watch.stop()
expect(result.samples).toHaveLength(1)
expect(result.sampleCount).toBeGreaterThan(result.samples.length)
expect(result.infrastructureErrorCount).toBe(result.sampleCount)
expect(result.maxStatusMs).toBeGreaterThanOrEqual(0)
})
})
@@ -5038,5 +5038,14 @@
},
"settings.appearance.statusBar.sshToggleDescription": {
"ko": "사용 가능한 SSH 및 원격 Orca 호스트가 있으면 표시합니다."
},
"auto.components.right.sidebar.AiVaultPanelControls.selectAllAgents": {
"ko": "모두 선택"
},
"auto.components.right.sidebar.AiVaultPanelControls.clearAgents": {
"ko": "모두 해제"
},
"auto.components.right.sidebar.AiVaultPanel.noAgentsSelected": {
"ko": "선택된 에이전트가 없습니다"
}
}
@@ -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 <dispatch_id> --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 <dispatch_id> --json`'
)
expect(workerLoop).toContain(
'orca orchestration worker-start --task <next_task_id> --terminal <handle> --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 <dispatch_id> --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')
+17 -1
View File
@@ -20,11 +20,27 @@ function quoteWindowsArg(value) {
return `"${value.replace(/"/g, '""')}"`
}
// Why: under a Git Bash setup runner, Orca exports ORCA_WORKTREE_PATH in MSYS form (/c/...), which
// cmd.exe cannot resolve. This is the migration pattern for any setup script feeding a native exe.
function posixShellPathToNativeWindowsPath(value) {
const driveMatch = value.match(/^\/([A-Za-z])\/(.*)$/)
if (driveMatch) {
return `${driveMatch[1].toUpperCase()}:\\${driveMatch[2].replace(/\//g, '\\')}`
}
return value
}
function spawnOptionalSetup(spawn, setupPath, worktreePath, platform, env) {
if (platform === 'win32') {
const nativeWorktreePath = posixShellPathToNativeWindowsPath(worktreePath)
spawn(
env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `call ${quoteWindowsArg(setupPath)} ${quoteWindowsArg(worktreePath)}`],
[
'/d',
'/s',
'/c',
`call ${quoteWindowsArg(setupPath)} ${quoteWindowsArg(nativeWorktreePath)}`
],
{
stdio: 'inherit',
windowsVerbatimArguments: true
@@ -0,0 +1,43 @@
import { spawnSync } from 'node:child_process'
const extraArgs = process.argv.slice(2)
const pnpmEntry = process.env.npm_execpath
if (!pnpmEntry) {
throw new Error('npm_execpath is required; run this harness through pnpm')
}
const env = {
...process.env,
ORCA_E2E_SSH_DOCKER: '1'
}
const runtime = spawnSync(process.execPath, [pnpmEntry, 'run', 'ensure:electron-runtime'], {
stdio: 'inherit',
env
})
if (runtime.status !== 0) {
process.exit(runtime.status ?? 1)
}
const result = spawnSync(
process.execPath,
[
pnpmEntry,
'exec',
'playwright',
'test',
'tests/e2e/ssh-docker-bulk-open-freeze-repro.spec.ts',
'--config',
'tests/playwright.config.ts',
'--project',
'electron-headless',
'--workers=1',
...extraArgs
],
{
stdio: 'inherit',
env
}
)
process.exit(result.status ?? 1)
@@ -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..."
Binary file not shown.

Before

Width:  |  Height:  |  Size: 380 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 399 KiB

+2 -3
View File
@@ -243,10 +243,9 @@ Associez-la à l'app de bureau pour surveiller et piloter vos agents depuis votr
- **Discord :** Rejoignez la communauté sur **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X :** Suivez **[@orca_build](https://x.com/orca_build)** pour les news et annonces.
- **WeChat :** Si le groupe 5 est complet, vous pouvez rejoindre le groupe 6.
- **WeChat :** Scannez pour rejoindre le groupe WeChat 7 de la communauté Orca.
<img src="../assets/wechat-qr.jpg" alt="QR code WeChat groupe 5 de la communauté Orca" width="160" style="margin-right: 16px;" />
<img src="../assets/wechat-qr-group6.jpg" alt="QR code WeChat groupe 6 de la communauté Orca" width="160" />
<img src="../assets/wechat-qr-group7.jpg" alt="QR code WeChat groupe 7 de la communauté Orca" width="160" />
- **Feedback &amp; idées :** On ship vite. Il manque quelque chose ? [Demandez une feature](https://github.com/stablyai/orca/issues).
- **Confidentialité :** Voir la [doc confidentialité &amp; télémétrie](https://www.onorca.dev/docs/telemetry) pour ce qu'Orca collecte en anonyme et comment désactiver la télémétrie.
+2 -3
View File
@@ -235,10 +235,9 @@ yay -S stably-orca-bin
- **Discord:** 加入 **[Discord](https://discord.gg/fzjDKHxv8Q)** 社区。
- **Twitter / X:** 关注 **[@orca_build](https://x.com/orca_build)** 获取更新和公告。
- **微信:** 如果第 5 群已满,可加入第 6 群。
- **微信:** 扫码加入 Orca 社区微信第 7 群。
<img src="../assets/wechat-qr.jpg" alt="Orca 社区微信第 5 群二维码" width="160" style="margin-right: 16px;" />
<img src="../assets/wechat-qr-group6.jpg" alt="Orca 社区微信第 6 群二维码" width="160" />
<img src="../assets/wechat-qr-group7.jpg" alt="Orca 社区微信第 7 群二维码" width="160" />
- **反馈与想法:** 我们发布很快。缺少什么功能?[提交功能请求](https://github.com/stablyai/orca/issues)。
- **隐私:** 查看[隐私与遥测文档](https://www.onorca.dev/docs/telemetry),了解 Orca 收集哪些匿名使用数据以及如何退出。
+1
View File
@@ -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/
+1 -1
View File
@@ -14,7 +14,7 @@ import { ChevronLeft, Check, RefreshCw, User } from 'lucide-react-native'
import { loadHosts } from '../../../src/transport/host-store'
import { useHostClient } from '../../../src/transport/client-context'
import { colors, spacing } from '../../../src/theme/mobile-theme'
import { styles } from './accounts-screen-styles'
import { styles } from '../../../src/accounts/mobile-accounts-screen-styles'
import { useNow } from '../../../src/hooks/use-now'
import { ClaudeIcon, OpenAIIcon } from '../../../src/components/AgentIcons'
import {
+30 -33
View File
@@ -1,14 +1,5 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import {
View,
Text,
StyleSheet,
SectionList,
Pressable,
ActivityIndicator,
Alert,
RefreshControl
} from 'react-native'
import { View, Text, StyleSheet, SectionList, Pressable, Alert, RefreshControl } from 'react-native'
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'
import { useFocusEffect, useLocalSearchParams, usePathname, useRouter } from 'expo-router'
import {
@@ -95,6 +86,7 @@ import { useWorkspaceSections } from '../../../src/worktree/use-workspace-sectio
import { getMobileWorkspaceLineageGroupKey } from '../../../src/worktree/mobile-workspace-lineage'
import { areWorktreeListsEqual } from '../../../src/worktree/worktree-list-snapshot'
import { WorktreeCatalogSnapshotClient } from '../../../src/worktree/worktree-catalog-snapshot-client'
import { HostWorkspaceListStates } from '../../../src/worktree/host-workspace-list-states'
import { repoColor } from '../../../src/worktree/repo-color'
import {
WORKSPACE_GROUP_OPTIONS as GROUP_OPTIONS,
@@ -154,6 +146,9 @@ export function HostScreen({
const forceReconnectHost = useForceReconnect()
const [worktrees, setWorktrees] = useState<Worktree[]>(initialCache ?? [])
const [worktreesLoaded, setWorktreesLoaded] = useState(initialCache != null)
// Why (STA-3123): error code of the last failed worktree.ps, so a broken catalog
// path renders as a failure instead of an empty host. Cleared on the next success.
const [catalogError, setCatalogError] = useState<string | null>(null)
// Why: track the locally-opened worktree so the active-row highlight moves instantly instead of waiting for the next poll.
const [optimisticActiveWorktreeId, setOptimisticActiveWorktreeId] = useState<string | null>(null)
// One tick drives every visible agent row's relative timestamp.
@@ -326,6 +321,7 @@ export function HostScreen({
repoMetadataFetchedAtRef.current = 0
// Why: useState initializer runs only on first mount, so re-seed the cache when Expo Router reuses this screen for a new hostId.
const freshCache = hostId ? (getCachedWorktrees(hostId) as Worktree[] | null) : null
setCatalogError(null)
if (freshCache) {
setWorktrees(freshCache)
setLastKnownWorktrees(freshCache)
@@ -427,17 +423,27 @@ export function HostScreen({
const requestHostId = hostId
try {
const pendingCatalog = await worktreeCatalogRef.current.fetch(requestClient, requestHostId)
const fetched = await worktreeCatalogRef.current.fetch(requestClient, requestHostId)
if (clientRef.current !== requestClient || hostId !== requestHostId) {
return
}
if (!options.allowDuringModal && newWorktreeModalVisibleRef.current) {
return
}
// Why (STA-3123): a failed catalog request must not pass for "0 worktrees";
// surface it so a broken remote host is diagnosable instead of looking empty.
if (fetched.kind === 'request_failed') {
setCatalogError(fetched.code)
return
}
if (fetched.pending.admission.kind === 'invalid') {
setCatalogError('invalid_response')
}
// Why: unchanged responses still yield the confirmed rows, so every poll reasserts
// host truth over optimistic local edits regardless of payload size.
const confirmed = worktreeCatalogRef.current.admit(pendingCatalog)
const confirmed = worktreeCatalogRef.current.admit(fetched.pending)
if (confirmed) {
setCatalogError(null)
// Why: reuse the existing array on identical snapshots to keep SectionList/sort rebuilds off the tap path.
setWorktrees((current) =>
areWorktreeListsEqual(current, confirmed) ? current : confirmed
@@ -486,6 +492,9 @@ export function HostScreen({
}
} catch {
// Will retry on reconnect
if (clientRef.current === requestClient && hostId === requestHostId) {
setCatalogError('network_error')
}
} finally {
fetchWorktreesInFlightRef.current = false
}
@@ -1099,27 +1108,15 @@ export function HostScreen({
</View>
)}
{/* Loading state */}
{((connState === 'connecting' || connState === 'reconnecting') &&
displayWorktrees.length === 0) ||
(connState === 'connected' && !worktreesLoaded && displayWorktrees.length === 0) ? (
<View style={styles.centered}>
<ActivityIndicator size="small" color={colors.textSecondary} />
</View>
) : null}
{/* Empty state */}
{connState === 'connected' && worktreesLoaded && sections.length === 0 && (
<View style={styles.centered}>
<Text style={styles.emptyText}>
{search
? 'No matching worktrees'
: activeFilterCount > 0
? 'No worktrees match filters'
: 'No worktrees'}
</Text>
</View>
)}
<HostWorkspaceListStates
connState={connState}
worktreesLoaded={worktreesLoaded}
displayCount={displayWorktrees.length}
sectionCount={sections.length}
catalogError={catalogError}
search={search}
activeFilterCount={activeFilterCount}
/>
{sections.length > 0 && (
<SectionList
+62 -64
View File
@@ -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,
@@ -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'
@@ -267,8 +273,8 @@ import {
reconcileMobileSessionCreateWarningState
} from '../../../../src/session/mobile-session-create-warning-state'
import { colors, spacing } from '../../../../src/theme/mobile-theme'
import { styles } from './mobile-session-styles'
import { QuickCommandsTabButton } from './QuickCommandsTabButton'
import { QuickCommandsTabButton } from '../../../../src/session/QuickCommandsTabButton'
import { styles } from '../../../../src/session/mobile-session-styles'
import type { DiffComment, TerminalQuickCommand } from '../../../../../src/shared/types'
import type {
DiffCommentActions,
@@ -289,7 +295,7 @@ import type {
TerminalCreateResult,
TerminalGestureInputBucket,
TerminalGestureInputQueue
} from './mobile-session-route-types'
} from '../../../../src/session/mobile-session-route-types'
const TERMINAL_KEYBOARD_DISMISS_ACTION_SHEET_FALLBACK_MS = 450
@@ -1030,6 +1036,8 @@ export default function SessionScreen() {
const subscribingHandlesRef = useRef<Set<string>>(new Set())
const initializedHandlesRef = useRef<Set<string>>(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<Set<string>>(new Set())
const activeHandleRef = useRef<string | null>(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<string>()
@@ -3590,6 +3600,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 +4282,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 }]
+17 -39
View File
@@ -20,6 +20,11 @@ import { navigateToMobileHostEdit } from '../src/transport/host-edit-navigation'
import { removeHostAndCloseClient } from '../src/transport/host-removal-lifecycle'
import { pickResumeWorktree } from '../src/worktree/resume-worktree'
import { WORKTREE_PS_FULL_LIMIT } from '../src/worktree/worktree-catalog-snapshot-client'
import {
markHomeWorktreeCatalogUnavailable,
type HomeWorktreeSummary,
type HostWorktreeInfo
} from '../src/worktree/home-worktree-info'
import type { RpcClient } from '../src/transport/rpc-client'
import { sendSingleFlightRequest } from '../src/transport/request-single-flight'
import {
@@ -70,26 +75,6 @@ type StatsSummary = {
firstEventAt: number | null
}
type WorktreeSummary = {
worktreeId: string
repo: string
branch: string
displayName: string
liveTerminalCount: number
status?: 'working' | 'active' | 'permission' | 'done' | 'inactive'
// The worktree the desktop currently has focused (exactly one is true).
isActive?: boolean
// Last terminal-output time (ms); breaks ties when nothing is focused.
lastOutputAt?: number
}
type HostWorktreeInfo = {
hostId: string
totalWorktrees: number
activeCount: number
lastActiveWorktree: WorktreeSummary | null
}
type HomeTaskSettings = {
visibleTaskProviders?: unknown
}
@@ -161,21 +146,11 @@ function fetchWorktreeInfo(
) => void,
disposed: () => boolean
) {
// Why: only seed a zeroed entry when the host has no prior info; keep cached data on transient failure so counts don't flip to 0 during reconnects.
const markLoadedIfMissing = () => {
const markUnavailable = () => {
setInfo((prev) => {
if (prev[hostId]) {
return prev
}
return {
...prev,
[hostId]: {
hostId,
totalWorktrees: 0,
activeCount: 0,
lastActiveWorktree: null
}
}
const current = prev[hostId]
const next = markHomeWorktreeCatalogUnavailable(current, hostId)
return next === current ? prev : { ...prev, [hostId]: next }
})
}
@@ -185,7 +160,7 @@ function fetchWorktreeInfo(
return
}
if (response.ok) {
const result = response.result as { worktrees: WorktreeSummary[] }
const result = response.result as { worktrees: HomeWorktreeSummary[] }
const worktrees = result.worktrees ?? []
setCachedWorktrees(hostId, worktrees)
const activeStatuses = new Set(['working', 'active', 'permission'])
@@ -202,12 +177,12 @@ function fetchWorktreeInfo(
}
}))
} else {
markLoadedIfMissing()
markUnavailable()
}
})
.catch(() => {
if (!disposed()) {
markLoadedIfMissing()
markUnavailable()
}
})
}
@@ -554,7 +529,7 @@ export default function HomeScreen() {
const resumeWorktree = useMemo(() => {
// Why: only surface Resume for connected hosts; a stale worktree taps into a route that can't load.
if (lastVisited && hostStates[lastVisited.hostId] === 'connected') {
const cached = getCachedWorktrees(lastVisited.hostId) as WorktreeSummary[] | null
const cached = getCachedWorktrees(lastVisited.hostId) as HomeWorktreeSummary[] | null
const match = cached?.find((w) => w.worktreeId === lastVisited.worktreeId)
if (match) {
return { hostId: lastVisited.hostId, worktree: match }
@@ -789,8 +764,11 @@ export default function HomeScreen() {
verdict={verdict}
path={hostPaths[item.id] ?? 'lan'}
worktreeCounts={
info ? { total: info.totalWorktrees, active: info.activeCount } : undefined
info && !info.catalogUnavailable
? { total: info.totalWorktrees, active: info.activeCount }
: undefined
}
worktreeCountsUnavailable={info?.catalogUnavailable === true}
onPress={() => router.push(`/h/${item.id}`)}
onLongPress={() => {
triggerMediumImpact()
+2 -1
View File
@@ -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",
+792
View File
File diff suppressed because it is too large Load Diff
@@ -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 </script> 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()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# Repro driver for "mobile sits on Connecting… after leaving and re-entering the
# app" (Slack P0, iOS 0.0.39(2)).
#
# Two things the iOS Simulator will not do on its own, and how this works around
# them:
#
# * It never suspends an app the way a device does, so the JS runtime keeps
# servicing timers while backgrounded and the bug hides. SIGSTOP on the app
# process reproduces real suspension: timers frozen, socket left dangling.
# * SIGSTOP on the desktop runtime makes its port blackhole — the kernel still
# completes the TCP handshake from the listen backlog, but no WebSocket
# upgrade ever comes back, which is what a wedged Tailscale tunnel or a relay
# with nothing behind it looks like to the phone.
#
# Everything is driven with xcrun simctl rather than `orca emulator`, because the
# emulator CLI routes through the desktop runtime that this script freezes.
#
# Setup:
# node scripts/start-emulator.mjs --device "iPhone 17 Pro" --wait-for-ready \
# > /tmp/orca-emulator-boot.log 2>&1 &
#
# Usage: repro-mobile-foreground-stall.sh <udid> <paired-host-port> [log]
set -euo pipefail
UDID="${1:?simulator udid}"
PORT="${2:?port of the paired host, from the [net] logs}"
LOG="${3:-/tmp/orca-emulator-boot.log}"
BUNDLE_ID=com.stably.orca.mobile
# Long enough for the tiered backoff to reach its 30s/60s tail.
ESCALATE_SECONDS=200
APP=$(pgrep -f "CoreSimulator.*Orca.app/Orca" | head -1)
DESK=$(pgrep -f "serve-mobile-pairing" | head -1)
: "${APP:?mobile app is not running in the simulator}"
: "${DESK:?headless desktop runtime is not running}"
strip() { sed 's/\x1b\[[0-9;]*m//g'; }
since() { sed -n "$(( $1 + 1 )),\$p" "$LOG" | strip; }
step() { echo "$(date +%T) $*"; }
echo "### app=$APP desktop=$DESK port=$PORT"
step "[1] desktop goes unreachable"
kill -STOP "$DESK"
sleep "$ESCALATE_SECONDS"
step "[2] backoff at $(since 0 | grep "$PORT" | grep -o '"attempt": [0-9]*' | tail -1)"
MARK=$(wc -l < "$LOG")
while true; do
since "$MARK" | grep "$PORT" | grep -q '"to": "connecting"' && break
sleep 0.3
done
step "[3] connect window open — user switches away"
xcrun simctl launch "$UDID" com.apple.mobilesafari >/dev/null 2>&1
sleep 1
kill -STOP "$APP"
step "[4] phone suspended mid-dial"
sleep 5
MARK=$(wc -l < "$LOG")
kill -CONT "$APP"
sleep 0.3
xcrun simctl launch "$UDID" "$BUNDLE_ID" >/dev/null 2>&1
T0=$(date +%s)
step "[5] user returns to Orca <-- t0, desktop still down"
# The desktop is deliberately still unreachable here: the only question is
# whether returning to the app abandons the dead dial or waits it out.
sleep 6
echo "--- first 6s after t0 ---"
since "$MARK" | grep -E "$PORT|foreground" \
| grep -E 'state |foreground|scheduleReconnect|openConnection' | head -8
kill -CONT "$DESK"
step "[6] desktop healthy again"
for _ in $(seq 1 45); do
if since "$MARK" | grep "$PORT" | grep -q '"to": "connected"'; then
step ">>> connected $(( $(date +%s) - T0 ))s after t0"
exit 0
fi
sleep 2
done
step ">>> STILL STUCK 90s after t0"
exit 1
@@ -1,5 +1,5 @@
import { StyleSheet } from 'react-native'
import { colors, spacing, typography, radii } from '../../../src/theme/mobile-theme'
import { colors, spacing, typography, radii } from '../theme/mobile-theme'
export const styles = StyleSheet.create({
container: {
+1 -1
View File
@@ -32,7 +32,7 @@ function OmpIcon({ size = 16 }: { size?: number }) {
<Defs>
<LinearGradient id="ompMarkGradient" x1="0" y1="0" x2="1" y2="1">
<Stop offset="0" stopColor="#ed4abf" />
<Stop offset=".5" stopColor="#9b4dff" />
<Stop offset="0.5" stopColor="#9b4dff" />
<Stop offset="1" stopColor="#5ad8e6" />
</LinearGradient>
</Defs>
+6 -1
View File
@@ -14,6 +14,9 @@ export function MobileHostCard(props: {
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
onPress: () => void
onLongPress: () => void
}) {
@@ -21,7 +24,9 @@ export function MobileHostCard(props: {
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` : ''}`
: null
: props.worktreeCountsUnavailable
? 'Worktree list unavailable'
: null
return (
<Pressable
style={({ pressed }) => [styles.card, pressed && styles.cardPressed]}
@@ -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([
{
+19
View File
@@ -7,7 +7,9 @@ import {
isFilePathCodeSpan,
normalizeFilePath
} from './markdown-file-path-detection'
import { isMobileMermaidLanguage } from './mobile-mermaid-language'
import { parseMobileMarkdown } from './mobile-markdown-parser'
import { MermaidDiagram } from './pr-sidebar/MermaidDiagram'
type Props = {
content?: string
@@ -23,6 +25,8 @@ type Props = {
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()
@@ -153,6 +157,7 @@ function MobileMarkdownInner({ content, fallback = '', textScale = 1, onOpenFile
if (!text) {
return fallback ? <Text style={styles.paragraph}>{fallback}</Text> : null
}
const mermaidSourceOccurrences = new Map<string, number>()
return (
<View style={styles.root}>
@@ -175,6 +180,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 (
<MermaidDiagram
key={`${block.text}:${occurrence}`}
source={block.text}
base={MERMAID_BASE}
/>
)
}
return (
<View key={index} style={styles.codeBlock}>
{block.language ? <Text style={styles.codeLanguage}>{block.language}</Text> : null}
@@ -0,0 +1,65 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MobileAgentIcon } from './MobileAgentIcon'
vi.mock('react-native', () => ({
Image: 'Image',
StyleSheet: { create: (styles: unknown) => styles },
Text: 'Text',
View: 'View'
}))
vi.mock('lucide-react-native', () => ({
Terminal: 'Terminal'
}))
vi.mock('react-native-svg', () => ({
default: 'Svg',
Defs: 'Defs',
G: 'G',
LinearGradient: 'LinearGradient',
Path: 'Path',
Stop: 'Stop'
}))
vi.mock('./mobile-agent-icon-assets', () => ({
MOBILE_AGENT_ICON_ASSETS: {}
}))
vi.mock('./AgentIcons', () => ({
ClaudeIcon: 'ClaudeIcon',
OpenAIIcon: 'OpenAIIcon'
}))
describe('MobileAgentIcon OMP gradient', () => {
let renderer: ReactTestRenderer | null = null
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.restoreAllMocks()
})
it('uses valid SVG gradient stop offsets', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation((...args) => {
if (typeof args[0] !== 'string' || !args[0].includes('react-test-renderer is deprecated')) {
throw new Error(String(args[0]))
}
})
await act(async () => {
renderer = create(createElement(MobileAgentIcon, { agentId: 'omp' }))
})
consoleError.mockRestore()
expect(renderer.root.findAllByType('Stop').map((stop) => stop.props.offset)).toEqual([
'0',
'0.5',
'1'
])
})
})
@@ -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: <T>(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)
})
})
@@ -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
}
@@ -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'
}
@@ -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) {
/>
</View>
)
}
})
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 `</script>`
// would close this inline <script> and let the rest execute as markup. Diagram
// source is untrusted (agent output, PR/chat content), so escape those to \uXXXX;
// the literal still parses back to the exact original string inside the WebView.
function encodeSourceForScript(source: string): string {
return JSON.stringify(source).replace(
/[<>&\u2028\u2029]/g,
(char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
)
}
// Self-contained HTML: embedded mermaid bundle, render the graph, post the body
// height (or "error") back to RN. Theme variables match the dark sidebar palette.
function buildHtml(source: string): string {
// JSON.stringify safely escapes the user's diagram source for embedding.
const encoded = JSON.stringify(source)
export function buildHtml(source: string): string {
const encoded = encodeSourceForScript(source)
return `<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; base-uri 'none'; form-action 'none'" />
<style>
html, body { margin: 0; padding: 0; background: ${colors.bgRaised}; }
#c { padding: 8px; }
#c svg { max-width: 100%; height: auto; }
</style>
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<script>${MERMAID_ENGINE_JS}</script>
</head>
<body>
<div id="c"><pre class="mermaid"></pre></div>
@@ -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');
@@ -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: <T>(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 <script>, so it must not be able to close that script element.
describe('buildHtml source escaping', () => {
it('does not let a </script> payload break out of the inline script', () => {
const payload = 'graph TD; A-->B</script><script>window.evil=1</script>'
const countClosers = (html: string) => (html.match(/<\/script>/gi) ?? []).length
// The payload's two </script> 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 & <tag>"] --> 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?:/)
})
})
@@ -0,0 +1,121 @@
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { basename, dirname, extname, join, relative } from 'node:path'
import ts from 'typescript'
import { describe, expect, it } from 'vitest'
const appDirectory = fileURLToPath(new URL('../app', import.meta.url))
const routeSourceExtensions = new Set(['.js', '.jsx', '.ts', '.tsx'])
function sourceFiles(directory: string): string[] {
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const path = join(directory, entry.name)
return entry.isDirectory() ? sourceFiles(path) : [path]
})
}
function isNonScreenExpoModule(path: string): boolean {
const fileName = basename(path)
if (/\+api\.[jt]sx?$/.test(fileName)) {
return true
}
return (
dirname(relative(appDirectory, path)) === '.' &&
/^\+(?:html|middleware|native-intent)\.[jt]sx?$/.test(fileName)
)
}
function isPlatformSpecificApiRoute(path: string): boolean {
return /\+api\.(?:android|ios|native|web)\.[jt]sx?$/.test(basename(path))
}
function hasDefaultExport(path: string, source: string): boolean {
const extension = extname(path)
const sourceFile = ts.createSourceFile(
path,
source,
ts.ScriptTarget.Latest,
true,
extension === '.jsx'
? ts.ScriptKind.JSX
: extension === '.js'
? ts.ScriptKind.JS
: extension === '.tsx'
? ts.ScriptKind.TSX
: ts.ScriptKind.TS
)
return sourceFile.statements.some((statement) => {
if (ts.isExportAssignment(statement)) {
return !statement.isExportEquals
}
if (ts.isExportDeclaration(statement) && !statement.isTypeOnly && statement.exportClause) {
if (ts.isNamespaceExport(statement.exportClause)) {
return statement.exportClause.name.text === 'default'
}
return statement.exportClause.elements.some(
(element) => !element.isTypeOnly && element.name.text === 'default'
)
}
const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined
return (
!ts.isInterfaceDeclaration(statement) &&
!ts.isTypeAliasDeclaration(statement) &&
modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword) !== true &&
modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true &&
modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)
)
})
}
function isInvalidRouteModule(path: string, source: string): boolean {
return (
isPlatformSpecificApiRoute(path) ||
(!isNonScreenExpoModule(path) && !hasDefaultExport(path, source))
)
}
describe('Expo route module boundary', () => {
it('allows Expo modules that are not screen routes', () => {
expect(isNonScreenExpoModule(join(appDirectory, 'health+api.ts'))).toBe(true)
expect(isNonScreenExpoModule(join(appDirectory, 'health+api.ios.ts'))).toBe(false)
expect(isNonScreenExpoModule(join(appDirectory, '+html.tsx'))).toBe(true)
expect(isNonScreenExpoModule(join(appDirectory, '+middleware.ts'))).toBe(true)
expect(isNonScreenExpoModule(join(appDirectory, '+native-intent.ts'))).toBe(true)
expect(isNonScreenExpoModule(join(appDirectory, 'nested', '+middleware.ts'))).toBe(false)
})
it('recognizes syntax-level default exports', () => {
expect(hasDefaultExport('route.tsx', 'export default function Route() {}')).toBe(true)
expect(
hasDefaultExport('route.jsx', 'export default function Route() { return <View /> }')
).toBe(true)
expect(hasDefaultExport('route.ts', "export { default } from './route-screen'")).toBe(true)
expect(hasDefaultExport('route.ts', "export { Route as default } from './route-screen'")).toBe(
true
)
expect(hasDefaultExport('support.ts', '// export default')).toBe(false)
expect(hasDefaultExport('support.ts', "const marker = 'export default'")).toBe(false)
expect(hasDefaultExport('support.ts', 'export default interface Support {}')).toBe(false)
expect(
hasDefaultExport('support.ts', "export type { Support as default } from './types'")
).toBe(false)
})
it('rejects platform-specific API routes even with a default export', () => {
expect(isPlatformSpecificApiRoute(join(appDirectory, 'health+api.ts'))).toBe(false)
for (const platform of ['android', 'ios', 'native', 'web']) {
const path = join(appDirectory, `health+api.${platform}.ts`)
expect(isInvalidRouteModule(path, 'export default function Route() {}')).toBe(true)
}
})
it('keeps support modules outside the app route directory', () => {
const invalidRoutes = sourceFiles(appDirectory)
.filter((path) => routeSourceExtensions.has(extname(path)))
.filter((path) => isInvalidRouteModule(path, readFileSync(path, 'utf8')))
.map((path) => relative(appDirectory, path))
expect(invalidRoutes).toEqual([])
})
})
@@ -1,5 +1,5 @@
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react-native'
import type { MobileSessionTab } from '../../app/h/[hostId]/session/mobile-session-route-types'
import type { MobileSessionTab } from './mobile-session-route-types'
import { ActionSheetModal, type ActionSheetAction } from '../components/ActionSheetModal'
import { getMobileSessionTabTitle } from './mobile-terminal-tab-agent'
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react'
import { Pressable } from 'react-native'
import { colors } from '../theme/mobile-theme'
import { styles } from '../../app/h/[hostId]/session/mobile-session-styles'
import { styles } from './mobile-session-styles'
type HeaderIconProps = {
size?: number
@@ -1,7 +1,7 @@
import { Pressable, View } from 'react-native'
import { SquareChevronRight } from 'lucide-react-native'
import { colors } from '../../../../src/theme/mobile-theme'
import { colors } from '../theme/mobile-theme'
import { styles } from './mobile-session-styles'
type Props = {
+1 -1
View File
@@ -3,7 +3,7 @@ import {
buildAiVaultResumeCommand,
buildAiVaultResumeShellCommand,
realHomeCodexResumeEnvDeletion
} from '../../../src/shared/ai-vault-types'
} from '../../../src/shared/ai-vault-resume-command'
import { RESUME_RPC_TIMEOUT_MS } from './ai-vault-resume-preparation'
import { isResumableTuiAgent } from '../../../src/shared/agent-session-resume'
import type { SleepingAgentLaunchConfig } from '../../../src/shared/agent-session-resume'
@@ -1,7 +1,4 @@
import type {
MarkdownDocState,
MobileSessionTab
} from '../../app/h/[hostId]/session/mobile-session-route-types'
import type { MarkdownDocState, MobileSessionTab } from './mobile-session-route-types'
import type { ActionSheetAction } from '../components/ActionSheetModal'
import {
BULK_TAB_CLOSE_ACTIONS,
@@ -36,6 +36,7 @@ describe('resolveMobileNativeChatWorktreePath', () => {
.mockResolvedValueOnce({
ok: true,
result: {
worktree: 'sibling-worktree',
exists: true,
isDirectory: false,
openTarget: { kind: 'worktree-file', relativePath: 'src/app.ts' }
@@ -51,7 +52,7 @@ describe('resolveMobileNativeChatWorktreePath', () => {
})
expect(sendRequest).toHaveBeenLastCalledWith('files.open', {
worktree: 'id:worktree',
worktree: 'id:sibling-worktree',
relativePath: 'src/app.ts'
})
})
@@ -1,12 +1,17 @@
import type { RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types'
import type { RpcClient } from '../transport/rpc-client'
export async function resolveMobileNativeChatWorktreePath(args: {
type MobileNativeChatWorktreeTarget = {
worktreeId: string
relativePath: string
}
async function resolveMobileNativeChatWorktreeTarget(args: {
client: RpcClient
worktreeId: string
pathText: string
terminal: string | null
}): Promise<string | null> {
}): Promise<MobileNativeChatWorktreeTarget | null> {
try {
const response = await args.client.sendRequest('files.resolveTerminalPath', {
worktree: `id:${args.worktreeId}`,
@@ -20,28 +25,39 @@ export async function resolveMobileNativeChatWorktreePath(args: {
if (!resolved.exists || resolved.isDirectory) {
return null
}
return resolved.openTarget?.kind === 'worktree-file'
? resolved.openTarget.relativePath
: (resolved.relativePath ?? null)
const relativePath =
resolved.openTarget?.kind === 'worktree-file'
? resolved.openTarget.relativePath
: (resolved.relativePath ?? null)
return relativePath
? { worktreeId: resolved.worktree?.trim() || args.worktreeId, relativePath }
: null
} catch {
// Callers fire-and-forget file opens; a disconnect/timeout must not become
// an unhandled rejection.
return null
}
}
export async function resolveMobileNativeChatWorktreePath(args: {
client: RpcClient
worktreeId: string
pathText: string
terminal: string | null
}): Promise<string | null> {
return (await resolveMobileNativeChatWorktreeTarget(args))?.relativePath ?? null
}
export async function openMobileNativeChatFile(args: {
client: RpcClient
worktreeId: string
pathText: string
terminal: string | null
}): Promise<void> {
const relativePath = await resolveMobileNativeChatWorktreePath(args)
if (relativePath) {
const target = await resolveMobileNativeChatWorktreeTarget(args)
if (target) {
try {
await args.client.sendRequest('files.open', {
worktree: `id:${args.worktreeId}`,
relativePath
worktree: `id:${target.worktreeId}`,
relativePath: target.relativePath
})
} catch {
// Best-effort open; failures surface as a no-op rather than an
@@ -1,6 +1,6 @@
import { StyleSheet } from 'react-native'
import { colors, spacing, radii, typography } from '../../../../src/theme/mobile-theme'
import { colors, spacing, radii, typography } from '../theme/mobile-theme'
export const mobileSessionCommandInputStyles = StyleSheet.create({
createWarningBanner: {
@@ -1,6 +1,6 @@
import { StyleSheet } from 'react-native'
import { colors, spacing, radii, typography } from '../../../../src/theme/mobile-theme'
import { colors, spacing, radii, typography } from '../theme/mobile-theme'
export const mobileSessionFrameStyles = StyleSheet.create({
container: {
@@ -1,6 +1,6 @@
import { Platform, StyleSheet } from 'react-native'
import { colors, spacing, radii, typography } from '../../../../src/theme/mobile-theme'
import { colors, spacing, radii, typography } from '../theme/mobile-theme'
export const mobileSessionReaderStyles = StyleSheet.create({
markdownTextInput: {
@@ -1,6 +1,6 @@
import { StyleSheet } from 'react-native'
import { colors, spacing, radii, typography } from '../../../../src/theme/mobile-theme'
import { colors, spacing, radii, typography } from '../theme/mobile-theme'
export const mobileSessionReviewCommentStyles = StyleSheet.create({
diffCommentAddButton: {
@@ -1,13 +1,10 @@
import type { MobileBrowserTab } from '../../../../src/browser/MobileBrowserPane'
import type { MobileTerminalTheme } from '../../../../src/terminal/terminal-webview-contract'
import type { MobileDiffLine } from '../../../../src/session/mobile-diff-lines'
import type {
MobileHighlightedDiffLine,
MobileSyntaxSegment
} from '../../../../src/session/mobile-file-syntax'
import type { TerminalRecord } from '../../../../src/session/mobile-terminal-records'
import type { DiffComment, TuiAgent } from '../../../../../src/shared/types'
import type { AgentStatusEntry } from '../../../../../src/shared/agent-status-types'
import type { DiffComment, TuiAgent } from '../../../src/shared/types'
import type { AgentStatusEntry } from '../../../src/shared/agent-status-types'
import type { MobileBrowserTab } from '../browser/MobileBrowserPane'
import type { MobileTerminalTheme } from '../terminal/terminal-webview-contract'
import type { MobileDiffLine } from './mobile-diff-lines'
import type { MobileHighlightedDiffLine, MobileSyntaxSegment } from './mobile-file-syntax'
import type { TerminalRecord } from './mobile-terminal-records'
export type Terminal = TerminalRecord
@@ -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
})
}
@@ -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()
openMobileTerminalFileTap({
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({
@@ -74,13 +74,17 @@ async function openMobileTerminalFileTapAsync<T extends TerminalFileTapSessionTa
if (!shouldActivateOpenedMobileSessionTab(options.getActivationState(false))) {
return
}
const resolvedWorktreeId = resolved.worktree?.trim() || options.worktreeId
const resolvedWorktree = `id:${resolvedWorktreeId}`
const resolvedWorktreeName =
resolvedWorktreeId === options.worktreeId ? options.worktreeName : undefined
if (resolved.openTarget?.kind === 'absolute-file') {
options.triggerOpenFeedback()
options.pushPreviewRoute(
createMobileFilePreviewHref({
hostId: options.hostId,
worktreeId: options.worktreeId,
worktreeId: resolvedWorktreeId,
source: 'terminalArtifact',
absolutePath: resolved.openTarget.absolutePath,
grantId: resolved.openTarget.grantId,
@@ -92,7 +96,7 @@ async function openMobileTerminalFileTapAsync<T extends TerminalFileTapSessionTa
name: displayNameFromPath(resolved.openTarget.absolutePath),
...(options.line !== null ? { line: String(options.line) } : {}),
...(options.column !== null ? { column: String(options.column) } : {}),
...(options.worktreeName ? { worktreeName: options.worktreeName } : {})
...(resolvedWorktreeName ? { worktreeName: resolvedWorktreeName } : {})
})
)
return
@@ -106,17 +110,21 @@ async function openMobileTerminalFileTapAsync<T extends TerminalFileTapSessionTa
return
}
options.triggerOpenFeedback()
if (options.line !== null || options.column !== null) {
if (
resolvedWorktreeId !== options.worktreeId ||
options.line !== null ||
options.column !== null
) {
options.pushPreviewRoute(
createMobileFilePreviewHref({
hostId: options.hostId,
worktreeId: options.worktreeId,
worktreeId: resolvedWorktreeId,
source: 'worktree',
relativePath: openedPath,
name: displayNameFromPath(openedPath),
...(options.line !== null ? { line: String(options.line) } : {}),
...(options.column !== null ? { column: String(options.column) } : {}),
...(options.worktreeName ? { worktreeName: options.worktreeName } : {})
...(resolvedWorktreeName ? { worktreeName: resolvedWorktreeName } : {})
})
)
return
@@ -131,7 +139,7 @@ async function openMobileTerminalFileTapAsync<T extends TerminalFileTapSessionTa
}
const openResponse = await options.client.sendRequest(
'files.open',
{ worktree, relativePath: openedPath },
{ worktree: resolvedWorktree, relativePath: openedPath },
{ timeoutMs: 15_000 }
)
if (!openResponse.ok) {
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { AgentStatusEntry } from '../../../src/shared/agent-status-types'
import type { TuiAgent } from '../../../src/shared/types'
import type { MobileSessionTab } from '../../app/h/[hostId]/session/mobile-session-route-types'
import type { MobileSessionTab } from './mobile-session-route-types'
import {
getMobileSessionTabTitle,
resolveMobileTerminalTabAgentId
@@ -3,7 +3,7 @@ import { resolveExplicitTerminalTitleAgentType } from '../../../src/shared/termi
import type { AgentStatusEntry } from '../../../src/shared/agent-status-types'
import type { TuiAgent } from '../../../src/shared/types'
import { isBlankBrowserUrl } from '../browser/browser-url'
import type { MobileSessionTab } from '../../app/h/[hostId]/session/mobile-session-route-types'
import type { MobileSessionTab } from './mobile-session-route-types'
// Why: tab identity + title cleaning uses the same shared glyph/label maps as
// desktop, so the two platforms do not drift on which titles identify agents.
@@ -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<string, () => 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)
})
})
@@ -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<Record<string, unknown>>): {
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<string, number>()
private readonly absentSinceExhaustion = new Set<string>()
private readonly announcedExhaustion = new Set<string>()
private readonly retryGenerationByHandle = new Map<string, object>()
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<Record<string, unknown>>,
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<string>): 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<T> = { current: T }
type TerminalFitWebView = {
awaitReady: () => Promise<unknown>
measureFitDimensions: (frameHeight?: number) => Promise<TerminalViewportDims | null | undefined>
}
export type TerminalViewportFitPassArgs = {
handle: string
seq: number
hostCols: number | null
hostRows: number | null
budget: TerminalViewportResubscribeBudget
diagnostics: Pick<
MobileTerminalDiagnostics,
'streamResubscribing' | 'streamResubscribeHeld' | 'streamResubscribeExhausted'
>
viewportRef: MutableRef<TerminalViewportDims | null>
viewportMeasuredRef: MutableRef<boolean>
subscribeSeqRef: MutableRef<Map<string, number>>
initializedHandlesRef: MutableRef<Set<string>>
terminalUnsubsRef: MutableRef<Map<string, () => void>>
terminalFrameHeightRef: MutableRef<number>
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()
}
})()
}
@@ -0,0 +1,62 @@
import { createElement } from 'react'
import TestRenderer from 'react-test-renderer'
import { describe, expect, it } from 'vitest'
import type { AgentStatusEntry } from '../../../src/shared/agent-status-types'
import { useMobileNativeChatPrompts } from './use-mobile-native-chat-prompts'
const APPROVAL = JSON.stringify({
approval: { tool: 'Bash', summary: 'pnpm build > build.log 2>&1' }
})
function permissionFor(status: Partial<AgentStatusEntry> | null): unknown {
let captured: unknown
function Probe(): null {
captured = useMobileNativeChatPrompts({
enabled: true,
status: status as AgentStatusEntry | null,
messages: []
}).permission
return null
}
TestRenderer.act(() => {
TestRenderer.create(createElement(Probe))
})
return captured
}
describe('useMobileNativeChatPrompts approval-envelope state gate', () => {
it('renders no approval card while the agent is working', () => {
expect(permissionFor({ state: 'working', interactivePrompt: APPROVAL })).toBeNull()
})
it('renders no approval card after the turn is done', () => {
expect(permissionFor({ state: 'done', interactivePrompt: APPROVAL })).toBeNull()
})
it('renders no approval card without a status', () => {
expect(permissionFor(null)).toBeNull()
})
it('renders the approval card while the agent is waiting', () => {
expect(permissionFor({ state: 'waiting', interactivePrompt: APPROVAL })).toMatchObject({
title: 'Allow Bash?',
detail: 'pnpm build > build.log 2>&1'
})
})
it('renders the approval card while the agent is blocked', () => {
expect(permissionFor({ state: 'blocked', interactivePrompt: APPROVAL })).toMatchObject({
title: 'Allow Bash?'
})
})
it('prefers the heuristic numbered menu over the envelope while paused', () => {
const permission = permissionFor({
state: 'waiting',
interactivePrompt: APPROVAL,
lastAssistantMessage: 'Allow this Bash command?\n1. Yes\n2. No'
}) as { options: Array<{ label: string }> } | null
expect(permission).toMatchObject({ title: 'Permission requested' })
expect(permission?.options.map((o) => o.label)).toEqual(['Yes', 'No'])
})
})
@@ -19,15 +19,18 @@ export function useMobileNativeChatPrompts(args: {
}): MobileNativeChatPrompts {
const { enabled, status, messages } = args
const blocked = status?.state === 'waiting' || status?.state === 'blocked'
// Both permission paths sit inside the paused gate: an approval envelope can
// outlive its answer (the host keeps it sticky), so only a waiting/blocked
// agent may surface it — never a working or done one (STA-3144).
const permission =
(blocked && status
? detectAgentPermission({
blocked && status
? (detectAgentPermission({
state: status.state,
lastAssistantMessage: status.lastAssistantMessage,
toolName: status.toolName,
toolInput: status.toolInput
})
: null) ?? parseApprovalFromStatus(status?.interactivePrompt)
}) ?? parseApprovalFromStatus(status.interactivePrompt))
: null
const question =
blocked && status && !permission ? parseAgentQuestion(status.lastAssistantMessage ?? '') : null
const askFromStatus = useMemo(
@@ -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> = {}
): 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 })
})
})
@@ -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))
}
@@ -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
});
}
`
@@ -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<typeof makeLine> | undefined)[], altScreen = false) {
const notifications: Record<string, unknown>[] = []
const buffer = {
cursorY: 2,
viewportY: 3,
type: altScreen ? 'alternate' : 'normal',
getLine: (index: number) => lines[index - 3],
getNullCell: () => ({})
}
const context = {
notifications,
notify: (message: Record<string, unknown>) => 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<string, unknown>[] = []
new Script(
`${TERMINAL_KEYBOARD_AVOIDANCE_METRICS_JS}\nemitKeyboardAvoidanceMetrics();`
).runInNewContext({
notify: (message: Record<string, unknown>) => notifications.push(message),
term
})
return notifications[0] as MetricsNotification
}
function write(term: Terminal, data: string): Promise<void> {
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')
)
}
})
})
@@ -10,7 +10,7 @@ const liveInputStatusSource = readFileSync(
'utf8'
)
const commandInputStylesSource = readFileSync(
new URL('../../app/h/[hostId]/session/mobile-session-command-input-styles.ts', import.meta.url),
new URL('../session/mobile-session-command-input-styles.ts', import.meta.url),
'utf8'
)
const liveInputFocusSource = readFileSync(
@@ -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 })
})
})
@@ -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<string, unknown>
): 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 = {
+5 -11
View File
@@ -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;
@@ -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
})
})
})
@@ -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') {
@@ -28,5 +28,6 @@ export const TERMINAL_REFLOW_JS = `
}
applyFitScale('reflow-msg');
updateScrollIndicator(false);
emitKeyboardAvoidanceMetrics();
}
`
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { colors } from './mobile-theme'
function channelLuminance(channel: number): number {
const value = channel / 255
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
}
function relativeLuminance(hex: string): number {
const red = Number.parseInt(hex.slice(1, 3), 16)
const green = Number.parseInt(hex.slice(3, 5), 16)
const blue = Number.parseInt(hex.slice(5, 7), 16)
return (
0.2126 * channelLuminance(red) +
0.7152 * channelLuminance(green) +
0.0722 * channelLuminance(blue)
)
}
function contrastRatio(foreground: string, background: string): number {
const lighter = Math.max(relativeLuminance(foreground), relativeLuminance(background))
const darker = Math.min(relativeLuminance(foreground), relativeLuminance(background))
return (lighter + 0.05) / (darker + 0.05)
}
describe('mobile text contrast', () => {
it('keeps muted text readable on every standard dark surface', () => {
for (const surface of [colors.bgBase, colors.bgPanel, colors.bgRaised]) {
expect(contrastRatio(colors.textMuted, surface)).toBeGreaterThanOrEqual(4.5)
}
})
it('keeps secondary text more prominent than muted text', () => {
expect(contrastRatio(colors.textSecondary, colors.bgPanel)).toBeGreaterThan(
contrastRatio(colors.textMuted, colors.bgPanel)
)
})
})
+2 -2
View File
@@ -9,8 +9,8 @@ export const colors = {
editorSurface: '#1e1e1e',
textPrimary: '#e0e0e0',
textSecondary: '#888888',
textMuted: '#555555',
textSecondary: '#a1a1a1',
textMuted: '#8c8c8c',
// Crisp near-white surface for the single primary action on a screen (the
// worktree FAB). Brighter than textPrimary so it reads as a solid button, not
@@ -0,0 +1,301 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { connect } from './rpc-client'
import { classifyConnection, verdictDisplayLabel } from './connection-health'
// Slack P0 — "mobile connection issue. was using it with my linux host then
// after i navigated out of the app and back it doesn't work anymore. Now i went
// back again it's connected now."
//
// The tell is that the SECOND foreground fixed it. notifyForeground only ever
// acted on 'connected' (probe the socket) and 'reconnecting' (redial now). A
// phone that is suspended mid-dial resumes in 'connecting'/'handshaking', where
// the nudge did nothing: the user waited out the remainder of the 12s connect
// budget on a socket opened over a network path that no longer existed, and
// then the *preserved* backoff delay — up to 60s of "Connecting…" against a
// desktop that was answering the whole time. By the next foreground the client
// had landed in 'reconnecting', where the nudge works, so it connected at once.
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) => `encrypted:${plaintext}`,
decrypt: (raw: string) => raw.replace(/^encrypted:/, ''),
decryptBytes: (bytes: Uint8Array) => bytes
}))
// Mirrors React Native's WebSocket: readyState lives in JS and only advances on
// a delivered event, so a socket the OS killed while the app was suspended stays
// CONNECTING forever from the client's point of view.
class MockWebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
readonly CONNECTING = 0
readonly OPEN = 1
readyState = MockWebSocket.CONNECTING
onopen: (() => void) | null = null
onclose: ((event?: unknown) => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onerror: ((event?: unknown) => void) | null = null
// A socket the OS tore down while suspended never reports its own close.
deliversCloseEvent = true
sent: string[] = []
constructor(readonly endpoint: string) {
sockets.push(this)
}
send(payload: string): void {
this.sent.push(payload)
}
close(): void {
if (this.readyState === MockWebSocket.CLOSED) {
return
}
this.readyState = MockWebSocket.CLOSED
if (this.deliversCloseEvent) {
this.onclose?.({ code: 1006, wasClean: false })
}
}
open(): void {
this.readyState = MockWebSocket.OPEN
this.onopen?.()
}
authenticate(): void {
this.open()
this.onmessage?.({ data: JSON.stringify({ type: 'e2ee_ready' }) })
this.onmessage?.({ data: 'encrypted:{"type":"e2ee_authenticated"}' })
}
}
const sockets: MockWebSocket[] = []
const originalWebSocket = globalThis.WebSocket
function latest(): MockWebSocket {
const socket = sockets[sockets.length - 1]
if (!socket) {
throw new Error('no socket opened')
}
return socket
}
function label(client: ReturnType<typeof connect>, endpoint: string): string {
return verdictDisplayLabel(
classifyConnection({
state: client.getState(),
reconnectAttempts: client.getReconnectAttempt(),
lastConnectedAt: client.getLastConnectedAt(),
endpoint,
nowMs: Date.now()
})
)
}
// A suspended app is not a slow app: wall-clock time passes but not one JS timer
// runs, so the backoff loop does NOT keep cycling in the background. Advancing
// the system clock without draining the timer queue is what reproduces that —
// the connect timer armed before the suspension is still pending on resume, and
// the client is still sitting in the state it was suspended in.
function suspend(backgroundMs: number): void {
for (const socket of sockets) {
// iOS reclaims a suspended app's sockets without telling JS.
socket.deliversCloseEvent = false
}
vi.setSystemTime(Date.now() + backgroundMs)
}
// Steps the clock one second at a time and reports how long the user has to sit
// on "Connecting…" before the client opens its next socket.
async function millisecondsUntilNextDial(dialsBefore: number): Promise<number> {
const limitMs = 180_000
for (let elapsedMs = 0; elapsedMs <= limitMs; elapsedMs += 1_000) {
if (sockets.length > dialsBefore) {
return elapsedMs
}
await vi.advanceTimersByTimeAsync(1_000)
}
return limitMs
}
// Waits out the current backoff so the phone is suspended mid-dial — the state
// the reporter's phone resumed into — rather than between dials.
async function advanceUntilDialing(client: ReturnType<typeof connect>): Promise<void> {
for (let elapsedMs = 0; elapsedMs <= 120_000; elapsedMs += 250) {
if (client.getState() === 'connecting') {
return
}
await vi.advanceTimersByTimeAsync(250)
}
throw new Error(`client never re-entered connecting (state=${client.getState()})`)
}
const TAILSCALE_ENDPOINT = 'ws://100.84.12.9:6769'
describe('foregrounding a phone that was suspended mid-dial', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(console, 'log').mockImplementation(() => {})
sockets.length = 0
globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
globalThis.WebSocket = originalWebSocket
})
it('abandons a dial that predates the foreground edge instead of waiting it out', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
expect(client.getState()).toBe('connected')
// The user leaves the app. The link dies while the phone is suspended, so
// the client is left holding a socket that will never open.
latest().close()
expect(client.getState()).toBe('reconnecting')
await vi.advanceTimersByTimeAsync(500)
expect(client.getState()).toBe('connecting')
const doomed = latest()
suspend(120_000)
// Back in the app. The desktop is healthy and answering.
const socketsBeforeForeground = sockets.length
client.notifyForeground()
expect(sockets.length).toBe(socketsBeforeForeground + 1)
expect(latest()).not.toBe(doomed)
latest().authenticate()
expect(client.getState()).toBe('connected')
})
it('does not strand the user on "Connecting…" for a minute after returning', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
latest().close()
// The desktop drops off the network while the user is still in the app, so
// the tiered backoff climbs into its slow tail (15s, 30s, 60s) before they
// ever leave. This is what makes the post-resume wait a full minute.
for (let dial = 0; dial < 6; dial++) {
await vi.advanceTimersByTimeAsync(12_000 + 60_000)
}
expect(client.getReconnectAttempt()).toBeGreaterThanOrEqual(6)
await advanceUntilDialing(client)
suspend(90_000)
const dialsBefore = sockets.length
client.notifyForeground()
// The desktop is reachable again and the user is looking at the screen, so
// the redial has to be in flight now — not after the abandoned socket's
// connect budget expires and another tail-length backoff is waited out.
expect(await millisecondsUntilNextDial(dialsBefore)).toBe(0)
latest().authenticate()
expect(client.getState()).toBe('connected')
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
client.close()
})
it('clears the escalated label once the foreground redial lands', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
latest().close()
for (let dial = 0; dial < 4; dial++) {
await vi.advanceTimersByTimeAsync(12_000 + 60_000)
}
// Four failed dials is past WARNING_ATTEMPTS, so the card reads "Can't
// connect — check Tailscale" rather than a neutral "Connecting…".
expect(label(client, TAILSCALE_ENDPOINT)).toBe("Can't connect — check Tailscale")
await advanceUntilDialing(client)
const doomed = latest()
suspend(120_000)
client.notifyForeground()
expect(latest()).not.toBe(doomed)
latest().authenticate()
expect(client.getState()).toBe('connected')
expect(client.getReconnectAttempt()).toBe(0)
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
client.close()
})
it('keeps escalating when the user checks back repeatedly during a real outage', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
latest().close()
// The desktop really is gone. Abandoning the stale dial must book the failure
// it represents, or each visit resets the counter faster than it can climb and
// the card reassures the user with "Connecting…" indefinitely (issue #10119).
for (let visit = 0; visit < 14; visit++) {
await advanceUntilDialing(client)
suspend(30_000)
client.notifyForeground()
}
expect(client.getReconnectAttempt()).toBeGreaterThanOrEqual(12)
expect(label(client, TAILSCALE_ENDPOINT)).toBe("Can't reach desktop — check Tailscale")
// And the escalation is not sticky: the desktop comes back, the card clears.
latest().authenticate()
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
client.close()
})
it('leaves a dial opened after the foreground edge alone', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
latest().close()
await vi.advanceTimersByTimeAsync(500)
const fresh = latest()
expect(client.getState()).toBe('connecting')
// A Wi-Fi→cellular handoff fires a second revival nudge right behind the
// AppState one. It must not churn the dial that the first nudge just opened.
client.notifyForeground()
const afterFirstNudge = latest()
client.notifyForeground()
client.notifyForeground()
expect(latest()).toBe(afterFirstNudge)
expect(fresh.endpoint).toBe(TAILSCALE_ENDPOINT)
client.close()
})
it('abandons a handshake stalled across the suspension', async () => {
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
latest().authenticate()
latest().close()
await vi.advanceTimersByTimeAsync(500)
// The upgrade completed but the desktop never sent e2ee_ready before the
// phone was suspended — the classic wedged relay/Tailscale half-open.
latest().open()
expect(client.getState()).toBe('handshaking')
const wedged = latest()
suspend(120_000)
client.notifyForeground()
expect(latest()).not.toBe(wedged)
latest().authenticate()
expect(client.getState()).toBe('connected')
client.close()
})
})
@@ -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<typeof setTimeout> | 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<void>
onDirectMigrated: () => Promise<void>
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<void> {
if (!this.hooks.canAttempt() || !this.hooks.hysteresis.canProbe(this.deps.now())) {
this.schedule()
return
}
this.hooks.beginOperation()
let successful: Awaited<ReturnType<typeof openAuthenticatedDirectEndpoint>> = 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()
}
}
}
@@ -90,6 +90,7 @@ function createSupervisor(
readBundle: readMobileRelayCredentialBundle,
writeBundle: writeMobileRelayCredentialBundle,
saveHost,
onLog,
now: Date.now,
randomBytes: ExpoCrypto.getRandomBytes,
setTimer: setTimeout,
@@ -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
}
@@ -52,18 +52,21 @@ class FakeRelaySession extends FakeSession implements MobileRelayRpcSession {
constructor(
state: ConnectionState,
private readonly failure: Error | null = null,
private readonly lease = Date.now() + 120_000
private readonly resumeExpiry = Date.now() + 30 * 24 * 3_600_000
) {
super(state)
}
getLeaseExpiresAt = () => this.lease
// 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: 'current' as const,
renewed: true,
resumeExpiresAt: Date.now() + 300_000
resumeExpiresAt: this.resumeExpiry
})
getFailure = () => this.failure
}
@@ -716,6 +719,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 +748,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 +790,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)
@@ -808,12 +816,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 +842,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)
@@ -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<typeof setTimeout> | 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<void> {
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,21 @@ 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.
this.leaseRotation.scheduleFromLease(
this.stopped || !this.foreground ? null : session.getLeaseExpiresAt()
this.stopped || !this.foreground
? 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<void> {
if (
this.stopped ||
!this.foreground ||
this.operationInFlight ||
!this.hysteresis.canProbe(this.dependencies.now())
) {
this.scheduleDirectProbe()
return
}
this.operationInFlight = true
let successful: Awaited<ReturnType<typeof openAuthenticatedDirectEndpoint>> = 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<void> {
if (
this.stopped ||
@@ -321,11 +318,4 @@ export class MobileEndpointSupervisor {
}
}
}
private clearDirectProbeTimer(): void {
if (this.probeTimer) {
this.dependencies.clearTimer(this.probeTimer)
this.probeTimer = null
}
}
}
@@ -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<MobileRelayCredentialBundle | null>
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: [] }
}
@@ -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)
}
@@ -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,104 @@ 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('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', () => {
@@ -17,6 +17,12 @@ 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
// 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
export type RelayReconnectDependencies = {
now: () => number
@@ -34,6 +40,8 @@ export class RelayReconnectController {
private timer: ReturnType<typeof setTimeout> | null = null
private activeSession: MobileRelayRpcSession | null = null
private recoveryGate: RecoveryGate | null = null
private gateReprobePending = false
private gateReprobeStreak = 0
private readonly rejectedCredentialVersions = new Set<number>()
constructor(
@@ -43,12 +51,15 @@ export class RelayReconnectController {
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 +98,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 +107,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 +142,36 @@ 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
}
// 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.gateReprobeDelayMs()
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 +194,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 +219,9 @@ 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.
this.clearTimer()
this.scheduleGateReprobe()
return
}
const now = this.dependencies.now()
@@ -192,15 +239,20 @@ export class RelayReconnectController {
recovery?.kind === 'retry-after-host-offline' ? this.hostOfflineDelayMs() : this.delayMs()
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()
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()
this.scheduleGateReprobe()
return
}
if (recovery?.kind === 'retry-after-host-offline') {
@@ -235,12 +287,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,6 +315,45 @@ export class RelayReconnectController {
}, delay)
}
private scheduleGateReprobe(): void {
this.scheduleReprobeTick(this.gateReprobeDelayMs(), true)
}
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 gateReprobeDelayMs(): number {
const base = Math.min(
RELAY_GATE_REPROBE_CEILING_MS,
RELAY_GATE_REPROBE_BASE_MS * 2 ** Math.min(this.gateReprobeStreak, 8)
)
return Math.floor(base * (0.75 + 0.5 * this.jitterFraction()))
}
// 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()
}
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)

Some files were not shown because too many files have changed in this diff Show More