diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 400ed2719d3..f791a59c63e 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -53,6 +53,15 @@ pnpm install
pnpm dev
```
+`mobile/` is a separate pnpm project with its own lockfile, so the root `pnpm install` leaves its
+dependencies uninstalled. `pnpm build` (`build:mobile-web` fails without them) and the lint
+passes that cover `mobile/` need them. Install them before building or linting, and again
+when `mobile/pnpm-lock.yaml` changes:
+
+```bash
+pnpm -C mobile install --frozen-lockfile
+```
+
### Dev Profiles and Parallel Instances
`pnpm dev` in a linked Git worktree uses its own userData profile, renderer port, and remote
@@ -170,7 +179,7 @@ Avoid vague names like `test`, `misc`, or `changes`.
## Before Opening a PR
-Run the same checks that CI runs:
+Run the same checks that CI runs, after the `mobile/` install from [Local Setup](#local-setup):
```bash
pnpm lint
@@ -261,8 +270,6 @@ All stable kinds (`patch`, `minor`, `major`) are computed off the latest _stable
- **One-off RC for a feature branch:** `kind=rc`, `ref=`. Produces an RC tag that does not touch `main`.
- **Minor or major bump:** `kind=minor` or `kind=major`.
-The scheduled 2x/day RC cron in [`release-rc.yml`](../../actions/workflows/release-rc.yml) is independent and continues to run automatically from `main`.
-
## Release Channels
The public Homebrew cask tracks stable desktop releases:
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index cf330430661..19b5f42eabb 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -81,6 +81,7 @@ jobs:
/config/scripts/pr-layout-oracle-route.mjs
/config/scripts/pr-e2e-source-routing.mjs
/config/scripts/pr-browser-e2e-source-routes.mjs
+ /config/scripts/pr-editor-preview-e2e-source-routes.mjs
/config/scripts/ci-e2e-job-selection.mjs
/config/scripts/pr-ready-check-reuse.mjs
sparse-checkout-cone-mode: false
diff --git a/.github/workflows/wsl-orcad-e2e.yml b/.github/workflows/wsl-orcad-e2e.yml
index fc96f7ea76f..3d7b8e8390e 100644
--- a/.github/workflows/wsl-orcad-e2e.yml
+++ b/.github/workflows/wsl-orcad-e2e.yml
@@ -151,8 +151,8 @@ jobs:
name: WSL2 distro (${{ matrix.family }})
needs: [template, container-rootfs]
runs-on: windows-2025
- # Healthy runs take 4-11 min; a runner frozen during WSL2 setup is only reaped here (retried by wsl-orcad-e2e-frozen-runner-retry.yml).
- timeout-minutes: 30
+ # Healthy runs take 4-11 min plus the phase 3 restart baseline; a runner frozen during WSL2 setup is only reaped here (retried by wsl-orcad-e2e-frozen-runner-retry.yml).
+ timeout-minutes: 40
strategy:
fail-fast: false
matrix:
@@ -355,8 +355,8 @@ jobs:
if ($global:LASTEXITCODE -ne 0) { throw "WSL move real pause failed: $global:LASTEXITCODE" }
wsl.exe --terminate $env:PLAIN_DISTRO
# R40: with no terminal left, orcad idle-exits and the holder lets the distro stop on its own.
- - name: 'Phase 3: idle orcad releases the distro'
- timeout-minutes: 15
+ - name: 'Phase 3: idle orcad releases the distro; distro restart to first output baseline'
+ timeout-minutes: 30
env:
ORCA_RUN_WSL_ORCAD_LANE: '1'
ORCA_WSL_ORCAD_LANE_PHASE: idle-release
diff --git a/README.md b/README.md
index 0618bad096b..54d7fa0fae8 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
- 中文 · 日本語 · 한국어 · Español · Français · Português · Türkçe
+ 中文 · 日本語 · 한국어 · Español · Français · Português · Türkçe · Русский
@@ -272,7 +272,7 @@ The relay that pairs the mobile app with a desktop host is also in this reposito
## Signed Builds
-Windows code signing sponored/provided by [SignPath.io](https://signpath.io), certificate by [SignPath Foundation](https://signpath.org).
+Windows code signing sponsored/provided by [SignPath.io](https://signpath.io), certificate by [SignPath Foundation](https://signpath.org).
## License
diff --git a/config/daemon-blocking-call-baseline.txt b/config/daemon-blocking-call-baseline.txt
index 05e615e08eb..66debece11c 100644
--- a/config/daemon-blocking-call-baseline.txt
+++ b/config/daemon-blocking-call-baseline.txt
@@ -3,7 +3,6 @@
# This is a RATCHET: counts may only go DOWN.
# Prune after removing calls: pnpm check:daemon-blocking-call-ratchet --prune
2 src/main/daemon/daemon-cgroup-scope.ts
-1 src/main/daemon/daemon-file-log.ts
1 src/main/daemon/daemon-process-identity-query.ts
1 src/main/daemon/daemon-process-start-time.ts
2 src/main/daemon/daemon-stream-backlog-probe.ts
diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt
index 5949a9a02fd..14ae5b5a3e2 100644
--- a/config/focus-setting-read-baseline.txt
+++ b/config/focus-setting-read-baseline.txt
@@ -3,7 +3,8 @@
# This is a RATCHET: counts may only go DOWN. Only creation flows with no source row may read
# the default host, through defaultCreationHost. Everything else routes by the owner.
# Prune after removing reads: pnpm check:focus-read-ratchet --prune
-3 src/renderer/src/app-shell/use-app-shell-services.ts
+1 src/renderer/src/app-shell/ActiveWorkspaceSyncGate.tsx
+2 src/renderer/src/app-shell/use-app-shell-services.ts
2 src/renderer/src/App.tsx
1 src/renderer/src/component-fixtures/component-fixture-explorer.tsx # dev-only fixture page seeds default settings
1 src/renderer/src/components/activity/activity-scope-filter-controls.tsx
diff --git a/config/i18n-german.md b/config/i18n-german.md
new file mode 100644
index 00000000000..1e532fa611f
--- /dev/null
+++ b/config/i18n-german.md
@@ -0,0 +1,71 @@
+# German (de) UI Glossary and Style
+
+Catalog: `src/renderer/src/i18n/locales/de.json`. Missing keys fall back to English at runtime. System detection maps `de`, `de-DE`, `de-AT`, `de-CH` and POSIX tags such as `de_DE.UTF-8` to `de`.
+
+## Voice
+
+- Avoid addressing the user. Prefer neutral phrasing: `Branch auswählen`, `Keine Worktrees gefunden`, `Datei konnte nicht gespeichert werden.`
+- When a sentence must address the user, use informal `du` consistently (`dein`, `dir`), lowercase. Never use `Sie`.
+- Buttons, menu items and commands use the infinitive: `Öffnen`, `Speichern`, `Löschen`, `Entfernen`, `Erneut versuchen`, `Abbrechen`.
+- Failures: `… konnte nicht geladen werden.` in sentences, `Laden fehlgeschlagen` in short labels.
+- Confirmations are impersonal questions: `Fenster schließen?`, `Worktree löschen?`
+- German has no title case. Capitalize nouns and the first word only, even when the English label uses title case. Keep brand names and acronyms as written.
+- Labels have no final period. Use `…`, not `...`. Use German quotes `„…“` in prose; keep backticks and code quoting as in the source.
+- Join English terms to German words with a hyphen: `Worktree-Name`, `Branch-Name`, `SSH-Verbindung`, `PR-Titel`, `Git-Repository`.
+- German strings run about 30% longer than English. Prefer the shorter natural wording for buttons, tabs and badges, but never drop meaning.
+- Plurals follow English (`_one` / `_other`). Keep `{{count}}` wherever the English form has it.
+
+## Terms
+
+Keep Git and developer terms that German developers use in English. Use the noun genders below for articles and adjective endings.
+
+| English | German | Note |
+| ---------------------------- | --------------------------------------------- | ---------------------------------------------------------- |
+| worktree | der Worktree, die Worktrees | Distinct from workspace. |
+| workspace | der Arbeitsbereich | |
+| repository / repo | das Repository (die Repositorys) / das Repo | |
+| branch / base branch | der Branch (die Branches) / Basis-Branch | |
+| commit | der Commit; verb `committen` | |
+| pull request / PR | der Pull Request / PR | `merge request` stays `Merge Request` (GitLab). |
+| merge, rebase, diff, stash | Merge, Rebase, Diff, Stash | Verbs: `mergen`, `rebasen`, `stashen`. |
+| checkout | Checkout; verb `auschecken` | |
+| push / pull / fetch | Push / Pull / Fetch | Verbs: `pushen`, `pullen`, `fetchen`. |
+| remote (Git) / remote host | das Remote / Remote-Host | `remote` as an adjective: `entfernt`. |
+| issue | das Issue | |
+| review / code review | das Review / Code-Review | |
+| check (CI) | der Check | |
+| label (issue/PR) | das Label, die Labels | |
+| approve / comment | genehmigen / der Kommentar | |
+| source control | Quellcodeverwaltung | |
+| agent | der Agent, die Agenten | |
+| chat / prompt | der Chat / der Prompt | |
+| skill / plugin / hook | der Skill / das Plugin / der Hook | |
+| session | die Sitzung | |
+| terminal / shell | das Terminal / die Shell | |
+| tab | der Tab | The keyboard key stays `Tab`. |
+| pane / panel | der Bereich / das Panel | Split pane: `Bereich teilen`. Keep the two terms distinct. |
+| sidebar / status bar | die Seitenleiste / die Statusleiste | |
+| editor / browser | der Editor / der Browser | |
+| command palette / quick open | Befehlspalette / Schnellöffnen | |
+| file / folder / directory | Datei / Ordner / Verzeichnis | |
+| project | das Projekt | |
+| host / server / SSH host | der Host / der Server / der SSH-Host | |
+| automation / task | die Automatisierung / die Aufgabe | |
+| dashboard | das Dashboard | |
+| settings | die Einstellungen | |
+| shortcut / keybinding | das Tastenkürzel / die Tastenbelegung | |
+| sign in / sign out | anmelden / abmelden | |
+| account / provider / model | das Konto / der Anbieter / das Modell | |
+| token (LLM or auth) | der Token | |
+| usage / quota / rate limit | die Nutzung / das Kontingent / das Ratenlimit | |
+| credits / balance | Credits / das Guthaben | |
+| notification | die Benachrichtigung | |
+| delete / remove | löschen / entfernen | Keep the two terms distinct. |
+| enable / disable / default | aktivieren / deaktivieren / Standard | |
+| pin / unread / archive | anheften / ungelesen / archivieren | |
+| environment / sandbox | die Umgebung / die Sandbox | |
+| dictation | das Diktat; verb `diktieren` | |
+| clipboard | die Zwischenablage | |
+| port forwarding | die Portweiterleitung | |
+
+Do not translate placeholders (`{{value0}}`), markup, commands, paths, keyboard keys, or labels that belong to another product's UI.
diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json
index 7c2b73721d3..0c6f12bc809 100644
--- a/config/localization-coverage-allowlist.json
+++ b/config/localization-coverage-allowlist.json
@@ -20,6 +20,13 @@
"dynamic": false,
"count": 1
},
+ {
+ "filePath": "src/renderer/src/components/settings/appearance-search.ts",
+ "kind": "object-property:keywords",
+ "text": "Sprache",
+ "dynamic": false,
+ "count": 1
+ },
{
"filePath": "src/renderer/src/components/settings/appearance-search.ts",
"kind": "object-property:keywords",
diff --git a/config/patches/vitest@5.0.5.patch b/config/patches/vitest@5.0.5.patch
deleted file mode 100644
index 7a8746da87d..00000000000
--- a/config/patches/vitest@5.0.5.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-diff --git a/dist/chunks/cli-api.De07GUeT.js b/dist/chunks/cli-api.De07GUeT.js
---- a/dist/chunks/cli-api.De07GUeT.js
-+++ b/dist/chunks/cli-api.De07GUeT.js
-@@ -11817,7 +11817,8 @@ class TestRun {
- else error.stacks = parseErrorStacktrace(error, {
- frameFilter: project.config.onStackTrace,
- getSourceMap(file) {
-- if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && existsSync(file)) {
-+ // Orca: stack frames can name a directory; existsSync accepts it and readFileSync then throws EISDIR, failing a green run.
-+ if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && statSync(file, { throwIfNoEntry: false })?.isFile()) {
- const code = readFileSync(file, "utf-8");
- return extractSourcemapFromFile(code, file)?.map;
- }
diff --git a/config/scripts/apply-translation-delta.mjs b/config/scripts/apply-translation-delta.mjs
index ee3b5ac7f08..545e5379ec4 100644
--- a/config/scripts/apply-translation-delta.mjs
+++ b/config/scripts/apply-translation-delta.mjs
@@ -5,7 +5,7 @@ import process from 'node:process'
import { repairTranslatedValue } from './locale-translation-policy.mjs'
const LOCALES_DIR = path.join('src', 'renderer', 'src', 'i18n', 'locales')
-const SUPPORTED_LOCALES = new Set(['es', 'fr', 'ja', 'ko', 'ru', 'zh'])
+const SUPPORTED_LOCALES = new Set(['de', 'es', 'fr', 'ja', 'ko', 'ru', 'zh'])
const PLACEHOLDER_RE = /\{\{[^}]+\}\}/g
function placeholders(value) {
diff --git a/config/scripts/browser-session-startup-metadata-benchmark.mjs b/config/scripts/browser-session-startup-metadata-benchmark.mjs
new file mode 100644
index 00000000000..e1b5ca1cdca
--- /dev/null
+++ b/config/scripts/browser-session-startup-metadata-benchmark.mjs
@@ -0,0 +1,167 @@
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { performance } from 'node:perf_hooks'
+
+const root = resolve(import.meta.dirname, '../..')
+const baseline = process.argv[2] ?? 'HEAD^'
+const require = createRequire(join(root, 'package.json'))
+const { build } = require('esbuild')
+const relative = 'src/main/browser/browser-session-registry.ts'
+const target = join(root, relative)
+const scratch = mkdtempSync(join(tmpdir(), 'orca-browser-meta-bench-'))
+const previousSource = execFileSync('git', ['show', `${baseline}:${relative}`], {
+ cwd: root,
+ encoding: 'utf8'
+})
+const sources = { before: previousSource, after: readFileSync(target, 'utf8') }
+const stubs = new Map([
+ [
+ 'electron',
+ 'export const app={getPath:()=>globalThis.__metaBench.directory}; export const session={fromPartition:()=>({})};'
+ ],
+ [
+ './browser-session-cookie-staging',
+ 'export function applyPendingBrowserCookieImports(){} export function clearPendingBrowserCookieImport(){}'
+ ],
+ [
+ './browser-session-partition-policies',
+ 'export async function installBrowserSessionPartitionPolicies(){}'
+ ],
+ [
+ './browser-session-route-policies',
+ 'export function clearBrowserRoutePartitionPolicies(){} export async function installBrowserRoutePartitionPolicies(){}'
+ ],
+ [
+ './browser-session-profile-retirement',
+ 'export async function retireDeletedBrowserSessionProfile(){} export async function retireFailedBrowserSessionProfile(){}'
+ ],
+ [
+ '../persistence/loading-store/user-data-path',
+ 'export function getCanonicalUserDataPath(){return globalThis.__metaBench.directory}'
+ ],
+ [
+ './browser-identity-mode-store',
+ 'export async function markBrowserIdentityMigrationNoticePending(){}'
+ ],
+ ['./browser-site-permission-store', 'export function forgetBrowserSitePermissions(){}'],
+ ['./browser-site-display-store', 'export function forgetBrowserSiteDisplay(){}'],
+ [
+ './extensions/browser-extension-session-loader',
+ 'export function attachBrowserExtensionsToProfileSession(profile,ids){globalThis.__metaBench.assignments.push([profile.id,ids])}'
+ ]
+])
+const registryByVersion = {}
+try {
+ for (const [version, source] of Object.entries(sources)) {
+ const output = join(scratch, `${version}.cjs`)
+ await build({
+ stdin: { contents: source, sourcefile: target, resolveDir: dirname(target), loader: 'ts' },
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ outfile: output,
+ plugins: [
+ {
+ name: 'isolate-startup-metadata',
+ setup(builder) {
+ builder.onResolve({ filter: /.*/ }, (args) => {
+ if (args.importer === target && stubs.has(args.path)) {
+ return { path: args.path, namespace: 'startup-stub' }
+ }
+ if (
+ args.path === 'node:fs' &&
+ args.importer.endsWith('/browser-session-meta-store.ts')
+ ) {
+ return { path: 'fs-probe', namespace: 'startup-stub' }
+ }
+ })
+ builder.onLoad({ filter: /.*/, namespace: 'startup-stub' }, (args) => ({
+ contents:
+ args.path === 'fs-probe'
+ ? `import * as fs from 'node:fs'; export const {mkdirSync,renameSync,writeFileSync}=fs; export function readFileSync(...args){const result=fs.readFileSync(...args);globalThis.__metaBench.reads++;globalThis.__metaBench.bytes+=Buffer.byteLength(result);return result}`
+ : stubs.get(args.path),
+ loader: 'js'
+ }))
+ }
+ }
+ ]
+ })
+ globalThis.__metaBench = { directory: scratch, reads: 0, bytes: 0, assignments: [] }
+ registryByVersion[version] = require(output).browserSessionRegistry
+ }
+ const rows = []
+ for (const count of [10, 100, 1000]) {
+ const profiles = Array.from({ length: count }, (_, index) => {
+ const id = `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`
+ return {
+ id,
+ scope: 'isolated',
+ partition: `persist:orca-browser-session-${id}`,
+ label: `Browser ${index}`,
+ source: null
+ }
+ })
+ const enabledExtensionIdsByProfileId = Object.fromEntries([
+ ['default', ['default-extension']],
+ ...profiles.map((profile, index) => [profile.id, [`extension-${index}`]])
+ ])
+ const json = JSON.stringify({ profiles, enabledExtensionIdsByProfileId })
+ writeFileSync(join(scratch, 'browser-session-meta.json'), json)
+ const row = { profiles: count, metadataBytes: Buffer.byteLength(json) }
+ let beforeAssignments
+ for (const [version, registry] of Object.entries(registryByVersion)) {
+ const timings = []
+ for (let iteration = 0; iteration < 4; iteration++) {
+ globalThis.__metaBench = { directory: scratch, reads: 0, bytes: 0, assignments: [] }
+ registry.configureForOrcaProfile({
+ orcaProfileId: 'local-default',
+ profileDirectory: scratch
+ })
+ globalThis.__metaBench.reads = 0
+ globalThis.__metaBench.bytes = 0
+ const start = performance.now()
+ registry.initializeBrowserSessionsFromPersistedState()
+ const durationMs = performance.now() - start
+ const probe = globalThis.__metaBench
+ assert.equal(probe.reads, version === 'before' ? count + 2 : 1)
+ assert.equal(registry.listProfiles().length, count + 1)
+ assert.equal(probe.assignments.length, count + 1)
+ if (version === 'before') {
+ beforeAssignments = probe.assignments
+ } else {
+ assert.deepEqual(probe.assignments, beforeAssignments)
+ }
+ if (iteration > 0) {
+ timings.push(durationMs)
+ }
+ row[version] = { reads: probe.reads, bytes: probe.bytes }
+ await Promise.resolve()
+ }
+ timings.sort((left, right) => left - right)
+ row[version].medianSynchronousMs = Number(timings[1].toFixed(3))
+ }
+ rows.push(row)
+ }
+ console.log(
+ JSON.stringify(
+ {
+ node: process.version,
+ platform: process.platform,
+ baseline,
+ productionSeam: 'initializeBrowserSessionsFromPersistedState',
+ limitations:
+ 'Warm local filesystem; actual registry, JSON parser, profile validation and disk reads. Electron policy installation and extension loading stubbed. Synchronous hydration only; excludes process startup and guest creation.',
+ rows
+ },
+ null,
+ 2
+ )
+ )
+} finally {
+ rmSync(scratch, { recursive: true, force: true })
+ delete globalThis.__metaBench
+}
diff --git a/config/scripts/build-cli.mjs b/config/scripts/build-cli.mjs
index 6a66dfdb7a3..1825a35b12b 100644
--- a/config/scripts/build-cli.mjs
+++ b/config/scripts/build-cli.mjs
@@ -2,12 +2,13 @@ import { availableParallelism } from 'node:os'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { runProcess, runProcessSync } from '@orca/process-host'
-import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
+import { runProcess } from '@orca/process-host'
import { describeProcessFailure } from './process-failure-message.mjs'
import { isDirectInvocation } from './script-entry-detection.mjs'
+import { supportsTsrs } from './tsrs-typecheck-compiler.mjs'
import {
resolveProjectCompiler,
+ resolveTypecheckBunExecutable,
runTypecheckProjects,
selectTypecheckCompiler
} from './run-typecheck-projects-in-parallel.mjs'
@@ -21,7 +22,7 @@ export async function buildCli({
check = runTypecheckProjects,
execute = runProcess,
compiler = process.env.ORCA_CLI_BUILD_COMPILER ?? 'bun',
- resolveBunExecutable = (directory) => resolvePinnedBunExecutable(directory, runProcessSync)
+ resolveBunExecutable = resolveTypecheckBunExecutable
} = {}) {
if (compiler !== 'bun' && compiler !== 'tsrs') {
throw new Error(`Invalid ORCA_CLI_BUILD_COMPILER: ${compiler}`)
@@ -50,7 +51,11 @@ export async function buildCli({
}
return
}
- const selection = selectTypecheckCompiler('bun', { root, resolveBunExecutable })
+ const selection = selectTypecheckCompiler('bun', {
+ root,
+ resolveBunExecutable,
+ fallbackHint: supportsTsrs() ? 'set ORCA_CLI_BUILD_COMPILER=tsrs' : null
+ })
const failures = await check({
...selection,
root,
diff --git a/config/scripts/build-mobile-web-app-bundle.mjs b/config/scripts/build-mobile-web-app-bundle.mjs
index 4f2d0a32b17..d7ec945614d 100644
--- a/config/scripts/build-mobile-web-app-bundle.mjs
+++ b/config/scripts/build-mobile-web-app-bundle.mjs
@@ -1,6 +1,7 @@
import { readFile } from 'node:fs/promises'
import { readRouteSnapshot } from './mobile-web-app/mobile-web-app-route-snapshot.mjs'
-import { realpathSync } from 'node:fs'
+import { MOBILE_WEB_APP_DEPENDENCY_PATH } from './mobile-web-app/mobile-web-app-bundle-dependencies.mjs'
+import { existsSync, realpathSync } from 'node:fs'
import { basename, extname, join, resolve } from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
@@ -503,6 +504,12 @@ export async function buildMobileWebAppBundle({
}
if (isDirectInvocation(import.meta.url, process.argv[1])) {
+ if (!existsSync(MOBILE_WEB_APP_DEPENDENCY_PATH)) {
+ console.error(
+ '[build-mobile-web-app-bundle] mobile/ dependencies are not installed; run `pnpm -C mobile install --frozen-lockfile`'
+ )
+ process.exit(1)
+ }
try {
const { manifest, outDir, routeKeys, entryStaticBytes, chunkCount } =
await buildMobileWebAppBundle()
diff --git a/config/scripts/check-changed-code-quality.mjs b/config/scripts/check-changed-code-quality.mjs
index 207cf7ae389..2c2e41226a7 100644
--- a/config/scripts/check-changed-code-quality.mjs
+++ b/config/scripts/check-changed-code-quality.mjs
@@ -193,6 +193,7 @@ export function collectAddedLineRanges(
const source = renamedSources.get(file)
const paths = source ? [source, file] : [file]
const diff = runGit(root, [
+ '--literal-pathspecs',
'diff',
'--find-renames',
'--unified=0',
diff --git a/config/scripts/check-changed-code-quality.test.mjs b/config/scripts/check-changed-code-quality.test.mjs
index 9db417b8c7a..4c8de51f930 100644
--- a/config/scripts/check-changed-code-quality.test.mjs
+++ b/config/scripts/check-changed-code-quality.test.mjs
@@ -70,6 +70,42 @@ describe('changed-code quality line matching', () => {
).toBe(true)
})
+ it.each(['edit', 'rename'])('treats bracketed filenames literally after %s', (change) => {
+ const repo = mkdtempSync(path.join(tmpdir(), 'changed-code-quality-literal-'))
+ try {
+ const hooks = `core.hooksPath=${path.join(repo, '.git', 'no-hooks')}`
+ const git = (...args) => {
+ const result = runProcessSync({
+ program: 'git',
+ args: ['-c', 'commit.gpgsign=false', '-c', hooks, ...args],
+ cwd: repo
+ })
+ expect(result.code, result.stderr).toBe(0)
+ return result.stdout.trim()
+ }
+ git('init', '--quiet')
+ const file = '[cd].ts'
+ const source = change === 'rename' ? '[ab].ts' : file
+ const content = 'export const first = 1\n\nexport const legacy = 3\n'
+ writeFileSync(path.join(repo, source), content)
+ writeFileSync(path.join(repo, 'c.ts'), content)
+ git('add', '.')
+ git('-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', 'base')
+ const base = git('rev-parse', 'HEAD')
+ if (change === 'rename') {
+ git('mv', source, file)
+ }
+ writeFileSync(path.join(repo, file), content.replace('first = 1', 'first = 2'))
+ writeFileSync(path.join(repo, 'c.ts'), content.replace('legacy = 3', 'legacy = 4'))
+
+ const { rangesByFile } = collectAddedLineRanges(repo, base)
+ expect(rangesByFile.get(file)).toEqual([{ start: 1, end: 1 }])
+ expect(rangesByFile.get('c.ts')).toEqual([{ start: 3, end: 3 }])
+ } finally {
+ rmSync(repo, { recursive: true, force: true })
+ }
+ })
+
it('discovers nested rule overrides while retaining root diagnostics', () => {
const root = path.resolve(import.meta.dirname, '..', '..')
const directory = mkdtempSync(path.join(root, 'config', 'changed-code-quality-nested-'))
diff --git a/config/scripts/check-readme-local-links.mjs b/config/scripts/check-readme-local-links.mjs
index 4781adcc5da..5d16461b236 100644
--- a/config/scripts/check-readme-local-links.mjs
+++ b/config/scripts/check-readme-local-links.mjs
@@ -7,7 +7,7 @@ import { pathToFileURL } from 'node:url'
// Docs-only CI skips some media owners; check index paths because GitHub cannot render uncommitted docs-site/feature-wall assets.
const TRANSLATED_README_DIR = path.join('docs', 'readme')
const EXTERNAL_TARGET = /^(?:[a-z][a-z0-9+.-]*:|#|\/\/)/i
-const HTML_ATTRIBUTE = /\b(?:src|srcset|href)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
+const HTML_ATTRIBUTE = /\b(src|srcset|href)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
const MARKDOWN_LINK = /!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g
function readmeFiles(root) {
@@ -32,10 +32,14 @@ function trackedFiles(root, candidates) {
}
function* localTargets(markdown) {
- for (const match of markdown.matchAll(HTML_ATTRIBUTE)) {
- // srcset lists candidates; each begins with its URL.
- for (const candidate of (match[1] ?? match[2]).split(',')) {
- const target = candidate.trim().split(/\s+/)[0]
+ for (const [, attribute, doubleQuoted, singleQuoted] of markdown.matchAll(HTML_ATTRIBUTE)) {
+ const value = doubleQuoted ?? singleQuoted
+ // Only srcset lists candidates; each begins with its URL. src/href hold one whole URL.
+ const targets =
+ attribute === 'srcset'
+ ? value.split(',').map((candidate) => candidate.trim().split(/\s+/)[0])
+ : [value.trim()]
+ for (const target of targets) {
if (target) {
yield target
}
diff --git a/config/scripts/check-readme-local-links.test.mjs b/config/scripts/check-readme-local-links.test.mjs
index bbdbceb0529..54e5f5956b6 100644
--- a/config/scripts/check-readme-local-links.test.mjs
+++ b/config/scripts/check-readme-local-links.test.mjs
@@ -44,7 +44,9 @@ const validReadmes = {
" ",
' ',
'[Contributing](.github/CONTRIBUTING.md) [Docs](https://example.com/docs) [Top](#top)',
- ''
+ '',
+ // src/href hold one URL; only srcset is a comma-separated list.
+ ' Docs '
].join('\n'),
'docs/readme/README.ja.md': [
' ',
@@ -56,6 +58,7 @@ const validReadmes = {
'resources/onboarding/feature-wall/tile-01.poster.jpg': 'jpg',
'docs/site/public/docs/tab-split.gif': 'gif',
'docs/assets/hero image.jpg': 'jpg',
+ 'docs/assets/hero image,wide.jpg': 'jpg',
'.github/CONTRIBUTING.md': 'contributing',
LICENSE: 'mit'
}
@@ -77,6 +80,38 @@ describe('README local link check', () => {
expect(findBrokenReadmeLinks(makeFixture(validReadmes))).toEqual([])
})
+ it('rejects a missing full URL even when its split fragments are tracked', () => {
+ const root = makeFixture({
+ ...validReadmes,
+ 'README.md': ' ',
+ 'docs/assets/missing': 'fragment',
+ 'wide.jpg': 'fragment'
+ })
+
+ expect(findBrokenReadmeLinks(root)).toEqual([
+ {
+ readme: 'README.md',
+ target: 'docs/assets/missing image,wide.jpg',
+ resolved: 'docs/assets/missing image,wide.jpg'
+ }
+ ])
+ })
+
+ it('continues checking each srcset candidate without its descriptor', () => {
+ const root = makeFixture({
+ ...validReadmes,
+ 'README.md': ''
+ })
+
+ expect(findBrokenReadmeLinks(root)).toEqual([
+ {
+ readme: 'README.md',
+ target: 'docs/assets/missing.png',
+ resolved: 'docs/assets/missing.png'
+ }
+ ])
+ })
+
it('checks tracked media outside the detector sparse checkout', () => {
const root = makeFixture(validReadmes)
const workflow = parse(readFileSync(path.join(projectDir, '.github/workflows/pr.yml'), 'utf8'))
diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json
index 6a1ff73cde9..82e17cd905e 100644
--- a/config/scripts/ci-shard-timings.json
+++ b/config/scripts/ci-shard-timings.json
@@ -6213,7 +6213,6 @@
"src/main/skills/skill-remote-install-service.test.ts": 120,
"src/main/skills/skill-remove-transaction.test.ts": 439,
"src/main/skills/skill-root-file-walk.test.ts": 46,
- "src/main/skills/skill-runtime-capability.test.ts": 76,
"src/main/skills/skill-scan-coalescer.test.ts": 58,
"src/main/skills/skill-share-package-name.test.ts": 358,
"src/main/skills/skill-share-preparation-service.test.ts": 343,
@@ -12496,14 +12495,14 @@
"src/shared/native-chat/input/native-chat-slash-commands.omp.test.ts": 54,
"src/shared/native-chat/input/native-chat-slash-commands.test.ts": 52,
"src/shared/native-chat-stopped-send-turn.test.ts": 278,
- "src/shared/native-chat-subagent-items.test.ts": 167,
- "src/shared/native-chat-subagent-summary.test.ts": 45,
+ "src/shared/native-chat/transcript/native-chat-subagent-items.test.ts": 167,
+ "src/shared/native-chat/transcript/native-chat-subagent-summary.test.ts": 45,
"src/shared/native-chat/input/native-chat-task-list-history.test.ts": 58,
"src/shared/native-chat/input/native-chat-task-list.test.ts": 41,
"src/shared/native-chat/transcript/native-chat-text-reveal.test.ts": 27,
"src/shared/native-chat-transcript-contracts.test.ts": 591,
"src/shared/native-chat-transcript-projection.test.ts": 134,
- "src/shared/native-chat-transcript-retention.test.ts": 55,
+ "src/shared/native-chat/transcript/native-chat-transcript-retention.test.ts": 55,
"src/shared/native-chat/transcript/native-chat-turn-activity.test.ts": 137,
"src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 120,
"src/shared/native-chat-turn-membership.test.ts": 174,
diff --git a/config/scripts/locale-ko-key-overrides.json b/config/scripts/locale-ko-key-overrides.json
index 467a38ffec4..5a6f18751bb 100644
--- a/config/scripts/locale-ko-key-overrides.json
+++ b/config/scripts/locale-ko-key-overrides.json
@@ -4337,9 +4337,6 @@
"dashboardPopout.card.you": {
"ko": "나"
},
- "dashboardPopout.terminal.closed": {
- "ko": "실시간 터미널이 없습니다 — 이 에이전트의 창이 닫혔습니다."
- },
"dashboardPopout.terminal.focusWorktree": {
"ko": "워크트리 열기"
},
diff --git a/config/scripts/mobile-web-app/mobile-web-app-bundle-dependencies.mjs b/config/scripts/mobile-web-app/mobile-web-app-bundle-dependencies.mjs
index 36465dbfa1b..4d6dd232805 100644
--- a/config/scripts/mobile-web-app/mobile-web-app-bundle-dependencies.mjs
+++ b/config/scripts/mobile-web-app/mobile-web-app-bundle-dependencies.mjs
@@ -7,14 +7,19 @@ const projectDir = fileURLToPath(new URL('../../..', import.meta.url))
// Mobile CI requires dependencies so broken installs fail instead of silently skipping their tests.
export const MOBILE_WEB_APP_DEPENDENCIES_REQUIRED_ENV = 'ORCA_MOBILE_WEB_APP_DEPS_REQUIRED'
+export const MOBILE_WEB_APP_DEPENDENCY_PATH = join(
+ projectDir,
+ 'mobile',
+ 'node_modules',
+ 'react-native-web'
+)
+
const SKIP_NOTICE =
'[mobile-web-app] skipping the bundling tests: mobile/node_modules/react-native-web is absent. ' +
'They run for real in pr.yml, in the mobile_web_app job, which installs mobile dependencies.'
// Sharded root tests omit mobile/node_modules; check availability before bundling react-native-web pages.
-export function mobileWebAppDependenciesPresent(
- modulePath = join(projectDir, 'mobile', 'node_modules', 'react-native-web')
-) {
+export function mobileWebAppDependenciesPresent(modulePath = MOBILE_WEB_APP_DEPENDENCY_PATH) {
if (existsSync(modulePath)) {
return true
}
diff --git a/config/scripts/pr-auxiliary-preflight-admission.test.mjs b/config/scripts/pr-auxiliary-preflight-admission.test.mjs
index f516e8b4bd9..872e282a710 100644
--- a/config/scripts/pr-auxiliary-preflight-admission.test.mjs
+++ b/config/scripts/pr-auxiliary-preflight-admission.test.mjs
@@ -388,6 +388,7 @@ function createMobileCiScopeRepository(
'config/scripts/git-pull-request-diff-base.mjs',
'config/scripts/pr-e2e-source-routing.mjs',
'config/scripts/pr-browser-e2e-source-routes.mjs',
+ 'config/scripts/pr-editor-preview-e2e-source-routes.mjs',
'config/scripts/ci-e2e-job-selection.mjs'
]) {
mkdirSync(dirname(join(directory, file)), { recursive: true })
diff --git a/config/scripts/pr-e2e-route-contracts.test.mjs b/config/scripts/pr-e2e-route-contracts.test.mjs
index 117600fba1c..554ba60e2a5 100644
--- a/config/scripts/pr-e2e-route-contracts.test.mjs
+++ b/config/scripts/pr-e2e-route-contracts.test.mjs
@@ -503,6 +503,21 @@ function selectsManagedSshLane(file) {
return selectPrE2eSpecs([file]).some((spec) => spec.startsWith(MANAGED_SSH_E2E_SPEC_PREFIX))
}
+describe('wsl-host remove routing', () => {
+ it('runs the fake transport spec, which covers Remove, for a remove-path change', () => {
+ for (const file of [
+ 'src/main/wsl/wsl-host-server-stop.ts',
+ 'src/main/wsl/wsl-host-peer-desktops.ts',
+ 'src/main/wsl/wsl-host-removal.ts'
+ ]) {
+ expect(selectPrE2eSpecs([file]), file).toContain('tests/e2e/wsl-host-fake-transport.spec.ts')
+ }
+ expect(selectPrE2eSpecs(['src/main/wsl/wsl-host-server-stop.test.ts'])).not.toContain(
+ 'tests/e2e/wsl-host-fake-transport.spec.ts'
+ )
+ })
+})
+
describe('wsl-host fake connector routing', () => {
it('runs both WSL host specs for a fake connector change', () => {
const specs = selectPrE2eSpecs(['src/main/wsl/wsl-host-e2e-fake-connector.ts'])
diff --git a/config/scripts/pr-e2e-source-routing.mjs b/config/scripts/pr-e2e-source-routing.mjs
index ab191df0ab0..d1977d35202 100644
--- a/config/scripts/pr-e2e-source-routing.mjs
+++ b/config/scripts/pr-e2e-source-routing.mjs
@@ -8,6 +8,7 @@ import {
import { MANAGED_SSH_E2E_SPEC_PREFIX } from './ci-e2e-job-selection.mjs'
import { LAYOUT_ORACLE_E2E_SPECS } from './pr-layout-oracle-route.mjs'
import { PR_BROWSER_E2E_SOURCE_ROUTES } from './pr-browser-e2e-source-routes.mjs'
+import { PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES } from './pr-editor-preview-e2e-source-routes.mjs'
const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file)
@@ -35,6 +36,7 @@ const ENABLED_AUTOMATION_MOVE =
export const PR_E2E_SOURCE_ROUTES = [
...PR_BROWSER_E2E_SOURCE_ROUTES,
+ ...PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES,
{
id: 'ssh.orcad-editor-ownership',
specs: ['tests/e2e/ssh-orcad-editor-ownership.spec.ts'],
@@ -397,6 +399,15 @@ export const PR_E2E_SOURCE_ROUTES = [
specs: ['tests/e2e/wsl-host-fake-transport.spec.ts', 'tests/e2e/wsl-host-chat.spec.ts'],
matches: (file) => file === 'src/main/wsl/wsl-host-e2e-fake-connector.ts'
},
+ {
+ // Remove runs through the fake transport spec; its peer check asks the server who else uses it.
+ id: 'wsl-host.remove',
+ specs: ['tests/e2e/wsl-host-fake-transport.spec.ts'],
+ matches: (file) =>
+ /^src\/main\/wsl\/(?:wsl-host-server-stop|wsl-host-peer-desktops|wsl-host-removal)\.ts$/.test(
+ file
+ )
+ },
{
id: 'terminal.windows-wsl-launch-and-paste',
specs: [
diff --git a/config/scripts/pr-editor-preview-e2e-source-routes.mjs b/config/scripts/pr-editor-preview-e2e-source-routes.mjs
new file mode 100644
index 00000000000..902a528b92f
--- /dev/null
+++ b/config/scripts/pr-editor-preview-e2e-source-routes.mjs
@@ -0,0 +1,35 @@
+import { isUnitTestSupportSource } from './pr-code-change-scope.mjs'
+
+const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file)
+
+export const PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES = [
+ {
+ // Image, PDF and media viewers read orca-media grants; the PDF reloads exercise remint and range reads.
+ id: 'editor.byte-range-preview',
+ specs: [
+ 'tests/e2e/editor-media-playback-position.spec.ts',
+ 'tests/e2e/media-preview-partition-isolation.spec.ts',
+ 'tests/e2e/paired-remote-large-file-open.spec.ts',
+ 'tests/e2e/pdf-find-counter.spec.ts',
+ 'tests/e2e/pdf-viewer-rebuild-recovery.spec.ts',
+ 'tests/e2e/pdf-viewer-reload-cleanup.spec.ts'
+ ],
+ matches: (file) =>
+ isProductSource(file) &&
+ (/^src\/main\/media\/[^/]+\.ts$/.test(file) ||
+ /^src\/renderer\/src\/components\/editor\/(?:ImageViewer|PdfViewer|pdf-document-loader|pdf-js-document-options|pdf-orca-media-range-transport)\.tsx?$/.test(
+ file
+ ) ||
+ /^src\/renderer\/src\/components\/editor\/(?:EditorEditFileSurface|EditorConflictReviewSurface)\.tsx$/.test(
+ file
+ ) ||
+ [
+ 'src/main/ipc/filesystem/filesystem-read-handlers.ts',
+ 'src/main/startup/privileged-custom-schemes.ts',
+ 'src/preload/api/fs-bridge.ts',
+ 'src/renderer/src/runtime/runtime-file-range-preview.ts',
+ 'src/renderer/src/runtime/runtime-file-read-client.ts',
+ 'src/shared/file-preview-kind.ts'
+ ].includes(file))
+ }
+]
diff --git a/config/scripts/run-e2e-typecheck.mjs b/config/scripts/run-e2e-typecheck.mjs
index 36ef063862b..c9f0195e862 100644
--- a/config/scripts/run-e2e-typecheck.mjs
+++ b/config/scripts/run-e2e-typecheck.mjs
@@ -1,9 +1,9 @@
import { availableParallelism } from 'node:os'
import { runProcessSync } from '@orca/process-host'
-import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
import { describeProcessFailure } from './process-failure-message.mjs'
import { isDirectInvocation } from './script-entry-detection.mjs'
import {
+ resolveTypecheckBunExecutable,
resolveTypecheckCommand,
selectTypecheckCompiler
} from './run-typecheck-projects-in-parallel.mjs'
@@ -14,7 +14,7 @@ export function runE2eTypecheck({
root = process.cwd(),
compiler = 'bun',
execute = runProcessSync,
- resolveBunExecutable = (directory) => resolvePinnedBunExecutable(directory, runProcessSync)
+ resolveBunExecutable = resolveTypecheckBunExecutable
} = {}) {
const selection = selectTypecheckCompiler(compiler, { root, resolveBunExecutable })
const command = resolveTypecheckCommand(CONFIG, {
diff --git a/config/scripts/run-typecheck-projects-in-parallel.mjs b/config/scripts/run-typecheck-projects-in-parallel.mjs
index 7811c5eceb8..9188ecdf7d1 100644
--- a/config/scripts/run-typecheck-projects-in-parallel.mjs
+++ b/config/scripts/run-typecheck-projects-in-parallel.mjs
@@ -119,9 +119,36 @@ export function parseTypecheckOptions(args) {
return options
}
+const NATIVE_COMPILER_HINT = 'pass --compiler=native'
+
+const recoveryAdvice = (action, fallbackHint) =>
+ fallbackHint ? `${action}, or ${fallbackHint}.` : `${action}.`
+
+export function resolveTypecheckBunExecutable(root, fallbackHint, execute = runProcessSync) {
+ let timeoutMessage
+ const executable = resolvePinnedBunExecutable(root, (options) => {
+ const result = execute(options)
+ if (result.timedOut) {
+ timeoutMessage = `Bun version probe timed out after ${options.timeoutMs} ms: ${options.program}. ${recoveryAdvice('Retry when the host is less busy', fallbackHint)}`
+ }
+ return result
+ })
+ // Optional Bun callers still fall back; required typechecks must explain a timeout.
+ if (timeoutMessage) {
+ throw new Error(timeoutMessage)
+ }
+ return executable
+}
+
export function selectTypecheckCompiler(
compiler,
- { root, resolveBunExecutable, platform = process.platform, arch = process.arch }
+ {
+ root,
+ resolveBunExecutable,
+ fallbackHint = NATIVE_COMPILER_HINT,
+ platform = process.platform,
+ arch = process.arch
+ }
) {
if (compiler === 'auto') {
compiler = supportsTsrs(platform, arch) ? 'tsrs' : 'bun'
@@ -132,10 +159,10 @@ export function selectTypecheckCompiler(
if (compiler === 'native' || compiler === 'tsrs') {
return { compiler }
}
- const bunExecutable = resolveBunExecutable(root)
+ const bunExecutable = resolveBunExecutable(root, fallbackHint)
if (!bunExecutable) {
throw new Error(
- `Bun ${readPinnedBunVersion(root)} from devDependencies is missing; run pnpm install, or pass --compiler=native.`
+ `Bun ${readPinnedBunVersion(root)} from devDependencies is missing; ${recoveryAdvice('run pnpm install', fallbackHint)}`
)
}
return { compiler, bunExecutable }
@@ -283,7 +310,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
const options = parseTypecheckOptions(process.argv.slice(2))
const selection = selectTypecheckCompiler(options.compiler, {
root: repoRoot,
- resolveBunExecutable: (root) => resolvePinnedBunExecutable(root, runProcessSync)
+ resolveBunExecutable: resolveTypecheckBunExecutable
})
const failures = await runTypecheckProjects({ ...options, ...selection })
if (failures.length > 0) {
diff --git a/config/scripts/run-typecheck-projects-in-parallel.test.mjs b/config/scripts/run-typecheck-projects-in-parallel.test.mjs
index c9d866c3f98..d0b96fb2527 100644
--- a/config/scripts/run-typecheck-projects-in-parallel.test.mjs
+++ b/config/scripts/run-typecheck-projects-in-parallel.test.mjs
@@ -12,12 +12,14 @@ import { tmpdir } from 'node:os'
import { join, relative, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
+import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
import {
MOBILE_TYPECHECK_PROJECTS,
TYPECHECK_PROJECTS,
admissibleHeapGib,
planTypecheckBatches,
resolveProjectCompiler,
+ resolveTypecheckBunExecutable,
resolveTypecheckCommand,
parseTypecheckOptions,
selectTypecheckCompiler,
@@ -215,6 +217,38 @@ describe('local and CI compiler selection', () => {
).toThrow('run pnpm install')
})
+ it('reports a timed-out installed Bun probe without changing optional fallback', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-bun-probe-')))
+ try {
+ const manifest = join(root, 'node_modules', 'bun')
+ mkdirSync(manifest, { recursive: true })
+ mkdirSync(join(root, 'config'))
+ writeFileSync(join(root, 'package.json'), '{}')
+ writeFileSync(join(root, 'config', '.bun-version'), '1.4.4')
+ writeFileSync(join(manifest, 'package.json'), JSON.stringify({ bin: { bun: 'bin/bun' } }))
+ const execute = () => ({ code: null, signal: 'SIGTERM', stdout: '', timedOut: true })
+ expect(resolvePinnedBunExecutable(root, execute)).toBeNull()
+ expect(() =>
+ selectTypecheckCompiler('bun', {
+ root,
+ resolveBunExecutable: (directory, hint) =>
+ resolveTypecheckBunExecutable(directory, hint, execute)
+ })
+ ).toThrow(/Bun version probe timed out after 2000 ms: .*or pass --compiler=native\./)
+ expect(() => resolveTypecheckBunExecutable(root, null, execute)).toThrow(
+ /Retry when the host is less busy\.$/
+ )
+ expect(
+ resolveTypecheckBunExecutable(root, null, () => ({ code: 0, stdout: '1.4.4\n' }))
+ ).toBe(join(manifest, 'bin/bun'))
+ expect(
+ resolveTypecheckBunExecutable(root, null, () => ({ code: 0, stdout: '1.4.3\n' }))
+ ).toBeNull()
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+ })
+
it('never probes Bun when tsc is requested', () => {
expect(
selectTypecheckCompiler('native', {
diff --git a/config/scripts/vitest-node-runtime-files.mjs b/config/scripts/vitest-node-runtime-files.mjs
index 96eeefde245..b819a19094c 100644
--- a/config/scripts/vitest-node-runtime-files.mjs
+++ b/config/scripts/vitest-node-runtime-files.mjs
@@ -94,6 +94,10 @@ const NODE_RUNTIME_INCLUDE = [
'src/**/*.node-pty.test.ts',
'src/**/node-pty-*.test.ts',
'src/**/*.live-shell.test.ts',
+ // These drive live zsh through node-pty and rely on Node's native PTY stream delivery.
+ 'src/main/shell-startup-feature-channel.test.ts',
+ 'src/main/daemon/shell-ready.test.ts',
+ 'src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts',
'src/**/*real-pty*.test.ts',
'src/**/*-native.test.ts',
'src/**/*retention*.test.ts',
diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md
index 4425b0adeea..e5a3213c223 100644
--- a/docs/readme/README.es.md
+++ b/docs/readme/README.es.md
@@ -12,7 +12,7 @@
- English · 中文 · 日本語 · 한국어 · Français · Português · Türkçe
+ English · 中文 · 日本語 · 한국어 · Français · Português · Türkçe · Русский
diff --git a/docs/readme/README.fr.md b/docs/readme/README.fr.md
index fc5347d71a4..42494b58285 100644
--- a/docs/readme/README.fr.md
+++ b/docs/readme/README.fr.md
@@ -12,7 +12,7 @@
- English · 中文 · 日本語 · 한국어 · Español · Português · Türkçe
+ English · 中文 · 日本語 · 한국어 · Español · Português · Türkçe · Русский
diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md
index 12fb5d57e4b..34c06e6f767 100644
--- a/docs/readme/README.ja.md
+++ b/docs/readme/README.ja.md
@@ -12,7 +12,7 @@
- English · 中文 · 한국어 · Español · Français · Português · Türkçe
+ English · 中文 · 한국어 · Español · Français · Português · Türkçe · Русский
diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md
index 8ae14504a9b..c1273c67857 100644
--- a/docs/readme/README.ko.md
+++ b/docs/readme/README.ko.md
@@ -12,7 +12,7 @@
- English · 中文 · 日本語 · Español · Français · Português · Türkçe
+ English · 中文 · 日本語 · Español · Français · Português · Türkçe · Русский
diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md
index ec73f477c0a..4e50b9df263 100644
--- a/docs/readme/README.pt.md
+++ b/docs/readme/README.pt.md
@@ -12,7 +12,7 @@
- English · 中文 · 日本語 · 한국어 · Español · Français · Türkçe
+ English · 中文 · 日本語 · 한국어 · Español · Français · Türkçe · Русский
diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md
new file mode 100644
index 00000000000..7a5d9916d76
--- /dev/null
+++ b/docs/readme/README.ru.md
@@ -0,0 +1,279 @@
+
+ Orca
+
+
+
+
+
+
+
+
+
+
+
+
+ English · 中文 · 日本語 · 한국어 · Español · Français · Português · Türkçe
+
+
+
+ Оркестратор ИИ для тех, кто создаёт в 100 раз больше.
+ Запускайте Codex, ClaudeCode, OpenCode или Pi параллельно — каждый в своём рабочем дереве, все под контролем в одном месте.
+
+
+
+
+
+
+
+
+## Возможности
+
+
+
+
+
+### Мобильное приложение
+
+Следите за агентами и направляйте их работу с телефона — получайте уведомления о завершении задач и отправляйте дополнительные указания откуда угодно.
+
+[App Store для iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK для Android](https://www.onorca.dev/download/android) · [Документация →](https://www.onorca.dev/docs/mobile)
+
+
+
+
+
+
+
+
+
+### Параллельные рабочие деревья
+
+Отправьте один запрос пяти агентам, каждый из которых работает в своём изолированном рабочем дереве Git, — сравните результаты и слейте лучший вариант.
+
+[Документация →](https://www.onorca.dev/docs/model/worktrees)
+
+
+
+
+
+
+
+
+
+### Разделение терминала
+
+Терминалы уровня Ghostty с отрисовкой через WebGL, неограниченным разделением на панели и историей вывода, которая сохраняется после перезапуска.
+
+[Документация →](https://www.onorca.dev/docs/terminal)
+
+
+
+
+
+
+
+
+
+### Режим дизайна
+
+Нажмите на любой элемент интерфейса в настоящем окне Chromium, чтобы отправить его HTML, CSS и снимок соответствующей области экрана прямо в запрос агенту.
+
+[Документация →](https://www.onorca.dev/docs/browser/design-mode)
+
+
+
+
+
+
+
+
+
+### Встроенная поддержка GitHub и Linear
+
+Просматривайте пул-реквесты, задачи и доски проектов прямо в приложении — открывайте рабочее дерево из любой задачи и проверяйте код, не переключая контекст.
+
+[Документация →](https://www.onorca.dev/docs/review/linear)
+
+
+
+
+
+
+
+
+
+### Рабочие деревья по SSH
+
+Запускайте агентов на мощном удалённом сервере с полноценным редактированием файлов, работой с Git и терминалами — автоматическое переподключение и перенаправление портов уже предусмотрены.
+
+[Документация →](https://www.onorca.dev/docs/ssh)
+
+
+
+
+
+
+
+
+
+### Комментарии к изменениям ИИ
+
+Оставляйте комментарии к любой строке в сравнении и отправляйте их агенту — проверяйте и редактируйте код, создавайте коммиты, не выходя из Orca.
+
+[Документация →](https://www.onorca.dev/docs/review/annotate-ai-diff)
+
+
+
+
+
+
+
+
+
+### Перетаскивание файлов в запросы агентов
+
+Редактор VS Code с автоматическим сохранением всех изменений — перетаскивайте файлы или изображения прямо в запрос агенту.
+
+[Документация →](https://www.onorca.dev/docs/editing/file-explorer)
+
+
+
+
+
+
+
+
+
+### Orca CLI
+
+Агенты тоже управляют Orca — автоматизируйте любые рабочие процессы с помощью `orca worktree create`, `snapshot`, `click` и `fill`.
+
+[Документация →](https://www.onorca.dev/docs/cli/overview)
+
+
+
+
+
+
+
+
+**А ещё:**
+
+- **[Быстрое открытие](https://www.onorca.dev/docs/model/quick-open)** — Ищите рабочие деревья, файлы, агентов, команды и контекст репозитория, не прерывая работу.
+- **[Переключение учётных записей и учёт использования](https://www.onorca.dev/docs/agents/usage-tracking)** — Следите за использованием Claude и Codex и временем сброса лимитов, переключайтесь между учётными записями без повторного входа.
+- **[Предпросмотр содержимого репозитория](https://www.onorca.dev/docs/editing/markdown)** — Просматривайте Markdown, изображения, PDF и документацию репозитория прямо в рабочем пространстве.
+- **[Управление компьютером](https://www.onorca.dev/docs/cli/computer-use)** — Позвольте агентам управлять настольными приложениями и видимым интерфейсом, когда задача требует непосредственного взаимодействия.
+- **[Уведомления и статус прочтения](https://www.onorca.dev/docs/notifications)** — Узнавайте, когда агент завершил работу или требует внимания, и отмечайте обсуждения как непрочитанные, чтобы вернуться к ним позже.
+- **И многое, многое другое** — мы выпускаем обновления каждый день, поэтому этот список постоянно отстаёт. Актуальный список возможностей — в [журнале изменений](https://github.com/stablyai/orca/releases).
+
+---
+
+## Поддерживаемые агенты
+
+Работает с **любым CLI-агентом** — если он запускается в терминале, то запустится и в Orca.
+
+
+ Claude Code
+ Codex
+ Grok
+ Cursor
+ GitHub Copilot
+ Muse
+ DeepSeek Harness
+ ZCode
+ OpenCode
+ MiMo Code
+ Amp
+ OpenClaude
+ Antigravity
+ Pi
+ oh-my-pi
+ Hermes Agent
+ Devin
+ Goose
+ Auggie
+ Autohand Code
+ Charm
+ Cline
+ CodeBuddy
+ Codebuff
+ Freebuff
+ Command Code
+ Continue
+ Droid
+ Kilocode
+ Kimi
+ Kiro
+ Mistral Vibe
+ Qwen Code
+ Rovo Dev
+ + любой CLI-агент
+
+
+---
+
+## Установка
+
+### Настольное приложение — macOS, Windows, Linux
+
+- **[Скачать с onOrca.dev](https://onorca.dev/download)**
+- Или скачайте сборку напрямую: [macOS Apple Silicon](https://github.com/stablyai/orca/releases/latest/download/orca-macos-arm64.dmg) · [macOS Intel](https://github.com/stablyai/orca/releases/latest/download/orca-macos-x64.dmg) · [Windows (.exe)](https://github.com/stablyai/orca/releases/latest/download/orca-windows-setup.exe) · [Linux AppImage](https://github.com/stablyai/orca/releases/latest/download/orca-linux.AppImage) · [Все сборки](https://github.com/stablyai/orca/releases/latest)
+
+_Или через менеджер пакетов:_
+
+```bash
+# macOS (Homebrew)
+# Always use the full name; bare `orca` is an unrelated Plotly cask.
+brew install --cask stablyai/orca/orca
+# Upgrade an existing install
+brew upgrade --cask stablyai/orca/orca
+
+# Arch Linux (AUR) — or stably-orca-git to build from source
+yay -S stably-orca-bin
+```
+
+### Мобильное приложение — iOS, Android
+
+Подключите его к настольному приложению, чтобы следить за агентами и направлять их работу с телефона.
+
+- **iOS:** [Скачать в App Store](https://apps.apple.com/us/app/orca-ide/id6766130217)
+- **Android:** [Скачать APK](https://www.onorca.dev/download/android) · [Руководство по установке](https://www.onorca.dev/docs/android-apk)
+
+---
+
+## Сообщество и поддержка
+
+- **Discord:** Присоединяйтесь к сообществу в **[Discord](https://discord.gg/fzjDKHxv8Q)**.
+- **Twitter / X:** Подпишитесь на **[@orca_build](https://x.com/orca_build)**, чтобы узнавать об обновлениях и анонсах.
+- **WeChat:** Группа № 12 заполнена. Отсканируйте QR-код, чтобы присоединиться к группе № 13 сообщества Orca в WeChat.
+
+
+
+- **Отзывы и идеи:** Мы быстро выпускаем обновления. Чего-то не хватает? [Предложите новую возможность](https://github.com/stablyai/orca/issues).
+- **Конфиденциальность:** В [документации о конфиденциальности и телеметрии](https://www.onorca.dev/docs/telemetry) описано, какие анонимные данные об использовании собирает Orca и как отказаться от их сбора.
+- **Поддержите проект:** Отметьте этот репозиторий [звездой](https://github.com/stablyai/orca), чтобы следить за нашими ежедневными выпусками.
+
+---
+
+## Разработка
+
+Хотите внести вклад в проект или запустить его локально? Загляните в наше руководство [CONTRIBUTING.md](../../.github/CONTRIBUTING.md).
+
+Сервис-посредник для подключения мобильного приложения к компьютеру тоже находится в этом репозитории —
+в [`cloud/`](../../cloud/README.md), с отдельным рабочим пространством pnpm и руководством по настройке.
+
+
+
+
+
+
+
+
+
+## Подписанные сборки
+
+Подписание кода для Windows спонсирует и обеспечивает [SignPath.io](https://signpath.io), сертификат предоставляет [SignPath Foundation](https://signpath.org).
+
+## Лицензия
+
+Orca — бесплатное ПО с открытым исходным кодом под [лицензией MIT](../../LICENSE).
diff --git a/docs/readme/README.tr.md b/docs/readme/README.tr.md
index 5ea6fac3a99..5edeeee5a7f 100644
--- a/docs/readme/README.tr.md
+++ b/docs/readme/README.tr.md
@@ -12,7 +12,7 @@
- English · 中文 · 日本語 · 한국어 · Español · Français · Português
+ English · 中文 · 日本語 · 한국어 · Español · Français · Português · Русский
@@ -190,7 +190,7 @@ Orca'yı ajanlar da kullanır - her akışı `orca worktree create`, `snapshot`,
oh-my-pi
Hermes Agent
Devin
- Goose
+ Goose
Auggie
Autohand Code
Charm
@@ -199,7 +199,7 @@ Orca'yı ajanlar da kullanır - her akışı `orca worktree create`, `snapshot`,
Codebuff
Freebuff
Command Code
- Continue
+ Continue
Droid
Kilocode
Kimi
diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md
index 0bbc7f681d1..08c74ef281d 100644
--- a/docs/readme/README.zh-CN.md
+++ b/docs/readme/README.zh-CN.md
@@ -12,7 +12,7 @@
- English · 日本語 · 한국어 · Español · Français · Português · Türkçe
+ English · 日本語 · 한국어 · Español · Français · Português · Türkçe · Русский
diff --git a/docs/site/content/docs/cli/orchestration.mdx b/docs/site/content/docs/cli/orchestration.mdx
index 88355cb8c82..47725eeda8e 100644
--- a/docs/site/content/docs/cli/orchestration.mdx
+++ b/docs/site/content/docs/cli/orchestration.mdx
@@ -114,7 +114,7 @@ orca orchestration dispatch --task --to --inject --json
## Messaging notes
- Default `check` is the bound Run's oldest unacked Delivery (FIFO). Replay until `--ack`.
-- `--peek` / `--all` do not consume mail.
+- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check --ack ` until `deliveryId` is `null`.
- Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:` — never for `worker_done` / heartbeat.
- Every group except `@worktree:` means the live Dispatches of the sender's own Run, delivered to their Dispatch mailboxes (or child Run mailboxes for nested coordinators). A sender in no Run is refused; `--run` must match the audience and never grants membership.
- Run groups exclude their owning coordinator. A worker raising a blocker sends to `run:`. `@worktree:` includes coordinators in that workspace.
diff --git a/docs/site/content/docs/cli/reference.mdx b/docs/site/content/docs/cli/reference.mdx
index c58df5bd9eb..b22528d6c76 100644
--- a/docs/site/content/docs/cli/reference.mdx
+++ b/docs/site/content/docs/cli/reference.mdx
@@ -105,6 +105,8 @@ orca worktree rm --worktree id: --force --json
When `worktree create` runs from inside an Orca-managed worktree, Orca records the new worktree as a child when it can infer the relationship. Pass `--parent-worktree active` to be explicit, or `--no-parent` when the new work is independent.
+Pass `--branch DAT-111-fix-login` to name the Git branch yourself instead of applying the configured branch prefix. `--name` still sets the workspace name and `--base-branch` the starting ref. If that branch already exists and cannot be reused, or the workspace path is already taken, Orca appends a numeric suffix to both, as it does in the new-workspace composer, so `--name task --branch exact` can produce branch `exact-2` even when `exact` is free.
+
`worktree set --unread` puts the unread dot on the workspace in the sidebar, the same one Orca shows when an agent finishes; `--read` clears it.
Agent startup flags:
diff --git a/docs/site/content/docs/settings.mdx b/docs/site/content/docs/settings.mdx
index 28d6ecaa8a5..99952825bcd 100644
--- a/docs/site/content/docs/settings.mdx
+++ b/docs/site/content/docs/settings.mdx
@@ -28,7 +28,7 @@ Settings are grouped into panes. Everything here is searchable with `Cmd-,` then
- Status bar toggles, including **Resource Manager** (CPU/memory/sessions, daemon controls, workspace disk scans).
- **Usage percentages** — show provider limits as **% used** or **% remaining** on the status-bar roster.
- App Icon — cycle between Classic, Watercolor, and Blue for the icon shown in the Dock and window switcher.
-- **Language** — primary Interface control. Switch between System (follows the OS), English, 中文(简体), 繁體中文(台灣), 한국어, 日本語, Español, Français, Português (Brasil), Русский, or Türkçe. Settings search also matches native words for “language” (语言 / 語言 / 언어 / 言語 / Idioma / Langue / Язык / Dil) so you can find Language while the UI is still in English.
+- **Language** — primary Interface control. Switch between System (follows the OS), English, 中文(简体), 繁體中文(台灣), 한국어, 日本語, Español, Français, Português (Brasil), Русский, Türkçe, or Deutsch. Settings search also matches native words for “language” (语言 / 語言 / 언어 / 言語 / Idioma / Langue / Язык / Dil / Sprache) so you can find Language while the UI is still in English.
## Git
diff --git a/docs/site/src/assets/fonts/Geist-Bold.ttf b/docs/site/src/assets/fonts/Geist-Bold.ttf
index 70fe36ea227..ee5bf937abe 100644
Binary files a/docs/site/src/assets/fonts/Geist-Bold.ttf and b/docs/site/src/assets/fonts/Geist-Bold.ttf differ
diff --git a/docs/site/src/assets/fonts/Geist-Regular.ttf b/docs/site/src/assets/fonts/Geist-Regular.ttf
index 53622821cc3..c9319ebe7fd 100644
Binary files a/docs/site/src/assets/fonts/Geist-Regular.ttf and b/docs/site/src/assets/fonts/Geist-Regular.ttf differ
diff --git a/docs/site/src/assets/fonts/Geist-Variable.woff2 b/docs/site/src/assets/fonts/Geist-Variable.woff2
index b2f01210625..09082f6db07 100644
Binary files a/docs/site/src/assets/fonts/Geist-Variable.woff2 and b/docs/site/src/assets/fonts/Geist-Variable.woff2 differ
diff --git a/mobile/packages/expo-two-way-audio/ios/AudioEngine.swift b/mobile/packages/expo-two-way-audio/ios/AudioEngine.swift
index 8153bd0a3b9..2e85bf06ddc 100644
--- a/mobile/packages/expo-two-way-audio/ios/AudioEngine.swift
+++ b/mobile/packages/expo-two-way-audio/ios/AudioEngine.swift
@@ -63,7 +63,13 @@ class AudioEngine {
}
self.setupAudioSession()
- self.setup()
+ do {
+ try self.setup()
+ } catch {
+ // Hand the session back so a failed initialize leaves no other app's audio ducked.
+ tearDown()
+ throw error
+ }
self.start()
}
@@ -101,14 +107,10 @@ class AudioEngine {
}
}
- func setup() {
+ func setup() throws {
let input = avAudioEngine.inputNode
- do {
- try input.setVoiceProcessingEnabled(true)
- } catch {
- print("Could not enable voice processing \(error)")
- return
- }
+ // Throw rather than return: an engine with no mic tap would report recording and capture nothing.
+ try input.setVoiceProcessingEnabled(true)
avAudioEngine.inputNode.isVoiceProcessingInputMuted = !isRecording
@@ -269,7 +271,7 @@ class AudioEngine {
func stopRecordingAndPlayer(clearInterruptionResume: Bool = true){
do {
- try AVAudioSession.sharedInstance().setActive(false)
+ try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
print("Could not set the audio session to inactive: \(error)")
}
@@ -288,8 +290,9 @@ class AudioEngine {
func tearDown() {
guard !isTornDown else { return }
isTornDown = true
- stopRecordingAndPlayer()
+ // Stop I/O first; deactivating a session with running I/O returns a busy error.
avAudioEngine.stop()
+ stopRecordingAndPlayer()
}
var isPlaying: Bool {
@@ -355,7 +358,14 @@ class AudioEngine {
private func handleMediaServicesWereReset() {
guard !isTornDown else { return }
self.avAudioEngine.stop()
- self.setup()
+ do {
+ try self.setup()
+ } catch {
+ print("Could not rebuild the audio engine: \(error)")
+ tearDown()
+ onAudioInterruptionCallback?("blocked")
+ return
+ }
self.start()
}
diff --git a/mobile/scripts/check-tests-typecheck-incremental-cache.test.ts b/mobile/scripts/check-tests-typecheck-incremental-cache.test.ts
index 3e739392033..8b801c0032e 100644
--- a/mobile/scripts/check-tests-typecheck-incremental-cache.test.ts
+++ b/mobile/scripts/check-tests-typecheck-incremental-cache.test.ts
@@ -44,7 +44,7 @@ it.each([
const source = "import type { Shape } from './model'; const shape: Shape = { value: 1 }"
writeFileSync(test, source)
const clean = collectTypecheckPass(root)
- expect(clean).toEqual({ failing: [], programTestFiles: ['value.test.ts'] })
+ expect(clean).toEqual({ failing: [], diagnostics: [], programTestFiles: ['value.test.ts'] })
if (buildInfo) {
expect(existsSync(buildInfo)).toBe(true)
}
@@ -54,6 +54,9 @@ it.each([
writeFileSync(join(root, 'model.ts'), 'export interface Shape { value: string }')
const failed = collectTypecheckPass(root)
expect(failed.failing).toEqual(['value.test.ts'])
+ expect(failed.diagnostics).toEqual([
+ expect.stringMatching(/^value\.test\.ts\(1,\d+\): error TS2322:/)
+ ])
expect(collectTypecheckPass(root)).toEqual(failed)
writeFileSync(join(root, 'new.test.ts'), 'export const value: number = 1')
@@ -64,7 +67,11 @@ it.each([
expect(findTsNocheckFiles(root, nocheck.programTestFiles)).toEqual(['value.test.ts'])
unlinkSync(test)
- expect(collectTypecheckPass(root)).toEqual({ failing: [], programTestFiles: ['new.test.ts'] })
+ expect(collectTypecheckPass(root)).toEqual({
+ failing: [],
+ diagnostics: [],
+ programTestFiles: ['new.test.ts']
+ })
} finally {
vi.unstubAllEnvs()
removeTreeSync(root)
diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs
index 93972c1a0de..c4da37c5469 100644
--- a/mobile/scripts/check-tests-typecheck-ratchet.mjs
+++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs
@@ -153,6 +153,7 @@ export function collectTypecheckPass(root = process.cwd()) {
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`
return {
failing: parseFailingFiles(output),
+ diagnostics: output.split('\n').filter((line) => ERROR_LINE.test(line)),
programTestFiles: parseProgramTestFiles(output, fs.realpathSync(root))
}
}
@@ -277,6 +278,9 @@ export function main(root = process.cwd()) {
if (added.length > 0) {
printAddedFailure(added)
+ for (const diagnostic of pass.diagnostics) {
+ console.error(diagnostic)
+ }
if (stale.length > 0) {
printStaleFailure(stale)
}
diff --git a/mobile/scripts/check-tests-typecheck-ratchet.test.ts b/mobile/scripts/check-tests-typecheck-ratchet.test.ts
index fd2c33bf307..e8e5ea7704d 100644
--- a/mobile/scripts/check-tests-typecheck-ratchet.test.ts
+++ b/mobile/scripts/check-tests-typecheck-ratchet.test.ts
@@ -1,17 +1,95 @@
+import { runProcessSync } from '@orca/process-host'
import fs from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
-import { describe, expect, it } from 'vitest'
-// Only the pure functions are under test; the tsc spawn is proven end to end by CI.
+import { describe, expect, it, vi } from 'vitest'
+import { removeTreeSync } from '../../src/shared/windows-transient-lock-removal'
import {
diffBaseline,
diffCensus,
hasTsNocheckDirective,
+ main,
parseBaseline,
parseFailingFiles,
parseProgramTestFiles,
TESTS_OUTSIDE_PROGRAM
} from './check-tests-typecheck-ratchet.mjs'
+vi.mock('@orca/process-host', () => ({ runProcessSync: vi.fn() }))
+vi.mock('./mobile-typecheck-compiler.mjs', () => ({
+ resolveMobileTypecheckCommand: (project: string, cwd: string) => ({
+ program: 'compiler',
+ args: ['--project', project],
+ cwd
+ })
+}))
+
+describe('ratchet failure diagnostics', () => {
+ it.each([
+ { name: 'new failure', baseline: '', failed: true, exit: 1, printsDiagnostics: true },
+ { name: 'clean pass', baseline: '', failed: false, exit: 0, printsDiagnostics: false },
+ {
+ name: 'grandfathered failure',
+ baseline: 'src/value.test.ts\n',
+ failed: true,
+ exit: 0,
+ printsDiagnostics: false
+ },
+ {
+ name: 'stale baseline',
+ baseline: 'src/value.test.ts\n',
+ failed: false,
+ exit: 1,
+ printsDiagnostics: false
+ }
+ ])('preserves $name outcome and baseline', ({ baseline, failed, exit, printsDiagnostics }) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orca-pr31180-ratchet-'))
+ const diagnostic = 'src/value.test.ts(1,2): error TS2322: Type number is not assignable.'
+ const stderrDiagnostic = 'src/value.test.ts(2,3): error TS2345: Argument type mismatch.'
+ const detail = ' Type number is not assignable to type string.'
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const logs = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ for (const file of [...TESTS_OUTSIDE_PROGRAM.keys(), 'src/value.test.ts']) {
+ fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true })
+ fs.writeFileSync(path.join(root, file), 'export {}\n')
+ }
+ const baselineFile = path.join(root, 'tests-typecheck-baseline.txt')
+ fs.writeFileSync(baselineFile, baseline)
+ const programFile = path.join(fs.realpathSync(root), 'src/value.test.ts')
+ vi.mocked(runProcessSync).mockReturnValue({
+ code: failed ? 2 : 0,
+ signal: null,
+ timedOut: false,
+ stdout: `${programFile}\n${failed ? `${diagnostic}\n${detail}\n` : ''}`,
+ stderr: failed ? `${stderrDiagnostic}\n` : ''
+ })
+
+ expect(main(root)).toBe(exit)
+ expect(runProcessSync).toHaveBeenCalledExactlyOnceWith({
+ program: 'compiler',
+ args: ['--project', 'tsconfig.test.json', '--listFiles'],
+ cwd: root,
+ timeoutMs: null,
+ maxOutputBytes: 64 * 1024 * 1024
+ })
+ expect(errors.mock.calls.some(([message]) => message === diagnostic)).toBe(printsDiagnostics)
+ expect(errors.mock.calls.some(([message]) => message === stderrDiagnostic)).toBe(
+ printsDiagnostics
+ )
+ expect(
+ errors.mock.calls.some(([message]) => message === detail || message === programFile)
+ ).toBe(false)
+ expect(fs.readFileSync(baselineFile, 'utf8')).toBe(baseline)
+ } finally {
+ vi.mocked(runProcessSync).mockReset()
+ errors.mockRestore()
+ logs.mockRestore()
+ removeTreeSync(root)
+ }
+ })
+})
+
describe('the failing-file parser', () => {
it('names each file once however many errors it carries', () => {
const output = [
diff --git a/mobile/scripts/mobile-typecheck-compiler.mjs b/mobile/scripts/mobile-typecheck-compiler.mjs
index d8dad11cb0b..d4375593b47 100644
--- a/mobile/scripts/mobile-typecheck-compiler.mjs
+++ b/mobile/scripts/mobile-typecheck-compiler.mjs
@@ -1,8 +1,7 @@
-import { runProcessSync } from '@orca/process-host'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { resolvePinnedBunExecutable } from '../../config/scripts/pinned-bun-executable.mjs'
import {
+ resolveTypecheckBunExecutable,
resolveTypecheckCommand,
selectTypecheckCompiler
} from '../../config/scripts/run-typecheck-projects-in-parallel.mjs'
@@ -17,7 +16,8 @@ export function resolveMobileTypecheckCommand(project, cwd = process.cwd()) {
}
const selection = selectTypecheckCompiler(requested, {
root,
- resolveBunExecutable: (repoRoot) => resolvePinnedBunExecutable(repoRoot, runProcessSync)
+ resolveBunExecutable: resolveTypecheckBunExecutable,
+ fallbackHint: 'set ORCA_MOBILE_TYPECHECK_COMPILER=native'
})
const command = resolveTypecheckCommand(resolve(cwd, project), {
...selection,
diff --git a/mobile/src/hooks/mobile-dictation-native-start-failure.test.tsx b/mobile/src/hooks/mobile-dictation-native-start-failure.test.tsx
index 1b7e700ebe3..0b88c61dbf2 100644
--- a/mobile/src/hooks/mobile-dictation-native-start-failure.test.tsx
+++ b/mobile/src/hooks/mobile-dictation-native-start-failure.test.tsx
@@ -124,7 +124,7 @@ describe('a native start the desktop refuses', () => {
await started
})
expect(device.calls).toContain('initialize')
- expect(device.calls).toContain('toggleRecording(false)')
+ expect(device.calls).toContain('tearDown')
// The open capture owns a wake tag; no outer start catch releases it.
expect(device.screen).toEqual(['+', '-'])
expect(dictation().status).toBe('idle')
diff --git a/mobile/src/platform/dictation-capture.test.ts b/mobile/src/platform/dictation-capture.test.ts
index ab671db8113..adfb857b076 100644
--- a/mobile/src/platform/dictation-capture.test.ts
+++ b/mobile/src/platform/dictation-capture.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const engine = vi.hoisted(() => ({
listeners: new Map void>(),
calls: new Array(),
- throwOn: new Set(),
+ tearDownFails: false,
openFails: false,
// Record queued screen-lock calls separately; their microtask order relative to synchronous engine calls is not a contract.
screen: new Array(),
@@ -30,15 +30,12 @@ vi.mock('@orca/expo-two-way-audio', () => ({
},
tearDown: () => {
engine.calls.push('tearDown')
- if (engine.throwOn.has('tearDown')) {
+ if (engine.tearDownFails) {
throw new Error('the audio session would not tear down')
}
},
toggleRecording: (on: boolean) => {
engine.calls.push(`toggleRecording(${String(on)})`)
- if (engine.throwOn.has(`toggleRecording(${String(on)})`)) {
- throw new Error('the audio engine would not stop')
- }
return true
}
}))
@@ -63,7 +60,7 @@ beforeEach(async () => {
await flushScreen()
engine.listeners.clear()
engine.calls.length = 0
- engine.throwOn.clear()
+ engine.tearDownFails = false
engine.openFails = false
engine.screen.length = 0
engine.screenTags.clear()
@@ -100,14 +97,8 @@ describe('the calls the native half makes', () => {
expect(engine.calls).toEqual(['permission', 'initialize'])
expect(capture.begin()).toBe(true)
await capture.end()
- capture.release()
- expect(engine.calls).toEqual([
- 'permission',
- 'initialize',
- 'toggleRecording(true)',
- 'toggleRecording(false)',
- 'tearDown'
- ])
+ // Muting alone would keep the session and leave other apps' audio ducked until unmount.
+ expect(engine.calls).toEqual(['permission', 'initialize', 'toggleRecording(true)', 'tearDown'])
})
it('hands every microphone event over with nothing dropped', () => {
@@ -166,26 +157,9 @@ describe('the screen the native microphone holds awake', () => {
describe('a device whose audio session will not shut down', () => {
it('resolves `end` rather than rejecting it, which the contract promises', async () => {
// Synchronous try cannot catch void end() rejection; swallow/log binding failures inside cleanup to prevent unhandled rejections.
- engine.throwOn.add('toggleRecording(false)')
+ engine.tearDownFails = true
const capture = useDictationCapture()
await expect(capture.end()).resolves.toBeUndefined()
- expect(engine.calls).toEqual(['toggleRecording(false)'])
- })
-
- it('does not throw out of `release`, which runs bare in the unmount path', async () => {
- engine.throwOn.add('tearDown')
- const capture = useDictationCapture()
- expect(() => capture.release()).not.toThrow()
- await Promise.resolve()
expect(engine.calls).toEqual(['tearDown'])
})
-
- it('still stops the engine when the tear-down is the half that fails', async () => {
- engine.throwOn.add('tearDown')
- const capture = useDictationCapture()
- await capture.end()
- capture.release()
- await Promise.resolve()
- expect(engine.calls).toEqual(['toggleRecording(false)', 'tearDown'])
- })
})
diff --git a/mobile/src/platform/dictation-capture.ts b/mobile/src/platform/dictation-capture.ts
index 7fcadf16102..e3ef12486f3 100644
--- a/mobile/src/platform/dictation-capture.ts
+++ b/mobile/src/platform/dictation-capture.ts
@@ -11,6 +11,16 @@ import type { DictationCapture } from './dictation-capture-contract'
const screen = nativeMicrophoneScreenLock
+// Never throw: unmount calls this bare and `end` must not reject, so wake-tag release and desktop cancel still run.
+function releaseMicrophone(): void {
+ screen.release()
+ try {
+ tearDown()
+ } catch (error) {
+ console.error('Failed to tear down the audio session', error)
+ }
+}
+
const nativeDictationCapture: DictationCapture = {
open: async () => {
const permission = await requestMicrophonePermissionsAsync()
@@ -25,24 +35,9 @@ const nativeDictationCapture: DictationCapture = {
return { ok: true }
},
begin: () => toggleRecording(true),
- // Native events already delivered the tail. Catch binding throws inside this async cleanup because void callers’ synchronous try cannot catch rejections.
- end: async () => {
- screen.release()
- try {
- toggleRecording(false)
- } catch (error) {
- console.error('Failed to stop microphone recording', error)
- }
- },
- // Unmount calls release bare; catch failures so wake-tag release and desktop cancel can still run.
- release: () => {
- screen.release()
- try {
- tearDown()
- } catch (error) {
- console.error('Failed to tear down the audio session', error)
- }
- },
+ // Native events already delivered the tail. Tear down, not just mute, so other apps' audio resumes; the next open re-initializes.
+ end: async () => releaseMicrophone(),
+ release: releaseMicrophone,
onChunk: (handler) =>
addExpoTwoWayAudioEventListener('onMicrophoneData', (event) => {
const raw = event.data
diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx
index 411b3131d6e..b005393a341 100644
--- a/mobile/src/session/MobileNativeChatOverlay.tsx
+++ b/mobile/src/session/MobileNativeChatOverlay.tsx
@@ -1,3 +1,4 @@
+import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import { useCallback, useLayoutEffect, useMemo } from 'react'
import { StyleSheet, View } from 'react-native'
import { MobileNativeChatView, type MobileNativeChatInputLockReason } from './MobileNativeChatView'
@@ -121,6 +122,36 @@ export function MobileNativeChatOverlay({
: null,
[itemSource, fullContent.detail, load]
)
+ const queuedComposerContext = useMemo(
+ () => ({
+ agent,
+ structured: structuredComposer ?? null,
+ skillDiscovery: controller.nativeChatSkills,
+ onNeedSkills: controller.loadNativeChatSkills,
+ filePaths: controller.nativeChatFilePaths,
+ onNeedFiles: controller.loadNativeChatFiles,
+ onError: (message: string) => controller.reportQueuedEditError?.(message),
+ onMicPress,
+ micActive,
+ dictationMode,
+ onMicPressIn,
+ onMicPressOut
+ }),
+ [
+ agent,
+ structuredComposer,
+ controller.nativeChatSkills,
+ controller.loadNativeChatSkills,
+ controller.nativeChatFilePaths,
+ controller.loadNativeChatFiles,
+ controller.reportQueuedEditError,
+ onMicPress,
+ micActive,
+ dictationMode,
+ onMicPressIn,
+ onMicPressOut
+ ]
+ )
const noticeNames = useMemo(
() => ({ hostName, ...(agent ? { agentName: tuiAgentDisplayName(agent) ?? agent } : {}) }),
[hostName, agent]
@@ -133,94 +164,97 @@ export function MobileNativeChatOverlay({
conversation={{ surfaceId: sendSurfaceId, sessionId }}
imageClient={controller.nativeChatVisualSource?.client}
>
-
-
-
-
-
- controller.setTabView(activeSessionTabId, 'terminal')
- : undefined
- }
- onCancelAsk={controller.handleNativeChatCancelAsk}
- onCancelPrompt={controller.handleNativeChatCancelPrompt}
- onCollapseAsk={controller.collapseNativeChatAsk}
- onCollapsePrompt={controller.collapseNativeChatPrompt}
- collapsedPrompt={controller.nativeChatCollapsedPrompt}
- question={controller.nativeChatQuestion}
- onAnswerQuestion={controller.handleNativeChatQuestionAnswer}
- permission={controller.nativeChatPermission}
- onRespondPermission={controller.handleNativeChatRespondPermission}
- composerTray={composerTray}
- onOpenFile={onOpenFile}
- hasMore={session.hasMore}
- olderPages={session.olderPages}
- onLoadEarlier={session.loadEarlier}
- onSend={images.sendNativeChat}
- sendSurfaceId={sendSurfaceId}
- getSendCompletionGeneration={getSendCompletionGeneration}
- getComposerEditGeneration={controller.getChatComposerEditGeneration}
- pending={controller.chatPending}
- imagePreviewsByMessageId={controller.chatImagePreviewsByMessageId}
- draftKey={controller.chatDraftKey}
- onComposerTextChange={controller.setChatComposerText}
- onAttachImage={
- controller.nativeChatAcceptsImages
- ? () => void images.attachImage('library')
- : undefined
- }
- attachments={images.attachments}
- onRemoveAttachment={images.removeAttachment}
- isAttaching={images.isAttaching}
- onMicPress={onMicPress}
- micActive={micActive}
- dictationMode={dictationMode}
- onMicPressIn={onMicPressIn}
- onMicPressOut={onMicPressOut}
- inputLockReason={inputLockReason}
- sendErrorMessage={sendErrorMessage}
- onClearSendError={onClearSendError}
- filePaths={controller.nativeChatFilePaths}
- onNeedFiles={controller.loadNativeChatFiles}
- skillDiscovery={controller.nativeChatSkills}
- onNeedSkills={controller.loadNativeChatSkills}
- sessionOptions={controller.nativeChatSessionOptions}
- structuredComposer={structuredComposer}
- keyboardInset={keyboardInset}
- />
-
-
-
-
-
+
+
+
+
+
+
+ controller.setTabView(activeSessionTabId, 'terminal')
+ : undefined
+ }
+ onCancelAsk={controller.handleNativeChatCancelAsk}
+ onCancelPrompt={controller.handleNativeChatCancelPrompt}
+ onCollapseAsk={controller.collapseNativeChatAsk}
+ onCollapsePrompt={controller.collapseNativeChatPrompt}
+ collapsedPrompt={controller.nativeChatCollapsedPrompt}
+ question={controller.nativeChatQuestion}
+ onAnswerQuestion={controller.handleNativeChatQuestionAnswer}
+ permission={controller.nativeChatPermission}
+ onRespondPermission={controller.handleNativeChatRespondPermission}
+ composerTray={composerTray}
+ onOpenFile={onOpenFile}
+ hasMore={session.hasMore}
+ olderPages={session.olderPages}
+ onLoadEarlier={session.loadEarlier}
+ onSend={images.sendNativeChat}
+ sendSurfaceId={sendSurfaceId}
+ getSendCompletionGeneration={getSendCompletionGeneration}
+ getComposerEditGeneration={controller.getChatComposerEditGeneration}
+ pending={controller.chatPending}
+ imagePreviewsByMessageId={controller.chatImagePreviewsByMessageId}
+ composerScopeKey={controller.chatComposerScopeKey}
+ draftKey={controller.chatDraftKey}
+ onComposerTextChange={controller.setChatComposerText}
+ onAttachImage={
+ controller.nativeChatAcceptsImages
+ ? () => void images.attachImage('library')
+ : undefined
+ }
+ attachments={images.attachments}
+ onRemoveAttachment={images.removeAttachment}
+ isAttaching={images.isAttaching}
+ onMicPress={onMicPress}
+ micActive={micActive}
+ dictationMode={dictationMode}
+ onMicPressIn={onMicPressIn}
+ onMicPressOut={onMicPressOut}
+ inputLockReason={inputLockReason}
+ sendErrorMessage={sendErrorMessage}
+ onClearSendError={onClearSendError}
+ filePaths={controller.nativeChatFilePaths}
+ onNeedFiles={controller.loadNativeChatFiles}
+ skillDiscovery={controller.nativeChatSkills}
+ onNeedSkills={controller.loadNativeChatSkills}
+ sessionOptions={controller.nativeChatSessionOptions}
+ structuredComposer={structuredComposer}
+ keyboardInset={keyboardInset}
+ />
+
+
+
+
+
+
)
}
diff --git a/mobile/src/session/MobileNativeChatView.composer-lock.test.ts b/mobile/src/session/MobileNativeChatView.composer-lock.test.ts
index 9d1447690d5..fa51d08350b 100644
--- a/mobile/src/session/MobileNativeChatView.composer-lock.test.ts
+++ b/mobile/src/session/MobileNativeChatView.composer-lock.test.ts
@@ -183,3 +183,7 @@ describe('MobileNativeChatView: composer lock and prompt cards', () => {
})
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.failure-banner.test.ts b/mobile/src/session/MobileNativeChatView.failure-banner.test.ts
index 56780fd8bbd..1e9962fbe99 100644
--- a/mobile/src/session/MobileNativeChatView.failure-banner.test.ts
+++ b/mobile/src/session/MobileNativeChatView.failure-banner.test.ts
@@ -111,3 +111,7 @@ describe('MobileNativeChatView: send and read failure banners', () => {
expect(onClearSendError).toHaveBeenCalledOnce()
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.history-paging.test.ts b/mobile/src/session/MobileNativeChatView.history-paging.test.ts
index d92fb9fdaf8..f111d68091b 100644
--- a/mobile/src/session/MobileNativeChatView.history-paging.test.ts
+++ b/mobile/src/session/MobileNativeChatView.history-paging.test.ts
@@ -216,3 +216,7 @@ describe('MobileNativeChatView: history paging and anchoring', () => {
})
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts
index f435e366c81..83c009efc9a 100644
--- a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts
+++ b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts
@@ -250,3 +250,7 @@ describe('terminal prompt presentation with the production view, card and compos
}
)
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.rows.test.ts b/mobile/src/session/MobileNativeChatView.rows.test.ts
index a263b8e6cbd..7d813c307dc 100644
--- a/mobile/src/session/MobileNativeChatView.rows.test.ts
+++ b/mobile/src/session/MobileNativeChatView.rows.test.ts
@@ -74,3 +74,7 @@ describe('MobileNativeChatView: rows and the streaming bubble', () => {
expect(renderedRow('pending-1').props).not.toHaveProperty('queued')
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.stop.test.ts b/mobile/src/session/MobileNativeChatView.stop.test.ts
index b76341178ea..ac17509a2d0 100644
--- a/mobile/src/session/MobileNativeChatView.stop.test.ts
+++ b/mobile/src/session/MobileNativeChatView.stop.test.ts
@@ -105,3 +105,7 @@ describe('MobileNativeChatView: Stop control', () => {
expect(stops()).toHaveLength(1)
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.tail-follow.test.ts b/mobile/src/session/MobileNativeChatView.tail-follow.test.ts
index 95666c6946b..fce4ba34c76 100644
--- a/mobile/src/session/MobileNativeChatView.tail-follow.test.ts
+++ b/mobile/src/session/MobileNativeChatView.tail-follow.test.ts
@@ -382,3 +382,7 @@ describe('MobileNativeChatView: tail-follow', () => {
}
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx
index 6e7dfb15819..7fe3da017d2 100644
--- a/mobile/src/session/MobileNativeChatView.tsx
+++ b/mobile/src/session/MobileNativeChatView.tsx
@@ -100,6 +100,7 @@ type Props = ComposerTrayProps & {
pending: MobileNativeChatPendingItem[]
// Retain local preview URIs after authoritative image messages replace optimistic rows.
imagePreviewsByMessageId?: Record
+ composerScopeKey?: string | null
draftKey: string | null
onComposerTextChange: (text: string) => void
onAttachImage?: () => void
@@ -171,6 +172,7 @@ export function MobileNativeChatView({
pending,
imagePreviewsByMessageId,
draftKey,
+ composerScopeKey,
onComposerTextChange,
onAttachImage,
attachments,
@@ -388,6 +390,7 @@ export function MobileNativeChatView({
{}
{trayContent}
{
})
})
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileNativeChatView.waiting-rows.test.ts b/mobile/src/session/MobileNativeChatView.waiting-rows.test.ts
index 920c949ef6a..118466aca55 100644
--- a/mobile/src/session/MobileNativeChatView.waiting-rows.test.ts
+++ b/mobile/src/session/MobileNativeChatView.waiting-rows.test.ts
@@ -178,3 +178,7 @@ it('keeps a steer on its way into an ordinary running turn in the list, above th
expect(drawn).toEqual({ listed: ['ask', 'steer'], footer: ['status'] })
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/MobileQueuedMessageCardRow.tsx b/mobile/src/session/MobileQueuedMessageCardRow.tsx
index 794a7456cda..6fd00814fa1 100644
--- a/mobile/src/session/MobileQueuedMessageCardRow.tsx
+++ b/mobile/src/session/MobileQueuedMessageCardRow.tsx
@@ -5,6 +5,7 @@ import {
AlertCircle,
CornerDownRight,
ListEnd,
+ Image as ImageIcon,
MoreHorizontal,
Send,
Trash2
@@ -14,7 +15,7 @@ import { queuedMessageCardSteers } from '../../../src/shared/structured-agent-se
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards'
import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit'
-import { MobileNativeChatQueuedMessageEditor } from './native-chat/input/MobileNativeChatQueuedMessageEditor'
+import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
import { MobileQueuedCardText } from './MobileQueuedCardText'
import { queuedMessageStyles as styles } from './native-chat/input/mobile-native-chat-queued-message-styles'
@@ -45,7 +46,7 @@ export function MobileQueuedMessageCardRow({
style={styles.divided}
onLayout={(event) => onEditorLayout(event.nativeEvent.layout)}
>
-
+
)
}
@@ -93,7 +94,16 @@ function QueuedMessageCardContents({
) : null}
- {}
+ {card.images ? (
+
+
+ {card.images.length}
+
+ ) : null}
{card.waitsForAgent ? null : (
- {}
{card.command ? null : (
({ Text: 'Text', View: 'View' }))
+vi.mock('./native-chat/composer/MobileNativeChatComposer', () => ({
+ MobileNativeChatComposer: 'Composer'
+}))
+vi.mock('./native-chat/composer/use-mobile-native-chat-file-attachments', () => ({
+ useMobileNativeChatFileAttachments: () => ({
+ files: [],
+ attachFiles: vi.fn(),
+ removeFiles: vi.fn()
+ })
+}))
+vi.mock('./native-chat/composer/use-mobile-native-chat-image-upload', () => ({
+ useMobileNativeChatImageUpload: () => ({ attachImage: vi.fn(async () => {}), isAttaching: false })
+}))
+
+describe('queued phone composer action boundary', () => {
+ let renderer: ReactTestRenderer | undefined
+ afterEach(() => {
+ act(() => renderer?.unmount())
+ resetMobileNativeChatDraftInputsForTests()
+ })
+
+ it('saves literal text while refusing picked executable controls and retaining skill picks', async () => {
+ const save = vi.fn(async () => true)
+ const onError = vi.fn()
+ const client = new FakeSession('connected')
+ await act(async () => {
+ renderer = create(
+ createElement(
+ MobileQueuedMessageComposerContext.Provider,
+ {
+ value: {
+ agent: 'codex',
+ structured: null,
+ filePaths: [],
+ onNeedFiles: undefined,
+ onError,
+ onMicPress: undefined,
+ micActive: false,
+ dictationMode: undefined,
+ onMicPressIn: vi.fn(),
+ onMicPressOut: vi.fn()
+ }
+ },
+ createElement(MobileQueuedMessageComposer, {
+ attribution: null,
+ editor: {
+ messageId: 'card',
+ scopeKey: 'edit',
+ sessionId: 'session',
+ client,
+ imagesCapable: true,
+ text: 'hello',
+ saving: false,
+ canSave: true,
+ change: vi.fn(),
+ save,
+ removeImage: vi.fn(),
+ cancel: vi.fn()
+ }
+ })
+ )
+ )
+ })
+ const composer = findByHostType(renderer!.root, 'Composer')
+ await act(async () => {
+ expect(await composer.props.onSend('/compact')).toBe(true)
+ expect(await composer.props.onSend('/goal research')).toBe(true)
+ expect(composer.props.editSession.refuseCommand('/resume')).toBe(true)
+ })
+ expect(save).toHaveBeenCalledTimes(2)
+ save.mockClear()
+ expect(client.sendRequest).not.toHaveBeenCalled()
+ expect(onError).toHaveBeenCalledOnce()
+ act(() => composer.props.onPickSkill({ name: 'review', path: '/remote/SKILL.md' }))
+ expect(readMobileNativeChatDraftInputs('edit').skills).toEqual([
+ { name: 'review', path: '/remote/SKILL.md' }
+ ])
+ await act(async () => expect(await composer.props.onSend('hello')).toBe(true))
+ expect(save).toHaveBeenCalledOnce()
+ expect(client.sendRequest).not.toHaveBeenCalled()
+ })
+})
diff --git a/mobile/src/session/MobileQueuedMessageComposer.tsx b/mobile/src/session/MobileQueuedMessageComposer.tsx
new file mode 100644
index 00000000000..15323dd13f4
--- /dev/null
+++ b/mobile/src/session/MobileQueuedMessageComposer.tsx
@@ -0,0 +1,123 @@
+import { useContext, useEffect, useMemo, useRef } from 'react'
+import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
+import { Text, type TextInput, View } from 'react-native'
+import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer'
+import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit'
+import { useMobileNativeChatFileAttachments } from './native-chat/composer/use-mobile-native-chat-file-attachments'
+import { useMobileNativeChatImageUpload } from './native-chat/composer/use-mobile-native-chat-image-upload'
+import {
+ updateMobileNativeChatDraftInputs,
+ useMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { prepareQueuedMessageEditText } from '../../../src/shared/queued-message-edit-command'
+import { colors } from '../theme/mobile-theme'
+import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
+import { createUuidV4 } from '../../../src/shared/uuid-v4'
+
+export function MobileQueuedMessageComposer({
+ editor,
+ attribution
+}: {
+ editor: MobileQueuedMessageInlineEditor
+ attribution: string | null
+}): React.JSX.Element {
+ useMobileColorScheme()
+ const context = useContext(MobileQueuedMessageComposerContext)
+ const inputRef = useRef(null)
+ const emptyHandle = useRef(null)
+ const inputs = useMobileNativeChatDraftInputs(editor.scopeKey)
+ const files = useMobileNativeChatFileAttachments({
+ client: editor.client,
+ sessionId: editor.sessionId,
+ scopeKey: editor.scopeKey,
+ enabled: !editor.saving,
+ showToast: (message) => context?.onError(message)
+ })
+ const images = useMobileNativeChatImageUpload({
+ client: editor.client,
+ activeHandleRef: emptyHandle,
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: editor.scopeKey,
+ structuredNativeChat: true,
+ showToast: (message) => context?.onError(message),
+ onImagesUploaded: (scope, images) =>
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ images: [...current.images, ...images.map((image) => ({ ...image, id: createUuidV4() }))]
+ }))
+ })
+ useEffect(() => {
+ inputRef.current?.focus()
+ }, [])
+ const agent = context?.agent ?? 'codex'
+ const reported = context?.structured?.catalog.reported
+ const acceptsText = useMemo(
+ () => prepareQueuedMessageEditText(agent, reported),
+ [agent, reported]
+ )
+ const refuseCommand = (text: string): boolean => {
+ if (acceptsText(text)) {
+ return false
+ }
+ context?.onError("Commands can't be saved in a queued message.")
+ return true
+ }
+ return (
+
+
+ Editing message{attribution ? ` · ${attribution}` : ''}
+
+ editor.save()}
+ editSession={{ cancel: editor.cancel, locked: editor.saving, refuseCommand }}
+ sendSurfaceId={editor.scopeKey}
+ getSendCompletionGeneration={() => 0}
+ getComposerEditGeneration={() => 0}
+ disabled={editor.saving}
+ sendDisabled={!editor.canSave}
+ structured={
+ context?.structured
+ ? {
+ ...context.structured,
+ files: files.files,
+ onAttachFiles: () => void files.attachFiles(),
+ onRemoveFile: (id) => files.removeFiles([id])
+ }
+ : null
+ }
+ skillDiscovery={context?.skillDiscovery}
+ onNeedSkills={context?.onNeedSkills}
+ filePaths={context?.filePaths}
+ onNeedFiles={context?.onNeedFiles}
+ onPickSkill={(skill) =>
+ updateMobileNativeChatDraftInputs(editor.scopeKey, (current) => ({
+ ...current,
+ skills: [...current.skills.filter(({ name }) => name !== skill.name), skill]
+ }))
+ }
+ attachments={[...inputs.images]}
+ onRemoveAttachment={editor.imagesCapable ? editor.removeImage : undefined}
+ onAttachImage={
+ editor.imagesCapable
+ ? () => {
+ void images.attachImage('library')
+ }
+ : undefined
+ }
+ isAttaching={images.isAttaching}
+ onMicPress={context?.onMicPress}
+ micActive={context?.micActive}
+ dictationMode={context?.dictationMode}
+ onMicPressIn={context?.onMicPressIn}
+ onMicPressOut={context?.onMicPressOut}
+ />
+
+ )
+}
diff --git a/mobile/src/session/MobileQueuedMessageScrollList.tsx b/mobile/src/session/MobileQueuedMessageScrollList.tsx
index 5af2076f9e6..05f23acaaa5 100644
--- a/mobile/src/session/MobileQueuedMessageScrollList.tsx
+++ b/mobile/src/session/MobileQueuedMessageScrollList.tsx
@@ -23,15 +23,17 @@ export type MobileQueueDragViewport = {
type Metrics = { offset: number; viewport: number; content: number }
-/** The queued cards under the fixed header, capped so a long queue never takes over the screen. */
+/** Compact cards are capped; the full editor yields to the available chat viewport. */
export function MobileQueuedMessageScrollList({
messageIds,
newestIsPersons,
+ inlineEditorActive = false,
children
}: {
messageIds: readonly string[]
/** The newest card has no sender: the person just queued it, so the list shows it. */
newestIsPersons: boolean
+ inlineEditorActive?: boolean
/** Rows, given `reveal` to keep an edited row in view. */
children: (reveal: (row: LayoutRectangle) => void, drag: MobileQueueDragViewport) => ReactNode
}): React.JSX.Element {
@@ -75,17 +77,17 @@ export function MobileQueuedMessageScrollList({
// Never past the content's end, which may not have caught up with a row that just grew.
const top = Math.max(0, row.y - spacing.lg)
const bottom = Math.min(Math.max(content, rowBottom), rowBottom + spacing.lg)
- if (top < offset) {
+ if (row.height > viewport || top < offset) {
scrollRef.current?.scrollTo({ y: top, animated: false })
} else if (bottom > offset + viewport) {
scrollRef.current?.scrollTo({ y: bottom - viewport, animated: false })
}
}
return (
-
+
({
return true
},
requestMicrophonePermissionsAsync: async () => ({ granted: true }),
- tearDown: () => {},
+ tearDown: () => {
+ device.recording = false
+ },
toggleRecording: (recording: boolean) => {
device.recording = recording
return true
diff --git a/mobile/src/session/mobile-file-syntax.ts b/mobile/src/session/mobile-file-syntax.ts
index 9756b3eb6c3..4156291b2f4 100644
--- a/mobile/src/session/mobile-file-syntax.ts
+++ b/mobile/src/session/mobile-file-syntax.ts
@@ -50,7 +50,9 @@ const LANGUAGE_ALIASES: Record = {
zsh: 'bash',
fish: 'bash',
yml: 'yaml',
- 'cuda-cpp': 'cpp'
+ 'cuda-cpp': 'cpp',
+ 'glimmer-js': 'javascript',
+ 'glimmer-ts': 'typescript'
}
export function resolveMobileSyntaxLanguage(filePath: string, preferredLanguage?: string): string {
diff --git a/mobile/src/session/mobile-native-chat-controller-contract.ts b/mobile/src/session/mobile-native-chat-controller-contract.ts
index c133489ba35..4635edaad07 100644
--- a/mobile/src/session/mobile-native-chat-controller-contract.ts
+++ b/mobile/src/session/mobile-native-chat-controller-contract.ts
@@ -31,6 +31,8 @@ export type MobileNativeChatController = {
showNativeChat: boolean
showNativeChatRef: MutableRefObject
nativeChatAgent: string | null
+ chatComposerScopeKey?: string | null
+ reportQueuedEditError?: (message: string) => void
chatDraftKey: string | null
setChatComposerText: Dispatch>
getChatComposerEditGeneration: () => number
diff --git a/mobile/src/session/mobile-native-chat-render-data.ts b/mobile/src/session/mobile-native-chat-render-data.ts
index 8ceabf77350..e2b4d30991a 100644
--- a/mobile/src/session/mobile-native-chat-render-data.ts
+++ b/mobile/src/session/mobile-native-chat-render-data.ts
@@ -12,7 +12,7 @@ import {
isUndrawnProviderFrameMessage
} from '../../../src/shared/native-chat/tools/native-chat-tool-fold'
import { projectNativeChatTaskListFrames } from '../../../src/shared/native-chat/input/native-chat-task-list-frames'
-import { foldSubagentItems } from '../../../src/shared/native-chat-subagent-items'
+import { foldSubagentItems } from '../../../src/shared/native-chat/transcript/native-chat-subagent-items'
import { prepareNativeChatMessages } from '../../../src/shared/native-chat-message-preparation'
import {
isImageRefBlock,
diff --git a/mobile/src/session/mobile-prompt-controller.test.ts b/mobile/src/session/mobile-prompt-controller.test.ts
index ee852879f5a..d6be2d32633 100644
--- a/mobile/src/session/mobile-prompt-controller.test.ts
+++ b/mobile/src/session/mobile-prompt-controller.test.ts
@@ -282,3 +282,7 @@ describe('prompt cards through the production controller, send contract and view
}
)
})
+
+vi.mock('./MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/mobile-queued-edit-composer.test.tsx b/mobile/src/session/mobile-queued-edit-composer.test.tsx
new file mode 100644
index 00000000000..5413974164b
--- /dev/null
+++ b/mobile/src/session/mobile-queued-edit-composer.test.tsx
@@ -0,0 +1,628 @@
+import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
+import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
+import { createElement, type ReactNode } from 'react'
+import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
+import {
+ mobileNativeChatDraftDestination,
+ captureMobileNativeChatTextDestination,
+ readMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { act } from 'react-test-renderer'
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+import type {
+ AcpCommandOptionsFixtureModule,
+ MobileQueuedEditHostFixtureModule
+} from '../../../src/shared/mobile-queued-edit-host.test-fixture-contract'
+import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
+import { TextInput } from 'react-native'
+import { ActionSheetModal } from '../components/ActionSheetModal'
+import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
+import { MobileNativeChatQueuedMessages } from './native-chat/input/MobileNativeChatQueuedMessages'
+import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer'
+import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
+import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
+import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
+import {
+ mutationOk,
+ queuedDraft,
+ SESSION_ID
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
+
+let queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost']
+beforeAll(async () => {
+ const fixtures = await vi.importActual(
+ '../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
+ )
+ queuedEditHost = fixtures.queuedEditHost
+})
+
+const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
+vi.mock('../platform/media-picker', () => ({ useMediaPicker: () => picker }))
+vi.mock('../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' }))
+vi.mock('react-native-reanimated', async () => {
+ const { useRef } = await import('react')
+ return {
+ default: { ScrollView: 'ScrollView' },
+ useAnimatedRef: () => useRef(null),
+ useSharedValue: (value: unknown) => useRef({ value }).current
+ }
+})
+vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
+vi.mock('../components/mounted-bottom-drawer', () => ({ MountedBottomDrawer: 'BottomDrawer' }))
+vi.mock('../components/bottom-drawer-modal-host-scope', () => ({
+ useBottomDrawerModalHost: () => null
+}))
+
+const hostFixtures = await vi.importActual(
+ '../../../src/main/native-chat/agent-session-wire/mobile-queued-edit-host.test-fixture'
+)
+const { AcpStructuredOptions } = await vi.importActual(
+ '../../../src/main/acp/acp-structured-options'
+)
+
+describe('real phone inline composer from More through picker pruning and host body', () => {
+ const { state, Harness, mount, sendRequest, error, resolved } = mobileQueuedEditHarness()
+ const profiles = [
+ ['claude', 'model', '/model'],
+ ['codex', 'review.v2', '$review.v2'],
+ ['pi', 'skill:review', '/skill:review'],
+ ['openclaude', 'review', '/review'],
+ ['opencode', 'review', '/review'],
+ ['opencode2', 'review', '/review'],
+ ['grok', 'review', '/review']
+ ] as const
+ async function rows(
+ message: Parameters[0],
+ agent = 'codex',
+ sessionId = SESSION_ID,
+ catalog: {
+ reported: { name: string; kind: 'skill' | 'command'; path?: string }[]
+ discovery?: NativeChatSkillDiscoverySnapshot
+ } = {
+ reported: []
+ },
+ extra?: (hook: NonNullable) => ReactNode
+ ) {
+ await mount(message, true, agent, sessionId)
+ act(() => state.hook!.queued.editor!.cancel())
+ resolved.mockClear()
+ const renderContent: NonNullable[0]['renderContent']> = (hook) =>
+ createElement(
+ MobileQueuedMessageComposerContext.Provider,
+ {
+ value: {
+ agent,
+ structured: {
+ catalog: { reported: catalog.reported, conversationCommands: [] },
+ onSlashMenuOpen: () => {},
+ files: [],
+ onRemoveFile: () => {}
+ },
+ skillDiscovery: catalog.discovery ?? {
+ status: 'ready',
+ skills: catalog.reported
+ .filter((entry) => entry.kind === 'skill' && entry.path)
+ .map((entry) => ({
+ id: entry.name,
+ name: entry.name,
+ description: null,
+ providers: ['agent-skills'],
+ sourceKind: 'repo',
+ sourceLabel: 'Repo',
+ rootPath: '/skills',
+ directoryPath: `/skills/${entry.name}`,
+ skillFilePath: entry.path ?? '',
+ installed: true,
+ updatedAt: null
+ }))
+ },
+ filePaths: [],
+ onNeedFiles: undefined,
+ onError: error,
+ onMicPress: undefined,
+ micActive: false,
+ dictationMode: undefined,
+ onMicPressIn: () => {},
+ onMicPressOut: () => {}
+ }
+ },
+ createElement(MobileNativeChatQueuedMessages, {
+ cards: hook.queued.cards,
+ onEdit: hook.queued.edit,
+ editor: hook.queued.editor
+ }),
+ extra?.(hook)
+ )
+ const rerender = async () =>
+ act(async () =>
+ state.renderer!.update(
+ createElement(Harness, {
+ sessionId,
+ agent,
+ renderContent,
+ skillsSupport: true,
+ imagesSupport: true,
+ composerScopeKey: 'original-bottom'
+ })
+ )
+ )
+ await rerender()
+ const root = () => state.renderer!.root
+ const button = (label: string) =>
+ root().findAll(
+ (node) =>
+ node.props.accessibilityLabel === label && typeof node.props.onPress === 'function'
+ )[0]!
+ const field = () =>
+ root().find((node) => node.type === TextInput && node.props.multiline === true)
+ const open = async () => {
+ await act(async () => button('More actions').props.onPress())
+ const sheet = root().find(
+ (node) =>
+ node.type === ActionSheetModal && node.props.actions?.[0]?.label === 'Edit message'
+ )
+ await act(async () => sheet.props.actions[0].onPress())
+ expect(root().findAllByType(MobileQueuedMessageComposer)).toHaveLength(1)
+ expect(root().findAllByType(MobileNativeChatComposer)).toHaveLength(extra ? 2 : 1)
+ }
+ await open()
+ return { root, button, field, rerender, open }
+ }
+ it.each(profiles)(
+ '%s preserves its actual offered %s shape through the wrapper and accepted body',
+ async (agent, name, token) => {
+ const message = queuedDraft({
+ messageId: 'picked',
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'seed' }] }
+ })
+ const host = queuedEditHost(SESSION_ID, message)
+ let path = '/A/SKILL.md'
+ let unknown = agent === 'claude'
+ let desired = message.body
+ const scanned = agent === 'opencode' || agent === 'opencode2'
+ const options = new AcpStructuredOptions()
+ options.adoptCommands([{ name, description: 'Review the prompt' }])
+ const catalog: NonNullable[3]> = {
+ reported: scanned ? (options.readCommands() ?? []) : [{ name, kind: 'skill', path }],
+ ...(scanned
+ ? {
+ discovery: {
+ status: 'ready',
+ skills: [
+ {
+ id: 'repo:review',
+ name,
+ description: null,
+ providers: ['agent-skills'],
+ sourceKind: 'repo',
+ sourceLabel: 'Repo',
+ rootPath: '/skills',
+ directoryPath: '/skills/review',
+ skillFilePath: path,
+ installed: true,
+ updatedAt: null
+ }
+ ]
+ }
+ }
+ : {})
+ }
+ const { button, field, rerender } = await rows(message, agent, SESSION_ID, catalog)
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ const fields = QueuedMessageUpdateParams.parse(params)
+ const edited = queuedMessageWithEdit(host.row!.body, fields)
+ if (!edited.ok) {
+ throw new Error(edited.reason)
+ }
+ desired = edited.body
+ if (unknown) {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return mutationOk(host.update(fields))
+ })
+ const pick = async () => {
+ act(() => field().props.onChangeText('/'))
+ act(() =>
+ field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
+ )
+ await act(async () => button(token).props.onPress())
+ expect(state.hook!.queued.editor?.text).toBe(`${token} `)
+ expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual(
+ scanned ? [] : [{ name, path }]
+ )
+ }
+ await pick()
+ await act(async () => button('Save edited message').props.onPress())
+ if (unknown) {
+ const first = desired
+ path = '/B/SKILL.md'
+ catalog.reported = [{ name, kind: 'skill', path }]
+ await rerender()
+ // Reopen menu after deleting: deletion retires A before picking B.
+ act(() => field().props.onChangeText(''))
+ await pick()
+ act(() => field().props.onChangeText(`${token} suffix`))
+ const { batchEvent } =
+ await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ act(() => state.listener?.(batchEvent([{ ...message, body: first }])))
+ expect(state.hook!.queued.editor?.text).toBe(`${token} suffix`)
+ expect(resolved).not.toHaveBeenCalled()
+ expect(state.bottomText).toBe('')
+ host.update({
+ messageId: 'picked',
+ expectedBodyFingerprint: host.row!.fingerprint,
+ text: token,
+ images: [],
+ skills: [{ name, path: '/A/SKILL.md' }]
+ })
+ unknown = false
+ await act(async () => button('Save edited message').props.onPress())
+ }
+ expect(error.mock.calls).toEqual([])
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).not.toHaveLength(0)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(host.row!.body.skills).toEqual(scanned ? undefined : [{ name, path }])
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toHaveLength(agent === 'claude' ? 2 : 1)
+ expect(
+ sendRequest.mock.calls.some(([method]) =>
+ /(?:\.send$|conversationCommand|goal|resume|pty)/i.test(method)
+ )
+ ).toBe(false)
+ host.leases.dispose()
+ }
+ )
+ it('keeps both saved files on clean Save and projects the phone picked list after an argument edit', async () => {
+ const skills = [
+ { name: 'review', path: '/A/SKILL.md' },
+ { name: 'review', path: '/B/SKILL.md' }
+ ]
+ const message = queuedDraft({
+ messageId: 'two-files',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [{ type: 'text', text: '$review old' }],
+ skills
+ }
+ })
+ const host = queuedEditHost(SESSION_ID, message)
+ try {
+ const { button, field, open } = await rows(message)
+ sendRequest.mockImplementation(async (method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? mutationOk(host.update(QueuedMessageUpdateParams.parse(params)))
+ : readOrHoldReply(method, params)
+ )
+ await act(async () => button('Save edited message').props.onPress())
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toHaveLength(0)
+ expect(host.row!.body.skills).toEqual(skills)
+ await open()
+ act(() => field().props.onChangeText('$review changed'))
+ await act(async () => button('Save edited message').props.onPress())
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(host.row!.body.skills).toEqual(skills)
+ expect(host.row!.body.blocks).toEqual([{ type: 'text', text: '$review changed' }])
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toHaveLength(1)
+ } finally {
+ host.leases.dispose()
+ }
+ })
+
+ it.each(['question', 'approval'] as const)(
+ 'automatic/mail More→Edit→Save persists user authorship, position and options across journal reopen under %s',
+ async (kind) => {
+ const { ok, snapshotEvent } =
+ await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(hostFixtures.now)
+ const rig = await hostFixtures.createMobileQueuedEditHostFixture()
+ try {
+ await rig.start()
+ const from = { kind: 'agent' as const, senders: [], orchestration: null }
+ const before = await rig.insert({
+ messageId: `mail-${kind}`,
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [{ type: 'text', text: 'mail intent' }],
+ sentAs: 'goal',
+ from
+ },
+ options: { model: 'saved-model', effort: 'high' }
+ })
+ const beforeWire = await rig.published(before.messageId)
+ const { button, field, open } = await rows(beforeWire, 'codex', rig.sessionId)
+ act(() => state.hook!.queued.editor!.cancel())
+ const pending = {
+ options: [{ id: 'yes', label: 'Yes' }],
+ resolution: {
+ state: 'pending' as const,
+ selectedOptionId: null,
+ resolvedBy: null,
+ resolvedAt: null
+ }
+ }
+ const prompt = snapshotEvent({
+ queuedMessages: [beforeWire],
+ items: [
+ {
+ itemId: 'prompt',
+ revision: 1,
+ sequence: 1,
+ observedAt: 1,
+ body:
+ kind === 'question'
+ ? { kind, question: 'Pick', ...pending }
+ : { kind, title: 'Allow?', detail: null, ...pending }
+ }
+ ]
+ })
+ act(() =>
+ state.listener?.({
+ ...prompt,
+ sessionId: rig.sessionId,
+ page: { ...prompt.page, sessionId: rig.sessionId }
+ })
+ )
+ await open()
+ const hostResults: unknown[] = []
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method === 'agentSession.queuedMessageEditHold') {
+ return ok(await rig.request(method, params))
+ }
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ const result = await rig.request(method, params)
+ hostResults.push(result)
+ return ok(result)
+ })
+ // Equal Save proves no durable sender mutation or update RPC.
+ await act(async () => button('Save edited message').props.onPress())
+ expect(rig.read(before.messageId)?.body.from).toEqual(from)
+ expect(
+ sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toBe(false)
+ await open()
+ act(() => field().props.onChangeText('user replacement'))
+ await act(async () => button('Save edited message').props.onPress())
+ expect(hostResults, JSON.stringify(hostResults)).toMatchObject([
+ { ok: true, value: { status: 'updated' } }
+ ])
+ expect(error.mock.calls).toEqual([])
+ expect(state.hook!.queued.editor).toBeUndefined()
+ const accepted = rig.read(before.messageId)!
+ expect(accepted).toMatchObject({
+ position: before.position,
+ options: before.options,
+ body: { sentAs: 'goal', blocks: [{ type: 'text', text: 'user replacement' }] }
+ })
+ expect(accepted.body).not.toHaveProperty('from')
+ await rig.restart()
+ const reopened = rig.read(before.messageId)!
+ expect(reopened).toEqual(accepted)
+ const publication = snapshotEvent({
+ queuedMessages: [await rig.published(reopened.messageId)]
+ })
+ act(() =>
+ state.listener?.({
+ ...publication,
+ sessionId: rig.sessionId,
+ page: { ...publication.page, sessionId: rig.sessionId }
+ })
+ )
+ await open()
+ expect(state.hook!.queued.editor?.text).toBe('user replacement')
+ expect(state.hook!.queued.cards[0]?.attribution).toBeNull()
+ } finally {
+ await rig.dispose()
+ clock.mockRestore()
+ }
+ },
+ 15000
+ )
+
+ it.each(['updated', 'unknown', 'refused', 'unknown-phase'] as const)(
+ 'real phone Cancel revokes pending/unknown Save before late %s and cannot mutate a new edit',
+ async (mode) => {
+ const { batchEvent, fieldsOf } =
+ await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ const message = queuedDraft({ messageId: 'pending-cancel' })
+ const other = queuedDraft({ messageId: 'new-edit', position: 2 })
+ const host = queuedEditHost(SESSION_ID, message)
+ const { button, field } = await rows(message)
+ act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
+ act(() => field().props.onChangeText('B'))
+ act(() => field().props.onFocus())
+ const dictate = captureMobileNativeChatTextDestination()!
+ expect(dictate).toBeTypeOf('function')
+ const oldScope = state.hook!.queued.editor!.scopeKey
+ const destination = mobileNativeChatDraftDestination(oldScope)
+ let release = () => {}
+ const pending = new Promise((resolve) => {
+ release = resolve
+ })
+ let oldEditId = ''
+ sendRequest.mockImplementation(async (method, params) => {
+ if (
+ method === 'agentSession.queuedMessageEditHold' &&
+ fieldsOf(params).action === 'release'
+ ) {
+ oldEditId = String(fieldsOf(params).editId)
+ }
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ const decision =
+ mode === 'refused'
+ ? { status: 'not-editable' as const, messageId: message.messageId }
+ : host.update(QueuedMessageUpdateParams.parse(params))
+ expect(decision.status).toBe(mode === 'refused' ? 'not-editable' : 'updated')
+ await pending
+ if (mode === 'unknown' || mode === 'unknown-phase') {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return mutationOk(decision)
+ })
+ let save!: Promise
+ act(() => {
+ save = button('Save edited message').props.onPress()
+ })
+ expect(state.hook!.queued.editor?.saving).toBe(true)
+ expect(field().props.editable).toBe(false)
+ expect(button('Save edited message').props.disabled).toBe(true)
+ expect(button('Cancel editing').props.disabled ?? false).toBe(false)
+ if (mode === 'unknown-phase') {
+ await act(async () => {
+ release()
+ await save
+ })
+ expect(state.hook!.queued.editor?.saving).toBe(false)
+ expect(field().props.editable).toBe(true)
+ }
+ await act(async () => button('Cancel editing').props.onPress())
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(destination.active).toBe(false)
+ expect(oldEditId).not.toBe('')
+ expect(state.bottomText).toBe('occupied')
+ act(() => state.listener?.(batchEvent([message, other])))
+ await act(async () => {
+ await state.hook!.queued.edit!(other.messageId)
+ })
+ act(() => field().props.onChangeText('fresh input'))
+ const newScope = state.hook!.queued.editor!.scopeKey
+ act(() => expect(dictate('late speech')).toBe(false))
+ await act(async () => {
+ release()
+ await save
+ })
+ act(() => state.listener?.(batchEvent([{ ...message, body: host.row!.body }, other])))
+ expect(state.hook!.queued.editor).toMatchObject({
+ messageId: other.messageId,
+ text: 'fresh input',
+ scopeKey: newScope,
+ saving: false
+ })
+ expect(state.bottomText).toBe('occupied')
+ expect(readMobileNativeChatDraftInputs(oldScope)).toMatchObject({
+ files: [],
+ images: [],
+ skills: []
+ })
+ expect(error).not.toHaveBeenCalled()
+ expect(resolved).not.toHaveBeenCalled()
+ expect(
+ sendRequest.mock.calls.filter(
+ ([method, params]) =>
+ method === 'agentSession.queuedMessageEditHold' &&
+ fieldsOf(params).action === 'release' &&
+ fieldsOf(params).editId === oldEditId
+ )
+ ).toHaveLength(1)
+ host.leases.dispose()
+ }
+ )
+
+ it.each(['files', 'images'] as const)(
+ 'real %s upload Cancel revokes its captured destination while normal pending admission blocks Save',
+ async (kind) => {
+ const { ok } = await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ const message = queuedDraft({ messageId: `cancel-${kind}` })
+ const { root, button } = await rows(message)
+ act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
+ const scope = state.hook!.queued.editor!.scopeKey
+ const destination = mobileNativeChatDraftDestination(scope)
+ let release = () => {}
+ const pending = new Promise((resolve) => {
+ release = resolve
+ })
+ let started = () => {}
+ const start = new Promise((resolve) => {
+ started = resolve
+ })
+ picker.pickFiles.mockImplementation(async function* () {
+ yield { name: 'late.txt', mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
+ yield { name: 'never.txt', mime: 'text/plain', byteLength: 1, base64: 'Yg==' }
+ })
+ picker.pickImages.mockResolvedValue([
+ { base64: 'YQ==', uri: 'file:///late.png' },
+ { base64: 'Yg==', uri: 'file:///never.png' }
+ ])
+ const isStart = (method: string) =>
+ method.endsWith('uploadStart') || method === 'clipboard.startImageUpload'
+ sendRequest.mockImplementation(async (method, params) => {
+ if (isStart(method)) {
+ started()
+ await pending
+ return ok({ uploadId: 'held' })
+ }
+ if (method === 'clipboard.commitImageUpload') {
+ return ok('/late.png')
+ }
+ if (method.endsWith('uploadCommit')) {
+ return ok({ path: '/late.txt', name: 'late.txt', byteLength: 1 })
+ }
+ if (method.includes('uploadChunk') || method === 'clipboard.appendImageUploadChunk') {
+ return ok(null)
+ }
+ return readOrHoldReply(method, params)
+ })
+ const inline = root()
+ .findByType(MobileQueuedMessageComposer)
+ .findByType(MobileNativeChatComposer)
+ await act(async () => {
+ if (kind === 'files') {
+ inline.props.structured.onAttachFiles()
+ } else {
+ inline.props.onAttachImage()
+ }
+ await start
+ })
+ expect(readMobileNativeChatDraftInputs(scope).pending).toBe(1)
+ expect(state.hook!.queued.editor!.canSave).toBe(false)
+ expect(button('Save edited message').props.disabled).toBe(true)
+ expect(button('Cancel editing').props.disabled ?? false).toBe(false)
+ await act(async () => button('Cancel editing').props.onPress())
+ expect(destination.active).toBe(false)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ await act(async () => {
+ release()
+ await vi.waitFor(() =>
+ expect(
+ sendRequest.mock.calls.some(
+ ([method]) =>
+ method.endsWith('uploadCommit') || method === 'clipboard.commitImageUpload'
+ )
+ ).toBe(true)
+ )
+ })
+ expect(sendRequest.mock.calls.filter(([method]) => isStart(method))).toHaveLength(1)
+ expect(
+ sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toBe(false)
+ expect(readMobileNativeChatDraftInputs(scope)).toMatchObject({
+ files: [],
+ images: [],
+ skills: []
+ })
+ expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
+ files: [],
+ images: []
+ })
+ expect(state.bottomText).toBe('occupied')
+ expect(error).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx
new file mode 100644
index 00000000000..6b60d180a6d
--- /dev/null
+++ b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx
@@ -0,0 +1,254 @@
+import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
+import { useMobileNativeChatComposerMenu } from './native-chat/composer/use-mobile-native-chat-composer-menu'
+import {
+ resetMobileNativeChatDraftStoreForTests,
+ useMobileNativeChatDraft
+} from './native-chat/composer/mobile-native-chat-draft-store'
+import {
+ updateMobileNativeChatDraftInputs,
+ resetMobileNativeChatDraftInputsForTests
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { createElement, type ReactNode } from 'react'
+import { act, create, type ReactTestRenderer } from 'react-test-renderer'
+import { afterEach, expect, vi } from 'vitest'
+import type {
+ AgentSessionQueuedMessage,
+ AgentSessionQueuedMessageEditHoldResult
+} from '../../../src/shared/agent-session-wire'
+import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
+import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
+import type { RpcClient } from '../transport/rpc-client'
+import type { RpcResponse } from '../transport/types'
+import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'
+import {
+ CAPABLE,
+ SESSION_ID,
+ fieldsOf,
+ mutationOk,
+ ok,
+ snapshotEvent
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+
+export function withText(body: AgentSessionQueuedMessage['body'], text: string) {
+ const edited = queuedMessageWithEdit(body, { text })
+ if (!edited.ok) {
+ throw new Error(edited.reason)
+ }
+ return edited.body
+}
+
+export function editHoldReply(params: unknown): RpcResponse {
+ const result: AgentSessionQueuedMessageEditHoldResult =
+ fieldsOf(params).action === 'release'
+ ? { status: 'released' }
+ : { status: 'held', fingerprint: 'fp', leaseDurationMs: 120_000, remainingMs: 120_000 }
+ return ok(result)
+}
+
+export function readOrHoldReply(method: string, params: unknown): RpcResponse {
+ return method === 'agentSession.queuedMessageEditHold'
+ ? editHoldReply(params)
+ : ok({ models: [], current: {} })
+}
+
+vi.mock('react-native', () => ({
+ Text: 'Text',
+ View: 'View',
+ Pressable: 'Pressable',
+ ScrollView: 'ScrollView',
+ TextInput: 'TextInput',
+ ActivityIndicator: 'ActivityIndicator',
+ Image: 'Image',
+ Keyboard: { dismiss: vi.fn() },
+ Platform: { OS: 'ios' },
+ useWindowDimensions: () => ({ fontScale: 1 }),
+ StyleSheet: { create: (styles: unknown) => styles }
+}))
+vi.mock('lucide-react-native', () => ({
+ FileText: 'FileText',
+ Package: 'Package',
+ Terminal: 'Terminal',
+ ArrowUp: 'ArrowUp',
+ AtSign: 'AtSign',
+ AlertCircle: 'AlertCircle',
+ Image: 'Image',
+ Paperclip: 'Paperclip',
+ Check: 'Check',
+ ChevronDown: 'ChevronDown',
+ ChevronLeft: 'ChevronLeft',
+ ChevronRight: 'ChevronRight',
+ CornerDownRight: 'CornerDownRight',
+ ListEnd: 'ListEnd',
+ MoreHorizontal: 'MoreHorizontal',
+ Mic: 'Mic',
+ Pencil: 'Pencil',
+ Play: 'Play',
+ Plus: 'Plus',
+ Send: 'Send',
+ ShieldAlert: 'ShieldAlert',
+ Square: 'Square',
+ Trash2: 'Trash2',
+ X: 'X'
+}))
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
+}))
+
+export function mobileQueuedEditHarness() {
+ const state: {
+ renderer?: ReactTestRenderer
+ bottomText: string
+ hook?: ReturnType
+ menu?: ReturnType
+ listener?: (data: unknown) => void
+ } = { bottomText: '' }
+ const append = vi.fn(() => true)
+ const error = vi.fn()
+ const notice = vi.fn()
+ const resolved = vi.fn()
+ const sendRequest = vi.fn()
+ const client: RpcClient = {
+ sendRequest,
+ subscribe: (_method, _params, onData) => {
+ state.listener = onData
+ return () => {}
+ },
+ updateTerminalSubscriptionViewport: () => {},
+ getState: () => 'connected',
+ getReconnectAttempt: () => 0,
+ getLastConnectedAt: () => null,
+ onStateChange: () => () => {},
+ notifyForeground: () => {},
+ close: () => {}
+ }
+ function Harness({
+ sessionId = SESSION_ID,
+ editSupport = true,
+ enabled = true,
+ connected = true,
+ transport = client,
+ composerScopeKey,
+ imagesSupport = false,
+ skillsSupport = false,
+ agent = 'codex',
+ renderContent
+ }: {
+ sessionId?: string
+ editSupport?: boolean | null
+ enabled?: boolean
+ connected?: boolean
+ transport?: RpcClient | null
+ composerScopeKey?: string
+ imagesSupport?: boolean
+ skillsSupport?: boolean
+ agent?: string
+ renderContent?: (hook: ReturnType) => ReactNode
+ }): ReactNode {
+ state.bottomText = useMobileNativeChatDraft('original-bottom')
+ state.hook = useMobileStructuredAgentSession({
+ client: transport,
+ sessionId,
+ sourceIdentity: 'host-a',
+ enabled,
+ connected,
+ agent,
+ hostSupport:
+ editSupport === null
+ ? null
+ : {
+ ...CAPABLE,
+ sendSkills: true,
+ queuedMessages: false,
+ queuedMessageImageEdit: imagesSupport,
+ queuedMessageSkillsEdit: skillsSupport,
+ queuedMessageEdit: editSupport
+ },
+ composerScopeKey,
+ appendComposerText: append,
+ onSendError: error,
+ onQueuedEditNotice: notice,
+ onActionResolved: resolved
+ })
+ state.menu = useMobileNativeChatComposerMenu({
+ value: state.hook.queued.editor?.text ?? '',
+ onChangeText: (text) => state.hook?.queued.editor?.change(text),
+ agent,
+ structuredCatalog: {
+ reported: [{ name: 'review', kind: 'skill', path: '/B/SKILL.md' }],
+ conversationCommands: []
+ },
+ filePaths: [],
+ focusField: () => {},
+ editing: true,
+ // Mirrors the real composer: the menu hands over its row; the draft keeps name and path.
+ onPickSkill: ({ token, path }) => {
+ const key = state.hook?.queued.editor?.scopeKey
+ if (key && path) {
+ updateMobileNativeChatDraftInputs(key, (before) => ({
+ ...before,
+ skills: [{ name: token.slice(1), path }]
+ }))
+ }
+ }
+ })
+ return renderContent?.(state.hook) ?? null
+ }
+ function requestedFingerprint(message: AgentSessionQueuedMessage) {
+ const params = sendRequest.mock.calls.findLast(
+ ([method]) => method === 'agentSession.queuedMessageUpdate'
+ )?.[1]
+ const fields = QueuedMessageUpdateParams.parse(params)
+ const edited = queuedMessageWithEdit(message.body, fields)
+ if (!edited.ok) {
+ throw new Error(edited.reason)
+ }
+ return agentSessionSendBodyFingerprint(SESSION_ID, edited.body)
+ }
+ async function mount(
+ message: AgentSessionQueuedMessage,
+ editSupport: boolean | null = true,
+ agent = 'codex',
+ sessionId = SESSION_ID
+ ) {
+ vi.clearAllMocks()
+ resetMobileNativeChatDraftInputsForTests()
+ resetMobileNativeChatDraftStoreForTests()
+ sendRequest.mockImplementation(async (method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? mutationOk({
+ status: 'updated',
+ messageId: message.messageId,
+ fingerprint: requestedFingerprint(message)
+ })
+ : readOrHoldReply(method, params)
+ )
+ await act(async () => {
+ state.renderer = create(createElement(Harness, { editSupport, agent, sessionId }))
+ })
+ const snapshot = snapshotEvent({ queuedMessages: [message], runningTurn: true })
+ act(() => state.listener?.({ ...snapshot, sessionId, page: { ...snapshot.page, sessionId } }))
+ if (editSupport !== null) {
+ await act(async () => {
+ expect(await state.hook!.queued.edit!(message.messageId)).toBe(true)
+ })
+ }
+ }
+ afterEach(async () => {
+ await act(async () => state.renderer?.unmount())
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ return {
+ state,
+ Harness,
+ mount,
+ client,
+ sendRequest,
+ append,
+ error,
+ notice,
+ resolved,
+ requestedFingerprint
+ }
+}
diff --git a/mobile/src/session/mobile-queued-edit-lease-outcome.test.tsx b/mobile/src/session/mobile-queued-edit-lease-outcome.test.tsx
new file mode 100644
index 00000000000..a123e3fd80a
--- /dev/null
+++ b/mobile/src/session/mobile-queued-edit-lease-outcome.test.tsx
@@ -0,0 +1,366 @@
+import { createElement } from 'react'
+import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
+import {
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { act } from 'react-test-renderer'
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
+import type { AgentSessionQueuedMessageEditHoldResult } from '../../../src/shared/agent-session-wire'
+import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
+import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
+import {
+ fieldsOf,
+ mutationOk,
+ ok,
+ queuedDraft,
+ SESSION_ID
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+
+let queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost']
+beforeAll(async () => {
+ const fixtures = await vi.importActual(
+ '../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
+ )
+ queuedEditHost = fixtures.queuedEditHost
+})
+
+function deferred() {
+ let resolve!: (value: T) => void
+ const promise = new Promise((accept) => {
+ resolve = accept
+ })
+ return { promise, resolve }
+}
+
+describe('mobile current acquisition belongs to the Save outcome owner', () => {
+ const { state, Harness, mount, sendRequest, notice, append, resolved } = mobileQueuedEditHarness()
+ it.each([
+ 'updated',
+ 'unchanged',
+ 'newer',
+ 'fresh-loss',
+ 'gone',
+ 'refused',
+ 'unknown',
+ 'late-unknown',
+ 'unresolved',
+ 'depart',
+ 'depart-equal'
+ ] as const)(
+ '%s does not return accepted current input before the delayed result',
+ async (mode) => {
+ const message = queuedDraft({ messageId: 'lease-race' })
+ const host = queuedEditHost(SESSION_ID, message)
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ const loss = deferred()
+ const freshLoss = deferred()
+ const release = deferred()
+ let expected = ''
+ let editId = ''
+ let acquires = 0
+ sendRequest.mockImplementation(async (method, params) => {
+ const fields = fieldsOf(params)
+ if (method === 'agentSession.queuedMessageEditHold' && fields.action === 'acquire') {
+ acquires++
+ expected = String(fields.expectedBodyFingerprint)
+ editId = String(fields.editId)
+ return ok(
+ acquires === 1
+ ? await loss.promise
+ : mode === 'fresh-loss'
+ ? await freshLoss.promise
+ : host.acquire(editId, expected)
+ )
+ }
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ await release.promise
+ if (mode === 'unknown' || mode === 'late-unknown') {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return mutationOk(
+ mode === 'refused' ? { status: 'not-editable', messageId: message.messageId } : decision
+ )
+ })
+ await act(async () => {
+ await state.hook!.queued.edit!(message.messageId)
+ })
+ act(() => state.hook!.queued.editor!.change('B'))
+ if (mode === 'unchanged') {
+ host.update({
+ messageId: message.messageId,
+ expectedBodyFingerprint: host.row!.fingerprint,
+ text: 'B'
+ })
+ }
+ let save!: Promise
+ act(() => {
+ save = state.hook!.queued.editor!.save()
+ })
+ const decision = host.update({
+ messageId: message.messageId,
+ expectedBodyFingerprint: expected,
+ text: 'B'
+ })
+ expect(decision.status).toBe(mode === 'unchanged' ? 'unchanged' : 'updated')
+ if (mode === 'newer' || mode === 'fresh-loss' || mode === 'gone' || mode === 'depart') {
+ act(() => {
+ state.hook!.queued.editor!.insertDictation!('C')
+ })
+ }
+ if (mode === 'gone') {
+ host.depart()
+ }
+ const negative = host.acquire(editId, expected)
+ expect(negative.status).toBe(mode === 'gone' ? 'gone' : 'changed')
+ if (mode === 'depart' || mode === 'depart-equal') {
+ act(() => state.renderer!.unmount())
+ state.renderer = undefined
+ }
+ if (mode !== 'late-unknown' && mode !== 'unresolved') {
+ await act(async () => loss.resolve(negative))
+ if (mode !== 'depart' && mode !== 'depart-equal') {
+ expect(state.hook!.queued.editor?.saving).toBe(true)
+ }
+ expect(append).not.toHaveBeenCalled()
+ expect(notice).not.toHaveBeenCalled()
+ }
+ await act(async () => {
+ release.resolve()
+ await save
+ })
+ if (mode === 'late-unknown') {
+ expect(state.hook!.queued.editor).toMatchObject({ saving: false })
+ await act(async () => loss.resolve(negative))
+ }
+ if (mode === 'newer' || mode === 'fresh-loss') {
+ expect(state.hook!.queued.editor).toMatchObject({ text: 'B C', saving: false })
+ expect(append).not.toHaveBeenCalled()
+ expect(acquires).toBe(2)
+ expect(resolved).not.toHaveBeenCalled()
+ if (mode === 'fresh-loss') {
+ host.depart()
+ await act(async () => freshLoss.resolve(host.acquire(editId, expected)))
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(append).toHaveBeenCalledWith('B C')
+ expect(notice).toHaveBeenCalledOnce()
+ } else {
+ act(() => state.hook!.queued.editor!.cancel())
+ expect(state.bottomText).toBe('')
+ }
+ } else if (
+ mode === 'gone' ||
+ mode === 'refused' ||
+ mode === 'unknown' ||
+ mode === 'late-unknown' ||
+ mode === 'depart'
+ ) {
+ if (mode !== 'depart') {
+ expect(state.hook!.queued.editor).toBeUndefined()
+ }
+ expect(append).toHaveBeenCalledOnce()
+ expect(append).toHaveBeenCalledWith(mode === 'gone' || mode === 'depart' ? 'B C' : 'B')
+ expect(notice).toHaveBeenCalledOnce()
+ } else {
+ if (mode !== 'depart-equal') {
+ expect(state.hook!.queued.editor).toBeUndefined()
+ }
+ expect(append).not.toHaveBeenCalled()
+ expect(notice).not.toHaveBeenCalled()
+ if (mode !== 'depart-equal') {
+ expect(resolved).toHaveBeenCalledOnce()
+ }
+ }
+ if (mode === 'unresolved') {
+ await act(async () => loss.resolve(negative))
+ }
+ expect(append).toHaveBeenCalledTimes(
+ ['gone', 'refused', 'unknown', 'late-unknown', 'depart', 'fresh-loss'].includes(mode)
+ ? 1
+ : 0
+ )
+ host.leases.dispose()
+ }
+ )
+ it.each(['unknown-changed', 'unknown-gone', 'pending-proof', 'rebase-loss'] as const)(
+ '%s delivers timed terminal loss through the actual phone lease into its owner',
+ async (mode) => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const message = queuedDraft({ messageId: 'timed' })
+ const host = queuedEditHost(SESSION_ID, message)
+ await mount(message)
+ await act(async () => state.hook!.queued.editor!.cancel())
+ const actions: string[] = []
+ const reply = deferred()
+ let decision: ReturnType
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method === 'agentSession.queuedMessageEditHold') {
+ const fields = fieldsOf(params)
+ const editId = String(fields.editId)
+ const key = { callerKey: 'client', editId }
+ actions.push(String(fields.action))
+ if (fields.action === 'release') {
+ host.leases.release(key, message.messageId)
+ return ok({ status: 'released' })
+ }
+ return ok(
+ fields.action === 'acquire'
+ ? host.acquire(editId, String(fields.expectedBodyFingerprint))
+ : host.leases.renew(key, message.messageId)
+ )
+ }
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ decision = host.update({
+ messageId: message.messageId,
+ expectedBodyFingerprint: host.row!.fingerprint,
+ text: '$review B'
+ })
+ expect(decision.status).toBe('updated')
+ await reply.promise
+ if (mode.startsWith('unknown')) {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return mutationOk(decision)
+ })
+ await act(async () =>
+ state.renderer!.update(
+ createElement(Harness, {
+ composerScopeKey: 'original-bottom',
+ imagesSupport: true,
+ skillsSupport: true
+ })
+ )
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!(message.messageId)
+ })
+ act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
+ act(() => state.hook!.queued.editor!.change('$review B'))
+ let save!: Promise
+ await act(async () => {
+ save = state.hook!.queued.editor!.save()
+ })
+ const scope = state.hook!.queued.editor!.scopeKey
+ if (mode === 'rebase-loss') {
+ act(() => {
+ state.hook!.queued.editor!.insertDictation!('C')
+ updateMobileNativeChatDraftInputs(scope, (input) => ({
+ ...input,
+ skills: [{ name: 'review', path: '/C/SKILL.md' }],
+ images: [{ id: 'new-C', path: '/C.png', previewUri: 'file:///C.png' }]
+ }))
+ })
+ }
+ if (mode !== 'pending-proof') {
+ await act(async () => {
+ reply.resolve()
+ await save
+ })
+ }
+ if (mode === 'unknown-gone') {
+ host.depart()
+ }
+ if (mode === 'rebase-loss') {
+ expect(state.hook!.queued.editor).toMatchObject({ text: '$review B C', saving: false })
+ expect(state.bottomText).toBe('occupied')
+ expect(host.leases.heldIds()).toEqual(new Set([message.messageId]))
+ host.update({
+ messageId: message.messageId,
+ expectedBodyFingerprint: host.row!.fingerprint,
+ text: 'rival'
+ })
+ }
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000)
+ })
+ if (mode === 'pending-proof') {
+ expect(state.hook!.queued.editor?.saving).toBe(true)
+ expect(notice).not.toHaveBeenCalled()
+ expect(state.bottomText).toBe('occupied')
+ await act(async () => {
+ reply.resolve()
+ await save
+ })
+ }
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(state.bottomText).toBe(
+ mode === 'pending-proof'
+ ? 'occupied'
+ : `occupied\n\n$review B${mode === 'rebase-loss' ? ' C' : ''}`
+ )
+ expect(notice).toHaveBeenCalledTimes(mode === 'pending-proof' ? 0 : 1)
+ if (mode === 'rebase-loss') {
+ expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
+ skills: [{ name: 'review', path: '/C/SKILL.md' }],
+ images: [{ id: 'new-C', path: '/C.png' }]
+ })
+ }
+ expect(actions).toEqual(
+ mode === 'rebase-loss'
+ ? ['acquire', 'acquire', 'release', 'renew', 'acquire', 'release']
+ : ['acquire', 'renew', 'acquire', 'release']
+ )
+ const count = sendRequest.mock.calls.length
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(120_000)
+ })
+ expect(sendRequest.mock.calls).toHaveLength(count)
+ host.leases.dispose()
+ }
+ )
+
+ it.each(['gone', 'held'] as const)(
+ 'initial phone transport failure then timed %s preserves owner outcomes',
+ async (status) => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const message = queuedDraft({ messageId: 'retry' })
+ const host = queuedEditHost(SESSION_ID, message)
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ let first = true
+ sendRequest.mockImplementation(async (method, params) => {
+ const fields = fieldsOf(params)
+ if (method !== 'agentSession.queuedMessageEditHold') {
+ return readOrHoldReply(method, params)
+ }
+ if (fields.action === 'release') {
+ return ok({ status: 'released' })
+ }
+ if (first) {
+ first = false
+ throw new Error('offline')
+ }
+ return ok(host.acquire(String(fields.editId), String(fields.expectedBodyFingerprint)))
+ })
+ await act(async () => {
+ await state.hook!.queued.edit!(message.messageId)
+ })
+ act(() => state.hook!.queued.editor!.change('B'))
+ if (status === 'gone') {
+ host.depart()
+ }
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000)
+ })
+ if (status === 'gone') {
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(append).toHaveBeenCalledOnce()
+ expect(append).toHaveBeenCalledWith('B')
+ expect(notice).toHaveBeenCalledOnce()
+ } else {
+ expect(state.hook!.queued.editor).toMatchObject({ text: 'B', saving: false })
+ expect(append).not.toHaveBeenCalled()
+ act(() => state.hook!.queued.editor!.cancel())
+ }
+ host.leases.dispose()
+ warn.mockRestore()
+ }
+ )
+})
diff --git a/mobile/src/session/mobile-queued-edit-presentation.test.tsx b/mobile/src/session/mobile-queued-edit-presentation.test.tsx
new file mode 100644
index 00000000000..f41587687c2
--- /dev/null
+++ b/mobile/src/session/mobile-queued-edit-presentation.test.tsx
@@ -0,0 +1,594 @@
+import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
+import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
+import type { AcpCommandOptionsFixtureModule } from '../../../src/shared/mobile-queued-edit-host.test-fixture-contract'
+import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
+import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
+import { createElement, type ReactNode } from 'react'
+import { act } from 'react-test-renderer'
+import { describe, expect, it, vi } from 'vitest'
+import { ScrollView, TextInput } from 'react-native'
+import { ActionSheetModal } from '../components/ActionSheetModal'
+import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
+import { MobileNativeChatQueuedMessages } from './native-chat/input/MobileNativeChatQueuedMessages'
+import {
+ MobileNativeChatComposer,
+ MobileNativeChatDraftComposer
+} from './native-chat/composer/MobileNativeChatComposer'
+import { MobileNativeChatComposerMenu } from './native-chat/composer/MobileNativeChatComposerMenu'
+import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
+import { useMobileNativeChatDrafts } from './native-chat/composer/use-mobile-native-chat-drafts'
+import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge'
+import { mobileNativeChatScopeKey } from './native-chat/mobile-native-chat-scope-key'
+import { structuredSendResultFixture } from './structured-agent-send-result.test-fixture'
+import { useMobileNativeChatFileAttachments } from './native-chat/composer/use-mobile-native-chat-file-attachments'
+import { useMobileNativeChatImageAttachments } from './native-chat/composer/use-mobile-native-chat-image-attachments'
+import {
+ useMobileNativeChatDraft,
+ setMobileNativeChatDraftText
+} from './native-chat/composer/mobile-native-chat-draft-store'
+import {
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import {
+ queuedDraft,
+ SESSION_ID,
+ mutationOk
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+
+const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
+vi.mock('../platform/media-picker', () => ({ useMediaPicker: () => picker }))
+vi.mock('../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' }))
+vi.mock('react-native-reanimated', async () => {
+ const { useRef } = await import('react')
+ return {
+ default: { ScrollView: 'ScrollView' },
+ useAnimatedRef: () => useRef(null),
+ useSharedValue: (value: unknown) => useRef({ value }).current
+ }
+})
+vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
+vi.mock('../components/mounted-bottom-drawer', () => ({ MountedBottomDrawer: 'BottomDrawer' }))
+vi.mock('../components/bottom-drawer-modal-host-scope', () => ({
+ useBottomDrawerModalHost: () => null
+}))
+
+const { queuedEditHost } = await vi.importActual(
+ '../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
+)
+const { AcpStructuredOptions } = await vi.importActual(
+ '../../../src/main/acp/acp-structured-options'
+)
+
+describe('phone inline editor presentation', () => {
+ const { state, Harness, mount, sendRequest, error, resolved, client } = mobileQueuedEditHarness()
+ async function rows(
+ message: Parameters[0],
+ agent = 'codex',
+ sessionId = SESSION_ID,
+ catalog: {
+ reported: { name: string; kind: 'skill' | 'command'; path?: string }[]
+ discovery?: NativeChatSkillDiscoverySnapshot
+ } = {
+ reported: []
+ },
+ extra?: (hook: NonNullable) => ReactNode,
+ composerScopeKey = 'original-bottom'
+ ) {
+ await mount(message, true, agent, sessionId)
+ act(() => state.hook!.queued.editor!.cancel())
+ resolved.mockClear()
+ const renderContent: NonNullable[0]['renderContent']> = (hook) =>
+ createElement(
+ MobileQueuedMessageComposerContext.Provider,
+ {
+ value: {
+ agent,
+ structured: {
+ catalog: { reported: catalog.reported, conversationCommands: [] },
+ onSlashMenuOpen: () => {},
+ files: [],
+ onRemoveFile: () => {}
+ },
+ skillDiscovery: catalog.discovery,
+ filePaths: [],
+ onNeedFiles: undefined,
+ onError: error,
+ onMicPress: undefined,
+ micActive: false,
+ dictationMode: undefined,
+ onMicPressIn: () => {},
+ onMicPressOut: () => {}
+ }
+ },
+ createElement(MobileNativeChatQueuedMessages, {
+ cards: hook.queued.cards,
+ onEdit: hook.queued.edit,
+ editor: hook.queued.editor
+ }),
+ extra?.(hook)
+ )
+ const rerender = async () =>
+ act(async () =>
+ state.renderer!.update(
+ createElement(Harness, {
+ sessionId,
+ agent,
+ renderContent,
+ skillsSupport: true,
+ imagesSupport: true,
+ composerScopeKey
+ })
+ )
+ )
+ await rerender()
+ const root = () => state.renderer!.root
+ const button = (label: string) =>
+ root().findAll(
+ (node) =>
+ node.props.accessibilityLabel === label && typeof node.props.onPress === 'function'
+ )[0]!
+ const field = () =>
+ root()
+ .findByType(MobileQueuedMessageComposer)
+ .find((node) => node.type === TextInput && node.props.multiline === true)
+ const open = async () => {
+ await act(async () => button('More actions').props.onPress())
+ const sheet = root().find(
+ (node) =>
+ node.type === ActionSheetModal && node.props.actions?.[0]?.label === 'Edit message'
+ )
+ await act(async () => sheet.props.actions[0].onPress())
+ expect(root().findAllByType(MobileQueuedMessageComposer)).toHaveLength(1)
+ expect(root().findAllByType(MobileNativeChatComposer)).toHaveLength(extra ? 2 : 1)
+ }
+ await open()
+ return { root, button, field, rerender, open }
+ }
+ it('gives the short image editor and open picker the available queue scroll space, separate from the ordinary draft', async () => {
+ const message = queuedDraft({
+ messageId: 'photo-layout',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [
+ { type: 'text', text: 'short edit' },
+ { type: 'image-ref', url: 'https://host/photo.png', alt: 'photo' }
+ ]
+ }
+ })
+ const catalog = {
+ reported: Array.from({ length: 6 }, (_, i) => ({
+ name: `skill-${i}`,
+ kind: 'skill' as const,
+ path: `/skills/${i}/SKILL.md`
+ }))
+ }
+ const { root, button } = await rows(message, 'codex', SESSION_ID, catalog, () =>
+ createElement(MobileNativeChatDraftComposer, {
+ draftKey: 'original-bottom',
+ draftScopeKey: 'original-bottom',
+ agent: 'codex',
+ structured: {
+ catalog: { ...catalog, conversationCommands: [] },
+ onSlashMenuOpen: () => {},
+ files: [],
+ onRemoveFile: () => {}
+ },
+ onChangeText: (text) => setMobileNativeChatDraftText('original-bottom', text),
+ onSend: async () => true,
+ sendSurfaceId: 'original-bottom',
+ getSendCompletionGeneration: () => 0,
+ getComposerEditGeneration: () => 0
+ })
+ )
+ const { snapshotEvent } =
+ await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ act(() => {
+ setMobileNativeChatDraftText('original-bottom', 'Bottom draft stays here.')
+ state.listener?.(
+ snapshotEvent({
+ queuedMessages: [message, queuedDraft({ messageId: 'neighbor', position: 2 })],
+ runningTurn: true
+ })
+ )
+ })
+ const style = (value: unknown): Record => Object.assign({}, ...[value].flat())
+ const queue = () => root().findByType(MobileNativeChatQueuedMessages)
+ const scroll = () =>
+ queue().find((node) => node.type === ScrollView && node.props.onContentSizeChange)
+ const box = () => root().findByProps({ testID: 'queued-box' })
+ const editor = () => root().findByType(MobileQueuedMessageComposer)
+ const bottom = () => root().findByType(MobileNativeChatDraftComposer)
+ expect(editor().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
+ expect(queue().findAllByProps({ testID: 'queued-card-row' })).toHaveLength(2)
+ // Every boundary down to the scrollport must yield to the keyboard/bottom siblings.
+ for (const node of [box().parent!, box(), scroll().parent!, scroll()]) {
+ expect(style(node.props.style)).toMatchObject({ flexShrink: 1, minHeight: 0 })
+ }
+ expect(style(scroll().props.style).maxHeight).toBeUndefined()
+ expect(style(box().parent!.props.style).marginBottom).toBe(0)
+ expect(style(box().props.style).paddingBottom).toBe(0)
+ expect(queue().findAllByType(MobileNativeChatDraftComposer)).toHaveLength(0)
+ const field = editor().findByType(TextInput)
+ act(() => {
+ field.props.onChangeText('/')
+ field.props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
+ })
+ const menuScroll = root().findByType(MobileNativeChatComposerMenu).findByType(ScrollView)
+ expect(style(menuScroll.props.style).maxHeight).toBe(300)
+ expect(menuScroll.props.nestedScrollEnabled).toBe(true)
+ expect(menuScroll.props.keyboardShouldPersistTaps).toBe('always')
+ const scrollTo = vi.fn()
+ scroll().props.ref.current = { scrollTo, flashScrollIndicators: vi.fn() }
+ act(() => {
+ scroll().props.onLayout({ nativeEvent: { layout: { height: 280 } } })
+ scroll().props.onContentSizeChange(360, 800)
+ editor().parent!.props.onLayout({
+ nativeEvent: { layout: { x: 0, y: 0, width: 360, height: 620 } }
+ })
+ })
+ expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ y: 0, animated: false })
+ act(() => scroll().props.onScroll({ nativeEvent: { contentOffset: { y: 120 } } }))
+ expect(scrollTo).toHaveBeenCalledTimes(1)
+ await act(async () => button('$skill-5').props.onPress())
+ expect(state.hook!.queued.editor?.text).toBe('$skill-5 ')
+ expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual([
+ { name: 'skill-5', path: '/skills/5/SKILL.md' }
+ ])
+ expect(editor().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
+ expect(bottom().findByType(TextInput).props.value).toBe('Bottom draft stays here.')
+ await act(async () => button('Cancel editing').props.onPress())
+ expect(style(scroll().props.style).maxHeight).toBe(160)
+ expect(style(box().parent!.props.style).marginBottom).toBeLessThan(0)
+ expect(bottom().findByType(TextInput).props.value).toBe('Bottom draft stays here.')
+ act(() => {
+ bottom().findByType(TextInput).props.onChangeText('/')
+ bottom()
+ .findByType(TextInput)
+ .props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
+ })
+ const ordinaryMenu = bottom().findByType(MobileNativeChatComposerMenu).findByType(ScrollView)
+ expect(style(ordinaryMenu.props.style).maxHeight).toBe(300)
+ expect(ordinaryMenu.props.nestedScrollEnabled).toBeFalsy()
+ expect(
+ sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toBe(false)
+ })
+ it('hands back into the main captured Send path, keeps pending files, and restores a rejected complete draft', async () => {
+ const { snapshotEvent, ok, fieldsOf } =
+ await import('./use-mobile-structured-agent-session-queued.test-fixture')
+ const scope = mobileNativeChatScopeKey('host', 'worktree', 'handoff')!
+ const message = queuedDraft({
+ messageId: 'pending-files',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [{ type: 'text', text: '$review intent' }],
+ skills: [{ name: 'review', path: '/edit/SKILL.md' }]
+ }
+ })
+ function Bottom({ session }: { session: NonNullable }) {
+ const drafts = useMobileNativeChatDrafts({
+ hostId: 'host',
+ worktreeId: 'worktree',
+ tabId: 'handoff',
+ sessionId: SESSION_ID,
+ messages: [],
+ transcriptSettled: true
+ })
+ const bridge = useMobileStructuredNativeChatSendBridge({
+ ...drafts,
+ agent: 'codex',
+ sendStructured: session.sendWithOutcome,
+ onSendError: error
+ })
+ const text = useMobileNativeChatDraft(scope)
+ const files = useMobileNativeChatFileAttachments({
+ client,
+ sessionId: SESSION_ID,
+ scopeKey: scope,
+ enabled: true,
+ showToast: error
+ })
+ const images = useMobileNativeChatImageAttachments({
+ client,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: scope,
+ enabled: true,
+ structuredNativeChat: true,
+ showToast: error,
+ onSendError: error,
+ baseSend: bridge.sendWithOutcome,
+ readSeededLaunchDraft: () => null,
+ files: files.files,
+ onFilesSent: files.removeFiles
+ })
+ return createElement(MobileNativeChatComposer, {
+ value: text,
+ agent: 'codex',
+ draftScopeKey: scope,
+ onChangeText: drafts.setComposerText,
+ onSend: images.sendNativeChat,
+ sendSurfaceId: scope,
+ getSendCompletionGeneration: () => 0,
+ getComposerEditGeneration: drafts.getComposerEditGeneration,
+ attachments: images.attachments,
+ structured: {
+ catalog: { reported: [], conversationCommands: [] },
+ onSlashMenuOpen: () => {},
+ files: files.files,
+ onRemoveFile: () => {}
+ }
+ })
+ }
+ const { root, button, field } = await rows(
+ message,
+ 'codex',
+ SESSION_ID,
+ { reported: [{ name: 'later', kind: 'skill', path: '/later/SKILL.md' }] },
+ (hook) => createElement(Bottom, { session: hook }),
+ scope
+ )
+ act(() => {
+ field().props.onChangeText('$review intent then $la')
+ field().props.onSelectionChange({ nativeEvent: { selection: { start: 23, end: 23 } } })
+ })
+ await act(async () => button('$later').props.onPress())
+ act(() => {
+ setMobileNativeChatDraftText(scope, '$prior occupied')
+ updateMobileNativeChatDraftInputs(scope, () => ({
+ images: [{ id: 'prior-image', path: '/prior.png', previewUri: 'file:///prior.png' }],
+ files: [
+ {
+ id: 'prior-file',
+ path: '/prior.txt',
+ name: 'prior.txt',
+ mime: 'text/plain',
+ byteLength: 1
+ }
+ ],
+ skills: [{ name: 'prior', path: '/prior/SKILL.md' }]
+ }))
+ updateMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey, (input) => ({
+ ...input,
+ images: [{ id: 'edit-image', path: '/added.png', previewUri: 'file:///added.png' }]
+ }))
+ })
+ let release = () => {}
+ const held = new Promise((resolve) => {
+ release = resolve
+ })
+ let started = () => {}
+ const start = new Promise((resolve) => {
+ started = resolve
+ })
+ picker.pickFiles.mockImplementation(async function* () {
+ yield { name: 'late.txt', mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
+ })
+ let rejected = false
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method.endsWith('uploadStart')) {
+ started()
+ await held
+ return ok({ uploadId: 'pending-upload' })
+ }
+ if (method.endsWith('uploadCommit')) {
+ return ok({ path: '/late.txt', name: 'late.txt', byteLength: 1 })
+ }
+ if (method.endsWith('uploadChunk')) {
+ return ok(null)
+ }
+ if (method === 'agentSession.send') {
+ if (!rejected) {
+ rejected = true
+ return {
+ id: 'send-refusal',
+ ok: false,
+ error: { code: 'unauthorized', message: 'Send refused before execution' }
+ }
+ }
+ return mutationOk(structuredSendResultFixture('accepted'))
+ }
+ return readOrHoldReply(method, params)
+ })
+ const inline = root()
+ .findByType(MobileQueuedMessageComposer)
+ .findByType(MobileNativeChatComposer)
+ await act(async () => {
+ inline.props.structured.onAttachFiles()
+ await start
+ })
+ const beforeBottom = root()
+ .findAllByType(MobileNativeChatComposer)
+ .find((node) => node.props.draftScopeKey === scope)!
+ act(() => state.listener?.(snapshotEvent({ queuedMessages: [] })))
+ expect(root().findByType(MobileNativeChatComposer)).toBe(beforeBottom)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ const pressSend = () =>
+ root()
+ .findAll(
+ (node) =>
+ node.props.accessibilityLabel === 'Send message' &&
+ typeof node.props.onPress === 'function'
+ )[0]!
+ .props.onPress()
+ await act(async () => pressSend())
+ expect(sendRequest.mock.calls.some(([method]) => method === 'agentSession.send')).toBe(false)
+ await act(async () => {
+ release()
+ await vi.waitFor(() => expect(readMobileNativeChatDraftInputs(scope).pending ?? 0).toBe(0))
+ })
+ await act(async () => pressSend())
+ expect(root().findByType(MobileNativeChatComposer)).toBe(beforeBottom)
+ expect(root().findByType(TextInput).props.value).toBe(
+ '$prior occupied\n\n$review intent then $later '
+ )
+ expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([
+ { name: 'prior', path: '/prior/SKILL.md' },
+ { name: 'review', path: '/edit/SKILL.md' },
+ { name: 'later', path: '/later/SKILL.md' }
+ ])
+ await act(async () => pressSend())
+ const requests = sendRequest.mock.calls.filter(([method]) => method === 'agentSession.send')
+ expect(requests).toHaveLength(2)
+ expect(requests[1]![1]).toMatchObject({ body: fieldsOf(requests[0]![1]).body })
+ expect(requests[0]![1]).toMatchObject({
+ body: {
+ blocks: [
+ {
+ type: 'text',
+ text: '$prior occupied\n\n$review intent then $later\n@/prior.txt @/late.txt'
+ },
+ { type: 'image-ref', path: '/prior.png' },
+ { type: 'image-ref', path: '/added.png' }
+ ],
+ skills: [
+ { name: 'prior', path: '/prior/SKILL.md' },
+ { name: 'review', path: '/edit/SKILL.md' },
+ { name: 'later', path: '/later/SKILL.md' }
+ ]
+ }
+ })
+ expect(readMobileNativeChatDraftInputs(scope).files).toEqual([])
+ expect(readMobileNativeChatDraftInputs(scope).images).toEqual([])
+ })
+
+ it('refuses a stale control pick but saves a typed namesake literally when its menu is closed', async () => {
+ const message = queuedDraft({ messageId: 'namesake' })
+ const { root, button, field } = await rows(message, 'claude', SESSION_ID, {
+ reported: [{ name: 'model', kind: 'skill', path: '/A/SKILL.md' }]
+ })
+ act(() => field().props.onChangeText('/'))
+ act(() => field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } }))
+ const stale = root().findByType(MobileNativeChatComposerMenu).props.onPick
+ await act(async () => button('/model').props.onPress())
+ const key = state.hook!.queued.editor!.scopeKey
+ expect(readMobileNativeChatDraftInputs(key).skills).toHaveLength(1)
+ act(() => stale({ kind: 'command', token: '/model', name: 'model', id: 'command:model' }))
+ expect(error).toHaveBeenLastCalledWith("Commands can't be saved in a queued message.")
+ expect(state.hook!.queued.editor!.text).toBe('/model ')
+ act(() => field().props.onChangeText(''))
+ act(() => field().props.onChangeText('/model literal'))
+ expect(readMobileNativeChatDraftInputs(key).skills).toEqual([])
+ act(() =>
+ field().props.onSelectionChange({ nativeEvent: { selection: { start: 14, end: 14 } } })
+ )
+ expect(root().findAllByType(MobileNativeChatComposerMenu)).toHaveLength(0)
+ await act(async () => button('Save edited message').props.onPress())
+ expect(error).toHaveBeenCalledOnce()
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toHaveLength(1)
+ expect(
+ sendRequest.mock.calls.some(([method]) =>
+ /(?:\.send$|conversationCommand|goal|resume|pty)/i.test(method)
+ )
+ ).toBe(false)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ })
+
+ it('an image-only attributed card reaches the actual inline composer and no-op Save retains its image and sender', async () => {
+ const message = queuedDraft({
+ messageId: 'photo-only',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [{ type: 'image-ref', url: 'https://host/photo.png', alt: 'photo' }],
+ from: { kind: 'agent', senders: [], orchestration: null }
+ }
+ })
+ const { root, button } = await rows(message)
+ expect(root().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
+ await act(async () => button('Save edited message').props.onPress())
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(
+ sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toBe(false)
+ expect(state.hook!.queued.cards[0]?.images).toEqual(message.body.blocks)
+ expect(state.hook!.queued.cards[0]?.attribution).not.toBeNull()
+ expect(state.bottomText).toBe('')
+ })
+ it('saves a scanned model skill picked through More and Edit without dispatching a host command', async () => {
+ const options = new AcpStructuredOptions()
+ options.adoptCommands([{ name: 'model', description: 'Choose the model' }])
+ const reported = options.readCommands() ?? []
+ expect(reported).toEqual([{ name: 'model', kind: 'command', description: 'Choose the model' }])
+ const message = queuedDraft({
+ messageId: 'scanned-model',
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'seed' }] }
+ })
+ const host = queuedEditHost(SESSION_ID, message)
+ try {
+ const { root, button, field } = await rows(message, 'opencode2', SESSION_ID, {
+ reported,
+ discovery: {
+ status: 'ready',
+ skills: [
+ {
+ id: 'repo:model',
+ name: 'model',
+ description: 'Explain the domain model',
+ providers: ['agent-skills'],
+ sourceKind: 'repo',
+ sourceLabel: 'Repo',
+ rootPath: '/workspace/.agents/skills',
+ directoryPath: '/workspace/.agents/skills/model',
+ skillFilePath: '/workspace/.agents/skills/model/SKILL.md',
+ installed: true,
+ updatedAt: null
+ }
+ ]
+ }
+ })
+ sendRequest.mockImplementation(async (method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? mutationOk(host.update(QueuedMessageUpdateParams.parse(params)))
+ : readOrHoldReply(method, params)
+ )
+ act(() => field().props.onChangeText('/'))
+ act(() =>
+ field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
+ )
+ const menu = root().findByType(MobileNativeChatComposerMenu)
+ expect(menu.props.rows.filter((row: { token?: string }) => row.token === '/model')).toEqual([
+ expect.objectContaining({
+ kind: 'skill',
+ id: 'skill:model',
+ token: '/model',
+ sources: [
+ { sourceKind: 'repo', skillFilePath: '/workspace/.agents/skills/model/SKILL.md' }
+ ]
+ })
+ ])
+ expect(
+ menu.props.rows.find((row: { token?: string }) => row.token === '/model')
+ ).not.toHaveProperty('path')
+ await act(async () => button('/model').props.onPress())
+ expect(state.hook!.queued.editor?.text).toBe('/model ')
+ expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual(
+ []
+ )
+ expect(error.mock.calls).toEqual([])
+ await act(async () => button('Save edited message').props.onPress())
+ expect(
+ sendRequest.mock.calls.some(([method]) =>
+ /(?:\.send$|conversationCommand|goal|resume|pty|setOption)/i.test(method)
+ )
+ ).toBe(false)
+ expect(error.mock.calls).toEqual([])
+ expect(
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ ).toHaveLength(1)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(host.row!.body.blocks).toEqual([{ type: 'text', text: '/model' }])
+ expect(host.row!.body.skills).toBeUndefined()
+ } finally {
+ host.leases.dispose()
+ }
+ })
+})
diff --git a/mobile/src/session/mobile-queued-edit-trigger-scaling.test.tsx b/mobile/src/session/mobile-queued-edit-trigger-scaling.test.tsx
new file mode 100644
index 00000000000..1627fbecc44
--- /dev/null
+++ b/mobile/src/session/mobile-queued-edit-trigger-scaling.test.tsx
@@ -0,0 +1,136 @@
+import { mobileQueuedEditHarness, withText } from './mobile-queued-edit-hook.test-fixture'
+import { countedQueuedEditPublication } from '../../../src/shared/queued-edit-publication.test-fixture'
+import * as publication from '../../../src/shared/queued-message-edit-publication'
+import * as eligibility from '../../../src/shared/queued-message-edit-command'
+import { createElement } from 'react'
+import { act, create } from 'react-test-renderer'
+import { afterEach, expect, it, vi } from 'vitest'
+import {
+ queuedDraft,
+ snapshotEvent
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+import { useMobileNativeChatComposerMenu } from './native-chat/composer/use-mobile-native-chat-composer-menu'
+import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
+import type { MobileComposerStructuredCatalog } from './native-chat/composer/mobile-native-chat-composer-menu'
+afterEach(() => vi.restoreAllMocks())
+const { state, mount, sendRequest } = mobileQueuedEditHarness()
+it.each([10, 100])(
+ 'actual phone hook bounds publication-key reads with %i fresh Q/C/R rows',
+ async (n) => {
+ const counter = countedQueuedEditPublication()
+ vi.spyOn(publication, 'queuedEditPublicationKey').mockImplementation(counter.key)
+ const message = queuedDraft({ messageId: 'target' })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ const rows = () => [
+ ...Array.from({ length: n - 1 }, (_, i) => queuedDraft({ messageId: `other-${i}` })),
+ message
+ ]
+ const submissions = () =>
+ Array.from({ length: n }, (_, i) => ({
+ clientMessageId: `s${i}`,
+ queuedMessageId: `unused-${i}`,
+ fence: 3,
+ payloadFingerprint: 'other',
+ dispatchState: 'pending' as const,
+ providerItemId: null,
+ reason: null,
+ submittedAt: 1,
+ resolvedAt: null
+ }))
+ counter.reset()
+ act(() =>
+ state.listener?.(snapshotEvent({ queuedMessages: rows(), submissions: submissions() }))
+ )
+ expect(counter.reads).toBe(0)
+ await act(async () => {
+ await state.hook!.queued.edit!('target')
+ })
+ counter.reset()
+ act(() =>
+ state.listener?.(snapshotEvent({ queuedMessages: rows(), submissions: submissions() }))
+ )
+ expect(counter.reads).toBeGreaterThanOrEqual(3 * n)
+ expect(counter.reads).toBeLessThanOrEqual(3 * n + 2)
+ expect(state.hook!.queued.editor).toBeDefined()
+ act(() => state.hook!.queued.editor!.change('saved'))
+ sendRequest.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('lost')))
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ counter.reset()
+ act(() =>
+ state.listener?.(
+ snapshotEvent({
+ queuedMessages: [
+ ...rows().slice(0, -1),
+ { ...message, body: withText(message.body, 'saved') }
+ ],
+ submissions: submissions()
+ })
+ )
+ )
+ expect(counter.reads).toBeLessThanOrEqual(3 * n + 2)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ }
+)
+it.each([10, 100])(
+ 'actual phone menu reuses one eligibility preparation across query/all-token paths for %i rows',
+ async (n) => {
+ const prepare = vi.spyOn(eligibility, 'prepareQueuedMessageEditText')
+ const reported = () =>
+ Array.from({ length: n }, (_, i) => ({ name: `provider-${i}`, kind: 'command' as const }))
+ const catalog: MobileComposerStructuredCatalog = {
+ reported: reported(),
+ conversationCommands: []
+ }
+ let menu!: ReturnType
+ function Menu({
+ value = '',
+ agent = 'claude',
+ editing = true,
+ structured = catalog
+ }: {
+ value?: string
+ agent?: string
+ editing?: boolean
+ structured?: MobileComposerStructuredCatalog
+ }) {
+ menu = useMobileNativeChatComposerMenu({
+ value,
+ agent,
+ structuredCatalog: structured,
+ filePaths: [],
+ onChangeText: () => {},
+ focusField: () => {},
+ editing
+ })
+ return null
+ }
+ let renderer!: ReturnType
+ await act(async () => {
+ renderer = create(createElement(Menu))
+ })
+ try {
+ expect(prepare).toHaveBeenCalledTimes(1)
+ for (const value of ['/', '/p', '/provider', '/provider-9']) {
+ act(() => renderer.update(createElement(Menu, { value })))
+ act(() => menu.onSelectionChange({ start: value.length, end: value.length }))
+ }
+ expect(menu.rows.length).toBeGreaterThan(0)
+ expect(prepare).toHaveBeenCalledTimes(1)
+ act(() => renderer.update(createElement(Menu, { value: '/', editing: false })))
+ expect(prepare).toHaveBeenCalledTimes(1)
+ act(() =>
+ renderer.update(
+ createElement(Menu, { value: '/', structured: { ...catalog, reported: reported() } })
+ )
+ )
+ expect(prepare).toHaveBeenCalledTimes(2)
+ act(() => renderer.update(createElement(Menu, { value: '/', agent: 'codex' })))
+ expect(prepare).toHaveBeenCalledTimes(3)
+ } finally {
+ act(() => renderer.unmount())
+ }
+ }
+)
diff --git a/mobile/src/session/mobile-queued-message-composer-context.ts b/mobile/src/session/mobile-queued-message-composer-context.ts
new file mode 100644
index 00000000000..659442a19df
--- /dev/null
+++ b/mobile/src/session/mobile-queued-message-composer-context.ts
@@ -0,0 +1,18 @@
+import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
+import { createContext } from 'react'
+import type { MobileNativeChatStructuredComposer } from './native-chat/composer/MobileNativeChatComposer'
+
+export const MobileQueuedMessageComposerContext = createContext<{
+ agent: string | null
+ structured: MobileNativeChatStructuredComposer | null
+ skillDiscovery?: NativeChatSkillDiscoverySnapshot
+ onNeedSkills?: () => void
+ filePaths: string[]
+ onNeedFiles: ((query: string) => void) | undefined
+ onError: (text: string) => void
+ onMicPress: (() => void) | undefined
+ micActive: boolean
+ dictationMode: string | undefined
+ onMicPressIn: () => void
+ onMicPressOut: () => void
+} | null>(null)
diff --git a/mobile/src/session/mobile-queued-message-edit-draft.ts b/mobile/src/session/mobile-queued-message-edit-draft.ts
new file mode 100644
index 00000000000..3360ff120c4
--- /dev/null
+++ b/mobile/src/session/mobile-queued-message-edit-draft.ts
@@ -0,0 +1,238 @@
+import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease'
+import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation'
+import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards'
+import {
+ mobileQueuedEditValueKey,
+ sameMobileQueuedEditImage
+} from './mobile-queued-message-edit-value'
+import { appendBufferedDictation } from '../terminal/terminal-live-dictation-routing'
+import type {
+ MobileNativeChatDraftInputs,
+ MobileNativeChatDraftDestination
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import type { AgentSessionQueuedMessage } from '../../../src/shared/agent-session-wire'
+import type { AgentJournalSubmission } from '../../../src/shared/agent-session-journal-types'
+import type { RpcClient } from '../transport/rpc-client'
+import type { MobileQueuedEditLease } from './mobile-queued-message-edit-lease'
+import { pickedSkillsInText } from '../../../src/shared/structured-agent-session-send-mutation'
+import {
+ queuedEditKeptImages,
+ queuedEditTextForKeptImages
+} from '../../../src/shared/queued-message-edit'
+import { appendReturnedDraftText } from '../../../src/shared/returned-draft-text'
+import {
+ closeMobileNativeChatEditInputs,
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
+import { nativeChatTextWithFileReferences } from './native-chat/composer/mobile-native-chat-file-attachment'
+
+export type MobileQueuedMessageInlineEditor = {
+ messageId: string
+ scopeKey: string
+ client: RpcClient
+ sessionId: string
+ imagesCapable: boolean
+ text: string
+ saving: boolean
+ canSave: boolean
+ insertDictation?: (text: string) => boolean
+ change: (text: string) => void
+ save: () => Promise
+ removeImage: (id: string) => void
+ cancel: () => void
+}
+
+export type MobileQueuedEditAttempt = {
+ phase: 'pending' | 'unknown'
+ expected: string
+ fingerprint: string
+ body: AgentSessionQueuedMessage['body']
+ text: string
+ inputs: MobileNativeChatDraftInputs
+ key: string
+}
+export function mobileQueuedEditSaving(edit: MobileQueuedEditDraft): boolean {
+ return edit.attempt?.phase === 'pending'
+}
+
+export type MobileQueuedEditDraft = {
+ scope: string
+ client: RpcClient
+ sessionId: string
+ published: {
+ cards: readonly MobileQueuedMessageCard[]
+ messages: readonly AgentSessionQueuedMessage[] | null
+ submissions: readonly AgentJournalSubmission[]
+ }
+ scopeKey: string
+ destination: string | null
+ handBackText: ((text: string) => boolean) | undefined
+ messageId: string
+ body: AgentSessionQueuedMessage['body']
+ text: string
+ fingerprint: string
+ baseKey: string
+ kept: {
+ image: MobileNativeChatDraftInputs['images'][number]
+ block: ReturnType[number]['block']
+ }[]
+ uncertain: boolean
+ leaseLoss?: QueuedEditLeaseLoss
+ attempt?: MobileQueuedEditAttempt
+ closed: boolean
+ pendingClose: boolean
+ lease: MobileQueuedEditLease
+}
+
+export function closeMobileQueuedEditDraft(
+ edit: MobileQueuedEditDraft,
+ handBack: boolean,
+ notice?: (text: string) => void
+): void {
+ if (edit.closed) {
+ return
+ }
+ edit.closed = true
+ edit.lease.end()
+ if (handBack) {
+ const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
+ const dirty = edit.uncertain || mobileQueuedEditValueKey(edit.text, inputs) !== edit.baseKey
+ const kept = edit.kept.filter((entry) =>
+ inputs.images.some((image) => sameMobileQueuedEditImage(entry.image, image))
+ )
+ const text = dirty
+ ? queuedEditTextForKeptImages(
+ edit.text,
+ inputs.images.map(({ id }) => id),
+ inputs.images
+ .filter((image) => !kept.some((entry) => sameMobileQueuedEditImage(entry.image, image)))
+ .map(({ id }) => id)
+ )
+ : ''
+ if (dirty && edit.destination) {
+ setMobileNativeChatDraftText(edit.destination, (before) =>
+ appendReturnedDraftText(before, text)
+ )
+ } else if (dirty) {
+ edit.handBackText?.(text)
+ }
+ closeMobileNativeChatEditInputs(
+ edit.scopeKey,
+ edit.destination ?? undefined,
+ kept.map(({ image }) => image),
+ !dirty
+ )
+ if (dirty) {
+ notice?.('Your edit is in the chat box.')
+ }
+ } else {
+ closeMobileNativeChatEditInputs(edit.scopeKey)
+ }
+}
+
+export function serializeMobileQueuedEdit(
+ edit: MobileQueuedEditDraft,
+ imagesCapable = false,
+ skillsCapable = false
+) {
+ const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
+ return {
+ text: nativeChatTextWithFileReferences(
+ edit.text,
+ inputs.files.flatMap(({ path }) => (path ? [{ path }] : []))
+ ),
+ ...(imagesCapable
+ ? {
+ images: inputs.images.map(
+ (image) =>
+ edit.kept.find((entry) => sameMobileQueuedEditImage(entry.image, image))?.block ?? {
+ type: 'image-ref' as const,
+ path: image.path
+ }
+ )
+ }
+ : {}),
+ ...(skillsCapable ? { skills: pickedSkillsInText(edit.text, inputs.skills, ['$', '/']) } : {})
+ }
+}
+
+export function removeMobileQueuedEditImage(edit: MobileQueuedEditDraft, id: string): void {
+ const images = readMobileNativeChatDraftInputs(edit.scopeKey).images
+ const kept = images.filter((image) => image.id !== id)
+ edit.text = queuedEditTextForKeptImages(
+ edit.text,
+ images.map(({ id }) => id),
+ kept.map(({ id }) => id)
+ )
+ updateMobileNativeChatDraftInputs(edit.scopeKey, (current) => ({
+ ...current,
+ images: kept
+ }))
+}
+
+export function mobileQueuedEditSaveHeld(
+ edit: MobileQueuedEditDraft,
+ imagesCapable = false
+): boolean {
+ const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
+ return (
+ (inputs.pending ?? 0) > 0 ||
+ inputs.files.some(({ path }) => path === null) ||
+ (!imagesCapable &&
+ JSON.stringify(inputs.images) !== JSON.stringify(edit.kept.map(({ image }) => image)))
+ )
+}
+
+export function seedMobileQueuedEditInputs(
+ scopeKey: string,
+ body: AgentSessionQueuedMessage['body']
+): void {
+ updateMobileNativeChatDraftInputs(scopeKey, () => ({
+ skills: body.skills ?? [],
+ files: [],
+ images: queuedEditKeptImages(body).map(({ id, block }) => ({
+ id,
+ path: block.path ?? block.url ?? '',
+ previewUri: block.url ?? block.path ?? ''
+ }))
+ }))
+}
+
+export function insertMobileQueuedEditDictation(
+ edit: MobileQueuedEditDraft,
+ destination: MobileNativeChatDraftDestination,
+ text: string
+): boolean {
+ if (!destination.active) {
+ return false
+ }
+ if (destination.scope !== edit.scopeKey) {
+ setMobileNativeChatDraftText(destination.scope, (before) =>
+ appendBufferedDictation(before, text)
+ )
+ } else {
+ edit.text = appendBufferedDictation(edit.text, text)
+ }
+ return true
+}
+
+export type MobileStructuredQueuedEditArgs = {
+ sessionKey: string
+ sessionId: string | null
+ client: RpcClient | null
+ chatActive: boolean
+ enabled: boolean
+ imagesCapable?: boolean
+ skillsCapable?: boolean
+ composerScopeKey?: string | null
+ messages: readonly AgentSessionQueuedMessage[] | null
+ submissions?: readonly AgentJournalSubmission[]
+ cards: readonly MobileQueuedMessageCard[]
+ mutate: MobileStructuredAgentMutate
+ appendComposerText: ((text: string) => boolean) | undefined
+ onQueuedEditNotice?: (text: string) => void
+ onSendError: (text: string) => void
+ onActionResolved?: () => void
+}
diff --git a/mobile/src/session/mobile-queued-message-edit-lease.ts b/mobile/src/session/mobile-queued-message-edit-lease.ts
index 7e1c40b5941..9b4c62c778a 100644
--- a/mobile/src/session/mobile-queued-message-edit-lease.ts
+++ b/mobile/src/session/mobile-queued-message-edit-lease.ts
@@ -1,4 +1,7 @@
-import { startQueuedEditLease } from '../../../src/shared/queued-message-edit-lease'
+import {
+ startQueuedEditLease,
+ type QueuedEditLeaseLoss
+} from '../../../src/shared/queued-message-edit-lease'
import type { RpcClient } from '../transport/rpc-client'
import { callAgentSession } from './mobile-structured-agent-session-rpc'
import { structuredSessionOperationId } from './structured-session-operation-id'
@@ -10,12 +13,14 @@ export function startMobileQueuedEditLease(args: {
sessionId: string
messageId: string
expectedBodyFingerprint: string
+ onLost: (loss: QueuedEditLeaseLoss) => void
}) {
return startQueuedEditLease({
sessionId: args.sessionId,
messageId: args.messageId,
editId: structuredSessionOperationId(),
expectedBodyFingerprint: args.expectedBodyFingerprint,
+ onLost: args.onLost,
request: (params) => {
const client = args.getClient()
return client
diff --git a/mobile/src/session/mobile-queued-message-edit-open.ts b/mobile/src/session/mobile-queued-message-edit-open.ts
new file mode 100644
index 00000000000..8a436be4ea8
--- /dev/null
+++ b/mobile/src/session/mobile-queued-message-edit-open.ts
@@ -0,0 +1,68 @@
+import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease'
+import {
+ queuedMessageEditableText,
+ queuedEditKeptImages
+} from '../../../src/shared/queued-message-edit'
+import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
+import { createUuidV4 } from '../../../src/shared/uuid-v4'
+import { startMobileQueuedEditLease } from './mobile-queued-message-edit-lease'
+import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value'
+import { readMobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
+import {
+ seedMobileQueuedEditInputs,
+ type MobileQueuedEditDraft as Edit,
+ type MobileStructuredQueuedEditArgs
+} from './mobile-queued-message-edit-draft'
+
+export function createMobileQueuedEdit(
+ args: MobileStructuredQueuedEditArgs,
+ messageId: string,
+ getClient: () => MobileStructuredQueuedEditArgs['client'],
+ onLost: (edit: Edit, loss: QueuedEditLeaseLoss) => void
+): Edit | null {
+ const { enabled, client, sessionId, sessionKey } = args
+ if (!enabled || !client || !sessionId) {
+ return null
+ }
+ const message = args.messages?.find((entry) => entry.messageId === messageId)
+ const text = message ? queuedMessageEditableText(message.body) : null
+ if (!message || text === null) {
+ return null
+ }
+ const fingerprint = agentSessionSendBodyFingerprint(sessionId, message.body)
+ const scopeKey = `queued-edit:${createUuidV4()}`
+ seedMobileQueuedEditInputs(scopeKey, message.body)
+ const edit: Edit = {
+ scope: sessionKey,
+ client,
+ sessionId,
+ published: {
+ messages: args.messages,
+ submissions: args.submissions ?? [],
+ cards: args.cards
+ },
+ scopeKey,
+ destination: args.composerScopeKey ?? null,
+ handBackText: args.appendComposerText,
+ messageId,
+ body: message.body,
+ text,
+ fingerprint,
+ uncertain: false,
+ baseKey: mobileQueuedEditValueKey(text, readMobileNativeChatDraftInputs(scopeKey)),
+ kept: queuedEditKeptImages(message.body).map((entry, index) => ({
+ block: entry.block,
+ image: readMobileNativeChatDraftInputs(scopeKey).images[index]
+ })),
+ closed: false,
+ pendingClose: false,
+ lease: startMobileQueuedEditLease({
+ getClient,
+ sessionId,
+ messageId,
+ expectedBodyFingerprint: fingerprint,
+ onLost: (loss) => onLost(edit, loss)
+ })
+ }
+ return edit
+}
diff --git a/mobile/src/session/mobile-queued-message-edit-outcome.ts b/mobile/src/session/mobile-queued-message-edit-outcome.ts
new file mode 100644
index 00000000000..93dc2909e65
--- /dev/null
+++ b/mobile/src/session/mobile-queued-message-edit-outcome.ts
@@ -0,0 +1,109 @@
+import type { AgentSessionQueuedMessageUpdateResult } from '../../../src/shared/agent-session-wire'
+import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
+import type { MobileQueuedEditDraft } from './mobile-queued-message-edit-draft'
+import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc'
+import { readMobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value'
+
+type Outcome = 'close' | 'rebase' | 'gone' | 'changed' | 'refused' | 'stay'
+export function settleMobileQueuedEdit(
+ edit: MobileQueuedEditDraft,
+ attempt = edit.attempt,
+ result?: StructuredAgentSessionMutationResult
+): Outcome {
+ if (edit.closed || edit.attempt !== attempt) {
+ return 'stay'
+ }
+ const loss =
+ edit.leaseLoss?.lease === edit.lease && edit.leaseLoss.expected === edit.fingerprint
+ ? edit.leaseLoss.status
+ : undefined
+ const lost = loss === 'changed' ? 'changed' : loss ? 'gone' : undefined
+ const { messages, submissions } = edit.published
+ const message = messages?.find((entry) => entry.messageId === edit.messageId)
+ const available = edit.published.cards.some((entry) => entry.messageId === edit.messageId)
+ const sent =
+ attempt &&
+ submissions.some(
+ (entry) =>
+ entry.queuedMessageId === edit.messageId && entry.payloadFingerprint === attempt.fingerprint
+ )
+ let proof = Boolean(
+ attempt &&
+ ((message &&
+ agentSessionSendBodyFingerprint(edit.sessionId, message.body) === attempt.fingerprint) ||
+ sent)
+ )
+ if (result?.status === 'accepted') {
+ const status = result.value.status
+ if (status === 'gone' || status === 'changed') {
+ edit.attempt = undefined
+ return status
+ }
+ if (status !== 'updated' && status !== 'unchanged') {
+ edit.attempt = undefined
+ return (
+ lost ??
+ (edit.pendingClose || (messages !== null && (!message || !available)) ? 'gone' : 'refused')
+ )
+ }
+ proof = result.value.fingerprint === attempt?.fingerprint
+ if (!proof && attempt) {
+ attempt.phase = 'unknown'
+ edit.uncertain ||= attempt.fingerprint !== attempt.expected
+ }
+ } else if (result?.status === 'rejected') {
+ edit.attempt = undefined
+ return (
+ lost ??
+ (edit.pendingClose || (messages !== null && (!message || !available)) ? 'gone' : 'refused')
+ )
+ } else if (result?.status === 'unknown' && attempt) {
+ attempt.phase = 'unknown'
+ edit.uncertain ||= attempt.fingerprint !== attempt.expected
+ }
+ if (attempt && proof) {
+ if (edit.uncertain && attempt.fingerprint === edit.fingerprint) {
+ attempt.phase = 'unknown'
+ return lost ?? (edit.pendingClose || sent ? 'gone' : 'stay')
+ }
+ const equal =
+ mobileQueuedEditValueKey(edit.text, readMobileNativeChatDraftInputs(edit.scopeKey)) ===
+ attempt.key
+ const blocks = attempt.body.blocks.filter((block) => block.type === 'image-ref')
+ edit.kept = attempt.inputs.images.flatMap((image, index) =>
+ blocks[index] ? [{ image, block: blocks[index] }] : []
+ )
+ edit.body = attempt.body
+ edit.baseKey = attempt.key
+ edit.fingerprint = attempt.fingerprint
+ edit.uncertain = false
+ edit.attempt = undefined
+ if (equal) {
+ return 'close'
+ }
+ return edit.pendingClose ||
+ sent ||
+ (messages !== null && (!message || !available)) ||
+ loss === 'gone' ||
+ loss === 'not-editable'
+ ? 'gone'
+ : loss === 'changed' && attempt.fingerprint === attempt.expected
+ ? 'changed'
+ : 'rebase'
+ }
+ if (lost) {
+ return lost
+ }
+ if (edit.pendingClose || (messages !== null && (!message || !available))) {
+ return 'gone'
+ }
+ if (
+ !result &&
+ message &&
+ agentSessionSendBodyFingerprint(edit.sessionId, message.body) !== edit.fingerprint
+ ) {
+ return 'changed'
+ }
+ return 'stay'
+}
diff --git a/mobile/src/session/mobile-queued-message-edit-value.ts b/mobile/src/session/mobile-queued-message-edit-value.ts
new file mode 100644
index 00000000000..be2abe1a6eb
--- /dev/null
+++ b/mobile/src/session/mobile-queued-message-edit-value.ts
@@ -0,0 +1,30 @@
+import type { MobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { pickedSkillsInText } from '../../../src/shared/structured-agent-session-send-mutation'
+
+type Image = MobileNativeChatDraftInputs['images'][number]
+export function sameMobileQueuedEditImage(left: Image, right: Image): boolean {
+ return left.id === right.id && left.path === right.path && left.previewUri === right.previewUri
+}
+export function mobileQueuedEditValueKey(
+ text: string,
+ inputs: MobileNativeChatDraftInputs
+): string {
+ return JSON.stringify([
+ text,
+ pickedSkillsInText(text, inputs.skills, ['$', '/']),
+ inputs.images,
+ inputs.files,
+ inputs.pending ?? 0
+ ])
+}
+
+export function snapshotMobileQueuedEditInputs(
+ inputs: MobileNativeChatDraftInputs
+): MobileNativeChatDraftInputs {
+ return {
+ ...inputs,
+ images: inputs.images.map((image) => ({ ...image })),
+ files: inputs.files.map((file) => ({ ...file })),
+ skills: inputs.skills.map((skill) => ({ ...skill }))
+ }
+}
diff --git a/mobile/src/session/mobile-structured-agent-session-contract.ts b/mobile/src/session/mobile-structured-agent-session-contract.ts
index 2be70f89bfa..f0d476ab2d4 100644
--- a/mobile/src/session/mobile-structured-agent-session-contract.ts
+++ b/mobile/src/session/mobile-structured-agent-session-contract.ts
@@ -63,7 +63,9 @@ export type MobileStructuredAgentSessionArgs = {
agent: string | null
/** What the session reported for its `/` menu; undefined until read or on an older host. */
sessionCommands?: readonly AgentSessionSlashCommand[]
+ composerScopeKey?: string | null
appendComposerText?: (text: string) => boolean
+ onQueuedEditNotice?: (message: string) => void
onSendError: MobileNativeChatSendErrorReporter
// Accepted queued actions retire the route’s failure banner.
onActionResolved?: () => void
diff --git a/mobile/src/session/mobile-structured-agent-session-host-support.ts b/mobile/src/session/mobile-structured-agent-session-host-support.ts
index 97e90b291e6..5af99dc6641 100644
--- a/mobile/src/session/mobile-structured-agent-session-host-support.ts
+++ b/mobile/src/session/mobile-structured-agent-session-host-support.ts
@@ -20,7 +20,10 @@ import {
AGENT_SESSION_PERMISSION_MODES_RUNTIME_CAPABILITY,
AGENT_SESSION_PERMISSION_OWN_RUNTIME_CAPABILITY
} from '../../../src/shared/agent-session-permission-modes-capability'
-import { AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session-runtime-capabilities'
+import {
+ AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY,
+ AGENT_SESSION_QUEUED_MESSAGE_SKILLS_EDIT_RUNTIME_CAPABILITY
+} from '../../../src/shared/agent-session-runtime-capabilities'
import { SKILL_DISCOVER_WORKSPACE_CAPABILITY } from '../../../src/shared/skill-install-capability'
export type StructuredAgentSessionHostSupport = {
@@ -36,6 +39,7 @@ export type StructuredAgentSessionHostSupport = {
queuedMessageReorder?: boolean
// Older hosts edit queued text only.
queuedMessageImageEdit?: boolean
+ queuedMessageSkillsEdit?: boolean
// Hosts predating mobile access refuse this feed even if they implement it.
statusFeed: boolean
quietRepeatedStop: boolean
@@ -63,6 +67,9 @@ export function structuredAgentSessionHostSupport(
queuedMessages: capabilities.includes(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY),
queuedCommands: capabilities.includes(AGENT_SESSION_QUEUED_COMMANDS_RUNTIME_CAPABILITY),
queuedMessageEdit: capabilities.includes(AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY),
+ queuedMessageSkillsEdit: capabilities.includes(
+ AGENT_SESSION_QUEUED_MESSAGE_SKILLS_EDIT_RUNTIME_CAPABILITY
+ ),
queuedMessageReorder: capabilities.includes(
AGENT_SESSION_QUEUED_MESSAGE_REORDER_RUNTIME_CAPABILITY
),
diff --git a/mobile/src/session/mobile-structured-queued-message-cards.ts b/mobile/src/session/mobile-structured-queued-message-cards.ts
index c6513a05207..a2b683c924d 100644
--- a/mobile/src/session/mobile-structured-queued-message-cards.ts
+++ b/mobile/src/session/mobile-structured-queued-message-cards.ts
@@ -1,3 +1,4 @@
+import { stripSentImagePromptMarkers } from '../../../src/shared/native-chat-image-transcript-markers'
// The shared projection decides each card's hold; this layer words it for the phone.
import type { AgentSessionFailureFact } from '../../../src/shared/agent-session-failure'
@@ -67,7 +68,10 @@ export function mobileQueuedMessageCards(
): MobileQueuedMessageCard[] {
return projectQueuedMessageCards(queuedMessages, submissions, facts).map((card) => ({
...card,
- line: queuedMessageCardLine(card),
+ line: queuedMessageCardLine({
+ ...card,
+ text: stripSentImagePromptMarkers(card.text, card.images?.length ?? 0)
+ }),
needsAttention: queuedMessageCardNeedsAttention(card),
caption: queuedMessageCardCaption(card, facts.agentName, facts.statedFailures ?? []),
attribution: agentMessageAttribution('From', card.from)
diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts
index d8a5604d9ab..76d501efbfb 100644
--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts
+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts
@@ -1,7 +1,40 @@
+import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
+import {
+ setMobileNativeChatDraftText,
+ readMobileNativeChatDraftEditGeneration
+} from './mobile-native-chat-draft-store'
+import {
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs,
+ resetMobileNativeChatDraftInputsForTests
+} from './mobile-native-chat-draft-inputs'
+import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts'
+import { useMobileStructuredNativeChatSendBridge } from '../../use-mobile-structured-native-chat-send-bridge'
+import { mobileNativeChatScopeKey } from '../mobile-native-chat-scope-key'
+import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session'
+import {
+ CAPABLE,
+ SESSION_ID,
+ snapshotEvent,
+ mutationOk,
+ ok
+} from '../../use-mobile-structured-agent-session-queued.test-fixture'
+import { structuredSendResultFixture } from '../../structured-agent-send-result.test-fixture'
+import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes'
+import type { RpcClient } from '../../../transport/rpc-client'
+vi.mock('../../../platform/media-picker', () => ({
+ useMediaPicker: () => ({ pickImages: async () => [] })
+}))
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
+}))
import { createElement, type ComponentProps } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
+import {
+ MobileNativeChatComposer as NativeChatComposer,
+ MobileNativeChatDraftComposer
+} from './MobileNativeChatComposer'
const getNoComposerEditGeneration = () => 0
@@ -99,6 +132,219 @@ describe('MobileNativeChatComposer on a structured chat', () => {
)
const drawers = () => renderer!.root.findAll((node) => node.props.onHidden !== undefined)
+ it.each(['', 'See this'])(
+ 'sends an ordinary image with %j text through the real RPC and clears its visible chip',
+ async (text) => {
+ const scope = mobileNativeChatScopeKey('host', 'worktree', `image-rpc-${text}`)!
+ resetMobileNativeChatDraftInputsForTests()
+ setMobileNativeChatDraftText(scope, text)
+ updateMobileNativeChatDraftInputs(scope, (input) => ({
+ ...input,
+ images: [{ id: 'photo', path: '/remote/photo.png', previewUri: 'file:///phone-photo.png' }]
+ }))
+ let publish: ((data: unknown) => void) | undefined
+ const sendRequest = vi.fn(async (method) =>
+ method === 'agentSession.send'
+ ? mutationOk(structuredSendResultFixture('accepted'))
+ : ok({ models: [], current: {} })
+ )
+ const client: RpcClient = {
+ sendRequest,
+ subscribe: (_m, _p, listener) => {
+ publish = listener
+ return () => {}
+ },
+ updateTerminalSubscriptionViewport: () => {},
+ getState: () => 'connected',
+ getReconnectAttempt: () => 0,
+ getLastConnectedAt: () => null,
+ onStateChange: () => () => {},
+ notifyForeground: () => {},
+ close: () => {}
+ }
+ function Conversation() {
+ const session = useMobileStructuredAgentSession({
+ client,
+ sessionId: SESSION_ID,
+ sourceIdentity: 'host',
+ enabled: true,
+ connected: true,
+ agent: 'codex',
+ hostSupport: { ...CAPABLE, sendSkills: true },
+ composerScopeKey: scope,
+ onSendError: vi.fn()
+ })
+ const drafts = useMobileNativeChatDrafts({
+ hostId: 'host',
+ worktreeId: 'worktree',
+ tabId: `image-rpc-${text}`,
+ sessionId: SESSION_ID,
+ messages: [],
+ transcriptSettled: true
+ })
+ const bridge = useMobileStructuredNativeChatSendBridge({
+ ...drafts,
+ agent: 'codex',
+ sendStructured: session.sendWithOutcome,
+ onSendError: vi.fn()
+ })
+ const image = useMobileNativeChatImageAttachments({
+ client,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: scope,
+ enabled: true,
+ structuredNativeChat: true,
+ showToast: vi.fn(),
+ onSendError: vi.fn(),
+ baseSend: bridge.sendWithOutcome,
+ readSeededLaunchDraft: () => null
+ })
+ return draw({
+ value: text,
+ onSend: image.sendNativeChat,
+ attachments: image.attachments,
+ onRemoveAttachment: image.removeAttachment,
+ structured: structured()
+ })
+ }
+ await act(async () => {
+ renderer = create(createElement(Conversation))
+ })
+ act(() => publish?.(snapshotEvent()))
+ expect(labelled('Remove image')[0]).toBeDefined()
+ await act(async () => labelled('Send message')[0]!.props.onPress())
+ const request = sendRequest.mock.calls.find(([method]) => method === 'agentSession.send')?.[1]
+ expect(request).toMatchObject({
+ body: {
+ blocks: [
+ ...(text ? [{ type: 'text', text }] : []),
+ { type: 'image-ref', path: '/remote/photo.png' }
+ ]
+ }
+ })
+ expect(readMobileNativeChatDraftInputs(scope).images).toEqual([])
+ expect(labelled('Remove image')).toEqual([])
+ }
+ )
+
+ it.each([
+ ['codex', '$review.v2'],
+ ['claude', '/review.v2']
+ ] as const)(
+ '%s matches main capture/clear and real Send refs, and forgets a deleted pick',
+ async (agent, token) => {
+ const scope = mobileNativeChatScopeKey('host', 'worktree', 'menu')!
+ resetMobileNativeChatDraftInputsForTests()
+ setMobileNativeChatDraftText(scope, '/re')
+ let publish: ((data: unknown) => void) | undefined
+ const sendRequest = vi.fn(async (method) =>
+ method === 'agentSession.send'
+ ? mutationOk(structuredSendResultFixture('accepted'))
+ : ok({ models: [], current: {} })
+ )
+ const client: RpcClient = {
+ sendRequest,
+ subscribe: (_m, _p, listener) => {
+ publish = listener
+ return () => {}
+ },
+ updateTerminalSubscriptionViewport: () => {},
+ getState: () => 'connected',
+ getReconnectAttempt: () => 0,
+ getLastConnectedAt: () => null,
+ onStateChange: () => () => {},
+ notifyForeground: () => {},
+ close: () => {}
+ }
+ function Conversation() {
+ const session = useMobileStructuredAgentSession({
+ client,
+ sessionId: SESSION_ID,
+ sourceIdentity: 'host',
+ enabled: true,
+ connected: true,
+ agent,
+ hostSupport: { ...CAPABLE, sendSkills: true },
+ composerScopeKey: scope,
+ onSendError: vi.fn()
+ })
+ const drafts = useMobileNativeChatDrafts({
+ hostId: 'host',
+ worktreeId: 'worktree',
+ tabId: 'menu',
+ sessionId: SESSION_ID,
+ messages: [],
+ transcriptSettled: true
+ })
+ const bridge = useMobileStructuredNativeChatSendBridge({
+ ...drafts,
+ agent,
+ sendStructured: session.sendWithOutcome,
+ onSendError: vi.fn()
+ })
+ return createElement(MobileNativeChatDraftComposer, {
+ draftKey: scope,
+ agent,
+ draftScopeKey: scope,
+ onChangeText: drafts.setComposerText,
+ onSend: bridge.send,
+ sendSurfaceId: scope,
+ getSendCompletionGeneration: () => 0,
+ getComposerEditGeneration: () => readMobileNativeChatDraftEditGeneration(scope),
+ structured: structured({
+ catalog: {
+ reported: [{ name: 'review.v2', kind: 'skill', path: '/remote/review/SKILL.md' }],
+ conversationCommands: []
+ }
+ })
+ })
+ }
+ await act(async () => {
+ renderer = create(createElement(Conversation))
+ })
+ act(() => publish?.(snapshotEvent()))
+ act(() => field().props.onSelectionChange({ nativeEvent: { selection: { end: 3 } } }))
+ await act(async () => labelled(token)[0]!.props.onPress())
+ expect(field().props.value).toBe(`${token} `)
+ await act(async () => labelled('Send message')[0]!.props.onPress())
+ const request = sendRequest.mock.calls.find(([method]) => method === 'agentSession.send')?.[1]
+ const skills = [{ name: 'review.v2', path: '/remote/review/SKILL.md' }]
+ expect(request).toMatchObject({ body: { blocks: [{ type: 'text', text: token }] } })
+ if (agent === 'codex') {
+ expect(request).toHaveProperty('body.skills', skills)
+ } else {
+ expect(request).not.toHaveProperty('body.skills')
+ }
+ expect(field().props.value).toBe('')
+ expect(readMobileNativeChatDraftInputs(scope).skills).toEqual(skills)
+ act(() => field().props.onChangeText(`${token} `))
+ await act(async () => labelled('Send message')[0]!.props.onPress())
+ const second = sendRequest.mock.calls.findLast(
+ ([method]) => method === 'agentSession.send'
+ )?.[1]
+ if (agent === 'codex') {
+ expect(second).toHaveProperty('body.skills', skills)
+ } else {
+ expect(second).not.toHaveProperty('body.skills')
+ }
+ // Pick again, delete, then retype: text alone cannot resurrect the old remote identity.
+ act(() => field().props.onChangeText('/re'))
+ act(() => field().props.onSelectionChange({ nativeEvent: { selection: { end: 3 } } }))
+ await act(async () => labelled(token)[0]!.props.onPress())
+ act(() => field().props.onChangeText(''))
+ act(() => field().props.onChangeText(`${token} `))
+ expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([])
+ await act(async () => labelled('Send message')[0]!.props.onPress())
+ expect(
+ sendRequest.mock.calls.findLast(([method]) => method === 'agentSession.send')?.[1]
+ ).not.toHaveProperty('body.skills')
+ }
+ )
+
it('puts a picked skill at the start of the draft, highlighted, and deletes it as one unit', async () => {
const onChangeText = vi.fn()
const catalog = structured()
@@ -162,4 +408,29 @@ describe('MobileNativeChatComposer on a structured chat', () => {
await act(async () => labelled('Send message')[0]!.props.onPress())
expect(onSend).toHaveBeenCalledExactlyOnceWith('')
})
+ it('forgets inline picked skill identity after its token is removed and retyped', async () => {
+ const scope = 'removed-skill'
+ updateMobileNativeChatDraftInputs(scope, () => ({
+ images: [],
+ files: [],
+ skills: [{ name: 'review', path: '/remote/SKILL.md' }]
+ }))
+ await act(async () => {
+ renderer = create(
+ createElement(MobileNativeChatComposer, {
+ draftScopeKey: scope,
+ value: '$review draft',
+ editSession: { cancel: vi.fn(), locked: false, refuseCommand: () => false },
+ onChangeText: vi.fn(),
+ onSend: async () => false,
+ sendSurfaceId: scope,
+ getSendCompletionGeneration: getNoComposerEditGeneration
+ })
+ )
+ })
+ const input = () => findByHostType(renderer!.root, 'TextInput')
+ await act(async () => input().props.onChangeText('draft'))
+ await act(async () => input().props.onChangeText('$review draft'))
+ expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([])
+ })
})
diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts
index 890aa689a01..69fd85fa599 100644
--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts
+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts
@@ -2,6 +2,10 @@ import { createElement, createRef, StrictMode, type ComponentProps, type ReactNo
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { Keyboard, type TextInput } from 'react-native'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ useMobileNativeChatDraft,
+ setMobileNativeChatDraftText
+} from './mobile-native-chat-draft-store'
import { radii, spacing } from '../../../theme/mobile-theme'
import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
import {
@@ -9,6 +13,8 @@ import {
findByHostType
} from '../../../test-support/react-test-renderer-host-nodes'
+import { captureMobileNativeChatTextDestination } from './mobile-native-chat-draft-inputs'
+
const getNoComposerEditGeneration = () => 0
function MobileNativeChatComposer({
@@ -109,6 +115,34 @@ describe('MobileNativeChatComposer', () => {
)
}
+ it('uses ordinary append semantics through the registered focused dictation destination', async () => {
+ const scope = 'dictation-ordinary'
+ setMobileNativeChatDraftText(scope, '/compact')
+ function Registered() {
+ const value = useMobileNativeChatDraft(scope)
+ return createElement(MobileNativeChatComposer, {
+ value,
+ draftScopeKey: scope,
+ onChangeText: (text) => setMobileNativeChatDraftText(scope, text),
+ onSend: async () => true,
+ sendSurfaceId: scope,
+ getSendCompletionGeneration: () => 0
+ })
+ }
+ await act(async () => {
+ renderer = create(createElement(Registered))
+ })
+ const input = () => findByHostType(renderer!.root, 'TextInput')
+ act(() => input().props.onFocus())
+ const insert = captureMobileNativeChatTextDestination()!
+ act(() => {
+ insert('hello')
+ insert('hello')
+ insert(' there ')
+ })
+ expect(input().props.value).toBe('/compact hello hello there ')
+ })
+
it('reports an accepted send without owning route-scoped draft cleanup', async () => {
const onChangeText = vi.fn()
const onSend = vi.fn().mockResolvedValue(true)
diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx
index 7bb30fd56a6..8e5a728ee72 100644
--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx
+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx
@@ -1,6 +1,18 @@
+import { getNativeChatAgentProfile } from '../../../../../src/shared/native-chat-agent-profiles'
+import {
+ recordMobileNativeChatSkillPick,
+ setMobileNativeChatDraftText,
+ useMobileNativeChatDraft
+} from './mobile-native-chat-draft-store'
+import { appendBufferedDictation } from '../../../terminal/terminal-live-dictation-routing'
+import {
+ focusMobileNativeChatTextDestination,
+ pruneMobileNativeChatDraftSkills,
+ registerMobileNativeChatTextDestination
+} from './mobile-native-chat-draft-inputs'
import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
-import { ActivityIndicator, Keyboard, Pressable, type TextInput, View } from 'react-native'
+import { ActivityIndicator, Keyboard, Pressable, type TextInput, Text, View } from 'react-native'
import { ArrowUp, Mic, Plus, Square } from 'lucide-react-native'
import { colors } from '../../../theme/mobile-theme'
import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
@@ -23,10 +35,6 @@ import { keepHeldPressThroughLongPress } from '../../held-press-long-press'
import { mobileNativeChatComposerShowsStop } from './mobile-native-chat-composer-layout'
import { MobileNativeChatStopButton } from '../input/MobileNativeChatStopButton'
import { mobileNativeChatComposerStyles as styles } from './mobile-native-chat-composer-styles'
-import {
- recordMobileNativeChatSkillPick,
- useMobileNativeChatDraft
-} from './mobile-native-chat-draft-store'
const NO_FILE_PATHS: string[] = []
const NO_ATTACHMENTS: PendingNativeChatImage[] = []
@@ -42,6 +50,10 @@ export type MobileNativeChatStructuredComposer = {
}
type Props = {
+ insertDictation?: (text: string) => boolean | void
+ draftScopeKey?: string | null
+ editSession?: { cancel: () => void; refuseCommand: (text: string) => boolean; locked: boolean }
+ onPickSkill?: (skill: { name: string; path: string }) => void
inputRef?: React.RefObject
// Terminal-backed chats keep curated commands and image-only attachment actions.
structured?: MobileNativeChatStructuredComposer | null
@@ -79,6 +91,10 @@ type Props = {
export function MobileNativeChatComposer({
inputRef,
+ draftScopeKey,
+ insertDictation,
+ editSession,
+ onPickSkill,
value,
onChangeText,
onSend,
@@ -106,6 +122,19 @@ export function MobileNativeChatComposer({
onNeedSkills,
stop = null
}: Props): React.JSX.Element {
+ useEffect(() => {
+ if (!draftScopeKey) {
+ return
+ }
+ return registerMobileNativeChatTextDestination(
+ draftScopeKey,
+ insertDictation ??
+ ((text) =>
+ setMobileNativeChatDraftText(draftScopeKey, (before) =>
+ appendBufferedDictation(before, text)
+ ))
+ )
+ }, [draftScopeKey, insertDictation])
useMobileColorScheme()
const fallbackInputRef = useRef(null)
const fieldRef = inputRef ?? fallbackInputRef
@@ -121,7 +150,26 @@ export function MobileNativeChatComposer({
const files = structured?.files ?? NO_FILES
const menu = useMobileNativeChatComposerMenu({
value,
- onChangeText,
+ onChangeText: (text) => {
+ if (editSession && draftScopeKey) {
+ pruneMobileNativeChatDraftSkills(
+ draftScopeKey,
+ text,
+ getNativeChatAgentProfile(agent)?.skillPrefix ?? '/'
+ )
+ }
+ onChangeText(text)
+ },
+ onPickSkill: (skill) => {
+ if (onPickSkill && skill.path) {
+ onPickSkill({ name: skill.token.slice(1), path: skill.path })
+ }
+ if (!editSession) {
+ recordMobileNativeChatSkillPick(sendSurfaceId, skill)
+ }
+ },
+ refuseCommand: editSession?.refuseCommand,
+ editing: editSession !== undefined,
agent,
structuredCatalog: structured?.catalog,
filePaths,
@@ -129,8 +177,6 @@ export function MobileNativeChatComposer({
skillDiscovery,
onNeedSkills,
onSlashMenuOpen: structured?.onSlashMenuOpen,
- // The surface id is the draft key both send paths read picks back from.
- onPickSkill: (skill) => recordMobileNativeChatSkillPick(sendSurfaceId, skill),
focusField: () => fieldRef.current?.focus()
})
const sendingRef = useRef(false)
@@ -196,7 +242,9 @@ export function MobileNativeChatComposer({
menu.resetCursor()
// Why: the turn is now the agent's — the keyboard would cover the reply.
// A rejected send keeps it up so the handed-back draft stays editable.
- Keyboard.dismiss()
+ if (!editSession) {
+ Keyboard.dismiss()
+ }
}
} finally {
sendingRef.current = false
@@ -211,22 +259,31 @@ export function MobileNativeChatComposer({
return (
{menu.rows.length > 0 ? (
-
+
) : null}
setFocused(true)}
+ onFocus={() => {
+ setFocused(true)
+ if (draftScopeKey) {
+ focusMobileNativeChatTextDestination(draftScopeKey)
+ }
+ }}
onBlur={() => setFocused(false)}
// Controlled only transiently right after an autocomplete insert.
selection={menu.pendingSelection ?? undefined}
@@ -235,6 +292,7 @@ export function MobileNativeChatComposer({
placeholderTextColor={colors.textMuted}
selectionColor={colors.accentBlue}
multiline
+ editable={!editSession?.locked}
// Why: never revoke `editable` — iOS resigns first responder on a focused
// field, so a transient lock would yank the keyboard mid-typing (#10681).
// The lock gates sending; the draft survives and rides the next send.
@@ -302,12 +360,22 @@ export function MobileNativeChatComposer({
)}
) : null}
+ {editSession ? (
+
+ Cancel
+
+ ) : null}
{showsStop && stop ? (
// Only this phone's own request holds Stop: a repeat is how a stuck stop escalates.
) : (
[
styles.sendButton,
!canSend && styles.sendButtonDisabled,
@@ -316,11 +384,15 @@ export function MobileNativeChatComposer({
onPress={handleSend}
disabled={!canSend}
>
-
+ {editSession ? (
+ Save
+ ) : (
+
+ )}
)}
diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachments.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachments.tsx
index 877ee815afd..8ae57b1b2a0 100644
--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachments.tsx
+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachments.tsx
@@ -1,3 +1,4 @@
+import { isRenderableImageUri } from '../visual/mobile-native-chat-image-preview'
import {
ActivityIndicator,
Image,
@@ -7,7 +8,7 @@ import {
Text,
View
} from 'react-native'
-import { FileText, X } from 'lucide-react-native'
+import { FileText, Image as ImageIcon, X } from 'lucide-react-native'
import { colors, radii, spacing } from '../../../theme/mobile-theme'
import { themedStyleSheet } from '../../../theme/themed-styles'
import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
@@ -49,7 +50,21 @@ export function MobileNativeChatComposerAttachments({
>
{images.map((image) => (
-
+ {isRenderableImageUri(image.previewUri) ? (
+
+ ) : (
+
+
+
+ )}
{onRemoveImage ? (
onRemoveImage(image.id)} />
) : null}
diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposerMenu.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposerMenu.tsx
index deec33b1275..51fc68a73e7 100644
--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposerMenu.tsx
+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposerMenu.tsx
@@ -11,15 +11,21 @@ const HEADINGS = { command: 'Commands', skill: 'Skills', file: 'Files' } as cons
export function MobileNativeChatComposerMenu({
rows,
- onPick
+ onPick,
+ nestedScrollEnabled
}: {
rows: readonly ComposerMenuRow[]
onPick: (row: ComposerMenuRow) => void
+ nestedScrollEnabled?: boolean
}): React.JSX.Element {
useMobileColorScheme()
return (
-
+
{rows.map((row, index) => (
{rows[index - 1]?.kind !== row.kind ? (
diff --git a/mobile/src/session/native-chat/composer/mobile-attachment-operation-lifetime.test.ts b/mobile/src/session/native-chat/composer/mobile-attachment-operation-lifetime.test.ts
new file mode 100644
index 00000000000..7c003b592de
--- /dev/null
+++ b/mobile/src/session/native-chat/composer/mobile-attachment-operation-lifetime.test.ts
@@ -0,0 +1,215 @@
+import { createElement } from 'react'
+import { act, create } from 'react-test-renderer'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments'
+import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
+import {
+ closeMobileNativeChatEditInputs,
+ readMobileNativeChatDraftInputs,
+ resetMobileNativeChatDraftInputsForTests
+} from './mobile-native-chat-draft-inputs'
+import type { RpcClient } from '../../../transport/rpc-client'
+import type { RpcResponse } from '../../../transport/types'
+const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
+vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker }))
+afterEach(() => resetMobileNativeChatDraftInputsForTests())
+
+it.each(['files', 'images'] as const)(
+ 'retires remaining %s uploads on Cancel, and follows hand-back before the first chip',
+ async (kind) => {
+ for (const cancel of [true, false]) {
+ let release = () => {}
+ let started = () => {}
+ const firstStarted = new Promise((resolve) => {
+ started = resolve
+ })
+ const held = new Promise((resolve) => {
+ release = resolve
+ })
+ const starts: string[] = []
+ const client: RpcClient = {
+ sendRequest: vi.fn(async (method: string): Promise => {
+ if (method.endsWith('uploadStart') || method === 'clipboard.startImageUpload') {
+ starts.push(method)
+ if (starts.length === 1) {
+ started()
+ await held
+ }
+ return {
+ id: 'r',
+ ok: true,
+ result: { uploadId: `upload-${starts.length}` },
+ _meta: { runtimeId: 'r' }
+ }
+ }
+ const result =
+ method === 'clipboard.commitImageUpload'
+ ? `/stored/${starts.length}.png`
+ : method.endsWith('uploadCommit')
+ ? {
+ path: `/stored/${starts.length}.png`,
+ name: `${starts.length}.png`,
+ byteLength: 1
+ }
+ : null
+ return { id: 'r', ok: true, result, _meta: { runtimeId: 'r' } }
+ }),
+ subscribe: () => () => {},
+ updateTerminalSubscriptionViewport: () => {},
+ getState: () => 'connected',
+ getReconnectAttempt: () => 0,
+ getLastConnectedAt: () => null,
+ onStateChange: () => () => {},
+ notifyForeground: () => {},
+ close: () => {}
+ }
+ picker.pickFiles.mockImplementation(async function* () {
+ for (const name of ['a.txt', 'b.txt']) {
+ yield { name, mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
+ }
+ })
+ picker.pickImages.mockResolvedValue([
+ { base64: 'YQ==', uri: 'file:///a.png' },
+ { base64: 'Yg==', uri: 'file:///b.png' }
+ ])
+ let attach = () => Promise.resolve()
+ let send = () => Promise.resolve(false)
+ const baseSend = vi.fn().mockResolvedValue('accepted')
+ function Probe() {
+ const file = useMobileNativeChatFileAttachments({
+ client,
+ sessionId: 's',
+ scopeKey: 'edit',
+ enabled: true,
+ showToast: vi.fn()
+ })
+ const image = useMobileNativeChatImageAttachments({
+ client,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: 'edit',
+ enabled: true,
+ structuredNativeChat: true,
+ showToast: vi.fn(),
+ onSendError: vi.fn(),
+ baseSend,
+ readSeededLaunchDraft: () => null
+ })
+ attach = kind === 'files' ? file.attachFiles : () => image.attachImage('library')
+ return null
+ }
+ let edit!: ReturnType
+ await act(async () => {
+ edit = create(createElement(Probe))
+ })
+ let work!: Promise
+ await act(async () => {
+ work = attach()
+ await firstStarted
+ })
+ act(() => closeMobileNativeChatEditInputs('edit', cancel ? undefined : 'bottom'))
+ if (!cancel) {
+ // Bottom Send must consume the transferred pending obligation even before a completed image exists.
+ function Bottom() {
+ const image = useMobileNativeChatImageAttachments({
+ client,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: 'bottom',
+ enabled: true,
+ structuredNativeChat: true,
+ showToast: vi.fn(),
+ onSendError: vi.fn(),
+ baseSend,
+ readSeededLaunchDraft: () => null
+ })
+ send = () => image.sendNativeChat('bottom')
+ return null
+ }
+ let bottom!: ReturnType
+ await act(async () => {
+ bottom = create(createElement(Bottom))
+ })
+ await act(async () => expect(await send()).toBe(false))
+ expect(baseSend).not.toHaveBeenCalled()
+ act(() => bottom.unmount())
+ }
+ await act(async () => {
+ release()
+ await work
+ })
+ expect(starts).toHaveLength(cancel ? 1 : 2)
+ const result = readMobileNativeChatDraftInputs('bottom')
+ expect(result[kind]).toHaveLength(cancel ? 0 : 2)
+ expect(result.pending ?? 0).toBe(0)
+ act(() => edit.unmount())
+ resetMobileNativeChatDraftInputsForTests()
+ }
+ }
+)
+
+it('retains unique image identity across a real hook remount and removes only the chosen photo', async () => {
+ const client: RpcClient = {
+ sendRequest: vi.fn(async (method: string): Promise => ({
+ id: 'r',
+ ok: true,
+ result:
+ method === 'clipboard.startImageUpload'
+ ? { uploadId: 'upload' }
+ : method === 'clipboard.commitImageUpload'
+ ? '/stored/photo.png'
+ : null,
+ _meta: { runtimeId: 'r' }
+ })),
+ subscribe: () => () => {},
+ updateTerminalSubscriptionViewport: () => {},
+ getState: () => 'connected',
+ getReconnectAttempt: () => 0,
+ getLastConnectedAt: () => null,
+ onStateChange: () => () => {},
+ notifyForeground: () => {},
+ close: () => {}
+ }
+ picker.pickImages.mockResolvedValue([{ base64: 'YQ==', uri: 'file:///photo.png' }])
+ let hook!: ReturnType
+ function Probe() {
+ hook = useMobileNativeChatImageAttachments({
+ client,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'connected',
+ scopeKey: 'retained',
+ enabled: true,
+ structuredNativeChat: true,
+ showToast: vi.fn(),
+ onSendError: vi.fn(),
+ baseSend: vi.fn().mockResolvedValue('accepted'),
+ readSeededLaunchDraft: () => null
+ })
+ return null
+ }
+ let mounted!: ReturnType
+ await act(async () => {
+ mounted = create(createElement(Probe))
+ })
+ await act(async () => hook.attachImage('library'))
+ const first = hook.attachments[0]!.id
+ act(() => mounted.unmount())
+ await act(async () => {
+ mounted = create(createElement(Probe))
+ })
+ await act(async () => hook.attachImage('library'))
+ const second = hook.attachments[1]!.id
+ expect(second).not.toBe(first)
+ act(() => hook.removeAttachment(second))
+ expect(hook.attachments.map(({ id }) => id)).toEqual([first])
+ act(() => mounted.unmount())
+})
diff --git a/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts b/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts
new file mode 100644
index 00000000000..891f40ad215
--- /dev/null
+++ b/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts
@@ -0,0 +1,166 @@
+import { createElement } from 'react'
+import { act, create } from 'react-test-renderer'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments'
+import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
+import {
+ useMobileNativeChatDraft,
+ setMobileNativeChatDraftText,
+ resetMobileNativeChatDraftStoreForTests
+} from './mobile-native-chat-draft-store'
+import {
+ subscribeMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs,
+ closeMobileNativeChatEditInputs,
+ useMobileNativeChatDraftInputs
+} from './mobile-native-chat-draft-inputs'
+
+const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
+vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker }))
+afterEach(resetMobileNativeChatDraftStoreForTests)
+
+it.each([20, 200])(
+ 'isolates mounted text, input, image and file consumers across %i other scopes',
+ async (count) => {
+ const scopes = [
+ 'own-host:target',
+ ...Array.from({ length: count }, (_, i) => `other-host:${i}`)
+ ]
+ const own = scopes[0]
+ const renders = scopes.map(() => ({ text: 0, input: 0, image: 0, file: 0 }))
+ const values: {
+ text: string
+ pending: number
+ images: readonly string[]
+ files: readonly string[]
+ }[] = scopes.map(() => ({ text: '', pending: 0, images: [], files: [] }))
+ const upstream = scopes.map(() => vi.fn())
+ const releases = scopes.map((scope, i) =>
+ subscribeMobileNativeChatDraftInputs(scope, upstream[i])
+ )
+ function Text({ index }: { index: number }) {
+ values[index].text = useMobileNativeChatDraft(scopes[index])
+ renders[index].text++
+ return null
+ }
+ function Input({ index }: { index: number }) {
+ values[index].pending = useMobileNativeChatDraftInputs(scopes[index]).pending ?? 0
+ renders[index].input++
+ return null
+ }
+ function File({ index }: { index: number }) {
+ const file = useMobileNativeChatFileAttachments({
+ client: null,
+ sessionId: null,
+ scopeKey: scopes[index],
+ enabled: false,
+ showToast: vi.fn()
+ })
+ values[index].files = file.files.map((entry) => entry.path ?? '')
+ renders[index].file++
+ return null
+ }
+ function Image({ index }: { index: number }) {
+ const image = useMobileNativeChatImageAttachments({
+ client: null,
+ agent: 'codex',
+ activeHandleRef: { current: null },
+ deviceTokenRef: { current: null },
+ getActiveWorktreeConnectionId: async () => null,
+ connState: 'disconnected',
+ scopeKey: scopes[index],
+ enabled: false,
+ structuredNativeChat: true,
+ showToast: vi.fn(),
+ onSendError: vi.fn(),
+ baseSend: async () => 'rejected',
+ readSeededLaunchDraft: () => null
+ })
+ values[index].images = image.attachments.map((entry) => entry.path)
+ renders[index].image++
+ return null
+ }
+ let view: ReturnType | undefined
+ await act(async () => {
+ view = create(
+ createElement(
+ 'fixture',
+ {},
+ scopes.flatMap((_, index) => [
+ createElement(Text, { key: `t${index}`, index }),
+ createElement(Input, { key: `p${index}`, index }),
+ createElement(File, { key: `f${index}`, index }),
+ createElement(Image, { key: `i${index}`, index })
+ ])
+ )
+ )
+ })
+ renders.forEach((entry) => {
+ entry.text = entry.input = entry.image = entry.file = 0
+ })
+ try {
+ await act(async () => setMobileNativeChatDraftText(own, 'own text'))
+ expect(values[0].text).toBe('own text')
+ expect(renders[0]).toEqual({ text: 1, input: 0, image: 0, file: 0 })
+ await act(async () =>
+ updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 1 }))
+ )
+ expect(values[0].pending).toBe(1)
+ await act(async () =>
+ updateMobileNativeChatDraftInputs(own, (current) => ({
+ ...current,
+ images: [{ id: 'image', path: '/saved.png', previewUri: 'file:///saved.png' }]
+ }))
+ )
+ expect(values[0].images).toEqual(['/saved.png'])
+ await act(async () =>
+ updateMobileNativeChatDraftInputs(own, (current) => ({
+ ...current,
+ files: [
+ { id: 'file', path: '/saved.txt', name: 'saved.txt', mime: 'text/plain', byteLength: 1 }
+ ]
+ }))
+ )
+ expect(values[0].files).toEqual(['/saved.txt'])
+ expect(renders[0]).toEqual({ text: 1, input: 3, image: 3, file: 3 })
+ expect(upstream[0]).toHaveBeenCalledTimes(3)
+ for (let index = 1; index < scopes.length; index++) {
+ expect(renders[index]).toEqual({ text: 0, input: 0, image: 0, file: 0 })
+ expect(upstream[index]).not.toHaveBeenCalled()
+ }
+ } finally {
+ await act(async () => view?.unmount())
+ releases.forEach((release) => release())
+ }
+ await act(async () =>
+ updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 0 }))
+ )
+ expect(renders[0]).toEqual({ text: 1, input: 3, image: 3, file: 3 })
+ expect(upstream[0]).toHaveBeenCalledTimes(3)
+ }
+)
+it.each([20, 200])(
+ 'notifies only affected scopes across %i retained input subscribers and retires listeners',
+ (count) => {
+ const idle = vi.fn()
+ const releases = Array.from({ length: count }, (_, index) =>
+ subscribeMobileNativeChatDraftInputs(`idle-${index}`, idle)
+ )
+ const source = vi.fn()
+ const destination = vi.fn()
+ releases.push(
+ subscribeMobileNativeChatDraftInputs('queued-edit:one', source),
+ subscribeMobileNativeChatDraftInputs('bottom', destination)
+ )
+ updateMobileNativeChatDraftInputs('queued-edit:one', (inputs) => ({ ...inputs, pending: 1 }))
+ expect(source).toHaveBeenCalledTimes(1)
+ expect(idle).not.toHaveBeenCalled()
+ closeMobileNativeChatEditInputs('queued-edit:one', 'bottom')
+ expect(source).toHaveBeenCalledTimes(2)
+ expect(destination).toHaveBeenCalledTimes(1)
+ expect(idle).not.toHaveBeenCalled()
+ releases.forEach((release) => release())
+ updateMobileNativeChatDraftInputs('bottom', (inputs) => ({ ...inputs, pending: 0 }))
+ expect(destination).toHaveBeenCalledTimes(1)
+ }
+)
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.test.ts
index ec7d3e510be..83cfd0f288f 100644
--- a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.test.ts
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.test.ts
@@ -1,3 +1,4 @@
+import { prepareQueuedMessageEditText } from '../../../../../src/shared/queued-message-edit-command'
import { describe, expect, it } from 'vitest'
import { deriveComposerAutocomplete } from '../../../../../src/shared/native-chat-composer-autocomplete'
import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items'
@@ -13,6 +14,7 @@ import {
function mobileComposerSlashItems(input: {
agent: string
+ editing?: boolean
structured: MobileComposerStructuredCatalog | undefined
query: string
discovery?: NativeChatSkillDiscoverySnapshot
@@ -27,7 +29,10 @@ function mobileComposerSlashItems(input: {
catalog.profile,
catalog.discovery,
null,
- catalog.sessionSkills
+ catalog.sessionSkills,
+ input.editing
+ ? (name) => prepareQueuedMessageEditText(input.agent, input.structured?.reported)(`/${name}`)
+ : undefined
)
return result.mode === 'slash' ? boundedMenuItems(result.items) : []
}
@@ -176,3 +181,27 @@ describe('narrowedMenuItems', () => {
expect(narrowedMenuItems(commandsOnly, 'skill')).toEqual(commandsOnly)
})
})
+
+it('keeps edit-valid provider commands and namesake skills without changing the ordinary catalog', () => {
+ const input = {
+ agent: 'claude',
+ structured: {
+ reported: [
+ { name: 'model', kind: 'skill' as const, path: '/model/SKILL.md' },
+ { name: 'review', kind: 'command' as const },
+ { name: 'goal', kind: 'command' as const }
+ ],
+ conversationCommands: ['clear' as const, 'compact' as const]
+ },
+ query: ''
+ }
+ const ordinary = mobileComposerSlashItems(input)
+ const editing = mobileComposerSlashItems({ ...input, editing: true })
+ expect(editing.map(({ kind, name }) => `${kind}:${name}`)).toEqual([
+ 'command:review',
+ 'command:goal',
+ 'skill:model'
+ ])
+ expect(ordinary.map(({ name }) => name)).toContain('compact')
+ expect(ordinary.map(({ kind, name }) => `${kind}:${name}`)).toContain('command:model')
+})
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts
new file mode 100644
index 00000000000..34d8c797ee3
--- /dev/null
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts
@@ -0,0 +1,143 @@
+import { useCallback, useSyncExternalStore } from 'react'
+import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation'
+import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types'
+import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment'
+import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment'
+
+export type MobileNativeChatDraftInputs = {
+ images: readonly PendingNativeChatImage[]
+ files: readonly PendingNativeChatFile[]
+ skills: readonly AgentJournalSkillRef[]
+ pending?: number
+}
+const empty: MobileNativeChatDraftInputs = { images: [], files: [], skills: [] }
+const drafts = new Map()
+const listeners = new Map void>>()
+// Operations capture this object: hand-back redirects it; Cancel removes its right to publish.
+export type MobileNativeChatDraftDestination = { scope: string; active: boolean }
+const destinations = new Map()
+export function mobileNativeChatDraftDestination(scope: string): MobileNativeChatDraftDestination {
+ let destination = destinations.get(scope)
+ if (!destination) {
+ destination = { scope, active: true }
+ destinations.set(scope, destination)
+ }
+ return destination
+}
+export function readMobileNativeChatDraftInputs(scope: string | null): MobileNativeChatDraftInputs {
+ return scope ? (drafts.get(scope) ?? empty) : empty
+}
+export function updateMobileNativeChatDraftInputs(
+ target: string | MobileNativeChatDraftDestination,
+ update: (current: MobileNativeChatDraftInputs) => MobileNativeChatDraftInputs
+): void {
+ const destination = typeof target === 'string' ? mobileNativeChatDraftDestination(target) : target
+ if (!destination.active) {
+ return
+ }
+ drafts.set(destination.scope, update(readMobileNativeChatDraftInputs(destination.scope)))
+ listeners.get(destination.scope)?.forEach((listener) => listener())
+}
+export function subscribeMobileNativeChatDraftInputs(
+ scope: string | null,
+ listener: () => void
+): () => void {
+ if (!scope) {
+ return () => {}
+ }
+ const scoped = listeners.get(scope) ?? new Set<() => void>()
+ listeners.set(scope, scoped)
+ scoped.add(listener)
+ return () => {
+ scoped.delete(listener)
+ if (scoped.size === 0) {
+ listeners.delete(scope)
+ }
+ }
+}
+export function useMobileNativeChatDraftInputs(scope: string | null): MobileNativeChatDraftInputs {
+ const subscribe = useCallback(
+ (listener: () => void) => subscribeMobileNativeChatDraftInputs(scope, listener),
+ [scope]
+ )
+ return useSyncExternalStore(subscribe, () => readMobileNativeChatDraftInputs(scope))
+}
+export function closeMobileNativeChatEditInputs(
+ scope: string,
+ to?: string,
+ kept: readonly PendingNativeChatImage[] = [],
+ clean = false
+): void {
+ const destination = mobileNativeChatDraftDestination(scope)
+ const input = readMobileNativeChatDraftInputs(scope)
+ if (to) {
+ updateMobileNativeChatDraftInputs(to, (current) => ({
+ images: [
+ ...current.images,
+ ...input.images.filter(
+ (image) =>
+ !kept.some(
+ (owned) =>
+ owned.id === image.id &&
+ owned.path === image.path &&
+ owned.previewUri === image.previewUri
+ )
+ )
+ ],
+ files: [...current.files, ...(clean ? [] : input.files)],
+ skills: [...current.skills, ...(clean ? [] : input.skills)],
+ pending: (current.pending ?? 0) + (input.pending ?? 0)
+ }))
+ destination.scope = to
+ } else {
+ destination.active = false
+ }
+ drafts.delete(scope)
+ destinations.delete(scope)
+ listeners.get(scope)?.forEach((listener) => listener())
+}
+
+const textDestinations = new Map boolean | void>()
+let focusedScope: string | null = null
+export function registerMobileNativeChatTextDestination(
+ scope: string,
+ insert: (text: string) => boolean | void
+): () => void {
+ textDestinations.set(scope, insert)
+ return () => {
+ if (textDestinations.get(scope) === insert) {
+ textDestinations.delete(scope)
+ }
+ }
+}
+export function focusMobileNativeChatTextDestination(scope: string): void {
+ focusedScope = scope
+}
+export function captureMobileNativeChatTextDestination():
+ | ((text: string) => boolean | void)
+ | undefined {
+ return focusedScope ? textDestinations.get(focusedScope) : undefined
+}
+
+export function resetMobileNativeChatDraftInputsForTests(): void {
+ drafts.clear()
+ destinations.clear()
+ textDestinations.clear()
+ focusedScope = null
+}
+
+export function pruneMobileNativeChatDraftSkills(
+ scope: string,
+ text: string,
+ sigil: '$' | '/' | readonly ('$' | '/')[] = '$'
+): void {
+ const current = readMobileNativeChatDraftInputs(scope)
+ const skills = pickedSkillsInText(
+ text,
+ current.skills,
+ typeof sigil === 'string' ? [sigil] : sigil
+ )
+ if (skills.length !== current.skills.length) {
+ updateMobileNativeChatDraftInputs(scope, (current) => ({ ...current, skills }))
+ }
+}
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts
index d709849a245..658c7742ffb 100644
--- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts
@@ -4,6 +4,8 @@ import { afterEach, describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../src/shared/native-chat-types'
import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts'
import {
+ clearMobileNativeChatDraftForSend,
+ readMobileNativeChatDraftEditGeneration,
readMobileNativeChatPickedSkills,
editMobileNativeChatDraft,
readMobileNativeChatSkillOrigin,
@@ -13,6 +15,11 @@ import {
setMobileNativeChatDraftText,
useMobileNativeChatDraft
} from './mobile-native-chat-draft-store'
+import {
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs,
+ resetMobileNativeChatDraftInputsForTests
+} from './mobile-native-chat-draft-inputs'
type DraftState = ReturnType & { composerText: string }
@@ -23,6 +30,7 @@ describe('mobile native-chat draft store', () => {
afterEach(() => {
act(() => renderer?.unmount())
resetMobileNativeChatDraftStoreForTests()
+ resetMobileNativeChatDraftInputsForTests()
renderer = null
state = null
})
@@ -77,6 +85,25 @@ describe('mobile native-chat draft store', () => {
expect(currentState().composerText).toBe('ping')
})
+ it('keeps main picked refs across Send-clear but revokes them on a real token edit', () => {
+ const scope = 'sent-skills'
+ setMobileNativeChatDraftText(scope, '$review draft')
+ updateMobileNativeChatDraftInputs(scope, () => ({
+ images: [],
+ files: [],
+ skills: [{ name: 'review', path: '/remote/SKILL.md' }]
+ }))
+ const generation = readMobileNativeChatDraftEditGeneration(scope)
+ clearMobileNativeChatDraftForSend(scope, generation - 1, '$review draft')
+ expect(readMobileNativeChatDraftInputs(scope).skills).toHaveLength(1)
+ clearMobileNativeChatDraftForSend(scope, generation, '$review draft')
+ expect(readMobileNativeChatPickedSkills(scope)).toEqual([
+ { name: 'review', path: '/remote/SKILL.md' }
+ ])
+ editMobileNativeChatDraft(scope, 'different text')
+ expect(readMobileNativeChatPickedSkills(scope)).toEqual([])
+ })
+
it('keeps a typed draft after the chat screen unmounts and remounts', async () => {
await mount('a')
act(() => currentState().setComposerText('half-written prompt'))
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts
index 7ae8a24941f..bd5116d981b 100644
--- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts
@@ -1,6 +1,11 @@
import { useSyncExternalStore, type SetStateAction } from 'react'
import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types'
-import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation'
+import {
+ resetMobileNativeChatDraftInputsForTests,
+ pruneMobileNativeChatDraftSkills,
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './mobile-native-chat-draft-inputs'
import type { MobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-launch-draft-seed'
// Text and its edit revision outlive the screen, including callbacks from an older mount.
@@ -8,7 +13,6 @@ import type { MobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-l
type Draft = {
text: string
editGeneration: number
- skills?: AgentJournalSkillRef[]
skillOrigin?: string
}
@@ -29,9 +33,11 @@ export function recordMobileNativeChatSkillPick(
const current = drafts.get(draftKey) ?? { text: '', editGeneration: 0 }
const name = skill.token.slice(1)
// A pick replaces whatever file its token named before, like re-picking a desktop chip.
- const kept = (current.skills ?? []).filter((held) => held.name !== name)
- const skills = skill.path ? [...kept, { name, path: skill.path }] : kept
- drafts.set(draftKey, { ...current, skillOrigin: skill.token, skills })
+ updateMobileNativeChatDraftInputs(draftKey, (inputs) => {
+ const kept = inputs.skills.filter((held) => held.name !== name)
+ return { ...inputs, skills: skill.path ? [...kept, { name, path: skill.path }] : kept }
+ })
+ drafts.set(draftKey, { ...current, skillOrigin: skill.token })
}
// A rejected send's restored text gets back the files it named, even if newer edits dropped them.
@@ -39,15 +45,14 @@ export function restoreMobileNativeChatPickedSkills(
draftKey: string,
skills: readonly AgentJournalSkillRef[]
): void {
- const current = drafts.get(draftKey)
- if (!current || skills.length === 0) {
+ if (!drafts.has(draftKey) || skills.length === 0) {
return
}
- const paths = new Set((current.skills ?? []).map((skill) => skill.path))
- drafts.set(draftKey, {
+ const paths = new Set(readMobileNativeChatDraftInputs(draftKey).skills.map((skill) => skill.path))
+ updateMobileNativeChatDraftInputs(draftKey, (current) => ({
...current,
- skills: [...(current.skills ?? []), ...skills.filter((skill) => !paths.has(skill.path))]
- })
+ skills: [...current.skills, ...skills.filter((skill) => !paths.has(skill.path))]
+ }))
}
export function readMobileNativeChatSkillOrigin(draftKey: string): string | null {
@@ -55,7 +60,7 @@ export function readMobileNativeChatSkillOrigin(draftKey: string): string | null
}
export function readMobileNativeChatPickedSkills(draftKey: string): AgentJournalSkillRef[] {
- return drafts.get(draftKey)?.skills ?? []
+ return [...readMobileNativeChatDraftInputs(draftKey).skills]
}
function subscribe(listener: () => void): () => void {
@@ -73,14 +78,14 @@ function writeDraft(draftKey: string, update: SetStateAction, userEdit:
return
}
// Send clears and restores are not edits, so a rejected draft keeps its picks.
- const skills =
- userEdit && current?.skills ? pickedSkillsInText(next, current.skills) : current?.skills
+ if (userEdit) {
+ pruneMobileNativeChatDraftSkills(draftKey, next)
+ }
const skillOrigin =
userEdit && current?.skillOrigin !== next.split(/\s/, 1)[0] ? undefined : current?.skillOrigin
drafts.set(draftKey, {
text: next,
editGeneration: (current?.editGeneration ?? 0) + 1,
- ...(skills ? { skills } : {}),
...(skillOrigin ? { skillOrigin } : {})
})
if (next === text) {
@@ -123,6 +128,7 @@ export function useMobileNativeChatDraft(draftKey: string | null): string {
}
export function resetMobileNativeChatDraftStoreForTests(): void {
+ resetMobileNativeChatDraftInputsForTests()
drafts.clear()
mobileNativeChatLaunchDraftSeeds.clear()
}
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.ts
index d9f39a2159b..cfc87596d80 100644
--- a/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.ts
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.ts
@@ -33,6 +33,7 @@ function nativeChatFileAttachFailureMessage(error: unknown, fileName?: string):
// Keep successfully uploaded files when a later pick/upload fails; only the failing chip is removed.
export async function uploadPickedNativeChatFiles(args: {
+ canContinue?: () => boolean
picked: AsyncIterable
upload: (file: PickedMobileFile) => Promise
nextId: () => string
@@ -42,7 +43,13 @@ export async function uploadPickedNativeChatFiles(args: {
onError: (message: string) => void
}): Promise {
try {
+ if (args.canContinue?.() === false) {
+ return
+ }
for await (const file of args.picked) {
+ if (args.canContinue?.() === false) {
+ break
+ }
const id = args.nextId()
args.onPicked({
id,
@@ -57,6 +64,9 @@ export async function uploadPickedNativeChatFiles(args: {
args.onFailed(id)
args.onError(nativeChatFileAttachFailureMessage(error, file.name))
}
+ if (args.canContinue?.() === false) {
+ break
+ }
}
} catch (error) {
args.onError(nativeChatFileAttachFailureMessage(error))
diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.ts
index bfd738b84b6..9e721634e7e 100644
--- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.ts
+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.ts
@@ -25,6 +25,7 @@ export function appendPendingNativeChatImages(
}
export type UploadNativeChatImagesDeps = {
+ readonly canContinue?: () => boolean
readonly client: MobileClipboardImageRpcSender
readonly getConnectionId: () => Promise
readonly pickImages: (
@@ -43,6 +44,7 @@ export async function uploadMobileNativeChatImages(
source: MobileImageSource,
{
client,
+ canContinue,
getConnectionId,
pickImages,
onUploadStart,
@@ -52,11 +54,20 @@ export async function uploadMobileNativeChatImages(
const picked = await pickImages(source)
const uploaded: Omit[] = []
let connectionId: string | null = null
+ if (canContinue?.() === false) {
+ return uploaded
+ }
for await (const image of picked) {
+ if (canContinue?.() === false) {
+ break
+ }
if (uploaded.length === 0) {
onUploadStart?.()
connectionId = await getConnectionId()
}
+ if (canContinue?.() === false) {
+ break
+ }
const path = await saveMobileClipboardImageAsTempFile(client, image.base64, { connectionId })
const previewUri = image.uri ?? `data:image/png;base64,${image.base64}`
const result = {
@@ -65,6 +76,9 @@ export async function uploadMobileNativeChatImages(
}
uploaded.push(result)
onImageUploaded?.(result)
+ if (canContinue?.() === false) {
+ break
+ }
}
return uploaded
}
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-menu.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-menu.ts
index 2bb0b3e1539..e6a5c4e96bc 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-menu.ts
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-menu.ts
@@ -1,3 +1,4 @@
+import { prepareQueuedMessageEditText } from '../../../../../src/shared/queued-message-edit-command'
import { useEffect, useMemo, useState } from 'react'
import {
applyMentionSuggestion,
@@ -37,6 +38,8 @@ export function useMobileNativeChatComposerMenu(input: {
onSlashMenuOpen?: () => void
/** A picked skill; a send carries its file while its token stays, and treats a leading one as chat. */
onPickSkill?: (skill: { token: string; path?: string }) => void
+ editing?: boolean
+ refuseCommand?: (text: string) => boolean
focusField: () => void
}) {
const { value, onChangeText, agent, structuredCatalog, filePaths, skillDiscovery } = input
@@ -46,6 +49,15 @@ export function useMobileNativeChatComposerMenu(input: {
const [pendingSelection, setPendingSelection] = useState(null)
const [menuKind, setMenuKind] = useState(null)
+ const reported = structuredCatalog?.reported
+ const acceptsText = useMemo(
+ () => prepareQueuedMessageEditText(agent ?? 'codex', reported),
+ [agent, reported]
+ )
+ const commandAvailable = useMemo(
+ () => (input.editing ? (name: string) => acceptsText(`/${name}`) : undefined),
+ [input.editing, acceptsText]
+ )
const catalog = useMemo(
() =>
mobileComposerCatalog({ agent, structured: structuredCatalog, discovery: skillDiscovery }),
@@ -79,9 +91,10 @@ export function useMobileNativeChatComposerMenu(input: {
catalog.profile,
catalog.discovery,
null,
- catalog.sessionSkills
+ catalog.sessionSkills,
+ commandAvailable
),
- [beforeCaret, catalog]
+ [beforeCaret, catalog, commandAvailable]
)
const rows = useMemo(() => {
if (autocomplete.mode === 'mention') {
@@ -127,6 +140,9 @@ export function useMobileNativeChatComposerMenu(input: {
if (autocomplete.mode === 'none') {
return
}
+ if (row.kind === 'command' && input.refuseCommand?.(row.token)) {
+ return
+ }
setMenuKind(null)
// Restore page field focus after a menu tap so typing continues at the inserted pick.
input.focusField()
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.test.tsx b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.test.tsx
index 4919ccd0fd2..e8cac10515f 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.test.tsx
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.test.tsx
@@ -208,3 +208,7 @@ describe('useMobileNativeChatComposerTray', () => {
expect(duplicateKeys).toEqual([])
})
})
+
+vi.mock('../../MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-attachments.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-attachments.ts
index bbefbcf0056..82563943e4a 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-attachments.ts
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-attachments.ts
@@ -1,17 +1,20 @@
-import { useCallback, useRef, useState } from 'react'
+import { createUuidV4 } from '../../../../../src/shared/uuid-v4'
+import {
+ useMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs,
+ mobileNativeChatDraftDestination,
+ type MobileNativeChatDraftDestination
+} from './mobile-native-chat-draft-inputs'
+import { useCallback } from 'react'
import type { RpcClient } from '../../../transport/rpc-client'
import { useMediaPicker } from '../../../platform/media-picker'
import { uploadMobileAgentSessionAttachment } from '../../mobile-agent-session-attachment-upload'
-import { withScopeAttachments } from './mobile-native-chat-image-scope-state'
import {
uploadPickedNativeChatFiles,
type PendingNativeChatFile
} from './mobile-native-chat-file-attachment'
type ShowToast = (message: string, durationMs?: number) => void
-type FilesByScope = Readonly>
-
-const NO_FILES: readonly PendingNativeChatFile[] = []
export type MobileNativeChatFileAttachments = {
readonly files: readonly PendingNativeChatFile[]
@@ -28,17 +31,19 @@ export function useMobileNativeChatFileAttachments(args: {
showToast: ShowToast
}): MobileNativeChatFileAttachments {
const { client, sessionId, scopeKey, enabled, showToast } = args
- const [filesByScope, setFilesByScope] = useState({})
+
const picker = useMediaPicker()
- const idCounter = useRef(0)
- const files = (scopeKey ? filesByScope[scopeKey] : undefined) ?? NO_FILES
+ const files = useMobileNativeChatDraftInputs(scopeKey).files
const updateScope = useCallback(
(
- scope: string,
+ scope: string | MobileNativeChatDraftDestination,
next: (current: readonly PendingNativeChatFile[]) => readonly PendingNativeChatFile[]
) =>
- setFilesByScope((prev) => withScopeAttachments(prev, scope, next(prev[scope] ?? NO_FILES))),
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ files: next(current.files)
+ })),
[]
)
@@ -47,28 +52,43 @@ export function useMobileNativeChatFileAttachments(args: {
if (!client || !sessionId || !scope || !enabled) {
return
}
- await uploadPickedNativeChatFiles({
- picked: picker.pickFiles(),
- upload: (file) =>
- uploadMobileAgentSessionAttachment(client, {
- sessionId,
- name: file.name,
- base64: file.base64
- }),
- nextId: () => {
- idCounter.current += 1
- return `file-${idCounter.current}`
- },
- onPicked: (file) => updateScope(scope, (current) => [...current, file]),
- onStored: (id, stored) =>
- updateScope(scope, (current) =>
- current.map((file) =>
- file.id === id ? { ...file, name: stored.name, path: stored.path } : file
- )
- ),
- onFailed: (id) => updateScope(scope, (current) => current.filter((file) => file.id !== id)),
- onError: (message) => showToast(message)
- })
+ const destination = mobileNativeChatDraftDestination(scope)
+ updateMobileNativeChatDraftInputs(destination, (current) => ({
+ ...current,
+ pending: (current.pending ?? 0) + 1
+ }))
+ try {
+ await uploadPickedNativeChatFiles({
+ canContinue: () => destination.active,
+ picked: picker.pickFiles(),
+ upload: (file) =>
+ uploadMobileAgentSessionAttachment(client, {
+ sessionId,
+ name: file.name,
+ base64: file.base64
+ }),
+ nextId: createUuidV4,
+ onPicked: (file) => updateScope(destination, (current) => [...current, file]),
+ onStored: (id, stored) =>
+ updateScope(destination, (current) =>
+ current.map((file) =>
+ file.id === id ? { ...file, name: stored.name, path: stored.path } : file
+ )
+ ),
+ onFailed: (id) =>
+ updateScope(destination, (current) => current.filter((file) => file.id !== id)),
+ onError: (message) => {
+ if (destination.active) {
+ showToast(message)
+ }
+ }
+ })
+ } finally {
+ updateMobileNativeChatDraftInputs(destination, (current) => ({
+ ...current,
+ pending: Math.max(0, (current.pending ?? 0) - 1)
+ }))
+ }
}, [client, enabled, picker, scopeKey, sessionId, showToast, updateScope])
const removeFiles = useCallback(
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts
index f8adfe3f6a3..5fb7a1812bb 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts
@@ -1,3 +1,4 @@
+import { resetMobileNativeChatDraftInputsForTests } from './mobile-native-chat-draft-inputs'
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { buildAgentTuiClearInputForText } from '../../../../../src/shared/agent-tui-input-clear'
@@ -10,6 +11,8 @@ import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-im
// Stub the media seam so direct Expo imports would expose unsupported Flow syntax and fail the transform.
const pick = vi.hoisted(() => vi.fn())
+const ids = vi.hoisted(() => ({ next: 0 }))
+vi.mock('../../../../../src/shared/uuid-v4', () => ({ createUuidV4: () => `img-${++ids.next}` }))
vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => ({ pickImages: pick }) }))
function ok(id: string, result: unknown): RpcSuccess {
@@ -85,6 +88,8 @@ describe('useMobileNativeChatImageAttachments', () => {
}
beforeEach(() => {
+ resetMobileNativeChatDraftInputsForTests()
+ ids.next = 0
pick.mockReset()
resetMobileNativeChatStaleInputForTests()
resetMobileNativeChatTerminalWritesForTests()
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts
index 196c1d93186..ca65dffda3f 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts
@@ -1,17 +1,16 @@
-import { useCallback, useRef, useState } from 'react'
+import { createUuidV4 } from '../../../../../src/shared/uuid-v4'
+import {
+ readMobileNativeChatDraftInputs,
+ useMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs,
+ type MobileNativeChatDraftDestination
+} from './mobile-native-chat-draft-inputs'
+import { useCallback, useMemo } from 'react'
import { buildAgentTuiClearInputForText } from '../../../../../src/shared/agent-tui-input-clear'
import type { RpcClient } from '../../../transport/rpc-client'
import type { ConnectionState } from '../../../transport/types'
import type { MobileImageSource } from '../../../platform/media-picker-contract'
-import {
- appendPendingNativeChatImages,
- type PendingNativeChatImage
-} from './mobile-native-chat-image-attachment'
-import {
- NO_NATIVE_CHAT_IMAGE_ATTACHMENTS,
- withScopeAttachments,
- type MobileNativeChatImagesByScope
-} from './mobile-native-chat-image-scope-state'
+import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment'
import {
MOBILE_NATIVE_CHAT_IMAGE_SETTLE_MS,
pasteMobileNativeChatImagePaths
@@ -119,16 +118,21 @@ export function useMobileNativeChatImageAttachments({
onError,
sleep = defaultSleep
}: Args): MobileNativeChatImageAttachments {
- const [attachmentsByScope, setAttachmentsByScope] = useState({})
- const idCounter = useRef(0)
- const attachments =
- (scopeKey ? attachmentsByScope[scopeKey] : undefined) ?? NO_NATIVE_CHAT_IMAGE_ATTACHMENTS
+ const inputs = useMobileNativeChatDraftInputs(scopeKey)
+ const images = inputs.images
+ const attachments = useMemo(() => [...images], [images])
const addUploadedImages = useCallback(
- (scope: string, uploadedImages: Omit[]) => {
- setAttachmentsByScope((prev) => ({
- ...prev,
- [scope]: appendPendingNativeChatImages(prev[scope] ?? [], uploadedImages, idCounter)
+ (
+ scope: MobileNativeChatDraftDestination,
+ uploadedImages: Omit[]
+ ) => {
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ images: [
+ ...current.images,
+ ...uploadedImages.map((image) => ({ ...image, id: createUuidV4() }))
+ ]
}))
},
[]
@@ -153,13 +157,10 @@ export function useMobileNativeChatImageAttachments({
if (!scope) {
return
}
- setAttachmentsByScope((prev) =>
- withScopeAttachments(
- prev,
- scope,
- (prev[scope] ?? []).filter((attachment) => attachment.id !== id)
- )
- )
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ images: current.images.filter((attachment) => attachment.id !== id)
+ }))
},
[scopeKey]
)
@@ -180,8 +181,10 @@ export function useMobileNativeChatImageAttachments({
const sentAt = Date.now()
try {
const scope = scopeKey
- const pendingImages =
- (scope ? attachmentsByScope[scope] : undefined) ?? NO_NATIVE_CHAT_IMAGE_ATTACHMENTS
+ if ((readMobileNativeChatDraftInputs(scope).pending ?? 0) > 0) {
+ return false
+ }
+ const pendingImages = attachments
// Hold Send until all selected files finish uploading.
const storedFiles = structuredNativeChat
? files.flatMap((file) =>
@@ -202,13 +205,10 @@ export function useMobileNativeChatImageAttachments({
)
if (outcome !== 'rejected') {
const sentIds = new Set(pendingImages.map((attachment) => attachment.id))
- setAttachmentsByScope((prev) =>
- withScopeAttachments(
- prev,
- scope,
- (prev[scope] ?? []).filter((attachment) => !sentIds.has(attachment.id))
- )
- )
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ images: current.images.filter((attachment) => !sentIds.has(attachment.id))
+ }))
onFilesSent?.(storedFiles.map((file) => file.id))
}
return outcome !== 'rejected'
@@ -290,13 +290,10 @@ export function useMobileNativeChatImageAttachments({
if (outcome !== 'rejected') {
// Drop only chips in this send, including unknown delivery to avoid duplicate retries; preserve newly attached chips.
const sentIds = new Set(pendingImages.map((attachment) => attachment.id))
- setAttachmentsByScope((prev) =>
- withScopeAttachments(
- prev,
- scope,
- (prev[scope] ?? []).filter((attachment) => !sentIds.has(attachment.id))
- )
- )
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ images: current.images.filter((attachment) => !sentIds.has(attachment.id))
+ }))
}
return outcome !== 'rejected'
} catch {
@@ -314,7 +311,7 @@ export function useMobileNativeChatImageAttachments({
},
[
activeHandleRef,
- attachmentsByScope,
+ attachments,
baseSend,
client,
connState,
@@ -331,5 +328,11 @@ export function useMobileNativeChatImageAttachments({
]
)
- return { attachments, isAttaching, attachImage, removeAttachment, sendNativeChat }
+ return {
+ attachments,
+ isAttaching: isAttaching || (inputs.pending ?? 0) > 0,
+ attachImage,
+ removeAttachment,
+ sendNativeChat
+ }
}
diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-upload.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-upload.ts
index c450d1215e9..03b87955312 100644
--- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-upload.ts
+++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-upload.ts
@@ -1,3 +1,8 @@
+import {
+ mobileNativeChatDraftDestination,
+ updateMobileNativeChatDraftInputs,
+ type MobileNativeChatDraftDestination
+} from './mobile-native-chat-draft-inputs'
import { useCallback, useLayoutEffect, useRef, useState } from 'react'
import { CLIPBOARD_IMAGE_TOO_LARGE_ERROR } from '../../../../../src/shared/clipboard-image'
import type { RpcClient } from '../../../transport/rpc-client'
@@ -24,7 +29,10 @@ export function useMobileNativeChatImageUpload(args: {
scopeKey: string | null
structuredNativeChat: boolean
showToast: ShowToast
- onImagesUploaded: (scope: string, images: UploadedNativeChatImage[]) => void
+ onImagesUploaded: (
+ scope: MobileNativeChatDraftDestination,
+ images: UploadedNativeChatImage[]
+ ) => void
onAttachSuccess?: () => void
onError?: () => void
}): {
@@ -62,11 +70,17 @@ export function useMobileNativeChatImageUpload(args: {
) {
return
}
+ const destination = mobileNativeChatDraftDestination(scope)
+ updateMobileNativeChatDraftInputs(destination, (inputs) => ({
+ ...inputs,
+ pending: (inputs.pending ?? 0) + 1
+ }))
let started = false
const uploadedImages: UploadedNativeChatImage[] = []
let uploadError: unknown = null
try {
await uploadMobileNativeChatImages(source, {
+ canContinue: () => destination.active,
client,
getConnectionId: getActiveWorktreeConnectionId,
pickImages: picker.pickImages,
@@ -88,10 +102,14 @@ export function useMobileNativeChatImageUpload(args: {
}
}
if (uploadedImages.length > 0) {
- onImagesUploaded(scope, uploadedImages)
+ onImagesUploaded(destination, uploadedImages)
onAttachSuccess?.()
}
- if (uploadError !== null) {
+ updateMobileNativeChatDraftInputs(destination, (inputs) => ({
+ ...inputs,
+ pending: Math.max(0, (inputs.pending ?? 0) - 1)
+ }))
+ if (uploadError !== null && destination.active) {
const message = uploadError instanceof Error ? uploadError.message : String(uploadError)
onError?.()
if (connStateRef.current !== 'connected') {
diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessageEditor.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessageEditor.tsx
deleted file mode 100644
index 7268b2690f9..00000000000
--- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessageEditor.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { useEffect, useRef, useState } from 'react'
-import {
- ActivityIndicator,
- Pressable,
- StyleSheet,
- Text,
- TextInput,
- View,
- type StyleProp,
- type ViewStyle
-} from 'react-native'
-import { Check, X } from 'lucide-react-native'
-import { colors, radii, spacing, typography } from '../../../theme/mobile-theme'
-import { themedStyleSheet } from '../../../theme/themed-styles'
-import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
-import { mobileNativeChatInputStyles } from '../composer/mobile-native-chat-input-styles'
-import type { MobileQueuedMessageInlineEditor } from '../../use-mobile-structured-queued-edit'
-import { useTextInputContentHeight } from '../../../platform/text-input-content-height'
-
-const BUTTON_SIZE = 28
-const ICON_SIZE = 16
-const LINE_HEIGHT = 20
-const FIELD_PADDING_VERTICAL = 7
-const FIELD_BORDER = 1
-const FIELD_MIN_HEIGHT = LINE_HEIGHT + 2 * (FIELD_PADDING_VERTICAL + FIELD_BORDER)
-const FIELD_MAX_HEIGHT = 4 * LINE_HEIGHT + 2 * (FIELD_PADDING_VERTICAL + FIELD_BORDER)
-const FIELD_GAP = 6
-const BUTTON_GAP = spacing.xs
-// react-native-web drops hitSlop, so each button's own box is the 44pt-tall touch target.
-const TOUCH_TARGET_HEIGHT = 44
-const TARGET_OVERHANG = (TOUCH_TARGET_HEIGHT - FIELD_MIN_HEIGHT) / 2
-
-export function MobileNativeChatQueuedMessageEditor({
- editor,
- attribution
-}: {
- editor: MobileQueuedMessageInlineEditor
- attribution: string | null
-}): React.JSX.Element {
- useMobileColorScheme()
- const input = useRef(null)
- const contentHeight = useTextInputContentHeight(input, editor.text)
- const [focused, setFocused] = useState(false)
- useEffect(() => {
- input.current?.focus()
- }, [])
- const saveDisabled = editor.saving || !editor.canSave
- const saveOff = !editor.canSave && !editor.saving
- return (
-
- {attribution ? (
-
- {attribution}
-
- ) : null}
-
- setFocused(true)}
- onBlur={() => setFocused(false)}
- />
-
-
-
- void editor.save()}
- >
- {editor.saving ? (
-
- ) : (
-
- )}
-
-
-
- )
-}
-
-function EditorButton({
- label,
- disabled,
- busy,
- targetStyle,
- squareStyle,
- pressedStyle,
- onPress,
- children
-}: {
- label: string
- disabled: boolean
- busy?: boolean
- targetStyle: StyleProp
- squareStyle: StyleProp
- pressedStyle: StyleProp
- onPress: () => void
- children: React.ReactNode
-}): React.JSX.Element {
- useMobileColorScheme()
- // Style the inner square separately because Pressable owns the larger invisible target.
- const [pressed, setPressed] = useState(false)
- return (
- setPressed(true)}
- onPressOut={() => setPressed(false)}
- >
-
- {children}
-
-
- )
-}
-
-const styles = themedStyleSheet(() => ({
- editor: {
- paddingVertical: spacing.sm,
- paddingLeft: spacing.md,
- paddingRight: spacing.sm,
- gap: spacing.xs
- },
- attribution: {
- color: colors.textMuted,
- fontSize: typography.metaSize,
- lineHeight: typography.metaSize + spacing.xs
- },
- // Bottom-align with the last text line and keep overhanging targets inside editor padding.
- line: {
- flexDirection: 'row',
- alignItems: 'flex-end',
- marginVertical: -TARGET_OVERHANG,
- marginRight: -spacing.sm
- },
- // Keep border width constant so focus cannot shift text.
- field: {
- minHeight: FIELD_MIN_HEIGHT,
- maxHeight: FIELD_MAX_HEIGHT,
- lineHeight: LINE_HEIGHT,
- paddingTop: FIELD_PADDING_VERTICAL,
- paddingBottom: FIELD_PADDING_VERTICAL,
- paddingHorizontal: 10,
- borderWidth: FIELD_BORDER,
- borderColor: colors.borderSubtle,
- marginVertical: TARGET_OVERHANG
- },
- fieldFocused: {
- borderColor: colors.accentBlue
- },
- target: {
- height: TOUCH_TARGET_HEIGHT,
- justifyContent: 'center'
- },
- cancelTarget: {
- paddingLeft: FIELD_GAP,
- paddingRight: BUTTON_GAP / 2
- },
- saveTarget: {
- paddingLeft: BUTTON_GAP / 2,
- paddingRight: spacing.sm
- },
- button: {
- width: BUTTON_SIZE,
- height: BUTTON_SIZE,
- borderRadius: radii.input,
- alignItems: 'center',
- justifyContent: 'center'
- },
- buttonRaised: {
- backgroundColor: colors.bgRaised,
- borderWidth: StyleSheet.hairlineWidth,
- borderColor: colors.borderSubtle
- },
- cancelPressed: {
- backgroundColor: colors.bgPanel
- },
- save: {
- backgroundColor: colors.textPrimary
- },
- savePressed: {
- backgroundColor: colors.textSecondary
- },
- disabled: { opacity: 0.5 }
-}))
diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx
index d2c58861cf7..37f2f5777db 100644
--- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx
+++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx
@@ -1,11 +1,17 @@
+import {
+ mobileQueuedMessageCards,
+ type MobileQueuedMessageCard
+} from '../../mobile-structured-queued-message-cards'
+import { queuedDraft } from '../../use-mobile-structured-agent-session-queued.test-fixture'
import { createElement } from 'react'
+import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes'
+import { FakeSession } from '../../../transport/mobile-endpoint-supervisor-test-fakes'
+import type { MobileQueuedMessageInlineEditor } from '../../mobile-queued-message-edit-draft'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ActionSheetAction } from '../../../components/ActionSheetModal'
import { colors } from '../../../theme/mobile-theme'
import { MobileNativeChatQueuedMessages } from './MobileNativeChatQueuedMessages'
-import type { MobileQueuedMessageCard } from '../../mobile-structured-queued-message-cards'
-import { mobileQueuedMessageCards } from '../../mobile-structured-queued-message-cards'
import { useMobileQueuedMessageComposerActions } from '../../use-mobile-queued-message-composer-actions'
import type { MobileStructuredAgentMutate } from '../../use-mobile-structured-agent-mutation'
import type {
@@ -38,6 +44,7 @@ vi.mock('react-native', () => ({
}))
vi.mock('lucide-react-native', () => ({
+ Image: 'Image',
AlertCircle: 'AlertCircle',
Check: 'Check',
ChevronDown: 'ChevronDown',
@@ -54,6 +61,29 @@ vi.mock('lucide-react-native', () => ({
vi.mock('../../../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
+vi.mock('../../MobileQueuedMessageComposer', () => ({
+ MobileQueuedMessageComposer: 'QueuedMessageComposer'
+}))
+
+function inlineEditor(
+ fields: Partial & { messageId: string }
+): MobileQueuedMessageInlineEditor {
+ return {
+ scopeKey: 'edit-scope',
+ sessionId: 'session',
+ client: new FakeSession('connected'),
+ imagesCapable: true,
+ text: 'edited text',
+ saving: false,
+ canSave: true,
+ change: vi.fn(),
+ save: vi.fn(async () => true),
+ removeImage: vi.fn(),
+ cancel: vi.fn(),
+ ...fields
+ }
+}
+
function card(
overrides: Partial & { messageId: string }
): MobileQueuedMessageCard {
@@ -108,75 +138,44 @@ describe('MobileNativeChatQueuedMessages', () => {
return mounted.root.find((node) => String(node.type) === 'ActionSheetModal')
}
- it('edits in place of the card row with an X and a checkmark while keeping another card visible', async () => {
- const change = vi.fn()
- const save = vi.fn(async () => true)
- const cancel = vi.fn()
+ it('mounts the real composer boundary in the edited row and leaves other cards visible', async () => {
+ const editor = inlineEditor({ messageId: 'a' })
const mounted = await mount({
- cards: [
- card({
- messageId: 'a',
- attribution: 'From Alex',
- caption: 'Returned',
- needsAttention: true,
- state: 'returned'
- }),
- card({ messageId: 'b' })
- ],
- editor: {
- messageId: 'a',
- text: 'edited text',
- saving: false,
- canSave: true,
- change,
- save,
- cancel
- }
+ cards: [card({ messageId: 'a', attribution: 'From Alex' }), card({ messageId: 'b' })],
+ editor
})
- const input = mounted.root.findByProps({ accessibilityLabel: 'Edit queued message' })
- expect(input.props.value).toBe('edited text')
- const editedRow = mounted.root.findAllByProps({ testID: 'queued-card-row' })[0]!
- expect(texts(mounted)).toContain('From Alex')
- expect(texts(mounted)).not.toContain('Editing message')
- expect(texts(mounted)).not.toContain('Returned')
- expect(nodeTypes(editedRow)).toEqual(expect.arrayContaining(['X', 'Check']))
- expect(nodeTypes(editedRow)).not.toContain('Pencil')
- expect(nodeTypes(editedRow)).not.toContain('AlertCircle')
- expect(
- editedRow.findAll((node) => node.props.accessibilityLabel === 'Delete this queued message')
- ).toHaveLength(0)
- act(() => input.props.onChangeText('updated text'))
- expect(change).toHaveBeenCalledWith('updated text')
- const button = (label: string) => mounted.root.findByProps({ accessibilityLabel: label })
- await act(async () => button('Save edited message').props.onPress())
- expect(save).toHaveBeenCalledOnce()
- act(() => button('Cancel editing').props.onPress())
- expect(cancel).toHaveBeenCalledOnce()
+ const child = findByHostType(mounted.root, 'QueuedMessageComposer')
+ expect(child.props.editor).toBe(editor)
+ expect(child.props.attribution).toBe('From Alex')
expect(mounted.root.findAllByProps({ testID: 'queued-card-row' })).toHaveLength(2)
expect(mounted.root.findByProps({ accessibilityLabel: 'More actions' }).props.disabled).toBe(
true
)
- const editAgain = (state: { saving: boolean; canSave: boolean }) =>
- act(async () =>
- mounted.update(
- createElement(MobileNativeChatQueuedMessages, {
- cards: [card({ messageId: 'a' })],
- editor: { messageId: 'a', text: '', change, save, cancel, ...state }
- })
- )
- )
- await editAgain({ saving: false, canSave: false })
- expect(button('Save edited message').props.disabled).toBe(true)
- expect(button('Cancel editing').props.disabled).toBe(false)
- await editAgain({ saving: true, canSave: true })
- const saveButton = button('Save edited message')
- expect(saveButton.props.disabled).toBe(true)
- expect(saveButton.props.accessibilityState).toEqual({ disabled: true })
- expect(saveButton.props['aria-busy']).toBe(true)
- expect(nodeTypes(saveButton)).toContain('ActivityIndicator')
- expect(nodeTypes(saveButton)).not.toContain('Check')
- expect(button('Cancel editing').props.disabled).toBe(true)
- expect(button('Edit queued message').props.editable).toBe(false)
+ })
+
+ it('projects image-only and mixed queue blocks into the ordinary card line and edit boundary', async () => {
+ const image = { type: 'image-ref' as const, path: '/host/photo.png', alt: 'Diagram' }
+ const rows = [
+ queuedDraft({
+ messageId: 'image-only',
+ body: { kind: 'message', role: 'user', blocks: [image] }
+ }),
+ queuedDraft({
+ messageId: 'mixed',
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'See this' }, image] }
+ })
+ ]
+ const cards = mobileQueuedMessageCards(rows, [])
+ const mounted = await mount({ cards, onSend: vi.fn(async () => true) })
+ expect(texts(mounted)).toContain('Diagram')
+ expect(texts(mounted)).toContain('See this')
+ expect(cards.map((card) => card.images)).toEqual([[image], [image]])
+ const editor = inlineEditor({ messageId: 'image-only', text: '' })
+ await act(async () =>
+ mounted.update(createElement(MobileNativeChatQueuedMessages, { cards, editor }))
+ )
+ expect(findByHostType(mounted.root, 'QueuedMessageComposer').props.editor).toBe(editor)
+ expect(texts(mounted)).toContain('See this')
})
it('draws a plain waiting card as one compact row with no caption', async () => {
@@ -639,7 +638,7 @@ describe('MobileNativeChatQueuedMessages', () => {
try {
const mounted = await mountPaused({
pause: { reason: 'stopped' },
- editor: {
+ editor: inlineEditor({
messageId: 'waiting-1',
text: 'next',
saving: false,
@@ -647,7 +646,7 @@ describe('MobileNativeChatQueuedMessages', () => {
change: vi.fn(),
save: vi.fn(async () => true),
cancel: vi.fn()
- }
+ })
})
const header = mounted.root.findByProps({ testID: 'queued-header' })
for (const label of ['Delete every queued message', 'Resume sending the queued messages']) {
diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx
index 878334d5783..d4664f6f309 100644
--- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx
+++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx
@@ -126,9 +126,9 @@ export function MobileNativeChatQueuedMessages({
const attentionCaption = !expanded ? cards.find((card) => card.needsAttention)?.caption : null
const headerCountStyle = [styles.headerCount, attentionCaption && styles.captionReturned]
return (
-
+
{}
-
+
{/* A polite region, as the app's other notices: React Native has no status role. */}
card.messageId)}
newestIsPersons={!cards.at(-1)?.attribution}
+ inlineEditorActive={editor !== undefined}
>
{(reveal, drag) => {
const renderRow = (card: MobileQueuedMessageCard, handle?: React.ReactNode) => (
diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-queued-message-styles.ts b/mobile/src/session/native-chat/input/mobile-native-chat-queued-message-styles.ts
index 9811456f9a1..add5949536b 100644
--- a/mobile/src/session/native-chat/input/mobile-native-chat-queued-message-styles.ts
+++ b/mobile/src/session/native-chat/input/mobile-native-chat-queued-message-styles.ts
@@ -26,6 +26,9 @@ export const queuedMessageStyles = themedStyleSheet(() => ({
borderColor: colors.composerBorder,
overflow: 'hidden'
},
+ // Full editors and menus scroll above the ordinary composer instead of tucking under it.
+ inlineList: { flexShrink: 1, minHeight: 0, marginBottom: 0 },
+ inlineBox: { flexShrink: 1, minHeight: 0, paddingBottom: 0 },
header: {
minHeight: HEADER_HEIGHT,
flexDirection: 'row',
diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx
index 73d713936a7..58e7134d6ca 100644
--- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx
+++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx
@@ -12,7 +12,7 @@ import {
import {
isRenderableSubagentGroup,
withoutSubagentGroupTwins
-} from '../../../../../src/shared/native-chat-subagent-summary'
+} from '../../../../../src/shared/native-chat/transcript/native-chat-subagent-summary'
import type {
NativeChatBlock,
NativeChatMessage,
diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatSubagentGroup.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatSubagentGroup.tsx
index 580207f16ff..ffd5d56a43d 100644
--- a/mobile/src/session/native-chat/transcript/MobileNativeChatSubagentGroup.tsx
+++ b/mobile/src/session/native-chat/transcript/MobileNativeChatSubagentGroup.tsx
@@ -6,7 +6,7 @@ import {
sayNativeChatSubagentGroupEnglish as say,
subagentStateLabel
} from '../../../../../src/shared/native-chat/transcript/native-chat-subagent-group-header'
-import { normalizeSubagentState } from '../../../../../src/shared/native-chat-subagent-summary'
+import { normalizeSubagentState } from '../../../../../src/shared/native-chat/transcript/native-chat-subagent-summary'
import { formatNativeChatDuration } from '../../../../../src/shared/native-chat-turn-status'
import type {
NativeChatSubagentGroupBlock,
diff --git a/mobile/src/session/use-mobile-native-chat-active-resolution.ts b/mobile/src/session/use-mobile-native-chat-active-resolution.ts
index c46f762669c..c2f49ac721b 100644
--- a/mobile/src/session/use-mobile-native-chat-active-resolution.ts
+++ b/mobile/src/session/use-mobile-native-chat-active-resolution.ts
@@ -1,5 +1,5 @@
import { useLayoutEffect, useRef, type MutableRefObject } from 'react'
-import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat-transcript-retention'
+import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat/transcript/native-chat-transcript-retention'
import {
resolveMobileNativeChat,
type MobileNativeChatTab
diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts
index 78c33a0529e..7aafafad5b7 100644
--- a/mobile/src/session/use-mobile-native-chat-controller.ts
+++ b/mobile/src/session/use-mobile-native-chat-controller.ts
@@ -36,6 +36,7 @@ export function useMobileNativeChatController(args: {
agentSessionHostSupport?: StructuredAgentSessionHostSupport | null
onSendError: Parameters[0]['onSendError']
// Any accepted chat write clears the held failure banner, including answers and permission replies.
+ onQueuedEditNotice?: (message: string) => void
onSendResolved: () => void
}): MobileNativeChatController {
const {
@@ -73,16 +74,14 @@ export function useMobileNativeChatController(args: {
// Fixed hook order mounts the lane before drafts; defer Edit’s append through a ref and delete nothing until copying succeeds.
const appendComposerTextRef = useRef<(text: string) => boolean>(() => false)
const nativeChatLane = useMobileNativeChatSessionLane({
- client,
- hostId,
+ ...args,
+ composerScopeKey: mobileNativeChatScopeKey(hostId, worktreeId, activeSessionTabId),
structured: activeChatStructured,
resolution: activeChatResolution,
sourceIdentity,
enabled: showNativeChat,
- connState,
hostSupport: agentSessionHostSupport,
appendComposerTextRef,
- onSendError,
onActionResolved: onSendResolved
})
const { structuredSession: structuredNativeChat, session: nativeChatSession } = nativeChatLane
@@ -251,6 +250,8 @@ export function useMobileNativeChatController(args: {
})
return {
+ reportQueuedEditError: onSendError,
+ chatComposerScopeKey: mobileNativeChatScopeKey(hostId, worktreeId, activeSessionTabId),
sessionViewReady,
isTabChatView,
setTabView,
diff --git a/mobile/src/session/use-mobile-native-chat-session-lane.ts b/mobile/src/session/use-mobile-native-chat-session-lane.ts
index b1fb1138f2f..0d12a6a3754 100644
--- a/mobile/src/session/use-mobile-native-chat-session-lane.ts
+++ b/mobile/src/session/use-mobile-native-chat-session-lane.ts
@@ -12,6 +12,7 @@ import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile
export function useMobileNativeChatSessionLane({
client,
hostId,
+ composerScopeKey,
structured,
resolution,
sourceIdentity,
@@ -20,10 +21,12 @@ export function useMobileNativeChatSessionLane({
enabled,
connState,
onSendError,
+ onQueuedEditNotice,
onActionResolved
}: {
client: RpcClient | null
hostId: string
+ composerScopeKey?: string | null
structured: boolean
resolution: MobileNativeChatResolution | null
sourceIdentity: Parameters[0]['sourceIdentity']
@@ -32,6 +35,7 @@ export function useMobileNativeChatSessionLane({
appendComposerTextRef: { readonly current: (text: string) => boolean }
enabled: boolean
connState: ConnectionState
+ onQueuedEditNotice?: (message: string) => void
onSendError: MobileNativeChatSendErrorReporter
onActionResolved?: () => void
}): {
@@ -65,6 +69,7 @@ export function useMobileNativeChatSessionLane({
sourceIdentity,
hostSupport,
appendComposerText,
+ composerScopeKey,
enabled,
// Holds are connection-scoped; dropping this on transport loss lets the hook
// reacquire the provider without clearing the cached transcript.
@@ -72,6 +77,7 @@ export function useMobileNativeChatSessionLane({
agent: structured ? agent : null,
sessionCommands: sessionCommands.commands,
onSendError,
+ onQueuedEditNotice,
...(onActionResolved ? { onActionResolved } : {})
})
return {
diff --git a/mobile/src/session/use-mobile-native-chat-session.ts b/mobile/src/session/use-mobile-native-chat-session.ts
index a1862ac24ee..9d4dfd91813 100644
--- a/mobile/src/session/use-mobile-native-chat-session.ts
+++ b/mobile/src/session/use-mobile-native-chat-session.ts
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import {
createNativeChatTranscriptRetention,
encodeNativeChatTranscriptIdentity
-} from '../../../src/shared/native-chat-transcript-retention'
+} from '../../../src/shared/native-chat/transcript/native-chat-transcript-retention'
import { createNativeChatMerger, replaceList } from '../../../src/shared/native-chat-merge'
import type {
NativeChatMessage,
diff --git a/mobile/src/session/use-mobile-queued-edit-replacement.test.tsx b/mobile/src/session/use-mobile-queued-edit-replacement.test.tsx
new file mode 100644
index 00000000000..ec1ab7e3e23
--- /dev/null
+++ b/mobile/src/session/use-mobile-queued-edit-replacement.test.tsx
@@ -0,0 +1,321 @@
+import { createElement } from 'react'
+import { act } from 'react-test-renderer'
+import { describe, expect, it, vi } from 'vitest'
+import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
+import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
+import { queuedMessageUpdateDecision } from '../../../src/main/native-chat/agent-session-journal/queued-message-update'
+import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
+import type { RpcResponse } from '../transport/types'
+import {
+ mobileNativeChatDraftDestination,
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
+import {
+ SESSION_ID,
+ batchEvent,
+ fieldsOf,
+ mutationOk,
+ queuedDraft
+} from './use-mobile-structured-agent-session-queued.test-fixture'
+import {
+ mobileQueuedEditHarness,
+ withText,
+ readOrHoldReply
+} from './mobile-queued-edit-hook.test-fixture'
+
+describe('mobile queued replacement contracts', () => {
+ const { state, Harness, mount, sendRequest, append, notice, resolved, requestedFingerprint } =
+ mobileQueuedEditHarness()
+ it.each(['refused', 'unknown-committed', 'unknown-refused-unchanged'] as const)(
+ 'restored seed after %s follows host CAS without a stale accepted action',
+ async (mode) => {
+ const message = queuedDraft({
+ messageId: 'seed',
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'base' }] }
+ })
+ await mount(message)
+ const updates = () =>
+ sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
+ .length
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ if (mode === 'refused') {
+ return mutationOk({ status: 'not-editable', messageId: 'seed' })
+ }
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ })
+ act(() => state.hook!.queued.editor!.change('attempt'))
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ if (mode === 'unknown-refused-unchanged') {
+ sendRequest.mockImplementation(async (method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? mutationOk({ status: 'not-editable', messageId: 'seed' })
+ : readOrHoldReply(method, params)
+ )
+ act(() => state.hook!.queued.editor!.change('refused later'))
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ }
+ act(() => state.hook!.queued.editor!.change('base'))
+ const before = updates()
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method !== 'agentSession.queuedMessageUpdate') {
+ return readOrHoldReply(method, params)
+ }
+ const body = mode === 'unknown-committed' ? withText(message.body, 'attempt') : message.body
+ const result = queuedMessageUpdateDecision(
+ {
+ messageId: 'seed',
+ position: 1,
+ body,
+ fingerprint: agentSessionSendBodyFingerprint(SESSION_ID, body),
+ state: 'waiting',
+ holdReason: null,
+ returnedReason: null,
+ returnedRejection: null,
+ consumedAs: null,
+ queuedAt: null
+ },
+ SESSION_ID,
+ {
+ messageId: 'seed',
+ expectedBodyFingerprint: String(fieldsOf(params).expectedBodyFingerprint),
+ text: String(fieldsOf(params).text)
+ }
+ )
+ if (result.status === 'ready') {
+ throw new Error('unexpected ready')
+ }
+ return mutationOk(result)
+ })
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ expect(updates()).toBe(before + (mode === 'refused' ? 0 : 1))
+ if (mode === 'unknown-refused-unchanged') {
+ expect(state.hook!.queued.editor).toMatchObject({
+ text: 'base',
+ saving: false,
+ canSave: true
+ })
+ act(() => state.listener?.(batchEvent([{ ...message }])))
+ expect(state.hook!.queued.editor).toBeDefined()
+ expect(resolved).not.toHaveBeenCalled()
+ } else {
+ expect(state.hook!.queued.editor).toBeUndefined()
+ }
+ expect(append).toHaveBeenCalledTimes(mode === 'unknown-committed' ? 1 : 0)
+ expect(notice).toHaveBeenCalledTimes(mode === 'unknown-committed' ? 1 : 0)
+ }
+ )
+
+ it('joins state.menu re-pick after unknown proof to a complete next Save RPC and retained tray', async () => {
+ const message = queuedDraft({
+ messageId: 'rich-proof',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [{ type: 'text', text: '$review original' }],
+ skills: [{ name: 'review', path: '/A/SKILL.md' }]
+ }
+ })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer?.update(
+ createElement(Harness, {
+ skillsSupport: true,
+ imagesSupport: true,
+ composerScopeKey: 'original-bottom'
+ })
+ )
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!('rich-proof')
+ })
+ act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method === 'agentSession.queuedMessageUpdate') {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return readOrHoldReply(method, params)
+ })
+ act(() => state.hook!.queued.editor!.change('$review'))
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ vi.stubGlobal('structuredClone', undefined)
+ const key = state.hook!.queued.editor!.scopeKey
+ const accepted = queuedMessageWithEdit(message.body, {
+ text: '$review',
+ skills: [{ name: 'review', path: '/A/SKILL.md' }],
+ images: []
+ })
+ if (!accepted.ok) {
+ throw new Error(accepted.reason)
+ }
+ act(() => state.hook!.queued.editor!.change('/rev'))
+ act(() => state.menu!.onSelectionChange({ start: 4, end: 4 }))
+ const row = state.menu!.rows.find(
+ (entry) => entry.kind === 'skill' && entry.path === '/B/SKILL.md'
+ )
+ expect(row).toBeDefined()
+ act(() => state.menu!.pick(row!))
+ act(() => state.hook!.queued.editor!.change(`${state.hook!.queued.editor!.text}suffix`))
+ act(() =>
+ updateMobileNativeChatDraftInputs(key, (before) => ({
+ ...before,
+ images: [{ id: 'uploaded', path: '/new.png', previewUri: '/new.png' }]
+ }))
+ )
+ const inputs = readMobileNativeChatDraftInputs(key)
+ act(() => state.listener?.(batchEvent([{ ...message, body: accepted.body }])))
+ expect(state.hook!.queued.editor).toMatchObject({
+ scopeKey: key,
+ text: '$review suffix',
+ saving: false
+ })
+ expect(readMobileNativeChatDraftInputs(key)).toEqual(inputs)
+ expect(state.bottomText).toBe('occupied')
+ expect(resolved).not.toHaveBeenCalled()
+ const holds = sendRequest.mock.calls
+ .filter(
+ ([method, params]) =>
+ method === 'agentSession.queuedMessageEditHold' && fieldsOf(params).action === 'acquire'
+ )
+ .map(([, params]) => fieldsOf(params))
+ expect(holds.at(-1)).toMatchObject({
+ expectedBodyFingerprint: agentSessionSendBodyFingerprint(SESSION_ID, accepted.body)
+ })
+ expect(holds.at(-1)?.editId).not.toBe(holds.at(-2)?.editId)
+ sendRequest.mockImplementation(async (method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? mutationOk({
+ status: 'updated',
+ messageId: message.messageId,
+ fingerprint: requestedFingerprint(message)
+ })
+ : readOrHoldReply(method, params)
+ )
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ const update = sendRequest.mock.calls.findLast(
+ ([method]) => method === 'agentSession.queuedMessageUpdate'
+ )
+ expect(fieldsOf(update?.[1])).toMatchObject({
+ text: '$review suffix',
+ skills: [{ name: 'review', path: '/B/SKILL.md' }],
+ images: [{ type: 'image-ref', path: '/new.png' }],
+ expectedBodyFingerprint: agentSessionSendBodyFingerprint(SESSION_ID, accepted.body)
+ })
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(resolved).toHaveBeenCalledOnce()
+ expect(state.bottomText).toBe('occupied')
+ })
+ it('hands back a full retained replacement and pending operations once with exact accepted-image exclusion', async () => {
+ const message = queuedDraft({
+ messageId: 'rebase-images',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [
+ { type: 'text', text: 'original' },
+ { type: 'image-ref', path: '/original.png', alt: 'original' }
+ ]
+ }
+ })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer?.update(
+ createElement(Harness, { imagesSupport: true, composerScopeKey: 'original-bottom' })
+ )
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!('rebase-images')
+ })
+ act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
+ const key = state.hook!.queued.editor!.scopeKey
+ act(() => {
+ state.hook!.queued.editor!.change('submitted')
+ updateMobileNativeChatDraftInputs(key, (before) => ({
+ ...before,
+ images: [
+ ...before.images,
+ { id: 'uploaded', path: '/accepted.png', previewUri: '/accepted.png' }
+ ]
+ }))
+ })
+ let finish: ((response: RpcResponse) => void) | undefined
+ sendRequest.mockImplementation((method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? new Promise((resolve) => {
+ finish = resolve
+ })
+ : Promise.resolve(readOrHoldReply(method, params))
+ )
+ let saving: Promise | undefined
+ act(() => {
+ saving = state.hook!.queued.editor!.save()
+ })
+ const voice = state.hook!.queued.editor!.insertDictation!
+ act(() => {
+ voice('newer')
+ })
+ await act(async () => {
+ finish!(
+ mutationOk({
+ status: 'updated',
+ messageId: message.messageId,
+ fingerprint: requestedFingerprint(message)
+ })
+ )
+ await saving
+ })
+ expect(state.hook!.queued.editor).toMatchObject({ text: 'submitted newer', saving: false })
+ expect(resolved).not.toHaveBeenCalled()
+ const operation = mobileNativeChatDraftDestination(key)
+ act(() =>
+ updateMobileNativeChatDraftInputs(operation, (before) => ({
+ ...before,
+ images: [
+ ...before.images.filter(({ id }) => id !== 'uploaded'),
+ { id: 'uploaded', path: '/changed.png', previewUri: '/changed.png' }
+ ],
+ files: [{ id: 'file', name: 'report.txt', path: null, mime: 'text/plain', byteLength: 3 }],
+ pending: 1
+ }))
+ )
+ act(() => state.listener?.(batchEvent([])))
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(state.bottomText).toBe('occupied\n\nsubmitted newer')
+ expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
+ images: [{ id: 'uploaded', path: '/changed.png' }],
+ pending: 1
+ })
+ act(() =>
+ updateMobileNativeChatDraftInputs(operation, (before) => ({
+ ...before,
+ files: before.files.map((file) => ({ ...file, path: '/report.txt' })),
+ pending: 0
+ }))
+ )
+ act(() => {
+ voice('newer')
+ state.listener?.(batchEvent([]))
+ })
+ expect(state.bottomText).toBe('occupied\n\nsubmitted newer newer')
+ expect(readMobileNativeChatDraftInputs('original-bottom').files).toMatchObject([
+ { path: '/report.txt' }
+ ])
+ expect(notice).toHaveBeenCalledOnce()
+ })
+})
diff --git a/mobile/src/session/use-mobile-session-image-attachments.test.tsx b/mobile/src/session/use-mobile-session-image-attachments.test.tsx
index 2719eaf2ccf..b99ace3c67a 100644
--- a/mobile/src/session/use-mobile-session-image-attachments.test.tsx
+++ b/mobile/src/session/use-mobile-session-image-attachments.test.tsx
@@ -1,4 +1,5 @@
import { createElement } from 'react'
+import { resetMobileNativeChatDraftInputsForTests } from './native-chat/composer/mobile-native-chat-draft-inputs'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes'
@@ -66,6 +67,7 @@ describe('useMobileSessionImageAttachments', () => {
}
beforeEach(() => {
+ resetMobileNativeChatDraftInputsForTests()
vi.useFakeTimers()
resetMobileNativeChatStaleInputForTests()
resetMobileNativeChatTerminalWritesForTests()
@@ -85,7 +87,7 @@ describe('useMobileSessionImageAttachments', () => {
await hook.nativeChatImages.attachImage('library')
})
expect(hook.nativeChatImages.attachments).toEqual([
- { id: 'img-1', path: '/tmp/a.png', previewUri: 'file:///a.jpg' }
+ { id: expect.any(String), path: '/tmp/a.png', previewUri: 'file:///a.jpg' }
])
}
@@ -102,13 +104,14 @@ describe('useMobileSessionImageAttachments', () => {
it('sends structured session images without a terminal input lease', async () => {
const args = baseArgs({ activeHandle: null, activeHandleRef: { current: null } })
await renderWithImage(args)
+ const image = hook.nativeChatImages.attachments[0]
expect(await send()).toBe(true)
expect(args.nativeChatBaseSend).toHaveBeenCalledWith(
'look',
['file:///a.jpg'],
expect.any(Number),
- [{ id: 'img-1', path: '/tmp/a.png', previewUri: 'file:///a.jpg' }]
+ [image]
)
expect(args.client.sendRequest.mock.calls.map(([method]) => method)).toEqual([
'clipboard.startImageUpload',
diff --git a/mobile/src/session/use-mobile-session-native-chat-dictation.ts b/mobile/src/session/use-mobile-session-native-chat-dictation.ts
index a0dfc71ba7c..c173eeac3b3 100644
--- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts
+++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts
@@ -1,3 +1,4 @@
+import { captureMobileNativeChatTextDestination } from './native-chat/composer/mobile-native-chat-draft-inputs'
import { useEffect, useCallback, useRef } from 'react'
import { AppState } from 'react-native'
import { useFocusEffect } from 'expo-router'
@@ -81,6 +82,7 @@ export function useMobileSessionNativeChatDictation(
connState,
agentSessionHostSupport,
onSendError: nativeChatSendError.show,
+ onQueuedEditNotice: showToast,
onSendResolved: nativeChatSendError.clear
})
const { toggleTabChatView, showNativeChat, showNativeChatRef } = nativeChatController
@@ -114,16 +116,25 @@ export function useMobileSessionNativeChatDictation(
[setShowDictationSetup, showToast]
)
+ const chatDictationDestination = useRef<((text: string) => boolean | void) | undefined>(undefined)
const dictationTargetReady = showNativeChat ? connState === 'connected' : canSend
const dictation = useMobileDictation({
client,
enabled: dictationTargetReady && dictationEnabled,
onTranscript: (text) => {
// Route dictation to the visible chat composer locally; terminal mode retains live-input routing.
- if (showNativeChatRef.current) {
- nativeChatController.setChatComposerText((current) =>
- appendBufferedDictation(current, text)
- )
+ if (showNativeChatRef.current || chatDictationDestination.current) {
+ const insert = chatDictationDestination.current
+ chatDictationDestination.current = undefined
+ if (insert) {
+ if (insert(text) === false) {
+ return
+ }
+ } else {
+ nativeChatController.setChatComposerText((current) =>
+ appendBufferedDictation(current, text)
+ )
+ }
showToast('Dictation inserted')
return
}
@@ -160,6 +171,7 @@ export function useMobileSessionNativeChatDictation(
})
const startDictation = useCallback(() => {
+ chatDictationDestination.current = captureMobileNativeChatTextDestination()
const routeContext = activeHandle
? { handle: activeHandle, liveInputEnabled: liveInputTerminalHandles.has(activeHandle) }
: null
diff --git a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx
index 208383bf865..be178992178 100644
--- a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx
+++ b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx
@@ -1,3 +1,7 @@
+import {
+ updateMobileNativeChatDraftInputs,
+ resetMobileNativeChatDraftInputsForTests
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { createElement, useState } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -12,6 +16,9 @@ import {
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
import { structuredSendResultFixture } from './structured-agent-send-result.test-fixture'
import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'
+import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge'
+import { useMobileNativeChatDrafts } from './native-chat/composer/use-mobile-native-chat-drafts'
+import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire'
import {
AGENT_SESSION_SEND_OPTIONS_RUNTIME_CAPABILITY,
AGENT_SESSION_SEND_SKILLS_RUNTIME_CAPABILITY
@@ -61,6 +68,8 @@ describe('mobile structured send actions', () => {
let listener: ((value: unknown) => void) | null = null
let storedOperations: Map
let agent = 'codex'
+ let sessionCommands: readonly AgentSessionSlashCommand[] | undefined
+ let sendOrdinary: ReturnType['sendWithOutcome']
let hostSupport: StructuredAgentSessionHostSupport | null = null
const onSendError = vi.fn()
const sendRequest = vi.fn()
@@ -104,18 +113,39 @@ describe('mobile structured send actions', () => {
client,
sessionId: 'session-1',
sourceIdentity: 'host-a\0workspace-a',
+ composerScopeKey: 'ordinary-draft',
enabled: true,
connected: true,
agent,
+ sessionCommands,
hostSupport,
onSendError
})
return createElement('span', null, banner.message)
}
- async function mountSession(): Promise {
+ function BridgeHarness() {
+ const drafts = useMobileNativeChatDrafts({
+ hostId: 'host-a',
+ worktreeId: 'workspace-a',
+ tabId: 'performance',
+ sessionId: 'session-1',
+ messages: [],
+ transcriptSettled: true
+ })
+ sendOrdinary = useMobileStructuredNativeChatSendBridge({
+ ...drafts,
+ agent: 'codex',
+ sessionCommands,
+ sendStructured: (...args) => hook!.sendWithOutcome(...args),
+ onSendError
+ }).sendWithOutcome
+ return createElement(Harness)
+ }
+
+ async function mountSession(ordinary = false): Promise {
act(() => {
- renderer = create(createElement(Harness))
+ renderer = create(createElement(ordinary ? BridgeHarness : Harness))
})
await vi.waitFor(() => expect(listener).toEqual(expect.any(Function)))
act(() => listener?.(snapshotEvent()))
@@ -159,9 +189,50 @@ describe('mobile structured send actions', () => {
banner = null
listener = null
agent = 'codex'
+ sessionCommands = undefined
hostSupport = null
+ resetMobileNativeChatDraftInputsForTests()
})
+ it.each([10, 100])(
+ 'ordinary phone bridge and Send skip %i commands for prose but still route slash controls',
+ async (count) => {
+ let kinds = 0
+ let names = 0
+ sessionCommands = Array.from({ length: count }, (_, index) => ({
+ get kind() {
+ kinds++
+ return 'command' as const
+ },
+ get name() {
+ names++
+ return `provider-${index}`
+ }
+ }))
+ sendRequest.mockImplementation(async (method) =>
+ method === 'agentSession.send' ? sendResult('accepted') : ok({})
+ )
+ await mountSession(true)
+ kinds = 0
+ names = 0
+ await act(async () => {
+ expect(await sendOrdinary('hello')).toBe('accepted')
+ })
+ expect(calls()).toHaveLength(1)
+ expect(fieldsOf(calls()[0]![1]).body).toMatchObject({
+ blocks: [{ type: 'text', text: 'hello' }]
+ })
+ expect({ kinds, names }).toEqual({ kinds: 0, names: 0 })
+ await act(async () => {
+ expect(await sendOrdinary('/compact extra')).toBe('rejected')
+ })
+ expect(calls()).toHaveLength(1)
+ expect(onSendError).toHaveBeenCalledWith('Use /compact without arguments.', undefined)
+ expect(kinds).toBeGreaterThanOrEqual(count)
+ expect(names).toBeGreaterThanOrEqual(count)
+ }
+ )
+
it('selects a native OMP skill and sends the exact token and arguments through RPC', async () => {
agent = 'omp'
sendRequest.mockImplementation(async (method) =>
@@ -518,6 +589,23 @@ describe('mobile structured send actions', () => {
}
)
+ it('does not infer omitted captured skills from the live composer draft', async () => {
+ hostSupport = structuredAgentSessionHostSupport([AGENT_SESSION_SEND_SKILLS_RUNTIME_CAPABILITY])
+ sendRequest.mockImplementation(async (method) =>
+ method === 'agentSession.send' ? sendResult('accepted') : ok({ models: [], current: {} })
+ )
+ updateMobileNativeChatDraftInputs('ordinary-draft', () => ({
+ images: [],
+ files: [],
+ skills: [{ name: 'review', path: '/live/SKILL.md' }]
+ }))
+ await mountSession()
+ await act(async () => {
+ await hook!.sendWithOutcome('$review text')
+ })
+ expect(fieldsOf(calls()[0]?.[1]).body).not.toHaveProperty('skills')
+ })
+
it('sends an attached file as a reference after the text, and only images as image blocks', async () => {
sendRequest.mockImplementation(async (method) =>
method === 'agentSession.send' ? sendResult('accepted') : ok({ models: [], current: {} })
diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts
index 7a34a3200ab..4e001fe5c46 100644
--- a/mobile/src/session/use-mobile-structured-agent-session.ts
+++ b/mobile/src/session/use-mobile-structured-agent-session.ts
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useRef } from 'react'
-import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat-transcript-retention'
+import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat/transcript/native-chat-transcript-retention'
import { projectStructuredAgentSessionMessages } from '../../../src/shared/structured-agent-session-message-projection'
import {
projectStructuredQuestionMessages,
@@ -53,7 +53,6 @@ export function useMobileStructuredAgentSession(
): StructuredMobileSession {
const {
agent,
- appendComposerText,
client,
connected,
sessionId,
@@ -220,6 +219,8 @@ export function useMobileStructuredAgentSession(
[approvalPrompt, questionPrompt, queueSendsNext, turnId]
)
const queued = useMobileStructuredQueuedMessageControls({
+ ...args,
+ appendComposerText: args.appendComposerText,
sessionKey,
agentName: agent ? (tuiAgentDisplayName(agent) ?? agent) : undefined,
journalItems: state.items,
@@ -227,15 +228,13 @@ export function useMobileStructuredAgentSession(
queuePause,
submissions: state.submissions,
agentWorking: isWorking,
- client,
- sessionId,
+ imagesCapable: hostSupport?.queuedMessageImageEdit === true,
+ skillsCapable: hostSupport?.queuedMessageSkillsEdit === true,
reorderCapable: hostSupport?.queuedMessageReorder === true,
editCapable: hostSupport ? hostSupport.queuedMessageEdit === true : null,
chatActive: enabled,
enabled: enabled && connected,
mutate,
- appendComposerText,
- onSendError,
...(onActionResolved ? { onActionResolved } : {})
})
// Stop preserves host-held cards under queue pause; only a later user action resumes them.
diff --git a/mobile/src/session/use-mobile-structured-queued-edit.test.tsx b/mobile/src/session/use-mobile-structured-queued-edit.test.tsx
index a93901ec9c3..ce80299c06a 100644
--- a/mobile/src/session/use-mobile-structured-queued-edit.test.tsx
+++ b/mobile/src/session/use-mobile-structured-queued-edit.test.tsx
@@ -1,134 +1,48 @@
+import type { RpcClient } from '../transport/rpc-client'
import { createElement } from 'react'
-import { act, create, type ReactTestRenderer } from 'react-test-renderer'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import type {
- AgentSessionQueuedMessage,
- AgentSessionQueuedMessageEditHoldResult
-} from '../../../src/shared/agent-session-wire'
+import { act } from 'react-test-renderer'
+import { describe, expect, it, vi } from 'vitest'
import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
-import type { RpcClient } from '../transport/rpc-client'
import type { RpcResponse } from '../transport/types'
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
-import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'
import {
- CAPABLE,
+ mobileNativeChatDraftDestination,
+ readMobileNativeChatDraftInputs,
+ updateMobileNativeChatDraftInputs
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
+import {
SESSION_ID,
batchEvent,
fieldsOf,
mutationOk,
ok,
- queuedDraft,
- snapshotEvent
+ queuedDraft
} from './use-mobile-structured-agent-session-queued.test-fixture'
-
-function withText(body: AgentSessionQueuedMessage['body'], text: string) {
- const edited = queuedMessageWithEdit(body, { text })
- if (!edited.ok) {
- throw new Error(edited.reason)
- }
- return edited.body
-}
-
-function editHoldReply(params: unknown): RpcResponse {
- const result: AgentSessionQueuedMessageEditHoldResult =
- fieldsOf(params).action === 'release'
- ? { status: 'released' }
- : { status: 'held', fingerprint: 'fp', leaseDurationMs: 120_000, remainingMs: 120_000 }
- return ok(result)
-}
-
-function readOrHoldReply(method: string, params: unknown): RpcResponse {
- return method === 'agentSession.queuedMessageEditHold'
- ? editHoldReply(params)
- : ok({ models: [], current: {} })
-}
-
-vi.mock('@react-native-async-storage/async-storage', () => ({
- default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
-}))
+import {
+ editHoldReply,
+ mobileQueuedEditHarness,
+ withText,
+ readOrHoldReply
+} from './mobile-queued-edit-hook.test-fixture'
describe('mobile in-place queued Edit', () => {
- let renderer: ReactTestRenderer | undefined
- let hook: ReturnType | undefined
- let listener: ((data: unknown) => void) | undefined
- const append = vi.fn(() => true)
- const error = vi.fn()
- const resolved = vi.fn()
- const sendRequest = vi.fn()
- const client: RpcClient = {
+ const {
+ state,
+ Harness,
+ mount,
+ client,
sendRequest,
- subscribe: (_method, _params, onData) => {
- listener = onData
- return () => {}
- },
- updateTerminalSubscriptionViewport: () => {},
- getState: () => 'connected',
- getReconnectAttempt: () => 0,
- getLastConnectedAt: () => null,
- onStateChange: () => () => {},
- notifyForeground: () => {},
- close: () => {}
- }
- function Harness({
- sessionId = SESSION_ID,
- editSupport = true,
- enabled = true,
- connected = true,
- transport = client
- }: {
- sessionId?: string
- editSupport?: boolean | null
- enabled?: boolean
- connected?: boolean
- transport?: RpcClient | null
- }): null {
- hook = useMobileStructuredAgentSession({
- client: transport,
- sessionId,
- sourceIdentity: 'host-a',
- enabled,
- connected,
- agent: 'codex',
- hostSupport:
- editSupport === null
- ? null
- : {
- ...CAPABLE,
- queuedMessages: false,
- queuedMessageEdit: editSupport
- },
- appendComposerText: append,
- onSendError: error,
- onActionResolved: resolved
- })
- return null
- }
- async function mount(message: AgentSessionQueuedMessage, editSupport: boolean | null = true) {
- vi.clearAllMocks()
- sendRequest.mockImplementation(async (method, params) =>
- method === 'agentSession.queuedMessageUpdate'
- ? mutationOk({ status: 'updated', messageId: message.messageId, fingerprint: 'new' })
- : readOrHoldReply(method, params)
- )
- await act(async () => {
- renderer = create(createElement(Harness, { editSupport }))
- })
- act(() => listener?.(snapshotEvent({ queuedMessages: [message], runningTurn: true })))
- if (editSupport !== null) {
- await act(async () => {
- expect(await hook!.queued.edit!(message.messageId)).toBe(true)
- })
- }
- }
- afterEach(async () => {
- await act(async () => renderer?.unmount())
- vi.useRealTimers()
- })
-
+ append,
+ error,
+ notice,
+ resolved,
+ requestedFingerprint
+ } = mobileQueuedEditHarness()
it('waits for the capability probe before offering the legacy fallback', async () => {
await mount(queuedDraft({ messageId: 'draft-1' }), null)
- expect(hook!.queued.edit).toBeUndefined()
+ expect(state.hook!.queued.edit).toBeUndefined()
expect(
sendRequest.mock.calls.some(
([method]) =>
@@ -136,10 +50,108 @@ describe('mobile in-place queued Edit', () => {
method === 'agentSession.queuedMessageEditHold'
)
).toBe(false)
- await act(async () => renderer?.update(createElement(Harness, { editSupport: false })))
- expect(hook!.queued.edit).toEqual(expect.any(Function))
+ await act(async () => state.renderer?.update(createElement(Harness, { editSupport: false })))
+ expect(state.hook!.queued.edit).toEqual(expect.any(Function))
})
+ it.each([
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true]
+ ])(
+ 'sends own optional keys only for host image=%s skill=%s capabilities',
+ async (imagesSupport, skillsSupport) => {
+ const message = queuedDraft({
+ messageId: 'matrix',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [
+ { type: 'text', text: '$review original' },
+ {
+ type: 'image-ref',
+ path: '/host/original.png',
+ alt: 'original'
+ }
+ ],
+ skills: [{ name: 'review', path: '/host/old/SKILL.md' }]
+ }
+ })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer!.update(createElement(Harness, { imagesSupport, skillsSupport }))
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!('matrix')
+ })
+ act(() => state.hook!.queued.editor!.change('$review changed'))
+ await act(async () => {
+ expect(await state.hook!.queued.editor!.save()).toBe(true)
+ })
+ const request = fieldsOf(
+ sendRequest.mock.calls.find(
+ ([method]) => method === 'agentSession.queuedMessageUpdate'
+ )?.[1]
+ )
+ expect(Object.hasOwn(request, 'images')).toBe(imagesSupport)
+ expect(Object.hasOwn(request, 'skills')).toBe(skillsSupport)
+ if (imagesSupport) {
+ expect(request.images).toEqual([message.body.blocks[1]])
+ }
+ if (skillsSupport) {
+ expect(request.skills).toEqual(message.body.skills)
+ }
+ // The old-host path leaves image blocks on the host while changing only text.
+ const edited = queuedMessageWithEdit(message.body, {
+ text: String(request.text),
+ ...(imagesSupport
+ ? {
+ images: [
+ {
+ type: 'image-ref' as const,
+ path: '/host/original.png',
+ alt: 'original'
+ }
+ ]
+ }
+ : {}),
+ ...(skillsSupport ? { skills: message.body.skills } : {})
+ })
+ expect(edited.ok && edited.body.blocks.filter((block) => block.type === 'image-ref')).toEqual(
+ [message.body.blocks[1]]
+ )
+ }
+ )
+
+ it.each([false, true])(
+ 'clean departure redirects captured dictation and Cancel=%s retires it',
+ async (cancel) => {
+ await mount(queuedDraft({ messageId: 'clean-dictation' }))
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer!.update(createElement(Harness, { composerScopeKey: 'original-bottom' }))
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!('clean-dictation')
+ })
+ const insert = state.hook!.queued.editor!.insertDictation!
+ if (cancel) {
+ act(() => state.hook!.queued.editor!.cancel())
+ } else {
+ await act(async () =>
+ state.renderer!.update(
+ createElement(Harness, { sessionId: 'elsewhere', composerScopeKey: 'elsewhere' })
+ )
+ )
+ }
+ act(() => setMobileNativeChatDraftText('original-bottom', 'bottom'))
+ act(() => expect(insert('later')).toBe(!cancel))
+ expect(state.bottomText).toBe(cancel ? 'bottom' : 'bottom later')
+ }
+ )
+
it('holds and renews a card while typing, sends only its edited text, and cancels in place', async () => {
const message = queuedDraft({
messageId: 'image-card',
@@ -168,9 +180,9 @@ describe('mobile in-place queued Edit', () => {
expectedBodyFingerprint: agentSessionSendBodyFingerprint(SESSION_ID, message.body)
})
expect(fieldsOf(holdCalls()[1]?.[1])).toMatchObject({ action: 'renew', editId: acquire.editId })
- act(() => hook!.queued.editor!.change('edited'))
+ act(() => state.hook!.queued.editor!.change('edited'))
await act(async () => {
- expect(await hook!.queued.editor!.save()).toBe(true)
+ expect(await state.hook!.queued.editor!.save()).toBe(true)
})
const update = sendRequest.mock.calls.find(
([method]) => method === 'agentSession.queuedMessageUpdate'
@@ -182,26 +194,26 @@ describe('mobile in-place queued Edit', () => {
})
expect(fieldsOf(update?.[1])).not.toHaveProperty('body')
const body = withText(message.body, 'edited')
- act(() => listener?.(batchEvent([{ ...message, body }])))
- expect(hook!.queued.cards).toMatchObject([{ messageId: 'image-card', text: 'edited' }])
- expect(hook!.queued.editor).toBeUndefined()
+ act(() => state.listener?.(batchEvent([{ ...message, body }])))
+ expect(state.hook!.queued.cards).toMatchObject([{ messageId: 'image-card', text: 'edited' }])
+ expect(state.hook!.queued.editor).toBeUndefined()
expect(fieldsOf(holdCalls().at(-1)?.[1])).toMatchObject({
action: 'release',
editId: acquire.editId
})
await act(async () => {
- await hook!.queued.edit!('image-card')
+ await state.hook!.queued.edit!('image-card')
})
- act(() => hook!.queued.editor!.change('cancelled'))
- await act(async () => hook!.queued.editor!.cancel())
- expect(hook!.queued.cards[0]?.text).toBe('edited')
+ act(() => state.hook!.queued.editor!.change('cancelled'))
+ await act(async () => state.hook!.queued.editor!.cancel())
+ expect(state.hook!.queued.cards[0]?.text).toBe('edited')
expect(
sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageDelete')
).toBe(false)
expect(append).not.toHaveBeenCalled()
})
- it('hands a stale Save to the composer and reopens on the newer text; closes an unconfirmed one the card holds', async () => {
+ it('hands a conflicted edit back once and reconciles a lost reply from the published desired body', async () => {
const message = queuedDraft({ messageId: 'draft-1' })
await mount(message)
const newer = withText(message.body, 'edited elsewhere')
@@ -209,48 +221,118 @@ describe('mobile in-place queued Edit', () => {
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
- listener?.(batchEvent([{ ...message, body: newer }]))
+ state.listener?.(batchEvent([{ ...message, body: newer }]))
return mutationOk({ status: 'changed', messageId: 'draft-1' })
})
- act(() => hook!.queued.editor!.change('my text'))
+ act(() => state.hook!.queued.editor!.change('my text'))
await act(async () => {
- expect(await hook!.queued.editor!.save()).toBe(false)
+ expect(await state.hook!.queued.editor!.save()).toBe(false)
})
- expect(append).toHaveBeenCalledWith('my text')
- expect(error).toHaveBeenCalledWith(
- 'This message changed while you were editing. Your edit is in the chat box.'
- )
- expect(hook!.queued.editor).toMatchObject({ messageId: 'draft-1', text: 'edited elsewhere' })
- act(() => hook!.queued.editor!.change('saved text'))
+ expect(append).toHaveBeenCalledExactlyOnceWith('my text')
+ expect(notice).toHaveBeenCalledExactlyOnceWith('Your edit is in the chat box.')
+ expect(state.hook!.queued.editor).toBeUndefined()
+ await act(async () => {
+ await state.hook!.queued.edit!('draft-1')
+ })
+ act(() => state.hook!.queued.editor!.change('saved text'))
const body = withText(message.body, 'saved text')
sendRequest.mockImplementation(async (method, params) => {
if (method === 'agentSession.queuedMessageUpdate') {
- listener?.(batchEvent([{ ...message, body }]))
+ state.listener?.(batchEvent([{ ...message, body }]))
throw markRpcDeliveryUnknown(new Error('reply lost'))
}
return readOrHoldReply(method, params)
})
await act(async () => {
- await hook!.queued.editor!.save()
+ await state.hook!.queued.editor!.save()
})
- expect(hook!.queued.editor).toBeUndefined()
- expect(hook!.queued.cards[0]?.text).toBe('saved text')
- const retry = sendRequest.mock.calls.findLast(
- ([method]) => method === 'agentSession.queuedMessageUpdate'
- )
- expect(fieldsOf(retry?.[1]).expectedBodyFingerprint).toBe(
- agentSessionSendBodyFingerprint(SESSION_ID, newer)
- )
- expect(error).toHaveBeenCalledTimes(1)
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(state.hook!.queued.cards[0]?.text).toBe('saved text')
+ expect(error).not.toHaveBeenCalled()
expect(append).toHaveBeenCalledTimes(1)
})
- it('hands unsaved typing to the composer and releases the hold when changing chats', async () => {
+ it('preserves typing made after an unknown result when delayed proof arrives', async () => {
+ const message = queuedDraft({ messageId: 'late-proof' })
+ await mount(message)
+ sendRequest.mockImplementation(async (method, params) => {
+ if (method === 'agentSession.queuedMessageUpdate') {
+ throw markRpcDeliveryUnknown(new Error('lost'))
+ }
+ return readOrHoldReply(method, params)
+ })
+ act(() => state.hook!.queued.editor!.change('submitted'))
+ await act(async () => {
+ await state.hook!.queued.editor!.save()
+ })
+ act(() => state.hook!.queued.editor!.change('submitted plus unsaved'))
+ act(() =>
+ state.listener?.(batchEvent([{ ...message, body: withText(message.body, 'submitted') }]))
+ )
+ expect(state.hook!.queued.editor).toMatchObject({
+ text: 'submitted plus unsaved',
+ saving: false
+ })
+ expect(append).not.toHaveBeenCalled()
+ expect(resolved).not.toHaveBeenCalled()
+ })
+
+ it.each(['updated', 'not-editable'] as const)(
+ 'retains dictation during a deferred %s Save and after success',
+ async (status) => {
+ const message = queuedDraft({ messageId: 'dictation-save' })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer?.update(createElement(Harness, { composerScopeKey: 'original-bottom' }))
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!(message.messageId)
+ })
+ let reply: ((response: RpcResponse) => void) | undefined
+ sendRequest.mockImplementation((method, params) =>
+ method === 'agentSession.queuedMessageUpdate'
+ ? new Promise((resolve) => {
+ reply = resolve
+ })
+ : Promise.resolve(readOrHoldReply(method, params))
+ )
+ act(() => state.hook!.queued.editor!.change('submitted'))
+ const insert = state.hook!.queued.editor!.insertDictation!
+ let saving: Promise | undefined
+ act(() => {
+ saving = state.hook!.queued.editor!.save()
+ })
+ act(() => {
+ expect(insert('speech')).toBe(true)
+ })
+ await act(async () => {
+ reply!(mutationOk({ status, messageId: message.messageId }))
+ await saving
+ })
+ if (status === 'updated') {
+ expect(state.bottomText).toBe('')
+ expect(state.hook!.queued.editor!.text).toBe('submitted speech')
+ act(() => {
+ expect(insert('later')).toBe(true)
+ })
+ expect(state.bottomText).toBe('')
+ expect(state.hook!.queued.editor!.text).toBe('submitted speech later')
+ } else {
+ expect(state.hook!.queued.editor!.text).toBe('submitted speech')
+ }
+ }
+ )
+
+ it('preserves unsaved typing once and releases the hold when changing chats', async () => {
await mount(queuedDraft({ messageId: 'draft-1' }))
- act(() => hook!.queued.editor!.change('unsaved'))
- await act(async () => renderer?.update(createElement(Harness, { sessionId: 'other-chat' })))
+ act(() => state.hook!.queued.editor!.change('unsaved'))
+ await act(async () =>
+ state.renderer?.update(createElement(Harness, { sessionId: 'other-chat' }))
+ )
expect(append).toHaveBeenCalledExactlyOnceWith('unsaved')
- expect(hook!.queued.editor).toBeUndefined()
+ expect(notice).toHaveBeenCalledOnce()
+ expect(state.hook!.queued.editor).toBeUndefined()
expect(
sendRequest.mock.calls
.filter(([method]) => method === 'agentSession.queuedMessageEditHold')
@@ -259,7 +341,7 @@ describe('mobile in-place queued Edit', () => {
})
it.each(['updated', 'changed'] as const)(
- 'ignores a deferred %s reply after leaving the chat',
+ 'lets the submitted snapshot own a deferred %s reply after leaving the chat',
async (status) => {
const message = queuedDraft({ messageId: 'deferred-card' })
await mount(message)
@@ -271,30 +353,42 @@ describe('mobile in-place queued Edit', () => {
})
: Promise.resolve(readOrHoldReply(method, params))
)
- act(() => hook!.queued.editor!.change('edited in place'))
+ act(() => state.hook!.queued.editor!.change('edited in place'))
let save: Promise | undefined
act(() => {
- save = hook!.queued.editor!.save()
+ save = state.hook!.queued.editor!.save()
})
- expect(hook!.queued.editor!.saving).toBe(true)
- await act(async () => renderer?.update(createElement(Harness, { sessionId: 'other-chat' })))
- expect(append).toHaveBeenCalledExactlyOnceWith('edited in place')
+ expect(state.hook!.queued.editor!.saving).toBe(true)
+ await act(async () =>
+ state.renderer?.update(createElement(Harness, { sessionId: 'other-chat' }))
+ )
+ expect(append).not.toHaveBeenCalled()
await act(async () => {
- answer?.(mutationOk({ status, messageId: message.messageId, fingerprint: 'new' }))
+ answer?.(
+ mutationOk({
+ status,
+ messageId: message.messageId,
+ fingerprint: requestedFingerprint(message)
+ })
+ )
await save
})
- expect(append).toHaveBeenCalledTimes(1)
+ if (status === 'changed') {
+ expect(append).toHaveBeenCalledExactlyOnceWith('edited in place')
+ expect(notice).toHaveBeenCalledOnce()
+ } else {
+ expect(append).not.toHaveBeenCalled()
+ expect(notice).not.toHaveBeenCalled()
+ }
expect(error).not.toHaveBeenCalled()
expect(resolved).not.toHaveBeenCalled()
- expect(hook!.queued.editor).toBeUndefined()
+ expect(state.hook!.queued.editor).toBeUndefined()
}
)
- it('lets an in-flight Save decide a removed card: its refusal hands the typing to the composer', async () => {
+ it('leaves a disappeared card to its in-flight Save and returns a refused submitted draft once', async () => {
const message = queuedDraft({ messageId: 'lost-reply-card' })
- const nextMessage = queuedDraft({ messageId: 'next-card', position: 2 })
await mount(message)
- act(() => listener?.(batchEvent([message, nextMessage])))
let answer: ((response: RpcResponse) => void) | undefined
sendRequest.mockImplementation((method, params) =>
method === 'agentSession.queuedMessageUpdate'
@@ -303,13 +397,14 @@ describe('mobile in-place queued Edit', () => {
})
: Promise.resolve(readOrHoldReply(method, params))
)
- act(() => hook!.queued.editor!.change('submitted edit'))
+ act(() => state.hook!.queued.editor!.change('submitted edit'))
let save: Promise | undefined
act(() => {
- save = hook!.queued.editor!.save()
+ save = state.hook!.queued.editor!.save()
})
- act(() => listener?.(batchEvent([nextMessage])))
- expect(hook!.queued.editor).toMatchObject({ messageId: message.messageId, saving: true })
+ act(() => state.listener?.(batchEvent([])))
+ expect(state.hook!.queued.editor?.saving).toBe(true)
+ expect(append).not.toHaveBeenCalled()
await act(async () => {
answer?.(
ok({
@@ -319,15 +414,12 @@ describe('mobile in-place queued Edit', () => {
)
expect(await save).toBe(false)
})
- expect(hook!.queued.editor).toBeUndefined()
+ expect(state.hook!.queued.editor).toBeUndefined()
expect(append).toHaveBeenCalledExactlyOnceWith('submitted edit')
- expect(error).toHaveBeenCalledExactlyOnceWith(
- 'This message was already sent or removed. Your edit is in the chat box.'
- )
- expect(resolved).not.toHaveBeenCalled()
+ expect(notice).toHaveBeenCalledOnce()
})
- it('keeps a refused Save in the editor and hands it to the composer once the card is gone', async () => {
+ it('keeps a refused Save in the editor and closes only when the published card is gone', async () => {
const message = queuedDraft({ messageId: 'refused-card' })
await mount(message)
sendRequest.mockImplementation(async (method, params) =>
@@ -338,34 +430,30 @@ describe('mobile in-place queued Edit', () => {
})
: readOrHoldReply(method, params)
)
- act(() => hook!.queued.editor!.change('keep this text'))
+ act(() => state.hook!.queued.editor!.change('keep this text'))
await act(async () => {
- expect(await hook!.queued.editor!.save()).toBe(false)
+ expect(await state.hook!.queued.editor!.save()).toBe(false)
})
- expect(hook!.queued.editor?.text).toBe('keep this text')
- expect(hook!.queued.editor?.saving).toBe(false)
+ expect(state.hook!.queued.editor?.text).toBe('keep this text')
+ expect(state.hook!.queued.editor?.saving).toBe(false)
expect(error).toHaveBeenCalledTimes(1)
expect(append).not.toHaveBeenCalled()
- act(() => listener?.(batchEvent([])))
- expect(hook!.queued.editor).toBeUndefined()
- expect(append).toHaveBeenCalledExactlyOnceWith('keep this text')
- expect(error).toHaveBeenLastCalledWith(
- 'This message was already sent or removed. Your edit is in the chat box.'
- )
+ act(() => state.listener?.(batchEvent([])))
+ expect(state.hook!.queued.editor).toBeUndefined()
})
it('keeps exact typing through disconnect and reacquires the hold on the replacement transport', async () => {
vi.useFakeTimers()
await mount(queuedDraft({ messageId: 'reconnect-card' }))
const text = 'unsaved text\nwith spacing and 🐈'
- act(() => hook!.queued.editor!.change(text))
+ act(() => state.hook!.queued.editor!.change(text))
await act(async () =>
- renderer?.update(createElement(Harness, { connected: false, transport: null }))
+ state.renderer?.update(createElement(Harness, { connected: false, transport: null }))
)
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
- expect(hook!.queued.editor?.text).toBe(text)
+ expect(state.hook!.queued.editor?.text).toBe(text)
const reconnectedRequest = vi.fn(async (method, params) =>
method === 'agentSession.queuedMessageEditHold'
? fieldsOf(params).action === 'renew'
@@ -374,14 +462,14 @@ describe('mobile in-place queued Edit', () => {
: ok({ models: [], current: {} })
)
await act(async () =>
- renderer?.update(
+ state.renderer?.update(
createElement(Harness, { transport: { ...client, sendRequest: reconnectedRequest } })
)
)
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
- expect(hook!.queued.editor?.text).toBe(text)
+ expect(state.hook!.queued.editor?.text).toBe(text)
expect(
reconnectedRequest.mock.calls
.filter(([method]) => method === 'agentSession.queuedMessageEditHold')
@@ -389,23 +477,90 @@ describe('mobile in-place queued Edit', () => {
).toEqual(['renew', 'acquire'])
expect(error).not.toHaveBeenCalled()
expect(append).not.toHaveBeenCalled()
- await act(async () => hook!.queued.editor!.cancel())
+ await act(async () => state.hook!.queued.editor!.cancel())
await act(async () =>
- renderer?.update(createElement(Harness, { connected: false, transport: null }))
+ state.renderer?.update(createElement(Harness, { connected: false, transport: null }))
)
const calls = reconnectedRequest.mock.calls.length
await act(async () => {
- expect(await hook!.queued.edit!('reconnect-card')).toBe(false)
+ expect(await state.hook!.queued.edit!('reconnect-card')).toBe(false)
})
expect(error).toHaveBeenCalledExactlyOnceWith('Reconnect to edit.')
- expect(hook!.queued.editor).toBeUndefined()
+ expect(state.hook!.queued.editor).toBeUndefined()
expect(reconnectedRequest).toHaveBeenCalledTimes(calls)
})
+ it('returns skills, new images, files and pending work into the original non-empty draft on involuntary close', async () => {
+ const message = queuedDraft({
+ messageId: 'full-draft',
+ body: {
+ kind: 'message',
+ role: 'user',
+ blocks: [
+ { type: 'text', text: '$review original' },
+ { type: 'image-ref', path: '/original.png' }
+ ],
+ skills: [{ name: 'review', path: '/remote/SKILL.md' }]
+ }
+ })
+ await mount(message)
+ act(() => state.hook!.queued.editor!.cancel())
+ await act(async () =>
+ state.renderer?.update(
+ createElement(Harness, {
+ composerScopeKey: 'original-bottom',
+ imagesSupport: true,
+ skillsSupport: true
+ })
+ )
+ )
+ await act(async () => {
+ await state.hook!.queued.edit!(message.messageId)
+ })
+ const scope = state.hook!.queued.editor!.scopeKey
+ const operation = mobileNativeChatDraftDestination(scope)
+ act(() => {
+ setMobileNativeChatDraftText('original-bottom', 'already typed')
+ state.hook!.queued.editor!.change('$review changed')
+ updateMobileNativeChatDraftInputs(scope, (current) => ({
+ ...current,
+ pending: 1,
+ images: [
+ ...current.images,
+ { id: 'new-image', path: '/new.png', previewUri: 'file:///new.png' }
+ ],
+ files: [{ id: 'file', name: 'report.txt', path: null, mime: 'text/plain', byteLength: 10 }]
+ }))
+ })
+ expect(state.hook!.queued.editor!.canSave).toBe(false)
+ act(() => state.listener?.(batchEvent([])))
+ expect(state.hook!.queued.editor).toBeUndefined()
+ expect(state.bottomText).toBe('already typed\n\n$review changed')
+ expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
+ skills: message.body.skills,
+ images: [{ id: 'new-image' }],
+ files: [{ id: 'file', path: null }],
+ pending: 1
+ })
+ act(() =>
+ updateMobileNativeChatDraftInputs(operation, (current) => ({
+ ...current,
+ pending: 0,
+ files: current.files.map((file) => ({ ...file, path: '/stored/report.txt' }))
+ }))
+ )
+ expect(readMobileNativeChatDraftInputs('original-bottom').files[0]?.path).toBe(
+ '/stored/report.txt'
+ )
+ expect(readMobileNativeChatDraftInputs(scope).images).toEqual([])
+ expect(notice).toHaveBeenCalledOnce()
+ expect(error).not.toHaveBeenCalled()
+ })
+
it('submits Save while hold acquisition is still pending', async () => {
const message = queuedDraft({ messageId: 'save-before-hold' })
await mount(message)
- act(() => hook!.queued.editor!.cancel())
+ act(() => state.hook!.queued.editor!.cancel())
let answerHold: ((response: RpcResponse) => void) | undefined
sendRequest.mockImplementation((method, params) =>
method === 'agentSession.queuedMessageEditHold' && fieldsOf(params).action === 'acquire'
@@ -415,17 +570,21 @@ describe('mobile in-place queued Edit', () => {
: method === 'agentSession.queuedMessageEditHold'
? Promise.resolve(readOrHoldReply(method, params))
: Promise.resolve(
- mutationOk({ status: 'updated', messageId: message.messageId, fingerprint: 'new' })
+ mutationOk({
+ status: 'updated',
+ messageId: message.messageId,
+ fingerprint: requestedFingerprint(message)
+ })
)
)
await act(async () => {
- await hook!.queued.edit!(message.messageId)
+ await state.hook!.queued.edit!(message.messageId)
})
- act(() => hook!.queued.editor!.change('saved without hold reply'))
+ act(() => state.hook!.queued.editor!.change('saved without hold reply'))
await act(async () => {
- expect(await hook!.queued.editor!.save()).toBe(true)
+ expect(await state.hook!.queued.editor!.save()).toBe(true)
})
- expect(hook!.queued.editor).toBeUndefined()
+ expect(state.hook!.queued.editor).toBeUndefined()
expect(answerHold).toBeDefined()
await act(async () => answerHold?.(editHoldReply({ action: 'acquire' })))
expect(append).not.toHaveBeenCalled()
diff --git a/mobile/src/session/use-mobile-structured-queued-edit.ts b/mobile/src/session/use-mobile-structured-queued-edit.ts
index 284608180d8..3366bf10f2f 100644
--- a/mobile/src/session/use-mobile-structured-queued-edit.ts
+++ b/mobile/src/session/use-mobile-structured-queued-edit.ts
@@ -1,293 +1,303 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
-import type { AgentJournalSubmission } from '../../../src/shared/agent-session-journal-types'
-import type {
- AgentSessionQueuedMessage,
- AgentSessionQueuedMessageUpdateResult
-} from '../../../src/shared/agent-session-wire'
+import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease'
+import { createMobileQueuedEdit } from './mobile-queued-message-edit-open'
+import {
+ useCallback,
+ useEffect,
+ useEffectEvent,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState
+} from 'react'
+import type { AgentSessionQueuedMessageUpdateResult } from '../../../src/shared/agent-session-wire'
import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
+import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
import {
- QUEUED_EDIT_NOTICE_COPY,
- queuedCardOnScreen,
- queuedEditChangedNotice,
- queuedEditDirty,
- queuedEditHandOffTyping,
- queuedEditKeptImages,
- queuedEditStanding,
- queuedMessageEditableText,
- queuedMessageWithEdit,
- type QueuedMessageEditDraft
-} from '../../../src/shared/queued-message-edit'
-import type { RpcClient } from '../transport/rpc-client'
+ mobileQueuedEditValueKey,
+ snapshotMobileQueuedEditInputs
+} from './mobile-queued-message-edit-value'
+import { settleMobileQueuedEdit } from './mobile-queued-message-edit-outcome'
+import { queuedEditPublicationKey } from '../../../src/shared/queued-message-edit-publication'
+import { startMobileQueuedEditLease } from './mobile-queued-message-edit-lease'
import {
- startMobileQueuedEditLease,
- type MobileQueuedEditLease
-} from './mobile-queued-message-edit-lease'
-import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation'
-import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards'
+ useMobileNativeChatDraftInputs,
+ readMobileNativeChatDraftInputs,
+ mobileNativeChatDraftDestination
+} from './native-chat/composer/mobile-native-chat-draft-inputs'
+import {
+ closeMobileQueuedEditDraft,
+ mobileQueuedEditSaving,
+ insertMobileQueuedEditDictation,
+ serializeMobileQueuedEdit,
+ mobileQueuedEditSaveHeld,
+ removeMobileQueuedEditImage,
+ type MobileQueuedEditDraft as Edit,
+ type MobileStructuredQueuedEditArgs,
+ type MobileQueuedMessageInlineEditor
+} from './mobile-queued-message-edit-draft'
+export type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft'
-export type MobileQueuedMessageInlineEditor = {
- messageId: string
- text: string
- saving: boolean
- canSave: boolean
- change: (text: string) => void
- save: () => Promise
- cancel: () => void
-}
-
-// The phone edits text only, so the card's images are all kept.
-type Edit = QueuedMessageEditDraft & {
- scope: string
- messageId: string
- body: AgentSessionQueuedMessage['body']
- fingerprint: string
- saving: boolean
- lease: MobileQueuedEditLease
-}
-
-export function useMobileStructuredQueuedEdit(args: {
- sessionKey: string
- sessionId: string | null
- client: RpcClient | null
- chatActive: boolean
- enabled: boolean
- messages: readonly AgentSessionQueuedMessage[] | null
- cards: readonly MobileQueuedMessageCard[]
- submissions: readonly AgentJournalSubmission[]
- mutate: MobileStructuredAgentMutate
- appendComposerText: ((text: string) => boolean) | undefined
- onSendError: (text: string) => void
- onActionResolved?: () => void
-}) {
- const { sessionKey, sessionId, client, enabled, mutate, onSendError, onActionResolved } = args
- const { messages, cards, submissions, appendComposerText } = args
- const clientRef = useRef({ sessionKey, client })
- const latest = useRef({ messages, cards, submissions, appendComposerText })
- useLayoutEffect(() => {
- clientRef.current = { sessionKey, client }
- latest.current = { messages, cards, submissions, appendComposerText }
- }, [appendComposerText, cards, client, messages, sessionKey, submissions])
+export function useMobileStructuredQueuedEdit(args: MobileStructuredQueuedEditArgs) {
+ const { sessionKey, sessionId, client, mutate, onSendError, onActionResolved } = args
const active = useRef(null)
- // A changed reply reopens the editor once the card publishes its newer text.
- const reopen = useRef<{ scope: string; messageId: string; stale: string } | null>(null)
const [shown, setShown] = useState(null)
+ const latest = useRef(args)
+ useLayoutEffect(() => {
+ latest.current = args
+ const edit = active.current
+ if (edit?.scope === args.sessionKey) {
+ edit.published = {
+ messages: args.messages,
+ submissions: args.submissions ?? [],
+ cards: args.cards
+ }
+ }
+ })
+ useMobileNativeChatDraftInputs(shown?.scopeKey ?? null)
const render = useCallback((edit: Edit | null) => {
active.current = edit
setShown(edit ? { ...edit } : null)
}, [])
- const close = useCallback(() => {
- const edit = active.current
- render(null)
- edit?.lease.end()
- }, [render])
- /** Unsaved typing goes to the chat box; false when there was none to keep. */
- const handOff = useCallback((edit: Edit): boolean => {
- const typing = queuedEditHandOffTyping(edit.body, edit)
- return typing !== '' && latest.current.appendComposerText?.(typing) === true
- }, [])
- const gone = useCallback(
- (edit: Edit) => {
- if (active.current !== edit) {
- return
- }
- if (queuedEditDirty(edit.body, edit) && handOff(edit)) {
- onSendError(QUEUED_EDIT_NOTICE_COPY.editGone)
- }
- close()
- },
- [close, handOff, onSendError]
- )
-
- // On chat changes or unmount, hand unsaved typing back to the chat it came from: a layout
- // cleanup runs before the composer's append is repointed at the next chat.
- useLayoutEffect(() => {
- return () => {
- const edit = active.current
- active.current = null
- reopen.current = null
- setShown(null)
- if (edit && queuedEditDirty(edit.body, edit)) {
- handOff(edit)
- }
- edit?.lease.end()
- }
- }, [handOff, sessionKey, args.chatActive])
-
- const begin = useCallback(
- async (messageId: string): Promise => {
- reopen.current = null
- if (active.current || !enabled || !client || !sessionId) {
- return false
- }
- const message = messages?.find((entry) => entry.messageId === messageId)
- const text = message ? queuedMessageEditableText(message.body) : null
- if (!message || text === null) {
- return false
- }
- const fingerprint = agentSessionSendBodyFingerprint(sessionId, message.body)
- const edit: Edit = {
- scope: sessionKey,
- messageId,
- body: message.body,
- text,
- kept: queuedEditKeptImages(message.body),
- added: [],
- fingerprint,
- saving: false,
- lease: startMobileQueuedEditLease({
- getClient: () =>
- clientRef.current.sessionKey === sessionKey ? clientRef.current.client : client,
- sessionId,
- messageId,
- expectedBodyFingerprint: fingerprint
- })
- }
- render(edit)
- void edit.lease.acquired.then(
- (answer) => {
- if (!isOpen(active, edit) || edit.saving) {
- return
- }
- // Sent, removed or edited elsewhere before the edit began: the card shows what happened.
- if (answer.status === 'gone' || answer.status === 'changed') {
- gone(edit)
- } else if (answer.status === 'not-editable') {
- handOff(edit)
- onSendError(QUEUED_EDIT_NOTICE_COPY.editFailed)
- close()
- }
- },
- () => undefined
- )
- return true
- },
- [client, close, enabled, gone, handOff, messages, onSendError, render, sessionId, sessionKey]
- )
- const change = useCallback(
- (text: string) => {
- const edit = active.current
- if (edit && !edit.saving) {
- edit.text = text
- render(edit)
+ const close = useCallback(
+ (edit: Edit, handBack = false) => {
+ closeMobileQueuedEditDraft(edit, handBack, latest.current.onQueuedEditNotice)
+ if (active.current === edit) {
+ render(null)
}
},
[render]
)
+
+ const receiveLoss = useCallback(
+ (edit: Edit, loss: QueuedEditLeaseLoss, observe: (edit: Edit) => unknown) => {
+ if (edit.closed || edit.lease !== loss.lease) {
+ return
+ }
+ edit.leaseLoss = loss
+ observe(edit)
+ },
+ []
+ )
+ const acquire = useCallback(
+ (edit: Edit, observe: (edit: Edit) => unknown) => {
+ edit.lease.end()
+ edit.leaseLoss = undefined
+ edit.lease = startMobileQueuedEditLease({
+ getClient: () =>
+ latest.current.sessionKey === edit.scope ? latest.current.client : edit.client,
+ sessionId: edit.sessionId,
+ messageId: edit.messageId,
+ expectedBodyFingerprint: edit.fingerprint,
+ onLost: (loss) => receiveLoss(edit, loss, observe)
+ })
+ },
+ [receiveLoss]
+ )
+
+ const settle = useCallback(
+ function settleResult(
+ edit: Edit,
+ attempt = edit.attempt,
+ result?: Awaited>>
+ ) {
+ if (edit.closed || edit.attempt !== attempt || (!result && mobileQueuedEditSaving(edit))) {
+ return false
+ }
+ const outcome = settleMobileQueuedEdit(edit, attempt, result)
+ if (outcome === 'close') {
+ close(edit, true)
+ if (!edit.pendingClose) {
+ onActionResolved?.()
+ }
+ return true
+ }
+ if (outcome === 'rebase') {
+ acquire(edit, settleResult)
+ } else if (outcome === 'gone' || outcome === 'changed' || edit.pendingClose) {
+ // A restored seed is still intent if an earlier write remains uncertain or a rival changed it.
+ edit.uncertain ||= outcome === 'changed'
+ close(edit, true)
+ return false
+ } else if (outcome === 'refused' && result?.status === 'accepted') {
+ onSendError("This message can't be edited.")
+ }
+ if (active.current === edit) {
+ render(edit)
+ }
+ return false
+ },
+ [acquire, close, onActionResolved, onSendError, render]
+ )
+
+ useEffect(
+ () => () => {
+ const edit = active.current
+ if (!edit) {
+ return
+ }
+ // A submitted snapshot owns its reply even across navigation; no publication duplicates it.
+ if (mobileQueuedEditSaving(edit)) {
+ edit.pendingClose = true
+ active.current = null
+ return
+ }
+ close(edit, true)
+ },
+ [sessionKey, args.chatActive, close]
+ )
+
+ const begin = useCallback(
+ async (messageId: string): Promise => {
+ if (active.current) {
+ return false
+ }
+ const edit = createMobileQueuedEdit(
+ { ...latest.current, sessionKey, sessionId, client },
+ messageId,
+ () => (latest.current.sessionKey === sessionKey ? latest.current.client : client),
+ (edit, loss) => receiveLoss(edit, loss, settle)
+ )
+ if (!edit) {
+ return false
+ }
+ render(edit)
+ return true
+ },
+ [client, receiveLoss, render, sessionId, sessionKey, settle]
+ )
+
const save = useCallback(async (): Promise => {
const edit = active.current
- if (!edit || edit.saving || !sessionId) {
+ if (!edit || mobileQueuedEditSaving(edit) || !sessionId) {
return false
}
- const edited = queuedMessageWithEdit(edit.body, { text: edit.text })
- if (!edited.ok) {
+ if (mobileQueuedEditSaveHeld(edit, args.imagesCapable)) {
return false
}
- if (!queuedEditDirty(edit.body, edit)) {
- close()
+ const fields = serializeMobileQueuedEdit(edit, args.imagesCapable, args.skillsCapable)
+ const desired = queuedMessageWithEdit(edit.body, fields)
+ if (!desired.ok) {
+ return false
+ }
+ if (
+ !edit.uncertain &&
+ !edit.attempt &&
+ mobileQueuedEditValueKey(edit.text, readMobileNativeChatDraftInputs(edit.scopeKey)) ===
+ edit.baseKey
+ ) {
+ close(edit, true)
+ onActionResolved?.()
return true
}
- // When Save’s reply is lost or refused, published card state proves whether its body landed.
- const desired = agentSessionSendBodyFingerprint(sessionId, edited.body)
- const standing = () => queuedEditStanding(latest.current, sessionId, edit.messageId, desired)
- edit.saving = true
+ const attempt = {
+ phase: 'pending' as const,
+ expected: edit.fingerprint,
+ fingerprint: agentSessionSendBodyFingerprint(sessionId, desired.body),
+ body: desired.body,
+ text: edit.text,
+ inputs: snapshotMobileQueuedEditInputs(readMobileNativeChatDraftInputs(edit.scopeKey)),
+ key: mobileQueuedEditValueKey(edit.text, readMobileNativeChatDraftInputs(edit.scopeKey))
+ }
+ edit.attempt = attempt
render(edit)
const result = await mutate(
'agentSession.queuedMessageUpdate',
'agentSession.queuedMessageUpdate',
- { messageId: edit.messageId, expectedBodyFingerprint: edit.fingerprint, text: edit.text },
- () => isOpen(active, edit) && standing() === 'differs'
+ { messageId: edit.messageId, expectedBodyFingerprint: attempt.expected, ...fields },
+ () => !edit.closed && !edit.pendingClose && edit.leaseLoss?.lease !== edit.lease
)
- // A reply during a chat switch belongs to the outgoing chat.
- if (!isOpen(active, edit) || clientRef.current.sessionKey !== edit.scope) {
- return false
- }
- edit.saving = false
- if (result.status === 'accepted') {
- const { status } = result.value
- if (status === 'updated' || status === 'unchanged') {
- close()
- onActionResolved?.()
- return true
- }
- if (status === 'gone') {
- gone(edit)
- return false
- }
- if (status === 'changed') {
- // Preserve typing after a competing edit, then reopen on the newer text.
- onSendError(QUEUED_EDIT_NOTICE_COPY[queuedEditChangedNotice(handOff(edit), false)])
- reopen.current = { scope: edit.scope, messageId: edit.messageId, stale: edit.fingerprint }
- close()
- return false
- }
- onSendError(QUEUED_EDIT_NOTICE_COPY.editFailed)
- render(edit)
- return false
- }
- const settled = standing()
- if (settled === 'sent' || settled === 'holds') {
- close()
- onActionResolved?.()
- return true
- }
- if (settled === 'gone') {
- gone(edit)
- return false
- }
- render(edit)
- return false
- }, [close, gone, handOff, mutate, onActionResolved, onSendError, render, sessionId])
+ return settle(edit, attempt, result)
+ }, [
+ args.imagesCapable,
+ args.skillsCapable,
+ close,
+ mutate,
+ onActionResolved,
+ render,
+ sessionId,
+ settle
+ ])
- // Let in-flight Save decide delivery races; otherwise reconcile departures, but never infer them from an unloaded list.
- useEffect(() => {
+ const publication = useMemo(
+ () =>
+ queuedEditPublicationKey(
+ { messages: args.messages, cards: args.cards, submissions: args.submissions },
+ sessionId ?? '',
+ shown?.messageId
+ ),
+ [args.messages, args.cards, args.submissions, sessionId, shown?.messageId]
+ )
+ const reconcile = useEffectEvent(() => {
const edit = active.current
- if (edit && edit.scope === sessionKey && !edit.saving && messages !== null && sessionId) {
- const typed = queuedMessageWithEdit(edit.body, { text: edit.text })
- const desired = typed.ok ? agentSessionSendBodyFingerprint(sessionId, typed.body) : null
- const standing = queuedEditStanding(
- { messages, cards, submissions },
- sessionId,
- edit.messageId,
- desired
- )
- // `holds`: the card already holds what is typed, as after a Save whose answer was lost.
- if (standing === 'sent' || (standing === 'holds' && desired !== edit.fingerprint)) {
- close()
- } else if (standing === 'gone') {
- gone(edit)
- }
- }
- const pending = reopen.current
- if (!pending || active.current || messages === null || !sessionId) {
+ if (
+ !edit ||
+ mobileQueuedEditSaving(edit) ||
+ edit.scope !== sessionKey ||
+ args.messages === null
+ ) {
return
}
- const listed = messages.find((entry) => entry.messageId === pending.messageId)
- if (pending.scope !== sessionKey || !listed || !queuedCardOnScreen(cards, pending.messageId)) {
- reopen.current = null
- } else if (agentSessionSendBodyFingerprint(sessionId, listed.body) !== pending.stale) {
- void begin(pending.messageId)
+ const onScreen = args.cards.some(({ messageId }) => messageId === edit.messageId)
+ if (!onScreen && !edit.attempt) {
+ close(edit, true)
+ } else {
+ settle(edit)
}
- }, [begin, cards, close, gone, messages, sessionId, sessionKey, shown, submissions])
+ })
+ useEffect(() => {
+ reconcile()
+ }, [publication, sessionKey])
+ const editing = active.current
+ const inputDestination = editing ? mobileNativeChatDraftDestination(editing.scopeKey) : null
const editor: MobileQueuedMessageInlineEditor | undefined =
shown?.scope === sessionKey
? {
messageId: shown.messageId,
+ scopeKey: shown.scopeKey,
+ client: shown.client,
+ sessionId: shown.sessionId,
+ imagesCapable: args.imagesCapable === true,
text: shown.text,
- saving: shown.saving,
- canSave: queuedMessageWithEdit(shown.body, { text: shown.text }).ok,
- change,
+ saving: mobileQueuedEditSaving(shown),
+ canSave:
+ !mobileQueuedEditSaveHeld(shown, args.imagesCapable) &&
+ queuedMessageWithEdit(
+ shown.body,
+ serializeMobileQueuedEdit(shown, args.imagesCapable, args.skillsCapable)
+ ).ok,
+ insertDictation: (text) => {
+ const inserted =
+ editing &&
+ inputDestination &&
+ insertMobileQueuedEditDictation(editing, inputDestination, text)
+ if (inserted && active.current === editing) {
+ render(editing)
+ }
+ return Boolean(inserted)
+ },
+ change: (text) => {
+ const edit = active.current
+ if (edit && !mobileQueuedEditSaving(edit)) {
+ edit.text = text
+ render(edit)
+ }
+ },
+ removeImage: (id) => {
+ const edit = active.current
+ if (!edit || mobileQueuedEditSaving(edit) || !args.imagesCapable) {
+ return
+ }
+ removeMobileQueuedEditImage(edit, id)
+ render(edit)
+ },
save,
cancel: () => {
- if (!active.current?.saving) {
- close()
+ if (active.current) {
+ close(active.current)
}
}
}
: undefined
return { begin, editor }
}
-
-function isOpen(active: { current: Edit | null }, edit: Edit): boolean {
- return active.current === edit
-}
diff --git a/mobile/src/session/use-mobile-structured-queued-message-controls.ts b/mobile/src/session/use-mobile-structured-queued-message-controls.ts
index f5d46e5e8ad..2d6694801d3 100644
--- a/mobile/src/session/use-mobile-structured-queued-message-controls.ts
+++ b/mobile/src/session/use-mobile-structured-queued-message-controls.ts
@@ -53,6 +53,9 @@ export function useMobileStructuredQueuedMessageControls(args: {
chatActive: boolean
enabled: boolean
editCapable: boolean | null
+ imagesCapable?: boolean
+ skillsCapable?: boolean
+ composerScopeKey?: string | null
reorderCapable?: boolean
agentName?: string
journalItems?: readonly AgentJournalRenderItem[]
@@ -63,6 +66,7 @@ export function useMobileStructuredQueuedMessageControls(args: {
mutate: MobileStructuredAgentMutate
// Without a live composer or a successful copy, Edit must refuse.
appendComposerText: ((text: string) => boolean) | undefined
+ onQueuedEditNotice?: (message: string) => void
onSendError: (message: string) => void
onActionResolved?: () => void
}): MobileStructuredQueuedMessageControls {
diff --git a/mobile/src/transport/mobile-runtime-client-capabilities.ts b/mobile/src/transport/mobile-runtime-client-capabilities.ts
index a8e37d9e33f..92e0953a9fc 100644
--- a/mobile/src/transport/mobile-runtime-client-capabilities.ts
+++ b/mobile/src/transport/mobile-runtime-client-capabilities.ts
@@ -1,3 +1,4 @@
+import { AGENT_SESSION_QUEUED_IMAGE_CARDS_CLIENT_CAPABILITY } from '../../../src/shared/agent-session-runtime-capabilities'
import { AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY } from '../../../src/shared/structured-agent-session-surface-capabilities'
import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../../src/shared/agent-session-current-requests-capability'
import {
@@ -44,7 +45,8 @@ export const MOBILE_RUNTIME_CLIENT_CAPABILITIES = remoteRuntimeClientCapabilitie
AGENT_LAUNCH_TAB_CLOSED_CLIENT_CAPABILITY,
// Native chat offers no Stop for a turn the host restored but could not confirm.
AGENT_STATUS_RESTORED_UNCONFIRMED_RUNTIME_CAPABILITY,
- AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY
+ AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY,
+ AGENT_SESSION_QUEUED_IMAGE_CARDS_CLIENT_CAPABILITY
])
export const MOBILE_RUNTIME_CLIENT_CAPABILITY_UPDATE_METHOD =
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4ee04f0c596..499835b0291 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -187,7 +187,6 @@ patchedDependencies:
node-pty@1.1.0: 3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43
oxlint-plugin-anti-slop@0.1.2: c10c871702365a0c2c59e9f1c5fb92df97cae5755d534c0a3d83c6368f6feafe
sprintf-js@1.1.3: 05316a8b01f155fe19a1e0cb4042c81d43d798a76755c407684e1199a18b1e08
- vitest@5.0.5: a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db
ws@8.22.0: 9393e04dd9a90b01eb7aa35fcd5b1431b5038ce999fbbd82651136193ba51f14
importers:
@@ -326,7 +325,7 @@ importers:
version: 3.14.13(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(@types/react@19.2.18)(react@19.2.8))(react@19.2.8)
'@testing-library/jest-dom':
specifier: ^6.9.1
- version: 6.9.1(vitest@5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))
+ version: 6.9.1(vitest@5.0.5(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/dom@10.4.1)(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(@types/react@19.2.18)(react@19.2.8))(react@19.2.8)
@@ -626,7 +625,7 @@ importers:
version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
vitest:
specifier: 5.0.5
- version: 5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
+ version: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
vscode-oniguruma:
specifier: ^2.0.1
version: 2.0.1
@@ -687,7 +686,7 @@ importers:
version: 7.0.2
vitest:
specifier: 5.0.5
- version: 5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@18.19.130)(happy-dom@21.0.4)(msw@2.14.3(@types/node@18.19.130)(typescript@7.0.2))(vite@8.3.5(@types/node@18.19.130)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
+ version: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@18.19.130)(happy-dom@21.0.4)(msw@2.14.3(@types/node@18.19.130)(typescript@7.0.2))(vite@8.3.5(@types/node@18.19.130)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
packages:
@@ -10453,7 +10452,7 @@ snapshots:
picocolors: 1.1.1
pretty-format: 27.5.1
- '@testing-library/jest-dom@6.9.1(vitest@5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))':
+ '@testing-library/jest-dom@6.9.1(vitest@5.0.5(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))':
dependencies:
'@adobe/css-tools': 4.5.0
'@types/aria-query': 5.0.4
@@ -10463,7 +10462,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
- vitest: 5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
+ vitest: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
'@testing-library/react@16.3.3(@testing-library/dom@10.4.1)(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(@types/react@19.2.18)(react@19.2.8))(react@19.2.8)':
dependencies:
@@ -15184,7 +15183,7 @@ snapshots:
transitivePeerDependencies:
- '@types/picomatch'
- vitest@5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@18.19.130)(happy-dom@21.0.4)(msw@2.14.3(@types/node@18.19.130)(typescript@7.0.2))(vite@8.3.5(@types/node@18.19.130)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
+ vitest@5.0.5(@opentelemetry/api@1.9.1)(@types/node@18.19.130)(happy-dom@21.0.4)(msw@2.14.3(@types/node@18.19.130)(typescript@7.0.2))(vite@8.3.5(@types/node@18.19.130)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5(msw@2.14.3(@types/node@18.19.130)(typescript@7.0.2))(vite@8.3.5(@types/node@18.19.130)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
@@ -15209,7 +15208,7 @@ snapshots:
- '@types/picomatch'
- msw
- vitest@5.0.5(patch_hash=a1a4e3c1fe4348649acf21d13315b98c967d257c6e349a6047aee7befd8d97db)(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
+ vitest@5.0.5(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(happy-dom@21.0.4)(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5(msw@2.14.3(@types/node@24.19.2)(typescript@7.0.2))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 9e6c81ddabf..e28a38ebcc2 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -131,4 +131,3 @@ patchedDependencies:
monaco-editor@0.55.1: config/patches/monaco-editor@0.55.1.patch
sprintf-js@1.1.3: config/patches/sprintf-js@1.1.3.patch
'@tiptap/extension-list@3.31.3': config/patches/@tiptap__extension-list@3.31.3.patch
- vitest@5.0.5: config/patches/vitest@5.0.5.patch
diff --git a/skill-guides/orca-cli.md b/skill-guides/orca-cli.md
index 00ebf7da5be..aa5eb5b9b25 100644
--- a/skill-guides/orca-cli.md
+++ b/skill-guides/orca-cli.md
@@ -223,6 +223,8 @@ Terminal rules:
- A bulk close fails when the execution host cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another host.
- Use workspace Sleep, not close, when the terminals and agent sessions should resume later. `terminal stop` is legacy compatibility plumbing and should not be used in new agent workflows.
- `terminal list --json` omits `visualLayouts` to keep the common agent payload bounded. Add `--include-visual-layouts` only when tab and pane topology is required.
+- `terminal create --title` and `terminal rename` set the tab title, which `terminal list` reports under `visualLayouts`. `terminal set-pane-title` sets one pane's title, reported as `terminals[].paneTitle`. `terminals[].title` may be the tab title or the running program's own title, which agents repaint constantly, so never match on it to re-find a terminal.
+- `terminals[].agentIdentity`, when present, is only the agent type (e.g. `codex`), not a session identity, so two Codex panes share it. To find a specific agent's terminal, join `worktree ps --json` `agents[].paneKey` (`:`) to the `tabId` and `leafId` of a `terminal list` row to get its handle.
- A paired server has no window. `terminal switch --environment ` moves the desktop app on this machine to that server's terminal, and reports `navigated: false` when no desktop here shows that server.
- Use `terminal read` before `terminal send` unless the next input is obvious.
- `terminal read` returns accumulated output with escape sequences stripped, not the rendered screen, so anything that repaints (shells, progress bars, TUIs) reads as stacked fragments. Use `--screen` whenever the answer depends on what the terminal actually shows.
diff --git a/skill-guides/orchestration/references/recovery-and-cleanup.md b/skill-guides/orchestration/references/recovery-and-cleanup.md
index b10bcc21f8a..96036c42237 100644
--- a/skill-guides/orchestration/references/recovery-and-cleanup.md
+++ b/skill-guides/orchestration/references/recovery-and-cleanup.md
@@ -133,6 +133,17 @@ ORCA orchestration worker-abandon --dispatch --json
`worker-stop` closes only the exact proven supervised agent terminal. It never
deletes the worktree, setup terminal, configured tabs, or unrelated processes.
+Its receipt's `processAction` reports what it did:
+
+- `closed_agent_terminal`: Orca issued that close; do not follow it with
+ `terminal close`.
+- `none`: this call issued no close (for example, already settled or
+ unsupervised).
+- `unknown`: Orca could not attempt or confirm a close.
+
+`stop_unknown` exits 1 and can still report `closed_agent_terminal` when the
+agent's exit was not proven; inspect `worker-show` before acting further.
+
`worker-abandon` fences orchestration while accepting that resources may remain
live; it performs no remote, process, or filesystem action. When it settles a
worker, it retains an owned terminal by the same rule as `worker-retain`, so Orca
diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts
index 7442a8abdbc..227df048b3b 100644
--- a/src/cli/bundled-skill-guides.ts
+++ b/src/cli/bundled-skill-guides.ts
@@ -606,6 +606,8 @@ const ORCA_CLI_MARKDOWN = [
"- A bulk close fails when the execution host cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another host.",
"- Use workspace Sleep, not close, when the terminals and agent sessions should resume later. `terminal stop` is legacy compatibility plumbing and should not be used in new agent workflows.",
"- `terminal list --json` omits `visualLayouts` to keep the common agent payload bounded. Add `--include-visual-layouts` only when tab and pane topology is required.",
+ "- `terminal create --title` and `terminal rename` set the tab title, which `terminal list` reports under `visualLayouts`. `terminal set-pane-title` sets one pane's title, reported as `terminals[].paneTitle`. `terminals[].title` may be the tab title or the running program's own title, which agents repaint constantly, so never match on it to re-find a terminal.",
+ "- `terminals[].agentIdentity`, when present, is only the agent type (e.g. `codex`), not a session identity, so two Codex panes share it. To find a specific agent's terminal, join `worktree ps --json` `agents[].paneKey` (`:`) to the `tabId` and `leafId` of a `terminal list` row to get its handle.",
"- A paired server has no window. `terminal switch --environment ` moves the desktop app on this machine to that server's terminal, and reports `navigated: false` when no desktop here shows that server.",
"- Use `terminal read` before `terminal send` unless the next input is obvious.",
"- `terminal read` returns accumulated output with escape sequences stripped, not the rendered screen, so anything that repaints (shells, progress bars, TUIs) reads as stacked fragments. Use `--screen` whenever the answer depends on what the terminal actually shows.",
@@ -3060,6 +3062,17 @@ const ORCHESTRATION_RECOVERY_AND_CLEANUP_REFERENCE_MARKDOWN = [
"",
"`worker-stop` closes only the exact proven supervised agent terminal. It never",
"deletes the worktree, setup terminal, configured tabs, or unrelated processes.",
+ "Its receipt's `processAction` reports what it did:",
+ "",
+ "- `closed_agent_terminal`: Orca issued that close; do not follow it with",
+ " `terminal close`.",
+ "- `none`: this call issued no close (for example, already settled or",
+ " unsupervised).",
+ "- `unknown`: Orca could not attempt or confirm a close.",
+ "",
+ "`stop_unknown` exits 1 and can still report `closed_agent_terminal` when the",
+ "agent's exit was not proven; inspect `worker-show` before acting further.",
+ "",
"`worker-abandon` fences orchestration while accepting that resources may remain",
"live; it performs no remote, process, or filesystem action. When it settles a",
"worker, it retains an owned terminal by the same rule as `worker-retain`, so Orca",
diff --git a/src/cli/command-scoped-flag-help.ts b/src/cli/command-scoped-flag-help.ts
index c6e243c9395..b1cf1aa2424 100644
--- a/src/cli/command-scoped-flag-help.ts
+++ b/src/cli/command-scoped-flag-help.ts
@@ -18,6 +18,7 @@ const COMMAND_SCOPED_FLAG_HELP: Record> = {
limit: '--limit Maximum matching workspaces (default 50)'
},
'worktree create': {
+ branch: '--branch Git branch name to use instead of the prefixed default',
reference:
'--reference Attach an issue/review URL or Jira key; repeat for several',
'reference-site': '--reference-site Jira site for bare keys; see orca jira connection',
diff --git a/src/cli/handlers/orchestration/worker-output.test.ts b/src/cli/handlers/orchestration/worker-output.test.ts
index 7d2d04ce5a6..b25faae3a57 100644
--- a/src/cli/handlers/orchestration/worker-output.test.ts
+++ b/src/cli/handlers/orchestration/worker-output.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { OrchestrationFleetWorker } from '../../../shared/orchestration-fleet-projection'
-import { subagentGroupFallbackText } from '../../../shared/native-chat-subagent-summary'
+import { subagentGroupFallbackText } from '../../../shared/native-chat/transcript/native-chat-subagent-summary'
import type {
NativeChatBlock,
NativeChatMessage,
diff --git a/src/cli/handlers/search.test.ts b/src/cli/handlers/search.test.ts
index 88fd3c85848..b59b175afcf 100644
--- a/src/cli/handlers/search.test.ts
+++ b/src/cli/handlers/search.test.ts
@@ -155,7 +155,7 @@ describe('orca search over the runtime RPC', () => {
filters: {
agents: ['claude', 'codex'],
scopePaths: ['/a', '/b'],
- since: '2026-08-01T00:00:00Z',
+ since: '2026-08-01T00:00:00.000Z',
sort: 'newest'
}
}
diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts
index 6a480f76a5a..174e843fc7b 100644
--- a/src/cli/handlers/worktree.ts
+++ b/src/cli/handlers/worktree.ts
@@ -131,6 +131,7 @@ export const WORKTREE_HANDLERS: Record = {
const referenceInputs = getCreateReferenceInputs(flags)
assertWorktreeParentFlagsCompatible(flags)
assertWorkspaceTargetFlagsCompatible(flags)
+ const branchNameOverride = getPresentStringFlag(flags, 'branch')
const reviewLinks = getReviewTargetLinkFlags(flags)
const callerTerminalHandle =
typeof process.env.ORCA_TERMINAL_HANDLE === 'string' &&
@@ -182,6 +183,7 @@ export const WORKTREE_HANDLERS: Record = {
displayName: name,
displayNameKind: 'user',
baseBranch: getOptionalStringFlag(flags, 'base-branch'),
+ branchNameOverride,
...reviewLinks,
...linearIssueLink,
...(linkedItems ? { linkedItems } : {}),
diff --git a/src/cli/index-worktree-create-agent.test.ts b/src/cli/index-worktree-create-agent.test.ts
index 36258a8091d..34d10a74351 100644
--- a/src/cli/index-worktree-create-agent.test.ts
+++ b/src/cli/index-worktree-create-agent.test.ts
@@ -109,6 +109,8 @@ describe('orca cli worktree awareness', () => {
'id:repo-1',
'--name',
'agent-task',
+ '--branch',
+ 'DAT-111-agent-task',
'--agent',
'codex',
'--model',
@@ -133,6 +135,7 @@ describe('orca cli worktree awareness', () => {
displayName: 'agent-task',
displayNameKind: 'user',
baseBranch: undefined,
+ branchNameOverride: 'DAT-111-agent-task',
linkedIssue: undefined,
comment: undefined,
runHooks: false,
diff --git a/src/cli/index-worktree-create-target.test.ts b/src/cli/index-worktree-create-target.test.ts
index 638a39f2a63..67e641949a4 100644
--- a/src/cli/index-worktree-create-target.test.ts
+++ b/src/cli/index-worktree-create-target.test.ts
@@ -75,6 +75,42 @@ describe('orca cli worktree awareness', () => {
spawnMock
})
+ it('passes --branch as the branch name, separate from the workspace name and base ref', async () => {
+ queueFixtures(
+ callMock,
+ okFixture('req_create', {
+ worktree: buildWorktree('/tmp/repo/task', 'DAT-111-fix', 'abc', 'repo-1')
+ })
+ )
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ await main(
+ [
+ 'worktree',
+ 'create',
+ '--repo',
+ 'id:repo-1',
+ '--name',
+ 'Fix login',
+ '--branch',
+ 'DAT-111-fix',
+ '--base-branch',
+ 'origin/main',
+ '--no-parent',
+ '--json'
+ ],
+ '/tmp/repo'
+ )
+ expect(callMock).toHaveBeenCalledWith(
+ 'worktree.create',
+ expect.objectContaining({
+ name: 'Fix login',
+ displayName: 'Fix login',
+ branchNameOverride: 'DAT-111-fix',
+ baseBranch: 'origin/main'
+ })
+ )
+ })
+
it('passes explicit activation through worktree.create', async () => {
queueFixtures(
callMock,
diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts
index bc41f53cd4e..2ee4c9faa69 100644
--- a/src/cli/specs/core.ts
+++ b/src/cli/specs/core.ts
@@ -68,7 +68,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
repeatableFlags: ['reference'],
summary: 'Create a new Orca-managed worktree',
usage:
- 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch [] [--reference ]...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]',
+ 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch [] [--branch ]] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'repo',
@@ -83,6 +83,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
'surface',
'retry-launch',
'base-branch',
+ 'branch',
'reference',
'reference-site',
'issue',
@@ -107,6 +108,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
'--host takes local, ssh:, runtime:, or the bare host name `orca host list` prints for any of them.',
'For related work, use the inferred parent or pass --parent-worktree active, folder:, or worktree: to make the relationship explicit. Worktree ids are the full :: values returned by `orca worktree list --json`.',
'Use --no-parent when the new worktree should be independent of the current context.',
+ 'Pass --branch to name the Git branch without the configured prefix (a taken name gets a numeric suffix); --base-branch selects the starting ref instead.',
'--no-parent only affects Orca lineage; omit --base-branch to use the repo default base, or pass the default base ref explicitly for independent top-level work.',
'By default this creates the worktree and its first terminal without switching the active Orca view.',
'Pass --agent to start an agent with the worktree, as a chat or a terminal per your Chat UI setting, exactly as a new agent tab does; --prompt sends initial work to it. --model and --effort pick its model and reasoning effort, and --surface chat|terminal picks chat or terminal for this launch instead of your setting.',
diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts
index 16d2a3251b3..a19198a02ef 100644
--- a/src/cli/specs/orchestration-worker-specs.ts
+++ b/src/cli/specs/orchestration-worker-specs.ts
@@ -80,6 +80,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [
allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'],
notes: [
'A Dispatch created by orchestration dispatch is fenced without closing its unsupervised terminal process.',
+ 'processAction closed_agent_terminal means Orca issued the close (do not also run terminal close); stop_unknown exits 1 and may still report it when the agent exit was not proven.',
'Never deletes the worktree, setup terminal, configured tabs, or unrelated processes.'
]
},
diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts
index 921b27e43b1..8ed88085e54 100644
--- a/src/cli/specs/orchestration.ts
+++ b/src/cli/specs/orchestration.ts
@@ -117,7 +117,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
'On Windows PowerShell, quote comma-separated type filters, e.g. --types "worker_done,escalation".',
'--types is the wake condition for --wait; a returned Delivery is always the whole FIFO batch, so it is never filtered by type. Without --wait it has no effect on consuming checks. Only --peek and --all filter their rows.',
'--format renders the returned rows as local text only; it never writes to another terminal.',
- 'A bound Run replays the same Delivery until --ack or all its messages are marked read, even with --types; process every message before acknowledging. Several --wait calls may wait on one Run inbox; waiting reserves nothing, listeners woken together get the same Delivery, and a repeated --ack is a no-op.'
+ 'A bound Run replays the same Delivery until --ack or all its messages are marked read, even with --types; process every message before acknowledging. Several --wait calls may wait on one Run inbox; waiting reserves nothing, listeners woken together get the same Delivery, and a repeated --ack is a no-op. --peek and --all return no deliveryId, so they do not drain a mailbox on their own; --all and a Run --peek show at most 100 rows. To drain, repeat plain check with --ack until deliveryId is null.'
]
},
{
diff --git a/src/main/__fixtures__/shell-wrapper-snapshots/daemon-bash-rcfile.txt b/src/main/__fixtures__/shell-wrapper-snapshots/daemon-bash-rcfile.txt
index 39db3318927..3b61d36b65d 100644
--- a/src/main/__fixtures__/shell-wrapper-snapshots/daemon-bash-rcfile.txt
+++ b/src/main/__fixtures__/shell-wrapper-snapshots/daemon-bash-rcfile.txt
@@ -119,6 +119,9 @@ if [[ -n "${__orca_codex_binary:-}" && -x "${__orca_codex_binary}" ]]; then
function codex {
# Why local: zsh's warn_create_global warns for each global a function creates.
local __orca_codex_arg __orca_codex_isolate="${ORCA_CODEX_ISOLATE:-1}" __orca_codex_identity="${ORCA_CODEX_ISOLATE:-1}"
+ if [[ "${ORCA_REMOTE_VIEWER_CLIPBOARD:-}" == 1 && -z "${SSH_CONNECTION+x}" && -z "${SSH_TTY+x}" ]]; then
+ local -x SSH_CONNECTION='127.0.0.1 0 127.0.0.1 0'
+ fi
if [[ -n "${ORCA_CODEX_LAUNCH_PREFLIGHT:-}" && -x "${ORCA_CODEX_LAUNCH_PREFLIGHT}" ]]; then
"${ORCA_CODEX_LAUNCH_PREFLIGHT}" agent hooks prepare-codex >/dev/null 2>&1 || :
fi
diff --git a/src/main/__fixtures__/shell-wrapper-snapshots/daemon-fish-init.txt b/src/main/__fixtures__/shell-wrapper-snapshots/daemon-fish-init.txt
index 404ffd4ccea..7c53db56ee8 100644
--- a/src/main/__fixtures__/shell-wrapper-snapshots/daemon-fish-init.txt
+++ b/src/main/__fixtures__/shell-wrapper-snapshots/daemon-fish-init.txt
@@ -21,7 +21,12 @@ if test "$__orca_codex_type" = file
if test "$ORCA_CODEX_ISOLATE" != 0; and not string match -qr -- '^(agents|queue|--remote|--no-daemon|--remote=.*)$' $argv; and command codex --help 2>/dev/null /dev/null 2>&1 || :
fi
diff --git a/src/main/__fixtures__/shell-wrapper-snapshots/local-bash-rcfile.txt b/src/main/__fixtures__/shell-wrapper-snapshots/local-bash-rcfile.txt
index 7bc19fd874d..0fee1d58a0b 100644
--- a/src/main/__fixtures__/shell-wrapper-snapshots/local-bash-rcfile.txt
+++ b/src/main/__fixtures__/shell-wrapper-snapshots/local-bash-rcfile.txt
@@ -127,6 +127,9 @@ if [[ -n "${__orca_codex_binary:-}" && -x "${__orca_codex_binary}" ]]; then
function codex {
# Why local: zsh's warn_create_global warns for each global a function creates.
local __orca_codex_arg __orca_codex_isolate="${ORCA_CODEX_ISOLATE:-1}" __orca_codex_identity="${ORCA_CODEX_ISOLATE:-1}"
+ if [[ "${ORCA_REMOTE_VIEWER_CLIPBOARD:-}" == 1 && -z "${SSH_CONNECTION+x}" && -z "${SSH_TTY+x}" ]]; then
+ local -x SSH_CONNECTION='127.0.0.1 0 127.0.0.1 0'
+ fi
if [[ -n "${ORCA_CODEX_LAUNCH_PREFLIGHT:-}" && -x "${ORCA_CODEX_LAUNCH_PREFLIGHT}" ]]; then
"${ORCA_CODEX_LAUNCH_PREFLIGHT}" agent hooks prepare-codex >/dev/null 2>&1 || :
fi
diff --git a/src/main/__fixtures__/shell-wrapper-snapshots/local-fish-init.txt b/src/main/__fixtures__/shell-wrapper-snapshots/local-fish-init.txt
index 404ffd4ccea..7c53db56ee8 100644
--- a/src/main/__fixtures__/shell-wrapper-snapshots/local-fish-init.txt
+++ b/src/main/__fixtures__/shell-wrapper-snapshots/local-fish-init.txt
@@ -21,7 +21,12 @@ if test "$__orca_codex_type" = file
if test "$ORCA_CODEX_ISOLATE" != 0; and not string match -qr -- '^(agents|queue|--remote|--no-daemon|--remote=.*)$' $argv; and command codex --help 2>/dev/null /dev/null 2>&1 || :
fi
diff --git a/src/main/acp/acp-structured-options.test.ts b/src/main/acp/acp-structured-options.test.ts
index 3b279890197..2d848e08a68 100644
--- a/src/main/acp/acp-structured-options.test.ts
+++ b/src/main/acp/acp-structured-options.test.ts
@@ -5,6 +5,9 @@ import { grokModelEfforts } from './acp-dialects/grok-model-catalog'
import { GROK_ACP_DIALECT } from './acp-dialects/grok-dialect'
import { OMP_ACP_DIALECT } from './acp-dialects/omp-dialect'
import { OPENCODE_ACP_DIALECT } from './acp-dialects/opencode-dialect'
+import type { AcpCommandOptionsFixtureModule } from '../../shared/mobile-queued-edit-host.test-fixture-contract'
+
+const mobileProducer = { AcpStructuredOptions } satisfies AcpCommandOptionsFixtureModule
const configOptions = [
{
@@ -36,7 +39,7 @@ describe('ACP session options', () => {
'projects %i live models once while retaining current/report values',
async (count) => {
const modelEfforts = vi.fn(grokModelEfforts)
- const options = new AcpStructuredOptions({ ...GROK_ACP_DIALECT, modelEfforts })
+ const options = new mobileProducer.AcpStructuredOptions({ ...GROK_ACP_DIALECT, modelEfforts })
options.adoptSession({
configOptions: [
...configOptions.slice(1),
diff --git a/src/main/acp/acp-subagents.ts b/src/main/acp/acp-subagents.ts
index 8eae33370ea..482ff449924 100644
--- a/src/main/acp/acp-subagents.ts
+++ b/src/main/acp/acp-subagents.ts
@@ -7,7 +7,7 @@ import type {
AgentChildWorkEvidenceHandle
} from '../../shared/agent-status-child-work-evidence'
import { AGENT_CHILD_WORK_ID_MAX_LENGTH } from '../../shared/agent-status-child-work-value-guards'
-import { MAX_SUBAGENT_FIELD_CHARS } from '../../shared/native-chat-subagent-summary'
+import { MAX_SUBAGENT_FIELD_CHARS } from '../../shared/native-chat/transcript/native-chat-subagent-summary'
import type { NativeChatSubagentState } from '../../shared/native-chat-types'
import { boundSubagentLabel } from '../native-chat/agent-session-journal/journal-subagent-item'
import type { ProviderTimelineJoin } from '../native-chat/agent-session-timeline/provider-timeline-event'
diff --git a/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts b/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts
new file mode 100644
index 00000000000..0efcfbd488d
--- /dev/null
+++ b/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { normalizeHookPayload } from '../../shared/agent-hook-listener'
+import {
+ createHookListenerState,
+ seedLegacyAgentStatusForTests
+} from '../../shared/agent-hook-listener/listener-state'
+import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build'
+import { AgentHookServer, _internals } from './server'
+import { PANE, buildBody } from './server.test-fixtures'
+
+vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
+vi.mock('../telemetry/cohort-classifier', () => ({
+ getCohortAtEmit: () => ({ nth_repo_added: 2 })
+}))
+
+const QUESTIONS = {
+ questions: [
+ {
+ id: 'scope',
+ header: 'Scope',
+ question: 'Which scope should I use?',
+ options: [{ label: 'Current workspace', description: 'Update the current workspace.' }]
+ }
+ ]
+}
+
+beforeEach(() => {
+ _internals.resetCachesForTests()
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+function remoteCodex() {
+ const host = createHookListenerState()
+ const server = new AgentHookServer()
+ return {
+ server,
+ report(payload: Record, legacy = false) {
+ const event = normalizeHookPayload(
+ host,
+ 'codex',
+ buildBody(payload, { worktreeId: 'folder-workspace' }),
+ 'production'
+ )
+ if (!event) {
+ throw new Error('Expected a Codex hook event')
+ }
+ seedLegacyAgentStatusForTests(host, event)
+ const { mainAgent: _mainAgent, ...legacyPayload } = event.payload
+ server.ingestRemote(
+ buildRelayHookEnvelope(
+ { ...event, payload: legacy ? legacyPayload : event.payload },
+ 'codex'
+ ),
+ 'wsl:Ubuntu'
+ )
+ return server.getStatusSnapshotForPane(PANE)[0]
+ }
+ }
+}
+
+describe('remote Codex questions', () => {
+ it.each([false, true])(
+ 'keeps a host question waiting until its answer (legacy relay: %s)',
+ (legacy) => {
+ const pane = remoteCodex()
+ expect(
+ pane.report(
+ { hook_event_name: 'UserPromptSubmit', prompt: 'Update this workspace' },
+ legacy
+ )
+ ).toMatchObject({ state: 'working', mainAgent: { state: 'working' } })
+
+ const question = pane.report(
+ {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'request_user_input',
+ tool_input: QUESTIONS,
+ tool_use_id: 'question-1'
+ },
+ legacy
+ )
+ expect(question).toMatchObject({
+ state: 'waiting',
+ mainAgent: { state: 'waiting' },
+ toolName: 'request_user_input',
+ interactivePrompt: JSON.stringify(QUESTIONS),
+ connectionId: 'wsl:Ubuntu',
+ worktreeId: 'folder-workspace'
+ })
+
+ expect(
+ pane.report(
+ {
+ hook_event_name: 'PostToolUse',
+ tool_name: 'request_user_input',
+ tool_input: QUESTIONS,
+ tool_response: '{"answers":{"scope":{"answers":["Current workspace"]}}}',
+ tool_use_id: 'question-1'
+ },
+ legacy
+ )
+ ).toMatchObject({ state: 'working', mainAgent: { state: 'working' } })
+ expect(pane.server.getStatusSnapshotForPane(PANE)[0]?.interactivePrompt).toBeUndefined()
+
+ expect(pane.report({ hook_event_name: 'Stop' }, legacy)).toMatchObject({
+ state: 'done',
+ mainAgent: { state: 'done' }
+ })
+ }
+ )
+
+ it('does not mistake a waiting child for a root question on an ordinary tool call', () => {
+ const pane = remoteCodex()
+ pane.report({ hook_event_name: 'UserPromptSubmit', prompt: 'Run the checks' })
+ pane.report({ hook_event_name: 'SubagentStart', agent_id: 'child' })
+ pane.report({
+ hook_event_name: 'PreToolUse',
+ agent_id: 'child',
+ tool_name: 'request_user_input',
+ tool_input: QUESTIONS
+ })
+
+ expect(pane.report({ hook_event_name: 'PreToolUse', tool_name: 'exec_command' })).toMatchObject(
+ { state: 'waiting', mainAgent: { state: 'working' } }
+ )
+ })
+
+ it('preserves ordinary approval waiting and resumes on tool execution', () => {
+ const pane = remoteCodex()
+ pane.report({ hook_event_name: 'UserPromptSubmit', prompt: 'Run the checks' })
+ expect(
+ pane.report({ hook_event_name: 'PermissionRequest', tool_name: 'exec_command' })
+ ).toMatchObject({ state: 'waiting', mainAgent: { state: 'waiting' } })
+ expect(pane.report({ hook_event_name: 'PreToolUse', tool_name: 'exec_command' })).toMatchObject(
+ { state: 'working', mainAgent: { state: 'working' } }
+ )
+ })
+})
diff --git a/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts b/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts
new file mode 100644
index 00000000000..35f439ec65f
--- /dev/null
+++ b/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts
@@ -0,0 +1,299 @@
+import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { normalizeHookPayload } from '../../shared/agent-hook-listener'
+import { createShedSubagentsField } from '../../shared/agent-hook-relay'
+import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state'
+import { pollCodexTranscriptStatus } from '../../shared/agent-hook-listener/providers/codex-transcript-poll'
+import { transcriptPollUpdate } from '../../shared/agent-hook-listener/transcript-poll-policy'
+import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build'
+import { AgentHookServer, _internals } from './server'
+import { PANE, buildBody } from './server.test-fixtures'
+
+vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
+vi.mock('../telemetry/cohort-classifier', () => ({
+ getCohortAtEmit: () => ({ nth_repo_added: 2 })
+}))
+
+const CHILD = '01a16839-7f84-7ed3-aebf-ea51e50330cf'
+const SECOND_CHILD = '02a16839-7f84-7ed3-aebf-ea51e50330cf'
+const line = (type: string): string =>
+ `${JSON.stringify({ type: 'event_msg', payload: { type } })}\n`
+
+let directory: string
+
+beforeEach(() => {
+ _internals.resetCachesForTests()
+ directory = mkdtempSync(join(tmpdir(), 'orca-remote-codex-child-'))
+})
+
+afterEach(() => {
+ rmSync(directory, { recursive: true, force: true })
+ vi.restoreAllMocks()
+})
+
+describe('remote Codex transcript completion', () => {
+ it('retires transcript-completed children while keeping surviving child work live', () => {
+ const parentPath = join(directory, 'rollout-parent.jsonl')
+ const childPath = join(directory, `rollout-child-${CHILD}.jsonl`)
+ const secondChildPath = join(directory, `rollout-child-${SECOND_CHILD}.jsonl`)
+ writeFileSync(parentPath, line('task_complete'))
+ writeFileSync(childPath, line('task_started'))
+ writeFileSync(secondChildPath, line('task_started'))
+ const hostState = createHookListenerState()
+ const server = new AgentHookServer()
+ const root = normalizeHookPayload(
+ hostState,
+ 'codex',
+ buildBody({
+ hook_event_name: 'Stop',
+ session_id: 'root',
+ transcript_path: parentPath
+ }),
+ 'production'
+ )
+ if (!root) {
+ throw new Error('Root hook was rejected')
+ }
+ server.ingestRemote(buildRelayHookEnvelope(root, 'codex'), 'wsl:Ubuntu')
+
+ const childBody = buildBody({
+ hook_event_name: 'SubagentStart',
+ agent_id: CHILD,
+ session_id: CHILD,
+ transcript_path: childPath
+ })
+ const started = normalizeHookPayload(hostState, 'codex', childBody, 'production')
+ if (!started) {
+ throw new Error('Child hook was rejected')
+ }
+ server.ingestRemote(buildRelayHookEnvelope(started, 'codex'), 'wsl:Ubuntu')
+ expect(server.getStatusSnapshot()).toEqual([
+ expect.objectContaining({
+ paneKey: PANE,
+ state: 'working',
+ subagents: [
+ {
+ id: CHILD,
+ state: 'working',
+ startedAt: expect.any(Number)
+ }
+ ]
+ })
+ ])
+
+ const secondChildBody = buildBody({
+ hook_event_name: 'SubagentStart',
+ agent_id: SECOND_CHILD,
+ session_id: SECOND_CHILD,
+ transcript_path: secondChildPath
+ })
+ const secondStarted = normalizeHookPayload(hostState, 'codex', secondChildBody, 'production')
+ if (!secondStarted) {
+ throw new Error('Second child hook was rejected')
+ }
+ server.ingestRemote(buildRelayHookEnvelope(secondStarted, 'codex'), 'wsl:Ubuntu')
+ expect(
+ server
+ .getStatusSnapshot()[0]
+ .subagents?.map((child) => child.id)
+ .sort()
+ ).toEqual([CHILD, SECOND_CHILD])
+
+ appendFileSync(childPath, line('task_complete'))
+ const oneRemaining = pollCodexTranscriptStatus(
+ hostState,
+ secondStarted,
+ secondChildBody,
+ 'production'
+ )
+ if (!oneRemaining) {
+ throw new Error('No first child completion status')
+ }
+ const partialUpdate = transcriptPollUpdate('codex', secondStarted, oneRemaining)
+ if (!partialUpdate) {
+ throw new Error('Host did not publish first child completion')
+ }
+ expect(partialUpdate).toMatchObject({
+ toolAgentId: SECOND_CHILD,
+ payload: {
+ state: 'working',
+ mainAgent: { state: 'done' },
+ subagents: [expect.objectContaining({ id: SECOND_CHILD, state: 'working' })]
+ }
+ })
+ expect(partialUpdate.hookEventName).toBeUndefined()
+ server.ingestRemote(buildRelayHookEnvelope(partialUpdate, 'codex'), 'wsl:Ubuntu')
+ expect(server.getStatusSnapshot()[0]).toMatchObject({
+ state: 'working',
+ mainAgent: { state: 'done' },
+ subagents: [expect.objectContaining({ id: SECOND_CHILD, state: 'working' })]
+ })
+
+ appendFileSync(secondChildPath, line('task_complete'))
+ const polled = pollCodexTranscriptStatus(
+ hostState,
+ partialUpdate,
+ secondChildBody,
+ 'production'
+ )
+ if (!polled) {
+ throw new Error('No completion status')
+ }
+ const update = transcriptPollUpdate('codex', partialUpdate, polled)
+ if (!update) {
+ throw new Error('Host did not publish transcript completion')
+ }
+ expect(update).toMatchObject({ toolAgentId: SECOND_CHILD, payload: { state: 'done' } })
+ expect(update.hookEventName).toBeUndefined()
+ expect(update.payload.subagents).toBeUndefined()
+
+ server.ingestRemote(buildRelayHookEnvelope(update, 'codex'), 'wsl:Ubuntu')
+
+ expect(server.getStatusSnapshot()).toEqual([
+ expect.objectContaining({
+ paneKey: PANE,
+ state: 'done',
+ mainAgent: expect.objectContaining({ state: 'done' })
+ })
+ ])
+ expect(server.getStatusSnapshot()[0].subagents).toBeUndefined()
+ })
+})
+
+describe('remote Codex truncated transcript snapshots', () => {
+ it('keeps live work when a changed roster was shed to fit the relay frame', () => {
+ const server = new AgentHookServer()
+ const children = [
+ { id: CHILD, state: 'working' as const, startedAt: 1 },
+ { id: SECOND_CHILD, state: 'working' as const, startedAt: 2 }
+ ]
+ server.ingestRemote(
+ {
+ paneKey: PANE,
+ source: 'codex',
+ hookEventName: 'SubagentStart',
+ toolAgentId: SECOND_CHILD,
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: 'working',
+ mainAgent: { state: 'done', stateStartedAt: 1 },
+ subagents: children
+ }
+ },
+ 'wsl:Ubuntu'
+ )
+ server.ingestRemote(
+ {
+ paneKey: PANE,
+ source: 'codex',
+ toolAgentId: SECOND_CHILD,
+ shedFields: [createShedSubagentsField([children[1]!])],
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: 'working',
+ mainAgent: { state: 'done', stateStartedAt: 1 }
+ }
+ },
+ 'wsl:Ubuntu'
+ )
+ expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({ state: 'working' })
+ expect(server.getStatusSnapshotForPane(PANE)[0]?.subagents).toHaveLength(2)
+ })
+
+ it('keeps a shed roster when an unlabelled root poll reports a done main agent', () => {
+ const server = new AgentHookServer()
+ const child = { id: CHILD, state: 'working' as const, startedAt: 1 }
+ server.ingestRemote(
+ {
+ paneKey: PANE,
+ source: 'codex',
+ hookEventName: 'SubagentStart',
+ toolAgentId: CHILD,
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: 'working',
+ mainAgent: { state: 'working', stateStartedAt: 1 },
+ subagents: [child]
+ }
+ },
+ 'wsl:Ubuntu'
+ )
+ server.ingestRemote(
+ {
+ paneKey: PANE,
+ source: 'codex',
+ shedFields: [createShedSubagentsField([{ ...child, description: 'changed' }])],
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: 'working',
+ mainAgent: { state: 'done', stateStartedAt: 2 }
+ }
+ },
+ 'wsl:Ubuntu'
+ )
+ expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({
+ state: 'working',
+ mainAgent: { state: 'done' },
+ subagents: [expect.objectContaining({ id: CHILD })]
+ })
+ })
+})
+
+describe('remote Codex unlabelled roster removals', () => {
+ const childStart = (id: string, startedAt: number) => ({
+ paneKey: PANE,
+ source: 'codex',
+ hookEventName: 'SubagentStart',
+ toolAgentId: id,
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: 'working',
+ mainAgent: { state: 'working', stateStartedAt: 1 },
+ subagents: [{ id, state: 'working', startedAt }]
+ }
+ })
+ const emptyPoll = (mainState: 'working' | 'done', toolAgentId?: string) => ({
+ paneKey: PANE,
+ source: 'codex',
+ toolAgentId,
+ payload: {
+ agentType: 'codex',
+ prompt: 'Run the checks',
+ state: mainState,
+ mainAgent: { state: mainState, stateStartedAt: 1 }
+ }
+ })
+
+ it('retires the last child while the root keeps working', () => {
+ const server = new AgentHookServer()
+ server.ingestRemote(childStart(CHILD, 1), 'wsl:Ubuntu')
+ server.ingestRemote(emptyPoll('working', CHILD), 'wsl:Ubuntu')
+ const row = server.getStatusSnapshotForPane(PANE)[0]
+ expect(row).toMatchObject({ state: 'working', mainAgent: { state: 'working' } })
+ expect(row?.subagents).toBeUndefined()
+ })
+
+ it('keeps children a restarted relay never listed', () => {
+ const server = new AgentHookServer()
+ server.beginRemoteRelaySession('wsl:Ubuntu')
+ server.ingestRemote(childStart(CHILD, 1), 'wsl:Ubuntu')
+ server.beginRemoteRelaySession('wsl:Ubuntu')
+ server.ingestRemote(emptyPoll('done'), 'wsl:Ubuntu')
+ expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({
+ state: 'working',
+ subagents: [expect.objectContaining({ id: CHILD })]
+ })
+
+ server.ingestRemote(childStart(CHILD, 1), 'wsl:Ubuntu')
+ server.ingestRemote(emptyPoll('done'), 'wsl:Ubuntu')
+ expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({ state: 'done' })
+ expect(server.getStatusSnapshotForPane(PANE)[0]?.subagents).toBeUndefined()
+ })
+})
diff --git a/src/main/agent-hooks/server/server-ingest-remote.ts b/src/main/agent-hooks/server/server-ingest-remote.ts
index 4ac2f8fa3ef..2e5f2ced681 100644
--- a/src/main/agent-hooks/server/server-ingest-remote.ts
+++ b/src/main/agent-hooks/server/server-ingest-remote.ts
@@ -19,7 +19,8 @@ import {
} from '../../../shared/claude-compact-completion'
import { launchTokenHash } from '../../../shared/agent-hook-spool'
import { parsePaneKey } from '../../../shared/stable-pane-id'
-import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event'
+import type { IncomingAgentHookEvent } from './server-types'
+import { RelaySessionGenerations } from './server-relay-sessions'
import {
AGENT_STATUS_LEGACY_UNADVERTISED_PEER_CAPABILITIES,
canAdmitLegacyAgentStatus,
@@ -33,6 +34,13 @@ import {
import { AgentHookServerIngestStructuredChildren } from './server-ingest-structured-children'
export abstract class AgentHookServerIngestRemote extends AgentHookServerIngestStructuredChildren {
+ private readonly relaySessions = new RelaySessionGenerations()
+
+ /** Call as each relay link starts, before its first envelope. */
+ beginRemoteRelaySession(connectionId: string): void {
+ this.relaySessions.begin(connectionId)
+ }
+
/** Relay payloads cross the SSH trust boundary and require canonical validation here. */
ingestRemote(envelope: RemoteAgentStatusEnvelope, connectionId: string | null): void {
if (
@@ -247,7 +255,7 @@ export abstract class AgentHookServerIngestRemote extends AgentHookServerIngestS
env: envelope.env,
expectedEnv: this.env
})
- const event: AgentHookEventPayload & { authorityRestartId?: string } = {
+ const event: IncomingAgentHookEvent = {
paneKey,
agentPresence: readAgentProcessPresence(envelope.agentPresence),
source: effectiveSource,
@@ -281,6 +289,11 @@ export abstract class AgentHookServerIngestRemote extends AgentHookServerIngestS
typeof envelope.claudeRunningNonAgentTask === 'boolean'
? envelope.claudeRunningNonAgentTask
: undefined,
+ codexRosterAuthority: this.relaySessions.codexRosterAuthority(
+ trimmedConnectionId,
+ normalizedPayload,
+ envelope.shedFields
+ ),
payload: normalizedPayload
}
this.recordCurrentAuthorityObservation(event)
diff --git a/src/main/agent-hooks/server/server-relay-sessions.ts b/src/main/agent-hooks/server/server-relay-sessions.ts
new file mode 100644
index 00000000000..d4c8b1ec31d
--- /dev/null
+++ b/src/main/agent-hooks/server/server-relay-sessions.ts
@@ -0,0 +1,28 @@
+import { hasShedSubagentsField } from '../../../shared/agent-hook-relay'
+import type { CodexRemoteRosterAuthority } from '../../../shared/agent-hook-listener/providers/codex-state'
+import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types'
+
+/** Counts relay links per connection: a restarted guest rebuilds only part of its state, so it cannot vouch for an earlier guest's children. */
+export class RelaySessionGenerations {
+ private readonly generationByConnectionId = new Map()
+
+ begin(connectionId: string): void {
+ const key = connectionId.trim()
+ this.generationByConnectionId.set(key, (this.generationByConnectionId.get(key) ?? 0) + 1)
+ }
+
+ codexRosterAuthority(
+ connectionId: string | null,
+ payload: ParsedAgentStatusPayload,
+ shedFields: unknown
+ ): CodexRemoteRosterAuthority | undefined {
+ if (payload.agentType !== 'codex') {
+ return undefined
+ }
+ const key = connectionId ?? ''
+ return {
+ relaySession: `${key}#${this.generationByConnectionId.get(key) ?? 0}`,
+ rosterShed: hasShedSubagentsField(shedFields)
+ }
+ }
+}
diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts
index b79a01220d2..9d2e31bc75e 100644
--- a/src/main/agent-hooks/server/server-status-update.ts
+++ b/src/main/agent-hooks/server/server-status-update.ts
@@ -1,15 +1,14 @@
import { deriveCliWriterTopology } from './cli-writer-observation'
import { transitionHookPresence } from '../../../shared/agent-hook-presence-transition'
import {
- reconcileRemoteCodexState,
+ reconcileCodexStatusEvent,
markCodexLeadTurnInterrupted
} from '../../../shared/agent-hook-listener/providers/codex-state'
import {
resolveAgentStatusIdentity,
shouldSuppressInheritedTerminalStatus
} from '../../../shared/agent-status-identity'
-import type { EnrichedAgentHookEventPayload } from './server-types'
-import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event'
+import type { EnrichedAgentHookEventPayload, IncomingAgentHookEvent } from './server-types'
import type { AgentStatusObservationOrigin } from '../../../shared/agent-status-observation'
import { ClaudeOwedNotificationExpiryTimers } from '../../../shared/claude-owed-notification-expiry-timers'
import { setClaudeMainAgentTurnState } from '../../../shared/agent-hook-listener/providers/claude-roster-state'
@@ -46,7 +45,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA
}
protected applyNormalizedStatus(
- incoming: AgentHookEventPayload & { authorityRestartId?: string },
+ incoming: IncomingAgentHookEvent,
onAccepted?: () => void,
origin: AgentStatusObservationOrigin = 'hook',
observedAt?: number,
@@ -60,7 +59,10 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA
if (!transitioned) {
return undefined
}
- const { authorityRestartId, ...payload } = { ...incoming, ...transitioned }
+ const { authorityRestartId, codexRosterAuthority, ...payload } = {
+ ...incoming,
+ ...transitioned
+ }
if (!this.canWriteLegacyStatusRow(payload)) {
return undefined
}
@@ -165,22 +167,12 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA
this.emitEnrichedStatus(enriched)
return enriched
}
- const stateReconciledPayload =
- (terminalOwnedPayload.connectionId || !terminalOwnedPayload.hookEventName) &&
- terminalOwnedPayload.payload.agentType === 'codex' &&
- (terminalOwnedPayload.hookEventName || terminalOwnedPayload.payload.mainAgent)
- ? {
- ...terminalOwnedPayload,
- payload: reconcileRemoteCodexState(
- this.state,
- terminalOwnedPayload.paneKey,
- terminalOwnedPayload.hookEventName,
- terminalOwnedPayload.toolAgentId,
- terminalOwnedPayload.payload,
- previous?.payload
- )
- }
- : terminalOwnedPayload
+ const stateReconciledPayload = reconcileCodexStatusEvent(
+ this.state,
+ terminalOwnedPayload,
+ previous?.payload,
+ codexRosterAuthority
+ )
const previousCodexRoot =
stateReconciledPayload.payload.agentType === 'codex' &&
stateReconciledPayload.toolAgentId &&
diff --git a/src/main/agent-hooks/server/server-types.ts b/src/main/agent-hooks/server/server-types.ts
index d3c8ef9a82e..9e3773657ae 100644
--- a/src/main/agent-hooks/server/server-types.ts
+++ b/src/main/agent-hooks/server/server-types.ts
@@ -9,6 +9,13 @@ import type {
import type { AgentStatusObservation } from '../../../shared/agent-status-observation'
import type { AgentKind } from '../../../shared/telemetry-events'
import type { LegacyPaneKeyAliasEntry } from '../../../shared/persisted-state-types'
+import type { CodexRemoteRosterAuthority } from '../../../shared/agent-hook-listener/providers/codex-state'
+
+/** Ingest-only fields, stripped before the row is stored. */
+export type IncomingAgentHookEvent = AgentHookEventPayload & {
+ authorityRestartId?: string
+ codexRosterAuthority?: CodexRemoteRosterAuthority
+}
export type EnrichedAgentHookEventPayload = AgentHookEventPayload & {
/** Live acknowledgement of the matching renderer retirement; never cached. */
diff --git a/src/main/agent-hooks/wsl-bridge-daemon-sessions.test.ts b/src/main/agent-hooks/wsl-bridge-daemon-sessions.test.ts
new file mode 100644
index 00000000000..eb7d643c41a
--- /dev/null
+++ b/src/main/agent-hooks/wsl-bridge-daemon-sessions.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest'
+import type { SessionInfo } from '../daemon/daemon-session-info'
+import { daemonBridgeSessionVerdict } from './wsl-bridge-daemon-sessions'
+
+function session(fields: Partial): SessionInfo {
+ return {
+ sessionId: 's',
+ state: 'running',
+ shellState: 'ready',
+ isAlive: true,
+ pid: 1,
+ cwd: null,
+ cols: 80,
+ rows: 24,
+ createdAt: 0,
+ ...fields
+ }
+}
+
+describe("the daemon's bridge sessions for a relay's distro", () => {
+ it('finds a live session named for the distro, in any case', () => {
+ expect(daemonBridgeSessionVerdict([session({ wslDistro: 'ubuntu' })], 'Ubuntu')).toBe('live')
+ })
+
+ it('reads an older daemon’s session by its WSL folder', () => {
+ expect(
+ daemonBridgeSessionVerdict([session({ cwd: '\\\\wsl.localhost\\Ubuntu\\home\\u' })], 'Ubuntu')
+ ).toBe('live')
+ })
+
+ it('ignores native, other-distro and exited sessions', () => {
+ expect(
+ daemonBridgeSessionVerdict(
+ [
+ session({ wslDistro: null, cwd: 'C:\\repo' }),
+ session({ wslDistro: 'Debian' }),
+ session({ wslDistro: 'Ubuntu', isAlive: false })
+ ],
+ 'Ubuntu'
+ )
+ ).toBe('none')
+ })
+
+ it('cannot vouch when a daemon generation did not answer', () => {
+ expect(daemonBridgeSessionVerdict(null, 'Ubuntu')).toBe('unverifiable')
+ })
+})
diff --git a/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts b/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts
new file mode 100644
index 00000000000..c5b403b6902
--- /dev/null
+++ b/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts
@@ -0,0 +1,48 @@
+/**
+ * Whether the terminal daemon still runs a bridge session in a distro, mounted or not: after a
+ * relaunch a hidden worktree's or headless tab's session is live in the daemon though no pane in
+ * this app run has noted it, and orchestration, automations or mobile may wake its agent.
+ */
+import { getDaemonProvider, listLiveDaemonSessions } from '../daemon/daemon-provider-state'
+import type { SessionInfo } from '../daemon/daemon-session-info'
+import { parseWslUncPath } from '../../shared/wsl-paths'
+import { wslHookRelayStateKey } from './wsl-hook-relay-state-key'
+
+/** 'unverifiable' when any daemon generation couldn't answer: the relay then stays. */
+export type DaemonBridgeSessionVerdict = 'live' | 'none' | 'unverifiable'
+
+function sessionDistro(session: SessionInfo): string | null {
+ if (typeof session.wslDistro === 'string') {
+ return session.wslDistro
+ }
+ // Older daemons omit the field; a session in a WSL folder still names its distro by its cwd.
+ return session.wslDistro === undefined && session.cwd
+ ? (parseWslUncPath(session.cwd)?.distro ?? null)
+ : null
+}
+
+export function daemonBridgeSessionVerdict(
+ sessions: readonly SessionInfo[] | null,
+ distro: string
+): DaemonBridgeSessionVerdict {
+ if (!sessions) {
+ return 'unverifiable'
+ }
+ const key = wslHookRelayStateKey(distro)
+ return sessions.some((session) => {
+ const named = sessionDistro(session)
+ return session.isAlive && named !== null && wslHookRelayStateKey(named) === key
+ })
+ ? 'live'
+ : 'none'
+}
+
+export async function readDaemonBridgeSessions(
+ distro: string
+): Promise {
+ // No daemon: local terminals run in this process, and presence already counts them all.
+ if (!getDaemonProvider()) {
+ return 'none'
+ }
+ return daemonBridgeSessionVerdict(await listLiveDaemonSessions().catch(() => null), distro)
+}
diff --git a/src/main/agent-hooks/wsl-bridge-pty-presence.ts b/src/main/agent-hooks/wsl-bridge-pty-presence.ts
new file mode 100644
index 00000000000..fdf13e8dd5a
--- /dev/null
+++ b/src/main/agent-hooks/wsl-bridge-pty-presence.ts
@@ -0,0 +1,61 @@
+/**
+ * Live local WSL (bridge) terminals per distro: the hook relay for a distro idles out only when
+ * none remain. Fed by the PTY layer at spawn, reattach and exit.
+ */
+import { wslHookRelayStateKey } from './wsl-hook-relay-state-key'
+
+// A WSL terminal whose distro the spawn didn't report: it counts for every distro, so no relay it
+// may be using idles out under it (rare: an older daemon reporting no distro).
+const UNNAMED_DISTRO = ''
+
+type PresenceListener = (distro: string) => void
+
+export class WslBridgePtyPresence {
+ private readonly distroByPty = new Map()
+ private readonly listeners = new Set()
+
+ /** `distro` null: a WSL terminal the spawn didn't name a distro for. */
+ noteLive(ptyId: string, distro: string | null): void {
+ const key = distro === null ? UNNAMED_DISTRO : wslHookRelayStateKey(distro)
+ if (this.distroByPty.get(ptyId) === key) {
+ return
+ }
+ const previous = this.distroByPty.get(ptyId)
+ this.distroByPty.set(ptyId, key)
+ if (previous !== undefined) {
+ this.notify(previous)
+ }
+ this.notify(key)
+ }
+
+ noteExited(ptyId: string): void {
+ const key = this.distroByPty.get(ptyId)
+ if (key !== undefined) {
+ this.distroByPty.delete(ptyId)
+ this.notify(key)
+ }
+ }
+
+ count(distro: string): number {
+ const key = wslHookRelayStateKey(distro)
+ let live = 0
+ for (const candidate of this.distroByPty.values()) {
+ live += candidate === key || candidate === UNNAMED_DISTRO ? 1 : 0
+ }
+ return live
+ }
+
+ /** Called with the distro (state key) whose count changed; '' means every distro's. */
+ onChange(listener: PresenceListener): () => void {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
+ private notify(key: string): void {
+ for (const listener of this.listeners) {
+ listener(key)
+ }
+ }
+}
+
+export const wslBridgePtyPresence = new WslBridgePtyPresence()
diff --git a/src/main/agent-hooks/wsl-hook-relay-deps.ts b/src/main/agent-hooks/wsl-hook-relay-deps.ts
index 7fb6ac7eec5..bb970ee2c55 100644
--- a/src/main/agent-hooks/wsl-hook-relay-deps.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-deps.ts
@@ -22,6 +22,11 @@ import { waitForWslRelaySentinel } from './wsl-hook-relay-sentinel'
import { listWslDistrosAsync } from '../wsl'
import { deferUntilWslDistroRunning, isWslDistroRunning } from '../wsl-background-distro-gate'
import { isWslAgentHookRelayEnabled } from '../../shared/agent-hook-relay'
+import { wslBridgePtyPresence, type WslBridgePtyPresence } from './wsl-bridge-pty-presence'
+import {
+ readDaemonBridgeSessions,
+ type DaemonBridgeSessionVerdict
+} from './wsl-bridge-daemon-sessions'
// Concurrent wsl.exe spawns can trigger transient E_UNEXPECTED failures.
export const WSL_RELAY_TRANSIENT_RETRY_DELAY_MS = 2_000
@@ -54,6 +59,7 @@ export type WslHookRelayManagerDeps = {
runInstall: typeof runWslInstallProcess
waitForSentinel: typeof waitForWslRelaySentinel
ingest: (envelope: Record, connectionId: string) => void
+ beginRelaySession?: (connectionId: string) => void
receiveClaudeAgentView?: (body: unknown) => unknown
bindInterruptReconciliation?: (
mux: Parameters[1],
@@ -67,6 +73,11 @@ export type WslHookRelayManagerDeps = {
pluginSources: () => PluginSources
warn: (message: string) => void
transientRetryDelayMs: number
+ /** Live bridge terminals per distro; a relay idles out only when its distro has none. */
+ bridgePtyPresence: Pick
+ /** Whether the terminal daemon still runs a bridge session there, mounted or not. */
+ daemonBridgeSessions: (distro: string) => Promise
+ idleStopMs?: number
}
/** Read the hooks setting live for spawn, reattach, and crash recovery. */
@@ -88,6 +99,8 @@ export const defaultWslHookRelayDeps: WslHookRelayManagerDeps = {
const source = agentHookServer.endpointFilePath
return source ? createHash('sha256').update(source).digest('hex').slice(0, 12) : null
},
+ bridgePtyPresence: wslBridgePtyPresence,
+ daemonBridgeSessions: readDaemonBridgeSessions,
resolveBundle: resolveWslHookRelayBundle,
readBundle: (jsPath) => readFileSync(jsPath),
listDistros: () => listWslDistrosAsync(),
@@ -106,6 +119,7 @@ export const defaultWslHookRelayDeps: WslHookRelayManagerDeps = {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: envelope is the wire-deserialized notification; ingestRemote independently re-validates paneKey's type before trusting anything here.
return agentHookServer.ingestRemote(capped as IngestEnvelope, connectionId)
},
+ beginRelaySession: (connectionId) => agentHookServer.beginRemoteRelaySession(connectionId),
bindInterruptReconciliation: (mux, connectionId, isCurrent) =>
bindRemoteClaudeInterruptReconciliation(agentHookServer, mux, connectionId, isCurrent),
installHooks: installRemoteManagedAgentHooks,
diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts b/src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts
new file mode 100644
index 00000000000..ebd2af90926
--- /dev/null
+++ b/src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { WslBridgePtyPresence } from './wsl-bridge-pty-presence'
+import { WslRelayIdleStop } from './wsl-hook-relay-idle-stop'
+import type { WslRelayDistroState } from './wsl-hook-relay-state'
+import type { DaemonBridgeSessionVerdict } from './wsl-bridge-daemon-sessions'
+
+function running(distro = 'Ubuntu'): WslRelayDistroState {
+ return {
+ distro,
+ phase: 'running',
+ launchKinds: new Set(),
+ failures: 0,
+ cooldownUntil: 0,
+ child: { kill: vi.fn() },
+ codexHomePath: '/home/u/.codex'
+ }
+}
+
+describe('the WSL hook relay idle stop', () => {
+ let states: Map
+ let presence: WslBridgePtyPresence
+ let idle: WslRelayIdleStop
+ const clearRecoveryTimers = vi.fn()
+ let daemon: DaemonBridgeSessionVerdict
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ states = new Map()
+ presence = new WslBridgePtyPresence()
+ clearRecoveryTimers.mockClear()
+ daemon = 'none'
+ idle = new WslRelayIdleStop({
+ idleMs: 1_000,
+ states,
+ livePtyCount: (distro) => presence.count(distro),
+ daemonBridgeSessions: async () => daemon,
+ isDisposed: () => false,
+ clearRecoveryTimers,
+ warn: () => {}
+ })
+ presence.onChange((key) => idle.presenceChanged(key))
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('counts hook traffic as activity, restarting the window', async () => {
+ const state = running()
+ states.set('ubuntu', state)
+ idle.update(state)
+ const ingest = vi.fn()
+ const traffic = idle.noteTraffic(state, ingest)
+ await vi.advanceTimersByTimeAsync(999)
+ traffic({ paneKey: 'p' }, 'wsl:Ubuntu')
+ expect(ingest).toHaveBeenCalledWith({ paneKey: 'p' }, 'wsl:Ubuntu')
+ await vi.advanceTimersByTimeAsync(999)
+ expect(states.has('ubuntu')).toBe(true)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(states.has('ubuntu')).toBe(false)
+ expect(state.child?.kill).toHaveBeenCalledOnce()
+ expect(clearRecoveryTimers).toHaveBeenCalledWith(state)
+ })
+
+ it('arms only when the last bridge terminal of the distro goes, and only for that distro', async () => {
+ const ubuntu = running()
+ const debian = running('Debian')
+ states.set('ubuntu', ubuntu)
+ states.set('debian', debian)
+ presence.noteLive('pty-1', 'Ubuntu')
+ presence.noteLive('pty-2', 'ubuntu')
+ presence.noteLive('pty-3', 'Debian')
+ presence.noteExited('pty-1')
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(states.has('ubuntu')).toBe(true)
+
+ presence.noteExited('pty-2')
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(states.has('ubuntu')).toBe(false)
+ expect(states.has('debian')).toBe(true)
+ })
+
+ // Review of #35173: a WSL shell whose distro the spawn didn't report still uses a relay.
+ it('keeps every relay while a WSL terminal of unknown distro is open', async () => {
+ const ubuntu = running()
+ states.set('ubuntu', ubuntu)
+ presence.noteLive('pty-1', null)
+ idle.update(ubuntu)
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(states.has('ubuntu')).toBe(true)
+
+ presence.noteExited('pty-1')
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(states.has('ubuntu')).toBe(false)
+ })
+
+ // Review of #35173: after a relaunch a hidden or headless bridge session is live in the daemon
+ // though no pane noted it; orchestration or mobile may wake its agent.
+ it("keeps a relay while the daemon still runs a bridge session there, or can't say", async () => {
+ const state = running()
+ states.set('ubuntu', state)
+ for (const verdict of ['live', 'unverifiable'] as const) {
+ daemon = verdict
+ idle.update(state)
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(states.get('ubuntu')).toBe(state)
+ }
+
+ daemon = 'none'
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(states.has('ubuntu')).toBe(false)
+ })
+
+ it('brings a stopped relay back with its config, and a quit forgets it', async () => {
+ const state = running()
+ states.set('ubuntu', state)
+ idle.update(state)
+ await vi.advanceTimersByTimeAsync(1_000)
+
+ idle.restoreParked('Ubuntu')
+ expect(states.get('ubuntu')).toMatchObject({
+ phase: 'failed',
+ cooldownUntil: 0,
+ codexHomePath: '/home/u/.codex'
+ })
+
+ states.clear()
+ const again = running()
+ states.set('ubuntu', again)
+ idle.update(again)
+ await vi.advanceTimersByTimeAsync(1_000)
+ idle.dispose(true)
+ idle.restoreParked('Ubuntu')
+ expect(states.has('ubuntu')).toBe(false)
+ })
+
+ it('never stops a relay that is not running, or one a newer state replaced', async () => {
+ const starting = { ...running(), phase: 'starting' as const }
+ states.set('ubuntu', starting)
+ idle.update(starting)
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(states.get('ubuntu')).toBe(starting)
+
+ const old = running()
+ idle.update(old)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(states.get('ubuntu')).toBe(starting)
+ expect(old.child?.kill).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.ts b/src/main/agent-hooks/wsl-hook-relay-idle-stop.ts
new file mode 100644
index 00000000000..ae83547c355
--- /dev/null
+++ b/src/main/agent-hooks/wsl-hook-relay-idle-stop.ts
@@ -0,0 +1,157 @@
+/**
+ * A running relay is the last thing holding its distro (and the WSL VM's memory) once no bridge
+ * terminal remains there. After WSL_RELAY_IDLE_STOP_MS with no bridge terminal and no hook
+ * traffic, it is stopped and its config parked; the next terminal or agent in that distro (a user
+ * act that runs wsl.exe itself) starts it again. Nothing here starts a relay, so nothing boots.
+ */
+import type { WslRelayDistroState, WslRelayRestartSetup } from './wsl-hook-relay-state'
+import { wslHookRelayStateKey } from './wsl-hook-relay-state-key'
+import { captureWslRelaySetup, seedWslRelayState } from './wsl-hook-relay-state-machine'
+import type { WslHookRelayManagerDeps } from './wsl-hook-relay-deps'
+import type { WslRelayRecovery } from './wsl-hook-relay-recovery'
+import type { DaemonBridgeSessionVerdict } from './wsl-bridge-daemon-sessions'
+
+export const WSL_RELAY_IDLE_STOP_MS = 5 * 60_000
+
+export type WslRelayIdleStopDeps = {
+ idleMs?: number
+ states: Map
+ livePtyCount: (distro: string) => number
+ /** The daemon's own inventory, read before a stop; anything but 'none' keeps the relay. */
+ daemonBridgeSessions: (distro: string) => Promise
+ isDisposed: () => boolean
+ clearRecoveryTimers: (state: WslRelayDistroState) => void
+ warn: (message: string) => void
+}
+
+export class WslRelayIdleStop {
+ private readonly timers = new Map>()
+ private readonly parked = new Map()
+
+ constructor(private readonly deps: WslRelayIdleStopDeps) {}
+
+ /** Re-evaluate after a relay came up, a bridge terminal came or went, or a hook arrived. */
+ update(state: WslRelayDistroState): void {
+ this.clear(state)
+ if (state.phase !== 'running' || this.deps.livePtyCount(state.distro) > 0) {
+ return
+ }
+ const timer = setTimeout(() => {
+ this.timers.delete(state)
+ void this.stopIfIdle(state)
+ }, this.deps.idleMs ?? WSL_RELAY_IDLE_STOP_MS)
+ timer.unref?.()
+ this.timers.set(state, timer)
+ }
+
+ /** Hook traffic over this relay's link counts as activity. */
+ noteTraffic(
+ state: WslRelayDistroState,
+ ingest: (...args: TArgs) => void
+ ): (...args: TArgs) => void {
+ return (...args) => {
+ this.update(state)
+ ingest(...args)
+ }
+ }
+
+ /** A bridge terminal count changed for this distro (state key). */
+ presenceChanged(key: string): void {
+ const changed = key ? [this.deps.states.get(key)] : [...this.deps.states.values()]
+ for (const state of changed) {
+ if (state) {
+ this.update(state)
+ }
+ }
+ }
+
+ private clear(state: WslRelayDistroState): void {
+ const timer = this.timers.get(state)
+ if (timer) {
+ clearTimeout(timer)
+ this.timers.delete(state)
+ }
+ }
+
+ /** Before an ensure: an idle-stopped relay comes back with the config it served. */
+ restoreParked(distro: string): void {
+ const key = wslHookRelayStateKey(distro)
+ const setup = this.parked.get(key)
+ if (!setup) {
+ return
+ }
+ this.parked.delete(key)
+ if (!this.deps.states.has(key)) {
+ this.deps.states.set(key, seedWslRelayState(distro, setup))
+ }
+ }
+
+ /** Hooks off or quit: no timer outlives the relays; a quit also forgets what was parked. */
+ dispose(permanent: boolean): void {
+ for (const timer of this.timers.values()) {
+ clearTimeout(timer)
+ }
+ this.timers.clear()
+ if (permanent) {
+ this.parked.clear()
+ }
+ }
+
+ private async stopIfIdle(state: WslRelayDistroState): Promise {
+ if (state.phase !== 'running' || this.deps.livePtyCount(state.distro) > 0) {
+ return
+ }
+ const verdict = await this.deps.daemonBridgeSessions(state.distro)
+ // A session no pane in this run has noted (a hidden or headless one after a relaunch) still
+ // needs its hooks; so does one the daemon couldn't vouch for. Look again a window later.
+ if (verdict !== 'none') {
+ this.update(state)
+ return
+ }
+ // Re-checked after the await: a terminal or hook may have come meanwhile.
+ if (
+ !this.timers.has(state) &&
+ state.phase === 'running' &&
+ this.deps.livePtyCount(state.distro) === 0
+ ) {
+ this.stop(state)
+ }
+ }
+
+ /** Detach first: the link's death then reads as superseded, so recovery never restarts it. */
+ private stop(state: WslRelayDistroState): void {
+ const key = wslHookRelayStateKey(state.distro)
+ if (this.deps.isDisposed() || this.deps.states.get(key) !== state) {
+ return
+ }
+ const { mux, child } = state
+ state.mux = undefined
+ this.deps.states.delete(key)
+ this.parked.set(key, captureWslRelaySetup(state))
+ this.deps.clearRecoveryTimers(state)
+ mux?.dispose()
+ child?.kill()
+ this.deps.warn(`[agent-hooks] WSL hook relay for '${state.distro}' stopped: idle`)
+ }
+}
+
+/** The relay manager's idle-stop, listening to bridge terminals coming and going. */
+export function createWslRelayIdleStopForManager(manager: {
+ deps: () => WslHookRelayManagerDeps
+ states: Map
+ recovery: Pick
+ isDisposed: () => boolean
+}): WslRelayIdleStop {
+ const deps = manager.deps()
+ const idle = new WslRelayIdleStop({
+ idleMs: deps.idleStopMs,
+ states: manager.states,
+ livePtyCount: (distro) => manager.deps().bridgePtyPresence.count(distro),
+ daemonBridgeSessions: (distro) => manager.deps().daemonBridgeSessions(distro),
+ isDisposed: manager.isDisposed,
+ clearRecoveryTimers: (state) => manager.recovery.clearTimers(state),
+ warn: (message) => manager.deps().warn(message)
+ })
+ deps.bridgePtyPresence.onChange((key) => idle.presenceChanged(key))
+ return idle
+}
diff --git a/src/main/agent-hooks/wsl-hook-relay-link.ts b/src/main/agent-hooks/wsl-hook-relay-link.ts
index 0973adc1464..c556e5eb485 100644
--- a/src/main/agent-hooks/wsl-hook-relay-link.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-link.ts
@@ -10,6 +10,8 @@ export type WslRelayLinkOptions = {
child: ChildProcessWithoutNullStreams
distro: string
ingest: (envelope: Record, connectionId: string) => void
+ /** Runs before the link's first envelope: each link talks to a freshly started guest. */
+ beginSession?: (connectionId: string) => void
receiveClaudeAgentView?: (body: unknown) => unknown
bindInterruptReconciliation?: (
mux: SshChannelMultiplexer,
@@ -25,6 +27,7 @@ export function wireWslRelayLink(options: WslRelayLinkOptions): void {
const { mux, child, distro, ingest, warn, onDead } = options
const connectionId = wslHookRelayConnectionId(distro)
let dead = false
+ options.beginSession?.(connectionId)
mux.onRequest(CLAUDE_AGENT_VIEW_RELAY_METHOD, ({ body }) =>
dead ? {} : (options.receiveClaudeAgentView?.(body) ?? {})
)
diff --git a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts b/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
index fbcbabeecad..0b292cbe5ba 100644
--- a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
@@ -108,7 +108,10 @@ describe.skipIf(process.platform === 'win32')(
}
}),
warn: (message) => warns.push(message),
- transientRetryDelayMs: 1
+ transientRetryDelayMs: 1,
+ // A bridge terminal stays open, so no relay idles out mid-test.
+ bridgePtyPresence: { count: () => 1, onChange: () => () => {} },
+ daemonBridgeSessions: async () => 'none' as const
})
manager.ensureForDistro('LiveDistro', codexHome)
diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts
index 427594ed346..f068f8bed11 100644
--- a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts
@@ -253,6 +253,9 @@ describe('WslHookRelayManager', () => {
pluginSources: () => ({ opencodePluginSource: '// opencode plugin source' }),
warn: vi.fn(),
transientRetryDelayMs: 1,
+ // A bridge terminal stays open, so no relay idles out mid-test.
+ bridgePtyPresence: { count: () => 1, onChange: () => () => {} },
+ daemonBridgeSessions: async () => 'none' as const,
...overrides
}
return { manager: new WslHookRelayManager(deps), deps }
@@ -575,6 +578,80 @@ describe('WslHookRelayManager', () => {
manager.disposeAll()
})
+ // Memory and battery: once no bridge terminal is left, the relay alone held the distro and VM.
+ describe('idle stop', () => {
+ const presence = () => {
+ let live = 1
+ const listeners = new Set<(key: string) => void>()
+ return {
+ count: () => live,
+ onChange: (listener: (key: string) => void) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ set(count: number) {
+ live = count
+ listeners.forEach((listener) => listener('ubuntu'))
+ }
+ }
+ }
+
+ it('stops a relay idle past the window once no bridge terminal is left, without a restart', async () => {
+ const bridges = presence()
+ const kill = vi.fn()
+ const { manager, deps } = createManager({
+ bridgePtyPresence: bridges,
+ idleStopMs: 1_000,
+ spawnRelay: vi.fn(() => Object.assign(fakeChild(), { kill }))
+ })
+ manager.ensureForDistro('Ubuntu', codexHome)
+ await vi.waitFor(() => expect(manager.getGuestEndpointFilePath('Ubuntu')).not.toBeNull())
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ // An open terminal keeps it, however long.
+ await vi.advanceTimersByTimeAsync(60 * 60_000)
+ expect(kill).not.toHaveBeenCalled()
+
+ bridges.set(0)
+ await vi.advanceTimersByTimeAsync(999)
+ expect(kill).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ } finally {
+ vi.useRealTimers()
+ }
+ // The link's own teardown kills it again; harmless.
+ expect(kill).toHaveBeenCalled()
+ expect(manager.getGuestEndpointFilePath('Ubuntu')).toBeNull()
+ // Detached before the kill: its link's death schedules no restart, and nothing probes the distro.
+ await vi.waitFor(() =>
+ expect(deps.warn).toHaveBeenCalledWith(expect.stringContaining('stopped: idle'))
+ )
+ expect(deps.warn).not.toHaveBeenCalledWith(expect.stringContaining('scheduling restart'))
+ expect(deps.isDistroRunning).not.toHaveBeenCalled()
+ expect(deps.deferUntilRunning).not.toHaveBeenCalled()
+ expect(deps.spawnRelay).toHaveBeenCalledOnce()
+ manager.disposeAll()
+ })
+
+ it('starts again, with the config it served, on the next terminal or agent in the distro', async () => {
+ const bridges = presence()
+ bridges.set(0)
+ const { manager, deps } = createManager({ bridgePtyPresence: bridges, idleStopMs: 1 })
+ manager.ensureForDistro('Ubuntu', codexHome)
+ await vi.waitFor(() =>
+ expect(deps.warn).toHaveBeenCalledWith(expect.stringContaining('stopped: idle'))
+ )
+ vi.mocked(deps.installCodex).mockClear()
+ bridges.set(1)
+
+ manager.ensureForDistro('Ubuntu')
+ await vi.waitFor(() => expect(manager.getGuestEndpointFilePath('Ubuntu')).not.toBeNull())
+ expect(deps.spawnRelay).toHaveBeenCalledTimes(2)
+ expect(deps.installCodex).toHaveBeenCalledWith(codexHome, 'Ubuntu')
+ manager.disposeAll()
+ })
+ })
+
it('marks the distro failed when the relay exits and blocks an immediate re-ensure', async () => {
const children: ReturnType[] = []
const spawnRelay = vi.fn(() => {
diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-hook-relay-manager.ts
index dad34d49048..51a2ae3d2dc 100644
--- a/src/main/agent-hooks/wsl-hook-relay-manager.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-manager.ts
@@ -35,9 +35,11 @@ import {
resumeWslStoppedRelays
} from './wsl-hook-relay-state-machine'
import type { WslRelayDistroState } from './wsl-hook-relay-state'
+import { createWslRelayIdleStopForManager, type WslRelayIdleStop } from './wsl-hook-relay-idle-stop'
export class WslHookRelayManager {
private deps: WslHookRelayManagerDeps
private recovery: WslRelayRecovery
+ private idle: WslRelayIdleStop
private states = new Map()
private stoppedByHooksOff = new Map()
private defaultDistro: string | null = null
@@ -45,12 +47,12 @@ export class WslHookRelayManager {
private warnedBundleMissing = false
constructor(deps: Partial = {}) {
this.deps = { ...defaultWslHookRelayDeps, ...deps }
+ const owner = { deps: () => this.deps, states: this.states, isDisposed: () => this.disposed }
this.recovery = createWslRelayRecoveryForManager({
- deps: () => this.deps,
- states: this.states,
- isDisposed: () => this.disposed,
+ ...owner,
ensure: (...args) => this.ensureForDistro(...args)
})
+ this.idle = createWslRelayIdleStopForManager({ ...owner, recovery: this.recovery })
}
setManagedHookSettingsResolver(resolve: WslHookRelayManagerDeps['managedHookSettings']): void {
this.deps.managedHookSettings = resolve
@@ -98,6 +100,7 @@ export class WslHookRelayManager {
/** Nonpermanent disposal allows relays to restart when hooks are re-enabled. */
disposeAll({ permanent = true }: { permanent?: boolean } = {}): void {
this.disposed ||= permanent
+ this.idle.dispose(permanent)
for (const state of this.states.values()) {
this.recovery.clearTimers(state)
state.mux?.dispose()
@@ -124,6 +127,7 @@ export class WslHookRelayManager {
return
}
const key = wslHookRelayStateKey(distro)
+ this.idle.restoreParked(distro)
const existing = this.states.get(key)
if (requestedCodexHomePath) {
recordManagedWslCodexHome(distro, requestedCodexHomePath)
@@ -228,7 +232,8 @@ export class WslHookRelayManager {
mux,
child,
distro: state.distro,
- ingest: this.deps.ingest,
+ ingest: this.idle.noteTraffic(state, this.deps.ingest),
+ beginSession: this.deps.beginRelaySession,
receiveClaudeAgentView: (body) =>
isWslHookRelayAllowed(this.deps) ? (this.deps.receiveClaudeAgentView?.(body) ?? {}) : {},
warn: this.deps.warn,
@@ -272,6 +277,7 @@ export class WslHookRelayManager {
}
state.phase = 'running'
state.connectedAt = Date.now()
+ this.idle.update(state)
this.recovery.scheduleOneShotReinstall(state, REINSTALL_ONE_SHOT_DELAY_MS, () => {
void maybeRerunWslRelayGuestInstall(this.deps, state)
})
diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts b/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts
index 9a041382562..125f523c508 100644
--- a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts
@@ -92,10 +92,40 @@ describe('WslRelayRecovery', () => {
expect(restart).not.toHaveBeenCalled()
expect(deferred).toHaveLength(1)
// Something else (the user) started the distro: only now does the relay come back.
+ isDistroRunning.mockResolvedValue(true)
deferred[0]()
+ await waitFor(() => restart.mock.calls.length === 1)
expect(restart).toHaveBeenCalledExactlyOnceWith('Ubuntu', { launchKinds: [] })
})
+ it('re-reads a settled list before a drained restart, and waits again if the distro stopped', async () => {
+ const restart = vi.fn()
+ const deferred: (() => void)[] = []
+ const isDistroRunning = vi.fn(async (_distro: string, _startedAfter: number) => false)
+ const recovery = new WslRelayRecovery({
+ isDistroRunning,
+ deferUntilRunning: (_distro, task) => deferred.push(task),
+ captureSetup: () => ({ launchKinds: [] }),
+ warn: vi.fn(),
+ isDisposed: () => false,
+ isCurrent: () => true,
+ restart,
+ dropState: vi.fn()
+ })
+ recovery.scheduleRestart(makeState())
+ await vi.advanceTimersByTimeAsync(250)
+ await waitFor(() => deferred.length === 1)
+
+ // Drained by a list that still named the stopping distro; a fresh settled read says stopped.
+ deferred[0]()
+ await waitFor(() => deferred.length === 2)
+ expect(restart).not.toHaveBeenCalled()
+
+ isDistroRunning.mockResolvedValue(true)
+ deferred[1]()
+ await waitFor(() => restart.mock.calls.length === 1)
+ })
+
it('restarts with the relay config captured before dropState discarded it', async () => {
const restart = vi.fn()
const deferred: (() => void)[] = []
@@ -105,8 +135,9 @@ describe('WslRelayRecovery', () => {
launchKinds: ['pi', 'omp']
}
const expected = live
+ const isDistroRunning = vi.fn(async (_distro: string, _startedAfter: number) => false)
const recovery = new WslRelayRecovery({
- isDistroRunning: async () => false,
+ isDistroRunning,
deferUntilRunning: (_distro, task) => deferred.push(task),
captureSetup: () => live ?? { launchKinds: [] },
warn: vi.fn(),
@@ -120,7 +151,9 @@ describe('WslRelayRecovery', () => {
recovery.scheduleRestart(makeState())
await vi.advanceTimersByTimeAsync(250)
await waitFor(() => deferred.length === 1)
+ isDistroRunning.mockResolvedValue(true)
deferred[0]()
+ await waitFor(() => restart.mock.calls.length === 1)
expect(restart).toHaveBeenCalledExactlyOnceWith('Ubuntu', expected)
})
diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.ts b/src/main/agent-hooks/wsl-hook-relay-recovery.ts
index ec8d9a36e90..c535b5aeda6 100644
--- a/src/main/agent-hooks/wsl-hook-relay-recovery.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-recovery.ts
@@ -81,17 +81,33 @@ export class WslRelayRecovery {
this.io.dropState(state)
// E9: come back when the distro runs again (started by the user or another act), never boot it.
let restarted = false
- const restartOnce = (): void => {
- if (!restarted && !this.io.isDisposed()) {
- restarted = true
- this.io.restart(state.distro, setup)
+ const restartOnce = (confirmedRunning = false): void => {
+ if (restarted || this.io.isDisposed()) {
+ return
}
+ restarted = true
+ // A drained deferral is a hint: the relay spawn runs wsl.exe, which boots a distro that
+ // stopped again, so re-read a settled running list right before it.
+ const running = confirmedRunning
+ ? Promise.resolve(true)
+ : this.io.isDistroRunning(state.distro, performance.now()).catch(() => false)
+ void running.then((running) => {
+ if (this.io.isDisposed()) {
+ return
+ }
+ if (running) {
+ this.io.restart(state.distro, setup)
+ return
+ }
+ restarted = false
+ this.io.deferUntilRunning(state.distro, () => restartOnce())
+ })
}
- this.io.deferUntilRunning(state.distro, restartOnce)
+ this.io.deferUntilRunning(state.distro, () => restartOnce())
const reprobe = setTimeout(() => {
void this.io
.isDistroRunning(state.distro, performance.now())
- .then((running) => running && restartOnce())
+ .then((running) => running && restartOnce(true))
.catch(() => {})
}, REPROBE_AFTER_STOPPED_MS)
reprobe.unref?.()
diff --git a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts b/src/main/agent-hooks/wsl-hook-relay-state-machine.ts
index 44d70fe0fa1..971be46a1d2 100644
--- a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts
+++ b/src/main/agent-hooks/wsl-hook-relay-state-machine.ts
@@ -97,6 +97,21 @@ export function captureWslRelaySetup(state: WslRelayDistroState): WslRelayRestar
}
}
+/** A cooled-down failed state: ensure replaces it with a starting relay that inherits its config. */
+export function seedWslRelayState(
+ distro: string,
+ setup: WslRelayRestartSetup
+): WslRelayDistroState {
+ return {
+ distro,
+ ...setup,
+ launchKinds: new Set(setup.launchKinds),
+ phase: 'failed',
+ failures: 0,
+ cooldownUntil: 0
+ }
+}
+
/** Brings a relay back with everything it served before, even after its state was dropped. */
export async function restartWslRelay(
states: Map,
@@ -107,15 +122,7 @@ export async function restartWslRelay(
const key = wslHookRelayStateKey(distro)
let seed: WslRelayDistroState | undefined
if (!states.has(key)) {
- // A cooled-down failed state: ensure replaces it with a starting relay that inherits its config.
- seed = {
- distro,
- ...setup,
- launchKinds: new Set(setup.launchKinds),
- phase: 'failed',
- failures: 0,
- cooldownUntil: 0
- }
+ seed = seedWslRelayState(distro, setup)
states.set(key, seed)
}
// No Codex home argument: ensure keeps the seed's, and never overwrites a newer relay's.
diff --git a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts b/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts
index 2c04fd5b153..f2ff4355e5e 100644
--- a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts
+++ b/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts
@@ -155,7 +155,10 @@ describe.skipIf(process.platform === 'win32')('WSL public-manager settings lifet
managedHookSettings: () => settings,
pluginSources: () => sources,
warn: vi.fn(),
- transientRetryDelayMs: 1
+ transientRetryDelayMs: 1,
+ // A bridge terminal stays open, so no relay idles out mid-test.
+ bridgePtyPresence: { count: () => 1, onChange: () => () => {} },
+ daemonBridgeSessions: async () => 'none' as const
})
})
afterEach(() => {
diff --git a/src/main/ai-vault-search/session-search-agent-compatibility.test.ts b/src/main/ai-vault-search/session-search-agent-compatibility.test.ts
index a0458abd94e..3b91b9d239b 100644
--- a/src/main/ai-vault-search/session-search-agent-compatibility.test.ts
+++ b/src/main/ai-vault-search/session-search-agent-compatibility.test.ts
@@ -161,7 +161,7 @@ test('projects agents before cursor identity and preserves every other ranking f
filters: {
agents: ['codex', 'jcode'] as const,
scopePaths: ['/host/folder'],
- since: '2026-08-01T00:00:00Z',
+ since: '2026-08-01T00:00:00.000Z',
sort: 'newest' as const
}
}
diff --git a/src/main/ai-vault-search/session-search-engine.test.ts b/src/main/ai-vault-search/session-search-engine.test.ts
index 997bf4f5ca6..d8e9218605a 100644
--- a/src/main/ai-vault-search/session-search-engine.test.ts
+++ b/src/main/ai-vault-search/session-search-engine.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it } from 'vitest'
+import { AiVaultSearchRequestSchema } from '../../shared/ai-vault-search-contract'
import { SESSION_SEARCH_QUERY_MAX_LENGTH } from './session-search-engine-types'
import type { SessionSearchRequest, SessionSearchResponse } from './session-search-engine-types'
import { planSessionSearchQuery } from './session-search-query-planner'
@@ -243,6 +244,16 @@ describe('filters narrow retrieval, not just the page', () => {
ids(engine.search({ query: 'resolveTerminalPath', filters: { scopePaths: ['/target'] } }))
).toEqual(['2'])
})
+
+ it('reads a sub-millisecond `since` as the instant it names, whatever its offset', async () => {
+ const { db, engine } = await open('ss-engine-since-sub-ms')
+ addSyntheticSession(db, { id: 1, text: 'needle', updatedAt: '2026-01-01T08:00:00.000Z' })
+ addSyntheticSession(db, { id: 2, text: 'needle', updatedAt: '2026-01-01T08:00:00.001Z' })
+ for (const since of ['2026-01-01T10:00:00.0005+02:00', '2026-01-01T08:00:00.0005Z']) {
+ const { filters } = AiVaultSearchRequestSchema.parse({ query: 'needle', filters: { since } })
+ expect(ids(engine.search({ query: 'needle', filters }))).toEqual(['2'])
+ }
+ })
})
describe('evidence', () => {
diff --git a/src/main/ai-vault/cached-session-list.test.ts b/src/main/ai-vault/cached-session-list.test.ts
index 92ec1422dd9..a5b3f0c907f 100644
--- a/src/main/ai-vault/cached-session-list.test.ts
+++ b/src/main/ai-vault/cached-session-list.test.ts
@@ -3,6 +3,12 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AiVaultListResult, AiVaultSession } from '../../shared/ai-vault-types'
+import { aiVaultLocalScanKey } from '../../shared/ai-vault-local-scan-key'
+import {
+ localAiVaultScanProgress,
+ resetLocalAiVaultScanProgressForTests,
+ type LocalAiVaultScanProgressHandle
+} from './ai-vault-local-scan-progress'
const {
filterPathsToRunningWslDistrosAsync,
@@ -44,10 +50,15 @@ function scanResult(scannedAt: string): AiVaultListResult {
function deferredScan(): { resolve: (value: AiVaultListResult) => void } {
let resolveFn: (value: AiVaultListResult) => void = () => {}
- scanAiVaultSessionsInService.mockReturnValueOnce(
- new Promise((resolve) => {
- resolveFn = resolve
- })
+ const pending = new Promise((resolve) => {
+ resolveFn = resolve
+ })
+ scanAiVaultSessionsInService.mockImplementationOnce(
+ async (_options, _signal, progress?: LocalAiVaultScanProgressHandle) => {
+ const value = await pending
+ progress?.finish(null)
+ return value
+ }
)
return { resolve: resolveFn }
}
@@ -57,6 +68,7 @@ describe('invalidateAiVaultSessionListCache generation guard', () => {
platform = 'win32'
vi.spyOn(process, 'platform', 'get').mockImplementation(() => platform)
resetAiVaultSessionListCacheForTests()
+ resetLocalAiVaultScanProgressForTests()
filterPathsToRunningWslDistrosAsync.mockClear()
getCachedWslDistros.mockReset().mockReturnValue(null)
hasCachedWslDistros.mockReset().mockReturnValue(false)
@@ -65,6 +77,7 @@ describe('invalidateAiVaultSessionListCache generation guard', () => {
})
afterEach(() => {
resetAiVaultSessionListCacheForTests()
+ resetLocalAiVaultScanProgressForTests()
vi.restoreAllMocks()
})
@@ -84,6 +97,51 @@ describe('invalidateAiVaultSessionListCache generation guard', () => {
expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(2)
})
+ it.each(['old-first', 'new-first'])(
+ 'keeps post-invalidation scans separate with %s completion',
+ async (order) => {
+ const request = { scopePaths: ['/project'] }
+ const scanKey = aiVaultLocalScanKey(request)
+ const scanA = deferredScan()
+ const beforeDelete = listAiVaultSessions(request)
+ await vi.waitFor(() => expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(1))
+
+ invalidateAiVaultSessionListCache()
+ const scanB = deferredScan()
+ const afterDelete = listAiVaultSessions(request)
+ const sameGeneration = listAiVaultSessions(request)
+ try {
+ await vi.waitFor(() => expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(2))
+ if (order === 'old-first') {
+ scanA.resolve(scanResult('scan-A'))
+ await beforeDelete
+ }
+ scanB.resolve(scanResult('scan-B'))
+ const fresh = await afterDelete
+ expect(fresh.scannedAt).toBe('scan-B')
+ expect(fresh.scanId).toEqual(expect.any(String))
+ expect((await sameGeneration).scanId).toBe(fresh.scanId)
+
+ scanA.resolve(scanResult('scan-A'))
+ const old = await beforeDelete
+ expect(old.scannedAt).toBe('scan-A')
+ expect(old.scanId).not.toBe(fresh.scanId)
+ const cached = await listAiVaultSessions(request)
+ expect(cached.scannedAt).toBe('scan-B')
+ expect(cached.scanId).toBe(fresh.scanId)
+ expect(localAiVaultScanProgress(scanKey)).toMatchObject({
+ scanId: fresh.scanId,
+ stage: 'finished'
+ })
+ expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(2)
+ } finally {
+ scanA.resolve(scanResult('scan-A'))
+ scanB.resolve(scanResult('scan-B'))
+ await Promise.allSettled([beforeDelete, afterDelete, sameGeneration])
+ }
+ }
+ )
+
it('caches normally when no invalidation interrupts the scan', async () => {
scanAiVaultSessionsInService.mockResolvedValueOnce(scanResult('scan-A'))
const request = { limit: 1000, scopePaths: ['/project'] }
diff --git a/src/main/ai-vault/cached-session-list.ts b/src/main/ai-vault/cached-session-list.ts
index 90751e31931..e1ac800f5b8 100644
--- a/src/main/ai-vault/cached-session-list.ts
+++ b/src/main/ai-vault/cached-session-list.ts
@@ -122,7 +122,8 @@ export async function listAiVaultSessions(
const startGeneration = cacheGeneration
let progress: LocalAiVaultScanProgressHandle | null = null
return scanCoordinator.run({
- key: scanKey,
+ // Isolate invalidated scans without changing the key used by progress readers.
+ key: JSON.stringify({ scanKey, generation: startGeneration }),
force: args?.force,
signal: options.signal,
onCreate: (scanId) => {
@@ -183,6 +184,10 @@ export async function getAiVaultWslHomeDirs(): Promise {
return listRunningWslHomeDirsAsync()
}
+export function aiVaultSessionListCacheGeneration(): number {
+ return cacheGeneration
+}
+
// Invalidate cached results and disarm in-flight cache writes after deletion.
export function invalidateAiVaultSessionListCache(): void {
cacheGeneration++
diff --git a/src/main/bitbucket/repository-ref.ts b/src/main/bitbucket/repository-ref.ts
index 8a0c35ff986..0dc70b2d73a 100644
--- a/src/main/bitbucket/repository-ref.ts
+++ b/src/main/bitbucket/repository-ref.ts
@@ -1,3 +1,4 @@
+import { normalizeBitbucketRemoteHost } from '../../shared/git-remote-host-alias'
import { createRemoteRefProbeCache } from '../git/remote-ref-probe-cache'
export type BitbucketRepoRef = {
@@ -58,8 +59,7 @@ export function parseBitbucketRepoRef(remoteUrl: string): BitbucketRepoRef | nul
try {
const url = new URL(trimmed)
- const host = url.hostname.toLowerCase()
- if (host !== 'bitbucket.org' && host !== 'ssh.bitbucket.org') {
+ if (normalizeBitbucketRemoteHost(url.hostname) !== 'bitbucket.org') {
return null
}
return parseBitbucketPath(url.pathname)
diff --git a/src/main/browser/agent-browser-bridge-capture-paint-hold.test.ts b/src/main/browser/agent-browser-bridge-capture-paint-hold.test.ts
index 4fd504a1418..c26f5c1b4cf 100644
--- a/src/main/browser/agent-browser-bridge-capture-paint-hold.test.ts
+++ b/src/main/browser/agent-browser-bridge-capture-paint-hold.test.ts
@@ -81,11 +81,17 @@ describe('AgentBrowserBridge', () => {
bridge.setActiveTab(100)
})
- it('never holds paint for commands that do not capture pixels', async () => {
+ it('holds only the guest, never paint, for commands that do not capture pixels', async () => {
+ const releases: ReturnType[] = []
+ const holdGuestActive = vi.fn(() => {
+ const release = vi.fn()
+ releases.push(release)
+ return release
+ })
const holdPaintForCapture = vi.fn(() => () => {})
const printToPDF = vi.fn(async () => Buffer.from('pdf'))
const b = new AgentBrowserBridge(
- mockBrowserManager(undefined, undefined, { holdPaintForCapture })
+ mockBrowserManager(undefined, undefined, { holdGuestActive, holdPaintForCapture })
)
b.setActiveTab(100)
webContentsFromIdMock.mockReturnValue({ ...mockWebContents(100), printToPDF })
@@ -98,6 +104,87 @@ describe('AgentBrowserBridge', () => {
await expect(b.pdf()).resolves.toEqual({ data: Buffer.from('pdf').toString('base64') })
expect(holdPaintForCapture).not.toHaveBeenCalled()
+ expect(holdGuestActive.mock.calls).toEqual([[100], [100], [100], [100], [100]])
+ expect(releases.map((release) => release.mock.calls.length)).toEqual([1, 1, 1, 1, 1])
+ })
+
+ it('holds only executing commands and resolves a queued command against the replacement guest', async () => {
+ const tabs = new Map([['tab-1', 100]])
+ const holds: number[] = []
+ const released: number[] = []
+ const b = new AgentBrowserBridge(
+ mockBrowserManager(tabs, undefined, {
+ holdGuestActive: (id) => {
+ holds.push(id)
+ return () => released.push(id)
+ }
+ })
+ )
+ const oldGuest = mockWebContents(100)
+ const replacement = mockWebContents(200)
+ let finish = (_value: unknown): void => {}
+ oldGuest.debugger.sendCommand.mockImplementation(
+ () => new Promise((resolve) => (finish = resolve))
+ )
+ replacement.debugger.sendCommand.mockResolvedValue({ result: { value: 'replacement' } })
+ webContentsFromIdMock.mockImplementation((id: number) => (id === 100 ? oldGuest : replacement))
+ b.setActiveTab(100)
+
+ const first = b.evaluate('first', undefined, 'tab-1')
+ const firstResult = expect(first).rejects.toMatchObject({ code: 'browser_tab_changed' })
+ const second = b.evaluate('second', undefined, 'tab-1')
+ const holdsWhileQueued = [...holds]
+ expect(released).toEqual([])
+ tabs.set('tab-1', 200)
+ finish({ result: { value: 'old' } })
+
+ await firstResult
+ await expect(second).resolves.toMatchObject({ result: 'replacement' })
+ expect(holdsWhileQueued).toEqual([100])
+ expect(holds).toEqual([100, 200])
+ expect(released).toEqual([100, 200])
+ })
+
+ it('drops queued commands without acquiring the guest and holds running work until it settles', async () => {
+ const release = vi.fn()
+ const holdGuestActive = vi.fn(() => release)
+ const b = new AgentBrowserBridge(mockBrowserManager(undefined, undefined, { holdGuestActive }))
+ b.setActiveTab(100)
+ const guest = mockWebContents(100)
+ let finish = (_value: unknown): void => {}
+ guest.debugger.sendCommand.mockImplementation(
+ () => new Promise((resolve) => (finish = resolve))
+ )
+ webContentsFromIdMock.mockReturnValue(guest)
+
+ const running = b.evaluate('first')
+ const queued = b.evaluate('second')
+ const queuedResult = expect(queued).rejects.toMatchObject({ code: 'browser_tab_closed' })
+ await b.onPageClosed('tab-1')
+ await queuedResult
+ expect(holdGuestActive.mock.calls).toEqual([[100]])
+ expect(release).not.toHaveBeenCalled()
+
+ finish({ result: { value: 'finished' } })
+ await running
+ expect(release).toHaveBeenCalledTimes(1)
+ })
+
+ it('releases the background hold when session setup fails', async () => {
+ const release = vi.fn()
+ const holdGuestActive = vi.fn(() => release)
+ const b = new AgentBrowserBridge(mockBrowserManager(undefined, undefined, { holdGuestActive }))
+ b.setActiveTab(100)
+ CdpWsProxyMock.mockImplementationOnce(function (this: Record) {
+ this.start = vi.fn(async () => {
+ throw new Error('cannot start proxy')
+ })
+ })
+ succeedWith(null)
+
+ await expect(b.snapshot()).rejects.toThrow('cannot start proxy')
+ expect(holdGuestActive).toHaveBeenCalledWith(100)
+ expect(release).toHaveBeenCalledTimes(1)
})
it('captures full-page screenshots directly through CDP using CSS layout bounds', async () => {
diff --git a/src/main/browser/agent-browser-bridge-queue.ts b/src/main/browser/agent-browser-bridge-queue.ts
index a4cfac92e92..1a550067ebd 100644
--- a/src/main/browser/agent-browser-bridge-queue.ts
+++ b/src/main/browser/agent-browser-bridge-queue.ts
@@ -120,10 +120,15 @@ export abstract class AgentBrowserBridgeQueue extends AgentBrowserBridgeShutdown
const sessionName = `${ORCA_TAB_SESSION_PREFIX}${browserPageId}`
// A queued page may acquire a replacement guest before execution.
const target = this.resolveCommandTarget(worktreeId, browserPageId)
- if (options.ensureSession !== false) {
- await this.ensureSession(sessionName, browserPageId, target.webContentsId)
+ const releaseGuest = this.browserManager.holdGuestActive(target.webContentsId)
+ try {
+ if (options.ensureSession !== false) {
+ await this.ensureSession(sessionName, browserPageId, target.webContentsId)
+ }
+ return await execute(sessionName, target)
+ } finally {
+ releaseGuest()
}
- return execute(sessionName, target)
}
/** Revocation must stop every later step of a host command. */
diff --git a/src/main/browser/agent-browser-bridge-session-lifecycle.test.ts b/src/main/browser/agent-browser-bridge-session-lifecycle.test.ts
index 88bb6f4b8c7..1eee2a3fc01 100644
--- a/src/main/browser/agent-browser-bridge-session-lifecycle.test.ts
+++ b/src/main/browser/agent-browser-bridge-session-lifecycle.test.ts
@@ -254,8 +254,14 @@ describe('AgentBrowserBridge', () => {
})
it('cancels the command already running when a session is destroyed', async () => {
+ const releasePaint = vi.fn()
+ bridge = new AgentBrowserBridge(
+ mockBrowserManager(undefined, undefined, { holdGuestActive: () => releasePaint })
+ )
+ bridge.setActiveTab(100)
succeedWith({ snapshot: 'initial' })
await bridge.snapshot()
+ releasePaint.mockClear()
execFileMock.mockClear()
@@ -290,6 +296,7 @@ describe('AgentBrowserBridge', () => {
message: 'Tab was closed while command was running'
})
await destroyPromise
+ expect(releasePaint).toHaveBeenCalledTimes(1)
})
it('destroys session on process swap and re-inits with --cdp', async () => {
diff --git a/src/main/browser/agent-browser-bridge-test-harness.ts b/src/main/browser/agent-browser-bridge-test-harness.ts
index 0f044d1dfd9..b1f91098095 100644
--- a/src/main/browser/agent-browser-bridge-test-harness.ts
+++ b/src/main/browser/agent-browser-bridge-test-harness.ts
@@ -35,6 +35,8 @@ export function mockBrowserManager(
getBrowserPageLoadError: vi.fn(() => null),
getBrowserPageCertificateFailure: vi.fn(() => null),
unregisterGuest: vi.fn(),
+ holdPaintForCapture: () => () => {},
+ holdGuestActive: () => () => {},
beginAgentCommand: () => ({
run: (execute: () => Promise) => execute(),
end: () => {}
diff --git a/src/main/browser/browser-client-host-command-dispatcher.ts b/src/main/browser/browser-client-host-command-dispatcher.ts
index 54140ff9585..d6fbc4b7199 100644
--- a/src/main/browser/browser-client-host-command-dispatcher.ts
+++ b/src/main/browser/browser-client-host-command-dispatcher.ts
@@ -63,10 +63,7 @@ export class BrowserClientHostCommandDispatcher {
this.maxActiveCommands = limits.maxActiveCommands
this.maxConcurrentHandlers = limits.maxConcurrentHandlers
this.maxQueuedCommandsPerPage = limits.maxQueuedCommandsPerPage
- this.resultCache = new BrowserClientHostCommandResultCache(
- limits.maxCachedResultsPerPage,
- limits.maxCachedCommandResults
- )
+ this.resultCache = new BrowserClientHostCommandResultCache(limits)
this.joinTimeoutMs = limits.joinTimeoutMs
this.closedSettlement = new Promise((resolve) => {
this.resolveClosedSettlement = resolve
diff --git a/src/main/browser/browser-client-host-command-result-cache.ts b/src/main/browser/browser-client-host-command-result-cache.ts
index 59c6430244c..929897aaf3c 100644
--- a/src/main/browser/browser-client-host-command-result-cache.ts
+++ b/src/main/browser/browser-client-host-command-result-cache.ts
@@ -1,11 +1,23 @@
-import type { CommandRecord, PageState } from './browser-client-host-command-state'
+import type {
+ CommandRecord,
+ DispatcherLimits,
+ PageState
+} from './browser-client-host-command-state'
+import { browserCommandCacheBytes } from './browser-command-cache-bytes'
export class BrowserClientHostCommandResultCache {
- private readonly pagesByRecord = new Map()
+ private readonly pagesByRecord = new Map()
+ private bytesByPage = new WeakMap()
+ private bytes = 0
constructor(
- private readonly maxPerPage: number,
- private readonly maxTotal: number
+ private readonly limits: Pick<
+ DispatcherLimits,
+ | 'maxCachedResultsPerPage'
+ | 'maxCachedCommandResults'
+ | 'maxCachedResultBytes'
+ | 'maxCachedResultBytesPerPage'
+ >
) {}
record(page: PageState, record: CommandRecord, retain = true): void {
@@ -13,18 +25,35 @@ export class BrowserClientHostCommandResultCache {
this.evict(page, record.event.commandSequence, record)
return
}
+ const bytes = browserCommandCacheBytes(record.event, record.result)
+ if (
+ bytes === null ||
+ bytes > this.limits.maxCachedResultBytes ||
+ bytes > this.limits.maxCachedResultBytesPerPage
+ ) {
+ this.evict(page, record.event.commandSequence, record)
+ return
+ }
page.settledSequences.push(record.event.commandSequence)
- this.pagesByRecord.set(record, page)
- while (page.settledSequences.length > this.maxPerPage) {
+ this.pagesByRecord.set(record, { page, bytes })
+ this.bytesByPage.set(page, (this.bytesByPage.get(page) ?? 0) + bytes)
+ this.bytes += bytes
+ while (
+ page.settledSequences.length > this.limits.maxCachedResultsPerPage ||
+ (this.bytesByPage.get(page) ?? 0) > this.limits.maxCachedResultBytesPerPage
+ ) {
const sequence = page.settledSequences[0]
this.evict(page, sequence)
}
- while (this.pagesByRecord.size > this.maxTotal) {
+ while (
+ this.pagesByRecord.size > this.limits.maxCachedCommandResults ||
+ this.bytes > this.limits.maxCachedResultBytes
+ ) {
const entry = this.pagesByRecord.entries().next().value
if (!entry) {
break
}
- const [oldestRecord, oldestPage] = entry
+ const [oldestRecord, { page: oldestPage }] = entry
this.evict(oldestPage, oldestRecord.event.commandSequence, oldestRecord)
}
}
@@ -37,6 +66,8 @@ export class BrowserClientHostCommandResultCache {
clear(): void {
this.pagesByRecord.clear()
+ this.bytesByPage = new WeakMap()
+ this.bytes = 0
}
private evict(page: PageState, sequence: number, expected?: CommandRecord): void {
@@ -46,7 +77,12 @@ export class BrowserClientHostCommandResultCache {
}
page.records.delete(sequence)
page.sequencesByCommandId.delete(cached.event.commandId)
- this.pagesByRecord.delete(cached)
+ const retained = this.pagesByRecord.get(cached)
+ if (retained) {
+ this.bytes -= retained.bytes
+ this.bytesByPage.set(page, (this.bytesByPage.get(page) ?? 0) - retained.bytes)
+ this.pagesByRecord.delete(cached)
+ }
const sequenceIndex = page.settledSequences.indexOf(sequence)
if (sequenceIndex !== -1) {
page.settledSequences.splice(sequenceIndex, 1)
diff --git a/src/main/browser/browser-client-host-command-state.ts b/src/main/browser/browser-client-host-command-state.ts
index a1927264d36..24f487edbb5 100644
--- a/src/main/browser/browser-client-host-command-state.ts
+++ b/src/main/browser/browser-client-host-command-state.ts
@@ -4,6 +4,11 @@ import type {
BrowserClientHostLeaseAuthority
} from '../../shared/browser-client-host-protocol'
+import {
+ BROWSER_COMMAND_CACHE_MAX_BYTES,
+ BROWSER_COMMAND_CACHE_MAX_BYTES_PER_PAGE
+} from './browser-command-cache-bytes'
+
export const DEFAULT_MAX_PAGES = 256
export const DEFAULT_MAX_ACTIVE_COMMANDS = 256
export const DEFAULT_MAX_CONCURRENT_HANDLERS = 8
@@ -52,6 +57,8 @@ export type DispatcherOptions = {
maxQueuedCommandsPerPage?: number
maxCachedResultsPerPage?: number
maxCachedCommandResults?: number
+ maxCachedResultBytes?: number
+ maxCachedResultBytesPerPage?: number
joinTimeoutMs?: number
}
@@ -62,6 +69,8 @@ export type DispatcherLimits = {
maxQueuedCommandsPerPage: number
maxCachedResultsPerPage: number
maxCachedCommandResults: number
+ maxCachedResultBytes: number
+ maxCachedResultBytesPerPage: number
joinTimeoutMs: number
}
@@ -85,6 +94,14 @@ export function resolveDispatcherLimits(options: DispatcherOptions): DispatcherL
options.maxCachedCommandResults,
DEFAULT_MAX_CACHED_COMMAND_RESULTS
),
+ maxCachedResultBytes: positiveCommandLimit(
+ options.maxCachedResultBytes,
+ BROWSER_COMMAND_CACHE_MAX_BYTES
+ ),
+ maxCachedResultBytesPerPage: positiveCommandLimit(
+ options.maxCachedResultBytesPerPage,
+ BROWSER_COMMAND_CACHE_MAX_BYTES_PER_PAGE
+ ),
joinTimeoutMs: positiveCommandLimit(options.joinTimeoutMs, DEFAULT_JOIN_TIMEOUT_MS)
}
}
diff --git a/src/main/browser/browser-client-page-creation-cancellation.test.ts b/src/main/browser/browser-client-page-creation-cancellation.test.ts
new file mode 100644
index 00000000000..82487d35612
--- /dev/null
+++ b/src/main/browser/browser-client-page-creation-cancellation.test.ts
@@ -0,0 +1,87 @@
+import { expect, it, vi } from 'vitest'
+import { createReservedBrowserClientPage } from './browser-client-page-creation'
+import {
+ createCommand,
+ createHarness,
+ createLifecycleClaim
+} from './browser-client-page-command-executor-test-harness'
+import {
+ completeRendererMount,
+ createRendererBridgeTestRig,
+ sentRendererRequest
+} from './browser-client-page-renderer-bridge-test-rig'
+
+it('claims a canceled mount reply and withholds release until exact native destruction', async () => {
+ const { dependencies, order, route, routeSession } = createHarness()
+ const rig = createRendererBridgeTestRig()
+ const renderer = rig.registry.attachRenderer(rig.endpoint)
+ const controller = new AbortController()
+ const commit = vi.fn()
+ const { promise: destroyed, resolve: acknowledgeDestroyed } = Promise.withResolvers()
+ const { promise: retiring, resolve: acknowledgeRetiring } = Promise.withResolvers()
+ dependencies.routeWebContents.claimGuestLifecycle.mockImplementationOnce((registration) => {
+ order.push('claim-guest')
+ return createLifecycleClaim(registration, destroyed)
+ })
+ dependencies.routeWebContents.beginGuestRetirement.mockImplementationOnce(() => {
+ order.push('retire-guest')
+ return Promise.resolve()
+ })
+ vi.mocked(rig.endpoint.send).mockImplementation(() => {
+ const request = sentRendererRequest(rig.endpoint)
+ if (request.type === 'mountPage') {
+ order.push('mount-page')
+ controller.abort()
+ completeRendererMount(rig, rig.endpoint, 92)
+ } else if (request.type === 'retirePage') {
+ order.push('retire-renderer-page')
+ rig.reply(rig.endpoint, {
+ type: 'retired',
+ requestId: request.requestId,
+ page: request.page
+ })
+ acknowledgeRetiring()
+ }
+ })
+
+ const creation = createReservedBrowserClientPage(
+ {
+ ...dependencies,
+ selectRenderer: () => renderer,
+ retireSupersededExecutionHostPages: async () => {}
+ },
+ createCommand('createPage'),
+ controller.signal,
+ () => {},
+ commit
+ )
+ const creationResult = creation.catch((error: unknown) => error)
+
+ await retiring
+ expect(order).toEqual([
+ 'retain-route',
+ 'prepare-page',
+ 'mount-page',
+ 'claim-guest',
+ 'retire-guest',
+ 'retire-renderer-page'
+ ])
+ expect(dependencies.routeWebContents.claimGuestLifecycle).toHaveBeenCalledWith({
+ ...sentRendererRequest(rig.endpoint).page,
+ rendererWebContentsId: rig.endpoint.id,
+ webContentsId: 92
+ })
+ expect(routeSession.release).not.toHaveBeenCalled()
+ expect(route.release).not.toHaveBeenCalled()
+ expect(dependencies.routeWebContents.registerGuest).not.toHaveBeenCalled()
+ expect(dependencies.routeWebContents.grantNavigation).not.toHaveBeenCalled()
+ expect(commit).not.toHaveBeenCalled()
+
+ acknowledgeDestroyed()
+ await expect(creationResult).resolves.toHaveProperty(
+ 'message',
+ 'browser_client_page_command_aborted'
+ )
+ expect(order.slice(-2)).toEqual(['release-session', 'release-route'])
+ rig.registry.dispose()
+})
diff --git a/src/main/browser/browser-client-page-renderer-bridge.test.ts b/src/main/browser/browser-client-page-renderer-bridge.test.ts
index bce4d98e656..211c337141f 100644
--- a/src/main/browser/browser-client-page-renderer-bridge.test.ts
+++ b/src/main/browser/browser-client-page-renderer-bridge.test.ts
@@ -128,27 +128,58 @@ describe('BrowserClientPageRendererBridgeRegistry', () => {
it('fences a pending generation when an exact renderer is replaced with a reused ID', async () => {
const harness = createHarness()
const first = harness.registry.attachRenderer(harness.endpoint)
- const pending = first.mountPage(page, new AbortController().signal)
+ const abort = new AbortController()
+ const pending = first.mountPage(page, abort.signal)
const staleRequest = sentRequest(harness.endpoint)
const replacementEndpoint = createEndpoint(harness.endpoint.id)
+ abort.abort()
const replacement = harness.registry.attachRenderer(replacementEndpoint)
await expect(pending).rejects.toThrow('browser_client_page_renderer_replaced')
expect(first.isCurrent()).toBe(false)
expect(replacement.isCurrent()).toBe(true)
+ const next = { ...page, pageHostGeneration: 8 }
+ const current = replacement.mountPage(next, new AbortController().signal)
+ harness.reply(harness.endpoint, {
+ type: 'mounted',
+ requestId: staleRequest.requestId,
+ page,
+ webContentsId: 92
+ })
harness.reply(replacementEndpoint, {
type: 'mounted',
requestId: staleRequest.requestId,
page,
webContentsId: 92
})
- const current = replacement.mountPage(page, new AbortController().signal)
+ await expect(Promise.race([current, Promise.resolve('pending')])).resolves.toBe('pending')
completeMount(harness, replacementEndpoint, 93)
await expect(current).resolves.toEqual({ webContentsId: 93 })
})
- it('aborts mount admission and ignores a late reply', async () => {
+ it('rejects an already aborted mount before admission while preserving the renderer fence', async () => {
+ const harness = createHarness({ maxPending: 1 })
+ const renderer = harness.registry.attachRenderer(harness.endpoint)
+ const mounted = renderer.mountPage(page, new AbortController().signal)
+ const abort = new AbortController()
+ abort.abort()
+
+ await expect(renderer.mountPage(page, abort.signal)).rejects.toThrow(
+ 'browser_client_page_renderer_request_aborted'
+ )
+ expect(harness.endpoint.send).toHaveBeenCalledTimes(1)
+ completeMount(harness)
+ await mounted
+
+ harness.registry.retireRenderer(harness.endpoint)
+ await expect(renderer.mountPage(page, abort.signal)).rejects.toThrow(
+ 'browser_client_page_renderer_stale'
+ )
+ harness.registry.dispose()
+ })
+
+ it('retains an admitted canceled mount until its exact guest identity arrives', async () => {
const harness = createHarness({ maxPending: 1 })
const renderer = harness.registry.attachRenderer(harness.endpoint)
const abort = new AbortController()
@@ -156,25 +187,65 @@ describe('BrowserClientPageRendererBridgeRegistry', () => {
const staleRequest = sentRequest(harness.endpoint)
abort.abort()
- await expect(mounted).rejects.toThrow('browser_client_page_renderer_request_aborted')
+ await expect(Promise.race([mounted, Promise.resolve('pending')])).resolves.toBe('pending')
+ await expect(renderer.retirePage(page)).rejects.toThrow(
+ 'browser_client_page_renderer_request_capacity'
+ )
harness.reply(harness.endpoint, {
type: 'mounted',
requestId: staleRequest.requestId,
page,
webContentsId: 92
})
+ await expect(mounted).resolves.toEqual({ webContentsId: 92 })
- const current = renderer.mountPage(page, new AbortController().signal)
+ const current = renderer.mountPage(
+ { ...page, pageHostGeneration: 8 },
+ new AbortController().signal
+ )
+ harness.reply(harness.endpoint, {
+ type: 'mounted',
+ requestId: staleRequest.requestId,
+ page,
+ webContentsId: 92
+ })
+ await expect(Promise.race([current, Promise.resolve('pending')])).resolves.toBe('pending')
completeMount(harness)
await expect(current).resolves.toEqual({ webContentsId: 91 })
})
+ it('settles a sibling independently while a canceled mount awaits its reply', async () => {
+ const harness = createHarness({ maxPending: 2 })
+ const renderer = harness.registry.attachRenderer(harness.endpoint)
+ const abort = new AbortController()
+ const mounted = renderer.mountPage(page, abort.signal)
+ const request = sentRequest(harness.endpoint)
+ const sibling = renderer.mountPage(
+ { ...page, browserPageId: 'page-b' },
+ new AbortController().signal
+ )
+
+ abort.abort()
+ completeMount(harness, harness.endpoint, 93)
+ await expect(sibling).resolves.toEqual({ webContentsId: 93 })
+ await expect(Promise.race([mounted, Promise.resolve('pending')])).resolves.toBe('pending')
+ harness.reply(harness.endpoint, {
+ type: 'mounted',
+ requestId: request.requestId,
+ page,
+ webContentsId: 92
+ })
+ await expect(mounted).resolves.toEqual({ webContentsId: 92 })
+ })
+
it('retires only the exact renderer and rejects its pending work', async () => {
const harness = createHarness()
const renderer = harness.registry.attachRenderer(harness.endpoint)
- const mounted = renderer.mountPage(page, new AbortController().signal)
+ const abort = new AbortController()
+ const mounted = renderer.mountPage(page, abort.signal)
const staleRequest = sentRequest(harness.endpoint)
+ abort.abort()
expect(harness.registry.retireRenderer(createEndpoint(harness.endpoint.id))).toBe(false)
expect(renderer.isCurrent()).toBe(true)
expect(harness.registry.retireRenderer(harness.endpoint)).toBe(true)
@@ -248,6 +319,71 @@ describe('BrowserClientPageRendererBridgeRegistry', () => {
}
})
+ it('times out a canceled mount and fences its late reply from a successor', async () => {
+ vi.useFakeTimers()
+ const harness = createHarness({ maxPending: 1, timeoutMs: 25 })
+ try {
+ const renderer = harness.registry.attachRenderer(harness.endpoint)
+ const abort = new AbortController()
+ const timedOut = renderer.mountPage(page, abort.signal)
+ const staleRequest = sentRequest(harness.endpoint)
+ const timedOutResult = timedOut.catch((error: unknown) => error)
+
+ abort.abort()
+ await vi.advanceTimersByTimeAsync(24)
+ const blocked = Promise.resolve(renderer.retirePage(page)).catch((error: unknown) => error)
+ expect(harness.endpoint.send).toHaveBeenCalledTimes(1)
+ await expect(blocked).resolves.toHaveProperty(
+ 'message',
+ 'browser_client_page_renderer_request_capacity'
+ )
+ await vi.advanceTimersByTimeAsync(1)
+ await expect(timedOutResult).resolves.toHaveProperty(
+ 'message',
+ 'browser_client_page_renderer_request_timeout'
+ )
+
+ const successor = renderer.mountPage(
+ { ...page, pageHostGeneration: 8 },
+ new AbortController().signal
+ )
+ harness.reply(harness.endpoint, {
+ type: 'mounted',
+ requestId: staleRequest.requestId,
+ page,
+ webContentsId: 92
+ })
+ await expect(Promise.race([successor, Promise.resolve('pending')])).resolves.toBe('pending')
+ completeMount(harness, harness.endpoint, 93)
+ await expect(successor).resolves.toEqual({ webContentsId: 93 })
+ } finally {
+ harness.registry.dispose()
+ vi.useRealTimers()
+ }
+ })
+
+ it('still aborts rekey admission and ignores its late reply', async () => {
+ const harness = createHarness({ maxPending: 1 })
+ const renderer = harness.registry.attachRenderer(harness.endpoint)
+ const next = { ...page, pageHostGeneration: 8 }
+ const abort = new AbortController()
+ const rekeyed = renderer.rekeyPage!(page, next, abort.signal)
+ const staleRequest = sentRequest(harness.endpoint)
+
+ abort.abort()
+ await expect(rekeyed).rejects.toThrow('browser_client_page_renderer_request_aborted')
+ const current = renderer.mountPage(next, new AbortController().signal)
+ harness.reply(harness.endpoint, {
+ type: 'rekeyed',
+ requestId: staleRequest.requestId,
+ page,
+ nextPage: next
+ })
+ await expect(Promise.race([current, Promise.resolve('pending')])).resolves.toBe('pending')
+ completeMount(harness)
+ await expect(current).resolves.toEqual({ webContentsId: 91 })
+ })
+
it('releases admission when Electron send throws', async () => {
const harness = createHarness({ maxPending: 1 })
const renderer = harness.registry.attachRenderer(harness.endpoint)
diff --git a/src/main/browser/browser-client-page-renderer-bridge.ts b/src/main/browser/browser-client-page-renderer-bridge.ts
index dd802b9a491..663bc6347b1 100644
--- a/src/main/browser/browser-client-page-renderer-bridge.ts
+++ b/src/main/browser/browser-client-page-renderer-bridge.ts
@@ -222,7 +222,8 @@ export class BrowserClientPageRendererBridgeRegistry {
resolve,
reject
}
- if (signal) {
+ // Mount identity must reach creation's lifecycle claim before canceled guest cleanup.
+ if (signal && request.type !== 'mountPage') {
pending.onAbort = () =>
this.rejectPending(request.requestId, 'browser_client_page_renderer_request_aborted')
signal.addEventListener('abort', pending.onAbort, { once: true })
diff --git a/src/main/browser/browser-command-cache-byte-retention.test.ts b/src/main/browser/browser-command-cache-byte-retention.test.ts
new file mode 100644
index 00000000000..bebb004eb8b
--- /dev/null
+++ b/src/main/browser/browser-command-cache-byte-retention.test.ts
@@ -0,0 +1,201 @@
+import { describe, expect, it } from 'vitest'
+import type {
+ BrowserClientHostCommandEvent,
+ BrowserClientHostCommandResult,
+ BrowserClientHostLeaseAuthority
+} from '../../shared/browser-client-host-protocol'
+import { BrowserHostCommandLedger } from '../runtime/browser-host/browser-host-command-ledger'
+import { BrowserClientHostCommandDispatcher } from './browser-client-host-command-dispatcher'
+
+const authority: BrowserClientHostLeaseAuthority = {
+ authorityRuntimeId: 'runtime-a',
+ authorityEpoch: 'epoch-a',
+ browserHostClientId: 'host-a',
+ browserHostGeneration: 1,
+ pageCommandProtocolVersion: 1
+}
+const completed: BrowserClientHostCommandResult = { status: 'completed' }
+const large: BrowserClientHostCommandResult = { status: 'completed', value: 'x'.repeat(4_000) }
+type ByteLimits = { maxCachedResultBytes: number; maxCachedResultBytesPerPage: number }
+type Command = BrowserClientHostCommandEvent['command']
+
+function resultParams(
+ event: BrowserClientHostCommandEvent,
+ result: BrowserClientHostCommandResult
+) {
+ return { ...event, result }
+}
+
+function createDriver(kind: 'desktop' | 'runtime', limits: ByteLimits) {
+ let calls = 0
+ let nextResult = completed
+ const sequences = new Map()
+ const dispatcher = new BrowserClientHostCommandDispatcher({
+ authority,
+ ...limits,
+ handler: () => {
+ calls += 1
+ return nextResult
+ }
+ })
+ const ledger = new BrowserHostCommandLedger({ authority, ...limits })
+ ledger.attach(() => {
+ calls += 1
+ })
+ return {
+ calls: () => calls,
+ async run(page: string, body?: Command, result = completed) {
+ const sequence = (sequences.get(page) ?? 0) + 1
+ sequences.set(page, sequence)
+ const command = body ?? {
+ type: 'createPage',
+ browserProfileId: 'default',
+ executionHostKey: 'host-a'
+ }
+ if (kind === 'runtime') {
+ const issued = ledger.issue({
+ browserPageId: page,
+ pageHostGeneration: 1,
+ command
+ })
+ expect(ledger.settle(resultParams(issued.event, result))).toBe(true)
+ expect(await issued.result).toEqual(result)
+ return issued.event
+ }
+ const event: BrowserClientHostCommandEvent = {
+ ...authority,
+ type: 'command',
+ pageCommandProtocolVersion: 1,
+ browserPageId: page,
+ pageHostGeneration: 1,
+ commandSequence: sequence,
+ commandId: `${page}-${sequence}`,
+ command
+ }
+ nextResult = result
+ expect(await dispatcher.dispatch(event)).toEqual(result)
+ nextResult = completed
+ return event
+ },
+ replay(event: BrowserClientHostCommandEvent, result = completed) {
+ if (kind === 'runtime') {
+ expect(ledger.settle(resultParams(event, result))).toBe(false)
+ } else {
+ void dispatcher.dispatch(event)
+ }
+ },
+ close: async () => {
+ ledger.close()
+ await dispatcher.close()
+ }
+ }
+}
+
+const navigate: Command = { type: 'navigate', url: 'https://example.invalid/' }
+
+describe.each(['desktop', 'runtime'] as const)('%s browser command replay byte limits', (kind) => {
+ it('expires old payloads at the page byte limit and replays the surviving result', async () => {
+ const driver = createDriver(kind, {
+ maxCachedResultBytes: 20_000,
+ maxCachedResultBytesPerPage: 6_000
+ })
+ try {
+ await driver.run('page-a')
+ const first = await driver.run('page-a', navigate, large)
+ const second = await driver.run('page-a', navigate, large)
+ const last = await driver.run('page-a', navigate, large)
+ expect(() => driver.replay(first, large)).toThrow('browser_host_command_result_expired')
+ expect(() => driver.replay(second, large)).toThrow('browser_host_command_result_expired')
+ expect(() => driver.replay(last, large)).not.toThrow()
+ expect(driver.calls()).toBe(4)
+ } finally {
+ await driver.close()
+ }
+ })
+
+ it('shares the byte limit across pages and permits new work after eviction', async () => {
+ const driver = createDriver(kind, {
+ maxCachedResultBytes: 10_000,
+ maxCachedResultBytesPerPage: 8_000
+ })
+ try {
+ const entries: BrowserClientHostCommandEvent[] = []
+ for (const page of ['page-a', 'page-b', 'page-c']) {
+ await driver.run(page)
+ entries.push(await driver.run(page, navigate, large))
+ }
+ expect(() => driver.replay(entries[0], large)).toThrow('browser_host_command_result_expired')
+ expect(() => driver.replay(entries[1], large)).not.toThrow()
+ expect(() => driver.replay(entries[2], large)).not.toThrow()
+ const next = await driver.run('page-a', navigate)
+ expect(() => driver.replay(next)).not.toThrow()
+ expect(driver.calls()).toBe(7)
+ } finally {
+ await driver.close()
+ }
+ })
+
+ it('charges inputs and UTF-8 results together without rejecting completed commands', async () => {
+ const driver = createDriver(kind, {
+ maxCachedResultBytes: 3_000,
+ maxCachedResultBytesPerPage: 3_000
+ })
+ try {
+ await driver.run('page-a')
+ const combined = await driver.run(
+ 'page-a',
+ { type: 'automation', method: 'browser.eval', params: { expression: 'x'.repeat(1_400) } },
+ { status: 'completed', value: 'y'.repeat(1_400) }
+ )
+ expect(() => driver.replay(combined)).toThrow('browser_host_command_result_expired')
+ const unicode = await driver.run('page-a', navigate, {
+ status: 'completed',
+ value: '漢'.repeat(950)
+ })
+ expect(() => driver.replay(unicode)).toThrow('browser_host_command_result_expired')
+ const next = await driver.run('page-a', navigate)
+ expect(() => driver.replay(next)).not.toThrow()
+ expect(driver.calls()).toBe(4)
+ } finally {
+ await driver.close()
+ }
+ })
+})
+
+async function collect(): Promise {
+ if (!global.gc) {
+ throw new Error('This retention test requires --expose-gc')
+ }
+ for (let turn = 0; turn < 8; turn += 1) {
+ await new Promise((resolve) => setImmediate(resolve))
+ global.gc()
+ }
+}
+
+describe.each(['desktop', 'runtime'] as const)('%s cached payload ownership', (kind) => {
+ it('releases evicted result objects while keeping the newest available until close', async () => {
+ const driver = createDriver(kind, {
+ maxCachedResultBytes: 2_000,
+ maxCachedResultBytesPerPage: 2_000
+ })
+ const remember = async (): Promise> => {
+ const value = { text: 'x'.repeat(1_000) }
+ await driver.run('page-a', navigate, { status: 'completed', value })
+ return new WeakRef(value)
+ }
+ const retained: WeakRef[] = []
+ try {
+ await driver.run('page-a')
+ for (let index = 0; index < 20; index += 1) {
+ retained.push(await remember())
+ }
+ await collect()
+ expect(retained.slice(0, -1).every((value) => value.deref() === undefined)).toBe(true)
+ expect(retained.at(-1)?.deref()).toBeDefined()
+ } finally {
+ await driver.close()
+ }
+ await collect()
+ expect(retained.every((value) => value.deref() === undefined)).toBe(true)
+ })
+})
diff --git a/src/main/browser/browser-command-cache-bytes.ts b/src/main/browser/browser-command-cache-bytes.ts
new file mode 100644
index 00000000000..76fcfd2a02c
--- /dev/null
+++ b/src/main/browser/browser-command-cache-bytes.ts
@@ -0,0 +1,24 @@
+import type {
+ BrowserClientHostCommandEvent,
+ BrowserClientHostCommandResult
+} from '../../shared/browser-client-host-protocol'
+
+export const BROWSER_COMMAND_CACHE_MAX_BYTES = 32 * 1024 * 1024
+export const BROWSER_COMMAND_CACHE_MAX_BYTES_PER_PAGE = 8 * 1024 * 1024
+
+export function browserCommandCacheBytes(
+ event: BrowserClientHostCommandEvent,
+ result: BrowserClientHostCommandResult | undefined
+): number | null {
+ if (!result) {
+ return null
+ }
+ try {
+ return (
+ Buffer.byteLength(JSON.stringify(event), 'utf8') +
+ Buffer.byteLength(JSON.stringify(result), 'utf8')
+ )
+ } catch {
+ return null
+ }
+}
diff --git a/src/main/browser/browser-guest-devtools-dock.ts b/src/main/browser/browser-guest-devtools-dock.ts
index 417133ecb17..d1f609c24ad 100644
--- a/src/main/browser/browser-guest-devtools-dock.ts
+++ b/src/main/browser/browser-guest-devtools-dock.ts
@@ -1,7 +1,13 @@
import { BrowserWindow, WebContentsView } from 'electron'
import type { BrowserDevToolsDockBounds } from '../../shared/browser-devtools-dock'
+type DevToolsOpenOperation = {
+ isCurrent: () => boolean
+ finish: () => void
+}
+
type DockedDevTools = {
+ operation: DevToolsOpenOperation
guest: Electron.WebContents
/** Replaced after a page crash; the entry itself lives until DevTools close. */
view: WebContentsView
@@ -19,19 +25,66 @@ export class BrowserGuestDevToolsDock {
private readonly docks = new Map()
/** Hosts still detaching: Electron opens nothing for a guest until its old frontend lets go. */
private readonly releases = new Map>()
+ private readonly pendingOpens = new Map()
isDocked(guestId: number): boolean {
return this.docks.has(guestId)
}
- /** Returns false when the guest has no window to dock into. `onClosed` runs however it closes. */
- async open(guest: Electron.WebContents, onClosed: () => void): Promise {
+ isOpening(guestId: number): boolean {
+ return this.pendingOpens.has(guestId)
+ }
+
+ beginOpen(
+ guest: Electron.WebContents,
+ isCurrent: () => boolean = () => true
+ ): DevToolsOpenOperation {
+ const operation: DevToolsOpenOperation = {
+ isCurrent: () =>
+ this.pendingOpens.get(guest.id) === operation && !guest.isDestroyed() && isCurrent(),
+ finish: () => {
+ try {
+ if (!operation.isCurrent() && this.docks.get(guest.id)?.operation === operation) {
+ void this.releaseDock(guest.id)
+ }
+ } finally {
+ if (this.pendingOpens.get(guest.id) === operation) {
+ this.pendingOpens.delete(guest.id)
+ }
+ }
+ }
+ }
+ this.pendingOpens.set(guest.id, operation)
+ const dock = this.docks.get(guest.id)
+ if (dock) {
+ dock.operation = operation
+ }
+ return operation
+ }
+
+ /** Returns false when docking is unavailable or superseded. */
+ open(
+ guest: Electron.WebContents,
+ onClosed: () => void,
+ operation?: DevToolsOpenOperation
+ ): Promise {
+ const pending = operation ?? this.beginOpen(guest)
+ const opened = this.openDock(guest, onClosed, pending)
+ return operation ? opened : opened.finally(pending.finish)
+ }
+
+ private async openDock(
+ guest: Electron.WebContents,
+ onClosed: () => void,
+ operation: DevToolsOpenOperation
+ ): Promise {
await this.releases.get(guest.id)
- if (guest.isDestroyed()) {
+ if (!operation.isCurrent()) {
return false
}
const existing = this.docks.get(guest.id)
if (existing) {
+ existing.operation = operation
existing.view.webContents?.focus()
return true
}
@@ -75,6 +128,7 @@ export class BrowserGuestDevToolsDock {
guest.on('dom-ready', handleDomReady)
guest.on('devtools-closed', handleClosed)
this.docks.set(guest.id, {
+ operation,
guest,
view: attachDevToolsView(guest, window),
window,
@@ -93,6 +147,21 @@ export class BrowserGuestDevToolsDock {
return true
}
+ async openDetached(
+ guest: Electron.WebContents,
+ operation: DevToolsOpenOperation
+ ): Promise {
+ if (!operation.isCurrent()) {
+ return false
+ }
+ await this.releaseDock(guest.id)
+ if (!operation.isCurrent()) {
+ return false
+ }
+ guest.openDevTools({ mode: 'detach' })
+ return true
+ }
+
/** Bounds are in the host renderer's CSS pixels; null hides the view. With `snapshot`, the
* hidden view's last frame comes back so the renderer can paint it under an overlay. */
async setBounds(
@@ -131,6 +200,11 @@ export class BrowserGuestDevToolsDock {
/** Resolves once Electron has let go of the host, so DevTools can open again. */
close(guestId: number): Promise {
+ this.pendingOpens.delete(guestId)
+ return this.releaseDock(guestId)
+ }
+
+ private releaseDock(guestId: number): Promise {
const dock = this.docks.get(guestId)
if (!dock) {
return this.releases.get(guestId) ?? Promise.resolve()
diff --git a/src/main/browser/browser-manager-devtools-retirement.test.ts b/src/main/browser/browser-manager-devtools-retirement.test.ts
new file mode 100644
index 00000000000..94a87db0ec3
--- /dev/null
+++ b/src/main/browser/browser-manager-devtools-retirement.test.ts
@@ -0,0 +1,470 @@
+import { EventEmitter } from 'node:events'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+type DevToolsHost = EventEmitter & { isDestroyed: () => boolean }
+type HeldDevToolsView = { release: () => void; destroyed: boolean }
+
+const native = vi.hoisted(() => {
+ const views: HeldDevToolsView[] = []
+ const state: { views: HeldDevToolsView[]; byId: Map; window: unknown } = {
+ views,
+ byId: new Map(),
+ window: undefined
+ }
+ return state
+})
+
+vi.mock('electron', () => {
+ class View {
+ destroyed = false
+ host = Object.assign(new EventEmitter(), {
+ isDestroyed: () => this.destroyed,
+ close: vi.fn(),
+ focus: vi.fn()
+ })
+ constructor() {
+ native.views.push(this)
+ }
+ get webContents(): DevToolsHost | null {
+ return this.destroyed ? null : this.host
+ }
+ setVisible(): void {}
+ release(): void {
+ this.destroyed = true
+ this.host.emit('destroyed')
+ }
+ }
+ return {
+ WebContentsView: View,
+ BrowserWindow: { fromWebContents: () => native.window },
+ app: { getPath: () => '/downloads' },
+ clipboard: { writeText: vi.fn() },
+ shell: { openExternal: vi.fn() },
+ Menu: { buildFromTemplate: vi.fn() },
+ screen: { getCursorScreenPoint: () => ({ x: 0, y: 0 }) },
+ webContents: { fromId: (id: number) => native.byId.get(id) }
+ }
+})
+vi.mock('./popup-origin-bar-window', () => ({ openPopupWithOriginBar: vi.fn() }))
+
+import { BrowserManager } from './browser-manager'
+
+function createGuest(id: number) {
+ let destroyed = false
+ let opened = false
+ const frontend: { devToolsWebContents: DevToolsHost | null } = { devToolsWebContents: null }
+ const guest = Object.assign(new EventEmitter(), frontend, {
+ id,
+ hostWebContents: {},
+ getType: () => 'webview',
+ getURL: () => 'https://example.com/',
+ isCurrentlyAudible: () => false,
+ isDestroyed: () => destroyed,
+ isDevToolsOpened: () => opened,
+ setWindowOpenHandler: vi.fn(),
+ setDevToolsWebContents: vi.fn((host: DevToolsHost) => {
+ guest.devToolsWebContents = host
+ host.once('destroyed', () => {
+ opened = false
+ guest.devToolsWebContents = null
+ guest.emit('devtools-closed')
+ })
+ }),
+ openDevTools: vi.fn((_options?: { mode?: string }) => {
+ opened = true
+ }),
+ closeDevTools: vi.fn(() => {
+ opened = false
+ }),
+ inspectElement: vi.fn(),
+ send: vi.fn()
+ })
+ native.byId.set(id, guest)
+ return {
+ guest,
+ destroy: () => {
+ destroyed = true
+ opened = false
+ guest.emit('destroyed')
+ }
+ }
+}
+
+function asGuest(guest: ReturnType['guest']): Electron.WebContents {
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fake implements the guest members used by registration, policy, and DevTools.
+ return guest as unknown as Electron.WebContents
+}
+
+function createFixture() {
+ const { guest, destroy } = createGuest(101)
+ const renderer = { id: 5001, isDestroyed: vi.fn(() => false), send: vi.fn() }
+ native.byId.set(renderer.id, renderer)
+ const children: unknown[] = []
+ native.window = {
+ isDestroyed: () => false,
+ contentView: {
+ addChildView: (view: unknown) => children.push(view),
+ removeChildView: (view: unknown) => {
+ const index = children.indexOf(view)
+ if (index !== -1) {
+ children.splice(index, 1)
+ }
+ }
+ }
+ }
+ const manager = new BrowserManager()
+ manager.setSettingsResolver(() => ({}))
+ manager.attachGuestPolicies(asGuest(guest))
+ expect(
+ manager.registerGuest({
+ browserPageId: 'page',
+ webContentsId: guest.id,
+ rendererWebContentsId: renderer.id
+ })
+ ).toBe(true)
+ renderer.send.mockClear()
+ return { manager, guest, destroy, renderer, children }
+}
+
+beforeEach(() => {
+ native.views.length = 0
+ native.byId.clear()
+})
+
+describe('pending page DevTools retirement', () => {
+ it.each(['dock', 'detach'] as const)(
+ 'cancels a first %s open before any native release exists',
+ async (mode) => {
+ const { manager, guest, renderer, children } = createFixture()
+ const opened = manager.openDevTools('page', { x: 1, y: 2 }, { detach: mode === 'detach' })
+ manager.closeDevTools('page')
+
+ await expect(opened).resolves.toBe(false)
+ expect(native.views).toHaveLength(0)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).not.toHaveBeenCalled()
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(renderer.send).not.toHaveBeenCalled()
+ }
+ )
+
+ it('toggles a pending first open closed before a frontend exists', async () => {
+ const { manager, guest, children } = createFixture()
+ const opened = manager.openDevTools('page')
+ expect(manager.toggleDevToolsOfFocusedPage(asGuest(guest))).toBe(true)
+
+ await expect(opened).resolves.toBe(false)
+ expect(native.views).toHaveLength(0)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).not.toHaveBeenCalled()
+ })
+
+ it.each(['dock', 'detach'] as const)(
+ 'lets a newer open replace an initial %s request',
+ async (mode) => {
+ const { manager, guest, renderer, children } = createFixture()
+ const first = manager.openDevTools('page', { x: 1, y: 2 }, { detach: mode === 'detach' })
+ const latest = manager.openDevTools('page', undefined, { detach: mode !== 'detach' })
+
+ await expect(first).resolves.toBe(false)
+ await expect(latest).resolves.toBe(true)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(children).toHaveLength(mode === 'detach' ? 1 : 0)
+ if (mode === 'dock') {
+ expect(guest.openDevTools).toHaveBeenLastCalledWith({ mode: 'detach' })
+ expect(renderer.send).not.toHaveBeenCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: true
+ })
+ }
+ }
+ )
+
+ it.each(['close', 'unregister'] as const)(
+ 'honors %s after native attach before manager completion',
+ async (action) => {
+ const { manager, guest, renderer, children } = createFixture()
+ const opened = manager.openDevTools('page', { x: 1, y: 2 })
+ await Promise.resolve()
+ expect(children).toHaveLength(1)
+ expect(renderer.send).not.toHaveBeenCalled()
+ if (action === 'close') {
+ manager.closeDevTools('page')
+ } else {
+ manager.unregisterGuest('page')
+ }
+
+ await expect(opened).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(renderer.send).not.toHaveBeenCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: true
+ })
+ native.views[0].release()
+ }
+ )
+
+ it('keeps a newer dock owner when the older opening finishes', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ const first = manager.openDevTools('page', { x: 1, y: 2 })
+ await Promise.resolve()
+ expect(children).toHaveLength(1)
+ const latest = manager.openDevTools('page')
+
+ await expect(first).resolves.toBe(false)
+ await expect(latest).resolves.toBe(true)
+ expect(children).toHaveLength(1)
+ expect(native.views).toHaveLength(1)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(renderer.send).toHaveBeenLastCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: true
+ })
+ })
+
+ it('does not fall back after an unavailable dock request was closed', async () => {
+ const { manager, guest, children } = createFixture()
+ native.window = null
+ const opened = manager.openDevTools('page', { x: 1, y: 2 })
+ await Promise.resolve()
+ manager.closeDevTools('page')
+
+ await expect(opened).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).not.toHaveBeenCalled()
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ })
+
+ it('skips inspect when the detached fallback closes before its await resumes', async () => {
+ const { manager, guest, children } = createFixture()
+ native.window = null
+ guest.openDevTools.mockImplementationOnce(() => {
+ queueMicrotask(() => manager.closeDevTools('page'))
+ })
+
+ await expect(manager.openDevTools('page', { x: 1, y: 2 })).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ })
+
+ it('keeps detached fallback and inspect for a surviving owner', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ native.window = null
+
+ await expect(manager.openDevTools('page', { x: 1, y: 2 })).resolves.toBe(true)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledExactlyOnceWith({ mode: 'detach' })
+ expect(guest.inspectElement).toHaveBeenCalledExactlyOnceWith(1, 2)
+ expect(renderer.send).not.toHaveBeenCalled()
+ })
+
+ it('retires an attached old guest when registration changes before manager completion', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ const opened = manager.openDevTools('page', { x: 1, y: 2 })
+ await Promise.resolve()
+ expect(children).toHaveLength(1)
+ const replacement = createGuest(102)
+ manager.attachGuestPolicies(asGuest(replacement.guest))
+ manager.registerGuest(
+ {
+ browserPageId: 'page',
+ webContentsId: replacement.guest.id,
+ rendererWebContentsId: renderer.id
+ },
+ { retainPreviousGuestPolicies: true }
+ )
+
+ await expect(opened).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(renderer.send).not.toHaveBeenCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: true
+ })
+ native.views[0].release()
+ await expect(manager.openDevTools('page')).resolves.toBe(true)
+ expect(children).toHaveLength(1)
+ })
+
+ it.each(['close', 'toggle'] as const)(
+ 'honors a later %s while a dock reopen waits',
+ async (action) => {
+ const { manager, guest, renderer, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page', { x: 1, y: 2 })
+
+ if (action === 'close') {
+ manager.closeDevTools('page')
+ } else {
+ expect(manager.toggleDevToolsOfFocusedPage(asGuest(guest))).toBe(true)
+ }
+ expect(native.views).toHaveLength(1)
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(guest.inspectElement).not.toHaveBeenCalled()
+ expect(renderer.send).toHaveBeenLastCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: false
+ })
+ }
+ )
+
+ it('honors a later detach without recreating a dock or falling back twice', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page')
+ const detached = manager.openDevTools('page', undefined, { detach: true })
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ await expect(detached).resolves.toBe(true)
+ expect(native.views).toHaveLength(1)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(2)
+ expect(guest.openDevTools).toHaveBeenLastCalledWith({ mode: 'detach' })
+ expect(renderer.send).toHaveBeenLastCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: false
+ })
+ })
+
+ it.each(['dock', 'detach'] as const)(
+ 'retires a pending %s open when a live guest is unregistered',
+ async (mode) => {
+ const { manager, guest, renderer, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page', undefined, { detach: mode === 'detach' })
+ renderer.send.mockClear()
+ manager.unregisterGuest('page')
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ expect(guest.isDestroyed()).toBe(false)
+ expect(manager.getGuestWebContentsId('page')).toBeNull()
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(renderer.send).not.toHaveBeenCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: true
+ })
+ }
+ )
+
+ it('honors a close that arrives while a detached open waits', async () => {
+ const { manager, guest, children } = createFixture()
+ await manager.openDevTools('page')
+ const detached = manager.openDevTools('page', undefined, { detach: true })
+ manager.closeDevTools('page')
+ native.views[0].release()
+
+ await expect(detached).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ })
+
+ it('reopens for a surviving owner after the old host releases', async () => {
+ const { manager, guest, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const superseded = manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page')
+ expect(native.views).toHaveLength(1)
+ native.views[0].release()
+
+ await expect(superseded).resolves.toBe(false)
+ await expect(reopened).resolves.toBe(true)
+ expect(manager.getGuestWebContentsId('page')).toBe(guest.id)
+ expect(children).toHaveLength(1)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(2)
+ expect(native.views).toHaveLength(2)
+ })
+
+ it('creates no frontend when a guest is destroyed while release is pending', async () => {
+ const { manager, guest, destroy, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page')
+ destroy()
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ expect(children).toHaveLength(0)
+ expect(native.views).toHaveLength(1)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not reopen an old guest retained during registration replacement', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page')
+ const replacement = createGuest(102)
+ manager.attachGuestPolicies(asGuest(replacement.guest))
+ expect(
+ manager.registerGuest(
+ {
+ browserPageId: 'page',
+ webContentsId: replacement.guest.id,
+ rendererWebContentsId: renderer.id
+ },
+ { retainPreviousGuestPolicies: true }
+ )
+ ).toBe(true)
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ expect(guest.isDestroyed()).toBe(false)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(children).toHaveLength(0)
+ await expect(manager.openDevTools('page')).resolves.toBe(true)
+ expect(replacement.guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(children).toHaveLength(1)
+ })
+
+ it('undocks the renderer when a retained old guest closes its dock', async () => {
+ const { manager, destroy, renderer } = createFixture()
+ await expect(manager.openDevTools('page')).resolves.toBe(true)
+ const replacement = createGuest(102)
+ manager.attachGuestPolicies(asGuest(replacement.guest))
+ manager.registerGuest(
+ {
+ browserPageId: 'page',
+ webContentsId: replacement.guest.id,
+ rendererWebContentsId: renderer.id
+ },
+ { retainPreviousGuestPolicies: true }
+ )
+ renderer.send.mockClear()
+ destroy()
+
+ expect(renderer.send).toHaveBeenCalledWith('browser:devToolsDockChanged', {
+ browserPageId: 'page',
+ docked: false
+ })
+ })
+
+ it('does not attach to a renderer retired while release is pending', async () => {
+ const { manager, guest, renderer, children } = createFixture()
+ await manager.openDevTools('page')
+ manager.closeDevTools('page')
+ const reopened = manager.openDevTools('page')
+ renderer.isDestroyed.mockReturnValue(true)
+ native.views[0].release()
+
+ await expect(reopened).resolves.toBe(false)
+ expect(guest.openDevTools).toHaveBeenCalledTimes(1)
+ expect(children).toHaveLength(0)
+ })
+})
diff --git a/src/main/browser/browser-manager-grab-test-harness.ts b/src/main/browser/browser-manager-grab-test-harness.ts
index 008fff89a71..60c1817c822 100644
--- a/src/main/browser/browser-manager-grab-test-harness.ts
+++ b/src/main/browser/browser-manager-grab-test-harness.ts
@@ -53,7 +53,9 @@ export function routeWebContentsIds(
if (id === GRAB_RENDERER_WEB_CONTENTS_ID) {
return {
isDestroyed: mocks.rendererIsDestroyedMock,
- send: mocks.rendererSendMock
+ send: mocks.rendererSendMock,
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null)
}
}
return null
diff --git a/src/main/browser/browser-manager-grab.ts b/src/main/browser/browser-manager-grab.ts
index 2a44dcd2a82..3ee108bb531 100644
--- a/src/main/browser/browser-manager-grab.ts
+++ b/src/main/browser/browser-manager-grab.ts
@@ -87,7 +87,12 @@ export abstract class BrowserManagerGrab extends BrowserManagerViewport {
rect: BrowserGrabRect,
guest: Electron.WebContents
): Promise {
- return captureGrabSelectionScreenshot(rect, guest)
+ const releasePaint = this.holdPaintForCapture(guest.id)
+ try {
+ return await captureGrabSelectionScreenshot(rect, guest)
+ } finally {
+ releasePaint()
+ }
}
/** Preserve the active selection overlay and awaitClick listener. */
diff --git a/src/main/browser/browser-manager-guest-lifecycle.test.ts b/src/main/browser/browser-manager-guest-lifecycle.test.ts
index bc0c3a30a25..ccdc93c4e92 100644
--- a/src/main/browser/browser-manager-guest-lifecycle.test.ts
+++ b/src/main/browser/browser-manager-guest-lifecycle.test.ts
@@ -431,7 +431,7 @@ describe('browserManager', () => {
browserManager.attachGuestPolicies(guest as never)
browserManager.attachGuestPolicies(guest as never)
- expect(guestSetBackgroundThrottlingMock).toHaveBeenCalledTimes(1)
+ expect(guestSetBackgroundThrottlingMock).not.toHaveBeenCalled()
expect(guestSetWindowOpenHandlerMock).toHaveBeenCalledTimes(1)
expect(guestOnMock.mock.calls.filter(([event]) => event === 'will-navigate')).toHaveLength(1)
expect(guestOnMock.mock.calls.filter(([event]) => event === 'will-redirect')).toHaveLength(1)
diff --git a/src/main/browser/browser-manager-guest-policy.ts b/src/main/browser/browser-manager-guest-policy.ts
index bf9aabd8191..98706c6a849 100644
--- a/src/main/browser/browser-manager-guest-policy.ts
+++ b/src/main/browser/browser-manager-guest-policy.ts
@@ -27,8 +27,6 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean
this.popupOwnerContextByGuestId.set(guest.id, inheritedOwnerContext)
}
const disposeDetachTracking = this.trackDebuggerDetachForCdpOverrides(guest)
- // Keep background compositor frames available for screenshots.
- guest.setBackgroundThrottling(false)
const disposePopupPolicy = this.installGuestPopupPolicy(guest)
const disposeNavigationPolicy = this.installGuestNavigationPolicy(guest)
const forwardAudioState = (
@@ -68,9 +66,9 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean
/** Closes the page's DevTools wherever they are: docked in the pane or in their own window. */
protected closeGuestDevTools(guest: Electron.WebContents): void {
- if (this.devToolsDock.isDocked(guest.id)) {
- void this.devToolsDock.close(guest.id)
- } else if (!guest.isDestroyed()) {
+ const docked = this.devToolsDock.isDocked(guest.id)
+ void this.devToolsDock.close(guest.id)
+ if (!docked && !guest.isDestroyed()) {
guest.closeDevTools()
}
}
diff --git a/src/main/browser/browser-manager-guest-visibility.test.ts b/src/main/browser/browser-manager-guest-visibility.test.ts
index 709aabce768..f5225a9b97c 100644
--- a/src/main/browser/browser-manager-guest-visibility.test.ts
+++ b/src/main/browser/browser-manager-guest-visibility.test.ts
@@ -40,6 +40,7 @@ vi.mock('./popup-origin-bar-window', () => ({
}))
import { browserManager } from './browser-manager'
+import { rendererPublicationThrottle } from '../window/renderer-publication-throttle'
import {
rendererWebContentsId,
resetBrowserManagerMocks,
@@ -65,7 +66,7 @@ describe('browserManager', () => {
vi.useRealTimers()
})
- it('holds capture paint one-way and keeps the renderer unthrottled until the last release', () => {
+ it('keeps idle guests throttled and holds both contents until the last capture release', () => {
vi.useFakeTimers()
const guest = {
id: 1707,
@@ -73,6 +74,7 @@ describe('browserManager', () => {
isCurrentlyAudible: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
+ capturePage: vi.fn(async () => null),
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
@@ -105,6 +107,7 @@ describe('browserManager', () => {
})
// Registration also reports audio state; this test is about paint holds.
renderer.send.mockClear()
+ expect(guestSetBackgroundThrottlingMock).not.toHaveBeenCalled()
// Synchronous: a capture never waits on the desktop renderer.
const releaseFirst = browserManager.holdPaintForCapture(guest.id)
@@ -115,11 +118,13 @@ describe('browserManager', () => {
['browser:capturePaintHold', { browserPageId: 'page-capture', held: true }]
])
expect(renderer.setBackgroundThrottling.mock.calls).toEqual([[false]])
+ expect(guestSetBackgroundThrottlingMock.mock.calls).toEqual([[false]])
releaseFirst()
releaseFirst()
expect(renderer.send).toHaveBeenCalledTimes(1)
expect(renderer.setBackgroundThrottling.mock.calls).toEqual([[false]])
+ expect(guestSetBackgroundThrottlingMock.mock.calls).toEqual([[false]])
releaseSecond()
expect(renderer.send.mock.calls.at(-1)).toEqual([
@@ -129,5 +134,153 @@ describe('browserManager', () => {
expect(renderer.setBackgroundThrottling.mock.calls).toEqual([[false]])
vi.runAllTimers()
expect(renderer.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
+ expect(guestSetBackgroundThrottlingMock.mock.calls).toEqual([[false], [true]])
+ })
+
+ it('shares guest leases with a concurrent stream even without a desktop renderer', () => {
+ vi.useFakeTimers()
+ const guest = {
+ id: 1708,
+ isDestroyed: vi.fn(() => false),
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null)
+ }
+ webContentsFromIdMock.mockReturnValue(guest)
+ const releaseStream = rendererPublicationThrottle.acquire(guest)
+ const releaseCapture = browserManager.holdPaintForCapture(guest.id)
+
+ releaseStream()
+ vi.runAllTimers()
+ expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false]])
+
+ releaseCapture()
+ releaseCapture()
+ vi.runAllTimers()
+ expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
+ })
+
+ it.each(['notify', 'acquire', 'release'] as const)(
+ 'cleans capture ownership after renderer %s fails',
+ (failure) => {
+ vi.useFakeTimers()
+ const guest = {
+ id: 1711,
+ isDestroyed: vi.fn(() => false),
+ isCurrentlyAudible: vi.fn(() => false),
+ getType: vi.fn(() => 'webview'),
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null),
+ setWindowOpenHandler: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ openDevTools: vi.fn()
+ }
+ const renderer = {
+ id: rendererWebContentsId,
+ isDestroyed: vi.fn(() => false),
+ send: vi.fn(),
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null)
+ }
+ webContentsFromIdMock.mockImplementation((id: number) => (id === guest.id ? guest : renderer))
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this guest provides the policy and registration members exercised here.
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'page-failure',
+ webContentsId: guest.id,
+ rendererWebContentsId
+ })
+ const fail = (): never => {
+ throw new Error('renderer unavailable')
+ }
+ if (failure === 'release') {
+ const release = browserManager.holdPaintForCapture(guest.id)
+ renderer.send.mockImplementationOnce(fail)
+ expect(release).not.toThrow()
+ } else if (failure === 'notify') {
+ renderer.send.mockImplementationOnce(fail)
+ const release = browserManager.holdPaintForCapture(guest.id)
+ expect(release).not.toThrow()
+ } else {
+ renderer.setBackgroundThrottling.mockImplementationOnce(fail)
+ expect(() => browserManager.holdPaintForCapture(guest.id)).toThrow('renderer unavailable')
+ }
+ vi.runAllTimers()
+ expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
+
+ renderer.send.mockClear()
+ const releaseNext = browserManager.holdPaintForCapture(guest.id)
+ expect(renderer.send.mock.calls).toEqual([
+ ['browser:capturePaintHold', { browserPageId: 'page-failure', held: true }]
+ ])
+ releaseNext()
+ vi.runAllTimers()
+ expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]])
+ }
+ )
+
+ it('does not let a destroyed guest and renderer release a replacement page hold', () => {
+ vi.useFakeTimers()
+ const makeGuest = (id: number) => ({
+ id,
+ isDestroyed: vi.fn(() => false),
+ isCurrentlyAudible: vi.fn(() => false),
+ getType: vi.fn(() => 'webview'),
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null),
+ setWindowOpenHandler: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ openDevTools: vi.fn()
+ })
+ const makeRenderer = (id: number) => ({
+ id,
+ isDestroyed: vi.fn(() => false),
+ send: vi.fn(),
+ setBackgroundThrottling: vi.fn(),
+ capturePage: vi.fn(async () => null)
+ })
+ const oldGuest = makeGuest(1709)
+ const newGuest = makeGuest(1710)
+ const oldRenderer = makeRenderer(rendererWebContentsId)
+ const newRenderer = makeRenderer(rendererWebContentsId + 1)
+ webContentsFromIdMock.mockImplementation((id: number) =>
+ [oldGuest, newGuest, oldRenderer, newRenderer].find((contents) => contents.id === id)
+ )
+ const register = (guest: ReturnType, rendererId: number) => {
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this guest provides the policy and registration members exercised here.
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'page-replaced',
+ webContentsId: guest.id,
+ rendererWebContentsId: rendererId
+ })
+ }
+ register(oldGuest, oldRenderer.id)
+ const releaseOld = browserManager.holdPaintForCapture(oldGuest.id)
+ oldGuest.isDestroyed.mockReturnValue(true)
+ oldRenderer.isDestroyed.mockReturnValue(true)
+ register(newGuest, newRenderer.id)
+ newRenderer.send.mockClear()
+ const releaseNew = browserManager.holdPaintForCapture(newGuest.id)
+
+ releaseOld()
+ vi.runAllTimers()
+ expect(newRenderer.send.mock.calls).toEqual([
+ ['browser:capturePaintHold', { browserPageId: 'page-replaced', held: true }]
+ ])
+ expect(oldGuest.setBackgroundThrottling.mock.calls).toEqual([[false]])
+ expect(oldRenderer.setBackgroundThrottling.mock.calls).toEqual([[false]])
+ expect(newGuest.setBackgroundThrottling.mock.calls).toEqual([[false]])
+ expect(newRenderer.setBackgroundThrottling.mock.calls).toEqual([[false]])
+
+ releaseNew()
+ vi.runAllTimers()
+ expect(newRenderer.send.mock.calls.at(-1)).toEqual([
+ 'browser:capturePaintHold',
+ { browserPageId: 'page-replaced', held: false }
+ ])
+ expect(newGuest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
+ expect(newRenderer.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
})
})
diff --git a/src/main/browser/browser-manager-popup-child.test.ts b/src/main/browser/browser-manager-popup-child.test.ts
index a31fd7c3266..0856e2a665f 100644
--- a/src/main/browser/browser-manager-popup-child.test.ts
+++ b/src/main/browser/browser-manager-popup-child.test.ts
@@ -112,7 +112,7 @@ describe('browserManager popup child policies', () => {
didCreateWindowHandler?.({ webContents: childGuest })
- expect(childSetBackgroundThrottlingMock).toHaveBeenCalledWith(false)
+ expect(childSetBackgroundThrottlingMock).not.toHaveBeenCalled()
expect(childSetWindowOpenHandlerMock).toHaveBeenCalledTimes(1)
expect(childOnMock.mock.calls.filter(([event]) => event === 'did-create-window')).toHaveLength(
1
diff --git a/src/main/browser/browser-manager-popup-routing.test.ts b/src/main/browser/browser-manager-popup-routing.test.ts
index d0d1c5eb479..e2df6c0b766 100644
--- a/src/main/browser/browser-manager-popup-routing.test.ts
+++ b/src/main/browser/browser-manager-popup-routing.test.ts
@@ -652,7 +652,7 @@ describe('browserManager', () => {
expect(returned).toBe(popupContents)
// Custom-created children skip did-create-window, so attach their guest policies directly.
expect(popupContents.setWindowOpenHandler).toHaveBeenCalledTimes(1)
- expect(popupContents.setBackgroundThrottling).toHaveBeenCalledWith(false)
+ expect(popupContents.setBackgroundThrottling).not.toHaveBeenCalled()
expect(popupContents.on.mock.calls.some(([event]) => event === 'dom-ready')).toBe(false)
expect(rendererSendMock).toHaveBeenCalledWith('browser:popup', {
browserPageId: 'browser-1',
diff --git a/src/main/browser/browser-manager-viewport.ts b/src/main/browser/browser-manager-viewport.ts
index ddcd5d123ab..b349963e2a7 100644
--- a/src/main/browser/browser-manager-viewport.ts
+++ b/src/main/browser/browser-manager-viewport.ts
@@ -22,18 +22,55 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec
if (!guest) {
return false
}
- if (options?.detach || !(await this.openDockedDevTools(browserTabId, guest))) {
- await this.devToolsDock.close(guest.id)
- if (guest.isDestroyed()) {
+ const renderer = this.resolveRendererForBrowserTab(browserTabId)
+ const operation = this.devToolsDock.beginOpen(
+ guest,
+ () =>
+ this.webContentsIdByTabId.get(browserTabId) === guest.id &&
+ !this.offscreenGuestIds.has(guest.id) &&
+ (!renderer ||
+ (this.resolveRendererForBrowserTab(browserTabId) === renderer && !renderer.isDestroyed()))
+ )
+ const notify = (docked: boolean): void => {
+ const currentGuestId = this.webContentsIdByTabId.get(browserTabId)
+ if (
+ renderer &&
+ !renderer.isDestroyed() &&
+ (currentGuestId === undefined ||
+ currentGuestId === guest.id ||
+ (!docked && !this.devToolsDock.isDocked(currentGuestId)))
+ ) {
+ renderer.send('browser:devToolsDockChanged', { browserPageId: browserTabId, docked })
+ }
+ }
+ try {
+ let docked = false
+ if (!options?.detach && renderer) {
+ docked = await this.devToolsDock.open(guest, () => notify(false), operation)
+ if (!operation.isCurrent()) {
+ return false
+ }
+ }
+ if (!docked && !(await this.devToolsDock.openDetached(guest, operation))) {
return false
}
- guest.openDevTools({ mode: 'detach' })
+ if (!operation.isCurrent()) {
+ return false
+ }
+ if (docked) {
+ notify(true)
+ }
+ if (!operation.isCurrent()) {
+ return false
+ }
+ if (inspectAt) {
+ // Open first: inspectElement alone opens Electron's own DevTools and bypasses the dock.
+ guest.inspectElement(inspectAt.x, inspectAt.y)
+ }
+ return true
+ } finally {
+ operation.finish()
}
- if (inspectAt) {
- // Open first: inspectElement alone opens Electron's own DevTools and bypasses the dock.
- guest.inspectElement(inspectAt.x, inspectAt.y)
- }
- return true
}
closeDevTools(browserTabId: string): void {
@@ -53,7 +90,11 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec
if (guest !== focused && guest.devToolsWebContents !== focused) {
continue
}
- if (this.devToolsDock.isDocked(guest.id) || guest.isDevToolsOpened()) {
+ if (
+ this.devToolsDock.isOpening(guest.id) ||
+ this.devToolsDock.isDocked(guest.id) ||
+ guest.isDevToolsOpened()
+ ) {
this.closeGuestDevTools(guest)
} else {
void this.openDevTools(browserTabId)
@@ -88,26 +129,6 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec
return this.offscreenGuestIds.has(webContentsId) ? null : guest
}
- private async openDockedDevTools(
- browserTabId: string,
- guest: Electron.WebContents
- ): Promise {
- const renderer = this.resolveRendererForBrowserTab(browserTabId)
- if (!renderer) {
- return false
- }
- const notify = (docked: boolean): void => {
- if (!renderer.isDestroyed()) {
- renderer.send('browser:devToolsDockChanged', { browserPageId: browserTabId, docked })
- }
- }
- if (!(await this.devToolsDock.open(guest, () => notify(false)))) {
- return false
- }
- notify(true)
- return true
- }
-
// Never detach here: other CDP clients, including the agent bridge, would lose their state.
async setViewportOverride(
browserTabId: string,
diff --git a/src/main/browser/browser-manager-visibility.ts b/src/main/browser/browser-manager-visibility.ts
index c080f1e9bc4..951592284c2 100644
--- a/src/main/browser/browser-manager-visibility.ts
+++ b/src/main/browser/browser-manager-visibility.ts
@@ -1,3 +1,4 @@
+import { webContents } from 'electron'
import { rendererPublicationThrottle } from '../window/renderer-publication-throttle'
import { BrowserManagerState } from './browser-manager-state'
import { focusGuardUnavailableError, guardPaneFocusForAgentInput } from './agent-input-focus-guard'
@@ -8,7 +9,7 @@ import {
} from './browser-agent-activity'
export abstract class BrowserManagerVisibility extends BrowserManagerState {
- private readonly capturePaintHolds = new Map()
+ private readonly capturePaintHolds = new Map>()
protected readonly agentActivity = new BrowserAgentActivity({
pageIdForGuest: (guestWebContentsId) =>
this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId),
@@ -26,37 +27,58 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState {
return this.agentActivity.showPointer(guest, input)
}
+ // Non-capture commands only need the guest itself unthrottled; host paint stays parked.
+ holdGuestActive(guestWebContentsId: number): () => void {
+ const guest = webContents.fromId(guestWebContentsId)
+ return guest && !guest.isDestroyed() ? rendererPublicationThrottle.acquire(guest) : () => {}
+ }
+
// Do not await the renderer: minimized or throttled windows must not stall frame capture.
holdPaintForCapture(guestWebContentsId: number): () => void {
+ const releaseGuestThrottle = this.holdGuestActive(guestWebContentsId)
const browserPageId = this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId)
const renderer = browserPageId ? this.resolveRendererForBrowserTab(browserPageId) : null
if (!browserPageId || !renderer || renderer.isDestroyed()) {
- return () => {}
+ return releaseGuestThrottle
}
- const holds = this.capturePaintHolds.get(browserPageId) ?? 0
- this.capturePaintHolds.set(browserPageId, holds + 1)
+ let pageHolds = this.capturePaintHolds.get(renderer)
+ if (!pageHolds) {
+ pageHolds = new Map()
+ this.capturePaintHolds.set(renderer, pageHolds)
+ }
+ const holds = pageHolds.get(browserPageId) ?? 0
+ pageHolds.set(browserPageId, holds + 1)
if (holds === 0) {
- renderer.send('browser:capturePaintHold', { browserPageId, held: true })
+ sendPaintHold(renderer, browserPageId, true)
}
- // Lift throttling so capture retries do not repeatedly wait on delayed parking changes.
- const releaseThrottle = rendererPublicationThrottle.acquire(renderer)
+ let releaseThrottle = (): void => {}
let released = false
- return () => {
+ const release = (): void => {
if (released) {
return
}
released = true
- releaseThrottle()
- const remaining = (this.capturePaintHolds.get(browserPageId) ?? 1) - 1
+ const remaining = (pageHolds.get(browserPageId) ?? 1) - 1
if (remaining > 0) {
- this.capturePaintHolds.set(browserPageId, remaining)
- return
- }
- this.capturePaintHolds.delete(browserPageId)
- if (!renderer.isDestroyed()) {
- renderer.send('browser:capturePaintHold', { browserPageId, held: false })
+ pageHolds.set(browserPageId, remaining)
+ } else {
+ pageHolds.delete(browserPageId)
+ if (pageHolds.size === 0) {
+ this.capturePaintHolds.delete(renderer)
+ }
+ sendPaintHold(renderer, browserPageId, false)
}
+ releaseThrottle()
+ releaseGuestThrottle()
}
+ try {
+ // Lift throttling so capture retries do not wait on delayed parking changes.
+ releaseThrottle = rendererPublicationThrottle.acquire(renderer)
+ } catch (error) {
+ release()
+ throw error
+ }
+ return release
}
// Agent input moves Chromium focus into the guest; the pane restores the user's focus.
@@ -69,3 +91,13 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState {
return guardPaneFocusForAgentInput(renderer, browserPageId)
}
}
+
+// A paint hint must not fail the capture or command it accompanies; disposed frames throw.
+function sendPaintHold(renderer: Electron.WebContents, browserPageId: string, held: boolean): void {
+ if (renderer.isDestroyed()) {
+ return
+ }
+ try {
+ renderer.send('browser:capturePaintHold', { browserPageId, held })
+ } catch {}
+}
diff --git a/src/main/browser/browser-route-partition-storage-dependencies.test.ts b/src/main/browser/browser-route-partition-storage-dependencies.test.ts
index dae28fdee9f..26c44eb0734 100644
--- a/src/main/browser/browser-route-partition-storage-dependencies.test.ts
+++ b/src/main/browser/browser-route-partition-storage-dependencies.test.ts
@@ -3,23 +3,44 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
-const mocks = vi.hoisted(() => ({ userData: '', fromPartition: vi.fn() }))
+const mocks = vi.hoisted(() => ({
+ userData: '',
+ fromPartition: vi.fn(),
+ clearPolicies: vi.fn(),
+ clearStorage: vi.fn(async () => {}),
+ clearCache: vi.fn(async () => {})
+}))
vi.mock('electron', () => ({
app: { getPath: () => mocks.userData },
session: { fromPartition: mocks.fromPartition }
}))
-vi.mock('./browser-session-registry', () => ({
- browserSessionRegistry: { clearRoutePartitionPolicies: vi.fn() }
+vi.mock('./browser-session-partition-policies', () => ({
+ installBrowserSessionPartitionPolicies: vi.fn(async () => {}),
+ clearBrowserSessionPartitionPolicies: mocks.clearPolicies
+}))
+vi.mock('./browser-session-profile-retirement', () => ({
+ retireDeletedBrowserSessionProfile: vi.fn(async () => {}),
+ retireFailedBrowserSessionProfile: vi.fn(async () => {})
+}))
+vi.mock('./browser-session-cookie-staging', () => ({
+ applyPendingBrowserCookieImports: vi.fn(),
+ clearPendingBrowserCookieImport: vi.fn()
+}))
+vi.mock('./extensions/browser-extension-session-loader', () => ({
+ attachBrowserExtensionsToProfileSession: vi.fn()
}))
import { browserRoutePartitionStorageDependencies } from './browser-route-partition-storage-dependencies'
import { browserRoutePartitionPendingDeletesPath } from './browser-route-partition-pending-deletes'
import {
configureBrowserRoutePartitionBindingsForOrcaProfile,
- currentBrowserRoutePartitionBindingFilePath
+ currentBrowserRoutePartitionBindingFilePath,
+ currentBrowserRoutePartitionBindingStore
} from './browser-route-partition-binding-runtime'
import { collectOrphanedBrowserRoutePartitionStorage } from './browser-route-partition-storage-runtime'
+import { deriveLocalSshBrowserRoutePartitionStorageScope } from './browser-route-identity'
+import { registerBrowserRoutePartitionRetentionProbe } from './browser-route-partition-retention'
const PARTITION = `persist:orca-browser-v1-${'a'.repeat(64)}`
@@ -29,9 +50,16 @@ beforeEach(() => {
mocks.userData = mkdtempSync(join(tmpdir(), 'orca-partition-deps-'))
folder = join(mocks.userData, 'Partitions', PARTITION.slice('persist:'.length))
mkdirSync(folder, { recursive: true })
+ configureBrowserRoutePartitionBindingsForOrcaProfile({
+ orcaProfileId: 'profile-a',
+ profileDirectory: mocks.userData
+ })
+ mocks.clearPolicies.mockClear()
+ mocks.clearStorage.mockClear()
+ mocks.clearCache.mockClear()
mocks.fromPartition.mockReset().mockReturnValue({
- clearStorageData: vi.fn(async () => {}),
- clearCache: vi.fn(async () => {})
+ clearStorageData: mocks.clearStorage,
+ clearCache: mocks.clearCache
})
})
@@ -45,6 +73,13 @@ it('clears a session this run may have loaded, and leaves its folder for the nex
await dependencies.removePartitionDirectory(folder)
expect(mocks.fromPartition).toHaveBeenCalledWith(PARTITION)
+ expect(mocks.fromPartition).toHaveBeenCalledTimes(2)
+ expect(mocks.clearStorage).toHaveBeenCalledTimes(1)
+ expect(mocks.clearCache).toHaveBeenCalledTimes(1)
+ expect(mocks.clearPolicies).toHaveBeenCalledWith(
+ PARTITION,
+ mocks.fromPartition.mock.results[0]?.value
+ )
// Deleting it now is what left a half-deleted folder (EBUSY) on Windows.
expect(existsSync(folder)).toBe(true)
const pending = browserRoutePartitionPendingDeletesPath(
@@ -62,6 +97,48 @@ it('deletes the folder at startup without loading its session', async () => {
expect(existsSync(folder)).toBe(false)
})
+it('collects cold orphan folders without opening sessions, preserving retained and listed scopes', async () => {
+ const store = currentBrowserRoutePartitionBindingStore()
+ const removedScope = deriveLocalSshBrowserRoutePartitionStorageScope({
+ orcaProfileId: 'profile-a',
+ targetId: 'removed'
+ })
+ const listedScope = deriveLocalSshBrowserRoutePartitionStorageScope({
+ orcaProfileId: 'profile-a',
+ targetId: 'listed'
+ })
+ const retained = `persist:orca-browser-v1-${'e'.repeat(64)}`
+ const listed = `persist:orca-browser-v1-${'f'.repeat(64)}`
+ const orphans = Array.from(
+ { length: 2 },
+ (_, index) => `persist:orca-browser-v1-${(index + 1).toString(16).padStart(64, '0')}`
+ )
+ const partitionFolder = (partition: string): string =>
+ join(mocks.userData, 'Partitions', partition.slice('persist:'.length))
+ for (const partition of [...orphans, retained, listed]) {
+ store.set(partition, 'a'.repeat(64), partition === listed ? listedScope : removedScope)
+ mkdirSync(partitionFolder(partition), { recursive: true })
+ }
+ const unregister = registerBrowserRoutePartitionRetentionProbe(
+ (partition) => partition === retained
+ )
+ try {
+ const cleared = await collectOrphanedBrowserRoutePartitionStorage(() => ['listed'])
+
+ expect(new Set(cleared)).toEqual(new Set(orphans))
+ expect(orphans.every((partition) => !existsSync(partitionFolder(partition)))).toBe(true)
+ expect(existsSync(partitionFolder(retained))).toBe(true)
+ expect(existsSync(partitionFolder(listed))).toBe(true)
+ expect(new Set(store.listBindings().keys())).toEqual(new Set([retained, listed]))
+ expect(mocks.fromPartition).not.toHaveBeenCalled()
+ expect(mocks.clearPolicies).not.toHaveBeenCalled()
+ expect(mocks.clearStorage).not.toHaveBeenCalled()
+ expect(mocks.clearCache).not.toHaveBeenCalled()
+ } finally {
+ unregister()
+ }
+})
+
it('leaves a folder queued by one Orca profile for that profile to delete', async () => {
const profileDirectory = (id: string) => {
const directory = join(mocks.userData, 'profiles', id)
diff --git a/src/main/browser/browser-route-partition-storage-dependencies.ts b/src/main/browser/browser-route-partition-storage-dependencies.ts
index de6da7657e0..4b8da0a2798 100644
--- a/src/main/browser/browser-route-partition-storage-dependencies.ts
+++ b/src/main/browser/browser-route-partition-storage-dependencies.ts
@@ -34,8 +34,8 @@ export function browserRoutePartitionStorageDependencies(
const partitionSession = session.fromPartition(partition)
await partitionSession.clearStorageData()
await partitionSession.clearCache()
+ browserSessionRegistry.clearRoutePartitionPolicies(partition)
}
- browserSessionRegistry.clearRoutePartitionPolicies(partition)
},
removePartitionDirectory: async (directory) => {
if (mode === 'live') {
diff --git a/src/main/browser/browser-route-partition-storage-runtime.ts b/src/main/browser/browser-route-partition-storage-runtime.ts
index f693fe58eb5..b709a487781 100644
--- a/src/main/browser/browser-route-partition-storage-runtime.ts
+++ b/src/main/browser/browser-route-partition-storage-runtime.ts
@@ -1,4 +1,3 @@
-import { app } from 'electron'
import { listEnvironments } from '../../shared/runtime-environment-store'
import {
deriveBrowserRoutePartitionStorageScope,
@@ -22,6 +21,7 @@ import {
currentBrowserRoutePartitionBindingFilePath
} from './browser-route-partition-binding-runtime'
import { browserRoutePartitionStorageDependencies } from './browser-route-partition-storage-dependencies'
+import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root'
export type BrowserRoutePartitionStorageClear = {
clearedPartitions: string[]
@@ -59,7 +59,7 @@ export async function collectOrphanedBrowserRoutePartitionStorage(
})
)
const liveStorageScopes = new Set(
- listEnvironments(app.getPath('userData')).map((environment) =>
+ listEnvironments(getRuntimeEnvironmentRegistryRoot()).map((environment) =>
deriveBrowserRoutePartitionStorageScope({ orcaProfileId, environmentId: environment.id })
)
)
diff --git a/src/main/browser/browser-session-proxy.test.ts b/src/main/browser/browser-session-proxy.test.ts
index 51b289895c6..beee191fa4f 100644
--- a/src/main/browser/browser-session-proxy.test.ts
+++ b/src/main/browser/browser-session-proxy.test.ts
@@ -1,17 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { sessionsByPartition, fromPartition, fromPartitionMock } = vi.hoisted(() => {
- const sessionsByPartition = new Map>>()
- const fromPartition = (partition: string): Record> => {
+ const createSession = () => ({
+ resolveProxy: vi.fn(async () => 'DIRECT'),
+ setProxy: vi.fn(async () => {}),
+ closeAllConnections: vi.fn(async () => {})
+ })
+ const sessionsByPartition = new Map>()
+ const fromPartition = (partition: string): ReturnType => {
const existing = sessionsByPartition.get(partition)
if (existing) {
return existing
}
- const created = {
- resolveProxy: vi.fn(async () => 'DIRECT'),
- setProxy: vi.fn(async () => {}),
- closeAllConnections: vi.fn(async () => {})
- }
+ const created = createSession()
sessionsByPartition.set(partition, created)
return created
}
@@ -27,12 +28,17 @@ vi.mock('electron', () => ({
import {
applyBrowserSessionProxies,
+ awaitBrowserSessionProxies,
applyProxyToBrowserSession,
invalidateBrowserSessionProxyApplication,
setBrowserNetworkProxySettingsResolver
} from './browser-session-proxy'
import { handleElectronProxyLogin } from '../network/electron-proxy-credentials'
-import { releaseProxySessionApplication } from '../network/proxy-settings'
+import {
+ applyProxySettingsToSession,
+ releaseProxySessionApplication
+} from '../network/proxy-settings'
+import type { NetworkProxySettings } from '../../shared/network-proxy'
const PROFILES = [
{
@@ -234,4 +240,147 @@ describe('browser session proxy', () => {
expect(sess.setProxy).not.toHaveBeenCalled()
})
+
+ describe('startup readiness', () => {
+ beforeEach(() => {
+ for (const key of [
+ 'http_proxy',
+ 'https_proxy',
+ 'all_proxy',
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'ALL_PROXY'
+ ]) {
+ vi.stubEnv(key, '')
+ }
+ setBrowserNetworkProxySettingsResolver(() => ({}))
+ })
+
+ afterEach(() => vi.unstubAllEnvs())
+
+ it('awaits installed policies without reapplying them and keeps later system probes fresh', async () => {
+ const sessions = PROFILES.map((profile) => fromPartition(profile.partition))
+ const finishResolutions: (() => void)[] = []
+ for (const sess of sessions) {
+ sess.resolveProxy.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishResolutions.push(() => resolve('DIRECT'))
+ })
+ )
+ }
+ const installations = sessions.map((sess) => applyProxySettingsToSession(sess, {}))
+ let settled = false
+ const startup = awaitBrowserSessionProxies(PROFILES).then(() => (settled = true))
+
+ await vi.waitFor(() => expect(finishResolutions).toHaveLength(PROFILES.length))
+ expect(settled).toBe(false)
+ for (const finish of finishResolutions) {
+ finish()
+ }
+ await Promise.all([...installations, startup])
+ await awaitBrowserSessionProxies(PROFILES)
+
+ for (const sess of sessions) {
+ expect(sess.resolveProxy).toHaveBeenCalledOnce()
+ expect(sess.setProxy).not.toHaveBeenCalled()
+ sess.resolveProxy.mockResolvedValue('PROXY changed-system.example:8080')
+ }
+ await applyBrowserSessionProxies(PROFILES, {})
+ for (const sess of sessions) {
+ expect(sess.resolveProxy).toHaveBeenCalledTimes(2)
+ }
+ })
+
+ it('retries only a failed installation after its bounded attempts are exhausted', async () => {
+ const failed = fromPartition('persist:orca-browser')
+ const healthy = fromPartition('persist:orca-browser-session-iso')
+ for (let attempt = 0; attempt < 3; attempt++) {
+ failed.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure'))
+ }
+ const initialFailure = expect(applyProxySettingsToSession(failed, {})).rejects.toThrow(
+ 'native proxy failure'
+ )
+ await applyProxySettingsToSession(healthy, {})
+ await initialFailure
+
+ await awaitBrowserSessionProxies(PROFILES)
+
+ expect(failed.resolveProxy).toHaveBeenCalledTimes(4)
+ expect(healthy.resolveProxy).toHaveBeenCalledOnce()
+ })
+
+ it('awaits every installation and preserves failed-partition warnings and retry budget', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const failed = fromPartition('persist:orca-browser')
+ failed.resolveProxy.mockRejectedValue(new Error('native proxy failure'))
+ await expect(applyProxySettingsToSession(failed, {})).rejects.toThrow('native proxy failure')
+ const healthy = fromPartition('persist:orca-browser-session-iso')
+ let finishHealthy: (() => void) | undefined
+ healthy.resolveProxy.mockImplementationOnce(
+ () => new Promise((resolve) => (finishHealthy = () => resolve('DIRECT')))
+ )
+ const installation = applyProxySettingsToSession(healthy, {})
+ let settled = false
+ const startup = awaitBrowserSessionProxies(PROFILES).finally(() => (settled = true))
+ const failure = expect(startup).rejects.toThrow('persist:orca-browser')
+
+ await vi.waitFor(() => expect(failed.resolveProxy).toHaveBeenCalledTimes(6))
+ expect(settled).toBe(false)
+ finishHealthy?.()
+ await Promise.all([installation, failure])
+
+ expect(healthy.resolveProxy).toHaveBeenCalledOnce()
+ expect(warn).toHaveBeenCalledExactlyOnceWith(
+ '[proxy] Failed to apply proxy to browser partition',
+ 'persist:orca-browser'
+ )
+ })
+
+ it.each([false, true])(
+ 'awaits the newest settings write when the initial policy fails=%s',
+ async (initialFails) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const profiles = PROFILES.slice(0, 1)
+ const sess = fromPartition('persist:orca-browser')
+ let settings: NetworkProxySettings = {}
+ setBrowserNetworkProxySettingsResolver(() => settings)
+ let finishInitial: (() => void) | undefined
+ sess.resolveProxy.mockImplementationOnce(
+ () =>
+ new Promise((resolve, reject) => {
+ finishInitial = () =>
+ initialFails ? reject(new Error('native proxy failure')) : resolve('DIRECT')
+ })
+ )
+ if (initialFails) {
+ sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure'))
+ sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure'))
+ }
+ let finishWrite: (() => void) | undefined
+ sess.setProxy.mockImplementationOnce(
+ () => new Promise((resolve) => (finishWrite = resolve))
+ )
+ const installation = applyProxySettingsToSession(sess, {}).catch((error: unknown) => error)
+ let settled = false
+ const startup = awaitBrowserSessionProxies(profiles).then(() => (settled = true))
+ await vi.waitFor(() => expect(sess.resolveProxy).toHaveBeenCalledOnce())
+ settings = { httpProxyUrl: 'http://fresh.example:8080' }
+ const sweep = applyBrowserSessionProxies(profiles, settings)
+ finishInitial?.()
+
+ await vi.waitFor(() => expect(sess.setProxy).toHaveBeenCalledOnce())
+ expect(settled).toBe(false)
+ finishWrite?.()
+ await Promise.all([installation, startup, sweep])
+
+ expect(sess.resolveProxy).toHaveBeenCalledTimes(initialFails ? 3 : 1)
+ expect(sess.setProxy).toHaveBeenCalledExactlyOnceWith({
+ mode: 'fixed_servers',
+ proxyRules: 'http://fresh.example:8080'
+ })
+ expect(warn).not.toHaveBeenCalled()
+ }
+ )
+ })
})
diff --git a/src/main/browser/browser-session-proxy.ts b/src/main/browser/browser-session-proxy.ts
index a9f1de349e9..8390ccdae24 100644
--- a/src/main/browser/browser-session-proxy.ts
+++ b/src/main/browser/browser-session-proxy.ts
@@ -1,6 +1,9 @@
import { session, type Session } from 'electron'
import type { BrowserSessionProfile } from '../../shared/browser-workspace-types'
-import { applyProxySettingsToSession } from '../network/proxy-settings'
+import {
+ applyProxySettingsToSession,
+ awaitProxySessionApplication
+} from '../network/proxy-settings'
import type { NetworkProxySettings } from '../../shared/network-proxy'
import {
readNetworkProxySettings,
@@ -50,11 +53,28 @@ export async function applyBrowserSessionProxies(
return
}
proxyPolicyGeneration += 1
+ await settleBrowserSessionProxyApplications(profiles, (sess) =>
+ applyProxySettingsToSession(sess, resolved)
+ )
+}
+
+export async function awaitBrowserSessionProxies(profiles: BrowserSessionProfile[]): Promise {
+ await settleBrowserSessionProxyApplications(profiles, async (sess) => {
+ if (!(await awaitProxySessionApplication(sess))) {
+ await applyProxyToBrowserSession(sess)
+ }
+ })
+}
+
+async function settleBrowserSessionProxyApplications(
+ profiles: BrowserSessionProfile[],
+ apply: (sess: Session) => Promise
+): Promise {
const failedPartitions = (
await Promise.all(
profiles.map(async (profile) => {
try {
- await applyProxySettingsToSession(session.fromPartition(profile.partition), resolved)
+ await apply(session.fromPartition(profile.partition))
return null
} catch {
console.warn('[proxy] Failed to apply proxy to browser partition', profile.partition)
diff --git a/src/main/browser/browser-session-registry-startup-metadata.test.ts b/src/main/browser/browser-session-registry-startup-metadata.test.ts
new file mode 100644
index 00000000000..bc986772893
--- /dev/null
+++ b/src/main/browser/browser-session-registry-startup-metadata.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ DEFAULT_LOCAL_ORCA_PROFILE_ID,
+ getOrcaProfileBrowserSessionPartition
+} from '../../shared/orca-profiles'
+import {
+ createFsState,
+ installModuleMocks,
+ META_PATH,
+ seedMeta
+} from './__mocks__/browser-session-registry-persistence-fixture'
+
+describe('browser profile startup metadata reads', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.restoreAllMocks()
+ })
+
+ it.each([10, 100])(
+ 'reads one snapshot when restoring %i profiles and keeps extension assignments current',
+ async (count) => {
+ const fsState = createFsState()
+ const profiles = Array.from({ length: count }, (_, index) => {
+ const id = `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`
+ return {
+ id,
+ scope: 'isolated',
+ partition: getOrcaProfileBrowserSessionPartition(DEFAULT_LOCAL_ORCA_PROFILE_ID, id),
+ label: `Browser ${index}`,
+ source: null
+ }
+ })
+ const enabledExtensionIdsByProfileId = Object.fromEntries([
+ ['default', ['default-extension']],
+ ...profiles.map((profile, index) => [profile.id, [`extension-${index}`]])
+ ])
+ seedMeta(fsState, { profiles, enabledExtensionIdsByProfileId })
+ installModuleMocks(fsState)
+ const attachExtensions = vi.fn()
+ vi.doMock('./extensions/browser-extension-session-loader', () => ({
+ attachBrowserExtensionsToProfileSession: attachExtensions
+ }))
+ const { browserSessionRegistry } = await import('./browser-session-registry')
+ const { readFileSync } = await import('node:fs')
+ vi.mocked(readFileSync).mockClear()
+
+ browserSessionRegistry.initializeBrowserSessionsFromPersistedState()
+
+ expect(
+ vi.mocked(readFileSync).mock.calls.filter(([path]) => path === META_PATH)
+ ).toHaveLength(1)
+ expect(browserSessionRegistry.listProfiles()).toHaveLength(count + 1)
+ expect(attachExtensions).toHaveBeenCalledTimes(count + 1)
+ for (const profile of browserSessionRegistry.listProfiles()) {
+ expect(attachExtensions).toHaveBeenCalledWith(
+ profile,
+ enabledExtensionIdsByProfileId[profile.id]
+ )
+ }
+
+ seedMeta(fsState, {
+ profiles,
+ enabledExtensionIdsByProfileId: { default: ['new-extension'] }
+ })
+ attachExtensions.mockClear()
+ vi.mocked(readFileSync).mockClear()
+
+ browserSessionRegistry.initializeBrowserSessionsFromPersistedState()
+
+ expect(
+ vi.mocked(readFileSync).mock.calls.filter(([path]) => path === META_PATH)
+ ).toHaveLength(1)
+ expect(attachExtensions).toHaveBeenCalledWith(browserSessionRegistry.getDefaultProfile(), [
+ 'new-extension'
+ ])
+ for (const profile of profiles) {
+ expect(attachExtensions).toHaveBeenCalledWith(profile, [])
+ }
+ }
+ )
+})
diff --git a/src/main/browser/browser-session-registry.ts b/src/main/browser/browser-session-registry.ts
index 4fbe188721c..f1918196660 100644
--- a/src/main/browser/browser-session-registry.ts
+++ b/src/main/browser/browser-session-registry.ts
@@ -130,7 +130,7 @@ class BrowserSessionRegistry {
}
}
if (meta.profiles.length > 0) {
- this.hydrateFromPersisted(meta.profiles)
+ this.hydrateFromPersisted(meta.profiles, meta.enabledExtensionIdsByProfileId)
}
// Hydration skips the default profile, so install its policies separately.
@@ -138,13 +138,16 @@ class BrowserSessionRegistry {
void installBrowserSessionPartitionPolicies(defaultProfile).catch(() => {
console.warn('[proxy] Failed to apply proxy to browser partition', defaultProfile.partition)
})
- this.attachExtensions(defaultProfile)
+ this.attachExtensions(defaultProfile, meta.enabledExtensionIdsByProfileId.default ?? [])
}
// Why here and not in the partition installer: that installer also serves route, SSH and
// doc-preview partitions, and release 1 runs extensions only in local browser profiles.
- private attachExtensions(profile: BrowserSessionProfile): void {
- attachBrowserExtensionsToProfileSession(profile, this.getEnabledExtensionIds(profile.id))
+ private attachExtensions(
+ profile: BrowserSessionProfile,
+ enabledExtensionIds = this.getEnabledExtensionIds(profile.id)
+ ): void {
+ attachBrowserExtensionsToProfileSession(profile, enabledExtensionIds)
}
getEnabledExtensionIds(profileId: string): string[] {
@@ -320,7 +323,10 @@ class BrowserSessionRegistry {
}
}
- hydrateFromPersisted(profiles: BrowserSessionProfile[]): void {
+ hydrateFromPersisted(
+ profiles: BrowserSessionProfile[],
+ enabledExtensionIdsByProfileId = this.loadPersistedMeta().enabledExtensionIdsByProfileId
+ ): void {
for (const profile of profiles) {
if (!isValidPersistedBrowserSessionProfile(profile, this.activeOrcaProfileId)) {
continue
@@ -330,7 +336,7 @@ class BrowserSessionRegistry {
void installBrowserSessionPartitionPolicies(profile).catch(() => {
console.warn('[proxy] Failed to apply proxy to browser partition', profile.partition)
})
- this.attachExtensions(profile)
+ this.attachExtensions(profile, enabledExtensionIdsByProfileId[profile.id] ?? [])
}
}
}
diff --git a/src/main/browser/browser-webauthn-account-picker.test.ts b/src/main/browser/browser-webauthn-account-picker.test.ts
index 3e9e370b807..f930438ccec 100644
--- a/src/main/browser/browser-webauthn-account-picker.test.ts
+++ b/src/main/browser/browser-webauthn-account-picker.test.ts
@@ -163,4 +163,84 @@ describe('browser WebAuthn account picker', () => {
renderer.emit('render-process-gone')
await expect(windowCrashed).resolves.toBeNull()
})
+
+ it.each(['guest', 'renderer'] as const)(
+ 'retires the request when the %s commits a navigation',
+ async (target) => {
+ const owners = { guest: mockWebContents(91), renderer: mockWebContents(92) }
+ fromFrameMock.mockReturnValue(owners.guest)
+ getRendererContextForGuestMock.mockReturnValue({
+ browserPageId: 'page-6',
+ renderer: owners.renderer
+ })
+
+ const selection = requestBrowserWebAuthnAccount(accountDetails(), mockSession())
+ const requestId = vi.mocked(owners.renderer.send).mock.calls[0][1].requestId
+ owners[target].emit('did-navigate')
+
+ await expect(selection).resolves.toBeNull()
+ expect(owners.renderer.send).toHaveBeenLastCalledWith(
+ 'browser:webauthn-account-request-closed',
+ { requestId }
+ )
+ expect(
+ respondToBrowserWebAuthnAccountRequest(owners.renderer, {
+ requestId,
+ credentialId: 'credential-1'
+ })
+ ).toBe(false)
+ for (const contents of Object.values(owners)) {
+ for (const event of ['did-navigate', 'render-process-gone', 'destroyed']) {
+ expect(contents.listenerCount(event)).toBe(0)
+ }
+ }
+ expect(vi.getTimerCount()).toBe(0)
+ }
+ )
+
+ it('keeps sibling and successor requests independent of a retired document', async () => {
+ const retiredGuest = mockWebContents(101)
+ const siblingGuest = mockWebContents(102)
+ const renderer = mockWebContents(103)
+ getRendererContextForGuestMock.mockImplementation((guestId: number) => ({
+ browserPageId: `page-${guestId}`,
+ renderer
+ }))
+ const browserSession = mockSession()
+ const requestIdAt = (index: number): string =>
+ vi.mocked(renderer.send).mock.calls[index][1].requestId
+
+ fromFrameMock.mockReturnValueOnce(retiredGuest)
+ const retired = requestBrowserWebAuthnAccount(accountDetails(), browserSession)
+ fromFrameMock.mockReturnValueOnce(siblingGuest)
+ const sibling = requestBrowserWebAuthnAccount(accountDetails(), browserSession)
+ const [retiredId, siblingId] = [requestIdAt(0), requestIdAt(1)]
+
+ retiredGuest.emit('did-navigate')
+ await expect(retired).resolves.toBeNull()
+ fromFrameMock.mockReturnValueOnce(retiredGuest)
+ const successor = requestBrowserWebAuthnAccount(accountDetails(), browserSession)
+ const successorId = requestIdAt(3)
+
+ expect(
+ respondToBrowserWebAuthnAccountRequest(renderer, {
+ requestId: retiredId,
+ credentialId: 'credential-1'
+ })
+ ).toBe(false)
+ expect(
+ respondToBrowserWebAuthnAccountRequest(renderer, {
+ requestId: successorId,
+ credentialId: 'credential-2'
+ })
+ ).toBe(true)
+ expect(
+ respondToBrowserWebAuthnAccountRequest(renderer, {
+ requestId: siblingId,
+ credentialId: 'credential-1'
+ })
+ ).toBe(true)
+ await expect(successor).resolves.toBe('credential-2')
+ await expect(sibling).resolves.toBe('credential-1')
+ })
})
diff --git a/src/main/browser/browser-webauthn-account-picker.ts b/src/main/browser/browser-webauthn-account-picker.ts
index 522630e6851..b0807f7a305 100644
--- a/src/main/browser/browser-webauthn-account-picker.ts
+++ b/src/main/browser/browser-webauthn-account-picker.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto'
import { webContents } from 'electron'
+import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort'
import type {
BrowserWebAuthnAccountRequest,
@@ -12,11 +13,10 @@ export const BROWSER_WEBAUTHN_ACCOUNT_PICKER_TIMEOUT_MS = 60_000
type PendingAccountRequest = {
browserPageId: string
browserSession: Electron.Session
- guest: Electron.WebContents
renderer: Electron.WebContents
credentialIds: Set
timer: ReturnType
- onUnavailable: () => void
+ dispose: () => void
settle: (credentialId: string | null) => void
}
@@ -34,10 +34,7 @@ function closeRendererPrompt(requestId: string, request: PendingAccountRequest):
function cleanUpRequest(requestId: string, request: PendingAccountRequest): void {
clearTimeout(request.timer)
- request.guest.removeListener('destroyed', request.onUnavailable)
- request.guest.removeListener('render-process-gone', request.onUnavailable)
- request.renderer.removeListener('destroyed', request.onUnavailable)
- request.renderer.removeListener('render-process-gone', request.onUnavailable)
+ request.dispose()
pendingAccountRequests.delete(requestId)
}
@@ -80,21 +77,30 @@ export function requestBrowserWebAuthnAccount(
}
resolve(credentialId)
}
+ const lifetimes = [abortWhenRendererGone(guest), abortWhenRendererGone(context.renderer)]
+ const onUnavailable = (): void => settle(null)
const request: PendingAccountRequest = {
browserPageId: context.browserPageId,
browserSession,
- guest,
renderer: context.renderer,
credentialIds: new Set(details.accounts.map((account) => account.credentialId)),
timer: setTimeout(settle, BROWSER_WEBAUTHN_ACCOUNT_PICKER_TIMEOUT_MS),
- onUnavailable: () => settle(null),
+ dispose: () => {
+ for (const lifetime of lifetimes) {
+ lifetime.signal.removeEventListener('abort', onUnavailable)
+ lifetime.dispose()
+ }
+ },
settle
}
pendingAccountRequests.set(requestId, request)
- guest.once('destroyed', request.onUnavailable)
- guest.once('render-process-gone', request.onUnavailable)
- context.renderer.once('destroyed', request.onUnavailable)
- context.renderer.once('render-process-gone', request.onUnavailable)
+ for (const lifetime of lifetimes) {
+ lifetime.signal.addEventListener('abort', onUnavailable, { once: true })
+ }
+ if (lifetimes.some(({ signal }) => signal.aborted)) {
+ settle(null)
+ return
+ }
try {
context.renderer.send('browser:webauthn-account-requested', requestPayload)
} catch {
diff --git a/src/main/browser/cdp-debugger-channel.ts b/src/main/browser/cdp-debugger-channel.ts
index 3124a4f9851..9bb4d1f27c4 100644
--- a/src/main/browser/cdp-debugger-channel.ts
+++ b/src/main/browser/cdp-debugger-channel.ts
@@ -7,6 +7,7 @@ import { sendGuestCdpCommand } from './guest-cdp-command'
import { isOrcaFrameSessionTraffic } from './guest-focused-frame-route'
export class CdpDebuggerChannel {
+ private nativeDebugger: WebContents['debugger'] | null = null
private debuggerMessageHandler: ((...args: unknown[]) => void) | null = null
private debuggerDetachHandler: ((...args: unknown[]) => void) | null = null
private debuggerLease: ElectronDebuggerLease | null = null
@@ -24,19 +25,17 @@ export class CdpDebuggerChannel {
if (this.attached) {
return
}
+ let lease: ElectronDebuggerLease
try {
- this.debuggerLease = acquireElectronDebugger(this.webContents)
+ lease = acquireElectronDebugger(this.webContents)
} catch {
throw new Error('Could not attach debugger. DevTools may already be open for this tab.')
}
+ const dbg = this.webContents.debugger
+ this.nativeDebugger = dbg
+ this.debuggerLease = lease
this.attached = true
- try {
- await this.webContents.debugger.sendCommand('Page.enable', {})
- } catch {
- /* The page domain may not be ready yet. */
- }
-
this.debuggerMessageHandler = (_event: unknown, ...rest: unknown[]) => {
const [method, params, sessionId] = rest as [
string,
@@ -57,29 +56,46 @@ export class CdpDebuggerChannel {
this.responder.send(msg, client)
}
this.debuggerDetachHandler = () => {
- this.attached = false
- const lease = this.debuggerLease
- this.debuggerLease = null
- lease?.release()
+ this.detachDebugger()
this.onDetached()
}
- this.webContents.debugger.on('message', this.debuggerMessageHandler as never)
- this.webContents.debugger.on('detach', this.debuggerDetachHandler as never)
+ dbg.on('message', this.debuggerMessageHandler)
+ dbg.on('detach', this.debuggerDetachHandler)
+
+ try {
+ await dbg.sendCommand('Page.enable', {})
+ } catch {
+ /* The page domain may not be ready yet. */
+ }
+ if (this.debuggerLease !== lease) {
+ throw new Error('Browser debugger was detached during startup')
+ }
+ if (this.webContents.isDestroyed() || !dbg.isAttached()) {
+ this.detachDebugger()
+ throw new Error('Browser tab is no longer available')
+ }
}
detachDebugger(): void {
- if (this.debuggerMessageHandler) {
- this.webContents.debugger.removeListener('message', this.debuggerMessageHandler as never)
- this.debuggerMessageHandler = null
- }
- if (this.debuggerDetachHandler) {
- this.webContents.debugger.removeListener('detach', this.debuggerDetachHandler as never)
- this.debuggerDetachHandler = null
- }
+ const dbg = this.nativeDebugger
+ const messageHandler = this.debuggerMessageHandler
+ const detachHandler = this.debuggerDetachHandler
const lease = this.debuggerLease
+ this.nativeDebugger = null
+ this.debuggerMessageHandler = null
+ this.debuggerDetachHandler = null
this.debuggerLease = null
- lease?.release()
this.attached = false
+ try {
+ if (messageHandler) {
+ dbg?.removeListener('message', messageHandler)
+ }
+ if (detachHandler) {
+ dbg?.removeListener('detach', detachHandler)
+ }
+ } finally {
+ lease?.release()
+ }
}
sendDebuggerCommand(
diff --git a/src/main/browser/cdp-ws-proxy-startup-lifetime.test.ts b/src/main/browser/cdp-ws-proxy-startup-lifetime.test.ts
new file mode 100644
index 00000000000..07479bfa45b
--- /dev/null
+++ b/src/main/browser/cdp-ws-proxy-startup-lifetime.test.ts
@@ -0,0 +1,216 @@
+import { EventEmitter } from 'node:events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { CdpWsProxy } from './cdp-ws-proxy'
+import { acquireElectronDebugger } from './electron-debugger-lease'
+import { createMockWebContents, mockAsWebContents } from './cdp-ws-proxy-test-harness'
+
+const { createServerMock, webSocketServerMock } = vi.hoisted(() => ({
+ createServerMock: vi.fn(),
+ webSocketServerMock: vi.fn()
+}))
+
+vi.mock('electron', () => ({ webContents: { fromId: vi.fn() } }))
+vi.mock('node:http', () => ({ createServer: createServerMock }))
+vi.mock('ws', () => ({
+ default: { OPEN: 1 },
+ WebSocket: { OPEN: 1 },
+ WebSocketServer: webSocketServerMock
+}))
+
+class ProxyServer extends EventEmitter {
+ listening = false
+
+ listen(_port: number, _host: string, callback: () => void): void {
+ this.listening = true
+ queueMicrotask(callback)
+ }
+
+ address(): { port: number } {
+ return { port: 9222 }
+ }
+
+ close(): void {
+ this.listening = false
+ }
+}
+
+class ProxyWebSocketServer extends EventEmitter {
+ closed = false
+
+ close(): void {
+ this.closed = true
+ }
+}
+
+function pendingEnable(mock: ReturnType) {
+ let finish = (): void => {}
+ let fail = (_error: Error): void => {}
+ const command = new Promise>((resolve, reject) => {
+ finish = () => resolve({})
+ fail = reject
+ })
+ mock.webContents.debugger.sendCommand.mockReturnValueOnce(command)
+ return { finish, fail }
+}
+
+function invalidateNativeHandle(mock: ReturnType): void {
+ mock.destroy()
+ Object.defineProperty(mock.webContents, 'debugger', {
+ get() {
+ throw new Error('Object has been destroyed')
+ }
+ })
+}
+
+describe('CdpWsProxy startup ownership', () => {
+ let servers: ProxyServer[]
+ let socketServers: ProxyWebSocketServer[]
+ let proxies: CdpWsProxy[]
+
+ beforeEach(() => {
+ servers = []
+ socketServers = []
+ proxies = []
+ createServerMock.mockImplementation(() => {
+ const server = new ProxyServer()
+ servers.push(server)
+ return server
+ })
+ webSocketServerMock.mockImplementation(function () {
+ const server = new ProxyWebSocketServer()
+ socketServers.push(server)
+ return server
+ })
+ })
+
+ afterEach(async () => {
+ await Promise.all(proxies.map((proxy) => proxy.stop()))
+ expect(servers.filter((server) => server.listening)).toHaveLength(0)
+ expect(socketServers.filter((server) => !server.closed)).toHaveLength(0)
+ })
+
+ function makeProxy(mock: ReturnType): CdpWsProxy {
+ const proxy = new CdpWsProxy(mockAsWebContents(mock), () => () => {})
+ proxies.push(proxy)
+ return proxy
+ }
+
+ function expectNoListeners(mock: ReturnType): void {
+ expect(mock.listeners.get('message') ?? []).toHaveLength(0)
+ expect(mock.listeners.get('detach') ?? []).toHaveLength(0)
+ }
+
+ it('tolerates Page.enable rejection on a live shared attachment', async () => {
+ const mock = createMockWebContents()
+ const debuggerHandle = mock.webContents.debugger
+ const lease = acquireElectronDebugger(mockAsWebContents(mock))
+ debuggerHandle.sendCommand.mockRejectedValueOnce(new Error('Page domain is not ready'))
+ const proxy = makeProxy(mock)
+
+ await expect(proxy.start()).resolves.toBe('ws://127.0.0.1:9222')
+ await proxy.stop()
+
+ expectNoListeners(mock)
+ expect(debuggerHandle.isAttached()).toBe(true)
+ expect(debuggerHandle.detach).not.toHaveBeenCalled()
+ lease.release()
+ expect(debuggerHandle.attach).toHaveBeenCalledTimes(1)
+ expect(debuggerHandle.detach).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([false, true])(
+ 'refuses server admission after native detach during Page.enable (destroyed: %s)',
+ async (destroyed) => {
+ const mock = createMockWebContents()
+ const debuggerHandle = mock.webContents.debugger
+ const enable = pendingEnable(mock)
+ const proxy = makeProxy(mock)
+ const starting = proxy.start()
+ debuggerHandle.isAttached.mockReturnValue(false)
+ if (destroyed) {
+ invalidateNativeHandle(mock)
+ }
+ mock.emit('detach', {}, 'target closed')
+ enable.fail(new Error('target closed while handling command'))
+
+ await expect(starting).rejects.toThrow('detached during startup')
+ expect(proxy.getPort()).toBe(0)
+ expect(servers).toHaveLength(0)
+ expect(socketServers).toHaveLength(0)
+ expectNoListeners(mock)
+ }
+ )
+
+ it('cleans a destroyed startup even when no native detach event arrives', async () => {
+ const mock = createMockWebContents()
+ const enable = pendingEnable(mock)
+ const proxy = makeProxy(mock)
+ const starting = proxy.start()
+ invalidateNativeHandle(mock)
+ enable.fail(new Error('target closed while handling command'))
+
+ await expect(starting).rejects.toThrow('no longer available')
+ expect(servers).toHaveLength(0)
+ expectNoListeners(mock)
+ })
+
+ it('refuses server admission when stopped after attachment completes', async () => {
+ const mock = createMockWebContents()
+ const proxy = makeProxy(mock)
+ const starting = proxy.start()
+ await Promise.resolve()
+ await proxy.stop()
+
+ await expect(starting).rejects.toThrow('stopped')
+ expect(servers).toHaveLength(0)
+ expectNoListeners(mock)
+ })
+
+ it('does not detach a successor when stopped Page.enable completes late', async () => {
+ const mock = createMockWebContents()
+ const debuggerHandle = mock.webContents.debugger
+ const enable = pendingEnable(mock)
+ const proxy = makeProxy(mock)
+ const starting = proxy.start()
+ await proxy.stop()
+ const successor = makeProxy(mock)
+ await successor.start()
+ enable.finish()
+
+ await expect(starting).rejects.toThrow('detached during startup')
+ expect(servers).toHaveLength(1)
+ expect(debuggerHandle.isAttached()).toBe(true)
+ expect(debuggerHandle.detach).toHaveBeenCalledTimes(1)
+ expect(mock.listeners.get('message')).toHaveLength(1)
+ expect(mock.listeners.get('detach')).toHaveLength(1)
+ await successor.stop()
+ expect(debuggerHandle.detach).toHaveBeenCalledTimes(2)
+ expectNoListeners(mock)
+ })
+
+ it('retires an established proxy without reading a destroyed native handle', async () => {
+ const mock = createMockWebContents()
+ const proxy = makeProxy(mock)
+ await proxy.start()
+ invalidateNativeHandle(mock)
+
+ await expect(proxy.stop()).resolves.toBeUndefined()
+ expectNoListeners(mock)
+ expect(servers[0].listening).toBe(false)
+ expect(socketServers[0].closed).toBe(true)
+ })
+
+ it('closes server resources even if debugger cleanup throws', async () => {
+ const mock = createMockWebContents()
+ const proxy = makeProxy(mock)
+ await proxy.start()
+ mock.webContents.debugger.removeListener.mockImplementationOnce(() => {
+ throw new Error('debugger cleanup failed')
+ })
+
+ await expect(proxy.stop()).rejects.toThrow('debugger cleanup failed')
+ expect(servers[0].listening).toBe(false)
+ expect(socketServers[0].closed).toBe(true)
+ expect(mock.webContents.debugger.detach).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/main/browser/cdp-ws-proxy.ts b/src/main/browser/cdp-ws-proxy.ts
index 6da8270b528..b18c0e88744 100644
--- a/src/main/browser/cdp-ws-proxy.ts
+++ b/src/main/browser/cdp-ws-proxy.ts
@@ -23,6 +23,7 @@ export class CdpWsProxy {
private client: WebSocket | null = null
private detachClientListeners: (() => void) | null = null
private port = 0
+ private stopped = false
private readonly responder = new CdpClientResponseWriter(() => this.client)
private readonly sessions = new CdpSyntheticSessionRegistry()
private readonly discovery: CdpTargetDiscovery
@@ -77,7 +78,14 @@ export class CdpWsProxy {
}
async start(): Promise {
+ if (this.stopped) {
+ throw new Error('CDP proxy has been stopped')
+ }
await this.debuggerChannel.attachDebugger()
+ if (this.stopped || this.webContents.isDestroyed()) {
+ await this.stop()
+ throw new Error('CDP proxy has been stopped')
+ }
return new Promise((resolve, reject) => {
this.httpServer = createServer((req, res) => {
if (!isTrustedCdpLoopbackRequest(req, this.port)) {
@@ -145,15 +153,19 @@ export class CdpWsProxy {
}
async stop(): Promise {
- this.debuggerChannel.detachDebugger()
- this.closeClient()
- if (this.wss) {
- this.wss.close()
- this.wss = null
- }
- if (this.httpServer) {
- this.httpServer.close()
- this.httpServer = null
+ this.stopped = true
+ try {
+ this.debuggerChannel.detachDebugger()
+ } finally {
+ this.closeClient()
+ if (this.wss) {
+ this.wss.close()
+ this.wss = null
+ }
+ if (this.httpServer) {
+ this.httpServer.close()
+ this.httpServer = null
+ }
}
}
diff --git a/src/main/browser/cookies/browser-cookie-import.test.ts b/src/main/browser/cookies/browser-cookie-import.test.ts
index f66989b0e7b..442803cee33 100644
--- a/src/main/browser/cookies/browser-cookie-import.test.ts
+++ b/src/main/browser/cookies/browser-cookie-import.test.ts
@@ -685,7 +685,8 @@ describe('detectInstalledBrowsers', () => {
'firefox',
'safari',
'comet',
- 'helium'
+ 'helium',
+ 'vivaldi'
]
for (const browser of browsers) {
expect(validFamilies).toContain(browser.family)
diff --git a/src/main/browser/cookies/browser-cookie-import.vivaldi.test.ts b/src/main/browser/cookies/browser-cookie-import.vivaldi.test.ts
new file mode 100644
index 00000000000..ecd51d856b2
--- /dev/null
+++ b/src/main/browser/cookies/browser-cookie-import.vivaldi.test.ts
@@ -0,0 +1,73 @@
+import { pbkdf2Sync } from 'node:crypto'
+import type * as fsModule from 'node:fs'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { existingPaths, runProcessSyncMock } = vi.hoisted(() => ({
+ existingPaths: new Set(),
+ runProcessSyncMock: vi.fn()
+}))
+
+vi.mock('node:fs', async () => {
+ const actual = await vi.importActual('node:fs')
+ return {
+ ...actual,
+ existsSync: (p: string) => existingPaths.has(p.replaceAll('\\', '/'))
+ }
+})
+vi.mock('@orca/process-host', () => ({ runProcessSync: runProcessSyncMock }))
+
+import { detectInstalledBrowsers } from './sources/browser-cookie-detection'
+import { getEncryptionKey } from './sources/browser-cookie-key'
+
+const originalPlatform = process.platform
+const originalEnv = { ...process.env }
+
+function setPlatform(platform: NodeJS.Platform): void {
+ Object.defineProperty(process, 'platform', { value: platform })
+}
+
+beforeEach(() => {
+ existingPaths.clear()
+ runProcessSyncMock.mockReset()
+ process.env.HOME = '/home/test'
+ process.env.LOCALAPPDATA = 'C:/Users/test/AppData/Local'
+ process.env.XDG_CONFIG_HOME = '/home/test/.config'
+})
+
+afterEach(() => {
+ setPlatform(originalPlatform)
+ process.env = { ...originalEnv }
+})
+
+describe('Vivaldi cookie import source', () => {
+ it.each([
+ ['darwin', '/home/test/Library/Application Support/Vivaldi/Default/Cookies'],
+ ['win32', 'C:/Users/test/AppData/Local/Vivaldi/User Data/Default/Network/Cookies'],
+ ['linux', '/home/test/.config/vivaldi/Default/Cookies']
+ ] as const)('detects the %s profile store', (platform, cookiesPath) => {
+ setPlatform(platform)
+ existingPaths.add(cookiesPath)
+
+ const vivaldi = detectInstalledBrowsers().find((browser) => browser.family === 'vivaldi')
+
+ expect(vivaldi?.label).toBe('Vivaldi')
+ expect(vivaldi?.cookiesPath.replaceAll('\\', '/')).toBe(cookiesPath)
+ })
+
+ it('reads the Linux keyring secret Vivaldi stores under the Chrome application name', () => {
+ setPlatform('linux')
+ existingPaths.add('/home/test/.config/vivaldi/Default/Cookies')
+ runProcessSyncMock.mockImplementation(({ args }: { args: string[] }) =>
+ args.join(' ') === 'lookup application chrome'
+ ? { code: 0, timedOut: false, stdout: 'vivaldi-secret\n', stderr: '' }
+ : { code: 1, timedOut: false, stdout: '', stderr: '' }
+ )
+ const vivaldi = detectInstalledBrowsers().find((browser) => browser.family === 'vivaldi')
+
+ const key = getEncryptionKey(vivaldi!.keychainService!, vivaldi!.keychainAccount!, vivaldi)
+
+ expect(key).toMatchObject({
+ keysByVersion: { v11: pbkdf2Sync('vivaldi-secret', 'saltysalt', 1, 16, 'sha1') }
+ })
+ })
+})
diff --git a/src/main/browser/cookies/sources/browser-cookie-detection-types.ts b/src/main/browser/cookies/sources/browser-cookie-detection-types.ts
index 872d544d1e2..d414c9c9b67 100644
--- a/src/main/browser/cookies/sources/browser-cookie-detection-types.ts
+++ b/src/main/browser/cookies/sources/browser-cookie-detection-types.ts
@@ -22,6 +22,8 @@ export type ChromiumBrowserDef = {
label: string
keychainService: string
keychainAccount: string
+ // Linux libsecret `application` attribute; defaults to keychainAccount lowercased without spaces.
+ linuxKeyringApplication?: string
macRoot?: string
winRoot?: string
linuxRoot?: string
@@ -77,6 +79,17 @@ export const CHROMIUM_BROWSERS: ChromiumBrowserDef[] = [
keychainAccount: 'Helium',
macRoot: 'net.imput.helium'
// Only the macOS install is verified.
+ },
+ {
+ family: 'vivaldi',
+ label: 'Vivaldi',
+ keychainService: 'Vivaldi Safe Storage',
+ keychainAccount: 'Vivaldi',
+ macRoot: 'Vivaldi',
+ winRoot: 'Vivaldi/User Data',
+ linuxRoot: 'vivaldi',
+ // Vivaldi on Linux keeps Chrome's libsecret entry name (matches yt-dlp and browser_cookie3).
+ linuxKeyringApplication: 'chrome'
}
]
diff --git a/src/main/browser/cookies/sources/browser-cookie-key.ts b/src/main/browser/cookies/sources/browser-cookie-key.ts
index baa10ca6ecf..75e53f6c86c 100644
--- a/src/main/browser/cookies/sources/browser-cookie-key.ts
+++ b/src/main/browser/cookies/sources/browser-cookie-key.ts
@@ -35,7 +35,10 @@ export function getEncryptionKey(
return getMacEncryptionKey(keychainService, keychainAccount)
}
if (process.platform === 'linux') {
- return getLinuxEncryptionKey(keychainService, keychainAccount)
+ const application = CHROMIUM_BROWSERS.find(
+ (b) => b.family === browser?.family
+ )?.linuxKeyringApplication
+ return getLinuxEncryptionKey(keychainService, keychainAccount, application)
}
if (process.platform === 'win32' && browser) {
return getWindowsEncryptionKey(browser)
@@ -66,17 +69,17 @@ export function getMacEncryptionKey(
export function getLinuxEncryptionKey(
keychainService: string,
- keychainAccount: string
+ keychainAccount: string,
+ application = keychainAccount.toLowerCase().replaceAll(' ', '')
): EncryptionKeyResult | null {
// Linux v10 uses "peanuts"; v11 requires OS key storage, and CBC cannot authenticate a wrong key.
const v10Key = pbkdf2Sync('peanuts', PBKDF2_SALT, 1, PBKDF2_KEY_LENGTH, 'sha1')
let keyringPassword = ''
let keyringFailure: LinuxCookieKeyFailure = 'key-unavailable'
- const app = keychainAccount.toLowerCase().replaceAll(' ', '')
for (const args of [
['lookup', 'service', keychainService, 'account', keychainAccount],
- ['lookup', 'application', app]
+ ['lookup', 'application', application]
]) {
try {
keyringPassword = runKeychainCommand('secret-tool', args, 5_000)
diff --git a/src/main/browser/doc-preview-file-reader.test.ts b/src/main/browser/doc-preview-file-reader.test.ts
index 81095230730..9d5836a3412 100644
--- a/src/main/browser/doc-preview-file-reader.test.ts
+++ b/src/main/browser/doc-preview-file-reader.test.ts
@@ -7,8 +7,8 @@ const mocks = vi.hoisted(() => ({
vi.mock('../ipc/runtime-environments/runtime-environment-transport-routing', () => ({
callRuntimeEnvironment: mocks.callRuntimeEnvironment
}))
-vi.mock('../persistence', () => ({
- getCanonicalUserDataPath: () => '/user-data'
+vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({
+ getRuntimeEnvironmentRegistryRoot: () => '/user-data'
}))
import { docPreviewContentType, readDocPreviewFile } from './doc-preview-file-reader'
diff --git a/src/main/browser/doc-preview-file-reader.ts b/src/main/browser/doc-preview-file-reader.ts
index ca56a62f15c..fcddbdf46ff 100644
--- a/src/main/browser/doc-preview-file-reader.ts
+++ b/src/main/browser/doc-preview-file-reader.ts
@@ -3,7 +3,6 @@ import type { RuntimeFilePreviewResult } from '../../shared/runtime-file-contrac
import type { DocPreviewFileFailureReason } from '../../shared/doc-preview-scheme'
import { FONT_FILE_MIME_TYPES } from '../../shared/font-file-extensions'
import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing'
-import { getCanonicalUserDataPath } from '../persistence'
import { SSH_HOST_NOT_SERVED_MESSAGE } from '../providers/ssh-host-not-served-error'
import {
resolveDocPreviewAuthorityPaths,
@@ -13,6 +12,7 @@ import {
toRuntimeWorktreeRelativePath,
type DocPreviewGrant
} from './doc-preview-grant-registry'
+import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root'
const DOC_PREVIEW_READ_TIMEOUT_MS = 15_000
@@ -99,7 +99,7 @@ async function readRuntimeDocPreviewFile(
implicitRootRelativePath: string | null,
authorizedRootRelativePaths: string[]
): Promise {
- const userDataPath = getCanonicalUserDataPath()
+ const userDataPath = getRuntimeEnvironmentRegistryRoot()
const response = await callRuntimeEnvironment(
userDataPath,
environmentId,
diff --git a/src/main/browser/electron-debugger-lease.test.ts b/src/main/browser/electron-debugger-lease.test.ts
index ff6fdd22cf8..22d4c399d2e 100644
--- a/src/main/browser/electron-debugger-lease.test.ts
+++ b/src/main/browser/electron-debugger-lease.test.ts
@@ -41,4 +41,18 @@ describe('electron debugger lease', () => {
expect(webContents.debugger.attach).not.toHaveBeenCalled()
expect(webContents.debugger.detach).not.toHaveBeenCalled()
})
+
+ it('releases a destroyed guest without querying its native debugger', () => {
+ const webContents = createWebContents()
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies the debugger lease's entire WebContents boundary.
+ const lease = acquireElectronDebugger(webContents as never)
+ webContents.isDestroyed.mockReturnValue(true)
+ webContents.debugger.isAttached.mockImplementation(() => {
+ throw new Error('Object has been destroyed')
+ })
+
+ expect(() => lease.release()).not.toThrow()
+ expect(() => lease.release()).not.toThrow()
+ expect(webContents.debugger.detach).not.toHaveBeenCalled()
+ })
})
diff --git a/src/main/browser/electron-debugger-lease.ts b/src/main/browser/electron-debugger-lease.ts
index 11400e95b29..f3c33f5da18 100644
--- a/src/main/browser/electron-debugger-lease.ts
+++ b/src/main/browser/electron-debugger-lease.ts
@@ -43,7 +43,7 @@ export function acquireElectronDebugger(webContents: WebContents): ElectronDebug
return
}
debuggerLeases.delete(webContents)
- if (!state.attachedByLease || !dbg.isAttached()) {
+ if (!state.attachedByLease || webContents.isDestroyed() || !dbg.isAttached()) {
return
}
try {
diff --git a/src/main/browser/extensions/api/downloads.test.ts b/src/main/browser/extensions/api/downloads.test.ts
index 894ba7386a7..ae922d6da8d 100644
--- a/src/main/browser/extensions/api/downloads.test.ts
+++ b/src/main/browser/extensions/api/downloads.test.ts
@@ -1,5 +1,5 @@
import { EventEmitter } from 'node:events'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { BrowserExtensionCaller } from '../browser-extension-namespace-registry'
const mocks = vi.hoisted(() => {
@@ -31,6 +31,13 @@ const { registerDownloadsNamespace } = await import('./downloads')
const { getBrowserExtensionNamespace } = await import('../browser-extension-namespace-registry')
const EXTENSION_ID = 'a'.repeat(32)
+const OTHER_ID = 'b'.repeat(32)
+const sessions = new Set()
+const pendingDownloads: Promise[] = []
+let nextOwnerId = 7
+
+const { ensureHostSessionState, forgetHostSession, forgetExtensionContexts } =
+ await import('../browser-extension-contexts')
function fakeItem(url: string, savePath: string, finalUrl = url) {
return {
@@ -52,29 +59,64 @@ function fakeItem(url: string, savePath: string, finalUrl = url) {
function setup() {
const session = new EventEmitter()
- const owner = { id: 7, isDestroyed: () => false, downloadURL: vi.fn() }
- const caller = { extension: { id: EXTENSION_ID }, session, webContents: owner }
- const download = (options: Record): Promise =>
- Promise.resolve().then(() =>
+ const owner = { id: nextOwnerId++, isDestroyed: () => false, downloadURL: vi.fn() }
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: downloads and context lifetime read only these stubbed caller fields.
+ const caller = {
+ extension: { id: EXTENSION_ID },
+ session,
+ webContents: owner
+ } as unknown as BrowserExtensionCaller
+ ensureHostSessionState(caller.session, 'default')
+ sessions.add(caller.session)
+ const download = (
+ options: Record,
+ extensionId = EXTENSION_ID
+ ): Promise => {
+ const pending = Promise.resolve().then(() =>
getBrowserExtensionNamespace('downloads')?.methods.download.invoke(
- // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: downloads reads only the caller fields stubbed above.
- caller as unknown as BrowserExtensionCaller,
+ { ...caller, extension: { ...caller.extension, id: extensionId } },
[options]
)
)
+ pendingDownloads.push(pending)
+ void pending.catch(() => {})
+ return pending
+ }
const willDownload = (item: ReturnType): void => {
session.emit('will-download', {}, item, owner)
}
- return { session, owner, download, willDownload }
+ return { session: caller.session, owner, download, willDownload }
+}
+
+function retireContext(session: Electron.Session, kind: 'extension' | 'host'): void {
+ if (kind === 'host') {
+ forgetHostSession(session)
+ ensureHostSessionState(session, 'default')
+ } else {
+ forgetExtensionContexts(session, EXTENSION_ID)
+ }
}
beforeEach(() => {
mocks.emitted.length = 0
mocks.requestDownloadFilename.mockReset()
mocks.requestDownloadSavePath.mockReset()
+ mocks.chooseSavePath.mockReset()
registerDownloadsNamespace()
})
+afterEach(async () => {
+ if (vi.isFakeTimers()) {
+ await vi.runAllTimersAsync()
+ vi.useRealTimers()
+ }
+ await Promise.allSettled(pendingDownloads.splice(0))
+ for (const session of sessions) {
+ forgetHostSession(session)
+ }
+ sessions.clear()
+})
+
describe('downloads.download', () => {
it("accepts the extension's own pages, relative or absolute, and refuses another extension's", async () => {
const { owner, download, willDownload } = setup()
@@ -202,3 +244,153 @@ describe('downloads.download', () => {
expect(owner.downloadURL).not.toHaveBeenCalled()
})
})
+
+describe('download context lifetime', () => {
+ beforeEach(() => vi.useFakeTimers())
+
+ it.each(['extension', 'host'] as const)(
+ 'skips obsolete starts after %s retirement without releasing the active native start',
+ async (kind) => {
+ const { session, owner, download, willDownload } = setup()
+ const url = 'https://site.test/serialized'
+ const first = download({ url, filename: 'active.txt' })
+ const obsolete = [
+ download({ url, filename: 'obsolete-1.txt' }),
+ download({ url, filename: 'obsolete-2.txt' })
+ ]
+ let obsoleteResults: PromiseSettledResult[] | undefined
+ void Promise.allSettled(obsolete).then((results) => {
+ obsoleteResults = results
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(owner.downloadURL).toHaveBeenCalledTimes(1)
+ retireContext(session, kind)
+ const successor = download({ url, filename: 'successor.txt' })
+ const sibling = download({ url, filename: 'sibling.txt' }, OTHER_ID)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(owner.downloadURL).toHaveBeenCalledTimes(1)
+ expect(session.listenerCount('will-download')).toBe(1)
+ expect(vi.getTimerCount()).toBe(1)
+
+ const activeItem = fakeItem(url, '/downloads/active.txt')
+ willDownload(activeItem)
+ await expect(first).resolves.toEqual(expect.any(Number))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(obsoleteResults).toEqual([
+ {
+ status: 'rejected',
+ reason: expect.objectContaining({ message: 'Extension context was unloaded' })
+ },
+ {
+ status: 'rejected',
+ reason: expect.objectContaining({ message: 'Extension context was unloaded' })
+ }
+ ])
+ expect(owner.downloadURL).toHaveBeenCalledTimes(2)
+ expect(mocks.requestDownloadFilename).toHaveBeenCalledExactlyOnceWith(
+ activeItem,
+ 'active.txt'
+ )
+ const successorItem = fakeItem(url, '/downloads/successor.txt')
+ willDownload(successorItem)
+ await expect(successor).resolves.toEqual(expect.any(Number))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(owner.downloadURL).toHaveBeenCalledTimes(3)
+ const siblingItem = fakeItem(url, '/downloads/sibling.txt')
+ willDownload(siblingItem)
+ await expect(sibling).resolves.toEqual(expect.any(Number))
+ expect(mocks.requestDownloadFilename.mock.calls.map(([, name]) => name)).toEqual([
+ 'active.txt',
+ 'successor.txt',
+ 'sibling.txt'
+ ])
+ expect(session.listenerCount('will-download')).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ }
+ )
+
+ it.each(['extension', 'host'] as const)(
+ 'rejects a late save dialog result after %s retirement before waiting behind a live start',
+ async (kind) => {
+ const { session, owner, download, willDownload } = setup()
+ const dialog = Promise.withResolvers()
+ mocks.chooseSavePath.mockReturnValueOnce(dialog.promise)
+ const url = 'https://site.test/save-as'
+ const old = download({ url, saveAs: true })
+ let oldSettled = false
+ void old
+ .finally(() => {
+ oldSettled = true
+ })
+ .catch(() => {})
+ await vi.advanceTimersByTimeAsync(0)
+ expect(mocks.chooseSavePath).toHaveBeenCalledOnce()
+ retireContext(session, kind)
+ const successor = download({ url, filename: 'live.txt' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(owner.downloadURL).toHaveBeenCalledTimes(1)
+ dialog.resolve('/downloads/obsolete.txt')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(oldSettled).toBe(true)
+ await expect(old).rejects.toThrow('Extension context was unloaded')
+ expect(owner.downloadURL).toHaveBeenCalledTimes(1)
+ expect(mocks.requestDownloadSavePath).not.toHaveBeenCalled()
+ willDownload(fakeItem(url, '/downloads/live.txt'))
+ await expect(successor).resolves.toEqual(expect.any(Number))
+ expect(session.listenerCount('will-download')).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ }
+ )
+
+ it('skips obsolete starts after the admitted predecessor times out', async () => {
+ const { session, owner, download, willDownload } = setup()
+ const url = 'https://site.test/timeout'
+ const first = download({ url })
+ const obsolete = download({ url })
+ let obsoleteResult: unknown
+ void obsolete.catch((error: unknown) => {
+ obsoleteResult = error
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ retireContext(session, 'extension')
+ const successor = download({ url })
+ await vi.advanceTimersByTimeAsync(15_000)
+ await expect(first).rejects.toThrow('The download did not start')
+ expect(obsoleteResult).toEqual(
+ expect.objectContaining({ message: 'Extension context was unloaded' })
+ )
+ await expect(obsolete).rejects.toThrow('Extension context was unloaded')
+ expect(owner.downloadURL).toHaveBeenCalledTimes(2)
+ expect(session.listenerCount('will-download')).toBe(1)
+ expect(vi.getTimerCount()).toBe(1)
+ willDownload(fakeItem(url, '/downloads/live.txt'))
+ await expect(successor).resolves.toEqual(expect.any(Number))
+ expect(session.listenerCount('will-download')).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('keeps another session live while an unloaded extension waits for its native item', async () => {
+ const firstSession = setup()
+ const otherSession = setup()
+ const url = 'https://site.test/independent'
+ const active = firstSession.download({ url })
+ const obsolete = firstSession.download({ url })
+ await vi.advanceTimersByTimeAsync(0)
+ retireContext(firstSession.session, 'extension')
+ const independent = otherSession.download({ url })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(firstSession.owner.downloadURL).toHaveBeenCalledTimes(1)
+ expect(otherSession.owner.downloadURL).toHaveBeenCalledTimes(1)
+ otherSession.willDownload(fakeItem(url, '/downloads/independent.txt'))
+ await expect(independent).resolves.toEqual(expect.any(Number))
+ firstSession.willDownload(fakeItem(url, '/downloads/active.txt'))
+ await expect(active).resolves.toEqual(expect.any(Number))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(firstSession.owner.downloadURL).toHaveBeenCalledTimes(1)
+ await expect(obsolete).rejects.toThrow('Extension context was unloaded')
+ expect(firstSession.owner.downloadURL).toHaveBeenCalledTimes(1)
+ expect(firstSession.session.listenerCount('will-download')).toBe(0)
+ expect(otherSession.session.listenerCount('will-download')).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/src/main/browser/extensions/api/downloads.ts b/src/main/browser/extensions/api/downloads.ts
index c9933c456e6..ffd99491966 100644
--- a/src/main/browser/extensions/api/downloads.ts
+++ b/src/main/browser/extensions/api/downloads.ts
@@ -6,6 +6,8 @@ import {
} from '../../../../shared/browser-extension-url'
import { browserManager } from '../../browser-manager'
import { emitBrowserExtensionEvent } from '../browser-extension-api-host'
+import { getBrowserExtensionContextSignal } from '../browser-extension-context-lifetime'
+import { getHostSessionState } from '../browser-extension-contexts'
import { chooseDownloadSavePath } from './downloads-save-as'
import {
BrowserExtensionApiError,
@@ -152,8 +154,10 @@ function startDownload(
owner: Electron.WebContents,
url: string,
options: z.infer,
- place: DownloadPlace
+ place: DownloadPlace,
+ signal: AbortSignal
): Promise {
+ requireDownloadContext(signal)
// Why: the tab can close during the save dialog or an earlier identical start.
if (owner.isDestroyed()) {
throw new BrowserExtensionApiError('The tab closed before the download started')
@@ -192,6 +196,12 @@ function startDownload(
return started
}
+function requireDownloadContext(signal: AbortSignal): void {
+ if (signal.aborted) {
+ throw new BrowserExtensionApiError('Extension context was unloaded')
+ }
+}
+
async function download(
caller: BrowserExtensionCaller,
options: z.infer
@@ -207,9 +217,15 @@ async function download(
const filename = requestedFilename(options.filename)
const url = resolveDownloadUrl(caller, options.url)
const owner = downloadOwner(caller)
+ const state = getHostSessionState(caller.session)
+ if (!state) {
+ throw new BrowserExtensionApiError('Extension context was unloaded')
+ }
+ const signal = getBrowserExtensionContextSignal(state, caller.extension.id)
const place: DownloadPlace = { filename }
if (saveAs) {
const savePath = await chooseDownloadSavePath(owner, url, filename)
+ requireDownloadContext(signal)
if (savePath === null) {
throw new BrowserExtensionApiError('Download canceled by the user')
}
@@ -218,8 +234,8 @@ async function download(
const key = `${owner.id} ${url}`
const previous = startsInFlight.get(key) ?? Promise.resolve()
const start = previous.then(
- () => startDownload(caller, owner, url, options, place),
- () => startDownload(caller, owner, url, options, place)
+ () => startDownload(caller, owner, url, options, place, signal),
+ () => startDownload(caller, owner, url, options, place, signal)
)
startsInFlight.set(key, start)
try {
diff --git a/src/main/browser/extensions/api/notifications.test.ts b/src/main/browser/extensions/api/notifications.test.ts
index 3045cf6c7f5..b099b9db9ca 100644
--- a/src/main/browser/extensions/api/notifications.test.ts
+++ b/src/main/browser/extensions/api/notifications.test.ts
@@ -1,15 +1,190 @@
import { join } from 'node:path'
-import { describe, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'node:events'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { BrowserExtensionCaller } from '../browser-extension-namespace-registry'
-vi.mock('electron', () => ({ Notification: {}, nativeImage: {} }))
-vi.mock('../../../window/foreground-activation-policy', () => ({ isBackgroundLaunch: () => true }))
+type TestNotification = EventEmitter & {
+ close: ReturnType
+ show: ReturnType
+}
+
+const mocks = vi.hoisted(() => {
+ const notifications: TestNotification[] = []
+ return { notifications, supported: true, background: false }
+})
+vi.mock('electron', async () => {
+ const { EventEmitter } = await import('node:events')
+ return {
+ Notification: class extends EventEmitter {
+ static isSupported = () => mocks.supported
+ close = vi.fn(() => this.emit('close', { reason: 'programmatic' }))
+ show = vi.fn()
+ constructor() {
+ super()
+ mocks.notifications.push(this)
+ }
+ },
+ nativeImage: {}
+ }
+})
+vi.mock('../../../window/foreground-activation-policy', () => ({
+ isBackgroundLaunch: () => mocks.background
+}))
vi.mock('../browser-extension-api-host', () => ({ emitBrowserExtensionEvent: vi.fn() }))
vi.mock('./permissions', () => ({ noteBrowserExtensionUserGesture: vi.fn() }))
-const { resolveNotificationIconPath } = await import('./notifications')
+const { registerNotificationsNamespace, resolveNotificationIconPath } =
+ await import('./notifications')
+const { getBrowserExtensionNamespace } = await import('../browser-extension-namespace-registry')
+const { emitBrowserExtensionEvent } = await import('../browser-extension-api-host')
+registerNotificationsNamespace()
const extension = { id: 'a'.repeat(32), path: join('/ext', 'root') }
+beforeEach(() => {
+ mocks.notifications.length = 0
+ mocks.supported = true
+ mocks.background = false
+ vi.clearAllMocks()
+})
+
+function notificationCaller(profileId: string): {
+ caller: BrowserExtensionCaller
+ extensions: EventEmitter
+} {
+ const extensions = new EventEmitter()
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: notification methods only use the session's native extension event emitter.
+ const session = Object.assign(new EventEmitter(), { extensions }) as Electron.Session
+ return {
+ caller: {
+ browserProfileId: profileId,
+ session,
+ extension: {
+ ...extension,
+ name: 'Owner',
+ url: `chrome-extension://${extension.id}/`,
+ version: '1.0',
+ manifest: { permissions: ['notifications'] }
+ }
+ },
+ extensions
+ }
+}
+
+function invoke(caller: BrowserExtensionCaller, method: string, args: unknown[] = []): unknown {
+ const target = getBrowserExtensionNamespace('notifications')?.methods[method]
+ if (!target) {
+ throw new Error(`Missing notification method: ${method}`)
+ }
+ return target.invoke(caller, args)
+}
+
+const options = { type: 'basic', title: 'Notification', message: 'Retire with its extension' }
+
+describe('notification extension ownership', () => {
+ it.each(['create', 'update'])(
+ 'forgets a failed native %s without reporting a dismissal',
+ (method) => {
+ const { caller } = notificationCaller(`failed-${method}`)
+ const sibling = { ...caller, extension: { ...caller.extension, id: 'b'.repeat(32) } }
+ invoke(caller, 'create', ['failed', options])
+ if (method === 'update') {
+ invoke(caller, 'update', ['failed', { message: 'updated' }])
+ }
+ const failed = mocks.notifications.at(-1)
+ if (!failed) {
+ throw new Error('Missing native notification')
+ }
+ invoke(sibling, 'create', ['live', options])
+ vi.clearAllMocks()
+
+ failed.emit('failed', {}, 'Native notification delivery failed')
+
+ expect(invoke(caller, 'getAll')).toEqual({})
+ expect(invoke(caller, 'update', ['failed', { message: 'retry' }])).toBe(false)
+ expect(invoke(caller, 'clear', ['failed'])).toBe(false)
+ expect(invoke(sibling, 'getAll')).toEqual({ live: true })
+ expect(failed.eventNames()).toEqual([])
+ expect(failed.close).not.toHaveBeenCalled()
+ expect(emitBrowserExtensionEvent).not.toHaveBeenCalled()
+
+ invoke(caller, 'create', ['failed', options])
+ failed.emit('failed', {}, 'Late old failure')
+ failed.emit('close', { reason: 'timedOut' })
+ expect(invoke(caller, 'getAll')).toEqual({ failed: true })
+ expect(invoke(caller, 'clear', ['failed'])).toBe(true)
+ expect(emitBrowserExtensionEvent).toHaveBeenLastCalledWith(
+ { session: caller.session, extensionId: caller.extension.id },
+ 'notifications',
+ 'onClosed',
+ ['failed', false]
+ )
+ }
+ )
+
+ it('closes and forgets unloaded notifications while preserving sibling extensions and profiles', () => {
+ const { caller, extensions } = notificationCaller('owner')
+ const sibling = { ...caller, extension: { ...caller.extension, id: 'b'.repeat(32) } }
+ const other = notificationCaller('other').caller
+ for (const owner of [caller, sibling, other]) {
+ invoke(owner, 'create', ['same-id', options])
+ }
+ expect(extensions.listenerCount('extension-unloaded')).toBe(1)
+ const [retired, siblingNotification, otherNotification] = mocks.notifications
+ extensions.emit('extension-unloaded', {}, caller.extension)
+ expect(invoke(caller, 'getAll')).toEqual({})
+ expect(invoke(sibling, 'getAll')).toEqual({ 'same-id': true })
+ expect(invoke(other, 'getAll')).toEqual({ 'same-id': true })
+ expect(retired.close).toHaveBeenCalledOnce()
+ expect(siblingNotification.close).not.toHaveBeenCalled()
+ expect(otherNotification.close).not.toHaveBeenCalled()
+ expect(retired.eventNames()).toEqual([])
+ expect(emitBrowserExtensionEvent).not.toHaveBeenCalled()
+ invoke(caller, 'create', ['same-id', options])
+ expect(extensions.listenerCount('extension-unloaded')).toBe(1)
+ retired.emit('close', { reason: 'timedOut' })
+ retired.emit('click')
+ expect(invoke(caller, 'getAll')).toEqual({ 'same-id': true })
+ expect(emitBrowserExtensionEvent).not.toHaveBeenCalled()
+ })
+
+ it('retires state even when native notifications are unavailable or presentation is suppressed', () => {
+ for (const suppressed of ['unsupported', 'background']) {
+ const { caller, extensions } = notificationCaller(suppressed)
+ mocks.supported = suppressed !== 'unsupported'
+ mocks.background = suppressed === 'background'
+ invoke(caller, 'create', ['retired', options])
+ expect(invoke(caller, 'getAll')).toEqual({ retired: true })
+ extensions.emit('extension-unloaded', {}, caller.extension)
+ expect(invoke(caller, 'getAll')).toEqual({})
+ }
+ expect(mocks.notifications).toHaveLength(0)
+ })
+
+ it('keeps live replacement, updates, native dismissal and explicit clear behavior', () => {
+ const { caller } = notificationCaller('live')
+ invoke(caller, 'create', ['live', options])
+ const original = mocks.notifications[0]
+ invoke(caller, 'create', ['live', { ...options, message: 'replacement' }])
+ expect(original.close).toHaveBeenCalledOnce()
+ expect(invoke(caller, 'getAll')).toEqual({ live: true })
+ expect(invoke(caller, 'update', ['live', { message: 'updated' }])).toBe(true)
+ expect(mocks.notifications[1].close).toHaveBeenCalledOnce()
+ mocks.notifications[2].emit('close', { reason: 'timedOut' })
+ expect(invoke(caller, 'getAll')).toEqual({})
+ expect(emitBrowserExtensionEvent).toHaveBeenLastCalledWith(
+ { session: caller.session, extensionId: caller.extension.id },
+ 'notifications',
+ 'onClosed',
+ ['live', false]
+ )
+ invoke(caller, 'create', ['clear', options])
+ expect(invoke(caller, 'clear', ['clear'])).toBe(true)
+ expect(mocks.notifications[3].close).toHaveBeenCalledOnce()
+ expect(invoke(caller, 'clear', ['clear'])).toBe(false)
+ })
+})
+
describe('resolveNotificationIconPath', () => {
it("resolves the extension's own icons, relative or absolute", () => {
const icon = join(extension.path, 'icons', 'bell.png')
diff --git a/src/main/browser/extensions/api/notifications.ts b/src/main/browser/extensions/api/notifications.ts
index a4bccb1058c..000f1a10a99 100644
--- a/src/main/browser/extensions/api/notifications.ts
+++ b/src/main/browser/extensions/api/notifications.ts
@@ -38,14 +38,22 @@ type Shown = {
notification: Electron.Notification | null
}
-/** Profile → extension → notification id. Held so click handlers survive GC. */
-const shownByProfile = new Map>>()
+/** Session → extension → notification id. Held so click handlers survive GC. */
+const shownBySession = new WeakMap>>()
function shownFor(caller: BrowserExtensionCaller): Map {
- let byExtension = shownByProfile.get(caller.browserProfileId)
+ let byExtension = shownBySession.get(caller.session)
if (!byExtension) {
byExtension = new Map()
- shownByProfile.set(caller.browserProfileId, byExtension)
+ shownBySession.set(caller.session, byExtension)
+ const owned = byExtension
+ caller.session.extensions.on('extension-unloaded', (_event, extension) => {
+ const shown = owned.get(extension.id)
+ owned.delete(extension.id)
+ for (const entry of shown?.values() ?? []) {
+ detach(entry)
+ }
+ })
}
let shown = byExtension.get(caller.extension.id)
if (!shown) {
@@ -85,12 +93,14 @@ function emit(caller: BrowserExtensionCaller, event: string, args: unknown[]): v
)
}
-function detach(entry: Shown): void {
+function detach(entry: Shown, closeNative = true): void {
const { notification } = entry
entry.notification = null
if (notification) {
notification.removeAllListeners()
- notification.close()
+ if (closeNative) {
+ notification.close()
+ }
}
}
@@ -130,6 +140,11 @@ function show(caller: BrowserExtensionCaller, id: string, entry: Shown): void {
shownFor(caller).delete(id)
emit(caller, 'onClosed', [id, details.reason !== 'timedOut'])
})
+ notification.once('failed', () => {
+ shownFor(caller).delete(id)
+ // Electron destroys the native notification after dispatching this failure.
+ detach(entry, false)
+ })
entry.notification = notification
notification.show()
}
diff --git a/src/main/browser/extensions/api/permissions.ts b/src/main/browser/extensions/api/permissions.ts
index d719d9cad6a..344b0849c32 100644
--- a/src/main/browser/extensions/api/permissions.ts
+++ b/src/main/browser/extensions/api/permissions.ts
@@ -28,10 +28,7 @@ import { getDnrSessionRuntime } from '../browser-extension-dnr-session'
import { observeBrowserExtensionWebRequests } from '../browser-extension-web-request'
const USER_GESTURE_WINDOW_MS = 5_000
-const recentGestures = new WeakMap<
- Electron.Session,
- Map
->()
+const recentGestures = new WeakMap()
const pendingRequests = new Set()
const permissionsSchema = z
@@ -56,24 +53,20 @@ export function noteBrowserExtensionUserGesture(
return
}
const signal = getBrowserExtensionContextSignal(state, extensionId)
- let gestures = recentGestures.get(session)
- if (!gestures) {
- gestures = new Map()
- recentGestures.set(session, gestures)
- }
- gestures.set(extensionId, { at: Date.now(), signal })
+ recentGestures.set(signal, Date.now())
}
export function hasBrowserExtensionUserGesture(caller: BrowserExtensionCaller): boolean {
if (caller.userGesture === true) {
return true
}
- const gesture = recentGestures.get(caller.session)?.get(caller.extension.id)
- return (
- gesture !== undefined &&
- !gesture.signal.aborted &&
- Date.now() - gesture.at <= USER_GESTURE_WINDOW_MS
- )
+ const state = getHostSessionState(caller.session)
+ if (!state) {
+ return false
+ }
+ const signal = getBrowserExtensionContextSignal(state, caller.extension.id)
+ const at = recentGestures.get(signal)
+ return at !== undefined && !signal.aborted && Date.now() - at <= USER_GESTURE_WINDOW_MS
}
function readGrants(profileId: string, extensionId: string) {
diff --git a/src/main/browser/extensions/api/tabs-capture.test.ts b/src/main/browser/extensions/api/tabs-capture.test.ts
index d9c0b4fb6d3..09a9cfb10ba 100644
--- a/src/main/browser/extensions/api/tabs-capture.test.ts
+++ b/src/main/browser/extensions/api/tabs-capture.test.ts
@@ -1,12 +1,25 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { BrowserExtensionCaller } from '../browser-extension-namespace-registry'
const mocks = vi.hoisted(() => {
const tabs: { windowId: number; active: boolean; contents: unknown }[] = []
const hostPatterns: string[] = []
- return { tabs, windows: new Set(), hostPatterns, activeTabGrants: new Set() }
+ return {
+ tabs,
+ windows: new Set(),
+ hostPatterns,
+ activeTabGrants: new Set(),
+ releasePaint: vi.fn(),
+ holdPaint: vi.fn()
+ }
})
+vi.mock('electron', () => ({ webFrameMain: { fromId: vi.fn() } }))
+
+vi.mock('../../browser-manager', () => ({
+ browserManager: { holdPaintForCapture: mocks.holdPaint }
+}))
+
vi.mock('../browser-extension-tab-model', () => ({
listBrowserExtensionTabs: () => mocks.tabs,
resolveCallerWindowId: () => 1
@@ -24,13 +37,15 @@ vi.mock('../browser-extension-active-tab', () => ({
}))
const { captureVisibleTabMethod } = await import('./tabs-capture')
+const { ensureHostSessionState, forgetExtensionContexts, forgetHostSession } =
+ await import('../browser-extension-contexts')
const EXTENSION_ID = 'a'.repeat(32)
function fakeImage(empty = false) {
return {
isEmpty: () => empty,
- toPNG: () => Buffer.from('png-bytes'),
+ toPNG: vi.fn(() => Buffer.from('png-bytes')),
toJPEG: vi.fn((quality: number) => Buffer.from(`jpeg-${quality}`))
}
}
@@ -44,23 +59,45 @@ function tab(id: number, url: string, windowId = 1, image = fakeImage()) {
}
}
-function capture(...args: unknown[]) {
- const caller = {
+const QUOTA_ERROR = 'This request exceeds the MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND quota.'
+let caller: BrowserExtensionCaller
+
+function createCaller(): BrowserExtensionCaller {
+ const stub = {
extension: { id: EXTENSION_ID, manifest: {} },
session: {},
browserProfileId: 'default'
}
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: capture and context ownership read only the extension/session/profile fields stubbed above.
+ const created = stub as unknown as BrowserExtensionCaller
+ ensureHostSessionState(created.session, created.browserProfileId)
+ return created
+}
+
+function captureAs(overrides: Partial, ...args: unknown[]) {
return new Promise((resolve) =>
- // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the method reads only the caller fields stubbed above.
- resolve(captureVisibleTabMethod.invoke(caller as unknown as BrowserExtensionCaller, args))
+ resolve(captureVisibleTabMethod.invoke({ ...caller, ...overrides }, args))
)
}
+function capture(...args: unknown[]) {
+ return captureAs({}, ...args)
+}
+
beforeEach(() => {
+ vi.spyOn(performance, 'now').mockReturnValue(0)
+ caller = createCaller()
mocks.tabs = []
mocks.windows = new Set([1, 2])
mocks.hostPatterns = []
mocks.activeTabGrants = new Set()
+ mocks.holdPaint.mockClear().mockReturnValue(mocks.releasePaint)
+ mocks.releasePaint.mockClear()
+})
+
+afterEach(() => {
+ forgetHostSession(caller.session)
+ vi.restoreAllMocks()
})
describe('tabs.captureVisibleTab', () => {
@@ -107,4 +144,148 @@ describe('tabs.captureVisibleTab', () => {
mocks.tabs = []
await expect(capture()).rejects.toThrow('No active web contents to capture')
})
+
+ it('admits two mixed-window captures before native work starts and rejects the rest', async () => {
+ mocks.hostPatterns = ['']
+ const image = fakeImage()
+ const deferred = Promise.withResolvers>()
+ const capturePage = vi.fn(() => deferred.promise)
+ mocks.tabs = [1, 2].map((windowId) => ({
+ windowId,
+ active: true,
+ contents: { id: windowId, getURL: () => 'https://site.test/', capturePage }
+ }))
+ const pending = Array.from({ length: 40 }, (_, index) =>
+ capture(index % 2 ? 2 : 1, { format: index % 2 ? 'png' : 'jpeg' })
+ )
+ const completed = Promise.allSettled(pending)
+ const nativeCallsBeforeCompletion = capturePage.mock.calls.length
+ expect(image.toPNG).not.toHaveBeenCalled()
+ expect(image.toJPEG).not.toHaveBeenCalled()
+ deferred.resolve(image)
+ const results = await completed
+ expect(nativeCallsBeforeCompletion).toBe(2)
+ expect(mocks.holdPaint).toHaveBeenCalledTimes(2)
+ expect(mocks.releasePaint).toHaveBeenCalledTimes(2)
+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(2)
+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(38)
+ for (const result of results.slice(2)) {
+ if (result.status === 'rejected') {
+ expect(result.reason).toHaveProperty('message', QUOTA_ERROR)
+ }
+ }
+ expect(image.toPNG).toHaveBeenCalledTimes(1)
+ expect(image.toJPEG).toHaveBeenCalledTimes(1)
+ })
+
+ it('shares page/worker admission but isolates extension and session identities', async () => {
+ mocks.hostPatterns = ['