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)', - '![hero](docs/assets/hero%20image.jpg "Hero")' + '![hero](docs/assets/hero%20image.jpg "Hero")', + // 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 Orca +

+ +

+ Звёзды на GitHub + Общее число скачиваний всех выпусков + Лицензия: MIT + Присоединяйтесь к сообществу Orca в Discord + Подпишитесь на Orca в X + Поддерживаемые платформы: macOS, Windows и Linux +

+ +

+ English · 中文 · 日本語 · 한국어 · Español · Français · Português · Türkçe +

+ +

+ Оркестратор ИИ для тех, кто создаёт в 100 раз больше.
+ Запускайте Codex, ClaudeCode, OpenCode или Pi параллельно — каждый в своём рабочем дереве, все под контролем в одном месте. +

+ +

Скачать Orca

+ +

+ Настольное приложение Orca с агентами в параллельных рабочих деревьях и мобильным приложением Orca в углу +

+ +## Возможности + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +### Мобильное приложение + +Следите за агентами и направляйте их работу с телефона — получайте уведомления о завершении задач и отправляйте дополнительные указания откуда угодно. + +[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) + + + Настольное и мобильное приложения Orca +
+ +### Параллельные рабочие деревья + +Отправьте один запрос пяти агентам, каждый из которых работает в своём изолированном рабочем дереве 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) + + + Работа с задачами GitHub и Linear в Orca +
+ +### Рабочие деревья по SSH + +Запускайте агентов на мощном удалённом сервере с полноценным редактированием файлов, работой с Git и терминалами — автоматическое переподключение и перенаправление портов уже предусмотрены. + +[Документация →](https://www.onorca.dev/docs/ssh) + + + Удалённые рабочие деревья по 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) + + + Автоматизация Orca через CLI +
+ +**А ещё:** + +- **[Быстрое открытие](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 Claude Code   + Логотип Codex Codex   + Логотип Grok Grok   + Логотип Cursor Cursor   + Логотип GitHub Copilot GitHub Copilot   + Логотип Muse Muse   + Логотип DeepSeek Harness DeepSeek Harness   + Логотип ZCode ZCode   + Логотип OpenCode OpenCode   + Логотип MiMo Code MiMo Code   + Логотип Amp Amp   + Логотип OpenClaude OpenClaude   + Логотип Antigravity Antigravity   + Логотип Pi Pi   + Логотип oh-my-pi oh-my-pi   + Логотип Hermes Agent Hermes Agent   + Логотип Devin Devin   + Логотип Goose Goose   + Логотип Auggie Auggie   + Логотип Autohand Code Autohand Code   + Логотип Charm Charm   + Логотип Cline Cline   + Логотип CodeBuddy CodeBuddy   + Логотип Codebuff Codebuff   + Логотип Freebuff Freebuff   + Логотип Command Code Command Code   + Логотип Continue Continue   + Логотип Droid Droid   + Логотип Kilocode Kilocode   + Логотип Kimi Kimi   + Логотип Kiro Kiro   + Логотип Mistral Vibe Mistral Vibe   + Логотип Qwen Code Qwen Code   + Логотип Rovo Dev 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. + + 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 и руководством по настройке. + + + Участники проекта Orca + + +

+ График числа звёзд stablyai/orca на GitHub +

+ +## Подписанные сборки + +Подписание кода для 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 logosu oh-my-pi   Hermes Agent logosu Hermes Agent   Devin logosu Devin   - Goose logosu Goose   + Goose logosu Goose   Auggie logosu Auggie   Autohand Code logosu Autohand Code   Charm logosu Charm   @@ -199,7 +199,7 @@ Orca'yı ajanlar da kullanır - her akışı `orca worktree create`, `snapshot`, Codebuff logosu Codebuff   Freebuff logosu Freebuff   Command Code logosu Command Code   - Continue logosu Continue   + Continue logosu Continue   Droid logosu Droid   Kilocode logosu Kilocode   Kimi logosu 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 = [''] + const active = tab(7, 'https://site.test/') + mocks.tabs = [active] + await capture() + await captureAs({ fromWorker: true }) + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + await expect(captureAs({ fromWorker: true })).rejects.toThrow(QUOTA_ERROR) + const extension = { ...caller.extension, id: 'b'.repeat(32) } + await captureAs({ extension }) + await captureAs({ extension, fromWorker: true }) + await expect(captureAs({ extension })).rejects.toThrow(QUOTA_ERROR) + const separate = createCaller() + try { + await captureAs(separate) + await captureAs({ ...separate, fromWorker: true }) + await expect(captureAs(separate)).rejects.toThrow(QUOTA_ERROR) + } finally { + forgetHostSession(separate.session) + } + expect(active.contents.capturePage).toHaveBeenCalledTimes(6) + }) + + it('resets the fixed window only after its deadline, independent of the second call', async () => { + mocks.hostPatterns = [''] + mocks.tabs = [tab(7, 'https://site.test/')] + const clock = vi.mocked(performance.now) + await capture() + clock.mockReturnValue(800) + await capture() + clock.mockReturnValue(1_000) + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + clock.mockReturnValue(1_000.001) + await capture() + await capture() + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + }) + + it('exempts trusted user gestures without spending or refilling ordinary admission', async () => { + mocks.hostPatterns = [''] + const active = tab(7, 'https://site.test/') + mocks.tabs = [active] + for (let count = 0; count < 5; count++) { + await captureAs({ userGesture: true }) + } + await capture() + await capture() + await expect(capture({ userGesture: true })).rejects.toThrow(QUOTA_ERROR) + await captureAs({ userGesture: true }) + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + expect(active.contents.capturePage).toHaveBeenCalledTimes(8) + }) + + it('preserves pre-capture failures without charging admission', async () => { + mocks.tabs = [tab(7, 'https://site.test/')] + await expect(capture()).rejects.toThrow('permission is required') + mocks.hostPatterns = [''] + await expect(capture({ quality: 101 })).rejects.toThrow('Invalid arguments') + await expect(capture(99)).rejects.toThrow('No window with id: 99.') + await capture() + await capture() + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + }) + + it('charges failed native work and recovers after the window expires', async () => { + mocks.hostPatterns = [''] + const clock = vi.mocked(performance.now) + const image = fakeImage(true) + const active = tab(7, 'https://site.test/', 1, image) + mocks.tabs = [active] + active.contents.capturePage.mockRejectedValueOnce(new Error('native capture rejected')) + await expect(capture()).rejects.toThrow('native capture rejected') + await expect(capture()).rejects.toThrow('Internal error while trying to capture') + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + expect(active.contents.capturePage).toHaveBeenCalledTimes(2) + expect(image.toJPEG).not.toHaveBeenCalled() + clock.mockReturnValue(1_000.001) + mocks.tabs = [tab(8, 'https://site.test/')] + await expect(capture()).resolves.toMatch(/^data:image\/jpeg;base64,/) + }) + + it('renews admission after extension unload and host replacement', async () => { + mocks.hostPatterns = [''] + mocks.tabs = [tab(7, 'https://site.test/')] + await capture() + await captureAs({ fromWorker: true }) + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + forgetExtensionContexts(caller.session, EXTENSION_ID) + await captureAs({ fromWorker: true }) + await capture() + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + forgetHostSession(caller.session) + await expect(capture()).rejects.toThrow('Not an extension context') + ensureHostSessionState(caller.session, 'replacement') + await capture() + await captureAs({ fromWorker: true }) + await expect(capture()).rejects.toThrow(QUOTA_ERROR) + }) + + it('releases hidden-page paint when capture fails', async () => { + mocks.hostPatterns = [''] + const active = tab(7, 'https://site.test/') + active.contents.capturePage.mockRejectedValueOnce(new Error('capture failed')) + mocks.tabs = [active] + + await expect(capture()).rejects.toThrow('capture failed') + + expect(mocks.holdPaint).toHaveBeenCalledWith(7) + expect(mocks.releasePaint).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/main/browser/extensions/api/tabs-capture.ts b/src/main/browser/extensions/api/tabs-capture.ts index ee9464b948e..8c606402323 100644 --- a/src/main/browser/extensions/api/tabs-capture.ts +++ b/src/main/browser/extensions/api/tabs-capture.ts @@ -1,4 +1,6 @@ import { z } from 'zod' +import { browserManager } from '../../browser-manager' +import { consumeBrowserExtensionCaptureQuota } from '../browser-extension-capture-quota' import { parseChromeExtensionUrl } from '../../../../shared/browser-extension-url' import { isChromeWebStoreUrl } from '../../../../shared/browser-extension-webstore' import { hasBrowserExtensionActiveTab } from '../browser-extension-active-tab' @@ -74,7 +76,14 @@ async function captureVisibleTab( if (denial) { throw new BrowserExtensionApiError(denial) } - const image = await tab.contents.capturePage() + consumeBrowserExtensionCaptureQuota(caller) + const releasePaint = browserManager.holdPaintForCapture(tab.contents.id) + let image: Electron.NativeImage + try { + image = await tab.contents.capturePage() + } finally { + releasePaint() + } if (image.isEmpty()) { throw new BrowserExtensionApiError( 'Internal error while trying to capture visible region of the current tab' diff --git a/src/main/browser/extensions/browser-extension-action-registry.ts b/src/main/browser/extensions/browser-extension-action-registry.ts index c832a76aee3..0520c3da580 100644 --- a/src/main/browser/extensions/browser-extension-action-registry.ts +++ b/src/main/browser/extensions/browser-extension-action-registry.ts @@ -82,6 +82,10 @@ export function getBrowserExtensionActionState( return state } +export function forgetBrowserExtensionActionProfile(profileId: string): void { + stateByProfileId.delete(profileId) +} + /** A tab's action overrides end when it loads a new document or closes (Chrome semantics). */ export function forgetBrowserExtensionActionTab(profileId: string, tabId: number): void { let changed = false diff --git a/src/main/browser/extensions/browser-extension-api-host.test.ts b/src/main/browser/extensions/browser-extension-api-host.test.ts index 878f4349f44..8546b9e99dc 100644 --- a/src/main/browser/extensions/browser-extension-api-host.test.ts +++ b/src/main/browser/extensions/browser-extension-api-host.test.ts @@ -1,10 +1,14 @@ +import { EventEmitter } from 'node:events' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeAll, describe, expect, it, vi } from 'vitest' import { z } from 'zod' +type PortStub = EventEmitter & { close: ReturnType; start: ReturnType } + const mocks = vi.hoisted(() => ({ + channels: new Array<{ port1: PortStub; port2: PortStub }>(), userData: '', prompt: vi.fn<() => Promise>(), handlers: new Map< @@ -17,22 +21,37 @@ const mocks = vi.hoisted(() => ({ >() })) -vi.mock('electron', () => ({ - app: { on: vi.fn(), getPath: () => mocks.userData }, - BrowserWindow: vi.fn(), - session: { fromPartition: vi.fn() }, - webContents: { fromId: vi.fn() }, - ipcMain: { - removeHandler: (channel: string) => mocks.handlers.delete(channel), - handle: ( - channel: string, - handler: (event: unknown, request: unknown, userGesture?: boolean) => Promise - ) => mocks.handlers.set(channel, handler) - }, - webFrameMain: { - fromId: (processId: number, routingId: number) => mocks.frames.get(`${processId}:${routingId}`) +vi.mock('electron', async () => { + const { EventEmitter } = await import('node:events') + class Port extends EventEmitter { + close = vi.fn(() => this.emit('close')) + start = vi.fn() } -})) + return { + MessageChannelMain: class { + port1 = new Port() + port2 = new Port() + constructor() { + mocks.channels.push(this) + } + }, + app: { on: vi.fn(), getPath: () => mocks.userData }, + BrowserWindow: vi.fn(), + session: { fromPartition: vi.fn() }, + webContents: { fromId: vi.fn() }, + ipcMain: { + removeHandler: (channel: string) => mocks.handlers.delete(channel), + handle: ( + channel: string, + handler: (event: unknown, request: unknown, userGesture?: boolean) => Promise + ) => mocks.handlers.set(channel, handler) + }, + webFrameMain: { + fromId: (processId: number, routingId: number) => + mocks.frames.get(`${processId}:${routingId}`) + } + } +}) vi.mock('../browser-manager', () => ({ browserManager: {} })) vi.mock('../../ipc/browser-tab-registration-wait', () => ({ waitForTabRegistration: vi.fn() })) vi.mock('../../runtime/browser/browser-tab-renderer-create', () => ({ @@ -47,11 +66,15 @@ vi.mock('./browser-extension-permission-prompt', () => ({ })) mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-api-host-')) -const { BROWSER_EXTENSION_EVENT_CHANNEL, BROWSER_EXTENSION_INVOKE_CHANNEL } = - await import('../../../shared/browser-extension-channels') +const { + BROWSER_EXTENSION_EVENT_CHANNEL, + BROWSER_EXTENSION_INVOKE_CHANNEL, + BROWSER_EXTENSION_FRAME_LIFETIME_CHANNEL +} = await import('../../../shared/browser-extension-channels') const surface = await import('../../../preload/browser-extension-api-surface') const registry = await import('./browser-extension-namespace-registry') const host = await import('./browser-extension-api-host') +const contexts = await import('./browser-extension-contexts') const { registerBrowserExtensionNamespaces } = await import('./register-browser-extension-namespaces') @@ -85,11 +108,22 @@ function frameEvent( // Node reports "null" for chrome-extension: URLs; Chromium reports the real extension origin. origin = url.split('/').slice(0, 3).join('/') ) { - const frame = { url, origin, processId, routingId, isDestroyed: () => false, send: vi.fn() } + const frame = { + url, + origin, + processId, + routingId, + isDestroyed: () => false, + send: vi.fn(), + postMessage: vi.fn() + } mocks.frames.set(`${processId}:${routingId}`, frame) return { frame, - event: { senderFrame: frame, sender: { id: 77, session: sess, once: vi.fn() } } + event: { + senderFrame: frame, + sender: Object.assign(new EventEmitter(), { id: 77, session: sess }) + } } } @@ -128,6 +162,9 @@ describe('preload API surface', () => { it('pins the preload channel copies to the ones main listens on', () => { expect(surface.PRELOAD_BROWSER_EXTENSION_INVOKE_CHANNEL).toBe(BROWSER_EXTENSION_INVOKE_CHANNEL) expect(surface.PRELOAD_BROWSER_EXTENSION_EVENT_CHANNEL).toBe(BROWSER_EXTENSION_EVENT_CHANNEL) + expect(surface.PRELOAD_BROWSER_EXTENSION_FRAME_LIFETIME_CHANNEL).toBe( + BROWSER_EXTENSION_FRAME_LIFETIME_CHANNEL + ) }) it('installs exactly what main registers, under the same permission', () => { @@ -261,3 +298,287 @@ describe('extension API host', () => { expect(listening.frame.send).toHaveBeenCalledTimes(1) }) }) + +describe('extension frame document ownership', () => { + const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } + + it.each(['did-navigate', 'render-process-gone', 'destroyed'])( + 'retires %s listeners while preserving other owners', + async (retirement) => { + const original = frameEvent( + `chrome-extension://${EXTENSION_ID}/page.html`, + extensionSession, + 6, + 1 + ) + const sibling = frameEvent( + `chrome-extension://${EXTENSION_ID}/sibling.html`, + extensionSession, + 6, + 2 + ) + sibling.event.sender.id = 88 + await expect(invoke(original.event, listen)).resolves.toEqual({ ok: true, value: undefined }) + await invoke(sibling.event, listen) + if (retirement === 'destroyed') { + for (const property of ['session', 'id']) { + Object.defineProperty(original.event.sender, property, { + get: () => { + throw new TypeError('Object has been destroyed') + } + }) + } + } + original.event.sender.emit(retirement) + host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['after retirement']) + expect(original.frame.send).not.toHaveBeenCalled() + expect(sibling.frame.send).toHaveBeenCalledTimes(1) + for (const event of ['did-navigate', 'render-process-gone', 'destroyed']) { + expect(original.event.sender.listenerCount(event)).toBe(0) + } + if (retirement !== 'destroyed') { + const successor = frameEvent( + `chrome-extension://${EXTENSION_ID}/new.html`, + extensionSession, + 6, + 3 + ) + successor.event.sender = original.event.sender + await invoke(successor.event, listen) + host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['successor']) + expect(successor.frame.send).toHaveBeenCalledTimes(1) + expect(original.frame.send).not.toHaveBeenCalled() + expect(sibling.frame.send).toHaveBeenCalledTimes(2) + successor.event.sender.emit('destroyed') + } + sibling.event.sender.emit('destroyed') + } + ) + + it('keeps the current document on same-document and uncommitted navigation', async () => { + const current = frameEvent( + `chrome-extension://${EXTENSION_ID}/page.html`, + extensionSession, + 7, + 1 + ) + await invoke(current.event, listen) + current.event.sender.emit('did-navigate-in-page') + current.event.sender.emit('will-navigate') + host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['current']) + expect(current.frame.send).toHaveBeenCalledTimes(1) + current.event.sender.emit('destroyed') + }) + + it('stops the listener precheck after the last listening document is replaced', async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary exposes the extensions, serviceWorkers and protocol members consumed by the actual host. + const isolated = { ...extensionSession } as unknown as Electron.Session + host.attachBrowserExtensionApiHostToSession(isolated, 'isolated') + const current = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 8, 1) + await invoke(current.event, { ...listen, filters: [{ urls: ['https://never.invalid/*'] }] }) + expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(true) + current.event.sender.emit('did-navigate') + expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(false) + expect(contexts.getHostSessionState(isolated)?.frames.size).toBe(0) + host.forgetBrowserExtensionContexts(isolated) + }) +}) + +it('keeps service-worker event ownership when a page document is replaced', async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary copies the extensions, serviceWorkers and protocol members consumed by the actual host. + const isolated = { ...extensionSession } as unknown as Electron.Session + host.attachBrowserExtensionApiHostToSession(isolated, 'worker-survives') + const state = contexts.getHostSessionState(isolated) + expect(state).not.toBeNull() + if (!state) { + throw new Error('Session host was not attached') + } + const worker = contexts.ensureWorkerContext( + state, + EXTENSION_ID, + `chrome-extension://${EXTENSION_ID}/` + ) + worker.events.add('probe.onPing') + const stream = { send: vi.fn(), close: vi.fn() } + worker.stream = stream + const page = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 9, 1) + await invoke(page.event, { type: 'listen', namespace: 'probe', event: 'onPing', active: true }) + page.event.sender.emit('did-navigate') + host.emitBrowserExtensionEvent({ session: isolated }, 'probe', 'onPing', ['worker']) + expect(page.frame.send).not.toHaveBeenCalled() + expect(stream.send).toHaveBeenCalledTimes(1) + expect(stream.close).not.toHaveBeenCalled() + host.forgetBrowserExtensionContexts(isolated) +}) + +it('retires the current host after extension support restarts in the same document', async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary copies the extensions, serviceWorkers and protocol members consumed by the actual host. + const isolated = { ...extensionSession } as unknown as Electron.Session + host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') + const current = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 10, 1) + const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } + await invoke(current.event, listen) + host.forgetBrowserExtensionContexts(isolated) + host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') + await invoke(current.event, listen) + current.event.sender.emit('did-navigate') + expect(contexts.getHostSessionState(isolated)?.frames.size).toBe(0) + expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(false) + host.forgetBrowserExtensionContexts(isolated) +}) + +describe('extension subframe listener retirement', () => { + const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } + + function isolatedSession() { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: host calls use the copied session members already exercised by the host fixtures. + const sess = { ...extensionSession } as unknown as Electron.Session + host.attachBrowserExtensionApiHostToSession(sess, 'subframes') + const state = contexts.getHostSessionState(sess) + if (!state) { + throw new Error('Missing session host') + } + return { sess, state } + } + + function channel() { + const current = mocks.channels.at(-1) + if (!current) { + throw new Error('Listening frame did not acquire a native port') + } + return current + } + + it('retires a detached filtered frame without dispatch or document navigation', async () => { + const { sess, state } = isolatedSession() + const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 20, 1) + await invoke(page.event, { ...listen, filters: [{ urls: ['https://never.invalid/*'] }] }) + expect(contexts.browserExtensionEventHasListener(sess, 'probe', 'onPing')).toBe(true) + channel().port1.emit('close') + expect(state.frames.size).toBe(0) + expect(contexts.browserExtensionEventHasListener(sess, 'probe', 'onPing')).toBe(false) + host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', ['removed']) + expect(page.frame.send).not.toHaveBeenCalled() + host.forgetBrowserExtensionContexts(sess) + }) + + it('shares one port across listeners and replaces it after final removal', async () => { + const { sess, state } = isolatedSession() + const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 21, 1) + await invoke(page.event, listen) + const first = channel() + const lateClose = first.port1.listeners('close')[0] + await invoke(page.event, listen) + await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated' }) + expect(page.frame.postMessage).toHaveBeenCalledTimes(1) + await invoke(page.event, { ...listen, active: false }) + expect(state.frames.size).toBe(1) + expect(first.port1.close).not.toHaveBeenCalled() + await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated', active: false }) + expect(state.frames.size).toBe(0) + expect(first.port1.close).toHaveBeenCalledTimes(1) + expect(first.port1.listenerCount('close')).toBe(0) + await invoke(page.event, listen) + expect(channel()).not.toBe(first) + lateClose?.() + host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', ['successor']) + expect(page.frame.send).toHaveBeenCalledTimes(1) + expect(state.frames.size).toBe(1) + host.forgetBrowserExtensionContexts(sess) + }) + + it('preserves sibling frames, windows, sessions and worker listeners', async () => { + const { sess, state } = isolatedSession() + const elsewhere = isolatedSession() + const removed = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 1) + const sibling = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 2) + sibling.event.sender = removed.event.sender + const window = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, sess, 22, 3) + window.event.sender.id = 78 + const other = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, elsewhere.sess, 23, 1) + await invoke(removed.event, listen) + const owner = channel() + await invoke(sibling.event, listen) + await invoke(window.event, listen) + await invoke(other.event, listen) + const worker = contexts.ensureWorkerContext( + state, + EXTENSION_ID, + `chrome-extension://${EXTENSION_ID}/` + ) + worker.events.add('probe.onPing') + worker.stream = { send: vi.fn(), close: vi.fn() } + owner.port1.emit('close') + host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['survivors']) + expect(removed.frame.send).not.toHaveBeenCalled() + for (const frame of [sibling.frame, window.frame, other.frame]) { + expect(frame.send).toHaveBeenCalledTimes(1) + } + expect(worker.stream.send).toHaveBeenCalledTimes(1) + expect(worker.stream.close).not.toHaveBeenCalled() + expect(state.frames.size).toBe(2) + expect(elsewhere.state.frames.size).toBe(1) + host.forgetBrowserExtensionContexts(sess) + host.forgetBrowserExtensionContexts(elsewhere.sess) + }) + + it.each([ + 'did-navigate', + 'render-process-gone', + 'destroyed', + 'extension-unloaded', + 'host-forgotten', + 'invalid-frame', + 'failed-send' + ])('closes a frame port exactly once on %s', async (retirement) => { + const { sess, state } = isolatedSession() + const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 24, 1) + await invoke(page.event, listen) + const owner = channel() + if (retirement === 'extension-unloaded') { + contexts.forgetExtensionContexts(sess, EXTENSION_ID) + } else if (retirement === 'host-forgotten') { + host.forgetBrowserExtensionContexts(sess) + } else if (retirement === 'invalid-frame') { + mocks.frames.delete('24:1') + host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', []) + } else if (retirement === 'failed-send') { + page.frame.send.mockImplementation(() => { + throw new Error('Frame retired') + }) + host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', []) + } else { + page.event.sender.emit(retirement) + } + expect(state.frames.size).toBe(0) + expect(owner.port1.close).toHaveBeenCalledTimes(1) + expect(owner.port1.listenerCount('close')).toBe(0) + page.event.sender.emit('destroyed') + host.forgetBrowserExtensionContexts(sess) + expect(owner.port1.close).toHaveBeenCalledTimes(1) + }) + + it('releases both endpoints and the registry when frame transfer fails', async () => { + const { sess, state } = isolatedSession() + const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 25, 1) + page.frame.postMessage.mockImplementation(() => { + throw new Error('Frame retired before transfer') + }) + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + await expect(invoke(page.event, listen)).resolves.toEqual({ + ok: false, + error: 'Frame retired before transfer' + }) + const owner = channel() + expect(state.frames.size).toBe(0) + expect(contexts.browserExtensionEventHasListener(sess, 'probe', 'onPing')).toBe(false) + expect(owner.port1.close).toHaveBeenCalledTimes(1) + expect(owner.port2.close).toHaveBeenCalledTimes(1) + expect(owner.port1.listenerCount('close')).toBe(0) + } finally { + warning.mockRestore() + host.forgetBrowserExtensionContexts(sess) + } + }) +}) diff --git a/src/main/browser/extensions/browser-extension-api-namespaces.test.ts b/src/main/browser/extensions/browser-extension-api-namespaces.test.ts index 14f405b1181..8be68b3c1e6 100644 --- a/src/main/browser/extensions/browser-extension-api-namespaces.test.ts +++ b/src/main/browser/extensions/browser-extension-api-namespaces.test.ts @@ -19,6 +19,10 @@ const mocks = vi.hoisted(() => ({ })) vi.mock('electron', () => ({ + MessageChannelMain: class { + port1 = Object.assign(new EventEmitter(), { start: vi.fn(), close: vi.fn() }) + port2 = { close: vi.fn() } + }, app: { on: vi.fn(), getPath: () => mocks.userData }, BrowserWindow: vi.fn(), Notification: { isSupported: () => false }, @@ -819,11 +823,15 @@ async function listenFrame(extensionId: string, namespace: string, event: string processId: 3, routingId, isDestroyed: () => false, - send: vi.fn() + send: vi.fn(), + postMessage: vi.fn() } mocks.frames.set(`3:${routingId}`, frame) await mocks.handlers.get(BROWSER_EXTENSION_INVOKE_CHANNEL)?.( - { senderFrame: frame, sender: { id: 40 + routingId, session, once: vi.fn() } }, + { + senderFrame: frame, + sender: Object.assign(new EventEmitter(), { id: 40 + routingId, session }) + }, { type: 'listen', namespace, event, active: true } ) return { diff --git a/src/main/browser/extensions/browser-extension-capture-quota.ts b/src/main/browser/extensions/browser-extension-capture-quota.ts new file mode 100644 index 00000000000..dec384d6858 --- /dev/null +++ b/src/main/browser/extensions/browser-extension-capture-quota.ts @@ -0,0 +1,38 @@ +import { getBrowserExtensionContextSignal } from './browser-extension-context-lifetime' +import { getHostSessionState } from './browser-extension-contexts' +import { + BrowserExtensionApiError, + type BrowserExtensionCaller +} from './browser-extension-namespace-registry' + +export const MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND = 2 +const QUOTA_INTERVAL_MS = 1_000 + +type CaptureQuota = { expiresAt: number; remaining: number } +const quotaByLifetime = new WeakMap() + +export function consumeBrowserExtensionCaptureQuota(caller: BrowserExtensionCaller): void { + const state = getHostSessionState(caller.session) + if (!state) { + throw new BrowserExtensionApiError('Not an extension context') + } + if (caller.userGesture) { + return + } + const lifetime = getBrowserExtensionContextSignal(state, caller.extension.id) + const now = performance.now() + let quota = quotaByLifetime.get(lifetime) + if (!quota || now > quota.expiresAt) { + quota = { + expiresAt: now + QUOTA_INTERVAL_MS, + remaining: MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND + } + quotaByLifetime.set(lifetime, quota) + } + if (quota.remaining === 0) { + throw new BrowserExtensionApiError( + 'This request exceeds the MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND quota.' + ) + } + quota.remaining -= 1 +} diff --git a/src/main/browser/extensions/browser-extension-contexts.ts b/src/main/browser/extensions/browser-extension-contexts.ts index a1c475c6709..ffef07302ec 100644 --- a/src/main/browser/extensions/browser-extension-contexts.ts +++ b/src/main/browser/extensions/browser-extension-contexts.ts @@ -1,4 +1,10 @@ import { forgetBrowserExtensionContextLifetime } from './browser-extension-context-lifetime' +import { + createBrowserExtensionFrameContext, + forgetBrowserExtensionFrame, + trackBrowserExtensionDocument, + type FrameContext +} from './browser-extension-frame-lifetime' import { webFrameMain } from 'electron' import { BROWSER_EXTENSION_EVENT_CHANNEL, @@ -17,15 +23,6 @@ import { type WorkerEventStream } from './browser-extension-worker-event-stream' -type FrameContext = { - extensionId: string - webContentsId: number - processId: number - routingId: number - events: Set - filters: ListenerFilters -} - /** Event key → every listener's filter; absent when some listener takes everything. */ export type ListenerFilters = Map @@ -49,7 +46,6 @@ export type HostSessionState = { } const stateBySession = new Map() -const trackedWebContents = new WeakSet() export function eventKey(namespace: string, event: string): string { return `${namespace}.${event}` @@ -72,8 +68,14 @@ export function ensureHostSessionState( } export function forgetHostSession(sess: Electron.Session): void { - forgetBrowserExtensionContextLifetime(stateBySession.get(sess)) - for (const context of stateBySession.get(sess)?.workers.values() ?? []) { + const state = stateBySession.get(sess) + forgetBrowserExtensionContextLifetime(state) + if (state) { + for (const [key, context] of state.frames) { + forgetBrowserExtensionFrame(state.frames, key, context) + } + } + for (const context of state?.workers.values() ?? []) { detachWorkerEventStream(context) } stateBySession.delete(sess) @@ -92,7 +94,7 @@ export function forgetExtensionContexts(sess: Electron.Session, extensionId: str state.workers.delete(extensionId) for (const [key, frame] of state.frames) { if (frame.extensionId === extensionId) { - state.frames.delete(key) + forgetBrowserExtensionFrame(state.frames, key, frame) } } } @@ -134,15 +136,13 @@ export function setFrameListening( if (!active) { return } - context = { + context = createBrowserExtensionFrameContext( + state.frames, + frameKey, extensionId, - webContentsId: webContents.id, - processId: frame.processId, - routingId: frame.routingId, - events: new Set(), - filters: new Map() - } - state.frames.set(frameKey, context) + webContents.id, + frame + ) } if (active) { context.events.add(key) @@ -150,18 +150,11 @@ export function setFrameListening( context.events.delete(key) } setListenerFilters(context.filters, key, active ? filters : undefined) - if (!trackedWebContents.has(webContents)) { - trackedWebContents.add(webContents) - webContents.once('destroyed', () => { - for (const sessionState of stateBySession.values()) { - for (const [candidateKey, candidate] of sessionState.frames) { - if (candidate.webContentsId === webContents.id) { - sessionState.frames.delete(candidateKey) - } - } - } - }) + if (context.events.size === 0) { + forgetBrowserExtensionFrame(state.frames, frameKey, context) } + const webSession = webContents.session + trackBrowserExtensionDocument(webContents, () => stateBySession.get(webSession)?.frames) } export function setListenerFilters( @@ -205,11 +198,8 @@ export function dispatchToWorkerWhenListening( return } const key = eventKey(namespace, event) - const context = ensureWorkerContext( - state, - extensionId, - `${getChromeExtensionOrigin(extensionId)}/` - ) + const scope = `${getChromeExtensionOrigin(extensionId)}/` + const context = ensureWorkerContext(state, extensionId, scope) const payload: BrowserExtensionEventPayload = { namespace, event, args } if (context.events.has(key)) { deliverToWorker(sess, context, key, payload, startWorker) @@ -242,13 +232,13 @@ function deliverToFrames( const frame = webFrameMain.fromId(context.processId, context.routingId) // Why: a frame that navigated away from the extension must stop receiving its events. if (!frame || frame.isDestroyed() || !frame.url.startsWith(origin)) { - state.frames.delete(frameKey) + forgetBrowserExtensionFrame(state.frames, frameKey, context) continue } try { frame.send(BROWSER_EXTENSION_EVENT_CHANNEL, payload) } catch { - state.frames.delete(frameKey) + forgetBrowserExtensionFrame(state.frames, frameKey, context) } } } diff --git a/src/main/browser/extensions/browser-extension-frame-lifetime.ts b/src/main/browser/extensions/browser-extension-frame-lifetime.ts new file mode 100644 index 00000000000..65bffcbae53 --- /dev/null +++ b/src/main/browser/extensions/browser-extension-frame-lifetime.ts @@ -0,0 +1,90 @@ +import { MessageChannelMain } from 'electron' +import { BROWSER_EXTENSION_FRAME_LIFETIME_CHANNEL } from '../../../shared/browser-extension-channels' +import { abortWhenRendererGone } from '../../ipc/renderer-lifetime-abort' + +export type FrameContext = { + extensionId: string + webContentsId: number + processId: number + routingId: number + events: Set + filters: Map + dispose: () => void +} + +const trackedWebContents = new WeakSet() + +export function forgetBrowserExtensionFrame( + frames: Map, + key: string, + context: FrameContext +): void { + if (frames.get(key) !== context) { + return + } + frames.delete(key) + context.dispose() +} + +export function createBrowserExtensionFrameContext( + frames: Map, + key: string, + extensionId: string, + webContentsId: number, + frame: Electron.WebFrameMain +): FrameContext { + const { port1, port2 } = new MessageChannelMain() + let disposed = false + const retire = (): void => forgetBrowserExtensionFrame(frames, key, context) + const context: FrameContext = { + extensionId, + webContentsId, + processId: frame.processId, + routingId: frame.routingId, + events: new Set(), + filters: new Map(), + dispose: () => { + if (disposed) { + return + } + disposed = true + port1.removeListener('close', retire) + port1.close() + } + } + frames.set(key, context) + port1.once('close', retire) + try { + port1.start() + // Native frame teardown closes the peer without needing an unload callback. + frame.postMessage(BROWSER_EXTENSION_FRAME_LIFETIME_CHANNEL, null, [port2]) + } catch (error) { + forgetBrowserExtensionFrame(frames, key, context) + port2.close() + throw error + } + return context +} + +export function trackBrowserExtensionDocument( + webContents: Electron.WebContents, + currentFrames: () => Map | undefined +): void { + if (trackedWebContents.has(webContents)) { + return + } + trackedWebContents.add(webContents) + const webContentsId = webContents.id + abortWhenRendererGone(webContents).signal.addEventListener('abort', () => { + trackedWebContents.delete(webContents) + const frames = currentFrames() + if (!frames) { + return + } + for (const [key, context] of frames) { + if (context.webContentsId === webContentsId) { + forgetBrowserExtensionFrame(frames, key, context) + } + } + }) +} diff --git a/src/main/browser/extensions/browser-extension-install-prompt.ts b/src/main/browser/extensions/browser-extension-install-prompt.ts index 3dc3dba1875..bdacf6c7c74 100644 --- a/src/main/browser/extensions/browser-extension-install-prompt.ts +++ b/src/main/browser/extensions/browser-extension-install-prompt.ts @@ -47,8 +47,8 @@ export function requestBrowserExtensionInstallPrompt( for (const contents of watched) { contents.removeListener('destroyed', decline) contents.removeListener('render-process-gone', decline) + contents.removeListener('did-navigate', decline) } - guest?.removeListener('did-navigate', decline) try { if (!renderer.isDestroyed()) { renderer.send(BROWSER_EXTENSION_INSTALL_PROMPT_CLOSED_CHANNEL, { requestId }) @@ -63,9 +63,9 @@ export function requestBrowserExtensionInstallPrompt( for (const contents of watched) { contents.once('destroyed', decline) contents.once('render-process-gone', decline) + // Why did-navigate: committed top-frame documents only, not store or Settings SPA routes. + contents.once('did-navigate', decline) } - // Why did-navigate: it fires only for committed cross-document top-frame loads, not store SPA routes. - guest?.once('did-navigate', decline) try { renderer.send(BROWSER_EXTENSION_INSTALL_PROMPT_REQUESTED_CHANNEL, { ...prompt, requestId }) } catch { diff --git a/src/main/browser/extensions/browser-extension-session-loader.test.ts b/src/main/browser/extensions/browser-extension-session-loader.test.ts index 2b8d8de9054..494cd7f660e 100644 --- a/src/main/browser/extensions/browser-extension-session-loader.test.ts +++ b/src/main/browser/extensions/browser-extension-session-loader.test.ts @@ -81,6 +81,7 @@ vi.mock('node:fs', async (importOriginal) => ({ vi.mock('./browser-extension-api-host', () => ({ attachBrowserExtensionApiHostToSession: vi.fn(), forgetBrowserExtensionContexts: vi.fn(), + getBrowserExtensionProfileIdForSession: vi.fn(() => null), emitBrowserExtensionWorkerStartEvent: mocks.emitWorkerStart })) vi.mock('./browser-extension-load-directory', () => ({ @@ -106,6 +107,7 @@ const { getBrowserExtensionProfileStateStore } = const { getBrowserExtensionSyncStorageStore } = await import('./browser-extension-sync-storage-store') const { getBrowserExtensionInstallStore } = await import('./browser-extension-install-store') +const { getBrowserExtensionActionState } = await import('./browser-extension-action-registry') const realFs = await vi.importActual('node:fs') const installed = { @@ -372,6 +374,67 @@ describe('profile changes while startup loads are in flight', () => { }) }) +describe('deleted profile action state', () => { + it.each([ + ['unattached', false, false], + ['attached', true, false], + ['failed-unload', true, true] + ] as const)('retires action payloads for %s', async (label, attached, failedUnload) => { + const profileId = `action-retirement-${label}` + const profile = { + id: profileId, + scope: 'isolated' as const, + partition: `persist:orca-${profileId}`, + label: 'Retired', + source: null + } + const extension = { + id: ID, + name: 'Vault', + path: installed.path, + url: `chrome-extension://${ID}/`, + version: installed.version, + manifest: { action: { default_title: 'Fresh' } } + } + setBrowserExtensionSupportEnabled(true) + if (attached) { + loader.attachBrowserExtensionsToProfileSession(profile, []) + await loader.whenBrowserExtensionProfileLoaded(profileId) + } + const removed = getBrowserExtensionActionState(profileId, extension) + removed.set('title', 'Retired title') + removed.set('icon', { kind: 'data', dataUrl: 'data:image/png;base64,retired' }) + removed.set('badgeText', 'Retired tab badge', 77) + const survivor = getBrowserExtensionActionState(`survivor-${profileId}`, extension) + survivor.set('title', 'Surviving title') + + if (failedUnload) { + mocks.loaded.set(ID, { id: ID }) + const unload = vi + .spyOn(mocks.session.extensions, 'removeExtension') + .mockImplementationOnce(() => { + throw new Error('native unload failed') + }) + try { + await expect(loader.detachBrowserExtensionsFromProfileSession(profile)).rejects.toThrow( + 'native unload failed' + ) + } finally { + unload.mockRestore() + mocks.loaded.delete(ID) + } + } else { + await loader.detachBrowserExtensionsFromProfileSession(profile) + } + + const fresh = getBrowserExtensionActionState(profileId, extension) + expect(fresh).not.toBe(removed) + expect(fresh.get(77)).toMatchObject({ title: 'Fresh', icon: null, badgeText: '' }) + expect(getBrowserExtensionActionState(`survivor-${profileId}`, extension)).toBe(survivor) + expect(survivor.get().title).toBe('Surviving title') + }) +}) + it('does not restore stale enablement after uninstall and reinstall in another Orca profile', async () => { setBrowserExtensionSupportEnabled(true) await loader.detachBrowserExtensionsFromAllProfileSessions() diff --git a/src/main/browser/extensions/browser-extension-session-loader.ts b/src/main/browser/extensions/browser-extension-session-loader.ts index 143c59fcc02..e1c6d9b00a8 100644 --- a/src/main/browser/extensions/browser-extension-session-loader.ts +++ b/src/main/browser/extensions/browser-extension-session-loader.ts @@ -1,4 +1,5 @@ import { session } from 'electron' +import { forgetBrowserExtensionActionProfile } from './browser-extension-action-registry' import { existsSync } from 'node:fs' import { join } from 'node:path' import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' @@ -168,8 +169,12 @@ export async function detachBrowserExtensionsFromProfileSession( await retireBrowserExtensionProfileStorage(sess, profile.partition).catch((error: unknown) => { console.warn('[browser-extensions] Could not clear deleted profile storage:', error) }) - if (state) { - await unloadProfileSession(state) + try { + if (state) { + await unloadProfileSession(state) + } + } finally { + forgetBrowserExtensionActionProfile(profile.id) } getBrowserExtensionProfileStateStore().forgetProfile(profile.id) getBrowserExtensionSyncStorageStore().forgetProfile(profile.id) diff --git a/src/main/browser/extensions/browser-extension-settings-prompt-lifetime.test.ts b/src/main/browser/extensions/browser-extension-settings-prompt-lifetime.test.ts new file mode 100644 index 00000000000..d888fd9ea02 --- /dev/null +++ b/src/main/browser/extensions/browser-extension-settings-prompt-lifetime.test.ts @@ -0,0 +1,210 @@ +import { EventEmitter } from 'node:events' +import { mkdtempSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { strToU8, zipSync } from 'fflate' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + BROWSER_EXTENSION_INSTALL_PROMPT_REQUESTED_CHANNEL, + type BrowserExtensionWebStoreInstallResult +} from '../../../shared/browser-extension-webstore' +import type * as PromptModule from './browser-extension-install-prompt' +import type * as ServiceModule from './browser-extension-webstore-service' +import type * as InstallModule from './browser-extension-webstore-install' + +const state = vi.hoisted(() => ({ + userData: '', + load: vi.fn(async () => {}), + download: vi.fn() +})) + +vi.mock('electron', () => ({ + app: { getPath: () => state.userData }, + webContents: { fromId: () => null } +})) +vi.mock('../browser-manager', () => ({ browserManager: {} })) +vi.mock('../browser-session-registry', () => ({ + browserSessionRegistry: { + getProfile: () => ({ label: 'Work' }), + getEnabledExtensionIds: () => [], + updateEnabledExtensionIds: vi.fn() + } +})) +vi.mock('./browser-extension-management', () => ({ removeBrowserExtension: vi.fn() })) +vi.mock('./browser-extension-session-loader', () => ({ + getBrowserExtensionSessionForProfile: () => ({}), + loadBrowserExtensionIntoProfile: () => state.load(), + unloadBrowserExtensionEverywhere: vi.fn() +})) +vi.mock('./browser-extension-support', () => ({ isBrowserExtensionSupportEnabled: () => true })) +vi.mock('./browser-extension-webstore-download', () => ({ + downloadWebStoreCrx: () => state.download(), + fetchWebStoreIconDataUrl: vi.fn(), + isAllowedWebStoreIconUrl: vi.fn() +})) +vi.mock('./browser-extension-webstore-events', () => ({ + notifyChromeWebStoreInstalled: vi.fn(), + notifyChromeWebStoreUninstalled: vi.fn() +})) +vi.mock('./browser-extension-load-directory', () => ({ + refuseOrcaFileCollisions: vi.fn(async () => {}) +})) +vi.mock('./browser-extension-held-updates', () => ({ + forgetHeldBrowserExtensionUpdate: vi.fn(), + getHeldBrowserExtensionUpdate: () => null +})) +vi.mock('./browser-extension-list-changes', () => ({ notifyBrowserExtensionListChanged: vi.fn() })) +vi.mock('./browser-extension-profile-reload', () => ({ + reloadBrowserExtensionWhereEnabled: vi.fn() +})) + +const extensionId = 'a'.repeat(32) +const renderers: EventEmitter[] = [] +const installs: Promise[] = [] +let service: typeof ServiceModule +let prompt: typeof PromptModule +let install: typeof InstallModule + +function renderer() { + const contents = Object.assign(new EventEmitter(), { + id: 41, + isDestroyed: () => false, + send: vi.fn<(channel: string, payload: { requestId: string }) => void>() + }) + renderers.push(contents) + return contents +} + +function asContents(contents: ReturnType): Electron.WebContents { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the prompt reads only these EventEmitter methods, id, isDestroyed and send. + return contents as unknown as Electron.WebContents +} + +function start(contents: ReturnType) { + const pending = service.installBrowserExtensionFromWebStore( + 'work', + extensionId, + asContents(contents) + ) + installs.push(pending) + return pending +} + +async function requested(contents: ReturnType): Promise<{ requestId: string }> { + await vi.waitFor(() => + expect(contents.send).toHaveBeenCalledWith( + BROWSER_EXTENSION_INSTALL_PROMPT_REQUESTED_CHANNEL, + expect.objectContaining({ kind: 'install', name: 'Vault' }) + ) + ) + const request = contents.send.mock.calls.find( + ([channel]) => channel === BROWSER_EXTENSION_INSTALL_PROMPT_REQUESTED_CHANNEL + )?.[1] + if (!request) { + throw new Error('Install prompt missing') + } + return request +} + +function stagedFolders(): string[] { + return readdirSync(join(state.userData, 'browser-extensions', extensionId)).filter((name) => + name.startsWith('.staging-') + ) +} + +beforeEach(async () => { + state.userData = mkdtempSync(join(tmpdir(), 'orca-settings-prompt-')) + state.load.mockReset() + state.load.mockResolvedValue(undefined) + state.download.mockReset() + state.download.mockResolvedValue({ + extensionId, + publicKey: Buffer.from('verified-download-key'), + archive: Buffer.from( + zipSync({ + 'manifest.json': strToU8( + JSON.stringify({ + name: 'Vault', + version: '1.0', + manifest_version: 3, + permissions: ['storage'] + }) + ) + }) + ) + }) + vi.resetModules() + service = await import('./browser-extension-webstore-service') + prompt = await import('./browser-extension-install-prompt') + install = await import('./browser-extension-webstore-install') +}) + +afterEach(async () => { + for (const contents of renderers.splice(0)) { + contents.emit('destroyed') + } + await Promise.all(installs.splice(0)) + rmSync(state.userData, { recursive: true, force: true }) +}) + +describe('Settings extension install prompt lifetime', () => { + it('discards staging and releases the install lock when the renderer reloads', async () => { + const contents = renderer() + const pending = start(contents) + const request = await requested(contents) + expect(stagedFolders()).toHaveLength(1) + expect(install.isBrowserExtensionBusy(extensionId)).toBe(true) + + contents.emit('did-navigate', {}, 'file:///orca/index.html', 200, 'OK') + + await vi.waitFor(() => expect(install.isBrowserExtensionBusy(extensionId)).toBe(false)) + await expect(pending).resolves.toEqual({ status: 'cancelled' }) + expect(stagedFolders()).toEqual([]) + expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + expect( + prompt.respondToBrowserExtensionInstallPrompt(asContents(contents), { + requestId: request.requestId, + accepted: true + }) + ).toBe(false) + for (const event of ['destroyed', 'render-process-gone', 'did-navigate']) { + expect(contents.listenerCount(event)).toBe(0) + } + + const successor = renderer() + const retry = start(successor) + const next = await requested(successor) + prompt.respondToBrowserExtensionInstallPrompt(asContents(successor), { + requestId: next.requestId, + accepted: true + }) + await expect(retry).resolves.toEqual({ status: 'installed', name: 'Vault' }) + expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + }) + + it('finishes an accepted install when the renderer navigates during loading', async () => { + let finishLoading = (): void => {} + state.load.mockImplementation( + () => + new Promise((resolve) => { + finishLoading = resolve + }) + ) + const contents = renderer() + const pending = start(contents) + const request = await requested(contents) + prompt.respondToBrowserExtensionInstallPrompt(asContents(contents), { + requestId: request.requestId, + accepted: true + }) + try { + await vi.waitFor(() => expect(state.load).toHaveBeenCalledOnce()) + contents.emit('did-navigate', {}, 'file:///orca/index.html', 200, 'OK') + expect(install.isBrowserExtensionBusy(extensionId)).toBe(true) + } finally { + finishLoading() + } + await expect(pending).resolves.toEqual({ status: 'installed', name: 'Vault' }) + expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + }) +}) diff --git a/src/main/browser/local-ssh-browser-partitions.probe-cache.test.ts b/src/main/browser/local-ssh-browser-partitions.probe-cache.test.ts index f83e664dd4c..5bf9efc4d58 100644 --- a/src/main/browser/local-ssh-browser-partitions.probe-cache.test.ts +++ b/src/main/browser/local-ssh-browser-partitions.probe-cache.test.ts @@ -1,27 +1,55 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ - probe: vi.fn<() => Promise<'ok' | 'forwarding-blocked' | 'ssh-unavailable'>>() -})) +type TestContents = { + id: number + session: object + destroyed: boolean + isDestroyed: () => boolean +} -vi.mock('electron', () => { - const sessions = new Map() +const mocks = vi.hoisted(() => { + const contents: TestContents[] = [] return { - app: { on: vi.fn() }, - session: { - fromPartition: (partition: string) => { - let existing = sessions.get(partition) - if (!existing) { - existing = { partition } - sessions.set(partition, existing) - } - return existing - } - }, - webContents: { getAllWebContents: () => [] } + contents, + probe: vi.fn<() => Promise<'ok' | 'forwarding-blocked' | 'ssh-unavailable'>>(), + census: vi.fn(() => [...contents]), + closeGuest: vi.fn((contents: TestContents) => { + contents.destroyed = true + }), + clearPolicies: vi.fn<(partition: string) => void>(), + removeTarget: vi.fn(), + clearStorage: vi.fn<(targetId: string) => Promise>(), + policy: vi.fn<() => Promise>(), + sessionForPartition: (_partition: string): object => ({}), + emitCreated: (_contents: TestContents): void => {}, + listenerCount: (): number => 0 } }) -vi.mock('./browser-route-guest-guard', () => ({ closeRouteGuest: vi.fn() })) + +vi.mock('electron', async () => { + const { EventEmitter } = await import('node:events') + const app = new EventEmitter() + const sessions = new Map() + const fromPartition = (partition: string): object => { + let existing = sessions.get(partition) + if (!existing) { + existing = { partition } + sessions.set(partition, existing) + } + return existing + } + mocks.sessionForPartition = fromPartition + mocks.emitCreated = (contents) => { + app.emit('web-contents-created', {}, contents) + } + mocks.listenerCount = () => app.listenerCount('web-contents-created') + return { + app, + session: { fromPartition }, + webContents: { getAllWebContents: mocks.census } + } +}) +vi.mock('./browser-route-guest-guard', () => ({ closeRouteGuest: mocks.closeGuest })) vi.mock('./browser-route-partition-binding-runtime', () => { const fingerprints = new Map() return { @@ -44,14 +72,14 @@ vi.mock('./browser-route-partition-storage-dependencies', () => ({ releaseEvictedBrowserRoutePartitionStorage: vi.fn(async () => {}) })) vi.mock('./browser-route-session-policy', () => ({ - prepareBrowserRouteSessionPolicy: vi.fn(async () => {}) + prepareBrowserRouteSessionPolicy: mocks.policy })) vi.mock('./browser-route-webrtc-policy', () => ({ enforceBrowserRouteWebRtcPolicy: vi.fn() })) vi.mock('./browser-session-registry', () => ({ browserSessionRegistry: { requireRouteBrowserProfile: vi.fn(), setupRoutePartitionPolicies: vi.fn(), - clearRoutePartitionPolicies: vi.fn() + clearRoutePartitionPolicies: mocks.clearPolicies } })) vi.mock('./local-ssh-browser-route', () => ({ @@ -59,14 +87,72 @@ vi.mock('./local-ssh-browser-route', () => ({ probeLocalSshBrowserRouteForwarding: mocks.probe, closeLocalSshBrowserRouteForTarget: vi.fn(async () => {}) })) +vi.mock('../ssh/targets/ssh-target-registry', () => ({ + getSshTargetRegistryStore: () => ({ removeTarget: mocks.removeTarget }) +})) +vi.mock('../ssh/ssh-host-server-status', () => ({ clearSshHostServerStatus: vi.fn() })) +vi.mock('../ssh/connection/ssh-connection-attribution', () => ({ + isSshConnectionSolelyOwnedBy: () => true +})) +vi.mock('../ipc/ssh/ssh-connect-attempt-registry', () => ({ + connectInFlight: new Map(), + invalidateConnectAttempt: vi.fn(), + isCurrentConnectAttempt: () => false +})) +vi.mock('../ipc/ssh/ssh-ipc-context', () => ({ + connectionManager: { disconnect: vi.fn(async () => {}) }, + persistedStore: { removeSshRemotePtyLeases: vi.fn() }, + portForwardManager: { removeAllForwards: vi.fn(async () => {}) } +})) +vi.mock('../ipc/ssh/ssh-managed-port-forward-restore', () => ({ + forgetPortForwardRestoreState: vi.fn() +})) +vi.mock('../ssh/legacy-relay/legacy-relay-bridge-registry', () => ({ + forgetLegacyRelayTarget: vi.fn(), + stopLegacyRelayBridge: vi.fn() +})) +vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ + closeOrcadManagedTunnelsForTarget: vi.fn(async () => {}) +})) +vi.mock('./browser-route-partition-storage-runtime', () => ({ + clearBrowserRoutePartitionStorageForLocalSshTarget: mocks.clearStorage +})) -import { prepareLocalSshBrowserPartition } from './local-ssh-browser-partitions' +import { + isLocalSshBrowserPartition, + prepareLocalSshBrowserPartition, + releaseLocalSshBrowserPartitionsForTarget +} from './local-ssh-browser-partitions' +import { removeRegisteredSshTarget } from '../ipc/ssh/ssh-session-teardown' +import { runTargetLifecycle, targetLifecycleInFlight } from '../ipc/ssh/ssh-target-lifecycle-queue' + +beforeEach(() => { + mocks.probe.mockReset().mockResolvedValue('ok') + mocks.policy.mockReset().mockResolvedValue(undefined) + mocks.contents.length = 0 + mocks.census.mockClear() + mocks.clearPolicies.mockReset() + mocks.removeTarget.mockReset() + mocks.clearStorage.mockReset().mockResolvedValue(undefined) + mocks.closeGuest.mockReset().mockImplementation((contents) => { + contents.destroyed = true + }) +}) +afterEach(() => vi.useRealTimers()) + +function createContents(partition: string): TestContents { + const contents = { + id: mocks.contents.length + 1, + session: mocks.sessionForPartition(partition), + destroyed: false, + isDestroyed: () => contents.destroyed + } + mocks.contents.push(contents) + mocks.emitCreated(contents) + return contents +} describe('prepareLocalSshBrowserPartition probe caching', () => { - beforeEach(() => { - mocks.probe.mockReset() - }) - it('does not let a Try-anyway success satisfy a later probed prepare from cache', async () => { mocks.probe.mockResolvedValue('forwarding-blocked') @@ -114,3 +200,250 @@ describe('prepareLocalSshBrowserPartition probe caching', () => { expect(probed.partition).toBe(skipped.partition) }) }) + +describe('releaseLocalSshBrowserPartitionsForTarget', () => { + it.each([10, 100])( + 'enumerates contents once for %i prepared profiles and preserves other targets', + async (profiles) => { + const targetId = `census-${profiles}` + const removed: TestContents[] = [] + for (let index = 0; index < profiles; index++) { + const { partition } = await prepareLocalSshBrowserPartition({ + targetId, + browserProfileId: `profile-${index}` + }) + removed.push(createContents(partition)) + } + const sibling = await prepareLocalSshBrowserPartition({ + targetId: `sibling-${profiles}`, + browserProfileId: 'default' + }) + const survivor = createContents(sibling.partition) + for (let index = 0; index < 1_000; index++) { + createContents('unrelated') + } + const listeners = mocks.listenerCount() + mocks.clearPolicies.mockImplementation((partition) => { + expect( + removed + .filter((contents) => contents.session === mocks.sessionForPartition(partition)) + .every((contents) => contents.destroyed) + ).toBe(true) + }) + + await releaseLocalSshBrowserPartitionsForTarget(targetId) + + expect(mocks.census).toHaveBeenCalledTimes(1) + expect(mocks.closeGuest).toHaveBeenCalledTimes(profiles) + expect(removed.every((contents) => contents.destroyed)).toBe(true) + expect(survivor.destroyed).toBe(false) + expect(mocks.contents.slice(profiles + 1).every((contents) => !contents.destroyed)).toBe(true) + expect(mocks.clearPolicies).toHaveBeenCalledTimes(profiles) + expect(mocks.listenerCount()).toBe(listeners) + } + ) + + it.each([false, true])( + 'waits for its own pending prepare (skipProbe=%s) and refreshes late guests', + async (skipProbe) => { + vi.useFakeTimers() + const first = await prepareLocalSshBrowserPartition({ + targetId: `late-guest-${skipProbe}`, + browserProfileId: 'first' + }) + const firstContents = createContents(first.partition) + const gate = Promise.withResolvers() + mocks.policy.mockImplementationOnce(() => gate.promise) + const second = prepareLocalSshBrowserPartition({ + targetId: `late-guest-${skipProbe}`, + browserProfileId: 'second', + skipProbe + }) + const firstClosed = Promise.withResolvers() + mocks.closeGuest.mockImplementationOnce((contents) => { + contents.destroyed = true + firstClosed.resolve() + }) + const listeners = mocks.listenerCount() + let released = false + const releasing = releaseLocalSshBrowserPartitionsForTarget(`late-guest-${skipProbe}`).then( + () => { + released = true + } + ) + await firstClosed.promise + await vi.advanceTimersByTimeAsync(0) + expect(released).toBe(false) + gate.resolve() + const late = createContents((await second).partition) + await releasing + + expect(firstContents.destroyed).toBe(true) + expect(late.destroyed).toBe(true) + expect(mocks.census).toHaveBeenCalledTimes(2) + expect(mocks.listenerCount()).toBe(listeners) + } + ) + + it.each([false, true])( + 'skips unrelated pending prepares (skipProbe=%s) across profiles and repeated release', + async (skipProbe) => { + vi.useFakeTimers() + const gate = Promise.withResolvers() + mocks.policy.mockImplementationOnce(() => gate.promise) + const siblingInput = { + targetId: `held-sibling-${skipProbe}`, + browserProfileId: 'default', + skipProbe + } + const sibling = prepareLocalSshBrowserPartition(siblingInput) + const targetId = `ready-owner-${skipProbe}` + const first = await prepareLocalSshBrowserPartition({ targetId, browserProfileId: 'first' }) + expect( + await prepareLocalSshBrowserPartition({ + targetId, + browserProfileId: 'first', + skipProbe: true + }) + ).toEqual(first) + const second = await prepareLocalSshBrowserPartition({ + targetId, + browserProfileId: 'second', + skipProbe + }) + const removed = [createContents(first.partition), createContents(second.partition)] + const listeners = mocks.listenerCount() + let released = false + const releasing = releaseLocalSshBrowserPartitionsForTarget(targetId).then(() => { + released = true + }) + try { + await vi.advanceTimersByTimeAsync(0) + expect(released).toBe(true) + expect(removed.every((contents) => contents.destroyed)).toBe(true) + expect(mocks.census).toHaveBeenCalledTimes(1) + expect(mocks.clearPolicies).toHaveBeenCalledTimes(3) + expect(mocks.listenerCount()).toBe(listeners) + } finally { + gate.resolve() + await releasing + await sibling + } + const survivor = createContents((await sibling).partition) + const policyCalls = mocks.policy.mock.calls.length + expect(await prepareLocalSshBrowserPartition(siblingInput)).toEqual(await sibling) + expect(mocks.policy).toHaveBeenCalledTimes(policyCalls) + await releaseLocalSshBrowserPartitionsForTarget(targetId) + expect(mocks.census).toHaveBeenCalledTimes(1) + expect(mocks.clearPolicies).toHaveBeenCalledTimes(3) + expect(survivor.destroyed).toBe(false) + expect(isLocalSshBrowserPartition((await sibling).partition)).toBe(true) + } + ) + + it('deduplicates pending prepares and evicts a rejected own-target entry before retry', async () => { + vi.useFakeTimers() + const gate = Promise.withResolvers() + mocks.policy.mockImplementationOnce(() => gate.promise) + const input = { targetId: 'rejected-owner', browserProfileId: 'default' } + const attempts = Promise.allSettled([ + prepareLocalSshBrowserPartition(input), + prepareLocalSshBrowserPartition(input) + ]) + let released = false + const releasing = releaseLocalSshBrowserPartitionsForTarget(input.targetId).then(() => { + released = true + }) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.policy).toHaveBeenCalledTimes(1) + expect(released).toBe(false) + const error = new Error('proxy setup failed') + gate.reject(error) + expect(await attempts).toEqual([ + { status: 'rejected', reason: error }, + { status: 'rejected', reason: error } + ]) + await releasing + expect(mocks.census).not.toHaveBeenCalled() + const retried = await prepareLocalSshBrowserPartition(input) + expect(mocks.policy).toHaveBeenCalledTimes(2) + const contents = createContents(retried.partition) + await releaseLocalSshBrowserPartitionsForTarget(input.targetId) + expect(contents.destroyed).toBe(true) + expect(isLocalSshBrowserPartition(retried.partition)).toBe(false) + }) + + it('finishes actual target removal and its lifecycle successor while another target prepares', async () => { + vi.useFakeTimers() + const gate = Promise.withResolvers() + mocks.policy.mockImplementationOnce(() => gate.promise) + const sibling = prepareLocalSshBrowserPartition({ + targetId: 'removal-sibling', + browserProfileId: 'default' + }) + const targetId = 'removed-owner' + const target = await prepareLocalSshBrowserPartition({ targetId, browserProfileId: 'default' }) + const guest = createContents(target.partition) + let removed = false + let successorStarted = false + const removing = removeRegisteredSshTarget(targetId).then(() => { + removed = true + }) + const successor = runTargetLifecycle(targetId, async () => { + successorStarted = true + }) + try { + await vi.advanceTimersByTimeAsync(0) + expect(mocks.removeTarget).toHaveBeenCalledWith(targetId) + expect(guest.destroyed).toBe(true) + expect(isLocalSshBrowserPartition(target.partition)).toBe(false) + expect(mocks.clearStorage.mock.calls).toEqual([[targetId]]) + expect(successorStarted).toBe(false) + await vi.advanceTimersByTimeAsync(500) + await removing + await successor + expect(removed).toBe(true) + expect(successorStarted).toBe(true) + expect(targetLifecycleInFlight.has(targetId)).toBe(false) + expect(mocks.clearStorage.mock.calls).toEqual([[targetId], [targetId]]) + } finally { + gate.resolve() + await sibling + await vi.advanceTimersByTimeAsync(500) + await removing + await successor + } + expect(isLocalSshBrowserPartition((await sibling).partition)).toBe(true) + }) + + it('skips destroyed guests and does no native census for an absent target', async () => { + const { partition } = await prepareLocalSshBrowserPartition({ + targetId: 'destroyed-guest', + browserProfileId: 'default' + }) + const dead = createContents(partition) + dead.destroyed = true + const live = createContents(partition) + await releaseLocalSshBrowserPartitionsForTarget('destroyed-guest') + expect(mocks.closeGuest.mock.calls.map(([contents]) => contents)).toEqual([live]) + const calls = mocks.census.mock.calls.length + await releaseLocalSshBrowserPartitionsForTarget('absent') + expect(mocks.census).toHaveBeenCalledTimes(calls) + }) + + it('releases the creation listener if policy cleanup throws', async () => { + const { partition } = await prepareLocalSshBrowserPartition({ + targetId: 'failed-cleanup', + browserProfileId: 'default' + }) + createContents(partition) + const listeners = mocks.listenerCount() + mocks.clearPolicies.mockImplementationOnce(() => { + throw new Error('policy cleanup failed') + }) + await expect(releaseLocalSshBrowserPartitionsForTarget('failed-cleanup')).rejects.toThrow( + 'policy cleanup failed' + ) + expect(mocks.listenerCount()).toBe(listeners) + }) +}) diff --git a/src/main/browser/local-ssh-browser-partitions.ts b/src/main/browser/local-ssh-browser-partitions.ts index 0668292a5ea..18141fdb7f4 100644 --- a/src/main/browser/local-ssh-browser-partitions.ts +++ b/src/main/browser/local-ssh-browser-partitions.ts @@ -36,7 +36,12 @@ type PreparedLocalSshPartition = { proxyEndpoint: BrowserRouteProxyEndpoint } -const preparedByIdentityKey = new Map>() +type PendingLocalSshPartition = { + targetId: string + promise: Promise +} + +const preparedByIdentityKey = new Map() const preparedByPartition = new Map() const partitionBySession = new WeakMap() @@ -77,15 +82,16 @@ export async function prepareLocalSshBrowserPartition(input: { ]) let pending = preparedByIdentityKey.get(identityKey) if (!pending) { - pending = prepareFresh(input) + const promise = prepareFresh(input) + pending = { targetId: input.targetId, promise } preparedByIdentityKey.set(identityKey, pending) - pending.catch(() => { + promise.catch(() => { if (preparedByIdentityKey.get(identityKey) === pending) { preparedByIdentityKey.delete(identityKey) } }) } - const prepared = await pending + const prepared = await pending.promise return { partition: prepared.partition } } @@ -184,20 +190,42 @@ function ensureLocalSshWebRtcGuard(): void { /** Stops guests and releases route records; the caller clears storage afterward. */ export async function releaseLocalSshBrowserPartitionsForTarget(targetId: string): Promise { await closeLocalSshBrowserRouteForTarget(targetId) - for (const [identityKey, pending] of preparedByIdentityKey) { - const prepared = await pending.catch(() => null) - if (prepared?.targetId === targetId) { - preparedByIdentityKey.delete(identityKey) - preparedByPartition.delete(prepared.partition) - // Close guests before clearing storage so they cannot recreate cookies after bindings are removed. - const partitionSession = session.fromPartition(prepared.partition) - for (const contents of webContents.getAllWebContents()) { - if (!contents.isDestroyed() && contents.session === partitionSession) { - closeRouteGuest(contents) + let contentsBySession: Map | null = null + const invalidateContents = (): void => { + contentsBySession = null + } + app.on('web-contents-created', invalidateContents) + try { + for (const [identityKey, pending] of preparedByIdentityKey) { + if (pending.targetId !== targetId) { + continue + } + const prepared = await pending.promise.catch(() => null) + if (prepared?.targetId === targetId) { + preparedByIdentityKey.delete(identityKey) + preparedByPartition.delete(prepared.partition) + // Close guests before clearing storage so they cannot recreate cookies after bindings are removed. + const partitionSession = session.fromPartition(prepared.partition) + if (!contentsBySession) { + contentsBySession = new Map() + for (const contents of webContents.getAllWebContents()) { + if (!contents.isDestroyed()) { + const peers = contentsBySession.get(contents.session) ?? [] + peers.push(contents) + contentsBySession.set(contents.session, peers) + } + } } + for (const contents of contentsBySession.get(partitionSession) ?? []) { + if (!contents.isDestroyed()) { + closeRouteGuest(contents) + } + } + browserSessionRegistry.clearRoutePartitionPolicies(prepared.partition) } - browserSessionRegistry.clearRoutePartitionPolicies(prepared.partition) } + } finally { + app.removeListener('web-contents-created', invalidateContents) } } diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index 59b81675614..658f25a32d1 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -19,7 +19,7 @@ import { createClaudeUserMessageQueue } from './claude-agent-sdk-user-message-queue' import type { ClaudeStructuredSdkOptions } from './claude-structured-launch-resolution' -import { withMissingProviderExecutable } from '../provider-process/provider-executable-missing' +import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing' import { claudeStreamJsonExitError } from './claude-stream-json-exit-error' export { ClaudeControlRequestError } @@ -170,7 +170,7 @@ export async function openClaudeStreamJsonConnection( resumeReading() if (!terminalError) { const error = claudeStreamJsonExitError(managed.stderrTail(), managed.exitStatus, cause) - terminalError = managed.executableMissing ? withMissingProviderExecutable(error) : error + terminalError = withProviderSpawnAbsence(error, managed.spawnAbsence) } inbox.fail(terminalError) if (!closing && !faultReported) { diff --git a/src/main/claude/claude-subagent-journaled-identities.ts b/src/main/claude/claude-subagent-journaled-identities.ts index 8bfab07a7b9..d765aab58ce 100644 --- a/src/main/claude/claude-subagent-journaled-identities.ts +++ b/src/main/claude/claude-subagent-journaled-identities.ts @@ -1,5 +1,5 @@ import type { AgentJournalProducerLinkage } from '../../shared/agent-session-journal-types' -import { namedSubagents } from '../../shared/native-chat-subagent-items' +import { namedSubagents } from '../../shared/native-chat/transcript/native-chat-subagent-items' import type { StructuredAgentSessionLinkageJournal } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { isBoundedClaudeTaskId } from './claude-background-task-tracker' diff --git a/src/main/codex-accounts/runtime-home-service-managed-home.ts b/src/main/codex-accounts/runtime-home-service-managed-home.ts index 887dcc60490..a357074129d 100644 --- a/src/main/codex-accounts/runtime-home-service-managed-home.ts +++ b/src/main/codex-accounts/runtime-home-service-managed-home.ts @@ -29,6 +29,9 @@ import type { CodexManagedAccount } from '../../shared/managed-account-types' import { CodexRuntimeHomeSync } from './runtime-home-service-sync' export abstract class CodexRuntimeHomeManagedHome extends CodexRuntimeHomeSync { + // One WSL sibling-bridge loop per target home; keyed by distro and Linux path. + private readonly wslSessionBridgesByTarget = new Map>() + // Host accounts refresh auth in separate homes so concurrent accounts cannot race one auth.json. protected getSelfContainedManagedHostAccount(): CodexManagedAccount | null { const settings = this.store.getSettings() @@ -259,13 +262,35 @@ export abstract class CodexRuntimeHomeManagedHome extends CodexRuntimeHomeSync { const systemCodexHomePath = resolveWslCodexSessionSourceHome(this.store.getSettings(), distro) ?? this.getWslSystemCodexHomePath({ runtime: 'wsl', wslDistro: distro }) - if (systemCodexHomePath && systemCodexHomePath !== runtimeHomePath) { - // Create history links inside the distro so Codex can see them in /resume. - void startWslCodexSessionBridgeInBackground({ - distro, - systemCodexHomePath, - managedCodexHomePath: runtimeHomePath - }) + const linuxPathOf = (home: string): string => parseWslUncPath(home)?.linuxPath ?? home + const targetLinuxPath = linuxPathOf(runtimeHomePath) + const accountHomes = this.store + .getSettings() + .codexManagedAccounts.map((account) => this.getWslLaunchCodexHomePath(account, distro)) + // Siblings only flow into a selected account's home; system default's own ~/.codex gets none (#24511). + const targetIsAccountHome = accountHomes.some( + (home) => !!home && linuxPathOf(home) === targetLinuxPath + ) + const sourceHomes = [ + systemCodexHomePath, + // Sibling account homes are sources too, or a switch hides the previous account's sessions (#18486). + ...(targetIsAccountHome ? accountHomes : []) + ].filter((home): home is string => !!home && linuxPathOf(home) !== targetLinuxPath) + const targetKey = `${distro.toLowerCase()}\0${targetLinuxPath}` + if (sourceHomes.length === 0 || this.wslSessionBridgesByTarget.has(targetKey)) { + // A concurrent launch joins the loop already bridging this home. + return } + // Create history links inside the distro so Codex can see them in /resume; one wsl.exe at a time. + const loop = (async () => { + for (const sourceHome of new Set(sourceHomes)) { + await startWslCodexSessionBridgeInBackground({ + distro, + systemCodexHomePath: sourceHome, + managedCodexHomePath: runtimeHomePath + }) + } + })().finally(() => this.wslSessionBridgesByTarget.delete(targetKey)) + this.wslSessionBridgesByTarget.set(targetKey, loop) } } diff --git a/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts b/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts index 5cb635350db..ceb1990607a 100644 --- a/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts +++ b/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts @@ -7,6 +7,7 @@ import type * as CodexConfigMirror from '../codex/codex-config-mirror' import type * as CodexHomePaths from '../codex/codex-home-paths' import type * as LegacyWslRuntimeAuthDrain from './legacy-wsl-runtime-auth-drain' import type * as WslCodexAuthBatchReader from './wsl-codex-auth-batch-reader' +import type * as WslCodexSessionBridge from '../codex/wsl-codex-session-bridge' import { createSettings } from './runtime-home-settings-test-fixtures' import { createCodexAuthJson, @@ -425,6 +426,11 @@ describe('CodexRuntimeHomeService', () => { ...(await importOriginal()), syncSystemConfigIntoManagedCodexHome: vi.fn() })) + // Launch-time sibling bridging is covered elsewhere; this pins only the drain's own target. + vi.doMock('../codex/wsl-codex-session-bridge', async (importOriginal) => ({ + ...(await importOriginal()), + startWslCodexSessionBridgeInBackground: vi.fn(() => Promise.resolve()) + })) const retiredHome = join(guestHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home') const relativeSessionPath = join('sessions', '2026', '08', '26', 'retired.jsonl') const retiredSessionPath = join(retiredHome, relativeSessionPath) diff --git a/src/main/codex-accounts/runtime-home-wsl-sibling-bridge.test.ts b/src/main/codex-accounts/runtime-home-wsl-sibling-bridge.test.ts new file mode 100644 index 00000000000..ac416f57530 --- /dev/null +++ b/src/main/codex-accounts/runtime-home-wsl-sibling-bridge.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { createSettings } from './runtime-home-settings-test-fixtures' +import { + createStore, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from './runtime-home-service-test-harness' + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) + +vi.mock(import('node:os'), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +const bridge = vi.hoisted(() => ({ + start: vi.fn<(target: Record) => Promise>(() => Promise.resolve()) +})) + +vi.mock('../codex/wsl-codex-session-bridge', () => ({ + startWslCodexSessionBridgeInBackground: bridge.start +})) + +let wslHome = '' +vi.mock('../wsl', () => ({ + getDefaultWslDistro: () => 'Ubuntu', + getWslHome: () => wslHome +})) + +function accountsRoot(): string { + return join(wslHome, '.local', 'share', 'orca', 'codex-accounts') +} + +function wslAccount(id: string, distro: string) { + return { + id, + email: `${id}@example.com`, + managedHomePath: join(accountsRoot(), id, 'home'), + managedHomeRuntime: 'wsl' as const, + wslDistro: distro, + wslLinuxHomePath: join(accountsRoot(), id, 'home'), + providerAccountId: null, + workspaceLabel: null, + workspaceAccountId: null, + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } +} + +async function createService(selectedUbuntuAccount: string | null) { + const store = createStore( + createSettings({ + codexManagedAccounts: [ + wslAccount('a', 'Ubuntu'), + wslAccount('b', 'Ubuntu'), + wslAccount('other-distro', 'Debian') + ], + activeCodexManagedAccountIdsByRuntime: { + host: null, + wsl: { Ubuntu: selectedUbuntuAccount } + } + }) + ) + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness store implements the getSettings/updateSettings surface this service reads. + return new CodexRuntimeHomeService(store as never) +} + +describe('WSL sibling account session bridging', () => { + let originalPlatform: PropertyDescriptor | undefined + + beforeEach(() => { + setupRuntimeHomeTest() + originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + wslHome = join(testState.userDataDir, 'ubuntu-home') + bridge.start.mockReset() + bridge.start.mockImplementation(() => Promise.resolve()) + }) + + afterEach(() => { + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + teardownRuntimeHomeTest() + }) + + it('bridges sibling WSL account homes into the selected account home', async () => { + const service = await createService('b') + const selectedHome = join(accountsRoot(), 'b', 'home') + + expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + selectedHome + ) + await vi.waitFor(() => + expect(bridge.start.mock.calls).toEqual([ + [ + { + distro: 'Ubuntu', + systemCodexHomePath: join(wslHome, '.codex'), + managedCodexHomePath: selectedHome + } + ], + [ + { + distro: 'Ubuntu', + systemCodexHomePath: join(accountsRoot(), 'a', 'home'), + managedCodexHomePath: selectedHome + } + ] + ]) + ) + }) + + it('bridges nothing into the system home when no WSL account is selected', async () => { + const service = await createService(null) + + expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + join(wslHome, '.codex') + ) + // The loop starts synchronously, so a skipped bridge has already been decided. + await Promise.resolve() + expect(bridge.start).not.toHaveBeenCalled() + }) + + it('lets a concurrent launch join the sibling loop already bridging that home', async () => { + let releaseFirst: () => void = () => {} + bridge.start.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFirst = resolve + }) + ) + const service = await createService('b') + + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + await vi.waitFor(() => expect(bridge.start).toHaveBeenCalledTimes(1)) + releaseFirst() + await vi.waitFor(() => expect(bridge.start).toHaveBeenCalledTimes(2)) + await Promise.resolve() + expect(bridge.start).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/codex/codex-app-server-connection.ts b/src/main/codex/codex-app-server-connection.ts index 09ec30d4db9..94bc1cdd776 100644 --- a/src/main/codex/codex-app-server-connection.ts +++ b/src/main/codex/codex-app-server-connection.ts @@ -4,7 +4,7 @@ import { spawnManagedProviderProcess } from '../provider-process/managed-provide import { createClaudeChildTreeReaper } from '../claude/claude-agent-sdk-exit-proof' import type { ProviderProcessLaunch } from '../provider-process/provider-process-launch' import { buildCodexAppServerExitError } from './app-server/codex-app-server-exit-error' -import { withMissingProviderExecutable } from '../provider-process/provider-executable-missing' +import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing' import { initializeCodexAppServerConnection } from './app-server/codex-app-server-handshake' import { CodexAppServerHandshakeExitUnprovenError } from './app-server/codex-app-server-handshake-exit-proof' import { @@ -51,7 +51,7 @@ async function connectCodexAppServer( function buildExitError(cause?: Error): Error { const error = buildCodexAppServerExitError(managed.stderrTail(), cause) - return managed.executableMissing ? withMissingProviderExecutable(error) : error + return withProviderSpawnAbsence(error, managed.spawnAbsence) } const dispatcher = createCodexAppServerRecordDispatcher({ diff --git a/src/main/codex/codex-structured-skill-report.test.ts b/src/main/codex/codex-structured-skill-report.test.ts index bb5461028da..18e105171e8 100644 --- a/src/main/codex/codex-structured-skill-report.test.ts +++ b/src/main/codex/codex-structured-skill-report.test.ts @@ -117,7 +117,8 @@ describe('a running Codex chat lists and runs the skills Codex loaded', () => { }), [] ], - [retyped, []] + [retyped, []], + [edit(body, { text: '/review', skills: [{ name: 'review', path: REPO_REVIEW }] }), []] ] as const) { expect(edited).toMatchObject(retainedFields) const adapter = await acquired(codex) diff --git a/src/main/codex/codex-subagent-executions.ts b/src/main/codex/codex-subagent-executions.ts index 341f96ef921..fcabf7bd0a5 100644 --- a/src/main/codex/codex-subagent-executions.ts +++ b/src/main/codex/codex-subagent-executions.ts @@ -2,7 +2,7 @@ import type { NativeChatSubagentState } from '../../shared/native-chat-types' import { MAX_SUBAGENT_FIELD_CHARS, canReplaceSubagentState -} from '../../shared/native-chat-subagent-summary' +} from '../../shared/native-chat/transcript/native-chat-subagent-summary' const MAX_SETTLED_TURNS = 256 /** Evicted turn ordinals fall back to first-run attribution. */ diff --git a/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts b/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts index e2a6dc7396a..b06828578fb 100644 --- a/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts +++ b/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts @@ -28,7 +28,7 @@ function skippedCrashDiagnosticBundle(): CrashDiagnosticBundleAttachment { } } -function collectCrashDiagnosticBundleAttachment(): CrashDiagnosticBundleAttachment { +async function collectCrashDiagnosticBundleAttachment(): Promise { const status = getDiagnosticsStatus() if (!status.bundleEnabled) { return { @@ -39,9 +39,9 @@ function collectCrashDiagnosticBundleAttachment(): CrashDiagnosticBundleAttachme } } - let bundle: ReturnType + let bundle: Awaited> try { - bundle = collectDiagnosticBundle({ + bundle = await collectDiagnosticBundle({ appVersion: app.getVersion(), platform: os.platform(), arch: os.arch(), @@ -70,9 +70,9 @@ function collectCrashDiagnosticBundleAttachment(): CrashDiagnosticBundleAttachme } } -export function prepareCrashDiagnosticBundle( +export async function prepareCrashDiagnosticBundle( includeDiagnosticLogs: boolean -): CrashDiagnosticBundleAttachment { +): Promise { return includeDiagnosticLogs ? collectCrashDiagnosticBundleAttachment() : skippedCrashDiagnosticBundle() diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 7b40ac4033d..3dfc8b17dc8 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -127,6 +127,8 @@ async function main(): Promise { const readyIdentity = await readCurrentDaemonReadyIdentity(startedAtMs) const daemonLog = logFilePath ? createDaemonFileLog(logFilePath) : createNoopDaemonFileLog() daemonLog.log('startup', { protocolVersion: PROTOCOL_VERSION, socketPath }) + // Log writes are async; every exit, including process.exit below, flushes the queued tail. + process.once('exit', () => daemonLog.close()) const daemonScope = ownFreshDaemonScope(freshDaemonScope === true, launchNonce) const log = (event: string, details?: Record): void => daemonLog.log(event, details) @@ -153,6 +155,8 @@ async function main(): Promise { return } daemonLog.log('uncaught-exception-fatal', uncaughtExceptionLogDetails(err)) + // Rethrowing from this handler skips 'exit' listeners. + daemonLog.close() console.error('[daemon] Uncaught exception (fatal):', err) throw err }) @@ -184,7 +188,6 @@ async function main(): Promise { daemonLog.log('shutdown-error', { message: (err as Error)?.message }) } finally { shutdownDeadline.cancel() - daemonLog.close() process.exit(0) } } @@ -239,7 +242,6 @@ async function main(): Promise { shuttingDown = true daemonLog.log('login-session-dead-retire', details) daemon?.recordOrderlyExit() - daemonLog.close() // Skip PTY teardown so replacement daemons cold-restore scrollback from unclean session metadata. process.exit(1) } @@ -292,12 +294,10 @@ async function main(): Promise { deathWatch?.stop() shuttingDown = true daemonLog.log('shutdown', { reason: 'idle' }) - daemonLog.close() process.exit(0) }, onRpcShutdown: () => { shutdownDeadline.cancel() - daemonLog.close() process.exit(0) }, onShutdownRequested: beginShutdown diff --git a/src/main/daemon/daemon-file-log.test.ts b/src/main/daemon/daemon-file-log.test.ts index 85067507c3b..ab055af8e77 100644 --- a/src/main/daemon/daemon-file-log.test.ts +++ b/src/main/daemon/daemon-file-log.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -21,34 +21,47 @@ function readLines(filePath: string): Record[] { } describe('createDaemonFileLog', () => { - it('appends NDJSON lines with src/ts/pid/event and terse details', () => { + it('appends NDJSON lines with src/ts/pid/event and terse details', async () => { const filePath = join(dir, 'daemon.log') const log = createDaemonFileLog(filePath) log.log('startup', { protocolVersion: 18 }) log.log('session-created', { sessionId: 'abc', pid: 42 }) + await vi.waitFor(() => expect(readLines(filePath)).toHaveLength(2), { timeout: 10_000 }) const lines = readLines(filePath) - expect(lines).toHaveLength(2) expect(lines[0]).toMatchObject({ src: 'daemon', event: 'startup', protocolVersion: 18 }) expect(typeof lines[0].ts).toBe('string') expect(lines[0].pid).toBe(process.pid) expect(lines[1]).toMatchObject({ event: 'session-created', sessionId: 'abc', pid: 42 }) }) - it('rotates at the byte cap and keeps only the configured rotated files', () => { + it('rotates at the byte cap and keeps only the configured rotated files', async () => { const filePath = join(dir, 'daemon.log') const log = createDaemonFileLog(filePath, { maxBytes: 150, maxRotatedFiles: 2 }) - for (let i = 0; i < 40; i++) { + // One line per batch, so each write sees the size left by the last. + for (let i = 0; i < 10; i++) { log.log('tick', { i }) + await vi.waitFor(() => expect(readLines(filePath).at(-1)).toMatchObject({ i }), { + timeout: 10_000 + }) } - expect(existsSync(filePath)).toBe(true) expect(existsSync(`${filePath}.1`)).toBe(true) expect(existsSync(`${filePath}.2`)).toBe(true) expect(existsSync(`${filePath}.3`)).toBe(false) + }) - const active = readLines(filePath) - expect(active.at(-1)).toMatchObject({ event: 'tick', i: 39 }) + it('counts a line too large for the queue instead of holding it', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath, { maxQueuedChars: 2_000 }) + log.log('huge', { detail: 'x'.repeat(10_000) }) + log.log('after') + log.close() + expect(readLines(filePath).map((l) => [l.event, l.count])).toEqual([ + ['log-entries-dropped', 1], + ['after', undefined], + ['daemon-log-closed', undefined] + ]) }) it('is fail-open when the log directory cannot be created', () => { @@ -70,8 +83,9 @@ describe('createDaemonFileLog', () => { circular.self = circular expect(() => log.log('weird', circular)).not.toThrow() log.log('ok') + log.close() const lines = readLines(filePath) - expect(lines.map((l) => l.event)).toEqual(['ok']) + expect(lines.map((l) => l.event)).toEqual(['ok', 'daemon-log-closed']) }) it('close() writes a terminal marker and stops further writes', () => { diff --git a/src/main/daemon/daemon-file-log.ts b/src/main/daemon/daemon-file-log.ts index 0c4b17d96ac..934fb05f1a5 100644 --- a/src/main/daemon/daemon-file-log.ts +++ b/src/main/daemon/daemon-file-log.ts @@ -1,23 +1,26 @@ // Daemon diagnostics must never affect lifecycle or include terminal content or tokens. -import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs' +import { mkdirSync } from 'node:fs' import { dirname } from 'node:path' +import { createBoundedLogFileWriter } from '../observability/bounded-log-file-writer' const DEFAULT_MAX_BYTES = 5 * 1024 * 1024 const DEFAULT_MAX_ROTATED_FILES = 2 -const PRIVATE_FILE_MODE = 0o600 +const BATCH_WINDOW_MS = 50 /** Includes the active file so diagnostic bundles collect the whole rotated family. */ export const DAEMON_LOG_MAX_FILES = DEFAULT_MAX_ROTATED_FILES + 1 export type DaemonFileLog = { log(event: string, details?: Record): void + /** Appends the queued tail synchronously; call right before exit. */ close(): void } export type DaemonFileLogOptions = { readonly maxBytes?: number readonly maxRotatedFiles?: number + readonly maxQueuedChars?: number } export function createNoopDaemonFileLog(): DaemonFileLog { @@ -27,88 +30,50 @@ export function createNoopDaemonFileLog(): DaemonFileLog { } } +function formatDaemonLogLine(event: string, details: Record): string { + return `${JSON.stringify({ + src: 'daemon', + ts: new Date().toISOString(), + pid: process.pid, + event, + ...details + })}\n` +} + export function createDaemonFileLog( filePath: string, opts: DaemonFileLogOptions = {} ): DaemonFileLog { - const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES - const maxRotatedFiles = opts.maxRotatedFiles ?? DEFAULT_MAX_ROTATED_FILES - - let disabled = false - let currentBytes = 0 - - function disable(): void { - disabled = true - } - try { mkdirSync(dirname(filePath), { recursive: true }) - currentBytes = existsSync(filePath) ? statSync(filePath).size : 0 } catch { - disable() - } - - function rotate(): void { - // Without rotation, preserve the active byte count so the overflow guard remains accurate. - if (maxRotatedFiles < 1) { - return - } - try { - for (let i = maxRotatedFiles; i >= 1; i--) { - const src = i === 1 ? filePath : `${filePath}.${i - 1}` - const dst = `${filePath}.${i}` - if (!existsSync(src)) { - continue - } - if (existsSync(dst)) { - unlinkSync(dst) - } - renameSync(src, dst) - } - currentBytes = 0 - } catch { - disable() - } + return createNoopDaemonFileLog() } + const writer = createBoundedLogFileWriter({ + filePath, + maxBytes: opts.maxBytes ?? DEFAULT_MAX_BYTES, + maxFiles: (opts.maxRotatedFiles ?? DEFAULT_MAX_ROTATED_FILES) + 1, + batchWindowMs: BATCH_WINDOW_MS, + maxQueuedChars: opts.maxQueuedChars, + formatDroppedLine: (count) => formatDaemonLogLine('log-entries-dropped', { count }) + }) function log(event: string, details: Record = {}): void { - if (disabled) { - return - } let line: string try { - line = `${JSON.stringify({ - src: 'daemon', - ts: new Date().toISOString(), - pid: process.pid, - event, - ...details - })}\n` + line = formatDaemonLogLine(event, details) } catch { // Malformed event details must not disrupt daemon lifecycle. return } - const lineBytes = Buffer.byteLength(line, 'utf8') - if (currentBytes > 0 && currentBytes + lineBytes > maxBytes) { - rotate() - if (disabled) { - return - } - } - try { - appendFileSync(filePath, line, { mode: PRIVATE_FILE_MODE }) - currentBytes += lineBytes - } catch { - disable() - } + writer.write(line) } return { log, close(): void { - // Appends are synchronous; there is nothing to flush. log('daemon-log-closed') - disabled = true + writer.close() } } } diff --git a/src/main/daemon/daemon-generation-liveness.test.ts b/src/main/daemon/daemon-generation-liveness.test.ts new file mode 100644 index 00000000000..d7bb4018b9e --- /dev/null +++ b/src/main/daemon/daemon-generation-liveness.test.ts @@ -0,0 +1,48 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { createServer, type Server } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { listLiveDaemonProtocols } from './daemon-generation-liveness' +import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath } from './daemon-spawner' + +const servers: Server[] = [] +let runtimeDir = '' + +async function serveGeneration(protocolVersion: number): Promise { + const server = createServer() + servers.push(server) + await new Promise((resolve) => + server.listen(getDaemonSocketPath(runtimeDir, protocolVersion), resolve) + ) +} + +afterEach(async () => { + await Promise.all(servers.splice(0).map((s) => new Promise((resolve) => s.close(resolve)))) + rmSync(runtimeDir, { recursive: true, force: true }) +}) + +describe('live daemon generations', () => { + it('names every answering generation, including one newer than this build knows', async () => { + runtimeDir = mkdtempSync(join(tmpdir(), 'orca-generations-')) + await serveGeneration(50) + await serveGeneration(51) + await serveGeneration(99) + // A generation this build does not know is found by its token even while its pid record is absent. + writeFileSync(getDaemonTokenPath(runtimeDir, 99), 'token') + writeFileSync(getDaemonPidPath(runtimeDir, 49), JSON.stringify({ pid: 2 ** 22 + 1 })) + // An answering endpoint counts even when its pid record is unreadable. + writeFileSync(getDaemonPidPath(runtimeDir, 50), 'not a pid record') + + await expect(listLiveDaemonProtocols(runtimeDir, [49, 50, 51])).resolves.toEqual([50, 51, 99]) + }) + + it('cannot vouch for a runtime dir it cannot list', async () => { + runtimeDir = mkdtempSync(join(tmpdir(), 'orca-generations-')) + // A file where the dir belongs fails the listing without depending on permissions. + const notADir = join(runtimeDir, 'daemon') + writeFileSync(notADir, '') + + await expect(listLiveDaemonProtocols(notADir, [51])).resolves.toBeNull() + }) +}) diff --git a/src/main/daemon/daemon-generation-liveness.ts b/src/main/daemon/daemon-generation-liveness.ts new file mode 100644 index 00000000000..5493653e03a --- /dev/null +++ b/src/main/daemon/daemon-generation-liveness.ts @@ -0,0 +1,113 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { endpointIsProvenDead, probeSocketConnect } from './daemon-endpoint-probe' +import type { ProcessLivenessVerdict } from './daemon-incarnation-evidence-types' +import { parseDaemonPidFile } from './daemon-pid-file-parse' +import { inspectDaemonProcessIdentity } from './daemon-pid-identity' +import { hasErrorCode } from './daemon-process-inspection' +import { shortDaemonSocketDir } from './daemon-socket-endpoint-path' +import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath } from './daemon-spawner' + +const PID_FILE_PATTERN = /^daemon-v(\d+)\.pid$/ +// Pid records can be mid-repair; token and socket names still mark a generation. +const GENERATION_ARTIFACT_PATTERN = /^daemon-v(\d+)\.(?:pid|token|sock)$/ + +function namedProtocols(names: readonly string[], pattern: RegExp): number[] { + return names + .map((name) => Number(pattern.exec(name)?.[1])) + .filter((version) => Number.isSafeInteger(version) && version > 0) +} + +/** Names in a dir; a missing dir has none, any other failure is null. */ +function readDirNames(dir: string): string[] | null { + try { + return readdirSync(dir) + } catch (error) { + return hasErrorCode(error, 'ENOENT') ? [] : null + } +} + +/** Protocols with a pid record in this runtime dir, including ones this build cannot speak. */ +export function listDaemonPidFileProtocols(runtimeDir: string): number[] { + try { + return namedProtocols(readdirSync(runtimeDir), PID_FILE_PATTERN) + } catch { + // Discovery errors leave no known pid records. + return [] + } +} + +async function probeDaemonEndpoint( + socketPath: string +): Promise>> { + const outcome = await probeSocketConnect(socketPath) + if (outcome !== 'unknown') { + return outcome + } + // A stalled main loop can fire timeout before the dead socket's refusal arrives. + await new Promise((resolve) => setImmediate(resolve)) + return probeSocketConnect(socketPath) +} + +/** Inspect one daemon generation's PID and endpoint without mutating its files. */ +export async function classifyDaemonGeneration( + runtimeDir: string, + protocolVersion: number +): Promise { + const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion) + const byEndpoint = async (): Promise => + endpointIsProvenDead(await probeDaemonEndpoint(socketPath)) ? 'exited' : 'unverifiable' + let contents: string + try { + contents = readFileSync(getDaemonPidPath(runtimeDir, protocolVersion), 'utf8') + } catch (error) { + return hasErrorCode(error, 'ENOENT') ? 'exited' : byEndpoint() + } + const parsed = parseDaemonPidFile(contents) + // An empty legacy record parses as PID 0, which is not a daemon PID. + if (!parsed || !Number.isInteger(parsed.pid) || parsed.pid <= 0) { + return byEndpoint() + } + const identity = await inspectDaemonProcessIdentity( + parsed.pid, + socketPath, + getDaemonTokenPath(runtimeDir, protocolVersion), + parsed.startedAtMs + ) + if (identity === 'match') { + return 'live' + } + return identity === 'mismatch' ? 'exited' : byEndpoint() +} + +/** Every daemon generation alive in this runtime dir, sorted; null when any one cannot be ruled in or out. */ +export async function listLiveDaemonProtocols( + runtimeDir: string, + knownProtocols: readonly number[] +): Promise { + // Unix sockets too long for the runtime dir live in a relocated one. + const uid = process.getuid?.() + const dirs = [runtimeDir, ...(uid === undefined ? [] : [shortDaemonSocketDir(runtimeDir, uid)])] + const protocols = new Set(knownProtocols) + for (const dir of dirs) { + const names = readDirNames(dir) + if (!names) { + // An unreadable dir could hide a generation this build does not know to probe. + return null + } + namedProtocols(names, GENERATION_ARTIFACT_PATTERN).forEach((p) => protocols.add(p)) + } + const live: number[] = [] + for (const protocol of [...protocols].sort((a, b) => a - b)) { + // Legacy discovery attaches any answering endpoint, whatever its pid record says. + const endpoint = await probeDaemonEndpoint(getDaemonSocketPath(runtimeDir, protocol)) + if (endpoint === 'connected') { + live.push(protocol) + } else if ( + !endpointIsProvenDead(endpoint) || + (await classifyDaemonGeneration(runtimeDir, protocol)) !== 'exited' + ) { + return null + } + } + return live +} diff --git a/src/main/daemon/daemon-launch-paths.ts b/src/main/daemon/daemon-launch-paths.ts index 4b84cb714a6..7e8d7dedf6d 100644 --- a/src/main/daemon/daemon-launch-paths.ts +++ b/src/main/daemon/daemon-launch-paths.ts @@ -5,13 +5,14 @@ import { getAppEnvironment } from '../../shared/app-environment' import { ensurePrivateDir } from './daemon-private-file-modes' import { scheduleTerminalHistoryPermissionRepair } from './terminal-history-permission-repair' import { getDaemonLogFilePath } from '../observability/logs-directory' +import { daemonRuntimeDirFor } from './daemon-runtime-dir' import { DaemonClient } from './client' import { daemonRecoveryProbeTimeoutMs } from './daemon-recovery-budget' import { remainingDaemonRequestTimeoutMs } from './daemon-request-deadline' import { PROTOCOL_VERSION, type ListSessionsResult } from './types' export function getDaemonRuntimeDir(): string { - const dir = join(getAppEnvironment().getPath('userData'), 'daemon') + const dir = daemonRuntimeDirFor(getAppEnvironment().getPath('userData')) ensurePrivateDir(dir) return dir } diff --git a/src/main/daemon/daemon-live-sleep-cwd.ts b/src/main/daemon/daemon-live-sleep-cwd.ts new file mode 100644 index 00000000000..64ba41fd5c6 --- /dev/null +++ b/src/main/daemon/daemon-live-sleep-cwd.ts @@ -0,0 +1,27 @@ +import type { DaemonClient } from './client' +import { teardownReadBudgetMs } from './daemon-request-deadline' + +const LIVE_SLEEP_CWD_BUDGET_MS = 1_500 + +/** + * A native shell's folder at Sleep (OSC 7, else its process's cwd). Bash prints no OSC 7, so + * without this the checkpoint keeps the spawn folder and Wake opens there (e.g. on a Linux host). + */ +export async function readDaemonLiveSleepCwd( + client: Pick, + sessionId: string, + deadlineMs?: number +): Promise { + // Windows has no process-cwd lookup (it would spawn a missing lsof); the snapshot's OSC 7 cwd stands. + const budget = teardownReadBudgetMs(LIVE_SLEEP_CWD_BUDGET_MS, deadlineMs) + if (process.platform === 'win32' || budget <= 0) { + return null + } + try { + const { cwd } = await client.request<{ cwd: string | null }>('getCwd', { sessionId }, budget) + // A removed folder reads back from /proc as ` (deleted)`, which no shell can return to. + return cwd && !cwd.endsWith(' (deleted)') ? cwd : null + } catch { + return null + } +} diff --git a/src/main/daemon/daemon-newer-protocol-hold.ts b/src/main/daemon/daemon-newer-protocol-hold.ts index 6165786fe47..4d38e3bed44 100644 --- a/src/main/daemon/daemon-newer-protocol-hold.ts +++ b/src/main/daemon/daemon-newer-protocol-hold.ts @@ -1,73 +1,22 @@ -import { readdirSync, readFileSync } from 'node:fs' import type { NewerDaemonHeldScreen, NewerDaemonReopenResult } from '../../shared/newer-daemon-hold' import { coldRestorePayloadFromInfo } from './cold-restore-payload-cache' -import { endpointIsProvenDead, probeSocketConnect } from './daemon-endpoint-probe' -import type { ProcessLivenessVerdict } from './daemon-incarnation-evidence-types' +import { classifyDaemonGeneration, listDaemonPidFileProtocols } from './daemon-generation-liveness' import { getDaemonHistoryDir, getDaemonRuntimeDir } from './daemon-launch-paths' -import { parseDaemonPidFile } from './daemon-pid-file-parse' -import { inspectDaemonProcessIdentity } from './daemon-pid-identity' -import { hasErrorCode } from './daemon-process-inspection' -import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath } from './daemon-spawner' +import { getDaemonSocketPath, getDaemonTokenPath } from './daemon-spawner' import { killStaleDaemon } from './daemon-stale-kill' import { HistoryReader } from './history-reader' import { PROTOCOL_VERSION } from './types' -const PID_FILE_PATTERN = /^daemon-v(\d+)\.pid$/ - let heldProtocols: readonly number[] = [] let reopenInFlight: Promise | null = null -/** This build cannot speak the newer protocol; inspect its PID and endpoint without mutating its files. */ -async function classifyNewerProtocolDaemon( - runtimeDir: string, - protocolVersion: number -): Promise { - const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion) - const byEndpoint = async (): Promise => { - let outcome = await probeSocketConnect(socketPath) - if (outcome === 'unknown') { - // A stalled main loop can fire timeout before the dead socket's refusal arrives. - await new Promise((resolve) => setImmediate(resolve)) - outcome = await probeSocketConnect(socketPath) - } - return endpointIsProvenDead(outcome) ? 'exited' : 'unverifiable' - } - let contents: string - try { - contents = readFileSync(getDaemonPidPath(runtimeDir, protocolVersion), 'utf8') - } catch (error) { - return hasErrorCode(error, 'ENOENT') ? 'exited' : byEndpoint() - } - const parsed = parseDaemonPidFile(contents) - // An empty legacy record parses as PID 0, which is not a daemon PID. - if (!parsed || !Number.isInteger(parsed.pid) || parsed.pid <= 0) { - return byEndpoint() - } - const identity = await inspectDaemonProcessIdentity( - parsed.pid, - socketPath, - getDaemonTokenPath(runtimeDir, protocolVersion), - parsed.startedAtMs - ) - if (identity === 'match') { - return 'live' - } - return identity === 'mismatch' ? 'exited' : byEndpoint() -} - /** Holds restores for every live or unverifiable newer daemon in this profile's runtime dir. */ export async function discoverNewerProtocolHolds(runtimeDir: string): Promise { - let names: string[] = [] - try { - names = readdirSync(runtimeDir) - } catch { - // Discovery errors leave no known newer-protocol records. - } - const versions = names - .map((name) => Number(PID_FILE_PATTERN.exec(name)?.[1])) - .filter((version) => Number.isSafeInteger(version) && version > PROTOCOL_VERSION) + const versions = listDaemonPidFileProtocols(runtimeDir).filter( + (version) => version > PROTOCOL_VERSION + ) const verdicts = await Promise.all( - versions.map((version) => classifyNewerProtocolDaemon(runtimeDir, version)) + versions.map((version) => classifyDaemonGeneration(runtimeDir, version)) ) heldProtocols = versions.filter((_, index) => verdicts[index] !== 'exited') } @@ -93,7 +42,7 @@ async function stopNewerProtocolDaemon( runtimeDir: string, protocolVersion: number ): Promise { - const verdict = await classifyNewerProtocolDaemon(runtimeDir, protocolVersion) + const verdict = await classifyDaemonGeneration(runtimeDir, protocolVersion) if (verdict !== 'live') { return verdict === 'exited' } @@ -105,7 +54,7 @@ async function stopNewerProtocolDaemon( ) return ( !outcome.liveOwnerSurvived && - (await classifyNewerProtocolDaemon(runtimeDir, protocolVersion)) === 'exited' + (await classifyDaemonGeneration(runtimeDir, protocolVersion)) === 'exited' ) } diff --git a/src/main/daemon/daemon-pty-adapter-test-harness.ts b/src/main/daemon/daemon-pty-adapter-test-harness.ts index 55a372516ed..4e8b520024a 100644 --- a/src/main/daemon/daemon-pty-adapter-test-harness.ts +++ b/src/main/daemon/daemon-pty-adapter-test-harness.ts @@ -82,7 +82,11 @@ export async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promi /** Boots a real daemon server over a temp socket plus a lazily-connecting adapter. */ export async function startDaemonAdapterHarness( spawnSubprocess: SpawnSubprocess, - adapterOptions: Pick = {} + adapterOptions: Pick< + DaemonPtyAdapterOptions, + 'readRunningWslDistros' | 'historyPath' | 'wslBridgeBootIdentity' + > = {}, + serverOptions: { onPtySessionExit?: (sessionId: string) => void } = {} ): Promise { const dir = createTestDir() const socketPath = getDaemonSocketPath(dir) @@ -92,7 +96,13 @@ export async function startDaemonAdapterHarness( log: (event) => daemonLogEvents.push(event), close() {} } - const server = new DaemonServer({ socketPath, tokenPath, log: daemonLog, spawnSubprocess }) + const server = new DaemonServer({ + socketPath, + tokenPath, + log: daemonLog, + spawnSubprocess, + ...serverOptions + }) await server.start() const adapter = new DaemonPtyAdapter({ socketPath, tokenPath, ...adapterOptions }) return { dir, socketPath, tokenPath, server, adapter, daemonLog, daemonLogEvents } diff --git a/src/main/daemon/daemon-pty-adapter-wsl-distro-loss-relaunch.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-distro-loss-relaunch.test.ts new file mode 100644 index 00000000000..d8c6f4434c2 --- /dev/null +++ b/src/main/daemon/daemon-pty-adapter-wsl-distro-loss-relaunch.test.ts @@ -0,0 +1,149 @@ +// 5e: a bridge pane whose distro was terminated must cold-restore its own session after a relaunch. +import './mock-descendant-sweep' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { rmSync } from 'node:fs' +import type { WslRunningDistrosRead } from '../wsl-background-distro-gate' +import { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { DaemonPtyAdapterOptions } from './daemon-pty-runtime-state' +import { DaemonServer } from './daemon-server' +import { WslBridgeBootIdentity } from './daemon-wsl-bridge-boot-identity' +import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' + +/** Drives the adapter's own periodic save, which has no public trigger. */ +class SavingDaemonPtyAdapter extends DaemonPtyAdapter { + savePeriodically(sessionIds: string[]): Promise { + return this.checkpointSessions(sessionIds, { final: false }) + } + + /** What a spawn in `\\wsl.localhost\Ubuntu\...` records, without faking win32. */ + runsInUbuntu(sessionId: string): void { + this.noteSpawnWslDistro(sessionId, 'Ubuntu', false) + } +} + +const PANE = 'wt-1::/project@@bridge' +const OTHER = 'wt-2::/other@@native' +const WORKTREES = new Set(['wt-1::/project', 'wt-2::/other']) + +describe('a WSL bridge pane whose distro was terminated, after a relaunch', () => { + let dir: string + let socketPath: string + let tokenPath: string + let server: DaemonServer + let historyDir: string + let lastSubprocess: ReturnType + const spawnSubprocess = () => { + lastSubprocess = createMockSubprocess() + return lastSubprocess + } + + const reaped = new Set() + + beforeEach(async () => { + reaped.clear() + const harness = await startDaemonAdapterHarness( + spawnSubprocess, + {}, + { + onPtySessionExit: (sessionId) => reaped.add(sessionId) + } + ) + harness.adapter.dispose() + dir = harness.dir + socketPath = harness.socketPath + tokenPath = harness.tokenPath + server = harness.server + historyDir = join(dir, 'history') + }) + afterEach(async () => { + await server?.shutdown() + rmSync(dir, { recursive: true, force: true }) + }) + + const launch = ( + options: Pick = {} + ) => new SavingDaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir, ...options }) + + /** A bridge pane with saved history, beside a native pane that keeps the daemon running. */ + async function openBridgePane(app: SavingDaemonPtyAdapter) { + await app.spawn({ cols: 80, rows: 24, cwd: '/other', sessionId: OTHER }) + await app.spawn({ cols: 80, rows: 24, cwd: '/project', sessionId: PANE }) + app.runsInUbuntu(PANE) + const bridge = lastSubprocess + bridge._simulateData('user@host:~/project$ echo KEPT\r\nKEPT\r\nuser@host:~/project$ ') + await app.savePeriodically([PANE]) + return bridge + } + + async function relaunchAndRestore(): Promise { + const app = launch() + await app.reconcileOnStartup(WORKTREES) + const restored = await app.spawn({ cols: 80, rows: 24, cwd: '/project', sessionId: PANE }) + await app.disconnectOnly() + return Boolean(restored.coldRestore) + } + + it('restores when the distro stopped while Orca was quit and the daemon kept running', async () => { + const app = launch() + const bridge = await openBridgePane(app) + await app.disconnectOnly() + + bridge._simulateExit(1) + // The relaunch must find no session to attach to, only the history to restore. + await vi.waitFor(() => expect(reaped.has(PANE)).toBe(true)) + + await expect(relaunchAndRestore()).resolves.toBe(true) + }) + + it('restores when the distro stopped while Orca was quit and the daemon exited with it', async () => { + const app = launch() + await app.spawn({ cols: 80, rows: 24, cwd: '/project', sessionId: PANE }) + lastSubprocess._simulateData('user@host:~/project$ echo KEPT\r\nKEPT\r\n') + await app.savePeriodically([PANE]) + await app.disconnectOnly() + + lastSubprocess._simulateExit(1) + // Its last session gone and no client, the daemon exits; the relaunch starts a new one. + await server.shutdown() + server = new DaemonServer({ socketPath, tokenPath, spawnSubprocess }) + await server.start() + + await expect(relaunchAndRestore()).resolves.toBe(true) + }) + + it.each([ + [ + 'something booted the distro again before the running list answered', + [{ status: 'confirmed', distros: ['Ubuntu'] }], + ['boot-1', 'boot-2'] + ], + [ + 'the first running list could not answer', + [{ status: 'unavailable' }, { status: 'confirmed', distros: [] }], + ['boot-1'] + ] + ] as const)('restores when %s while Orca ran', async (_name, answers, ids) => { + const reads: WslRunningDistrosRead[] = answers.map((answer) => ({ + ...answer, + ...('distros' in answer ? { distros: [...answer.distros] } : {}) + })) + const bootIds = [...ids] + const app = launch({ + readRunningWslDistros: async () => (reads.length > 1 ? reads.shift()! : reads[0]!), + wslBridgeBootIdentity: new WslBridgeBootIdentity({ + isRunning: async () => true, + readBootId: async () => (bootIds.length > 1 ? bootIds.shift()! : bootIds[0]!) + }) + }) + const exits: unknown[] = [] + app.onExit((exit) => exits.push(exit)) + const bridge = await openBridgePane(app) + + bridge._simulateExit(1) + await vi.waitFor(() => expect(exits).toEqual([expect.objectContaining({ hostLost: true })])) + await app.disconnectOnly() + + await expect(relaunchAndRestore()).resolves.toBe(true) + }) +}) diff --git a/src/main/daemon/daemon-pty-adapter-wsl-distro-loss.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-distro-loss.test.ts index 77515fa7652..97bd84d5115 100644 --- a/src/main/daemon/daemon-pty-adapter-wsl-distro-loss.test.ts +++ b/src/main/daemon/daemon-pty-adapter-wsl-distro-loss.test.ts @@ -7,6 +7,7 @@ import type { WslRunningDistrosRead } from '../wsl-background-distro-gate' import type { DaemonPtyAdapter } from './daemon-pty-adapter' import type { DaemonServer } from './daemon-server' import { HistoryManager } from './history-manager' +import { WslBridgeBootIdentity } from './daemon-wsl-bridge-boot-identity' import { createMockSubprocess, startDaemonAdapterHarness, @@ -23,12 +24,19 @@ describe('a WSL bridge pane exit', () => { let subprocesses: ReturnType[] let running: () => Promise const readRunning = vi.fn(() => running()) + // The distro's boot id each read returns; never a real wsl.exe. + let bootIds: string[] + const readBootId = vi.fn(async () => (bootIds.length > 1 ? bootIds.shift()! : bootIds[0]!)) + const noteMayHaveStopped = vi.fn() beforeEach(async () => { historyDir = mkdtempSync(join(tmpdir(), 'orca-distro-loss-history-')) subprocesses = [] running = async () => ({ status: 'confirmed', distros: ['Ubuntu'] }) readRunning.mockClear() + bootIds = ['boot-1'] + readBootId.mockClear() + noteMayHaveStopped.mockClear() const harness = await startDaemonAdapterHarness( () => { const subprocess = createMockSubprocess() @@ -37,7 +45,12 @@ describe('a WSL bridge pane exit', () => { }, { readRunningWslDistros: readRunning, - historyPath: historyDir + historyPath: historyDir, + wslBridgeBootIdentity: new WslBridgeBootIdentity({ + isRunning: async () => true, + readBootId, + noteMayHaveStopped + }) } ) dir = harness.dir @@ -55,9 +68,11 @@ describe('a WSL bridge pane exit', () => { async function spawnBridgePane(): Promise { const { id } = await adapter.spawn({ cols: 80, rows: 24 }) // What a spawn in `\\wsl.localhost\Ubuntu\...` records. - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the adapter's protected map, which a WSL spawn fills; set here without faking win32. - const internals = adapter as unknown as { wslDistrosBySessionId: Map } - internals.wslDistrosBySessionId.set(id, 'Ubuntu') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the adapter's protected spawn bookkeeping, which a WSL spawn runs; called here without faking win32. + const internals = adapter as unknown as { + noteSpawnWslDistro: (id: string, distro: string, clear: boolean) => void + } + internals.noteSpawnWslDistro(id, 'Ubuntu', false) return id } @@ -85,6 +100,33 @@ describe('a WSL bridge pane exit', () => { expect(clear).toHaveBeenCalledWith(id, -1, expect.any(String), { closeHistory: false }) }) + it("closes a pane's own clean exit at once, with no settle wait or running-list read", async () => { + // A list that never answers: classifying the exit would hang it. + running = () => new Promise(() => {}) + const exits = collectExits() + const id = await spawnBridgePane() + + subprocesses[0]!._simulateExit(0) + + await waitFor(() => exits.length > 0) + expect(exits).toEqual([expect.objectContaining({ id, code: 0 })]) + expect(exits[0]).not.toHaveProperty('hostLost') + expect(readRunning).not.toHaveBeenCalled() + // Still marked: background reads must settle in case the distro did stop (poweroff, --shutdown). + expect(noteMayHaveStopped).toHaveBeenCalledWith('Ubuntu') + }) + + it('marks a non-zero exit as a possible stop before classifying it', async () => { + running = async () => ({ status: 'confirmed', distros: [] }) + const exits = collectExits() + await spawnBridgePane() + + subprocesses[0]!._simulateExit(1) + + await waitFor(() => exits.length > 0) + expect(noteMayHaveStopped).toHaveBeenCalledWith('Ubuntu') + }) + it('logs what the running list said, so a run can tell host loss from a raced reboot', async () => { const info = vi.spyOn(console, 'info').mockImplementation(() => {}) for (const [distros, verdict] of [ @@ -98,13 +140,15 @@ describe('a WSL bridge pane exit', () => { await waitFor(() => exits.length > 0) expect(info).toHaveBeenLastCalledWith( expect.stringMatching( - new RegExp(`^\\[pty\\] WSL bridge exit: ${verdict} \\(distro Ubuntu, probe \\d+ms\\)$`) + new RegExp( + `^\\[pty\\] WSL bridge exit: ${verdict} \\(distro Ubuntu, code 1, probe \\d+ms\\)$` + ) ) ) } }) - it('stays a normal exit while its distro runs, so `exit` still closes the tab', async () => { + it('stays a normal exit while its distro runs on the same boot, so `exit` still closes the tab', async () => { const exits = collectExits() const id = await spawnBridgePane() @@ -115,6 +159,60 @@ describe('a WSL bridge pane exit', () => { expect(exits[0]).not.toHaveProperty('hostLost') }) + // 5e hardening (a): something booted the distro again before the running list answered. + it('is host loss when the distro runs again under a new boot id', async () => { + bootIds = ['boot-1', 'boot-2'] + const exits = collectExits() + const id = await spawnBridgePane() + + subprocesses[0]!._simulateExit(1) + + await waitFor(() => exits.length > 0) + expect(exits).toEqual([{ id, code: -1, incarnationId: expect.any(String), hostLost: true }]) + expect(readBootId).toHaveBeenCalledTimes(2) + }) + + // #35050 review: a pane opened during another's exit verdict took the old boot's id. + it("lets a pane opened during another pane's exit verdict close on its own `exit`", async () => { + bootIds = ['boot-1', 'boot-2'] + let answer: (read: WslRunningDistrosRead) => void = () => {} + running = () => + new Promise((resolve) => { + answer = resolve + }) + const exits = collectExits() + const first = await spawnBridgePane() + await waitFor(() => readBootId.mock.calls.length === 1) + + subprocesses[0]!._simulateExit(1) + await waitFor(() => readRunning.mock.calls.length === 1) + const second = await spawnBridgePane() + answer({ status: 'confirmed', distros: ['Ubuntu'] }) + await waitFor(() => exits.length === 1) + expect(exits[0]).toMatchObject({ id: first, code: -1, hostLost: true }) + + running = async () => ({ status: 'confirmed', distros: ['Ubuntu'] }) + subprocesses[1]!._simulateExit(1) + await waitFor(() => exits.length === 2) + expect(exits[1]).toMatchObject({ id: second, code: 1 }) + expect(exits[1]).not.toHaveProperty('hostLost') + }) + + // awin: a terminate exited each bridge pane with -1, never 0; a user's `exit` gives 0. + it('reads no boot id for a clean exit, which stays an exit even across a reboot', async () => { + bootIds = ['boot-1', 'boot-2'] + const exits = collectExits() + const id = await spawnBridgePane() + await waitFor(() => readBootId.mock.calls.length === 1) + + subprocesses[0]!._simulateExit(0) + + await waitFor(() => exits.length > 0) + expect(exits[0]).toMatchObject({ id, code: 0 }) + expect(exits[0]).not.toHaveProperty('hostLost') + expect(readBootId).toHaveBeenCalledOnce() + }) + it('stays a normal exit when the running list cannot answer', async () => { running = async () => ({ status: 'unavailable' }) const exits = collectExits() diff --git a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts new file mode 100644 index 00000000000..9dbf9aecc33 --- /dev/null +++ b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts @@ -0,0 +1,149 @@ +// Bridge bash reports no folder; a distro stopped while Orca was quit left the pane at its spawn folder. +import './mock-descendant-sweep' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { readFileSync, rmSync } from 'node:fs' +import { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { DaemonServer } from './daemon-server' +import { getHistorySessionDirName } from './history-paths' +import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' +import type { WslGuestProcessRow } from '../wsl/wsl-guest-pane-processes' +import type * as GuestProcessesModule from '../wsl/wsl-guest-pane-processes' +import * as startupCwdProbe from '../ipc/pty/host-env/startup-cwd-directory-exists' + +const readRows = vi.hoisted(() => + vi.fn( + async ( + _distro: string, + _timeoutMs: number, + _opts?: { running?: boolean } + ): Promise => null + ) +) +vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({ + ...(await importOriginal()), + readWslGuestPaneProcesses: readRows +})) + +const PANE_KEY = '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222' +const WSL_CWD = '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' +const DEEP = `${WSL_CWD}\\deep` + +/** Shortens quit's folder budget so an unanswering distro is not a real-time wait. */ +class QuickQuitDaemonPtyAdapter extends DaemonPtyAdapter { + protected quitWslCwdBudgetMs = 5 +} + +describe('a bridge WSL pane keeps its shell folder across quit', () => { + let dir: string + let socketPath: string + let tokenPath: string + let server: DaemonServer + let harnessAdapter: DaemonPtyAdapter + let adapters: DaemonPtyAdapter[] = [] + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + const spawnCwds: (string | undefined)[] = [] + let lastSubprocess: ReturnType + + beforeEach(async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + readRows.mockReset() + readRows.mockResolvedValue([ + { pid: 10, ppid: 1, comm: 'bash', paneKey: PANE_KEY, cwd: '/home/jin/repo/deep' } + ]) + spawnCwds.length = 0 + const harness = await startDaemonAdapterHarness((opts) => { + spawnCwds.push(opts.cwd) + lastSubprocess = createMockSubprocess() + return lastSubprocess + }) + ;({ dir, socketPath, tokenPath, server } = harness) + harnessAdapter = harness.adapter + }) + + afterEach(async () => { + vi.restoreAllMocks() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + for (const adapter of adapters) { + adapter.dispose() + } + adapters = [] + harnessAdapter.dispose() + await server.shutdown() + rmSync(dir, { recursive: true, force: true }) + }) + + const historyDir = () => join(dir, 'history') + const launch = (Adapter: typeof DaemonPtyAdapter = DaemonPtyAdapter) => { + const adapter = new Adapter({ socketPath, tokenPath, historyPath: historyDir() }) + adapters.push(adapter) + return adapter + } + const checkpointCwd = (id: string) => + JSON.parse( + readFileSync(join(historyDir(), getHistorySessionDirName(id), 'checkpoint.json'), 'utf-8') + ).cwd + const openBridgePane = (adapter: DaemonPtyAdapter, sessionId: string, cwd = WSL_CWD) => + adapter.spawn({ cols: 80, rows: 24, cwd, env: { ORCA_PANE_KEY: PANE_KEY }, sessionId }) + + it("saves the shell's folder in quit's final checkpoint, never booting the distro", async () => { + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@quit') + lastSubprocess._simulateData('$ cd deep\r\n') + + await app.disconnectOnly() + + // `running` lets the read skip its check only when the running-distro cache confirms it. + expect(readRows).toHaveBeenCalledWith('Ubuntu', expect.any(Number), { running: true }) + expect(checkpointCwd(id)).toBe(DEEP) + }) + + it('reopens in that folder when the distro stopped while Orca was quit', async () => { + vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true) + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@terminated') + lastSubprocess._simulateData('$ cd deep\r\n') + await app.disconnectOnly() + // `wsl --terminate` ends the bridge's wsl.exe; the daemon reaps the session. + lastSubprocess._simulateExit(1) + + const relaunched = launch() + await relaunched.reconcileOnStartup(new Set(['repo::/repo'])) + const restored = await openBridgePane(relaunched, id) + + expect(restored.coldRestore).toBeTruthy() + expect(spawnCwds.at(-1)).toBe(DEEP) + }) + + it('keeps the spawn folder when the distro cannot be read', async () => { + readRows.mockResolvedValue(null) + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@unreadable') + + await app.disconnectOnly() + + expect(checkpointCwd(id)).toBe(WSL_CWD) + }) + + it('quits on its budget when the distro does not answer', async () => { + readRows.mockReturnValue(new Promise(() => {})) + const app = launch(QuickQuitDaemonPtyAdapter) + const { id } = await openBridgePane(app, 'repo::/repo@@silent') + + await app.disconnectOnly() + + expect(readRows.mock.calls[0]?.[1]).toBe(5) + expect(checkpointCwd(id)).toBe(WSL_CWD) + }) + + it('reads no distro for a pane that is not a WSL pane', async () => { + const app = launch() + await openBridgePane(app, 'repo::/repo@@windows', 'C:\\repo') + + await app.disconnectOnly() + + expect(readRows).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd-relaunch.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd-relaunch.test.ts new file mode 100644 index 00000000000..bb54de627af --- /dev/null +++ b/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd-relaunch.test.ts @@ -0,0 +1,153 @@ +import './mock-descendant-sweep' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { readFileSync, rmSync } from 'node:fs' +import { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { DaemonServer } from './daemon-server' +import { getHistorySessionDirName } from './history-paths' +import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' +import type { WslGuestProcessRow } from '../wsl/wsl-guest-pane-processes' +import type * as GuestProcessesModule from '../wsl/wsl-guest-pane-processes' +import * as startupCwdProbe from '../ipc/pty/host-env/startup-cwd-directory-exists' + +const readRows = vi.hoisted(() => + vi.fn( + async ( + _distro: string, + _timeoutMs: number, + _opts?: { running?: boolean } + ): Promise => null + ) +) +vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({ + ...(await importOriginal()), + readWslGuestPaneProcesses: readRows +})) + +const PANE_KEY = '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222' +const WSL_CWD = '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' + +function shellIn(cwd: string): WslGuestProcessRow[] { + return [ + { pid: 10, ppid: 1, comm: 'bash', paneKey: PANE_KEY, cwd }, + { pid: 11, ppid: 10, comm: 'sleep', paneKey: PANE_KEY, cwd: '/tmp' } + ] +} + +// awin 5e: a bridge pane reopened or reattached around a reload or relaunch must still know its distro and pane key at Sleep. +describe('a sleeping bridge WSL pane keeps its shell folder across reloads and relaunches', () => { + let dir: string + let socketPath: string + let tokenPath: string + let server: DaemonServer + let harnessAdapter: DaemonPtyAdapter + let adapter: DaemonPtyAdapter | undefined + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + + beforeEach(async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + readRows.mockReset() + readRows.mockResolvedValue(shellIn('/home/jin/repo/deep/er')) + const harness = await startDaemonAdapterHarness(() => createMockSubprocess()) + ;({ dir, socketPath, tokenPath, server } = harness) + harnessAdapter = harness.adapter + }) + + afterEach(async () => { + vi.restoreAllMocks() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + adapter?.dispose() + harnessAdapter.dispose() + await server.shutdown() + rmSync(dir, { recursive: true, force: true }) + }) + + const historyDir = () => join(dir, 'history') + const checkpointCwd = (id: string) => + JSON.parse( + readFileSync(join(historyDir(), getHistorySessionDirName(id), 'checkpoint.json'), 'utf-8') + ).cwd + + const spawnPane = ( + a: DaemonPtyAdapter, + sessionId: string, + env: Record | undefined + ) => a.spawn({ cols: 80, rows: 24, cwd: WSL_CWD, ...(env ? { env } : {}), sessionId }) + + it('after a renderer reload re-spawns it with its environment', async () => { + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(adapter, 'repo::/repo@@s1', { ORCA_PANE_KEY: PANE_KEY }) + await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY }) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + }) + + it('after a relaunch adopts it and the window re-spawns it with its environment', async () => { + const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(before, 'repo::/repo@@s2', { ORCA_PANE_KEY: PANE_KEY }) + await before.disconnectOnly() + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + await adapter.reconcileOnStartup(new Set(['repo::/repo'])) + await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY }) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + }) + + it('after a relaunch adopts it and the window re-spawns it without its environment', async () => { + const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(before, 'repo::/repo@@s3', { ORCA_PANE_KEY: PANE_KEY }) + await before.disconnectOnly() + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + await adapter.reconcileOnStartup(new Set(['repo::/repo'])) + await spawnPane(adapter, id, undefined) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + }) + + it('after a relaunch whose window re-spawns it with its environment before adoption', async () => { + const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(before, 'repo::/repo@@s4', { ORCA_PANE_KEY: PANE_KEY }) + await before.disconnectOnly() + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY }) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + }) + + it('after a relaunch whose window re-spawns it without its environment before adoption', async () => { + const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(before, 'repo::/repo@@s5', { ORCA_PANE_KEY: PANE_KEY }) + await before.disconnectOnly() + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + await spawnPane(adapter, id, undefined) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + }) + + it('when slept again after a wake, at the folder it moved to', async () => { + vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true) + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(adapter, 'repo::/repo@@s6', { ORCA_PANE_KEY: PANE_KEY }) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + readRows.mockResolvedValue(shellIn('/home/jin/repo/other')) + await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY }) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\other`) + }) + + it('when a woken pane is slept by a relaunched app that only adopted it', async () => { + vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true) + const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + const { id } = await spawnPane(before, 'repo::/repo@@s7', { ORCA_PANE_KEY: PANE_KEY }) + await before.shutdown(id, { immediate: true, keepHistory: true }) + await spawnPane(before, id, { ORCA_PANE_KEY: PANE_KEY }) + await before.disconnectOnly() + adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() }) + await adapter.reconcileOnStartup(new Set(['repo::/repo'])) + readRows.mockResolvedValue(shellIn('/home/jin/repo/other')) + await adapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\other`) + }) +}) diff --git a/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts index 0153763b6d4..27dcdf806ee 100644 --- a/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts +++ b/src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts @@ -91,10 +91,20 @@ describe('a sleeping bridge WSL pane keeps its shell folder', () => { sessionId: 'repo::/repo@@spawned' }) + const info = vi.spyOn(console, 'info').mockImplementation(() => {}) await adapter.shutdown(id, { immediate: true, keepHistory: true }) expect(readRows).toHaveBeenCalledWith('Ubuntu', expect.any(Number), { running: true }) expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`) + const lines = info.mock.calls + .map(([line]) => String(line)) + .filter((line) => line.includes('Sleep folder')) + // One line per Sleep, naming the branch, what the distro returned and whether a folder came back. + expect(lines).toHaveLength(1) + expect(lines[0]).toContain(`[history] Sleep folder for ${id}: wsl probe (budget `) + expect(lines[0]).toContain( + `rows 2, shells 1), distro Ubuntu, pane ${PANE_KEY}, live true, folder found in ` + ) }) // awin verify-9: panes cd'd before a relaunch and slept before the window reopened them diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 3b302f4e89d..19b614e34b7 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -6,7 +6,7 @@ import { import { FENCED_TERMINATION_PROTOCOL_VERSION } from './daemon-protocol-version' import { emitPtyListeners, createPtyExitPayload } from './daemon-pty-listener-emission' import type { DaemonPtyRouterExitEvent } from './daemon-pty-router-events' -import { checkWslBridgeDistro, WSL_DISTRO_LOSS_EXIT_CODE } from './daemon-wsl-bridge-exit' +import { classifyWslBridgeExit, WSL_DISTRO_LOSS_EXIT_CODE } from './daemon-wsl-bridge-exit' import { isProvenProcessExit } from '../../shared/terminal-exit-cause' import { DaemonPtyDaemonRecovery } from './daemon-pty-daemon-recovery' import type { DaemonPtyAdapterOptions } from './daemon-pty-runtime-state' @@ -211,15 +211,25 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro ) operation.exitsBySessionId.set(event.sessionId, exits) } + const wslDistro = this.wslDistrosBySessionId.get(event.sessionId) // Retain raced exits for pending spawns; only this adapter's published incarnation may clear state or notify. if ( currentIncarnationId !== undefined && event.payload.incarnationId !== currentIncarnationId ) { + // A stale exit may still be a reboot's; the respawn that beat it re-reads its boot id. + if (wslDistro) { + this.wslBridgeBootIdentity.noteStaleExit(event.sessionId, wslDistro) + } return } - const wslDistro = this.wslDistrosBySessionId.get(event.sessionId) - if (wslDistro && isProvenProcessExit(event.payload.code)) { + // Every bridge exit marks a possible stop (unseen to the user; covers poweroff or --shutdown). + if (wslDistro) { + this.wslBridgeBootIdentity.noteExit(wslDistro) + } + // A terminate never exits 0 (awin: -1 per bridge pane; `exit`/`exit 0` gave 0): a clean exit is + // the user's own, so it closes at once, without the settle wait or classification. + if (wslDistro && event.payload.code !== 0 && isProvenProcessExit(event.payload.code)) { const exitAt = performance.now() void this.finishWslBridgeExit(event.sessionId, event.payload, wslDistro, exitAt) return @@ -243,17 +253,20 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro wslDistro: string, exitAt: number ): Promise { - const verdict = await checkWslBridgeDistro(wslDistro, exitAt, this.readRunningWslDistros) - // Only 'lost' keeps the tab; a reboot (or slow wsl.exe) racing the probe reads as an exit. + const verdict = await classifyWslBridgeExit(wslDistro, exitAt, this.readRunningWslDistros, () => + this.wslBridgeBootIdentity.rebootedSinceSpawn(sessionId, wslDistro) + ) + // Lost, or booted again since the spawn, keeps the tab; an unanswered check reads as an exit. + // The code shows a verify run which codes a terminate yields. console.info( - `[pty] WSL bridge exit: ${verdict} (distro ${wslDistro}, probe ${Math.round(performance.now() - exitAt)}ms)` + `[pty] WSL bridge exit: ${verdict} (distro ${wslDistro}, code ${exit.code}, probe ${Math.round(performance.now() - exitAt)}ms)` ) // A spawn that replaced this incarnation meanwhile owns the session now. const current = this.sessionIncarnations.get(sessionId) if (current !== undefined && current !== exit.incarnationId) { return } - if (verdict !== 'lost') { + if (verdict !== 'lost' && verdict !== 'rebooted') { this.finishExit(sessionId, exit) return } diff --git a/src/main/daemon/daemon-pty-checkpoint-persistence.ts b/src/main/daemon/daemon-pty-checkpoint-persistence.ts index b91c4f2c2e1..2675463ecd6 100644 --- a/src/main/daemon/daemon-pty-checkpoint-persistence.ts +++ b/src/main/daemon/daemon-pty-checkpoint-persistence.ts @@ -112,8 +112,9 @@ export abstract class DaemonPtyCheckpointPersistence extends DaemonPtyCheckpoint ? { requiredPreviousPendingOutputSeq: take.seq - 1 } : {}) }) - const sleepCwd = opts.teardown ? this.sleepShellCwds.get(sessionId) : undefined - const snapshot = sleepCwd ? { ...durable, cwd: sleepCwd } : durable + // Set only inside an exclusive final pass (Sleep or quit), so no other checkpoint sees it. + const probedCwd = this.probedShellCwds.get(sessionId) + const snapshot = probedCwd ? { ...durable, cwd: probedCwd } : durable const checkpoint = await this.historyManager.checkpoint(sessionId, snapshot, { pendingOutputSeq: take.seq }) diff --git a/src/main/daemon/daemon-pty-event-subscriptions.ts b/src/main/daemon/daemon-pty-event-subscriptions.ts index a8bba5d70da..27563bacddf 100644 --- a/src/main/daemon/daemon-pty-event-subscriptions.ts +++ b/src/main/daemon/daemon-pty-event-subscriptions.ts @@ -10,6 +10,7 @@ import { } from './types' import type { DaemonIdleRetirementResult } from './daemon-pty-runtime-state' import type { PtyBackgroundStreamEvent } from '../providers/pty-provider-contract' +import { readDaemonWslQuitCwds } from './daemon-wsl-sleep-cwd' export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInventory { onData(callback: (payload: DaemonPtyRouterDataEvent) => void): () => void { @@ -174,6 +175,14 @@ export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInvent } } + private wslBridgePanesForQuit(): { sessionId: string; paneKey: string; wslDistro: string }[] { + return [...this.activeSessionIds].flatMap((sessionId) => { + const wslDistro = this.wslDistrosBySessionId.get(sessionId) + const paneKey = this.wslPaneKeysBySessionId.get(sessionId) + return wslDistro && paneKey ? [{ sessionId, paneKey, wslDistro }] : [] + }) + } + private reopenAfterRefusedIdleRetirement(): void { this.idleRetirementState = 'open' this.idleRetirementAdmissionClosed = false @@ -196,10 +205,27 @@ export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInvent // Let admitted sleep shutdowns finish recovery and kill RPCs before disconnecting their client. await Promise.allSettled(keepHistoryShutdowns) this.respawnAdoptionClosed = true + // Bridge bash reports no folder and the daemon outlives quit; a distro stopped before relaunch leaves only this read. + const shellCwds = await readDaemonWslQuitCwds( + this.wslBridgePanesForQuit(), + this.quitWslCwdBudgetMs + ) // Await final checkpoints, including new sessions, before disconnect can reject their snapshot RPCs. - await this.runExclusiveCheckpoint(() => this.checkpointAllSessions(), { - rescheduleDirty: false - }) + await this.runExclusiveCheckpoint( + async () => { + for (const [id, cwd] of shellCwds) { + this.probedShellCwds.set(id, cwd) + } + try { + await this.checkpointAllSessions() + } finally { + for (const id of shellCwds.keys()) { + this.probedShellCwds.delete(id) + } + } + }, + { rescheduleDirty: false } + ) this.dirtySessionVersions.clear() this.lastFullCheckpointAt.clear() this.coldRestoreCache.clear() diff --git a/src/main/daemon/daemon-pty-runtime-state.ts b/src/main/daemon/daemon-pty-runtime-state.ts index a847d8a8559..03f8d99f391 100644 --- a/src/main/daemon/daemon-pty-runtime-state.ts +++ b/src/main/daemon/daemon-pty-runtime-state.ts @@ -32,6 +32,7 @@ import { HistoryReader } from './history-reader' import type { PtyBackgroundStreamEvent } from '../providers/pty-provider-contract' import type { DaemonPtyRouterDataEvent, DaemonPtyRouterExitEvent } from './daemon-pty-router-events' import type { ReadRunningWslDistros } from './daemon-wsl-bridge-exit' +import { WslBridgeBootIdentity } from './daemon-wsl-bridge-boot-identity' export type PendingDaemonSpawnOperation = { exitsBySessionId: Map @@ -62,6 +63,8 @@ export type DaemonPtyAdapterOptions = { respawn?: (reason: DaemonRespawnReason) => Promise void)> /** Test seam; production reads the shared, coalesced `wsl --list --running`. */ readRunningWslDistros?: ReadRunningWslDistros + /** Test seam; production reads each distro's boot id through the background-work gate. */ + wslBridgeBootIdentity?: WslBridgeBootIdentity } export type DaemonRespawnReason = @@ -83,6 +86,7 @@ export type DaemonIdleRetirementResult = export abstract class DaemonPtyRuntimeState { protected readonly readRunningWslDistros: ReadRunningWslDistros | undefined + protected readonly wslBridgeBootIdentity: WslBridgeBootIdentity readonly protocolVersion: number protected socketPath: string protected tokenPath: string @@ -121,8 +125,10 @@ export abstract class DaemonPtyRuntimeState { protected readonly hostLossSessionIds = new Set() /** ORCA_PANE_KEY a WSL session was spawned with; its shell's folder is read by it at Sleep. */ protected wslPaneKeysBySessionId = new Map() - /** A sleeping WSL pane's shell folder, read before its final checkpoint; the checkpoint keeps it. */ - protected sleepShellCwds = new Map() + /** A WSL bridge shell's folder read before a final checkpoint (Sleep or quit); that checkpoint keeps it. */ + protected probedShellCwds = new Map() + /** Quit's whole wait for bridge shell folders; a slow distro must not hold up quitting. */ + protected quitWslCwdBudgetMs = 1_000 protected killedSessionTombstones = new Map() protected sleepRestoreSessionIds = new Set() protected coldRestoreCache = new ColdRestorePayloadCache(undefined, (sessionId) => { @@ -209,6 +215,7 @@ export abstract class DaemonPtyRuntimeState { } this.initialCwds.delete(sessionId) this.wslDistrosBySessionId.delete(sessionId) + this.wslBridgeBootIdentity.forget(sessionId) this.wslPaneKeysBySessionId.delete(sessionId) this.sessionIncarnations.delete(sessionId) } @@ -239,6 +246,7 @@ export abstract class DaemonPtyRuntimeState { this.historyReader = opts.historyPath ? new HistoryReader(opts.historyPath) : null this.respawnFn = opts.respawn ?? null this.readRunningWslDistros = opts.readRunningWslDistros + this.wslBridgeBootIdentity = opts.wslBridgeBootIdentity ?? new WslBridgeBootIdentity() this.runtimeDir = opts.runtimeDir ?? opts.profileScope ?? null this.packagedAppVersion = opts.packagedAppVersion ?? null this.supportsCheckpoints = this.protocolVersion >= 4 diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts index d6970fbac0e..9e861909097 100644 --- a/src/main/daemon/daemon-pty-session-control.ts +++ b/src/main/daemon/daemon-pty-session-control.ts @@ -4,10 +4,11 @@ import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version' import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size' import { FinalCheckpointWaitExpiredError } from './daemon-pty-lifecycle-errors' import { DaemonPtySessionInput } from './daemon-pty-session-input' -import { remainingDaemonRequestTimeoutMs, teardownReadBudgetMs } from './daemon-request-deadline' +import { remainingDaemonRequestTimeoutMs } from './daemon-request-deadline' +import { readDaemonLiveSleepCwd } from './daemon-live-sleep-cwd' import type { ColdRestoreInfo } from './history-reader' import { normalizeWslColdRestoreCwd } from './wsl-cold-restore-cwd' -import { readDaemonWslSleepCwd } from './daemon-wsl-sleep-cwd' +import { describeSleepFolderRead, readDaemonWslSleepCwdWithFacts } from './daemon-wsl-sleep-cwd' import * as unlistedSession from './daemon-unlisted-session' import { SessionNotFoundError, type ListSessionsResult } from './types' import { resolveSafePtyDefaultCwd } from '../providers/pty-default-cwd' @@ -17,7 +18,6 @@ export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 const MAX_TOMBSTONES = 1000 // A busy daemon must not eat the final checkpoint's share of the Sleep deadline. -const LIVE_SLEEP_CWD_BUDGET_MS = 1_500 export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { protected abstract adoptListedSessionForSleep( @@ -141,28 +141,36 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { if (opts.keepHistory) { const sleepWslDistro = this.wslDistrosBySessionId.get(id) const sleepPaneKey = this.wslPaneKeysBySessionId.get(id) - const sleepCwd = + const live = this.activeSessionIds.has(id) + const startedAt = Date.now() + const read = sleepWslDistro && sleepPaneKey - ? await readDaemonWslSleepCwd( - { - paneKey: sleepPaneKey, - wslDistro: sleepWslDistro, - // A live pane's own wsl.exe keeps its distro running. - live: this.activeSessionIds.has(id) - }, + ? // A live pane's own wsl.exe keeps its distro running. + await readDaemonWslSleepCwdWithFacts( + { paneKey: sleepPaneKey, wslDistro: sleepWslDistro, live }, opts.deadlineMs ) - : await this.readLiveSleepCwd(id, opts.deadlineMs) + : { cwd: live ? await readDaemonLiveSleepCwd(this.client, id, opts.deadlineMs) : null } + const sleepCwd = read.cwd + // Device runs need to see why a WSL pane woke at its spawn folder (awin 5e). + console.info( + describeSleepFolderRead(id, read, { + wslDistro: sleepWslDistro, + paneKey: sleepPaneKey, + live, + elapsedMs: Date.now() - startedAt + }) + ) const committed = await this.runExclusiveCheckpoint( async () => { // Set inside: a caller past its deadline leaves this checkpoint running without it. if (sleepCwd) { - this.sleepShellCwds.set(id, sleepCwd) + this.probedShellCwds.set(id, sleepCwd) } try { await this.checkpointSessions([id], { final: true, teardown: true }) } finally { - this.sleepShellCwds.delete(id) + this.probedShellCwds.delete(id) } }, { callerDeadlineMs: opts.deadlineMs } @@ -301,29 +309,6 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { } } - /** - * A native shell's folder at Sleep (OSC 7, else its process's cwd). Bash prints no OSC 7, so - * without this the checkpoint keeps the spawn folder and Wake opens there (e.g. on a Linux host). - */ - private async readLiveSleepCwd(id: string, deadlineMs?: number): Promise { - // Windows has no process-cwd lookup (it would spawn a missing lsof); the snapshot's OSC 7 cwd stands. - const budget = teardownReadBudgetMs(LIVE_SLEEP_CWD_BUDGET_MS, deadlineMs) - if (process.platform === 'win32' || budget <= 0 || !this.activeSessionIds.has(id)) { - return null - } - try { - const { cwd } = await this.client.request<{ cwd: string | null }>( - 'getCwd', - { sessionId: id }, - budget - ) - // A removed folder reads back from /proc as ` (deleted)`, which no shell can return to. - return cwd && !cwd.endsWith(' (deleted)') ? cwd : null - } catch { - return null - } - } - async getInitialCwd(id: string): Promise { return this.initialCwds.get(id) ?? '' } diff --git a/src/main/daemon/daemon-pty-spawn-request.ts b/src/main/daemon/daemon-pty-spawn-request.ts index ea5abb25641..fc7271d5110 100644 --- a/src/main/daemon/daemon-pty-spawn-request.ts +++ b/src/main/daemon/daemon-pty-spawn-request.ts @@ -224,4 +224,20 @@ export abstract class DaemonPtySpawnRequest extends DaemonPtyRuntimeState { ? { ...result, historySeeded: false } : result } + + /** Records a spawn result's WSL distro (and its boot id), or clears it when `clear`. */ + protected noteSpawnWslDistro( + sessionId: string, + wslDistro: string | undefined, + clear: boolean, + incarnationId?: string + ): void { + if (wslDistro) { + this.wslDistrosBySessionId.set(sessionId, wslDistro) + this.wslBridgeBootIdentity.noteSpawn(sessionId, wslDistro, incarnationId) + } else if (clear) { + this.wslDistrosBySessionId.delete(sessionId) + this.wslBridgeBootIdentity.forget(sessionId) + } + } } diff --git a/src/main/daemon/daemon-pty-spawn-result.ts b/src/main/daemon/daemon-pty-spawn-result.ts index 167edd5f628..b390f94c749 100644 --- a/src/main/daemon/daemon-pty-spawn-result.ts +++ b/src/main/daemon/daemon-pty-spawn-result.ts @@ -88,11 +88,12 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest { // Null overrides caller WSL preference; undefined preserves compatibility with older daemons. wslDistro = providerWslDistro ?? undefined context.wslDistro = wslDistro - if (wslDistro) { - this.wslDistrosBySessionId.set(sessionId, wslDistro) - } else if (providerWslDistro === null || result.isNew) { - this.wslDistrosBySessionId.delete(sessionId) - } + this.noteSpawnWslDistro( + sessionId, + wslDistro, + providerWslDistro === null || result.isNew, + result.incarnationId + ) if (wslDistro && opts.env?.ORCA_PANE_KEY) { this.wslPaneKeysBySessionId.set(sessionId, opts.env.ORCA_PANE_KEY) } @@ -160,11 +161,12 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest { providerWslDistro = result.wslDistro === undefined ? wslDistro : result.wslDistro wslDistro = providerWslDistro ?? undefined context.wslDistro = wslDistro - if (wslDistro) { - this.wslDistrosBySessionId.set(sessionId, wslDistro) - } else if (providerWslDistro === null || result.isNew) { - this.wslDistrosBySessionId.delete(sessionId) - } + this.noteSpawnWslDistro( + sessionId, + wslDistro, + providerWslDistro === null || result.isNew, + result.incarnationId + ) pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : null this.initialCwds.set(sessionId, effectiveCwd) } diff --git a/src/main/daemon/daemon-rpc-shutdown-deadline.test.ts b/src/main/daemon/daemon-rpc-shutdown-deadline.test.ts index 6084ba6562d..038dd6feaae 100644 --- a/src/main/daemon/daemon-rpc-shutdown-deadline.test.ts +++ b/src/main/daemon/daemon-rpc-shutdown-deadline.test.ts @@ -51,7 +51,8 @@ async function start(): Promise<{ throw new Error('No PTY expected') }, onShutdownRequested: requested, - onRpcShutdown: deadline.cancel + onRpcShutdown: deadline.cancel, + onIdleShutdown: deadline.cancel }) client = new DaemonClient({ socketPath, tokenPath }) await client.ensureConnected() @@ -91,3 +92,23 @@ it('cancels the deadline when the RPC completes normally', async () => { await vi.advanceTimersByTimeAsync(DAEMON_SHUTDOWN_TIMEOUT_MS) expect(exit).not.toHaveBeenCalled() }) + +it.each(['disconnect', 'shutdownIfIdle'] as const)( + 'bounds idle retirement after %s when terminal disposal never settles', + async (mode) => { + const { exit, requested } = await start() + const stalled = new Promise((resolve) => { + releaseDisposal = resolve + }) + const dispose = vi.spyOn(TerminalHost.prototype, 'dispose').mockReturnValue(stalled) + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + if (mode === 'shutdownIfIdle') { + await expect(client.request('shutdownIfIdle', undefined)).resolves.toEqual({ retiring: true }) + } + client.disconnect() + await vi.waitFor(() => expect(dispose).toHaveBeenCalled()) + expect(requested).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(DAEMON_SHUTDOWN_TIMEOUT_MS) + expect(exit).toHaveBeenCalledOnce() + } +) diff --git a/src/main/daemon/daemon-runtime-dir.ts b/src/main/daemon/daemon-runtime-dir.ts new file mode 100644 index 00000000000..90a5df9b363 --- /dev/null +++ b/src/main/daemon/daemon-runtime-dir.ts @@ -0,0 +1,6 @@ +import { join } from 'node:path' + +/** The daemon runtime dir of a server serving this data root. */ +export function daemonRuntimeDirFor(userDataPath: string): string { + return join(userDataPath, 'daemon') +} diff --git a/src/main/daemon/daemon-server-lifecycle.ts b/src/main/daemon/daemon-server-lifecycle.ts index f2ce63314e5..0f46104da15 100644 --- a/src/main/daemon/daemon-server-lifecycle.ts +++ b/src/main/daemon/daemon-server-lifecycle.ts @@ -171,6 +171,7 @@ export class DaemonServerLifecycle { } retireAfterIdleReply(clientId: string, requestId: string, socket: Socket): void { + this.options.onShutdownRequested() this.state = 'shutting-down' this.initialAdoptionDeadlineMs = null this.retirementRequested = false @@ -210,6 +211,7 @@ export class DaemonServerLifecycle { this.reevaluateIdleShutdown() return } + this.options.onShutdownRequested() this.state = 'shutting-down' const serverClose = this.beginServerClose() this.shutdownPromise = this.finishIdleShutdown(serverClose) diff --git a/src/main/daemon/daemon-wsl-bridge-boot-identity.test.ts b/src/main/daemon/daemon-wsl-bridge-boot-identity.test.ts new file mode 100644 index 00000000000..ced31515c36 --- /dev/null +++ b/src/main/daemon/daemon-wsl-bridge-boot-identity.test.ts @@ -0,0 +1,177 @@ +import { describe, expect, it, vi } from 'vitest' +import { WslBridgeBootIdentity } from './daemon-wsl-bridge-boot-identity' + +function identity(options: { running?: boolean; ids?: (string | null)[] } = {}) { + const ids = [...(options.ids ?? ['boot-1'])] + const isRunning = vi.fn(async () => options.running ?? true) + const readBootId = vi.fn(async () => (ids.length > 1 ? ids.shift()! : (ids[0] ?? null))) + return { boot: new WslBridgeBootIdentity({ isRunning, readBootId }), isRunning, readBootId } +} + +describe('WslBridgeBootIdentity', () => { + it('reads each distro once while any of its panes lives', async () => { + const { boot, readBootId } = identity() + boot.noteSpawn('a', 'Ubuntu') + boot.noteSpawn('b', 'ubuntu') + boot.noteSpawn('a', 'Ubuntu') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + }) + + it('calls an exit rebooted only when the distro booted again since the spawn', async () => { + const same = identity({ ids: ['boot-1'] }) + same.boot.noteSpawn('a', 'Ubuntu') + await expect(same.boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + + const again = identity({ ids: ['boot-1', 'boot-2'] }) + again.boot.noteSpawn('a', 'Ubuntu') + await expect(again.boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(true) + }) + + it('falls back to an exit when either id is unreadable, or the pane was never noted', async () => { + for (const ids of [ + [null, 'boot-2'], + ['boot-1', null] + ]) { + const { boot } = identity({ ids }) + boot.noteSpawn('a', 'Ubuntu') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + } + await expect(identity().boot.rebootedSinceSpawn('unknown', 'Ubuntu')).resolves.toBe(false) + }) + + it('never reads a distro the background-work gate does not confirm running (E9)', async () => { + const { boot, readBootId } = identity({ running: false }) + boot.noteSpawn('a', 'Ubuntu') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + expect(readBootId).not.toHaveBeenCalled() + }) + + it('reads again for a spawn after an exit, or after its last pane went away', async () => { + const { boot, readBootId } = identity({ ids: ['boot-1', 'boot-2', 'boot-3', 'boot-4'] }) + boot.noteSpawn('a', 'Ubuntu') + boot.noteSpawn('b', 'Ubuntu') + boot.noteExit('Ubuntu') + boot.noteSpawn('c', 'Ubuntu') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledTimes(2)) + boot.forget('a') + boot.forget('b') + boot.forget('c') + boot.noteSpawn('d', 'Ubuntu') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledTimes(3)) + }) + + // Reviewers of #35050: a spawn during an earlier exit's verdict took the old boot's id. + it("gives a pane spawned during another's exit verdict the new boot, so its own exit is an exit", async () => { + const world = { boot: 'boot-1' } + const readBootId = vi.fn(async () => world.boot) + const boot = new WslBridgeBootIdentity({ isRunning: async () => true, readBootId }) + boot.noteSpawn('a', 'Ubuntu', 'inc-a') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + // The distro is terminated and booted again; A's exit arrives, and C opens before A's verdict. + world.boot = 'boot-2' + boot.noteExit('Ubuntu') + boot.noteSpawn('c', 'Ubuntu', 'inc-c') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(true) + boot.forget('a') + + boot.noteExit('Ubuntu') + await expect(boot.rebootedSinceSpawn('c', 'Ubuntu')).resolves.toBe(false) + }) + + it('gives a respawn of the same session into a rebooted distro the new boot id', async () => { + const world = { boot: 'boot-1' } + const readBootId = vi.fn(async () => world.boot) + const boot = new WslBridgeBootIdentity({ isRunning: async () => true, readBootId }) + boot.noteSpawn('a', 'Ubuntu', 'inc-1') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + world.boot = 'boot-2' + boot.noteExit('Ubuntu') + boot.noteSpawn('a', 'Ubuntu', 'inc-2') + + boot.noteExit('Ubuntu') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + }) + + // #35050 review, case 1b: a respawn into a rebooted distro beat the dead process's exit event. + it('re-reads the boot id of a respawn that beat its old incarnation’s exit', async () => { + const world = { boot: 'boot-1' } + const readBootId = vi.fn(async () => world.boot) + const boot = new WslBridgeBootIdentity({ isRunning: async () => true, readBootId }) + boot.noteSpawn('a', 'Ubuntu', 'inc-1') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + world.boot = 'boot-2' + // The respawn lands first and takes the cached (old) id; then the stale exit arrives. + boot.noteSpawn('a', 'Ubuntu', 'inc-2') + boot.noteStaleExit('a', 'Ubuntu') + boot.noteSpawn('b', 'Ubuntu', 'inc-b') + + boot.noteExit('Ubuntu') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + await expect(boot.rebootedSinceSpawn('b', 'Ubuntu')).resolves.toBe(false) + }) + + // #35050 review (b): a pane spawned after the stop was seen, before any exit reached the adapter. + it('drops the cached id when a running list sees the distro stop, and listens only while panes live', async () => { + const world = { boot: 'boot-1' } + const readBootId = vi.fn(async () => world.boot) + let stopped: ((distros: string[]) => void) | null = null + const unsubscribe = vi.fn(() => { + stopped = null + }) + const boot = new WslBridgeBootIdentity({ + isRunning: async () => true, + readBootId, + onDistrosStopped: (listener) => { + stopped = listener + return unsubscribe + } + }) + expect(stopped).toBeNull() + boot.noteSpawn('a', 'Ubuntu', 'inc-a') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + + world.boot = 'boot-2' + stopped!(['ubuntu']) + boot.noteSpawn('b', 'Ubuntu', 'inc-b') + boot.noteExit('Ubuntu') + await expect(boot.rebootedSinceSpawn('b', 'Ubuntu')).resolves.toBe(false) + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(true) + + boot.forget('a') + expect(unsubscribe).not.toHaveBeenCalled() + boot.forget('b') + expect(unsubscribe).toHaveBeenCalledOnce() + }) + + it('keeps the id across a reattach of the same incarnation', async () => { + const { boot, readBootId } = identity({ ids: ['boot-1', 'boot-2'] }) + boot.noteSpawn('a', 'Ubuntu', 'inc-1') + boot.noteExit('Ubuntu') + boot.noteSpawn('a', 'Ubuntu', 'inc-1') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + }) + + it('shares one read of the current id across a burst of exits', async () => { + const { boot, readBootId } = identity({ ids: ['boot-1', 'boot-2'] }) + for (const id of ['a', 'b', 'c']) { + boot.noteSpawn(id, 'Ubuntu') + } + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + boot.noteExit('Ubuntu') + await expect( + Promise.all(['a', 'b', 'c'].map((id) => boot.rebootedSinceSpawn(id, 'Ubuntu'))) + ).resolves.toEqual([true, true, true]) + expect(readBootId).toHaveBeenCalledTimes(2) + }) + + it('treats a failing read as unreadable', async () => { + const boot = new WslBridgeBootIdentity({ + isRunning: async () => true, + readBootId: async () => { + throw new Error('wsl.exe failed') + } + }) + boot.noteSpawn('a', 'Ubuntu') + await expect(boot.rebootedSinceSpawn('a', 'Ubuntu')).resolves.toBe(false) + }) +}) diff --git a/src/main/daemon/daemon-wsl-bridge-boot-identity.ts b/src/main/daemon/daemon-wsl-bridge-boot-identity.ts new file mode 100644 index 00000000000..dcbcc46412a --- /dev/null +++ b/src/main/daemon/daemon-wsl-bridge-boot-identity.ts @@ -0,0 +1,145 @@ +/** + * Each WSL bridge pane remembers its distro's boot id from its spawn, so an exit the running list + * calls 'running' can still be told apart as the distro having been terminated and booted again. + * Reads go through the background-work gate (E9): only into a distro a fresh list says is running. + */ +import { + isWslDistroRunningForBackgroundWork, + noteWslDistroMayHaveStopped +} from '../wsl-background-distro-gate' +import { onRunningWslDistrosStopped } from '../wsl-running-distro-cache' +import { readWslDistroBootId } from '../wsl/wsl-distro-boot-id' + +export type WslBridgeBootIdentityDeps = { + isRunning: (distro: string) => Promise + /** Null when the id could not be read. */ + readBootId: (distro: string) => Promise + /** Confirmed running lists that no longer name a distro; returns an unsubscribe. */ + onDistrosStopped?: (listener: (stopped: string[]) => void) => () => void + /** A bridge exit may be its distro stopping: later background reads must start after it settles. */ + noteMayHaveStopped?: (distro: string) => void +} + +export const PRODUCTION_WSL_BRIDGE_BOOT_IDENTITY_DEPS: WslBridgeBootIdentityDeps = { + isRunning: isWslDistroRunningForBackgroundWork, + readBootId: readWslDistroBootId, + onDistrosStopped: onRunningWslDistrosStopped, + noteMayHaveStopped: noteWslDistroMayHaveStopped +} + +function distroKey(distro: string): string { + return distro.trim().toLowerCase() +} + +export class WslBridgeBootIdentity { + // One read per distro boot, reused by later spawns; any bridge exit of the distro drops it. + private readonly byDistro = new Map>() + // A burst of exits (a terminate exits every pane) shares one read of the current id. + private readonly currentReads = new Map>() + private readonly bySession = new Map< + string, + { distro: string; incarnationId: string | undefined; bootId: Promise } + >() + + // Held only while a bridge pane lives, so an idle adapter keeps no listener. + private unsubscribeStops: (() => void) | null = null + + constructor( + private readonly deps: WslBridgeBootIdentityDeps = PRODUCTION_WSL_BRIDGE_BOOT_IDENTITY_DEPS + ) {} + + /** A spawn or reattach of `sessionId`; a new incarnation takes the distro's current boot id. */ + noteSpawn(sessionId: string, distro: string, incarnationId?: string): void { + const key = distroKey(distro) + const current = this.bySession.get(sessionId) + if ( + current?.distro === key && + incarnationId !== undefined && + current.incarnationId === incarnationId + ) { + return + } + // A stop seen before the exit reaches us: a pane spawned meanwhile must not take the old id. + this.unsubscribeStops ??= + this.deps.onDistrosStopped?.((stopped) => stopped.forEach((name) => this.dropBootId(name))) ?? + null + this.bySession.set(sessionId, { distro: key, incarnationId, bootId: this.distroBootId(distro) }) + } + + /** + * Synchronous, as the exit arrives: it may be the first of a reboot's, so a spawn during its + * verdict must not inherit the old boot's id. It may also be the distro stopping (E9): until that + * settles, a stopping distro WSL still lists must not pass the gate into a boot-id exec. + */ + noteExit(distro: string): void { + this.deps.noteMayHaveStopped?.(distro) + this.dropBootId(distro) + } + + private dropBootId(distro: string): void { + this.byDistro.delete(distroKey(distro)) + } + + /** + * An exit of an incarnation the session already replaced: the respawn that beat it took the + * cached id, which may be the old boot's, so the current incarnation reads it again. + */ + noteStaleExit(sessionId: string, distro: string): void { + this.noteExit(distro) + const current = this.bySession.get(sessionId) + if (current?.distro === distroKey(distro)) { + current.bootId = this.distroBootId(distro) + } + } + + /** After a bridge exit the running list answered 'running': has the distro booted again since? */ + async rebootedSinceSpawn(sessionId: string, distro: string): Promise { + const spawned = this.bySession.get(sessionId) + if (!spawned) { + return false + } + const [before, now] = await Promise.all([spawned.bootId, this.readCurrent(distro)]) + // An unreadable id on either side proves nothing: the exit stays an exit. + return before !== null && now !== null && before !== now + } + + forget(sessionId: string): void { + const spawned = this.bySession.get(sessionId) + this.bySession.delete(sessionId) + if (spawned && ![...this.bySession.values()].some(({ distro }) => distro === spawned.distro)) { + this.byDistro.delete(spawned.distro) + } + if (this.bySession.size === 0) { + this.unsubscribeStops?.() + this.unsubscribeStops = null + } + } + + private distroBootId(distro: string): Promise { + const key = distroKey(distro) + let bootId = this.byDistro.get(key) + if (!bootId) { + bootId = this.read(distro) + this.byDistro.set(key, bootId) + } + return bootId + } + + private readCurrent(distro: string): Promise { + const key = distroKey(distro) + let reading = this.currentReads.get(key) + if (!reading) { + reading = this.read(distro).finally(() => this.currentReads.delete(key)) + this.currentReads.set(key, reading) + } + return reading + } + + private async read(distro: string): Promise { + try { + return (await this.deps.isRunning(distro)) ? await this.deps.readBootId(distro) : null + } catch { + return null + } + } +} diff --git a/src/main/daemon/daemon-wsl-bridge-exit-no-boot.test.ts b/src/main/daemon/daemon-wsl-bridge-exit-no-boot.test.ts new file mode 100644 index 00000000000..244677a0b5c --- /dev/null +++ b/src/main/daemon/daemon-wsl-bridge-exit-no-boot.test.ts @@ -0,0 +1,151 @@ +// E9 regression: a WSL bridge pane's exit after `wsl --terminate` must not lead Orca to run a command +// in the distro (any `wsl.exe -d --exec` boots it again) while WSL still lists it as stopping. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const wslMocks = vi.hoisted(() => ({ + listRunningWslDistrosAsync: + vi.fn<(options?: { requireConfirmed?: boolean; startedAfter?: number }) => Promise>(), + listWslDistrosAsync: vi.fn<() => Promise>() +})) +vi.mock('../wsl', () => wslMocks) + +import { + _resetWslBackgroundDistroGateForTests, + deferUntilWslDistroRunning, + noteWslDistroMayHaveStopped, + readConfirmedRunningWslDistros, + wasWslDistroLastSeenRunningSettled +} from '../wsl-background-distro-gate' +import { + _resetRunningWslDistroCacheForTests, + resolveRunningWslDistros +} from '../wsl-running-distro-cache' +import { + PRODUCTION_WSL_BRIDGE_BOOT_IDENTITY_DEPS, + WslBridgeBootIdentity +} from './daemon-wsl-bridge-boot-identity' +import { classifyWslBridgeExit } from './daemon-wsl-bridge-exit' + +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') +// WSL keeps listing a terminated distro for a moment while it stops. +const STILL_LISTED_MS = 300 +let terminatedAt = Number.POSITIVE_INFINITY + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + terminatedAt = Number.POSITIVE_INFINITY + wslMocks.listWslDistrosAsync.mockResolvedValue(['Ubuntu']) + wslMocks.listRunningWslDistrosAsync.mockImplementation((options) => + resolveRunningWslDistros(async () => { + const startedAt = performance.now() + return startedAt < terminatedAt + STILL_LISTED_MS ? ['Ubuntu'] : [] + }, options) + ) +}) + +afterEach(() => { + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + _resetWslBackgroundDistroGateForTests() + _resetRunningWslDistroCacheForTests() + vi.useRealTimers() + vi.resetAllMocks() +}) + +describe('a WSL bridge pane exit after the distro is terminated', () => { + it('never execs into the distro while it is still being listed as it stops', async () => { + const readBootId = vi.fn(async () => 'boot-1') + // Production gate and stop bookkeeping; only the wsl.exe boot-id read is faked. + const boot = new WslBridgeBootIdentity({ + ...PRODUCTION_WSL_BRIDGE_BOOT_IDENTITY_DEPS, + readBootId + }) + boot.noteSpawn('pane-a', 'Ubuntu') + boot.noteSpawn('pane-b', 'Ubuntu') + await vi.waitFor(() => expect(readBootId).toHaveBeenCalledOnce()) + + await vi.advanceTimersByTimeAsync(60_000) + terminatedAt = performance.now() + // Both panes' wsl.exe exit together, as on the awin verify. + boot.noteExit('Ubuntu') + boot.noteExit('Ubuntu') + const exitAt = performance.now() + const verdicts = Promise.all( + ['pane-a', 'pane-b'].map((pane) => + classifyWslBridgeExit('Ubuntu', exitAt, undefined, () => + boot.rebootedSinceSpawn(pane, 'Ubuntu') + ) + ) + ) + await vi.advanceTimersByTimeAsync(15_000) + + const settled = await verdicts + // Only the read at spawn, while the distro ran; none after the terminate. + expect(readBootId).toHaveBeenCalledOnce() + expect(settled).toEqual(['lost', 'lost']) + }) + + // The pre-boot-id path (build f59bd43): a dying file watcher or hook relay defers its restart + // until the distro runs, and any confirmed list used to drain it, one probed mid-stop included. + it('runs no deferred work off a list probed while the distro was still stopping', async () => { + await vi.advanceTimersByTimeAsync(60_000) + terminatedAt = performance.now() + noteWslDistroMayHaveStopped('Ubuntu') + const restarts = vi.fn() + deferUntilWslDistroRunning('Ubuntu', 'fs-watch:root-a', restarts) + deferUntilWslDistroRunning('Ubuntu', 'fs-watch:root-b', restarts) + + // Some other read, e.g. a bridge exit's verdict, probes while WSL still lists the distro. + await expect(readConfirmedRunningWslDistros()).resolves.toEqual({ + status: 'confirmed', + distros: ['Ubuntu'] + }) + await vi.advanceTimersByTimeAsync(15_000) + await readConfirmedRunningWslDistros() + + expect(restarts).not.toHaveBeenCalled() + }) + + it('still runs deferred work once a settled list shows the distro running again', async () => { + await vi.advanceTimersByTimeAsync(60_000) + noteWslDistroMayHaveStopped('Ubuntu') + const restarts = vi.fn() + deferUntilWslDistroRunning('Ubuntu', 'fs-watch:root-a', restarts) + await vi.advanceTimersByTimeAsync(1_000) + + await readConfirmedRunningWslDistros() + + expect(restarts).toHaveBeenCalledOnce() + }) + + // Review of #35143: Sleep and quit reads skip the probe for a pane they hold live. + it('does not let a list taken before the stop vouch for a live pane', async () => { + await vi.advanceTimersByTimeAsync(60_000) + await readConfirmedRunningWslDistros() + expect(wasWslDistroLastSeenRunningSettled('Ubuntu')).toBe(true) + + terminatedAt = performance.now() + noteWslDistroMayHaveStopped('Ubuntu') + expect(wasWslDistroLastSeenRunningSettled('Ubuntu')).toBe(false) + + // A probe while it still stops names it, yet is inside the settle window. + await readConfirmedRunningWslDistros() + expect(wasWslDistroLastSeenRunningSettled('Ubuntu')).toBe(false) + }) + + it('lists once more past the settle when a mid-stop list skipped deferred work', async () => { + await vi.advanceTimersByTimeAsync(60_000) + noteWslDistroMayHaveStopped('Ubuntu') + const restarts = vi.fn() + deferUntilWslDistroRunning('Ubuntu', 'fs-watch:root-a', restarts) + // A false stop signal: the distro never went away, so a settled list names it. + await readConfirmedRunningWslDistros() + expect(restarts).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1_000) + + expect(restarts).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/daemon/daemon-wsl-bridge-exit.test.ts b/src/main/daemon/daemon-wsl-bridge-exit.test.ts index f945ce30b40..d0964d2fd76 100644 --- a/src/main/daemon/daemon-wsl-bridge-exit.test.ts +++ b/src/main/daemon/daemon-wsl-bridge-exit.test.ts @@ -4,7 +4,7 @@ import { _resetRunningWslDistroCacheForTests, resolveRunningWslDistros } from '../wsl-running-distro-cache' -import { checkWslBridgeDistro } from './daemon-wsl-bridge-exit' +import { checkWslBridgeDistro, classifyWslBridgeExit } from './daemon-wsl-bridge-exit' afterEach(() => { _resetRunningWslDistroCacheForTests() @@ -29,6 +29,8 @@ describe('checkWslBridgeDistro', () => { ) const exitAt = performance.now() const checks = [1, 2, 3].map(() => checkWslBridgeDistro('Ubuntu', exitAt, readRunning(probe))) + // The checks first wait out the stop's settle anchor, so the probe starts a tick later. + await vi.waitFor(() => expect(probe).toHaveBeenCalled()) answer(['Debian']) await expect(Promise.all(checks)).resolves.toEqual(['lost', 'lost', 'lost']) @@ -42,9 +44,35 @@ describe('checkWslBridgeDistro', () => { }) it('treats a hung check as unanswered, so the exit stays an exit', async () => { - await expect(checkWslBridgeDistro('Ubuntu', 0, () => new Promise(() => {}), 10)).resolves.toBe( - 'unavailable' - ) + await expect( + checkWslBridgeDistro('Ubuntu', 0, () => new Promise(() => {}), { firstMs: 10, totalMs: 30 }) + ).resolves.toBe('unavailable') + }) + + // 5e hardening (b): a slow or failing first read is asked once more before the exit stays an exit. + it('retries an unanswered read once, past the failure backoff, within the total budget', async () => { + const reads: { bypassFailureBackoff?: boolean }[] = [] + const answers: WslRunningDistrosRead[] = [ + { status: 'unavailable' }, + { status: 'confirmed', distros: [] } + ] + await expect( + checkWslBridgeDistro('Ubuntu', 0, async (options) => { + reads.push({ bypassFailureBackoff: options.bypassFailureBackoff }) + return answers.shift() ?? { status: 'unavailable' } + }) + ).resolves.toBe('lost') + expect(reads).toEqual([{ bypassFailureBackoff: undefined }, { bypassFailureBackoff: true }]) + }) + + it('gives the retry only what is left of the total budget after a hung first read', async () => { + const reads = vi.fn(() => new Promise(() => {})) + const startedAt = performance.now() + await expect( + checkWslBridgeDistro('Ubuntu', 0, reads, { firstMs: 20, totalMs: 60 }) + ).resolves.toBe('unavailable') + expect(reads).toHaveBeenCalledTimes(2) + expect(performance.now() - startedAt).toBeLessThan(500) }) it('treats a failed check as unanswered', async () => { @@ -77,3 +105,35 @@ describe('checkWslBridgeDistro', () => { await expect(Promise.all(checks)).resolves.toEqual(['running', 'running']) }) }) + +describe('classifyWslBridgeExit', () => { + const running = async (): Promise => ({ + status: 'confirmed', + distros: ['Ubuntu'] + }) + + it('calls a running distro that booted again since the spawn rebooted, not an exit', async () => { + await expect(classifyWslBridgeExit('Ubuntu', 0, running, async () => true)).resolves.toBe( + 'rebooted' + ) + await expect(classifyWslBridgeExit('Ubuntu', 0, running, async () => false)).resolves.toBe( + 'running' + ) + }) + + it('asks about the boot id only when the running list says running', async () => { + const rebooted = vi.fn(async () => true) + await expect( + classifyWslBridgeExit( + 'Ubuntu', + 0, + async () => ({ status: 'confirmed', distros: [] }), + rebooted + ) + ).resolves.toBe('lost') + await expect( + classifyWslBridgeExit('Ubuntu', 0, async () => ({ status: 'unavailable' }), rebooted) + ).resolves.toBe('unavailable') + expect(rebooted).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/daemon/daemon-wsl-bridge-exit.ts b/src/main/daemon/daemon-wsl-bridge-exit.ts index b769b2506b1..8627347baa3 100644 --- a/src/main/daemon/daemon-wsl-bridge-exit.ts +++ b/src/main/daemon/daemon-wsl-bridge-exit.ts @@ -2,10 +2,12 @@ * A WSL bridge pane's process exit, when its whole distro is gone (`wsl --terminate`, a shutdown * or a crash), is host loss, not the shell exiting: like a daemon crash, the pane keeps its tab * and history and cold-restores later. `wsl.exe` reports such an exit as an ordinary code (1), - * so only the running list tells it from a shell's own `exit`. + * so only the running list, and the distro's boot id when something booted it again first, tells + * it from a shell's own `exit`. */ import { readConfirmedRunningWslDistros, + settledWslRunningReadAnchor, type WslRunningDistrosRead } from '../wsl-background-distro-gate' @@ -13,10 +15,13 @@ import { export const WSL_DISTRO_LOSS_EXIT_CODE = -1 // Every bridge exit, a user's own `exit` too, waits on this before its tab reacts: keep it short. -const WSL_EXIT_CHECK_TIMEOUT_MS = 3_000 +const WSL_EXIT_CHECK_FIRST_MS = 3_000 +// One retry past the failure backoff when the first read can't answer; a wedged wsl.exe costs this. +const WSL_EXIT_CHECK_TOTAL_MS = 10_000 export type ReadRunningWslDistros = (options: { startedAfter?: number + bypassFailureBackoff?: boolean }) => Promise /** What the running list said about the distro after a bridge exit. */ @@ -26,33 +31,66 @@ export type WslBridgeExitVerdict = 'lost' | 'running' | 'unavailable' * Lost only when a running list confirmed after the exit lacks the distro. The probe is the shared, * coalesced `wsl --list --running` (it never boots): a terminate that exits many panes costs one * spawn, and a probe already in flight from before the exit (which may predate the distro's boot) - * gets one fresh probe after it. Unavailable or late means unchanged: the exit stays an exit. + * gets one fresh probe after it. A read that can't answer is retried once; still unavailable or + * late means unchanged: the exit stays an exit. */ export async function checkWslBridgeDistro( distro: string, exitAt: number, readRunning: ReadRunningWslDistros = readConfirmedRunningWslDistros, - timeoutMs = WSL_EXIT_CHECK_TIMEOUT_MS + { firstMs = WSL_EXIT_CHECK_FIRST_MS, totalMs = WSL_EXIT_CHECK_TOTAL_MS } = {} ): Promise { + // WSL keeps listing a stopping distro for a moment; a read inside that window would say 'running'. + const startedAfter = await settledWslRunningReadAnchor(distro, exitAt) + const startedAt = performance.now() + let running = await readWithin(() => readRunning({ startedAfter }), firstMs) + if (running.status !== 'confirmed') { + const remainingMs = totalMs - (performance.now() - startedAt) + running = + remainingMs > 0 + ? await readWithin( + () => readRunning({ startedAfter, bypassFailureBackoff: true }), + remainingMs + ) + : running + } + if (running.status !== 'confirmed') { + return 'unavailable' + } + const key = distro.trim().toLowerCase() + return running.distros.some((candidate) => candidate.trim().toLowerCase() === key) + ? 'running' + : 'lost' +} + +async function readWithin( + read: () => Promise, + timeoutMs: number +): Promise { let timer: ReturnType | undefined const timedOut = new Promise((resolve) => { timer = setTimeout(() => resolve({ status: 'unavailable' }), timeoutMs) }) try { - const running = await Promise.race([ - readRunning({ startedAfter: exitAt }).catch((): WslRunningDistrosRead => ({ - status: 'unavailable' - })), + return await Promise.race([ + read().catch((): WslRunningDistrosRead => ({ status: 'unavailable' })), timedOut ]) - if (running.status !== 'confirmed') { - return 'unavailable' - } - const key = distro.trim().toLowerCase() - return running.distros.some((candidate) => candidate.trim().toLowerCase() === key) - ? 'running' - : 'lost' } finally { clearTimeout(timer) } } + +/** + * The verdict for a bridge exit. A distro that answers 'running' may have been booted again by + * something else before the list ran; a new boot id since the pane's spawn still makes it loss. + */ +export async function classifyWslBridgeExit( + distro: string, + exitAt: number, + readRunning: ReadRunningWslDistros | undefined, + rebootedSinceSpawn: () => Promise +): Promise { + const verdict = await checkWslBridgeDistro(distro, exitAt, readRunning) + return verdict === 'running' && (await rebootedSinceSpawn()) ? 'rebooted' : verdict +} diff --git a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts index c4e076d769c..5734ca01635 100644 --- a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts +++ b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts @@ -10,7 +10,8 @@ vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({ readWslGuestPaneProcesses: readRows })) -const { readDaemonWslSleepCwd } = await import('./daemon-wsl-sleep-cwd') +const { readDaemonWslQuitCwds, readDaemonWslSleepCwd, readDaemonWslSleepCwdWithFacts } = + await import('./daemon-wsl-sleep-cwd') const pane = { paneKey: 'tab-1:leaf-1', wslDistro: 'Ubuntu', live: true } const shell: WslGuestProcessRow = { @@ -58,6 +59,38 @@ describe('readDaemonWslSleepCwd', () => { expect(await read).toBeNull() }) + it("answers quit's panes within its own budget, leaving out panes it cannot read", async () => { + readRows.mockResolvedValue([shell]) + const cwds = await readDaemonWslQuitCwds( + [ + { sessionId: 's1', paneKey: pane.paneKey, wslDistro: 'Ubuntu' }, + { sessionId: 's2', paneKey: 'tab-2:leaf-2', wslDistro: 'Ubuntu' } + ], + 1_000 + ) + expect(cwds).toEqual(new Map([['s1', '\\\\wsl.localhost\\Ubuntu\\home\\a\\deep']])) + expect(readRows).toHaveBeenCalledWith('Ubuntu', 1_000, { running: true }) + }) + + it('reports how many rows and pane shells the read saw', async () => { + readRows.mockResolvedValue([shell, { ...shell, pid: 11, cwd: '/home/a' }]) + expect(await readDaemonWslSleepCwdWithFacts(pane)).toEqual({ + cwd: null, + budgetMs: 3_000, + rows: 2, + shells: 2, + timedOut: false + }) + }) + + it('reports a read that ran out of budget', async () => { + vi.useFakeTimers() + readRows.mockReturnValue(new Promise(() => {})) + const read = readDaemonWslSleepCwdWithFacts(pane) + await vi.advanceTimersByTimeAsync(3_000) + expect(await read).toMatchObject({ cwd: null, rows: null, shells: null, timedOut: true }) + }) + it('reads nothing off Windows', async () => { Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) expect(await readDaemonWslSleepCwd(pane)).toBeNull() diff --git a/src/main/daemon/daemon-wsl-sleep-cwd.ts b/src/main/daemon/daemon-wsl-sleep-cwd.ts index 5b711bbc85b..988bf3775ae 100644 --- a/src/main/daemon/daemon-wsl-sleep-cwd.ts +++ b/src/main/daemon/daemon-wsl-sleep-cwd.ts @@ -1,37 +1,100 @@ /** Bridge WSL bash lacks OSC 7; read its shell folder before Sleep so wake avoids the spawn folder. Failures retain the old fallback. */ import { toWindowsWslUncPath } from '../../shared/wsl-paths' -import { - readWslGuestPaneProcesses, - readWslGuestPaneShellCwd -} from '../wsl/wsl-guest-pane-processes' +import { paneShells, readWslGuestPaneProcesses } from '../wsl/wsl-guest-pane-processes' import { teardownReadBudgetMs } from './daemon-request-deadline' // Reserve teardown time for the final checkpoint and kill when a distro does not answer. const READ_BUDGET_MS = 3_000 +/** What a Sleep's folder read saw, for the one diagnostic line Sleep logs. */ +export type DaemonWslSleepCwdRead = { + cwd: string | null + budgetMs: number + /** Process rows the distro returned; null when it was not read, refused, failed or timed out. */ + rows: number | null + /** Shells tagged with the pane's key; a folder is taken only when exactly one owns it. */ + shells: number | null + timedOut: boolean +} + /** The shell's folder in the bridge's UNC spelling, which wake reads; else null. */ export async function readDaemonWslSleepCwd( pane: { paneKey: string; wslDistro: string; live: boolean }, - deadlineMs?: number + deadlineMs?: number, + capMs = READ_BUDGET_MS ): Promise { - const budget = teardownReadBudgetMs(READ_BUDGET_MS, deadlineMs) - if (process.platform !== 'win32' || budget <= 0) { - return null + return (await readDaemonWslSleepCwdWithFacts(pane, deadlineMs, capMs)).cwd +} + +export async function readDaemonWslSleepCwdWithFacts( + pane: { paneKey: string; wslDistro: string; live: boolean }, + deadlineMs?: number, + capMs = READ_BUDGET_MS +): Promise { + const budgetMs = teardownReadBudgetMs(capMs, deadlineMs) + const none = { cwd: null, budgetMs, rows: null, shells: null, timedOut: false } + if (process.platform !== 'win32' || budgetMs <= 0) { + return none } let timer: ReturnType | undefined + let timedOut = false try { const rows = await Promise.race([ - readWslGuestPaneProcesses(pane.wslDistro, budget, { running: pane.live }), + readWslGuestPaneProcesses(pane.wslDistro, budgetMs, { running: pane.live }), new Promise((resolve) => { - timer = setTimeout(() => resolve(null), budget) + timer = setTimeout(() => { + timedOut = true + resolve(null) + }, budgetMs) timer.unref?.() }) ]) - const cwd = rows ? readWslGuestPaneShellCwd(rows, pane.paneKey) : null - return cwd && /^\/(?!\/)/.test(cwd) ? toWindowsWslUncPath(cwd, pane.wslDistro) : null + if (!rows) { + return { ...none, timedOut } + } + const shells = paneShells(rows, pane.paneKey) + const cwd = shells.length === 1 ? (shells[0].cwd ?? null) : null + return { + cwd: cwd && /^\/(?!\/)/.test(cwd) ? toWindowsWslUncPath(cwd, pane.wslDistro) : null, + budgetMs, + rows: rows.length, + shells: shells.length, + timedOut: false + } } catch { - return null + return none } finally { clearTimeout(timer) } } + +/** Quit's once-only read of live bridge panes' folders, in parallel within one budget; a distro read is shared. */ +export async function readDaemonWslQuitCwds( + panes: readonly { sessionId: string; paneKey: string; wslDistro: string }[], + budgetMs: number +): Promise> { + const cwds = new Map() + await Promise.all( + panes.map(async (pane) => { + // `live` only skips a fresh running check when the running-distro cache already confirms it. + const cwd = await readDaemonWslSleepCwd({ ...pane, live: true }, undefined, budgetMs) + if (cwd) { + cwds.set(pane.sessionId, cwd) + } + }) + ) + return cwds +} + +/** One info line per Sleep: which read ran, what it knew about the pane and what came back. */ +export function describeSleepFolderRead( + sessionId: string, + read: DaemonWslSleepCwdRead | { cwd: string | null }, + pane: { wslDistro?: string; paneKey?: string; live: boolean; elapsedMs: number } +): string { + const probe = + 'rows' in read + ? `wsl probe (budget ${read.budgetMs}ms, rows ${read.rows ?? 'none'}${read.timedOut ? ' timed out' : ''}, shells ${read.shells ?? 'none'})` + : 'live probe' + return `[history] Sleep folder for ${sessionId}: ${probe}, distro ${pane.wslDistro ?? 'unknown'}, pane ${pane.paneKey ?? 'unknown'}, live ${pane.live}, folder ${read.cwd ? 'found' : 'not found'} in ${pane.elapsedMs}ms` +} diff --git a/src/main/daemon/pty-session-id.test.ts b/src/main/daemon/pty-session-id.test.ts index 5aec7056ed8..4da47e9f455 100644 --- a/src/main/daemon/pty-session-id.test.ts +++ b/src/main/daemon/pty-session-id.test.ts @@ -9,16 +9,6 @@ import { parsePtySessionId } from '../../shared/pty-session-id-format' const USER_DATA = '/tmp/orca-userdata' describe('mintPtySessionId', () => { - it('returns a UUID when no worktreeId is provided', () => { - const id = mintPtySessionId() - expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) - }) - - it('prefixes the worktreeId and suffixes an 8-char hex tag', () => { - const id = mintPtySessionId('wt-alpha') - expect(id).toMatch(/^wt-alpha@@[0-9a-f]{8}$/) - }) - it('preserves path-shaped worktreeIds verbatim in the prefix', () => { // Workspace IDs embed absolute paths; preserve them for @@ ownership parsing. const id = mintPtySessionId('repo-123::/Users/me/work/wt-1') @@ -27,15 +17,6 @@ describe('mintPtySessionId', () => { }) describe('ptySessionIdForAgentCreateOperation', () => { - it('derives the same daemon session for retries of one host operation', () => { - const operationId = 'a'.repeat(43) - - expect(ptySessionIdForAgentCreateOperation('repo::/tmp/worktree', operationId)).toBe( - 'repo::/tmp/worktree@@aaaaaaaa' - ) - expect(ptySessionIdForAgentCreateOperation(undefined, operationId)).toBe('aaaaaaaa') - }) - it('produces a safe session id for a path-shaped worktree', () => { const id = ptySessionIdForAgentCreateOperation('repo::/Users/dev/worktree', 'b'.repeat(43)) @@ -53,23 +34,6 @@ describe('ptySessionIdForAgentCreateOperation', () => { }) describe('isSafePtySessionId', () => { - it('accepts minted UUIDs', () => { - expect(isSafePtySessionId(mintPtySessionId(), USER_DATA)).toBe(true) - }) - - it('accepts minted worktree-scoped ids (happy path, hyphen-only)', () => { - expect(isSafePtySessionId(mintPtySessionId('wt-alpha'), USER_DATA)).toBe(true) - }) - - it('accepts minted ids with path-shaped worktreeIds containing slashes', () => { - const id = mintPtySessionId('repo-abc123::/Users/thebr/work/wt-1') - expect(isSafePtySessionId(id, USER_DATA)).toBe(true) - }) - - it('accepts caller-supplied path-shaped ids that stay inside userData', () => { - expect(isSafePtySessionId('some-repo::/Users/me/wt/abc@@deadbeef', USER_DATA)).toBe(true) - }) - it('rejects empty string', () => { expect(isSafePtySessionId('', USER_DATA)).toBe(false) }) @@ -82,10 +46,6 @@ describe('isSafePtySessionId', () => { expect(isSafePtySessionId('safe\0evil', USER_DATA)).toBe(false) }) - it('rejects ids that traverse out of userData via ..', () => { - expect(isSafePtySessionId('../etc/passwd', USER_DATA)).toBe(false) - }) - it('rejects ids that traverse out of userData via deep ..', () => { expect(isSafePtySessionId('sub/../../etc/passwd', USER_DATA)).toBe(false) }) @@ -95,10 +55,6 @@ describe('isSafePtySessionId', () => { expect(isSafePtySessionId('.', USER_DATA)).toBe(false) }) - it('accepts ids with nested valid path segments inside userData', () => { - expect(isSafePtySessionId('sub/path/ok@@12345678', USER_DATA)).toBe(true) - }) - it('accepts ids with path segments that merely start with dot-dot', () => { expect(isSafePtySessionId('..sessions/ok@@12345678', USER_DATA)).toBe(true) }) @@ -128,20 +84,11 @@ describe('parsePtySessionId', () => { expect(parsePtySessionId('wt-only@@abcd1234')).toEqual({ worktreeId: null }) }) - it('returns null for an empty string', () => { - expect(parsePtySessionId('')).toEqual({ worktreeId: null }) - }) - it('handles worktreeIds whose path contains @ characters', () => { const wt = 'repo::/Users/me/email@host/wt' expect(parsePtySessionId(`${wt}@@deadbeef`)).toEqual({ worktreeId: wt }) }) - it('rejects degenerate `::@@…` ids with empty repo and path halves', () => { - // An empty repo::path pair must not become a memory-attribution bucket. - expect(parsePtySessionId('::@@deadbeef')).toEqual({ worktreeId: null }) - }) - it('rejects ids with an empty path half (`repo::@@…`)', () => { expect(parsePtySessionId('repo::@@deadbeef')).toEqual({ worktreeId: null }) }) diff --git a/src/main/daemon/pty-subprocess-env-inheritance.test.ts b/src/main/daemon/pty-subprocess-env-inheritance.test.ts index 8c6c096f628..4d80d1ca595 100644 --- a/src/main/daemon/pty-subprocess-env-inheritance.test.ts +++ b/src/main/daemon/pty-subprocess-env-inheritance.test.ts @@ -128,9 +128,11 @@ describe('createPtySubprocess', () => { ORCA_TAB_ID: process.env.ORCA_TAB_ID, ORCA_WORKTREE_ID: process.env.ORCA_WORKTREE_ID, ORCA_WSL_CLI_DIR: process.env.ORCA_WSL_CLI_DIR, - ORCA_ORCAD_MANAGED_ACTIVATION_ROOT: process.env.ORCA_ORCAD_MANAGED_ACTIVATION_ROOT + ORCA_ORCAD_MANAGED_ACTIVATION_ROOT: process.env.ORCA_ORCAD_MANAGED_ACTIVATION_ROOT, + ORCA_REMOTE_VIEWER_CLIPBOARD: process.env.ORCA_REMOTE_VIEWER_CLIPBOARD } process.env.ORCA_ORCAD_MANAGED_ACTIVATION_ROOT = '/home/u/.orca-remote/.activation' + process.env.ORCA_REMOTE_VIEWER_CLIPBOARD = '1' process.env.ORCA_PANE_KEY = 'parent-tab:parent-leaf' process.env.ORCA_TAB_ID = 'parent-tab' process.env.ORCA_WORKTREE_ID = 'parent-worktree' @@ -154,6 +156,7 @@ describe('createPtySubprocess', () => { expect(env.ORCA_WORKTREE_ID).toBeUndefined() expect(env.ORCA_WSL_CLI_DIR).toBeUndefined() expect(env.ORCA_ORCAD_MANAGED_ACTIVATION_ROOT).toBeUndefined() + expect(env.ORCA_REMOTE_VIEWER_CLIPBOARD).toBeUndefined() }) it('preserves explicit child Orca pane identity over parent env', async () => { diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index 6c3675b73ad..8b6051b71e1 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -29,6 +29,7 @@ import { applyScrubSafeAgentEnvAliases } from '../../../shared/agent-hook-scrub- import type { TuiAgent } from '../../../shared/tui-agent' import type { PtySubprocessOptions } from '../pty-subprocess' import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' +import { REMOTE_VIEWER_CLIPBOARD_ENV } from '../../../shared/remote-viewer-clipboard-env' const PANE_IDENTITY_ENV_KEYS = [ 'ORCA_PANE_KEY', @@ -38,6 +39,8 @@ const PANE_IDENTITY_ENV_KEYS = [ // Not identity but equally per-spawn: an inherited copy names another launch's CLI. 'ORCA_WSL_CLI_DIR', 'JCODE_RUNTIME_DIR', + // Per-viewer: an Orca started from a remote viewer's pane must not mark its own local panes. + REMOTE_VIEWER_CLIPBOARD_ENV, // A server's own launch marker; a user's `orcad` in this shell is not client-managed. ORCAD_MANAGED_ACTIVATION_ROOT_ENV ] as const diff --git a/src/main/daemon/startup-device-attributes-responder.ts b/src/main/daemon/startup-device-attributes-responder.ts index 7174c240fbe..020b8ae7ecd 100644 --- a/src/main/daemon/startup-device-attributes-responder.ts +++ b/src/main/daemon/startup-device-attributes-responder.ts @@ -1,10 +1,9 @@ /** Answer DA1 when ConPTY startup or shell-ready gating prevents a renderer reply; bypass queued stdin. */ import type { Terminal } from '@xterm/headless' +import { PRIMARY_DEVICE_ATTRIBUTES_QUERY_SEQUENCES } from '../../shared/terminal-reply-query-extraction' type DeviceAttributesParser = Pick -const PRIMARY_DEVICE_ATTRIBUTES_QUERIES = ['\x1b[c', '\x1b[0c'] as const - /** Match renderer attributes so startup gating does not change TUI capabilities. */ export const STARTUP_DA1_RESPONSE = '\x1b[?1;2c' @@ -25,7 +24,7 @@ export class StartupDeviceAttributesQueryFilter { break } output += input.slice(offset, candidate) - const query = PRIMARY_DEVICE_ATTRIBUTES_QUERIES.find((value) => + const query = PRIMARY_DEVICE_ATTRIBUTES_QUERY_SEQUENCES.find((value) => input.startsWith(value, candidate) ) if (query) { @@ -33,7 +32,7 @@ export class StartupDeviceAttributesQueryFilter { continue } const tail = input.slice(candidate) - if (PRIMARY_DEVICE_ATTRIBUTES_QUERIES.some((value) => value.startsWith(tail))) { + if (PRIMARY_DEVICE_ATTRIBUTES_QUERY_SEQUENCES.some((value) => value.startsWith(tail))) { this.pending = tail break } diff --git a/src/main/emulator/android/adb-devices.test.ts b/src/main/emulator/android/adb-devices.test.ts index 101ac7a3645..0b3df3d5b5b 100644 --- a/src/main/emulator/android/adb-devices.test.ts +++ b/src/main/emulator/android/adb-devices.test.ts @@ -1,14 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - adbDevicesArgs, - adbShellArgs, - bootCompletedArgs, - isBootCompleted, - parseAdbDevices, - parseWmSize, - wmSizeArgs, - type AndroidAdbDevice -} from './adb-devices' +import { parseAdbDevices, parseWmSize, type AndroidAdbDevice } from './adb-devices' describe('parseAdbDevices', () => { it('parses a mixed list of emulator and physical devices', () => { @@ -41,14 +32,6 @@ describe('parseAdbDevices', () => { ]) }) - it('returns an empty array for header-only output', () => { - expect(parseAdbDevices('List of devices attached\n')).toEqual([]) - }) - - it('returns an empty array for empty output', () => { - expect(parseAdbDevices('')).toEqual([]) - }) - it('parses the two-word "no permissions" state', () => { const device = parseAdbDevices( 'List of devices attached\n???????????? no permissions\n' @@ -59,76 +42,16 @@ describe('parseAdbDevices', () => { isEmulator: false }) }) - - it('omits model/product when the device line has no -l tokens', () => { - const [device] = parseAdbDevices('List of devices attached\nemulator-5556 device\n') - expect(device).toEqual({ serial: 'emulator-5556', state: 'device', isEmulator: true }) - expect(device.model).toBeUndefined() - expect(device.product).toBeUndefined() - }) }) describe('parseWmSize', () => { - it('parses a Physical size line', () => { - expect(parseWmSize('Physical size: 1080x2340\n')).toEqual({ width: 1080, height: 2340 }) - }) - it('prefers Override size over Physical size when both are present', () => { const stdout = 'Physical size: 1080x2340\nOverride size: 720x1560\n' expect(parseWmSize(stdout)).toEqual({ width: 720, height: 1560 }) }) - it('parses an Override size line on its own', () => { - expect(parseWmSize('Override size: 540x1170')).toEqual({ width: 540, height: 1170 }) - }) - it('returns null when no size line is present', () => { expect(parseWmSize('')).toBeNull() expect(parseWmSize('something unrelated\n')).toBeNull() }) }) - -describe('isBootCompleted', () => { - it('returns true for a trimmed "1"', () => { - expect(isBootCompleted('1\n')).toBe(true) - expect(isBootCompleted(' 1 ')).toBe(true) - }) - - it('returns false for "0"', () => { - expect(isBootCompleted('0')).toBe(false) - }) - - it('returns false for empty output', () => { - expect(isBootCompleted('')).toBe(false) - }) -}) - -describe('adb argument builders', () => { - it('exposes the device-list args', () => { - expect(adbDevicesArgs).toEqual(['devices', '-l']) - }) - - it('builds shell args with the serial and command', () => { - expect(adbShellArgs('emulator-5554', ['wm', 'size'])).toEqual([ - '-s', - 'emulator-5554', - 'shell', - 'wm', - 'size' - ]) - }) - - it('builds wm size args', () => { - expect(wmSizeArgs('emulator-5554')).toEqual(['-s', 'emulator-5554', 'shell', 'wm', 'size']) - }) - - it('builds boot-completed args', () => { - expect(bootCompletedArgs('emulator-5554')).toEqual([ - '-s', - 'emulator-5554', - 'shell', - 'getprop', - 'sys.boot_completed' - ]) - }) -}) diff --git a/src/main/emulator/android/android-capability-operations.test.ts b/src/main/emulator/android/android-capability-operations.test.ts index 88f65dd3f88..615524c0c69 100644 --- a/src/main/emulator/android/android-capability-operations.test.ts +++ b/src/main/emulator/android/android-capability-operations.test.ts @@ -1,13 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { AndroidCommandResult, AndroidCommandRunner } from './android-command-runner' import type { AndroidSdkPaths } from './android-sdk-discovery' -import { - captureAndroidLogcat, - dumpAndroidAccessibilityTree, - installAndroidApk, - launchAndroidApp, - setAndroidPermission -} from './android-capability-operations' +import { installAndroidApk } from './android-capability-operations' const SDK: AndroidSdkPaths = { sdkRoot: '/sdk', @@ -34,69 +28,4 @@ describe('installAndroidApk', () => { code: 'emulator_error' }) }) - - it('passes -r when reinstalling', async () => { - const runner = vi.fn(runnerReturning({ '-s s install -r /a.apk': ok('Success') })) - await installAndroidApk(runner as unknown as AndroidCommandRunner, SDK, 's', '/a.apk', { - reinstall: true - }) - expect(runner).toHaveBeenCalledWith(SDK.adb, ['-s', 's', 'install', '-r', '/a.apk']) - }) -}) - -describe('launchAndroidApp + setAndroidPermission', () => { - it('launches with an explicit activity', async () => { - const runner = vi.fn(runnerReturning({})) - await launchAndroidApp(runner as unknown as AndroidCommandRunner, SDK, 's', 'com.x', '.Main') - expect(runner).toHaveBeenCalledWith(SDK.adb, [ - '-s', - 's', - 'shell', - 'am', - 'start', - '-n', - 'com.x/.Main' - ]) - }) - - it('grants a runtime permission', async () => { - const runner = vi.fn(runnerReturning({})) - await setAndroidPermission( - runner as unknown as AndroidCommandRunner, - SDK, - 's', - 'grant', - 'com.x', - 'android.permission.CAMERA' - ) - expect(runner).toHaveBeenCalledWith(SDK.adb, [ - '-s', - 's', - 'shell', - 'pm', - 'grant', - 'com.x', - 'android.permission.CAMERA' - ]) - }) -}) - -describe('dumpAndroidAccessibilityTree', () => { - it('dumps then reads and parses the XML hierarchy', async () => { - const xml = '' - const runner = runnerReturning({ '-s s shell cat /sdcard/window_dump.xml': ok(xml) }) - const tree = await dumpAndroidAccessibilityTree(runner, SDK, 's') - expect(tree.children[0]).toMatchObject({ text: 'Hello' }) - }) -}) - -describe('captureAndroidLogcat', () => { - it('dumps and parses non-empty logcat lines', async () => { - const line = '06-26 12:00:00.123 1234 5678 D MyTag: hello' - const runner = runnerReturning({ '-s s logcat -d -v threadtime': ok(`${line}\n`) }) - const entries = await captureAndroidLogcat(runner, SDK, 's') - expect(entries).toEqual([ - { timestamp: '06-26 12:00:00.123', level: 'D', tag: 'MyTag', message: 'hello' } - ]) - }) }) diff --git a/src/main/emulator/android/android-logcat.test.ts b/src/main/emulator/android/android-logcat.test.ts index e06edb3f93e..cfd31ea52b5 100644 --- a/src/main/emulator/android/android-logcat.test.ts +++ b/src/main/emulator/android/android-logcat.test.ts @@ -1,82 +1,7 @@ import { describe, expect, it } from 'vitest' -import { logcatArgs, parseLogcatLine, type LogcatEntry } from './android-logcat' - -describe('logcatArgs', () => { - it('builds base streaming args with the threadtime format', () => { - expect(logcatArgs('emulator-5554')).toEqual([ - '-s', - 'emulator-5554', - 'logcat', - '-v', - 'threadtime' - ]) - }) - - it('adds -d before the format when dump is true', () => { - expect(logcatArgs('emulator-5554', { dump: true })).toEqual([ - '-s', - 'emulator-5554', - 'logcat', - '-d', - '-v', - 'threadtime' - ]) - }) - - it('adds -t with the stringified line count', () => { - expect(logcatArgs('emulator-5554', { lines: 100 })).toEqual([ - '-s', - 'emulator-5554', - 'logcat', - '-v', - 'threadtime', - '-t', - '100' - ]) - }) - - it('appends filterspec tokens at the end', () => { - expect(logcatArgs('emulator-5554', { filters: ['MyTag:D', '*:S'] })).toEqual([ - '-s', - 'emulator-5554', - 'logcat', - '-v', - 'threadtime', - 'MyTag:D', - '*:S' - ]) - }) - - it('combines dump, lines, and filters in order', () => { - expect( - logcatArgs('emulator-5554', { dump: true, lines: 50, filters: ['MyTag:D', '*:S'] }) - ).toEqual([ - '-s', - 'emulator-5554', - 'logcat', - '-d', - '-v', - 'threadtime', - '-t', - '50', - 'MyTag:D', - '*:S' - ]) - }) -}) +import { parseLogcatLine, type LogcatEntry } from './android-logcat' describe('parseLogcatLine', () => { - it('parses a well-formed threadtime-format line', () => { - expect( - parseLogcatLine('06-26 12:00:00.123 1234 5678 D MyTag: hello world') - ).toEqual({ - timestamp: '06-26 12:00:00.123', - level: 'D', - tag: 'MyTag', - message: 'hello world' - }) - }) - it('keeps colons that belong to the message', () => { expect( parseLogcatLine('06-26 12:00:00.123 1234 5678 E MyTag: value: 42') @@ -93,10 +18,4 @@ describe('parseLogcatLine', () => { message: '--------- beginning of main' }) }) - - it('trims surrounding whitespace in the fallback', () => { - expect(parseLogcatLine(' not a logcat line ')).toEqual({ - message: 'not a logcat line' - }) - }) }) diff --git a/src/main/emulator/android/avd-manager.test.ts b/src/main/emulator/android/avd-manager.test.ts index 77641e9d23f..045d1d41547 100644 --- a/src/main/emulator/android/avd-manager.test.ts +++ b/src/main/emulator/android/avd-manager.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { bootAvdArgs, emuKillArgs, listAvdsArgs, parseAvdList } from './avd-manager' +import { parseAvdList } from './avd-manager' describe('parseAvdList', () => { it('keeps AVD names while dropping blank and informational lines', () => { @@ -9,14 +9,6 @@ describe('parseAvdList', () => { expect(parseAvdList(stdout)).toEqual(['Pixel_7', 'Pixel_Tablet']) }) - it('returns an empty array for empty stdout', () => { - expect(parseAvdList('')).toEqual([]) - }) - - it('trims surrounding whitespace from kept names', () => { - expect(parseAvdList(' Pixel_7 \r\n\tPixel_Tablet\t')).toEqual(['Pixel_7', 'Pixel_Tablet']) - }) - it('drops WARNING, ERROR and "No AVD" lines', () => { const stdout = [ 'WARNING | no metrics', @@ -27,61 +19,3 @@ describe('parseAvdList', () => { expect(parseAvdList(stdout)).toEqual(['Pixel_7']) }) }) - -describe('listAvdsArgs', () => { - it('is the emulator -list-avds invocation', () => { - expect(listAvdsArgs).toEqual(['-list-avds']) - }) -}) - -describe('bootAvdArgs', () => { - it('boots an AVD by name with no extra flags', () => { - expect(bootAvdArgs('Pixel_7')).toEqual(['-avd', 'Pixel_7']) - }) - - it('appends the no-snapshot flag', () => { - expect(bootAvdArgs('Pixel_7', { noSnapshot: true })).toEqual([ - '-avd', - 'Pixel_7', - '-no-snapshot' - ]) - }) - - it('appends the no-window flag', () => { - expect(bootAvdArgs('Pixel_7', { noWindow: true })).toEqual(['-avd', 'Pixel_7', '-no-window']) - }) - - it('appends the no-boot-anim flag', () => { - expect(bootAvdArgs('Pixel_7', { noBootAnim: true })).toEqual([ - '-avd', - 'Pixel_7', - '-no-boot-anim' - ]) - }) - - it('emits the gpu flag as two tokens', () => { - expect(bootAvdArgs('Pixel_7', { gpu: 'swiftshader_indirect' })).toEqual([ - '-avd', - 'Pixel_7', - '-gpu', - 'swiftshader_indirect' - ]) - }) - - it('orders the name first, then flags in the documented order', () => { - expect( - bootAvdArgs('Pixel_7', { - noSnapshot: true, - noWindow: true, - noBootAnim: true, - gpu: 'host' - }) - ).toEqual(['-avd', 'Pixel_7', '-no-snapshot', '-no-window', '-no-boot-anim', '-gpu', 'host']) - }) -}) - -describe('emuKillArgs', () => { - it('targets a serial with the adb emu kill command', () => { - expect(emuKillArgs('emulator-5554')).toEqual(['-s', 'emulator-5554', 'emu', 'kill']) - }) -}) diff --git a/src/main/emulator/android/uiautomator-tree.test.ts b/src/main/emulator/android/uiautomator-tree.test.ts index 632c5cfcdda..9fe9e0080f5 100644 --- a/src/main/emulator/android/uiautomator-tree.test.ts +++ b/src/main/emulator/android/uiautomator-tree.test.ts @@ -11,22 +11,6 @@ const HIERARCHY_XML = ` ` describe('parseUiAutomatorXml', () => { - it('returns a synthetic root holding the top-level children of ', () => { - const root = parseUiAutomatorXml(HIERARCHY_XML) - expect(root.children).toHaveLength(1) - }) - - it('maps attributes and coerces booleans and bounds on a container node', () => { - const frame = parseUiAutomatorXml(HIERARCHY_XML).children[0] - expect(frame.className).toBe('android.widget.FrameLayout') - expect(frame.packageName).toBe('com.android.launcher3') - expect(frame.clickable).toBe(false) - expect(frame.enabled).toBe(true) - expect(frame.focused).toBe(false) - expect(frame.bounds).toEqual({ left: 0, top: 0, right: 1080, bottom: 2340 }) - expect(frame.children).toHaveLength(2) - }) - it('maps renamed attributes (class/resource-id/content-desc) on a leaf node', () => { const search = parseUiAutomatorXml(HIERARCHY_XML).children[0].children[0] expect(search.className).toBe('android.widget.EditText') @@ -39,11 +23,6 @@ describe('parseUiAutomatorXml', () => { expect(search.bounds).toEqual({ left: 42, top: 180, right: 1038, bottom: 320 }) }) - it('gives a childless node an empty children array', () => { - const search = parseUiAutomatorXml(HIERARCHY_XML).children[0].children[0] - expect(search.children).toEqual([]) - }) - it('preserves sibling order', () => { const frame = parseUiAutomatorXml(HIERARCHY_XML).children[0] expect(frame.children[0].text).toBe('Search apps') @@ -51,13 +30,6 @@ describe('parseUiAutomatorXml', () => { expect(frame.children[1].enabled).toBe(false) }) - it('omits string fields whose attribute is absent or empty', () => { - const frame = parseUiAutomatorXml(HIERARCHY_XML).children[0] - expect('text' in frame).toBe(false) - expect('resourceId' in frame).toBe(false) - expect('contentDesc' in frame).toBe(false) - }) - it('omits boolean and bounds fields when their attributes are absent', () => { const only = parseUiAutomatorXml('') .children[0] @@ -97,15 +69,6 @@ describe('parseUiAutomatorXml', () => { }) describe('parseAndroidBounds', () => { - it('parses a well-formed bounds string', () => { - expect(parseAndroidBounds('[0,0][1080,2340]')).toEqual({ - left: 0, - top: 0, - right: 1080, - bottom: 2340 - }) - }) - it('parses negative coordinates for off-screen elements', () => { expect(parseAndroidBounds('[-5,10][1080,2340]')).toEqual({ left: -5, diff --git a/src/main/emulator/emulator-session-registry.test.ts b/src/main/emulator/emulator-session-registry.test.ts index 4707b286647..4af46090028 100644 --- a/src/main/emulator/emulator-session-registry.test.ts +++ b/src/main/emulator/emulator-session-registry.test.ts @@ -1,39 +1,6 @@ import { describe, expect, it } from 'vitest' import { EmulatorSessionRegistry } from './emulator-session-registry' -describe('EmulatorSessionRegistry backend tagging', () => { - it('round-trips backend kind and stream codec', () => { - const registry = new EmulatorSessionRegistry() - registry.registerActive( - 'wt1', - { deviceUdid: 'emulator-5554', wsUrl: '', streamUrl: '', streamCodec: 'h264' }, - { managed: true, backend: 'android' } - ) - const session = registry.getSession('emulator-5554') - expect(session?.backend).toBe('android') - expect(session?.streamCodec).toBe('h264') - }) - - it('defaults backend to ios and codec to mjpeg when unspecified', () => { - const registry = new EmulatorSessionRegistry() - registry.registerActive('wt1', { deviceUdid: 'UDID', wsUrl: '', streamUrl: '' }) - const session = registry.getSession('UDID') - expect(session?.backend).toBe('ios') - expect(session?.streamCodec).toBe('mjpeg') - }) - - it('carries streamCodec back through getActiveForWorktree', () => { - const registry = new EmulatorSessionRegistry() - registry.registerActive( - 'wt1', - { deviceUdid: 'd', wsUrl: '', streamUrl: '', streamCodec: 'h264' }, - { backend: 'android' } - ) - const info = registry.getActiveForWorktree('wt1') - expect(info?.streamCodec).toBe('h264') - }) -}) - describe('EmulatorSessionRegistry managed-session liveness', () => { function registryWith(...serials: string[]): EmulatorSessionRegistry { const registry = new EmulatorSessionRegistry() @@ -63,12 +30,6 @@ describe('EmulatorSessionRegistry managed-session liveness', () => { expect(stopped).toContain('emulator-5556') }) - it('reads no managed devices once every one is gone', async () => { - const registry = registryWith('emulator-5554') - expect(await registry.pruneGoneManagedSessions(census([]))).toBe(false) - expect(registry.listSessions()).toEqual([]) - }) - it('keeps the records when adb could not answer', async () => { const registry = registryWith('emulator-5554') expect(await registry.pruneGoneManagedSessions(census(null))).toBe(true) diff --git a/src/main/emulator/scrcpy-video-registry.test.ts b/src/main/emulator/scrcpy-video-registry.test.ts index 34456bb825e..32c0ac9c4f3 100644 --- a/src/main/emulator/scrcpy-video-registry.test.ts +++ b/src/main/emulator/scrcpy-video-registry.test.ts @@ -33,13 +33,6 @@ describe('scrcpyVideoRegistry', () => { expect(scrcpyVideoRegistry.has('dev')).toBe(false) }) - it('ignores pushes for unknown devices', () => { - expect(() => - scrcpyVideoRegistry.pushMeta('missing', { codecId: 'h264', width: 1, height: 1 }) - ).not.toThrow() - expect(scrcpyVideoRegistry.subscribe('missing', () => {})()).toBeUndefined() - }) - it('replays the current GOP (keyframe + following deltas) to late subscribers', () => { scrcpyVideoRegistry.register('gop', () => {}) const tag = (event: ScrcpyVideoEvent): string => diff --git a/src/main/emulator/simctl-simulator-devices.test.ts b/src/main/emulator/simctl-simulator-devices.test.ts index 27fbd8c01aa..52cfd7c1b3c 100644 --- a/src/main/emulator/simctl-simulator-devices.test.ts +++ b/src/main/emulator/simctl-simulator-devices.test.ts @@ -22,7 +22,11 @@ vi.mock('./serve-sim-execution', () => ({ execServeSimCommand: vi.fn() })) -import { listSimulatorDevices, shutdownSimulatorDevice } from './simctl-simulator-devices' +import { + listSimulatorDevices, + resolveSimulatorUdid, + shutdownSimulatorDevice +} from './simctl-simulator-devices' describe('listSimulatorDevices', () => { beforeEach(() => { @@ -95,6 +99,45 @@ describe('listSimulatorDevices', () => { }) }) +describe('resolveSimulatorUdid', () => { + beforeEach(() => { + execFileMock.mockReset() + platformMock.mockReturnValue('darwin') + }) + + it('prefers an exact name over an earlier device whose name only contains it', async () => { + execFileMock.mockImplementation((_command, _args, _options, callback) => { + callback( + null, + JSON.stringify({ + devices: { + 'com.apple.CoreSimulator.SimRuntime.iOS-27-0': [ + { + name: 'iPhone 17e', + udid: '645A2204-ED7C-4253-B298-2749820B1B7E', + state: 'Shutdown' + }, + { name: 'iPhone 17', udid: '1BD4732B-EC1A-4074-8C70-6AC369607185', state: 'Shutdown' } + ] + } + }), + '' + ) + }) + const serveSim = { command: 'serve-sim', baseArgs: [], usesElectronAsNode: false } + + await expect(resolveSimulatorUdid('iPhone 17', serveSim)).resolves.toBe( + '1BD4732B-EC1A-4074-8C70-6AC369607185' + ) + await expect(resolveSimulatorUdid('iPHONE 17', serveSim)).resolves.toBe( + '1BD4732B-EC1A-4074-8C70-6AC369607185' + ) + await expect(resolveSimulatorUdid('17e', serveSim)).resolves.toBe( + '645A2204-ED7C-4253-B298-2749820B1B7E' + ) + }) +}) + describe('shutdownSimulatorDevice', () => { beforeEach(() => { execFileMock.mockReset() diff --git a/src/main/emulator/simctl-simulator-devices.ts b/src/main/emulator/simctl-simulator-devices.ts index 55466caf8a8..252fd9e148c 100644 --- a/src/main/emulator/simctl-simulator-devices.ts +++ b/src/main/emulator/simctl-simulator-devices.ts @@ -95,9 +95,12 @@ export async function resolveSimulatorUdid( try { const devices = await listSimulatorDevices() const needle = deviceOrName.toLowerCase() - const match = devices.find( - (device) => device.name.toLowerCase().includes(needle) || device.udid === deviceOrName - ) + // An exact name wins so `iPhone 17` cannot resolve to an earlier `iPhone 17e`. + const match = + devices.find((device) => device.name.toLowerCase() === needle) ?? + devices.find( + (device) => device.name.toLowerCase().includes(needle) || device.udid === deviceOrName + ) if (match) { return match.udid } diff --git a/src/main/external-conversations/external-conversation-reopen.ts b/src/main/external-conversations/external-conversation-reopen.ts index 8217315d9e6..fd01d423911 100644 --- a/src/main/external-conversations/external-conversation-reopen.ts +++ b/src/main/external-conversations/external-conversation-reopen.ts @@ -19,7 +19,9 @@ const REOPEN_REFUSALS: Record, Con // An unreachable SSH host may still run the old pane, so reopening would risk duplicates. held_elsewhere: 'agent_not_reachable', no_resume_command: 'reopen_refused', - create_failed: 'reopen_refused' + create_failed: 'reopen_refused', + // Connector refusal codes are a published set; the host-side result keeps the fix-it message. + windows_only_cli: 'reopen_refused' } /** Resume only the linked session after proving it is unheld; never substitute a shell or fresh agent. */ diff --git a/src/main/ghostty/parser.test.ts b/src/main/ghostty/parser.test.ts index d0ac459022d..43e3751caec 100644 --- a/src/main/ghostty/parser.test.ts +++ b/src/main/ghostty/parser.test.ts @@ -2,54 +2,6 @@ import { describe, expect, it } from 'vitest' import { parseGhosttyConfig } from './parser' describe('parseGhosttyConfig', () => { - it('returns empty object for empty content', () => { - expect(parseGhosttyConfig('')).toEqual({}) - }) - - it('parses a single key-value pair', () => { - expect(parseGhosttyConfig('font-family = JetBrains Mono')).toEqual({ - 'font-family': 'JetBrains Mono' - }) - }) - - it('ignores comments and blank lines', () => { - const input = ` -# This is a comment -font-size = 14 - -background = #1a1a1a -` - expect(parseGhosttyConfig(input)).toEqual({ - 'font-size': '14', - background: '#1a1a1a' - }) - }) - - it('ignores lines without an equals sign', () => { - expect(parseGhosttyConfig('invalid line\nfont-family = Fira Code')).toEqual({ - 'font-family': 'Fira Code' - }) - }) - - it('trims whitespace around keys and values', () => { - expect(parseGhosttyConfig(' foreground = #ffffff ')).toEqual({ - foreground: '#ffffff' - }) - }) - - it('parses multiple entries', () => { - const input = ` -font-family = JetBrains Mono -font-size = 13 -cursor-style = bar -` - expect(parseGhosttyConfig(input)).toEqual({ - 'font-family': 'JetBrains Mono', - 'font-size': '13', - 'cursor-style': 'bar' - }) - }) - it('returns array for duplicate keys', () => { const input = ` palette = 0=#000000 @@ -60,16 +12,6 @@ palette = 2=#00ff00 expect(result.palette).toEqual(['0=#000000', '1=#ff0000', '2=#00ff00']) }) - it('keeps single value as string when key is not duplicated', () => { - const input = ` -font-family = JetBrains Mono -palette = 0=#000000 -` - const result = parseGhosttyConfig(input) - expect(result['font-family']).toBe('JetBrains Mono') - expect(result.palette).toBe('0=#000000') - }) - it('strips inline comments', () => { const input = ` font-size = 14 # this is the size @@ -100,9 +42,4 @@ palette = 0='#000000' # black const result = parseGhosttyConfig('font-family = "JetBrains Mono"') expect(result['font-family']).toBe('JetBrains Mono') }) - - it('strips surrounding single quotes from string values', () => { - const result = parseGhosttyConfig("font-family = 'JetBrains Mono'") - expect(result['font-family']).toBe('JetBrains Mono') - }) }) diff --git a/src/main/git/hosted-remote-url.ts b/src/main/git/hosted-remote-url.ts index a1b080f6abf..500fbd2c1d8 100644 --- a/src/main/git/hosted-remote-url.ts +++ b/src/main/git/hosted-remote-url.ts @@ -1,4 +1,4 @@ -import { normalizeGitLabRemoteHost } from '../../shared/git-remote-host-alias' +import { normalizeForgeWebHost } from '../../shared/git-remote-host-alias' // Scoped local fork of the hosted-git-info@9.0.3 behavior Orca used. // Keep only the provider parsing and file/commit URL construction needed by source links. @@ -22,15 +22,14 @@ const shorthandHosts: Record({ content: '', isBinary: false, exists: false }), readGitBlobAtOidPath(worktreePath, args.commitOid, args.filePath, options) ]) @@ -55,7 +55,8 @@ async function loadCommitDiff( rightBlob.content, leftBlob.isBinary, rightBlob.isBinary, - args.filePath + args.filePath, + leftBlob.tooLarge === true || rightBlob.tooLarge === true ) } catch { return { diff --git a/src/main/git/source-control/diff-result.ts b/src/main/git/source-control/diff-result.ts index 745ed277a72..244fae60316 100644 --- a/src/main/git/source-control/diff-result.ts +++ b/src/main/git/source-control/diff-result.ts @@ -1,28 +1,35 @@ -import * as path from 'node:path' import type { GitDiffResult } from '../../../shared/git-diff-compare-types' import { getLargeDiffRenderLimit } from '../../../shared/large-diff-render-limit' -import { PREVIEWABLE_BINARY_MIME_TYPES } from './previewable-binary-mime-types' +import { + IMAGE_AND_PDF_PREVIEW_MIME_TYPES, + filePreviewExtension +} from '../../../shared/file-preview-kind' export function buildDiffResult( originalContent: string, modifiedContent: string, originalIsBinary: boolean, modifiedIsBinary: boolean, - filePath?: string + filePath?: string, + /** A side was over the read cap rather than proven binary. */ + tooLarge = false ): GitDiffResult { if (originalIsBinary || modifiedIsBinary) { const mimeType = filePath - ? PREVIEWABLE_BINARY_MIME_TYPES[path.extname(filePath).toLowerCase()] + ? IMAGE_AND_PDF_PREVIEW_MIME_TYPES[filePreviewExtension(filePath)] : undefined + const sides = originalIsBinary + ? { originalIsBinary: true as const, modifiedIsBinary } + : { originalIsBinary: false, modifiedIsBinary: true as const } return { kind: 'binary', originalContent, modifiedContent, - originalIsBinary, - modifiedIsBinary, + ...sides, // Why: renderer still checks legacy `isImage` before previewing, so set it for PDFs too until the contract is renamed. - ...(mimeType ? { isImage: true, mimeType } : {}) - } as GitDiffResult + ...(mimeType ? { isImage: true, mimeType } : {}), + ...(tooLarge ? { tooLarge: true } : {}) + } } // Why: over the render limit, return metadata instead of huge text so the renderer can show fallback UI. diff --git a/src/main/git/source-control/diff-too-large-real-git.test.ts b/src/main/git/source-control/diff-too-large-real-git.test.ts new file mode 100644 index 00000000000..346ec67d76a --- /dev/null +++ b/src/main/git/source-control/diff-too-large-real-git.test.ts @@ -0,0 +1,64 @@ +import { rm, writeFile } from 'node:fs/promises' +import { execFileSync } from 'node:child_process' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { getDiff } from './file-diff' +import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' +import { invalidateGitReadCaches } from './git-read-cache-invalidation' + +function git(dir: string, args: string[]): void { + execFileSync('git', args, { cwd: dir, stdio: 'pipe' }) +} + +// Text, not binary: only its size keeps it out of a text diff. +const largeText = (): string => 'a line of text\n'.repeat(Math.ceil(MAX_GIT_SHOW_BYTES / 15) + 1) + +describe('a diff side past the read cap', () => { + let repo: string + + beforeEach(() => { + repo = mkdtempSync(path.join(tmpdir(), 'orca-diff-too-large-')) + git(repo, ['init']) + git(repo, ['config', 'user.email', 'test@example.com']) + git(repo, ['config', 'user.name', 'Test User']) + invalidateGitReadCaches() + }) + + afterEach(async () => { + invalidateGitReadCaches() + await rm(repo, { recursive: true, force: true }) + }) + + it('is marked too large, still binary for older readers, from the working tree and from Git', async () => { + await writeFile(path.join(repo, 'big.txt'), 'small\n') + git(repo, ['add', '.']) + git(repo, ['commit', '-m', 'initial']) + await writeFile(path.join(repo, 'big.txt'), largeText()) + + expect(await getDiff(repo, 'big.txt', false)).toMatchObject({ + kind: 'binary', + modifiedIsBinary: true, + tooLarge: true + }) + git(repo, ['add', 'big.txt']) + invalidateGitReadCaches() + expect(await getDiff(repo, 'big.txt', true)).toMatchObject({ + kind: 'binary', + modifiedIsBinary: true, + tooLarge: true + }) + }) + + it('leaves a real binary unmarked', async () => { + await writeFile(path.join(repo, 'blob.bin'), Buffer.from([1, 0, 2])) + git(repo, ['add', '.']) + git(repo, ['commit', '-m', 'initial']) + await writeFile(path.join(repo, 'blob.bin'), Buffer.from([3, 0, 4])) + + const result = await getDiff(repo, 'blob.bin', false) + expect(result).toMatchObject({ kind: 'binary', modifiedIsBinary: true }) + expect(result).not.toHaveProperty('tooLarge') + }) +}) diff --git a/src/main/git/source-control/file-diff.ts b/src/main/git/source-control/file-diff.ts index b28a6fc4f5a..846dc964be1 100644 --- a/src/main/git/source-control/file-diff.ts +++ b/src/main/git/source-control/file-diff.ts @@ -141,6 +141,7 @@ async function loadDiff( let modifiedIsBinary = false let modifiedDeleted = false let readFailed = false + let tooLarge = false try { if (staged) { @@ -155,6 +156,7 @@ async function loadDiff( modifiedIsBinary = rightBlob.isBinary modifiedDeleted = !rightBlob.exists && !rightBlob.failed readFailed = leftBlob.failed === true || rightBlob.failed === true + tooLarge = leftBlob.tooLarge === true || rightBlob.tooLarge === true } else { // The index-to-HEAD fallback is sequential internally, but independent of the working-tree read. // WSL Git can use a Linux cwd while Node needs its Win32 spelling. @@ -173,6 +175,7 @@ async function loadDiff( modifiedIsBinary = workingTreeBlob.isBinary modifiedDeleted = !workingTreeBlob.exists readFailed = leftBlob.failed === true || workingTreeBlob.failed === true + tooLarge = leftBlob.tooLarge === true || workingTreeBlob.tooLarge === true } } catch { readFailed = true @@ -183,7 +186,8 @@ async function loadDiff( modifiedContent, originalIsBinary, modifiedIsBinary, - filePath + filePath, + tooLarge ) // Mark proven deletions so previewers can distinguish them from failed empty reads. if (result.kind === 'binary' && modifiedDeleted) { diff --git a/src/main/git/source-control/git-blob-read.ts b/src/main/git/source-control/git-blob-read.ts index 5d3d158e47a..d7721fa8bfd 100644 --- a/src/main/git/source-control/git-blob-read.ts +++ b/src/main/git/source-control/git-blob-read.ts @@ -1,5 +1,4 @@ import { readFile, stat } from 'node:fs/promises' -import * as path from 'node:path' import { isBinaryBuffer } from '../../../shared/binary-buffer' import { isMissingGitBlobPath } from '../../../shared/git-blob-absence' import type { GitRuntimeOptions } from '../git-runtime-options' @@ -7,7 +6,10 @@ import { gitReadOptionsForWorktree } from '../git-runtime-options' import { gitExecFileAsyncBuffer } from '../runner' import { isMaxBufferOverflowError } from '../max-buffer-overflow' import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' -import { PREVIEWABLE_BINARY_MIME_TYPES } from './previewable-binary-mime-types' +import { + IMAGE_AND_PDF_PREVIEW_MIME_TYPES, + filePreviewExtension +} from '../../../shared/file-preview-kind' export type GitBlobReadResult = { content: string @@ -15,6 +17,15 @@ export type GitBlobReadResult = { exists: boolean /** Unknown presence: never cache a diff whose empty side came from an incomplete read. */ failed?: boolean + /** Past MAX_GIT_SHOW_BYTES: left unread and reported binary, so older diff readers stay safe. */ + tooLarge?: boolean +} + +const TOO_LARGE_BLOB: GitBlobReadResult = { + content: '', + isBinary: true, + exists: true, + tooLarge: true } export async function readUnstagedLeftBlob( @@ -46,7 +57,7 @@ export async function readGitBlobAtIndexPath( return { ...bufferToBlob(stdout, filePath), exists: true } } catch (error) { if (isMaxBufferOverflowError(error)) { - return { content: '', isBinary: true, exists: true } + return TOO_LARGE_BLOB } return { content: '', @@ -77,7 +88,7 @@ export async function readGitBlobAtOidPath( return { ...bufferToBlob(stdout, filePath), exists: true } } catch (error) { if (isMaxBufferOverflowError(error)) { - return { content: '', isBinary: true, exists: true } + return TOO_LARGE_BLOB } return { content: '', @@ -102,7 +113,7 @@ export async function readWorkingTreeFile(filePath: string): Promise MAX_GIT_SHOW_BYTES) { // Mirror the Git buffer cap so filesystem reads cannot load huge assets. - return { content: '', isBinary: true, exists: true } + return TOO_LARGE_BLOB } try { const buffer = await readFile(filePath) @@ -116,7 +127,7 @@ function bufferToBlob(buffer: Buffer, filePath?: string): GitBlobReadResult { const isBinary = isBinaryBuffer(buffer) // Encode previewable binaries for the renderer. const isPreviewableBinary = filePath - ? !!PREVIEWABLE_BINARY_MIME_TYPES[path.extname(filePath).toLowerCase()] + ? !!IMAGE_AND_PDF_PREVIEW_MIME_TYPES[filePreviewExtension(filePath)] : false return { content: isBinary diff --git a/src/main/git/source-control/previewable-binary-mime-types.ts b/src/main/git/source-control/previewable-binary-mime-types.ts deleted file mode 100644 index 28ba602bc95..00000000000 --- a/src/main/git/source-control/previewable-binary-mime-types.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const PREVIEWABLE_BINARY_MIME_TYPES: Record = { - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.svg': 'image/svg+xml', - '.webp': 'image/webp', - '.bmp': 'image/bmp', - '.ico': 'image/x-icon', - '.pdf': 'application/pdf' -} diff --git a/src/main/git/source-control/status-read.ts b/src/main/git/source-control/status-read.ts index b3a383099a1..e442793c2e6 100644 --- a/src/main/git/source-control/status-read.ts +++ b/src/main/git/source-control/status-read.ts @@ -13,6 +13,7 @@ import { reuseOrRecomputeGitStatusLineStats } from '../../../shared/git-status-line-stats-cache' import { resolveWorktreeHostPath } from '../../../shared/git-metadata-path' +import { readGitCommandFailureStderr } from '../../../shared/git-command-failure-text' import { gitOptionalLocksDisabledEnv, gitStreamStdout } from '../runner' import { findExistingWorktreeSymlinkPaths, @@ -100,6 +101,15 @@ async function dropSharedSymlinkUntrackedEntries( } } +// Git's stderr is unbounded and travels to remote clients; the first lines say what failed. +const STATUS_READ_ERROR_MAX_LENGTH = 1_000 + +function describeStatusReadError(error: unknown): string { + const stderr = readGitCommandFailureStderr(error)?.trim() + const text = stderr || (error instanceof Error ? error.message : String(error)) + return text.slice(0, STATUS_READ_ERROR_MAX_LENGTH) +} + async function runGetStatus( worktreePath: string, options: GetStatusOptions = {} @@ -109,6 +119,7 @@ async function runGetStatus( options.includeLineStats === false ? null : beginGitStatusLineStatsCacheWrite(lineStatsCacheKey) let effectiveUpstreamStatus: GitUpstreamStatus | undefined let statusSucceeded = false + let readError: string | undefined const limit = resolveGitStatusLimit(options.limit) const conflictPromise = detectConflictOperation(worktreePath, options) @@ -161,6 +172,7 @@ async function runGetStatus( if (options.signal?.aborted) { throw error } + readError = describeStatusReadError(error) } let entries: GitStatusEntry[] = [] @@ -251,6 +263,7 @@ async function runGetStatus( conflictOperation, head, branch, + ...(readError !== undefined ? { readError } : {}), ...(options.includeIgnored ? { ignoredPaths: parser.ignoredPaths } : {}), ...(branchLineTotal ? { branchLineTotal } : {}), ...(branchLineTotalUnavailable ? { branchLineTotalUnavailable } : {}), diff --git a/src/main/git/source-control/submodule-diff.ts b/src/main/git/source-control/submodule-diff.ts index d016cbe748e..cead8baaf06 100644 --- a/src/main/git/source-control/submodule-diff.ts +++ b/src/main/git/source-control/submodule-diff.ts @@ -54,6 +54,7 @@ export async function buildSubmoduleInnerCommitRangeDiff( let modifiedContent = '' let originalIsBinary = false let modifiedIsBinary = false + let tooLarge = false try { const left = await readGitBlobAtOidPath(submoduleWorktreePath, fromOid, innerPath, options) originalContent = left.content @@ -61,12 +62,14 @@ export async function buildSubmoduleInnerCommitRangeDiff( const right = await readGitBlobAtOidPath(submoduleWorktreePath, toOid, innerPath, options) modifiedContent = right.content modifiedIsBinary = right.isBinary + tooLarge = left.tooLarge === true || right.tooLarge === true } catch {} return buildDiffResult( originalContent, modifiedContent, originalIsBinary, modifiedIsBinary, - innerPath + innerPath, + tooLarge ) } diff --git a/src/main/git/status-read-failure-real-git.test.ts b/src/main/git/status-read-failure-real-git.test.ts new file mode 100644 index 00000000000..65a442f8e8c --- /dev/null +++ b/src/main/git/status-read-failure-real-git.test.ts @@ -0,0 +1,47 @@ +import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as path from 'node:path' +import { runProcessSync } from '@orca/process-host' +import { afterEach, expect, it } from 'vitest' +import { getStatus, invalidateGitReadCaches } from './status' + +let root: string | undefined + +afterEach(async () => { + invalidateGitReadCaches() + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +it('reports a failed status read instead of a clean tree, then recovers', async () => { + root = await mkdtemp(path.join(tmpdir(), 'orca-status-read-failure-')) + const repo = path.join(root, 'repo') + const git = (args: string[], cwd = repo): void => { + const result = runProcessSync({ program: 'git', args, cwd }) + expect(result.code, result.stderr).toBe(0) + } + git(['init', '-q', repo], root) + git(['config', 'user.email', 'test@example.com']) + git(['config', 'user.name', 'Test User']) + git(['config', 'commit.gpgSign', 'false']) + await writeFile(path.join(repo, 'README.md'), 'original\n') + git(['add', 'README.md']) + git(['commit', '-q', '-m', 'Initial']) + await writeFile(path.join(repo, 'README.md'), 'changed\n') + + const indexPath = path.join(repo, '.git', 'index') + const backupPath = path.join(root, 'index.backup') + await copyFile(indexPath, backupPath) + await writeFile(indexPath, 'synthetic-invalid-index\n') + + const failed = await getStatus(repo, { includeLineStats: false }) + expect(failed.entries).toEqual([]) + expect(failed.readError).toMatch(/index/) + + await copyFile(backupPath, indexPath) + invalidateGitReadCaches() + const recovered = await getStatus(repo, { includeLineStats: false }) + expect(recovered.entries.map((entry) => entry.path)).toEqual(['README.md']) + expect(recovered.readError).toBeUndefined() +}) diff --git a/src/main/gitea/repository-ref.test.ts b/src/main/gitea/repository-ref.test.ts index b33a3f7abb0..031e9417eae 100644 --- a/src/main/gitea/repository-ref.test.ts +++ b/src/main/gitea/repository-ref.test.ts @@ -93,6 +93,7 @@ describe('Gitea repository ref parsing', () => { expect(parseGiteaRepoRef('git@github.com:team/project.git')).toBeNull() expect(parseGiteaRepoRef('https://gitlab.com/team/project.git')).toBeNull() expect(parseGiteaRepoRef('https://bitbucket.org/team/project.git')).toBeNull() + expect(parseGiteaRepoRef('git@ssh.bitbucket.org:team/project.git')).toBeNull() expect(parseGiteaRepoRef('https://dev.azure.com/team/project/_git/repo')).toBeNull() expect(parseGiteaRepoRef('https://team.visualstudio.com/project/_git/repo')).toBeNull() }) diff --git a/src/main/gitea/repository-ref.ts b/src/main/gitea/repository-ref.ts index cebdea882e3..8ab57367afc 100644 --- a/src/main/gitea/repository-ref.ts +++ b/src/main/gitea/repository-ref.ts @@ -16,6 +16,7 @@ const KNOWN_NON_GITEA_HOSTS = new Set([ 'github.com', 'gitlab.com', 'bitbucket.org', + 'ssh.bitbucket.org', 'dev.azure.com', 'ssh.dev.azure.com' ]) diff --git a/src/main/github/client-merge-queue-auto-merge.test.ts b/src/main/github/client-merge-queue-auto-merge.test.ts index fc803aef5df..ae5a944593f 100644 --- a/src/main/github/client-merge-queue-auto-merge.test.ts +++ b/src/main/github/client-merge-queue-auto-merge.test.ts @@ -99,10 +99,14 @@ describe('GitHub GraphQL rate-limit guard', () => { ).resolves.toBe(true) expect(getOwnerRepoMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['api', 'repos/stablyai/orca/pulls/7'], { - cwd: '/repo-root', - host: 'github.com' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 1, + ['api', 'repos/stablyai/orca/pulls/7', '--include'], + { + cwd: '/repo-root', + host: 'github.com' + } + ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 2, [ @@ -155,9 +159,13 @@ describe('GitHub GraphQL rate-limit guard', () => { }) ).resolves.toEqual({ ok: true }) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['api', 'repos/stablyai/orca/pulls/7'], { - host: 'github.com' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 1, + ['api', 'repos/stablyai/orca/pulls/7', '--include'], + { + host: 'github.com' + } + ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 2, ['pr', 'view', '7', '--json', 'id,headRefOid,baseRefName', '--repo', 'stablyai/orca'], diff --git a/src/main/github/client-pr-branch-discovery.test.ts b/src/main/github/client-pr-branch-discovery.test.ts index e9571266979..3f16f540cae 100644 --- a/src/main/github/client-pr-branch-discovery.test.ts +++ b/src/main/github/client-pr-branch-discovery.test.ts @@ -208,7 +208,11 @@ describe('getPRForBranch', () => { expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', undefined) expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(pr?.number).toBe(42) @@ -245,7 +249,11 @@ describe('getPRForBranch', () => { const pr = await getPRForBranch('/repo-root', 'feature/test') expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['api', 'repos/stablyai/orca/pulls?head=fork%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/stablyai/orca/pulls?head=fork%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(pr).toMatchObject({ @@ -277,7 +285,11 @@ describe('getPRForBranch', () => { expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 1, - ['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(pr).toMatchObject({ diff --git a/src/main/github/client-pr-fallback-number.test.ts b/src/main/github/client-pr-fallback-number.test.ts index 7be9fe18490..ad62a53acbc 100644 --- a/src/main/github/client-pr-fallback-number.test.ts +++ b/src/main/github/client-pr-fallback-number.test.ts @@ -82,7 +82,11 @@ describe('getPRForBranch', () => { expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 1, - ['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(pr).toMatchObject({ number: 43, title: 'Hydrated branch PR wins' }) @@ -113,7 +117,11 @@ describe('getPRForBranch', () => { expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 1, - ['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( @@ -167,7 +175,11 @@ describe('getPRForBranch', () => { ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 2, - ['api', 'repos/stablyai/orca/pulls?head=stablyai%3Afeature%2Ftest&state=all&per_page=1'], + [ + 'api', + 'repos/stablyai/orca/pulls?head=stablyai%3Afeature%2Ftest&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) }) diff --git a/src/main/github/client-pr-linked-lookup.test.ts b/src/main/github/client-pr-linked-lookup.test.ts index 618dd58dfa0..2207849f592 100644 --- a/src/main/github/client-pr-linked-lookup.test.ts +++ b/src/main/github/client-pr-linked-lookup.test.ts @@ -444,9 +444,13 @@ describe('getPRForBranch', () => { const pr = await getPRForBranch('/repo-root', 'feature/test', 99) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/acme/widgets/pulls/99'], { - cwd: '/repo-root' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + ['api', 'repos/acme/widgets/pulls/99', '--include'], + { + cwd: '/repo-root' + } + ) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(pr).toBeNull() }) @@ -477,9 +481,13 @@ describe('getPRForBranch', () => { const pr = await getPRForBranch('/repo-root', 'feature/test', 99) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/acme/widgets/pulls/99'], { - cwd: '/repo-root' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + ['api', 'repos/acme/widgets/pulls/99', '--include'], + { + cwd: '/repo-root' + } + ) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(pr).toBeNull() }) @@ -505,9 +513,13 @@ describe('getPRForBranch', () => { ], { cwd: '/repo-root' } ) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/acme/widgets/pulls/99'], { - cwd: '/repo-root' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + ['api', 'repos/acme/widgets/pulls/99', '--include'], + { + cwd: '/repo-root' + } + ) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(pr).toBeNull() }) @@ -662,9 +674,13 @@ describe('getPRForBranch', () => { ], { cwd: '/repo-root' } ) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/acme/widgets/pulls/99'], { - cwd: '/repo-root' - }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + ['api', 'repos/acme/widgets/pulls/99', '--include'], + { + cwd: '/repo-root' + } + ) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(pr).toMatchObject({ number: 99, diff --git a/src/main/github/client-pr-local-runtime.test.ts b/src/main/github/client-pr-local-runtime.test.ts index 70d26d26d39..dc539a5c56c 100644 --- a/src/main/github/client-pr-local-runtime.test.ts +++ b/src/main/github/client-pr-local-runtime.test.ts @@ -227,13 +227,13 @@ describe('GitHub PR local runtime routing', () => { stdout: JSON.stringify({ id: 13, node_id: 'PRRC_inline_13', user: null, body: 'Inline' }) } } - if (args.length === 2 && endpoint === 'repos/acme/orca/pulls/7') { + if (args.includes('--include') && endpoint === 'repos/acme/orca/pulls/7') { return { - stdout: JSON.stringify({ + stdout: `HTTP/2.0 200 OK\n\n${JSON.stringify({ number: 7, head: { ref: 'feature', sha: 'head-oid' }, base: { ref: 'main', sha: 'base-oid' } - }) + })}` } } return { stdout: '', stderr: '' } @@ -469,13 +469,13 @@ describe('GitHub PR local runtime routing', () => { if (endpoint.endsWith('/check-runs/88/annotations?per_page=20')) { return { stdout: '[]' } } - if (args.length === 2 && endpoint === 'repos/team/orca/pulls/7') { + if (args.includes('--include') && endpoint === 'repos/team/orca/pulls/7') { return { - stdout: JSON.stringify({ + stdout: `HTTP/2.0 200 OK\n\n${JSON.stringify({ number: 7, head: { ref: 'feature', sha: 'head-sha' }, base: { ref: 'main', sha: 'base-sha' } - }) + })}` } } if (query) { diff --git a/src/main/github/client-pr-rest-revalidation.test.ts b/src/main/github/client-pr-rest-revalidation.test.ts new file mode 100644 index 00000000000..87fdc4c303d --- /dev/null +++ b/src/main/github/client-pr-rest-revalidation.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as GithubApiRepositoryModule from './github-api-repository' +import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) +vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) +vi.mock('./local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('./github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('./github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' +import { resetPRForBranchMocks } from './client-test-harness' + +const { ghExecFileAsyncMock, getOwnerRepoMock, noteRateLimitSpendMock } = clientMocks + +describe('PR lookup conditional REST reads', () => { + beforeEach(() => resetPRForBranchMocks(clientMocks)) + + it('refreshes a missing branch immediately at zero primary cost when GitHub confirms it is unchanged', async () => { + getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: 'HTTP/2.0 200 OK\nEtag: "v1"\r\n\r\n[]' }) + .mockRejectedValueOnce( + Object.assign(new Error('gh: HTTP 304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) + ) + expect((await getPRForBranchOutcome('/repo', 'feature/missing')).kind).toBe('no-pr') + expect((await getPRForBranchOutcome('/repo', 'feature/missing')).kind).toBe('no-pr') + expect(ghExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fmissing&state=all&per_page=1', + '--include' + ], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fmissing&state=all&per_page=1', + '--include', + '-H', + 'If-None-Match: "v1"' + ] + ]) + expect(noteRateLimitSpendMock.mock.calls).toEqual([['core']]) + }) +}) diff --git a/src/main/github/client-stack-merge-guard.test.ts b/src/main/github/client-stack-merge-guard.test.ts index 7078e9933ae..99d60be51ad 100644 --- a/src/main/github/client-stack-merge-guard.test.ts +++ b/src/main/github/client-stack-merge-guard.test.ts @@ -566,7 +566,7 @@ describe('GitHub GraphQL rate-limit guard', () => { expect.soft(result).toEqual({ ok: false, error: scenario.expectedError }) expect .soft(ghExecFileAsyncMock.mock.calls.map(([args]) => args)) - .toEqual([['api', 'repos/stablyai/orca/pulls/202']]) + .toEqual([['api', 'repos/stablyai/orca/pulls/202', '--include']]) expect.soft(ghExecFileAsyncMock.mock.calls[0]?.[1]).toEqual(scenario.expectedOptions) expect .soft( diff --git a/src/main/github/client-test-mocks.ts b/src/main/github/client-test-mocks.ts index df940c3f12e..f04469b3a03 100644 --- a/src/main/github/client-test-mocks.ts +++ b/src/main/github/client-test-mocks.ts @@ -84,9 +84,25 @@ export type GhUtilsModuleMock = { } export function ghUtilsModuleMock(mocks: GitHubClientMocks): GhUtilsModuleMock { + const ghExecFileAsync = vi.fn(async (...args: unknown[]) => { + const result = await mocks.ghExecFileAsyncMock(...args) + const argv = args[0] + // Domain fixtures supply JSON bodies; --include also emits the CLI's HTTP framing. + if ( + Array.isArray(argv) && + argv.includes('--include') && + typeof argv[1] === 'string' && + /^repos\/[^/]+\/[^/]+\/pulls(?:\?head=|\/\d+$)/.test(argv[1]) && + typeof result?.stdout === 'string' && + !result.stdout.startsWith('HTTP/') + ) { + return { ...result, stdout: `HTTP/2.0 200 OK\n\n${result.stdout}` } + } + return result + }) return { execFileAsync: mocks.execFileAsyncMock, - ghExecFileAsync: mocks.ghExecFileAsyncMock, + ghExecFileAsync, getOwnerRepo: mocks.getOwnerRepoMock, getIssueOwnerRepo: mocks.getIssueOwnerRepoMock, getOwnerRepoForRemote: mocks.getOwnerRepoForRemoteMock, diff --git a/src/main/github/client-tracked-upstream-fork-owner.test.ts b/src/main/github/client-tracked-upstream-fork-owner.test.ts index 617bbaff365..c7f36530668 100644 --- a/src/main/github/client-tracked-upstream-fork-owner.test.ts +++ b/src/main/github/client-tracked-upstream-fork-owner.test.ts @@ -95,7 +95,8 @@ describe('getPRForBranch', () => { 3, [ 'api', - 'repos/stablyai/orca/pulls?head=fork-owner%3Acontributor%2Foriginal&state=all&per_page=1' + 'repos/stablyai/orca/pulls?head=fork-owner%3Acontributor%2Foriginal&state=all&per_page=1', + '--include' ], { cwd: '/repo-root' } ) @@ -165,7 +166,8 @@ describe('getPRForBranch', () => { 3, [ 'api', - 'repos/stablyai/orca/pulls?head=brennanb2025%3Abrennanb2025%2Fworktree-remove-fix&state=all&per_page=1' + 'repos/stablyai/orca/pulls?head=brennanb2025%3Abrennanb2025%2Fworktree-remove-fix&state=all&per_page=1', + '--include' ], { cwd: '/repo-root' } ) @@ -193,7 +195,11 @@ describe('getPRForBranch', () => { expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'origin', undefined) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fno-pr&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fno-pr&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) }) diff --git a/src/main/github/client-tracked-upstream-snapshot.test.ts b/src/main/github/client-tracked-upstream-snapshot.test.ts index bb1d78a6212..f268c4f0b34 100644 --- a/src/main/github/client-tracked-upstream-snapshot.test.ts +++ b/src/main/github/client-tracked-upstream-snapshot.test.ts @@ -94,12 +94,20 @@ describe('getPRForBranch', () => { ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 1, - ['api', 'repos/acme/widgets/pulls?head=acme%3Alocal-created-from-pr&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Alocal-created-from-pr&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 2, - ['api', 'repos/acme/widgets/pulls?head=acme%3Acontributor%2Foriginal&state=all&per_page=1'], + [ + 'api', + 'repos/acme/widgets/pulls?head=acme%3Acontributor%2Foriginal&state=all&per_page=1', + '--include' + ], { cwd: '/repo-root' } ) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( diff --git a/src/main/github/client/lookup/branch-lookup-resolution.ts b/src/main/github/client/lookup/branch-lookup-resolution.ts index fc114b72847..b40e613fab9 100644 --- a/src/main/github/client/lookup/branch-lookup-resolution.ts +++ b/src/main/github/client/lookup/branch-lookup-resolution.ts @@ -10,7 +10,6 @@ import { resolveGitHubApiRepositoryCandidates } from '../../github-api-repository' import { mapPRState } from '../../mappers' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' import { ownerRepoFromPullRequestUrl } from './../github-exec-scope' import { prRefreshUpstreamError } from './../gh-error-predicates' import { @@ -32,7 +31,6 @@ import { createImplicitDefaultBranchPRPolicy, type ImplicitDefaultBranchPRContext } from './implicit-default-branch-pr' -import { PR_BRANCH_LOOKUP_BUCKETS } from './pr-lookup-rate-limit' import type { HostedReviewLocalGitOptions } from './../github-exec-scope' export async function resolvePRForBranchOutcome(input: { repoPath: string @@ -65,10 +63,6 @@ export async function resolvePRForBranchOutcome(input: { if (connectionId && candidates.length === 0) { return { kind: 'no-pr', fetchedAt: Date.now() } } - // Renderer-direct lookups bypass coordinator accounting; debit both paths here. - for (const bucket of PR_BRANCH_LOOKUP_BUCKETS) { - noteRepositoryRateLimitSpend(headRepo ?? candidates[0], bucket, 1, ghOptions) - } let data: PullRequestLookupData | null = null let dataRepo: OwnerRepo | null = null let dataHeadRepo: OwnerRepo | null = headRepo diff --git a/src/main/github/client/lookup/pr-branch-lookup.ts b/src/main/github/client/lookup/pr-branch-lookup.ts index 0a1a24cb419..bdbf8862292 100644 --- a/src/main/github/client/lookup/pr-branch-lookup.ts +++ b/src/main/github/client/lookup/pr-branch-lookup.ts @@ -18,6 +18,8 @@ import { type RestPullRequest } from './pull-request-lookup-data' import { getPRByNumber } from './pr-number-lookup' +import { revalidateGitHubRestJson } from '../../github-rest-revalidation' +import { noteRepositoryRateLimitSpend } from '../../rate-limit' export async function getRestPRForBranch( prRepo: GitHubApiRepository, headOwner: string, @@ -25,9 +27,10 @@ export async function getRestPRForBranch( ghOptions: ReturnType ): Promise { const head = encodeURIComponent(`${headOwner}:${branchName}`) - const { stdout } = await ghExecFileAsync( - ['api', `repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=all&per_page=1`], - { ...ghOptions, ...githubHostExecOptions(prRepo) } + const stdout = await revalidateGitHubRestJson( + prRepo, + `repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=all&per_page=1`, + ghOptions ) const list = JSON.parse(stdout) as RestPullRequest[] const pr = list[0] @@ -39,6 +42,7 @@ export async function getFallbackPRListForBranch( branchName: string, ghOptions: ReturnType ): Promise { + noteRepositoryRateLimitSpend(prRepo, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync( [ 'pr', @@ -168,6 +172,7 @@ export async function lookupPRByBranchName(args: { } try { + noteRepositoryRateLimitSpend(null, 'graphql', 1, args.ghOptions) const { stdout } = await ghExecFileAsync( ['pr', 'view', args.branchName, '--json', PR_LOOKUP_JSON_FIELDS], args.ghOptions diff --git a/src/main/github/client/lookup/pr-number-lookup.ts b/src/main/github/client/lookup/pr-number-lookup.ts index 9aa18ef1cf8..2a4034d462c 100644 --- a/src/main/github/client/lookup/pr-number-lookup.ts +++ b/src/main/github/client/lookup/pr-number-lookup.ts @@ -16,15 +16,18 @@ import { } from './pull-request-lookup-data' import { hydratePullRequestLookupData } from './pull-request-lookup-hydration' import { isGitObjectId, isUsableRestStackMetadata } from './rest-stack-metadata-validation' +import { revalidateGitHubRestJson } from '../../github-rest-revalidation' +import { noteRepositoryRateLimitSpend } from '../../rate-limit' export async function getRestPRByNumber( ownerRepo: GitHubApiRepository, number: number, ghOptions: ReturnType, options: { requireUsableStackMetadata?: boolean } = {} ): Promise { - const { stdout } = await ghExecFileAsync( - ['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`], - { ...ghOptions, ...githubHostExecOptions(ownerRepo) } + const stdout = await revalidateGitHubRestJson( + ownerRepo, + `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`, + ghOptions ) const parsed = JSON.parse(stdout) as unknown if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { @@ -56,6 +59,7 @@ export async function getPRByNumber( knownPullRequestData?: PullRequestLookupData | null ): Promise { try { + noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync( [ 'pr', @@ -139,6 +143,7 @@ export async function lookupPRByNumber(args: { } try { + noteRepositoryRateLimitSpend(null, 'graphql', 1, args.ghOptions) const { stdout } = await ghExecFileAsync( ['pr', 'view', String(args.number), '--json', PR_LOOKUP_JSON_FIELDS], args.ghOptions diff --git a/src/main/github/default-branch-stale-pr.test.ts b/src/main/github/default-branch-stale-pr.test.ts index 11aefed1a77..b6021c8b931 100644 --- a/src/main/github/default-branch-stale-pr.test.ts +++ b/src/main/github/default-branch-stale-pr.test.ts @@ -163,7 +163,7 @@ function restPR({ function primeGhExecWithBranchList(list: Record[]): void { ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args[0] === 'api' && args[1]?.includes('pulls?head=')) { - return { stdout: JSON.stringify(list) } + return { stdout: `HTTP/2.0 200 OK\n\n${JSON.stringify(list)}` } } throw new Error(`gh unavailable: ${args.join(' ')}`) }) @@ -215,7 +215,7 @@ describe('issue #9171: default-branch checkout must not attach a stale non-open const pr = await getPRForBranch('/repo-root', 'master') expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['api', 'repos/acme/widgets/pulls?head=acme%3Amaster&state=all&per_page=1'], + ['api', 'repos/acme/widgets/pulls?head=acme%3Amaster&state=all&per_page=1', '--include'], { cwd: '/repo-root', host: 'github.com' } ) expect(pr).toBeNull() @@ -280,7 +280,7 @@ describe('issue #9171: default-branch checkout must not attach a stale non-open primeGitExecForDefaultBranch() ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args[0] === 'api' && args[1]?.includes('pulls?head=')) { - return { stdout: '[]' } + return { stdout: 'HTTP/2.0 200 OK\n\n[]' } } if (args[0] === 'pr' && args[1] === 'view' && args[2] === '7') { return { @@ -312,7 +312,7 @@ describe('issue #9171: default-branch checkout must not attach a stale non-open primeGitExecForDefaultBranch() ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args[0] === 'api' && args[1]?.includes('pulls?head=')) { - return { stdout: '[]' } + return { stdout: 'HTTP/2.0 200 OK\n\n[]' } } if (args[0] === 'pr' && args[1] === 'view' && args[2] === '7') { return { diff --git a/src/main/github/github-rest-revalidation.test.ts b/src/main/github/github-rest-revalidation.test.ts new file mode 100644 index 00000000000..ab9524cd0fd --- /dev/null +++ b/src/main/github/github-rest-revalidation.test.ts @@ -0,0 +1,118 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { revalidateGitHubRestJson } from './github-rest-revalidation' + +const { gh, spend } = vi.hoisted(() => ({ gh: vi.fn(), spend: vi.fn() })) +vi.mock('./gh-utils', () => ({ ghExecFileAsync: gh })) +vi.mock('./rate-limit', () => ({ noteRepositoryRateLimitSpend: spend })) + +const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } +const endpoint = 'repos/acme/widgets/pulls/7' +const options = { cwd: '/repo' } +let read: typeof revalidateGitHubRestJson +function http(status: number, body = '', etag?: string): { stdout: string; stderr: string } { + return { + stdout: `HTTP/2.0 ${status} ${status === 304 ? 'Not Modified' : 'OK'}\n${etag ? `Etag: ${etag}\r\n` : ''}\r\n${body}`, + stderr: '' + } +} +function notModified() { + return Object.assign(new Error('gh: HTTP 304'), http(304)) +} + +describe('GitHub REST revalidation', () => { + beforeEach(async () => { + vi.resetModules() + gh.mockReset() + spend.mockReset() + read = (await import('./github-rest-revalidation')).revalidateGitHubRestJson + }) + afterEach(() => vi.unstubAllEnvs()) + + it('revalidates immediately and returns the validated body on gh HTTP 304 exits without spending quota', async () => { + gh.mockResolvedValueOnce(http(200, '{"number":7}', 'W/"v1"')).mockRejectedValueOnce( + notModified() + ) + expect(await read(repository, endpoint, options)).toBe('{"number":7}') + expect(await read(repository, endpoint, options)).toBe('{"number":7}') + expect(gh.mock.calls[1][0]).toEqual([ + 'api', + endpoint, + '--include', + '-H', + 'If-None-Match: W/"v1"' + ]) + expect(spend).toHaveBeenCalledTimes(1) + expect(spend).toHaveBeenCalledWith(repository, 'core', 1, expect.objectContaining(options)) + }) + + it('replaces the validator when GitHub returns changed data', async () => { + gh.mockResolvedValueOnce(http(200, '{"number":7}', '"v1"')) + .mockResolvedValueOnce(http(200, '{"number":8}', '"v2"')) + .mockRejectedValueOnce(notModified()) + await read(repository, endpoint, options) + expect(await read(repository, endpoint, options)).toBe('{"number":8}') + expect(await read(repository, endpoint, options)).toBe('{"number":8}') + expect(gh.mock.calls[2][0]).toContain('If-None-Match: "v2"') + expect(spend).toHaveBeenCalledTimes(2) + }) + + it('does not return cached data after authorization failures and discards its validator', async () => { + gh.mockResolvedValueOnce(http(200, '{"number":7}', '"v1"')) + await read(repository, endpoint, options) + const failure = Object.assign( + new Error('HTTP 403 forbidden'), + http(403, '{"message":"forbidden"}') + ) + gh.mockRejectedValueOnce(failure).mockResolvedValueOnce(http(200, '{"number":8}')) + await expect(read(repository, endpoint, options)).rejects.toBe(failure) + expect(await read(repository, endpoint, options)).toBe('{"number":8}') + expect(gh.mock.calls[2][0]).not.toContain('-H') + }) + + it('keeps credentials, hosts, runtimes, directories, and endpoints separate', async () => { + gh.mockResolvedValue(http(200, '{"number":7}', '"v1"')) + await read(repository, endpoint, options) + await read(repository, `${endpoint}/files`, options) + await read(repository, endpoint, { cwd: '/other' }) + await read(repository, endpoint, { ...options, wslDistro: 'Ubuntu' }) + await read({ ...repository, host: 'github.example.com' }, endpoint, options) + await read(repository, endpoint, { + ...options, + ghAccount: { host: 'github.com', user: 'other' } + }) + vi.stubEnv('GH_TOKEN', 'different-test-account') + await read(repository, endpoint, options) + expect(gh.mock.calls.every(([args]) => !args.includes('-H'))).toBe(true) + expect(gh.mock.calls[4][1].host).toBe('github.example.com') + }) + + it('does not retain malformed or validator-free bodies and rejects ungrounded 304 responses', async () => { + gh.mockResolvedValueOnce(http(200, '{"number":7}')) + .mockResolvedValueOnce(http(200, 'truncated', '"bad"')) + .mockRejectedValueOnce(notModified()) + await read(repository, endpoint, options) + await expect(read(repository, endpoint, options)).rejects.toThrow() + await expect(read(repository, endpoint, options)).rejects.toThrow( + 'without a cached representation' + ) + expect(gh.mock.calls.every(([args]) => !args.includes('-H'))).toBe(true) + }) + + it('does not let an older read replace a newer validator', async () => { + let finish: (result: ReturnType) => void = () => {} + gh.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve + }) + ) + .mockResolvedValueOnce(http(200, '{"number":8}', '"new"')) + .mockRejectedValueOnce(notModified()) + const older = read(repository, endpoint, options) + await read(repository, endpoint, options) + finish(http(200, '{"number":7}', '"old"')) + await older + expect(await read(repository, endpoint, options)).toBe('{"number":8}') + expect(gh.mock.calls[2][0]).toContain('If-None-Match: "new"') + }) +}) diff --git a/src/main/github/github-rest-revalidation.ts b/src/main/github/github-rest-revalidation.ts new file mode 100644 index 00000000000..e3dd3980cfb --- /dev/null +++ b/src/main/github/github-rest-revalidation.ts @@ -0,0 +1,99 @@ +import { BoundedMap } from '../../shared/bounded-map' +import { extractExecError } from '../git/exec-error' +import { ghExecFileAsync } from './gh-utils' +import { githubReadExecutionScope } from './github-read-execution-scope' +import { + githubHostExecOptions, + type GitHubApiRepository, + type GitHubRepoExecOptions +} from './github-api-repository' +import { noteRepositoryRateLimitSpend } from './rate-limit' + +type Representation = { etag: string; body: string } +const representations = new BoundedMap({ + maxEntries: 512, + maxBytes: 16 * 1024 * 1024, + maxEntryBytes: 2 * 1024 * 1024, + sizeOf: (value, key) => + Buffer.byteLength(key) + Buffer.byteLength(value.etag) + Buffer.byteLength(value.body) +}) +const latestReads = new Map() + +function parseResponse(stdout: string): { status: number; etag?: string; body: string } | null { + const separator = /\r?\n\r?\n/.exec(stdout) + const status = /^HTTP\/\d+(?:\.\d+)? (\d{3})(?:[^\r\n]*)\r?\n/.exec(stdout) + if (!separator || !status) { + return null + } + const headers = stdout.slice(0, separator.index) + const etag = /^etag:[ \t]*([^\r\n]+)/im.exec(headers)?.[1].trim() + return { + status: Number(status[1]), + etag, + body: stdout.slice(separator.index + separator[0].length) + } +} + +/** Always revalidate: authenticated 304 responses preserve freshness without spending primary quota. */ +export async function revalidateGitHubRestJson( + repository: GitHubApiRepository, + endpoint: string, + options: GitHubRepoExecOptions +): Promise { + const execution = { + ...options, + ...githubHostExecOptions(repository) + } + const key = JSON.stringify([githubReadExecutionScope(execution), endpoint]) + const token = {} + latestReads.set(key, token) + const ownsKey = (): boolean => latestReads.get(key) === token + const previous = representations.get(key) + const args = ['api', endpoint, '--include'] + if (previous) { + args.push('-H', `If-None-Match: ${previous.etag}`) + } + try { + let stdout: string + try { + stdout = (await ghExecFileAsync(args, execution)).stdout + } catch (error) { + const failed = extractExecError(error).stdout + if (!failed || parseResponse(failed)?.status !== 304) { + throw error + } + stdout = failed + } + const response = parseResponse(stdout) + if (!response) { + throw new Error('GitHub REST response is missing HTTP headers') + } + if (response.status === 304) { + if (!previous) { + throw new Error('GitHub returned HTTP 304 without a cached representation') + } + return previous.body + } + if (response.status !== 200) { + throw new Error(`Unexpected GitHub REST response: HTTP ${response.status}`) + } + noteRepositoryRateLimitSpend(repository, 'core', 1, execution) + JSON.parse(response.body) + if (ownsKey()) { + representations.delete(key) + if (response.etag) { + representations.set(key, { etag: response.etag, body: response.body }) + } + } + return response.body + } catch (error) { + if (ownsKey()) { + representations.delete(key) + } + throw error + } finally { + if (ownsKey()) { + latestReads.delete(key) + } + } +} diff --git a/src/main/github/pr-refresh-coordinator-test-mocks.ts b/src/main/github/pr-refresh-coordinator-test-mocks.ts index 5c674077c8a..619cac5549e 100644 --- a/src/main/github/pr-refresh-coordinator-test-mocks.ts +++ b/src/main/github/pr-refresh-coordinator-test-mocks.ts @@ -1,10 +1,17 @@ import { vi, type Mock } from 'vitest' import { isWslUncPath } from '../../shared/wsl-paths' +type PRRefreshWebContentsMock = { + id: number + isDestroyed: () => boolean + send?: Mock +} + export type PRRefreshCoordinatorMocks = { sendMock: Mock sendToTrustedUIRendererMock: Mock - getAllWebContentsMock: Mock + getAllWebContentsMock: Mock<() => PRRefreshWebContentsMock[]> + webContentsFromIdMock: Mock<(id: number) => PRRefreshWebContentsMock | undefined> getPRForBranchOutcomeMock: Mock getOriginGitHubApiRepositoryMock: Mock getRateLimitMock: Mock @@ -19,6 +26,7 @@ export function createPRRefreshCoordinatorMocks(): PRRefreshCoordinatorMocks { sendMock: vi.fn(), sendToTrustedUIRendererMock: vi.fn(), getAllWebContentsMock: vi.fn(), + webContentsFromIdMock: vi.fn(), getPRForBranchOutcomeMock: vi.fn(), getOriginGitHubApiRepositoryMock: vi.fn(), getRateLimitMock: vi.fn(), @@ -28,12 +36,18 @@ export function createPRRefreshCoordinatorMocks(): PRRefreshCoordinatorMocks { } } -export type ElectronModuleMock = { webContents: { getAllWebContents: Mock } } +export type ElectronModuleMock = { + webContents: { + getAllWebContents: PRRefreshCoordinatorMocks['getAllWebContentsMock'] + fromId: PRRefreshCoordinatorMocks['webContentsFromIdMock'] + } +} export function electronModuleMock(mocks: PRRefreshCoordinatorMocks): ElectronModuleMock { return { webContents: { - getAllWebContents: mocks.getAllWebContentsMock + getAllWebContents: mocks.getAllWebContentsMock, + fromId: mocks.webContentsFromIdMock } } } @@ -86,6 +100,7 @@ export function resetPRRefreshCoordinatorMocks(mocks: PRRefreshCoordinatorMocks) sendMock, sendToTrustedUIRendererMock, getAllWebContentsMock, + webContentsFromIdMock, getPRForBranchOutcomeMock, getOriginGitHubApiRepositoryMock, getRateLimitMock, @@ -102,6 +117,10 @@ export function resetPRRefreshCoordinatorMocks(mocks: PRRefreshCoordinatorMocks) sendMock(channel, payload) }) getAllWebContentsMock.mockReset() + webContentsFromIdMock.mockReset() + webContentsFromIdMock.mockImplementation((id) => + getAllWebContentsMock().find((contents) => contents.id === id) + ) getPRForBranchOutcomeMock.mockReset() getOriginGitHubApiRepositoryMock.mockReset() getOriginGitHubApiRepositoryMock.mockResolvedValue({ diff --git a/src/main/github/pr-refresh-visibility.test.ts b/src/main/github/pr-refresh-visibility.test.ts new file mode 100644 index 00000000000..a1865a4736b --- /dev/null +++ b/src/main/github/pr-refresh-visibility.test.ts @@ -0,0 +1,126 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') + return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } +}) +vi.mock('electron', () => moduleMocks.electronModuleMock(coordinatorMocks)) + +import { makeCandidate } from './pr-refresh-coordinator-test-harness' +import { refreshKey } from './pr-refresh-candidate-policy' +import { PRRefreshVisibility } from './pr-refresh-visibility' + +const { getAllWebContentsMock, webContentsFromIdMock } = coordinatorMocks + +describe('PR refresh owner liveness', () => { + beforeEach(() => moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks)) + afterEach(() => vi.useRealTimers()) + + it('checks only recorded owners by ID instead of a native census', () => { + const registry = new Map( + Array.from({ length: 1_000 }, (_, index) => { + const id = index + 1 + return [id, { id, isDestroyed: () => false }] as const + }) + ) + getAllWebContentsMock.mockImplementation(() => Array.from(registry.values())) + webContentsFromIdMock.mockImplementation((id) => registry.get(id)) + const candidates = Array.from({ length: 100 }, (_, index) => + makeCandidate({ branch: `feature/${index}`, cacheKey: `/repo::feature/${index}` }) + ) + const visibility = new PRRefreshVisibility() + visibility.report(candidates, 1, 1) + + expect(candidates.every((candidate) => visibility.has(refreshKey(candidate)))).toBe(true) + expect(visibility.report(candidates, 2, 1)).toBe(true) + expect(visibility.windowCount).toBe(1) + expect(getAllWebContentsMock).not.toHaveBeenCalled() + expect(webContentsFromIdMock.mock.calls.every(([id]) => id === 1)).toBe(true) + }) + + it('does no native work without recorded owners', () => { + const visibility = new PRRefreshVisibility() + expect(visibility.has(refreshKey(makeCandidate()))).toBe(false) + expect(visibility.windowCount).toBe(0) + expect(getAllWebContentsMock).not.toHaveBeenCalled() + expect(webContentsFromIdMock).not.toHaveBeenCalled() + }) + + it('prunes missing and destroyed owners while checking surviving owners afresh', () => { + const destroyed = vi.fn(() => false) + const registry = new Map([ + [1, { id: 1, isDestroyed: () => false }], + [2, { id: 2, isDestroyed: destroyed }], + [3, { id: 3, isDestroyed: () => false }] + ]) + getAllWebContentsMock.mockImplementation(() => Array.from(registry.values())) + webContentsFromIdMock.mockImplementation((id) => registry.get(id)) + const visibility = new PRRefreshVisibility() + const candidate = makeCandidate() + for (const id of registry.keys()) { + visibility.report([candidate], 1, id) + } + registry.delete(1) + destroyed.mockReturnValue(true) + webContentsFromIdMock.mockClear() + expect(visibility.has(refreshKey(candidate))).toBe(true) + expect(visibility.windowCount).toBe(1) + expect(webContentsFromIdMock.mock.calls).toEqual([[1], [2], [3]]) + registry.delete(3) + webContentsFromIdMock.mockClear() + expect(visibility.has(refreshKey(candidate))).toBe(false) + expect(webContentsFromIdMock.mock.calls).toEqual([[3]]) + expect(visibility.windowCount).toBe(0) + }) + + it('prunes an old owner at the next report boundary', () => { + const registry = new Map([ + [1, { id: 1, isDestroyed: () => false }], + [2, { id: 2, isDestroyed: () => false }] + ]) + getAllWebContentsMock.mockImplementation(() => Array.from(registry.values())) + webContentsFromIdMock.mockImplementation((id) => registry.get(id)) + const visibility = new PRRefreshVisibility() + const first = makeCandidate() + const second = makeCandidate({ branch: 'feature/second', cacheKey: '/repo::feature/second' }) + visibility.report([first], 1, 1) + registry.delete(1) + expect(visibility.report([second], 1, 2)).toBe(true) + expect(visibility.windowCount).toBe(1) + expect(visibility.has(refreshKey(first))).toBe(false) + expect(visibility.has(refreshKey(second))).toBe(true) + }) + + it('retains generation, cached fields and surviving selection ownership', () => { + const registry = new Map([ + [1, { id: 1, isDestroyed: () => false }], + [2, { id: 2, isDestroyed: () => false }] + ]) + getAllWebContentsMock.mockImplementation(() => Array.from(registry.values())) + webContentsFromIdMock.mockImplementation((id) => registry.get(id)) + const visibility = new PRRefreshVisibility() + const candidate = makeCandidate({ cachedFetchedAt: 1, cachedHeadOid: 'old-head' }) + const key = refreshKey(candidate) + visibility.report([{ ...candidate, isSelected: true }], 2, 1) + visibility.report([candidate], 1, 2) + visibility.update({ ...candidate, cachedFetchedAt: 3, cachedHeadOid: 'new-head' }) + expect(visibility.report([], 1, 1)).toBe(false) + expect(visibility.candidate(key, candidate)).toMatchObject({ + isSelected: true, + cachedFetchedAt: 3, + cachedHeadOid: 'new-head' + }) + expect(visibility.report([candidate], 3, 1)).toBe(true) + expect(visibility.candidate(key, candidate)).toMatchObject({ + isSelected: false, + cachedFetchedAt: 3, + cachedHeadOid: 'new-head' + }) + visibility.report([{ ...candidate, isSelected: true }], 2, 2) + expect(visibility.clearWindow(1)).toBe(true) + expect(visibility.has(key)).toBe(true) + expect(visibility.candidate(key, candidate)).toMatchObject({ isSelected: true }) + registry.delete(2) + expect(visibility.has(key)).toBe(false) + }) +}) diff --git a/src/main/github/pr-refresh-visibility.ts b/src/main/github/pr-refresh-visibility.ts index 15dab59db1e..bf163f7d408 100644 --- a/src/main/github/pr-refresh-visibility.ts +++ b/src/main/github/pr-refresh-visibility.ts @@ -84,14 +84,9 @@ export class PRRefreshVisibility { } private pruneDestroyedWindows(): void { - const liveWindowIds = new Set( - webContents - .getAllWebContents() - .filter((contents) => !contents.isDestroyed()) - .map((contents) => contents.id) - ) for (const windowId of this.visibleByWindow.keys()) { - if (!liveWindowIds.has(windowId)) { + const contents = webContents.fromId(windowId) + if (!contents || contents.isDestroyed()) { this.visibleByWindow.delete(windowId) } } diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-item-details.test.ts index 5126549df5e..c919920283e 100644 --- a/src/main/github/work-item-details.test.ts +++ b/src/main/github/work-item-details.test.ts @@ -85,6 +85,7 @@ vi.mock('./rate-limit', () => ({ })) import { getWorkItemDetails } from './work-item-details' +import { getMentionParticipants } from './work-item-participants' import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' @@ -703,8 +704,7 @@ describe('getWorkItemDetails', () => { expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 42, 'pr', null, {}, 'origin') }) - // gh pr view omits avatar_url; Enterprise identities need GraphQL enrichment instead of dotcom fallbacks. - it('enriches PR author, reviewer, and assignee avatars from the GraphQL user lookup', async () => { + it('reuses participant profiles and enriches only missing or incomplete Enterprise users', async () => { getWorkItemMock.mockResolvedValueOnce({ id: 'pr:1102', type: 'pr', @@ -738,6 +738,24 @@ describe('getWorkItemDetails', () => { return { stdout: '[]' } } const query = args.find((arg) => arg.startsWith('query=')) ?? '' + if (query.includes('participants(first: 100)')) { + return { + stdout: JSON.stringify({ + data: { + repository: { + pullRequest: { + participants: { + nodes: [ + { login: 'seah', name: null, avatarUrl: avatars.seah }, + { login: 'ludi', name: 'Ludi', avatarUrl: '' } + ] + } + } + } + } + }) + } + } if (query.includes('user(login:')) { const data: Record = {} let index = 0 @@ -758,5 +776,40 @@ describe('getWorkItemDetails', () => { expect(details?.item.reviewRequests?.[0]?.avatarUrl).toBe(avatars.ludi) expect(details?.item.latestReviews?.[0]?.avatarUrl).toBe(avatars.inho) expect(details?.item.assignees?.[0]?.avatarUrl).toBe(avatars.seah) + const userQuery = ghExecFileAsyncMock.mock.calls + .flatMap(([args]) => args) + .find((arg: string) => arg.includes('user(login:')) + expect(userQuery).not.toContain('user(login: "seah")') + expect(userQuery).toContain('user(login: "ludi")') + expect(userQuery).toContain('user(login: "inho")') + expect(details?.participants).toContainEqual({ + login: 'ludi', + name: 'Ludi', + avatarUrl: avatars.ludi + }) + }) + + it('skips profile reads when participants already cover visible users regardless of login case', async () => { + const participants = [ + { login: 'alice', name: null, avatarUrl: 'https://ghe.example.com/avatar/1' }, + { login: 'bob', name: 'Bob', avatarUrl: 'https://ghe.example.com/avatar/2' } + ] + const result = await getMentionParticipants( + '/repo-root', + { + number: 42, + type: 'pr', + author: 'Alice', + reviewRequests: [{ login: 'BOB', name: null, avatarUrl: '' }], + latestReviews: [{ login: 'Bob', state: 'APPROVED', avatarUrl: null }], + assignees: [{ login: 'alice', name: null, avatarUrl: '' }] + }, + [], + participants, + { owner: 'acme', repo: 'widgets', host: 'ghe.example.com' } + ) + expect(result).toEqual(participants) + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled() }) }) diff --git a/src/main/github/work-item-participants.ts b/src/main/github/work-item-participants.ts index 0ac793b4812..d7bfc1f33f5 100644 --- a/src/main/github/work-item-participants.ts +++ b/src/main/github/work-item-participants.ts @@ -176,6 +176,9 @@ export async function getMentionParticipants( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { + const resolvedLogins = new Set( + participants.filter((user) => user.avatarUrl).map((user) => user.login.toLowerCase()) + ) const visibleLogins = [ item.author ?? '', ...(item.reviewRequests ?? []).map((user) => user.login), @@ -185,7 +188,7 @@ export async function getMentionParticipants( ] const graphQlUsers = await getGitHubUsersByLogin( repoPath, - visibleLogins, + visibleLogins.filter((login) => !resolvedLogins.has(login.trim().toLowerCase())), repository, connectionId, localGitOptions diff --git a/src/main/home-path-expansion.ts b/src/main/home-path-expansion.ts new file mode 100644 index 00000000000..7b577239764 --- /dev/null +++ b/src/main/home-path-expansion.ts @@ -0,0 +1,11 @@ +import { join, sep } from 'node:path' + +export function expandLeadingHomePath(input: string, home: string): string { + if (input === '~') { + return home + } + if (input.startsWith(`~${sep}`) || (process.platform === 'win32' && input.startsWith('~/'))) { + return join(home, input.slice(2)) + } + return input +} diff --git a/src/main/i18n/main-i18n.ts b/src/main/i18n/main-i18n.ts index 589bb4abdbe..d358a851776 100644 --- a/src/main/i18n/main-i18n.ts +++ b/src/main/i18n/main-i18n.ts @@ -27,6 +27,7 @@ const LAZY_LOCALE_LOADERS: Record< Exclude, () => Promise<{ default: Record }> > = { + de: () => import('../../renderer/src/i18n/locales/de.json'), es: () => import('../../renderer/src/i18n/locales/es.json'), fr: () => import('../../renderer/src/i18n/locales/fr.json'), ja: () => import('../../renderer/src/i18n/locales/ja.json'), diff --git a/src/main/i18n/system-language.test.ts b/src/main/i18n/system-language.test.ts index 334be5b1e8d..a183212e1ae 100644 --- a/src/main/i18n/system-language.test.ts +++ b/src/main/i18n/system-language.test.ts @@ -77,7 +77,7 @@ it.each([ status: 'supported' }, { platform: 'Linux C-only', preferences: ['C.UTF-8', 'C'], locale: 'en', status: 'unknown' }, - { platform: 'unsupported', preferences: ['de-DE', 'fr-FR'], locale: 'en', status: 'unsupported' } + { platform: 'unsupported', preferences: ['it-IT', 'fr-FR'], locale: 'en', status: 'unsupported' } ])('handles $platform preference lists', async ({ preferences, locale, status }) => { getPreferredSystemLanguages.mockReturnValue(preferences) const { getSystemLanguageDetection } = await import('./system-language') diff --git a/src/main/ipc/ai-vault-host-leg-cache.ts b/src/main/ipc/ai-vault-host-leg-cache.ts index 12c43c14752..af0a55b0bf1 100644 --- a/src/main/ipc/ai-vault-host-leg-cache.ts +++ b/src/main/ipc/ai-vault-host-leg-cache.ts @@ -1,5 +1,7 @@ import type { AiVaultProjectionDependency } from './ai-vault-projection-dependency' import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay' +import { AiVaultScanCoordinator } from '../ai-vault/ai-vault-scan-coordinator' +import { aiVaultSessionListCacheGeneration } from '../ai-vault/cached-session-list' import type { AiVaultListResult } from '../../shared/ai-vault-types' import { aiVaultCachedDepthServes, @@ -166,6 +168,22 @@ function dropEntry void }>(entries: Map, entries.delete(key) } +/** Keeps reads after a delete out of scans that began before it. Remote-client + * deletes bump only the shared session-list generation, so fence on both. */ +export function createAiVaultListScanCoordinator(): Pick { + const coordinator = new AiVaultScanCoordinator() + return { + run: (args) => + coordinator.run({ + ...args, + key: JSON.stringify({ + key: args.key, + generation: [cacheGeneration, aiVaultSessionListCacheGeneration()] + }) + }) + } +} + export function invalidateAiVaultHostLegCache(environmentId?: string): void { if (environmentId === undefined) { cacheGeneration++ diff --git a/src/main/ipc/ai-vault-scan-coalescing.test.ts b/src/main/ipc/ai-vault-scan-coalescing.test.ts index 8bfbcd2eb30..ad9c554c7f0 100644 --- a/src/main/ipc/ai-vault-scan-coalescing.test.ts +++ b/src/main/ipc/ai-vault-scan-coalescing.test.ts @@ -33,6 +33,7 @@ vi.mock('../../shared/runtime-environment-store', () => ({ })) import { createAiVaultAssociationObserver } from './ai-vault-projection-dependency' import { invalidateAiVaultHostLegCache } from './ai-vault-host-leg-cache' +import { invalidateAiVaultSessionListCache } from '../ai-vault/cached-session-list' import { registerRuntimeEnvironmentSubscriptionHandlers } from './runtime-environments/runtime-environment-subscription-handlers' import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environments/runtime-environment-transport-generation' import type { subscribeRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' @@ -120,6 +121,34 @@ describe('Agent Session History scan coalescing', () => { await expect(second).resolves.toMatchObject(EMPTY_RESULT) }) + it.each([ + ['local', 'desktop', mocks.scanAiVaultSessionsInService], + ['local', 'remote-client', mocks.scanAiVaultSessionsInService], + ['runtime:remote-server', 'desktop', mocks.scanRuntimeAiVaultSessions] + ] as const)( + 'does not let a %s read after a %s delete join a scan that began before it', + async (scope, deleter, scan) => { + registerRuntimeHost() + let finishBeforeDelete = (_result: AiVaultListResult): void => {} + scan + .mockReturnValueOnce(new Promise((resolve) => (finishBeforeDelete = resolve))) + .mockResolvedValueOnce({ ...EMPTY_RESULT, scannedAt: '2026-07-28T00:00:00.000Z' }) + const beforeDelete = _internals.listAiVaultSessions({ executionHostScope: scope }) + await vi.waitFor(() => expect(scan).toHaveBeenCalledTimes(1)) + + // Remote-client deletes skip the desktop host-leg cache. + if (deleter === 'desktop') { + invalidateAiVaultHostLegCache() + } + invalidateAiVaultSessionListCache() + const afterDelete = _internals.listAiVaultSessions({ executionHostScope: scope }) + finishBeforeDelete(EMPTY_RESULT) + + await expect(afterDelete).resolves.toMatchObject({ scannedAt: '2026-07-28T00:00:00.000Z' }) + await expect(beforeDelete).resolves.toMatchObject({ scannedAt: EMPTY_RESULT.scannedAt }) + } + ) + it('reports a failed local scan as a host issue rather than rejecting', async () => { mocks.scanAiVaultSessionsInService.mockRejectedValue(new Error('transcript root is unreadable')) registerAiVaultHandlers() diff --git a/src/main/ipc/ai-vault.ts b/src/main/ipc/ai-vault.ts index 5a73496a65a..c025b799717 100644 --- a/src/main/ipc/ai-vault.ts +++ b/src/main/ipc/ai-vault.ts @@ -17,7 +17,6 @@ import { cancelledAiVaultListResult, mergeAiVaultListResults } from '../ai-vault/session-list-results' -import { AiVaultScanCoordinator } from '../ai-vault/ai-vault-scan-coordinator' import type { AiVaultDeleteSessionArgs } from '../../shared/ai-vault-session-deletion' import { describeAiVaultScanError } from '../../shared/ai-vault-scan-error-message' import { @@ -46,6 +45,7 @@ import { type RuntimeAiVaultScanner } from './ai-vault-runtime-scan' import { + createAiVaultListScanCoordinator, invalidateAiVaultHostLegCache, resetAiVaultHostLegCacheForTests, scanHostLegWithCache @@ -78,7 +78,7 @@ type AiVaultScanHostScope = | { scope: ExecutionHostId } | { scope: 'all'; runtimeHosts: AiVaultHostDiscoveryResult } -let scanCoordinator = new AiVaultScanCoordinator() +let scanCoordinator = createAiVaultListScanCoordinator() let handlerOptions: AiVaultHandlerOptions = {} const listCancellations = createSenderScopedRequestCancellations() // Keep IPC and test deletion wired to this module's multi-host cache. @@ -308,7 +308,7 @@ export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): vo function resetAiVaultCacheForTests(): void { resetAiVaultHostLegCacheForTests() - scanCoordinator = new AiVaultScanCoordinator() + scanCoordinator = createAiVaultListScanCoordinator() handlerOptions = {} // Keep tests isolated from the shared local-leg cache. resetAiVaultSessionListCacheForTests() diff --git a/src/main/ipc/crash-reporting-submission.ts b/src/main/ipc/crash-reporting-submission.ts index f4cd5e0bbaf..90d2ff11620 100644 --- a/src/main/ipc/crash-reporting-submission.ts +++ b/src/main/ipc/crash-reporting-submission.ts @@ -46,7 +46,9 @@ export async function submitCrashReport( ): Promise { const report = await getRequestedCrashReport(store, args) if (!report) { - const diagnosticUpload = prepareCrashDiagnosticBundle(args.includeDiagnosticLogs !== false) + const diagnosticUpload = await prepareCrashDiagnosticBundle( + args.includeDiagnosticLogs !== false + ) const diagnosticBundle = diagnosticUpload.diagnosticBundle const reportOnlyDiagnosticBundle = diagnosticBundleForReportOnlyRetry(diagnosticUpload) const result = await submitFeedback({ @@ -98,7 +100,9 @@ export async function submitCrashReport( inFlightSubmissions.add(report.id) try { - const diagnosticUpload = prepareCrashDiagnosticBundle(args.includeDiagnosticLogs !== false) + const diagnosticUpload = await prepareCrashDiagnosticBundle( + args.includeDiagnosticLogs !== false + ) const diagnosticBundle = diagnosticUpload.diagnosticBundle const reportOnlyDiagnosticBundle = diagnosticBundleForReportOnlyRetry(diagnosticUpload) const result = await submitFeedback({ diff --git a/src/main/ipc/diagnostics.test.ts b/src/main/ipc/diagnostics.test.ts index 2868fdec19d..8a6b8d4c44a 100644 --- a/src/main/ipc/diagnostics.test.ts +++ b/src/main/ipc/diagnostics.test.ts @@ -302,7 +302,7 @@ describe('diagnostics IPC handlers', () => { collectDiagnosticBundleMock.mockReturnValue(bundle) const collect = handlers.get('diagnostics:collectBundle')! - expect(collect({}, 30)).toEqual({ + expect(await collect({}, 30)).toEqual({ bundleSubmissionId: bundle.bundleSubmissionId, bytes: bundle.bytes, spanCount: bundle.spanCount diff --git a/src/main/ipc/diagnostics.ts b/src/main/ipc/diagnostics.ts index 1b5e8377412..d81b9a71f7b 100644 --- a/src/main/ipc/diagnostics.ts +++ b/src/main/ipc/diagnostics.ts @@ -207,7 +207,7 @@ export function registerDiagnosticsHandlers(): void { ipcMain.handle( 'diagnostics:collectBundle', - (_event, lookbackMinutesIn: unknown): DiagnosticsBundlePreview => { + async (_event, lookbackMinutesIn: unknown): Promise => { // Enforce consent in main; hiding renderer controls is insufficient. const status = getDiagnosticsStatus() if (!status.bundleEnabled) { @@ -218,7 +218,7 @@ export function registerDiagnosticsHandlers(): void { typeof lookbackMinutesIn === 'number' && Number.isFinite(lookbackMinutesIn) ? Math.max(1, Math.min(30 * 24 * 60, Math.floor(lookbackMinutesIn))) : undefined - const bundle = collectDiagnosticBundle({ + const bundle = await collectDiagnosticBundle({ appVersion: app.getVersion(), platform: osPlatform(), arch: osArch(), diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 5b6441ec810..ecff0758281 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -35,6 +35,7 @@ import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handl import type { PluginService } from '../plugins/plugin-service' import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' const activeProvisionControllers = new Map() @@ -242,7 +243,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin let environment: ReturnType try { - environment = addEnvironmentFromPairingCode(app.getPath('userData'), { + environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), pairingCode: connection.pairingCode, source: 'ephemeral-vm' diff --git a/src/main/ipc/export.test.ts b/src/main/ipc/export.test.ts new file mode 100644 index 00000000000..03183517ab3 --- /dev/null +++ b/src/main/ipc/export.test.ts @@ -0,0 +1,362 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ExportHtmlToPdfArgs, ExportHtmlToPdfResult } from './export' + +type ExportHandler = ( + event: { sender: EventEmitter }, + args: ExportHtmlToPdfArgs +) => Promise + +const fake = vi.hoisted(() => ({ + handlers: new Map(), + tempFiles: new Set(), + savedFiles: new Map(), + windows: new Array<{ events: EventEmitter; destroyed: boolean }>(), + uuid: 0, + write: + vi.fn< + (path: string, data: string | Uint8Array, options?: { signal?: AbortSignal }) => Promise + >(), + load: vi.fn<(events: EventEmitter, path: string) => Promise>(), + images: vi.fn<() => Promise>(), + print: vi.fn<() => Promise>(), + dialog: vi.fn<() => Promise<{ canceled: boolean; filePath?: string }>>() +})) + +vi.mock('electron', () => ({ + app: { getPath: () => '/mock-export-temp' }, + ipcMain: { + removeHandler: () => { + fake.handlers.delete('export:html-to-pdf') + }, + handle: (_channel: string, handler: ExportHandler) => { + fake.handlers.set('export:html-to-pdf', handler) + } + }, + dialog: { showSaveDialog: fake.dialog }, + BrowserWindow: class { + static fromWebContents() { + return { id: 1 } + } + events = new EventEmitter() + destroyed = false + webContents = Object.assign(this.events, { + executeJavaScript: fake.images, + printToPDF: fake.print + }) + constructor() { + fake.windows.push(this) + } + loadFile(path: string) { + return fake.load(this.events, path) + } + isDestroyed() { + return this.destroyed + } + destroy() { + this.destroyed = true + } + } +})) +vi.mock('node:fs/promises', () => ({ + writeFile: fake.write, + unlink: async (path: string) => { + fake.tempFiles.delete(path) + } +})) +vi.mock('node:crypto', () => ({ randomUUID: () => `export-${++fake.uuid}` })) + +import { registerExportHandlers } from './export' + +const PDF = Buffer.from('exported PDF snapshot') +const ARGS = { html: '

captured markdown

', title: 'draft' } +const GONE_EVENTS = ['render-process-gone', 'did-navigate', 'destroyed'] as const + +function exportFrom(sender: EventEmitter): Promise { + const handler = fake.handlers.get('export:html-to-pdf') + if (!handler) { + throw new Error('Export handler was not registered') + } + return handler({ sender }, ARGS) +} + +async function flush(): Promise { + await vi.advanceTimersByTimeAsync(0) +} + +function expectReleased(sender: EventEmitter): void { + expect(fake.tempFiles.size).toBe(0) + expect(fake.windows.every((window) => window.destroyed)).toBe(true) + expect(vi.getTimerCount()).toBe(0) + for (const event of GONE_EVENTS) { + expect(sender.listenerCount(event)).toBe(0) + } + for (const window of fake.windows) { + expect(window.events.listenerCount('did-finish-load')).toBe(0) + expect(window.events.listenerCount('did-fail-load')).toBe(0) + } +} + +beforeEach(() => { + vi.useFakeTimers() + vi.resetAllMocks() + fake.tempFiles.clear() + fake.savedFiles.clear() + fake.windows.length = 0 + fake.write.mockImplementation(async (path, data) => { + if (typeof data === 'string') { + fake.tempFiles.add(path) + } else { + fake.savedFiles.set(path, data) + } + }) + fake.load.mockImplementation(async (events) => { + events.emit('did-finish-load') + }) + fake.images.mockResolvedValue() + fake.print.mockResolvedValue(PDF) + fake.dialog.mockResolvedValue({ canceled: true }) + registerExportHandlers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('PDF export requesting document lifetime', () => { + it.each(GONE_EVENTS)('releases a hidden export on %s before images settle', async (event) => { + const images = Promise.withResolvers() + fake.images.mockReturnValueOnce(images.promise) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + expect(fake.tempFiles.size).toBe(1) + expect(fake.windows).toHaveLength(1) + + sender.emit(event) + await flush() + expectReleased(sender) + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + expectReleased(sender) + images.resolve() + await flush() + expect(fake.print).not.toHaveBeenCalled() + expect(fake.dialog).not.toHaveBeenCalled() + }) + + it.each(['load', 'load-event', 'images', 'print'] as const)( + 'cleans up pending %s and observes its late rejection', + async (stage) => { + const pending = Promise.withResolvers() + const printing = Promise.withResolvers() + if (stage === 'load') { + fake.load.mockReturnValueOnce(pending.promise) + } + if (stage === 'load-event') { + fake.load.mockResolvedValueOnce() + } + if (stage === 'images') { + fake.images.mockReturnValueOnce(pending.promise) + } + if (stage === 'print') { + fake.print.mockReturnValueOnce(printing.promise) + } + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + sender.emit('render-process-gone') + await flush() + expectReleased(sender) + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + expectReleased(sender) + + if (stage === 'print') { + printing.reject(new Error('late print failure')) + } else if (stage === 'load-event') { + fake.windows[0]?.events.emit('did-fail-load', {}, -3, 'late failure') + } else { + pending.reject(new Error('late renderer failure')) + } + await flush() + expect(fake.dialog).not.toHaveBeenCalled() + expect(fake.print).toHaveBeenCalledTimes(stage === 'print' ? 1 : 0) + } + ) + + it.each(['resolve', 'reject'] as const)( + 'cancels initial document writing and cleans up after late %s', + async (settlement) => { + const writing = Promise.withResolvers() + fake.write.mockImplementationOnce(async (path) => { + fake.tempFiles.add(path) + await writing.promise + }) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + const signal = fake.write.mock.calls[0]?.[2]?.signal + expect(signal?.aborted).toBe(false) + sender.emit('did-navigate') + expect(signal?.aborted).toBe(true) + expect(fake.windows).toHaveLength(0) + expect(fake.tempFiles.size).toBe(1) + + if (settlement === 'resolve') { + writing.resolve() + } else { + writing.reject(new Error('write aborted')) + } + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + expectReleased(sender) + expect(fake.windows).toHaveLength(0) + expect(fake.dialog).not.toHaveBeenCalled() + } + ) + + it('prevents a late load resolution from admitting image or print work', async () => { + const load = Promise.withResolvers() + fake.load.mockReturnValueOnce(load.promise) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + sender.emit('destroyed') + await flush() + expectReleased(sender) + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + load.resolve() + fake.windows[0]?.events.emit('did-finish-load') + await flush() + expectReleased(sender) + expect(fake.images).not.toHaveBeenCalled() + expect(fake.print).not.toHaveBeenCalled() + }) + + it('keeps a replacement document and another requester independent of late old work', async () => { + const images = Promise.withResolvers() + const otherImages = Promise.withResolvers() + fake.images.mockReturnValueOnce(images.promise).mockReturnValueOnce(otherImages.promise) + const sender = new EventEmitter() + const oldResult = exportFrom(sender) + await flush() + const other = new EventEmitter() + const otherResult = exportFrom(other) + await flush() + sender.emit('did-navigate') + await flush() + expect(fake.windows.map((window) => window.destroyed)).toEqual([true, false]) + expect(fake.tempFiles.size).toBe(1) + expect(other.listenerCount('render-process-gone')).toBe(1) + await expect(oldResult).resolves.toEqual({ success: false, cancelled: true }) + fake.dialog.mockResolvedValueOnce({ canceled: false, filePath: '/chosen/new.pdf' }) + fake.dialog.mockResolvedValueOnce({ canceled: false, filePath: '/chosen/other.pdf' }) + await expect(exportFrom(sender)).resolves.toEqual({ + success: true, + filePath: '/chosen/new.pdf' + }) + otherImages.resolve() + await expect(otherResult).resolves.toEqual({ + success: true, + filePath: '/chosen/other.pdf' + }) + images.resolve() + await flush() + expect(fake.print).toHaveBeenCalledTimes(2) + expect(fake.dialog).toHaveBeenCalledTimes(2) + expect(fake.savedFiles).toEqual( + new Map([ + ['/chosen/new.pdf', PDF], + ['/chosen/other.pdf', PDF] + ]) + ) + expectReleased(sender) + expectReleased(other) + }) + + it('preserves captured content through tab/file switches and same-document navigation', async () => { + const images = Promise.withResolvers() + fake.images.mockReturnValueOnce(images.promise) + fake.dialog.mockResolvedValueOnce({ canceled: false, filePath: '/chosen/snapshot.pdf' }) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + sender.emit('did-navigate-in-page') + // Tab/file selection is renderer-local; the captured HTML request remains owned by this document. + images.resolve() + await expect(result).resolves.toEqual({ success: true, filePath: '/chosen/snapshot.pdf' }) + expect(fake.savedFiles.get('/chosen/snapshot.pdf')).toBe(PDF) + expectReleased(sender) + }) + + it('does not write a save choice returned after the requesting document retired', async () => { + const choice = Promise.withResolvers<{ canceled: boolean; filePath: string }>() + fake.dialog.mockReturnValueOnce(choice.promise) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + expect(fake.dialog).toHaveBeenCalledOnce() + sender.emit('render-process-gone') + choice.resolve({ canceled: false, filePath: '/chosen/late.pdf' }) + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + expect(fake.savedFiles.size).toBe(0) + expectReleased(sender) + }) + + it('finishes a user-accepted write that started before retirement', async () => { + const writing = Promise.withResolvers() + fake.dialog.mockResolvedValueOnce({ canceled: false, filePath: '/chosen/accepted.pdf' }) + fake.write.mockImplementation(async (path, data) => { + if (typeof data === 'string') { + fake.tempFiles.add(path) + return + } + await writing.promise + fake.savedFiles.set(path, data) + }) + const sender = new EventEmitter() + const result = exportFrom(sender) + await flush() + expect(fake.write).toHaveBeenCalledWith('/chosen/accepted.pdf', PDF) + sender.emit('destroyed') + writing.resolve() + await expect(result).resolves.toEqual({ success: true, filePath: '/chosen/accepted.pdf' }) + expect(fake.savedFiles.get('/chosen/accepted.pdf')).toBe(PDF) + expectReleased(sender) + }) + + it('releases listeners and resources across repeated successful and retired exports', async () => { + const sender = new EventEmitter() + for (let index = 0; index < 10; index++) { + const retired = index % 2 === 0 + const filePath = `/chosen/${index}.pdf` + const images = Promise.withResolvers() + fake.images.mockReturnValueOnce(images.promise) + if (!retired) { + fake.dialog.mockResolvedValueOnce({ canceled: false, filePath }) + } + const prints = fake.print.mock.calls.length + const dialogs = fake.dialog.mock.calls.length + const result = exportFrom(sender) + await flush() + if (retired) { + sender.emit('render-process-gone') + } else { + images.resolve() + } + await flush() + expectReleased(sender) + if (retired) { + await expect(result).resolves.toEqual({ success: false, cancelled: true }) + expect(fake.print.mock.calls.length).toBe(prints) + expect(fake.dialog.mock.calls.length).toBe(dialogs) + expect(fake.savedFiles.has(filePath)).toBe(false) + } else { + await expect(result).resolves.toEqual({ success: true, filePath }) + expect(fake.print.mock.calls.length).toBe(prints + 1) + expect(fake.savedFiles.get(filePath)).toEqual(PDF) + } + images.reject(new Error('late image failure')) + await flush() + expectReleased(sender) + } + }) +}) diff --git a/src/main/ipc/export.ts b/src/main/ipc/export.ts index 7b8c944791f..f7205dab33e 100644 --- a/src/main/ipc/export.ts +++ b/src/main/ipc/export.ts @@ -1,6 +1,7 @@ import { BrowserWindow, dialog, ipcMain } from 'electron' import { writeFile } from 'node:fs/promises' import { ExportTimeoutError, htmlToPdf } from '../lib/html-to-pdf' +import { abortWhenRendererGone } from './renderer-lifetime-abort' export type ExportHtmlToPdfArgs = { html: string @@ -21,8 +22,10 @@ export function registerExportHandlers(): void { return { success: false, error: 'No content to export' } } + const lifetime = abortWhenRendererGone(event.sender) try { - const pdfBuffer = await htmlToPdf(html) + const pdfBuffer = await htmlToPdf(html, lifetime.signal) + lifetime.signal.throwIfAborted() // Keep long titles and Windows-forbidden characters out of suggested save filenames. const sanitizedTitle = title.replace(/[/\\:*?"<>|]/g, '_').slice(0, 100) || 'export' @@ -37,13 +40,18 @@ export function registerExportHandlers(): void { ? await dialog.showSaveDialog(parent, dialogOptions) : await dialog.showSaveDialog(dialogOptions) + lifetime.signal.throwIfAborted() if (canceled || !filePath) { return { success: false, cancelled: true } } + lifetime.dispose() await writeFile(filePath, pdfBuffer) return { success: true, filePath } } catch (error) { + if (lifetime.signal.aborted) { + return { success: false, cancelled: true } + } if (error instanceof ExportTimeoutError) { return { success: false, error: 'Export timed out' } } @@ -51,6 +59,8 @@ export function registerExportHandlers(): void { success: false, error: error instanceof Error ? error.message : 'Failed to export PDF' } + } finally { + lifetime.dispose() } } ) diff --git a/src/main/ipc/filesystem/filesystem-file-content-inspection.ts b/src/main/ipc/filesystem/filesystem-file-content-inspection.ts index ab87ca5699f..2014a4ee99e 100644 --- a/src/main/ipc/filesystem/filesystem-file-content-inspection.ts +++ b/src/main/ipc/filesystem/filesystem-file-content-inspection.ts @@ -1,4 +1,7 @@ -import { extname } from 'node:path' +import { + IMAGE_AND_PDF_PREVIEW_MIME_TYPES, + filePreviewExtension +} from '../../../shared/file-preview-kind' import { localLogFileIdentity } from '../../ai-vault/local-log-tail-reader' import { BINARY_PROBE_BYTES, isBinaryBuffer } from '../../../shared/binary-buffer' import { @@ -11,21 +14,11 @@ import { // Monaco degrades features on large files; a 5MB cap would reject ordinary logs and JSON. export const MAX_TEXT_FILE_SIZE = 50 * 1024 * 1024 export const MAX_PREVIEWABLE_BINARY_SIZE = 50 * 1024 * 1024 -export const PREVIEWABLE_BINARY_MIME_TYPES: Record = { - '.png': 'image/png', - '.avif': 'image/avif', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.svg': 'image/svg+xml', - '.webp': 'image/webp', - '.bmp': 'image/bmp', - '.ico': 'image/x-icon', - '.pdf': 'application/pdf' -} export type LocalFileContent = { mediaUrl?: string + /** Bytes behind `mediaUrl`, for viewers that no longer see the content. */ + size?: number content: string isBinary: boolean isImage?: boolean @@ -37,7 +30,7 @@ export type LocalFileContent = { export async function readLocalFileContent(filePath: string): Promise { const { handle, stats } = await openLocalRegularFile(filePath) try { - const mimeType = PREVIEWABLE_BINARY_MIME_TYPES[extname(filePath).toLowerCase()] + const mimeType = IMAGE_AND_PDF_PREVIEW_MIME_TYPES[filePreviewExtension(filePath)] const sizeLimit = mimeType ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE if (stats.size > sizeLimit) { throw fileTooLargeError(stats.size, sizeLimit) diff --git a/src/main/ipc/filesystem/filesystem-read-handlers.ts b/src/main/ipc/filesystem/filesystem-read-handlers.ts index db09b7308a9..ee039362520 100644 --- a/src/main/ipc/filesystem/filesystem-read-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-read-handlers.ts @@ -23,9 +23,11 @@ import { recordCrashBreadcrumb } from '../../crash-reporting/crash-breadcrumb-st import { buildReadDirErrorBreadcrumb, type ReadDirThrowSite } from '../readdir-error-diagnostics' import type { FilesystemHandlerContext } from './filesystem-handler-context' import { registerFilesystemChunkReadHandler } from './filesystem-chunk-read-handler' -import { readMediaPreview } from '../../media/media-preview-protocol' +import { grantRemoteFilePreview, readLocalFilePreview } from '../../media/media-preview-protocol' +import { readPreviewGrantRange } from '../../media/preview-grant-range-read' import { windowsFsPath } from '../../wsl/wsl-unc-drive-fs-path' import { assertWslUncPathRunning, guardWslUncPathAccess } from '../../wsl/wsl-unc-access-gate' +import { parseRemoteFilePreviewAddress } from '../../../shared/remote-file-preview-address' import { readLocalFileContent, readLocalLogSnapshot, @@ -97,6 +99,8 @@ export function registerFilesystemReadHandlers(context: FilesystemHandlerContext access?: LocalFileAccess /** A user act (open, expand, Retry); may start a stopped WSL distro. */ wakeWslDistro?: boolean + /** A viewer that reads images and PDFs by URL; other readers keep their base64. */ + rangePreview?: boolean } ): Promise => { if (args.connectionId) { @@ -106,7 +110,9 @@ export function registerFilesystemReadHandlers(context: FilesystemHandlerContext args.filePath, async () => { const filePath = await resolveLocalFileRequestPath(args.filePath, args.access, store) - const media = readMediaPreview(event, args, store) + const media = await readLocalFilePreview(event, args, store, { + documents: args.rangePreview === true + }) if (media) { return media } @@ -119,6 +125,20 @@ export function registerFilesystemReadHandlers(context: FilesystemHandlerContext } ) + ipcMain.handle( + 'fs:readPreviewRange', + (event, args: { url: string; offset: number; length: number }) => + readPreviewGrantRange(event.sender, String(args?.url), args?.offset, args?.length) + ) + + ipcMain.handle('fs:grantRuntimeFilePreview', (event, args: unknown) => { + const remote = parseRemoteFilePreviewAddress(args) + if (!remote) { + throw new Error('Invalid preview path') + } + return grantRemoteFilePreview(event, remote, store) + }) + ipcMain.handle( 'fs:listMarkdownDocuments', async ( diff --git a/src/main/ipc/floating-workspace-directory.ts b/src/main/ipc/floating-workspace-directory.ts index 305d8fb287d..3b1c1bdc1c8 100644 --- a/src/main/ipc/floating-workspace-directory.ts +++ b/src/main/ipc/floating-workspace-directory.ts @@ -5,29 +5,15 @@ import { getAppEnvironment } from '../../shared/app-environment' import type { GlobalSettings } from '../../shared/global-settings-types' import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types' import type { Store } from '../persistence' +import { resolveFloatingWorkspacePath } from '../persistence/restoring-sessions/floating-workspace-normalization' type FloatingTerminalSettings = Pick const FLOATING_WORKSPACE_DIRNAME = 'floating-workspace' -function expandHomePath(input: string, home: string): string { - if (input === '~') { - return home - } - if (input.startsWith(`~${path.sep}`)) { - return path.join(home, input.slice(2)) - } - if (process.platform === 'win32' && input.startsWith('~/')) { - return path.join(home, input.slice(2)) - } - return input -} - function resolveFloatingWorkspaceInput(input: string): string { // Headless runtime uses this path resolver without an Electron app. - const home = getAppEnvironment().getPath('home') - const expanded = expandHomePath(input, home) - return path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(home, expanded) + return resolveFloatingWorkspacePath(input, getAppEnvironment().getPath('home')) } async function canonicalizeAccessibleDirectory(dirPath: string): Promise { diff --git a/src/main/ipc/github-pr-refresh-document-lifetime.test.ts b/src/main/ipc/github-pr-refresh-document-lifetime.test.ts new file mode 100644 index 00000000000..cea64ae837e --- /dev/null +++ b/src/main/ipc/github-pr-refresh-document-lifetime.test.ts @@ -0,0 +1,137 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' + +const { handlers, lookup, contents } = vi.hoisted(() => ({ + handlers: new Map unknown>(), + lookup: vi.fn(), + contents: new Map boolean }>() +})) +vi.mock('electron', () => ({ + ipcMain: { + handle: (channel: string, handler: (...args: unknown[]) => unknown) => + handlers.set(channel, handler) + }, + webContents: { fromId: (id: number) => contents.get(id) } +})) +vi.mock('../github/client', () => ({ getPRForBranch: vi.fn(), getPRForBranchOutcome: lookup })) +vi.mock('../github/pr-refresh-rate-limit-gate', () => ({ + prRefreshRateLimitPausedUntil: async () => null +})) +vi.mock('../wsl/wsl-unc-access-gate', () => ({ + wslDistroForPath: () => null, + blockedWslDistroForPath: async () => null +})) +vi.mock('../crash-reporting/crash-breadcrumb-store', () => ({ + recordCoalescedCrashBreadcrumb: () => {} +})) +vi.mock('./ui', () => ({ sendToTrustedUIRenderer: () => {} })) +vi.mock('./github-repo-routing', () => ({ + validateAutomaticPRRefreshCandidate: (candidate: unknown) => ({ kind: 'ok', candidate }), + isPRRefreshCandidateRegistered: () => true +})) + +import { makeCandidate, makePR } from '../github/pr-refresh-coordinator-test-harness' + +function sender(id: number) { + return Object.assign(new EventEmitter(), { id, isDestroyed: () => false }) +} +function found(): PRRefreshOutcome { + return { kind: 'found', pr: makePR({ checksStatus: 'pending' }), fetchedAt: Date.now() } +} +async function setup() { + const { registerGitHubPRRefreshHandlers } = await import('./github-pr-refresh-handlers') + const coordinator = await import('../github/pr-refresh-coordinator') + const owner = sender(17) + const other = sender(18) + contents.set(owner.id, owner) + contents.set(other.id, other) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Visible refresh registration reads only this store fixture's repo list. + const store = { getRepos: () => [] } as never + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Every PR is already counted, so the observer reads only this stats method. + const stats = { hasCountedPR: () => true } as never + registerGitHubPRRefreshHandlers(store, stats) + const report = (target = owner) => + handlers.get('gh:reportVisiblePRRefreshCandidates')!( + { sender: target }, + { candidates: [makeCandidate()], generation: Date.now() } + ) + return { owner, other, report, coordinator } +} + +describe('automatic PR refresh document ownership', () => { + beforeEach(() => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_700_000_000_000) + handlers.clear() + contents.clear() + lookup.mockReset().mockImplementation(async () => found()) + }) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + + it.each(['did-navigate', 'render-process-gone', 'destroyed'])( + 'stops automatic lookups and admits replacement reports after %s', + async (event) => { + const { owner, report, coordinator } = await setup() + report() + await vi.advanceTimersByTimeAsync(0) + expect(lookup).toHaveBeenCalledTimes(1) + owner.emit(event) + expect(coordinator._getVisiblePRRefreshWindowCountForTests()).toBe(0) + expect(coordinator._getPRRefreshQueueSizeForTests()).toBe(0) + await vi.advanceTimersByTimeAsync(360_000) + expect(lookup).toHaveBeenCalledTimes(1) + report() + await vi.advanceTimersByTimeAsync(0) + expect(lookup).toHaveBeenCalledTimes(2) + owner.emit('destroyed') + } + ) + + it('keeps a surviving window subscription and same-document navigation live', async () => { + const { owner, other, report, coordinator } = await setup() + report() + report(other) + await vi.advanceTimersByTimeAsync(0) + expect(lookup).toHaveBeenCalledTimes(1) + owner.emit('did-navigate-in-page', {}, '#section', true) + expect(coordinator._getVisiblePRRefreshWindowCountForTests()).toBe(2) + owner.emit('render-process-gone') + expect(coordinator._getVisiblePRRefreshWindowCountForTests()).toBe(1) + await vi.advanceTimersByTimeAsync(120_000) + expect(lookup).toHaveBeenCalledTimes(2) + other.emit('destroyed') + await vi.advanceTimersByTimeAsync(360_000) + expect(lookup).toHaveBeenCalledTimes(2) + }) + + it('does not requeue a late lookup after document retirement', async () => { + const pending = Promise.withResolvers() + lookup.mockImplementationOnce(() => pending.promise) + const { owner, report, coordinator } = await setup() + report() + await vi.advanceTimersByTimeAsync(0) + owner.emit('render-process-gone') + pending.resolve(found()) + await vi.advanceTimersByTimeAsync(360_000) + expect(lookup).toHaveBeenCalledTimes(1) + expect(coordinator._getVisiblePRRefreshWindowCountForTests()).toBe(0) + expect(coordinator._getPRRefreshQueueSizeForTests()).toBe(0) + }) + + it('bounds native listeners over ten document replacements', async () => { + const { owner, report } = await setup() + for (let index = 0; index < 10; index += 1) { + report() + expect(owner.listenerCount('did-navigate')).toBe(1) + expect(owner.listenerCount('render-process-gone')).toBe(1) + expect(owner.listenerCount('destroyed')).toBe(1) + owner.emit(index % 2 === 0 ? 'did-navigate' : 'render-process-gone') + expect(owner.eventNames()).toEqual([]) + } + }) +}) diff --git a/src/main/ipc/github-pr-refresh-handlers.ts b/src/main/ipc/github-pr-refresh-handlers.ts index 5c45c96901a..0c9a23d222f 100644 --- a/src/main/ipc/github-pr-refresh-handlers.ts +++ b/src/main/ipc/github-pr-refresh-handlers.ts @@ -27,6 +27,7 @@ import { isPRRefreshCandidateRegistered, validateAutomaticPRRefreshCandidate } from './github-repo-routing' +import { abortWhenRendererGone } from './renderer-lifetime-abort' const visibilityCleanupRegistered = new Set() @@ -151,10 +152,15 @@ export function registerGitHubPRRefreshHandlers(store: Store, stats: StatsCollec const senderId = event.sender.id if (!visibilityCleanupRegistered.has(senderId)) { visibilityCleanupRegistered.add(senderId) - event.sender.once('destroyed', () => { - visibilityCleanupRegistered.delete(senderId) - clearVisiblePRRefreshWindow(senderId) - }) + const lifetime = abortWhenRendererGone(event.sender) + lifetime.signal.addEventListener( + 'abort', + () => { + visibilityCleanupRegistered.delete(senderId) + clearVisiblePRRefreshWindow(senderId) + }, + { once: true } + ) } const candidates: GitHubPRRefreshCandidate[] = [] const repos = store.getRepos() diff --git a/src/main/ipc/github-pr-refresh-routing.test.ts b/src/main/ipc/github-pr-refresh-routing.test.ts index 145874e8a4f..93fbd4c00d3 100644 --- a/src/main/ipc/github-pr-refresh-routing.test.ts +++ b/src/main/ipc/github-pr-refresh-routing.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = await vi.hoisted(async () => { @@ -125,7 +126,7 @@ describe('registerGitHubHandlers', () => { expect( handlers['gh:reportVisiblePRRefreshCandidates']( - { sender: { id: 7, once: vi.fn() } }, + { sender: Object.assign(new EventEmitter(), { id: 7 }) }, { generation: 1, candidates: [ @@ -165,7 +166,7 @@ describe('registerGitHubHandlers', () => { registerGitHubHandlers(store as never, stats as never) await handlers['gh:reportVisiblePRRefreshCandidates']( - { sender: { id: 8, once: vi.fn() } }, + { sender: Object.assign(new EventEmitter(), { id: 8 }) }, { generation: 2, candidates: [ diff --git a/src/main/ipc/github-wsl-runtime-routing.test.ts b/src/main/ipc/github-wsl-runtime-routing.test.ts index 977422cb68e..7660af8743c 100644 --- a/src/main/ipc/github-wsl-runtime-routing.test.ts +++ b/src/main/ipc/github-wsl-runtime-routing.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = await vi.hoisted(async () => { @@ -87,7 +88,7 @@ describe('registerGitHubHandlers', () => { branch: 'feature/wsl' }) await handlers['gh:reportVisiblePRRefreshCandidates']( - { sender: { id: 7, once: vi.fn() } }, + { sender: Object.assign(new EventEmitter(), { id: 7 }) }, { generation: 1, candidates: [ diff --git a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts index 64296ccb068..d9952694bee 100644 --- a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts @@ -3,6 +3,7 @@ import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../share import { isFolderRepo } from '../../../shared/repo-kind' import { hasHooksFile, loadHooks, hasUnrecognizedOrcaYamlKeys } from '../../hooks' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' +import { blockedWslDistroForPath } from '../../wsl/wsl-unc-access-gate' import type { WorktreeIpcContext } from '../worktrees/worktree-ipc-context' export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): void { @@ -10,7 +11,7 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v ipcMain.handle( 'hooks:check', - async (_event, args: { repoId: string; hostId?: ExecutionHostId }) => { + async (_event, args: { repoId: string; hostId?: ExecutionHostId; background?: boolean }) => { const repo = resolveRepoForExecutionHost(store, args.repoId, args.hostId) if (!repo) { const repoIdExists = store.getRepos().some((candidate) => candidate.id === args.repoId) @@ -35,6 +36,19 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v } } + // A render-driven check must not open a stopped distro's `\\wsl.localhost` paths (E9). + const blocked = args.background ? await blockedWslDistroForPath(repo.path) : null + if (blocked) { + return { + status: 'error', + hasHooks: false, + hooks: null, + mayNeedUpdate: false, + // A stopped distro answers once it runs again; an unverifiable one is worth a retry. + ...(blocked.state === 'stopped' ? { unavailable: 'wsl-distro-stopped' as const } : {}) + } + } + const has = hasHooksFile(repo.path) const hooks = has ? loadHooks(repo.path) : null // Well-formed unknown keys may come from a newer Orca; suggest updating instead of parse repair. diff --git a/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts b/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts index 12ebcd751e7..83ba23498f3 100644 --- a/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts @@ -4,6 +4,7 @@ import { isFolderRepo } from '../../../shared/repo-kind' import { inspectSetupScriptImportCandidates } from '../../../shared/setup-script-imports' import { joinWorktreeRelativePath } from '../../runtime/runtime-relative-paths' import { windowsFsPath } from '../../wsl/wsl-unc-drive-fs-path' +import { blockedWslDistroForPath } from '../../wsl/wsl-unc-access-gate' import { readFile, stat } from 'node:fs/promises' import { isENOENT } from '../filesystem/filesystem-path-containment' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' @@ -20,6 +21,10 @@ export function registerWorktreeHookInspectionHandler(context: WorktreeIpcContex if (!repo || isFolderRepo(repo) || getRepoDialableSshTargetId(repo)) { return [] } + // A background sidebar inspection: opening `\\wsl.localhost` paths would boot a stopped distro (E9). + if (await blockedWslDistroForPath(repo.path)) { + return [] + } return inspectSetupScriptImportCandidates( async (relativePath) => { diff --git a/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts b/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts new file mode 100644 index 00000000000..761d2ff6a08 --- /dev/null +++ b/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts @@ -0,0 +1,77 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../shared/repo-types' + +const mocks = vi.hoisted(() => ({ + handlers: new Map unknown>(), + hasHooksFile: vi.fn((_path: string) => false), + blocked: + vi.fn<(path: string) => Promise<{ distro: string; state: 'stopped' | 'unverifiable' } | null>>() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) => + mocks.handlers.set(channel, handler) + } +})) +vi.mock('../../hooks', () => ({ + hasHooksFile: mocks.hasHooksFile, + loadHooks: () => null, + hasUnrecognizedOrcaYamlKeys: () => false +})) +vi.mock('../../wsl/wsl-unc-access-gate', () => ({ blockedWslDistroForPath: mocks.blocked })) + +import { registerWorktreeHookCheckHandler } from './register-worktree-hook-check-handler' + +const UNC = String.raw`\\wsl.localhost\Ubuntu\home\u\app` + +function check(args: { background?: boolean }) { + const repo: Partial = { id: 'repo', path: UNC, kind: 'git', executionHostId: 'local' } + const store = { getRepos: () => [repo], getRepo: () => repo } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The handler reads only these store accessors. + registerWorktreeHookCheckHandler({ store } as never) + return mocks.handlers.get('hooks:check')!(null, { repoId: 'repo', ...args }) +} + +describe('hooks:check on a stopped WSL distro', () => { + beforeEach(() => { + mocks.hasHooksFile.mockClear() + mocks.blocked.mockReset() + mocks.blocked.mockResolvedValue({ distro: 'Ubuntu', state: 'stopped' }) + }) + + it('refuses a background check without opening orca.yaml, so it cannot boot the distro', async () => { + await expect(check({ background: true })).resolves.toEqual({ + status: 'error', + hasHooks: false, + hooks: null, + mayNeedUpdate: false, + unavailable: 'wsl-distro-stopped' + }) + expect(mocks.blocked).toHaveBeenCalledWith(UNC) + expect(mocks.hasHooksFile).not.toHaveBeenCalled() + }) + + it('leaves an unverifiable distro a plain error, which a retry may clear', async () => { + mocks.blocked.mockResolvedValue({ distro: 'Ubuntu', state: 'unverifiable' }) + + const result = await check({ background: true }) + + expect(result).toMatchObject({ status: 'error' }) + expect(result).not.toHaveProperty('unavailable') + expect(mocks.hasHooksFile).not.toHaveBeenCalled() + }) + + it('still reads for a launch, which is a user act that starts the distro anyway', async () => { + await expect(check({})).resolves.toMatchObject({ status: 'ok' }) + expect(mocks.blocked).not.toHaveBeenCalled() + expect(mocks.hasHooksFile).toHaveBeenCalledWith(UNC) + }) + + it('reads a running distro for a background check as before', async () => { + mocks.blocked.mockResolvedValue(null) + + await expect(check({ background: true })).resolves.toMatchObject({ status: 'ok' }) + expect(mocks.hasHooksFile).toHaveBeenCalledWith(UNC) + }) +}) diff --git a/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts b/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts index 54715d93fe6..1b24db302bb 100644 --- a/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts +++ b/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts @@ -4,8 +4,10 @@ import type { Repo } from '../../../shared/repo-types' const mocks = vi.hoisted(() => ({ handlers: new Map unknown>(), readFile: vi.fn(), - stat: vi.fn() + stat: vi.fn(), + blocked: vi.fn<(path: string) => Promise<{ distro: string; state: 'stopped' } | null>>() })) +vi.mock('../../wsl/wsl-unc-access-gate', () => ({ blockedWslDistroForPath: mocks.blocked })) vi.mock('electron', () => ({ ipcMain: { @@ -34,6 +36,7 @@ function enoent(path: string): Error { describe('setup script import inspection of a UNC drive-mount project', () => { beforeEach(() => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + mocks.blocked.mockResolvedValue(null) // WSL 2.7 refuses Windows access to a drive mount over UNC; the drive path opens. mocks.readFile.mockImplementation(async (path: string) => { if (path.startsWith('\\\\')) { @@ -70,4 +73,23 @@ describe('setup script import inspection of a UNC drive-mount project', () => { expect(mocks.readFile).not.toHaveBeenCalledWith(expect.stringMatching(/^\\\\/), 'utf-8') expect(warn).not.toHaveBeenCalled() }) + + it('opens nothing in a stopped distro, so a background inspection cannot boot it (E9)', async () => { + mocks.readFile.mockClear() + mocks.stat.mockClear() + mocks.blocked.mockResolvedValue({ distro: 'Ubuntu', state: 'stopped' }) + const repo: Partial = { id: 'repo', path: UNC, kind: 'git', executionHostId: 'local' } + const store = { getRepos: () => [repo], getRepo: () => repo } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The handler reads only these store accessors. + registerWorktreeHookInspectionHandler({ store } as never) + + const candidates = await mocks.handlers.get('hooks:inspectSetupScriptImports')!(null, { + repoId: 'repo' + }) + + expect(candidates).toEqual([]) + expect(mocks.blocked).toHaveBeenCalledWith(UNC) + expect(mocks.readFile).not.toHaveBeenCalled() + expect(mocks.stat).not.toHaveBeenCalled() + }) }) diff --git a/src/main/ipc/local-file-access-resolution.ts b/src/main/ipc/local-file-access-resolution.ts index 910503de3f5..c9a8090baa5 100644 --- a/src/main/ipc/local-file-access-resolution.ts +++ b/src/main/ipc/local-file-access-resolution.ts @@ -1,4 +1,4 @@ -import { dirname, extname, isAbsolute, resolve } from 'node:path' +import { dirname, isAbsolute, resolve } from 'node:path' import { stat } from 'node:fs/promises' import type { Store } from '../persistence' import type { LocalFileAccess } from '../../shared/local-file-access' @@ -8,7 +8,7 @@ import { type ResolveAuthorizedPathOptions } from './filesystem/filesystem-auth' import { isDescendantOrEqual } from './filesystem/filesystem-path-containment' -import { PREVIEWABLE_BINARY_MIME_TYPES } from './filesystem/filesystem-file-content-inspection' +import { filePreviewForPath } from '../../shared/file-preview-kind' import { getDefaultFloatingWorkspacePath } from './floating-workspace-directory' import { isDeviceNamespacePath, @@ -58,8 +58,7 @@ export async function resolveUserNamedRegularFile( // Chat uses img rendering; PDF previews need a different surface. function isChatImage(filePath: string): boolean { - const extension = extname(filePath).toLowerCase() - return Boolean(PREVIEWABLE_BINARY_MIME_TYPES[extension]) && extension !== '.pdf' + return filePreviewForPath(filePath)?.kind === 'image' } // Resolve path text first because devices can hide behind dot and parent segments. diff --git a/src/main/ipc/plugins-panel-document-lifetime.test.ts b/src/main/ipc/plugins-panel-document-lifetime.test.ts new file mode 100644 index 00000000000..8646cc6790a --- /dev/null +++ b/src/main/ipc/plugins-panel-document-lifetime.test.ts @@ -0,0 +1,207 @@ +import { EventEmitter } from 'node:events' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { pluginManifestSchema } from '../../shared/plugins/plugin-manifest' +import { panelSessionTokenSchema } from '../../shared/plugins/plugin-panel-bridge' +import type { Store } from '../persistence' +import { PluginContentVerifier } from '../plugins/plugin-content-integrity' +import type { ValidDiscoveredPlugin } from '../plugins/plugin-discovery' +import { PluginPanelController } from '../plugins/plugin-panel-controller' +import { PluginPanelSessions } from '../plugins/plugin-panel-sessions' +import type { PluginService } from '../plugins/plugin-service' + +const mocks = vi.hoisted(() => ({ + handlers: new Map Promise>() +})) +vi.mock('electron', () => ({ + ipcMain: { + handle: (name: string, handler: (event: unknown, args: unknown) => Promise) => + mocks.handlers.set(name, handler) + } +})) + +const { registerPluginHandlers } = await import('./plugins') +const roots: string[] = [] +const controllers: PluginPanelController[] = [] +const senders: EventEmitter[] = [] +const PREDECESSOR = 'orca-samples.predecessor' +const SUCCESSOR = 'orca-samples.successor' +const entrySchema = z.object({ html: z.string(), sessionToken: panelSessionTokenSchema }) + +beforeEach(() => mocks.handlers.clear()) +afterEach(async () => { + for (const sender of senders.splice(0)) { + sender.emit('destroyed') + } + for (const controller of controllers.splice(0)) { + controller.dispose() + } + vi.restoreAllMocks() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +async function plugin(id: string): Promise { + const rootDir = await mkdtemp(join(tmpdir(), 'orca-panel-document-')) + roots.push(rootDir) + await writeFile(join(rootDir, 'panel.html'), `

${id}

`) + return { + pluginKey: `orca-samples.${id}`, + rootDir, + contentHash: null, + consentFingerprint: 'approved', + isDev: true, + manifest: pluginManifestSchema.parse({ + manifestVersion: 1, + id, + publisher: 'orca-samples', + name: id, + version: '1.0.0', + engines: { orca: '>=1.0.0' }, + pluginApi: 1, + contributes: { panels: [{ id: 'panel', title: id, entry: 'panel.html' }] }, + capabilities: [{ kind: 'notifications:show' }] + }) + } +} + +async function harness( + options: { + beforeVerify?: (plugin: ValidDiscoveredPlugin) => Promise + whenReady?: () => Promise + } = {} +) { + const plugins = new Map( + (await Promise.all([plugin('predecessor'), plugin('successor')])).map((entry) => [ + entry.pluginKey, + entry + ]) + ) + const verifier = new PluginContentVerifier() + const verified: string[] = [] + const panels = new PluginPanelController({ + resolveApprovedPlugin: (key) => plugins.get(key) ?? null, + contentVerifier: { + verify: async (entry) => { + verified.push(entry.pluginKey) + const discovered = plugins.get(entry.pluginKey) + if (!discovered) { + throw new Error('Missing approved plugin') + } + await options.beforeVerify?.(discovered) + await verifier.verify(entry) + } + }, + executeHostCall: async (pluginKey) => ({ ok: true, value: { pluginKey } }), + log: () => () => {} + }) + controllers.push(panels) + const service = { panels, whenReady: options.whenReady ?? (async () => {}) } + registerPluginHandlers( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration uses this store only to subscribe to settings updates. + { onSettingsChanged: () => () => {} } as unknown as Store, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: panel handlers consume real controller and readiness members only. + service as unknown as PluginService, + null + ) + return { verified } +} + +function sender(id = 1) { + const contents = Object.assign(new EventEmitter(), { id }) + senders.push(contents) + return contents +} + +function invoke(name: string, contents: ReturnType, args: unknown) { + const handler = mocks.handlers.get(`plugins:${name}`) + if (!handler) { + throw new Error(`Missing handler ${name}`) + } + return handler({ sender: contents }, args) +} + +function open(contents: ReturnType, pluginKey = SUCCESSOR) { + return invoke('readPanelEntry', contents, { pluginKey, panelId: 'panel' }) +} + +function action(contents: ReturnType, sessionToken: string) { + return invoke('panelAction', contents, { + sessionToken, + action: 'notifications.show', + params: { title: 'Live panel' } + }) +} + +describe('plugin panel document ownership', () => { + it('preserves successor and sibling authority when a crashed document finishes loading late', async () => { + const entered = Promise.withResolvers() + const blocked = Promise.withResolvers() + await harness({ + beforeVerify: async (entry) => { + if (entry.pluginKey === PREDECESSOR) { + entered.resolve() + await blocked.promise + } + } + }) + const current = sender() + const oldRequest = open(current, PREDECESSOR) + await entered.promise + current.emit('render-process-gone') + const successor = entrySchema.parse(await open(current)) + const other = sender(2) + const sibling = entrySchema.parse(await open(other)) + await expect(action(current, successor.sessionToken)).resolves.toMatchObject({ ok: true }) + blocked.resolve() + await expect(oldRequest).resolves.toBeNull() + await expect(action(current, successor.sessionToken)).resolves.toEqual({ + ok: true, + value: { pluginKey: SUCCESSOR } + }) + await expect(action(other, sibling.sessionToken)).resolves.toMatchObject({ ok: true }) + expect(entrySchema.parse(await open(current)).sessionToken).toBe(successor.sessionToken) + current.emit('destroyed') + await expect(action(current, successor.sessionToken)).resolves.toMatchObject({ + ok: false, + code: 'invalid_request' + }) + await expect(action(other, sibling.sessionToken)).resolves.toMatchObject({ ok: true }) + expect(current.eventNames()).toEqual([]) + }) + + it('skips loading a request retired while plugin discovery is pending', async () => { + const ready = Promise.withResolvers() + const { verified } = await harness({ whenReady: () => ready.promise }) + const current = sender() + const pending = open(current, PREDECESSOR) + current.emit('render-process-gone') + ready.resolve() + await expect(pending).resolves.toBeNull() + expect(verified).toEqual([]) + const successor = entrySchema.parse(await open(current)) + await expect(action(current, successor.sessionToken)).resolves.toMatchObject({ ok: true }) + }) + + it('does not issue a panel session after native owner destruction during a load', async () => { + const entered = Promise.withResolvers() + const blocked = Promise.withResolvers() + await harness({ + beforeVerify: async () => { + entered.resolve() + await blocked.promise + } + }) + const issue = vi.spyOn(PluginPanelSessions.prototype, 'issue') + const current = sender() + const pending = open(current) + await entered.promise + current.emit('destroyed') + blocked.resolve() + await expect(pending).resolves.toBeNull() + expect(issue).not.toHaveBeenCalled() + expect(current.eventNames()).toEqual([]) + }) +}) diff --git a/src/main/ipc/plugins.ts b/src/main/ipc/plugins.ts index 166f9ed46a2..1799cde774f 100644 --- a/src/main/ipc/plugins.ts +++ b/src/main/ipc/plugins.ts @@ -148,12 +148,12 @@ export function registerPluginHandlers( ) await pluginService.whenReady() const parsed = readPanelEntryArgsSchema.parse(args) - const entry = await pluginService.panels.open(ownerKey, parsed.pluginKey, parsed.panelId) - if (!ownerLease.isCurrent()) { - pluginService.panels.revokeOwner(ownerKey) - return null - } - return entry + return pluginService.panels.open( + ownerKey, + parsed.pluginKey, + parsed.panelId, + ownerLease.isCurrent + ) } ) diff --git a/src/main/ipc/pty/host-env/remote-viewer-clipboard-env.ts b/src/main/ipc/pty/host-env/remote-viewer-clipboard-env.ts index 072b0cfc308..71a96380f39 100644 --- a/src/main/ipc/pty/host-env/remote-viewer-clipboard-env.ts +++ b/src/main/ipc/pty/host-env/remote-viewer-clipboard-env.ts @@ -1,7 +1,9 @@ import type { TuiAgent } from '../../../../shared/tui-agent' - -/** Codex v0.162.1 emits OSC 52 under SSH/TMUX; a valid SSH_CONNECTION avoids tmux subprocess/passthrough and SSH_TTY device semantics. */ -export const CODEX_REMOTE_VIEWER_SSH_CONNECTION = '127.0.0.1 0 127.0.0.1 0' +import { + CODEX_REMOTE_VIEWER_SSH_CONNECTION, + REMOTE_VIEWER_CLIPBOARD_ENV +} from '../../../../shared/remote-viewer-clipboard-env' +export { CODEX_REMOTE_VIEWER_SSH_CONNECTION } /** Pi's own opt-in to emit OSC 52 alongside its host clipboard write; inert for every other program. */ export const PI_CLIPBOARD_OSC52_ENV = 'PI_CLIPBOARD_OSC52' @@ -18,6 +20,7 @@ export function applyRemoteViewerClipboardEnv( if (!options.viewerIsRemote) { return } + env[REMOTE_VIEWER_CLIPBOARD_ENV] = '1' const inherited = options.inheritedEnv ?? process.env // Daemons merge their inherited environment after assembly; respect existing values there too. const isSet = (key: string): boolean => env[key] !== undefined || inherited[key] !== undefined diff --git a/src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts b/src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts index 6d69400bd01..956e9a5246e 100644 --- a/src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts +++ b/src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts @@ -60,6 +60,20 @@ describe('assertWorkspaceAcceptsNewPty under a WSL move', () => { }) }) +// A moved project's chat, or an agent in it, asking for a terminal here after the move committed. +describe('a fresh terminal in a project its WSL host now owns', () => { + beforeEach(() => { + seedWslMoveCutover(userDataPath, cutover('move-1', 'destination-committed')) + }) + + it('refuses, naming the host instead of a move that already finished', async () => { + const refusal = await accept('repo-1::/x').catch((error: unknown) => error) + expect(refusal).toBeInstanceOf(WslMoveProjectFencedError) + expect(String(refusal)).toContain('now runs on its Ubuntu WSL host') + expect(String(refusal)).not.toContain('Try again when the move finishes') + }) +}) + // R46: a terminal the workspace fence misses would otherwise outlive the commit in a moved folder. describe('a spawn by its folder, between quiesce and commit', () => { beforeEach(() => { diff --git a/src/main/ipc/pty/host-env/spawn-cwd.ts b/src/main/ipc/pty/host-env/spawn-cwd.ts index 37b8229eb20..90649272d7c 100644 --- a/src/main/ipc/pty/host-env/spawn-cwd.ts +++ b/src/main/ipc/pty/host-env/spawn-cwd.ts @@ -13,6 +13,8 @@ import { import { isWslMoveCwdFenced, isWslMoveWorkspaceBlocked, + wslMoveHostDistro, + wslMoveProjectRefForWorkspace, WslMoveProjectFencedError } from '../../../persistence/moving-wsl-projects/wsl-move-scope-guard' import { listLiveDaemonPtyIds } from '../../../daemon/daemon-provider-state' @@ -31,7 +33,7 @@ export function assertWorkspaceAcceptsNewPty( ): Promise | void { const fencedByCwd = !!cwd && isWslMoveCwdFenced(cwd) if (fencedByCwd || isWslMoveWorkspaceBlocked(store, worktreeId)) { - return assertReattachesLiveSession(sessionId).then(() => + return assertReattachesLiveSession(sessionId, worktreeId).then(() => assertFolderWorkspacePtyPathUsable(store, worktreeId) ) } @@ -46,11 +48,17 @@ export function localPtySpawnCwd(args: { return args.connectionId ? undefined : args.cwd } -async function assertReattachesLiveSession(sessionId: string | undefined): Promise { +async function assertReattachesLiveSession( + sessionId: string | undefined, + worktreeId: string | undefined +): Promise { // An unanswered census is never proof the session lives, so it refuses. const live = sessionId ? await listLiveDaemonPtyIds() : null if (!sessionId || !live?.includes(sessionId)) { - throw new WslMoveProjectFencedError() + // A committed move's project names its host: "try again when the move finishes" never comes true. + throw new WslMoveProjectFencedError( + worktreeId ? wslMoveHostDistro(wslMoveProjectRefForWorkspace(worktreeId)) : null + ) } } diff --git a/src/main/ipc/pty/ipc/write-input-user-input.test.ts b/src/main/ipc/pty/ipc/write-input-user-input.test.ts index 02356f64ca8..4e80eb17ea7 100644 --- a/src/main/ipc/pty/ipc/write-input-user-input.test.ts +++ b/src/main/ipc/pty/ipc/write-input-user-input.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { TerminalRunFactsRegister } from '../../../runtime/terminal-run-facts' import { ptyOwnership } from '../provider/ownership-state' import { createPtyWriteInput } from './write-input' +import * as inputAdmission from '../../../runtime/terminal-input-admission' import { WRITE_ACCEPTED, writeRefused, @@ -46,10 +47,24 @@ beforeEach(() => { }) afterEach(() => { + vi.restoreAllMocks() ptyOwnership.delete(PTY_ID) }) describe('renderer PTY writes: input kind', () => { + it.each(['writePtyInput', 'writePtyInputAccepted'] as const)( + '%s forwards desktop provenance to shared admission', + async (writer) => { + const policy = vi.spyOn(inputAdmission, 'isTerminalInputPaused') + await createWriteInput(new TerminalRunFactsRegister())[writer]({ + id: PTY_ID, + data: 'keys', + inputKind: 'driving' + }) + expect(policy).toHaveBeenCalledWith(expect.anything(), PTY_ID, 'desktop') + } + ) + it.each(['local', 'ssh:ssh-connection'] as const)( 'observes a settled write only after acceptance on the execution host (%s)', async (owner) => { diff --git a/src/main/ipc/pty/ipc/write-input.ts b/src/main/ipc/pty/ipc/write-input.ts index 5567feff612..0aa45f36649 100644 --- a/src/main/ipc/pty/ipc/write-input.ts +++ b/src/main/ipc/pty/ipc/write-input.ts @@ -1,3 +1,4 @@ +import { isTerminalInputPaused } from '../../../runtime/terminal-input-admission' import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron' import type { PtyRendererDelivery } from '../session' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' @@ -68,10 +69,14 @@ export function createPtyWriteInput(deps: { const writePtyProviderInputWithinLimit = ( provider: IPtyProvider, - id: string, - data: string, + args: PtyWritePayload, verify = false ): boolean | Promise => { + const { id, data } = args + if (runtime && isTerminalInputPaused(runtime, id, 'desktop')) { + return false + } + noteRendererPtyInput(args) const chunks = iterateTerminalInputChunks(data) const first = chunks.next() if (first.done) { @@ -121,21 +126,21 @@ export function createPtyWriteInput(deps: { const writePtyProviderInput = ( provider: IPtyProvider, - id: string, - data: string, + args: PtyWritePayload, verify = false ): boolean | Promise => { + const { id, data } = args try { const tooLarge = isTerminalInputTooLargeWithDeferredMeasurement(data) if (typeof tooLarge === 'boolean') { - return tooLarge ? false : writePtyProviderInputWithinLimit(provider, id, data, verify) + return tooLarge ? false : writePtyProviderInputWithinLimit(provider, args, verify) } return tooLarge .then((result) => { if (result) { return false } - return writePtyProviderInputWithinLimit(provider, id, data, verify) + return writePtyProviderInputWithinLimit(provider, args, verify) }) .catch((error) => { return failedWrite(id, error, verify) @@ -224,21 +229,16 @@ export function createPtyWriteInput(deps: { } return accepted } - const result = writePtyProviderInput(provider, args.id, args.data, verify) + const result = writePtyProviderInput(provider, args, verify) return typeof result === 'boolean' ? observe(result) : result.then(observe) } const writePtyInput = (args: PtyWritePayload): boolean | Promise => { - // Enforce phone-owned input in main too; renderer presence state lags by one IPC hop (docs/mobile-presence-lock.md). - if (runtime?.getDriver(args.id).kind === 'mobile') { - return false - } const provider = ptyOwnership.has(args.id) ? tryGetProviderForPty(args.id) : undefined if (!provider) { return false } try { - noteRendererPtyInput(args) return writeAndObserveInput(provider, args) } catch { return false @@ -253,14 +253,10 @@ export function createPtyWriteInput(deps: { if (!provider?.hasPty?.(args.id)) { return false } - noteRendererPtyInput(args) return writeAndObserveInput(provider, args, true) } const writePtyInputAccepted = (args: PtyWritePayload): boolean | Promise => { - if (runtime?.getDriver(args.id).kind === 'mobile') { - return false - } if (args.requireWriteSettlement === true) { return writePtyInputSettled(args) } @@ -273,7 +269,6 @@ export function createPtyWriteInput(deps: { return false } try { - noteRendererPtyInput(args) return writeAndObserveInput(provider, args) } catch { return false diff --git a/src/main/ipc/pty/pane/complete-pane-adoption.ts b/src/main/ipc/pty/pane/complete-pane-adoption.ts index 882a9785267..65c8fc108b3 100644 --- a/src/main/ipc/pty/pane/complete-pane-adoption.ts +++ b/src/main/ipc/pty/pane/complete-pane-adoption.ts @@ -17,6 +17,7 @@ import { import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore' import { admitProviderReattachLaunchIdentity } from './launch-authority' import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-hook-relay-reattach' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' import { provenSpawnResponse } from '../spawn-outcome' import { ptySizes } from '../delivery/visibility-state' import { @@ -77,6 +78,9 @@ export async function completePaneAdoption( ) : undefined ensureWslHookRelayForReattach(result, args.connectionId) + if (result.wslDistro && !args.connectionId) { + wslBridgePtyPresence.noteLive(result.id, result.wslDistro) + } runtime?.preparePtyExecutionContext?.(result.id, result.wslDistro ?? null, { preserveExisting: result.wslDistro === undefined }) diff --git a/src/main/ipc/pty/pane/serializer-document-lifetime.test.ts b/src/main/ipc/pty/pane/serializer-document-lifetime.test.ts new file mode 100644 index 00000000000..5953fb7cba1 --- /dev/null +++ b/src/main/ipc/pty/pane/serializer-document-lifetime.test.ts @@ -0,0 +1,104 @@ +import { EventEmitter } from 'node:events' +import type { WebContents } from 'electron' +import { Terminal } from '@xterm/headless' +import { afterEach, describe, expect, it } from 'vitest' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { + declarePendingPaneSerializer, + hasPendingRendererSerializerForPaneKey, + settlePendingPaneSerializer +} from './serializer-state' +import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore' + +let nextSenderId = 1000 +const senders: EventEmitter[] = [] + +function sender() { + const events = Object.assign(new EventEmitter(), { + id: nextSenderId++, + isDestroyed: () => false + }) + senders.push(events) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: serializer ownership uses only id, isDestroyed and EventEmitter lifecycle methods. + return { events, contents: events as unknown as WebContents } +} + +const paneKey = makePaneKey('tab-document', '33333333-3333-4333-8333-333333333333') + +afterEach(() => { + for (const events of senders.splice(0)) { + events.emit('destroyed') + } +}) + +describe('pending pane serializer document ownership', () => { + it.each(['render-process-gone', 'did-navigate'] as const)( + 'restores provider history when a pending reattach completes after %s', + async (event) => { + const owner = sender() + const generation = declarePendingPaneSerializer(paneKey, owner.contents) + expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(true) + owner.events.emit(event) + + const terminal = new Terminal({ cols: 40, rows: 6, scrollback: 100, allowProposedApi: true }) + let writes = Promise.resolve() + const seedHeadlessTerminal = (_id: string, data: string): void => { + writes = writes.then(() => new Promise((resolve) => terminal.write(data, resolve))) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: provider-history seeding reads only seedHeadlessTerminal from this runtime seam. + const runtime = { seedHeadlessTerminal } as unknown as OrcaRuntimeService + try { + seedHeadlessTerminalFromSpawnResult( + runtime, + { id: 'reattached-pty', isReattach: true, snapshot: 'retained history\r\n' }, + paneKey + ) + await writes + await new Promise((resolve) => terminal.write('live suffix\r\n', resolve)) + const lines = Array.from( + { length: terminal.buffer.active.length }, + (_, index) => terminal.buffer.active.getLine(index)?.translateToString(true) ?? '' + ) + expect(lines).toEqual(['retained history', 'live suffix', '', '', '', '']) + expect(terminal.buffer.active.cursorX).toBe(0) + expect(terminal.buffer.active.cursorY).toBe(2) + expect(settlePendingPaneSerializer(paneKey, generation)).toBe(false) + } finally { + terminal.dispose() + } + } + ) + + it('preserves an active claim across same-document navigation and ignores old settlement', () => { + const owner = sender() + const first = declarePendingPaneSerializer(paneKey, owner.contents) + owner.events.emit('did-navigate-in-page') + expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(true) + owner.events.emit('render-process-gone') + const replacement = declarePendingPaneSerializer(paneKey, owner.contents) + expect(settlePendingPaneSerializer(paneKey, first)).toBe(false) + expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(true) + expect(settlePendingPaneSerializer(paneKey, replacement)).toBe(true) + }) + + it('preserves another window owner and registers one listener per document', () => { + const first = sender() + const second = sender() + const firstPane = makePaneKey('first', '44444444-4444-4444-8444-444444444444') + const secondPane = makePaneKey('second', '55555555-5555-4555-8555-555555555555') + declarePendingPaneSerializer(firstPane, first.contents) + declarePendingPaneSerializer(paneKey, first.contents) + declarePendingPaneSerializer(secondPane, second.contents) + expect(first.events.listenerCount('render-process-gone')).toBe(1) + first.events.emit('render-process-gone') + expect(hasPendingRendererSerializerForPaneKey(firstPane)).toBe(false) + expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(false) + expect(hasPendingRendererSerializerForPaneKey(secondPane)).toBe(true) + expect(first.events.eventNames()).toEqual([]) + declarePendingPaneSerializer(firstPane, first.contents) + expect(first.events.listenerCount('render-process-gone')).toBe(1) + first.events.emit('did-navigate') + expect(hasPendingRendererSerializerForPaneKey(firstPane)).toBe(false) + }) +}) diff --git a/src/main/ipc/pty/pane/serializer-state.ts b/src/main/ipc/pty/pane/serializer-state.ts index 2ca4683bbdc..adea799a961 100644 --- a/src/main/ipc/pty/pane/serializer-state.ts +++ b/src/main/ipc/pty/pane/serializer-state.ts @@ -1,4 +1,5 @@ import type { WebContents } from 'electron' +import { abortWhenRendererGone } from '../../renderer-lifetime-abort' import { RendererTerminalSerializerReadiness } from '../../renderer-terminal-serializer-readiness' import { isValidPaneKey, paneKeyPtyId } from './key-state' @@ -29,7 +30,14 @@ export function registerPendingPaneSerializerCleanup(sender: WebContents | undef return } pendingPaneSerializerCleanupRegistered.add(sender.id) - sender.once('destroyed', () => cleanupPendingPaneSerializersForSender(sender.id)) + const lifetime = abortWhenRendererGone(sender) + lifetime.signal.addEventListener( + 'abort', + () => cleanupPendingPaneSerializersForSender(sender.id), + { + once: true + } + ) } export function declarePendingPaneSerializer( diff --git a/src/main/ipc/pty/provider/bind-listeners.ts b/src/main/ipc/pty/provider/bind-listeners.ts index e217a40c970..7cd8478e298 100644 --- a/src/main/ipc/pty/provider/bind-listeners.ts +++ b/src/main/ipc/pty/provider/bind-listeners.ts @@ -1,4 +1,5 @@ import { isCurrentPtyExit, ptyOwnership } from './ownership-state' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' import { localBackgroundStreamUnsub, localDataUnsub, @@ -86,6 +87,8 @@ export function bindProviderListeners(session: PtyIpcSession): void { if (!isCurrentPtyExit(payload)) { return } + // Its distro's hook relay may idle out once no bridge terminal remains. + wslBridgePtyPresence.noteExited(payload.id) const syntheticExit = session.consumeSyntheticKillExit(payload.id, payload.incarnationId) // Daemon restart replaces processes while their panes survive. const settleRestartStop = payload.replacedByRestart diff --git a/src/main/ipc/pty/pty-daemon-spawn-wsl-runtime.test.ts b/src/main/ipc/pty/pty-daemon-spawn-wsl-runtime.test.ts index 2de9bee161e..a1496e06aca 100644 --- a/src/main/ipc/pty/pty-daemon-spawn-wsl-runtime.test.ts +++ b/src/main/ipc/pty/pty-daemon-spawn-wsl-runtime.test.ts @@ -593,6 +593,13 @@ describe('registerPtyHandlers', () => { expect(env.GIT_CONFIG_KEY_0).toBe('http.proxy') expect(env.GIT_CONFIG_KEY_1).toBeUndefined() }) + it('forwards the sequenced setup script into WSLENV before the daemon boundary', async () => { + const env = await withWin32Platform(() => + daemonSpawnAndGetEnv({ ORCA_SEQUENCED_SETUP_SCRIPT: 'true', WSLENV: 'EXISTING/p' }) + ) + + expect(env.WSLENV).toBe('EXISTING/p:ORCA_SEQUENCED_SETUP_SCRIPT') + }) }) }) }) diff --git a/src/main/ipc/pty/pty-serializer-settlement-mapping.test.ts b/src/main/ipc/pty/pty-serializer-settlement-mapping.test.ts index 988716f5fc6..30d8111d7ef 100644 --- a/src/main/ipc/pty/pty-serializer-settlement-mapping.test.ts +++ b/src/main/ipc/pty/pty-serializer-settlement-mapping.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { EventEmitter } from 'node:events' import { spawnMock } from './pty-ipc-mock-registry' import { setupPtyIpcSuite } from './pty-ipc-test-harness' import { makePaneKey } from '../../../shared/stable-pane-id' @@ -216,22 +217,16 @@ describe('registerPtyHandlers', () => { it('clears pending pane serializer declarations when their renderer is destroyed', async () => { registerPtyHandlers(mainWindow as never) const paneKey = makePaneKey('tab-crash', '22222222-2222-4222-8222-222222222222') - const destroyedListeners: (() => void)[] = [] - const sender = { + const sender = Object.assign(new EventEmitter(), { id: 42, - isDestroyed: () => false, - once: vi.fn((event: string, listener: () => void) => { - if (event === 'destroyed') { - destroyedListeners.push(listener) - } - }) - } + isDestroyed: () => false + }) await handlers.get('pty:declarePendingPaneSerializer')!({ sender }, { paneKey }) expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(true) - expect(destroyedListeners).toHaveLength(1) - destroyedListeners[0]() + expect(sender.listenerCount('destroyed')).toBe(1) + sender.emit('destroyed') expect(hasPendingRendererSerializerForPaneKey(paneKey)).toBe(false) }) it('does not retain a serializer declaration from an already-destroyed renderer', async () => { diff --git a/src/main/ipc/pty/pty-spawn-env-terminal-basics.test.ts b/src/main/ipc/pty/pty-spawn-env-terminal-basics.test.ts index 0b8ee99d744..47ddffb99fd 100644 --- a/src/main/ipc/pty/pty-spawn-env-terminal-basics.test.ts +++ b/src/main/ipc/pty/pty-spawn-env-terminal-basics.test.ts @@ -19,6 +19,7 @@ import { } from '../../../shared/jcode-runtime-dir' import { makePaneKey } from '../../../shared/stable-pane-id' import { selectShellStartupFeatures } from '../../shell-startup-features' +import { REMOTE_VIEWER_CLIPBOARD_ENV } from '../../../shared/remote-viewer-clipboard-env' import { CODEX_REMOTE_VIEWER_SSH_CONNECTION, PI_CLIPBOARD_OSC52_ENV @@ -299,8 +300,7 @@ describe('registerPtyHandlers', () => { } ) - // #33937: pi started by hand in a headless host's shell copied only to the host clipboard. - it('asks a hand-started pi for OSC 52 copies in a plain shell', () => { + it('installs clipboard forwarding for agents started by hand in a remote shell', () => { vi.stubEnv(PI_CLIPBOARD_OSC52_ENV, undefined) try { const env = buildPtyHostEnv( @@ -315,7 +315,17 @@ describe('registerPtyHandlers', () => { } ) expect(env[PI_CLIPBOARD_OSC52_ENV]).toBe('1') + expect(env[REMOTE_VIEWER_CLIPBOARD_ENV]).toBe('1') expect(env.SSH_CONNECTION).toBeUndefined() + expect( + selectShellStartupFeatures({ + shellPath: '/bin/bash', + env, + hasStartupCommand: false, + waitsForShellReady: false, + emitsStartupIdentity: false + }) + ).toContain('overlay') } finally { vi.unstubAllEnvs() } diff --git a/src/main/ipc/pty/spawn-execute.ts b/src/main/ipc/pty/spawn-execute.ts index 5782e8f7b67..0dd323a1f4c 100644 --- a/src/main/ipc/pty/spawn-execute.ts +++ b/src/main/ipc/pty/spawn-execute.ts @@ -25,6 +25,8 @@ import { failPtySpawnExecute } from './spawn-execute-failure' import type { PtySpawnOperationState, PtySpawnExecutionFacts } from './spawn-operation-state' import { excludeReplacedPaneOwner } from './pane/replaced-pane-owner' import { attachViewWithoutOwner } from './pane/attach-only-view' +import { wslBridgePtyPresence } from '../../agent-hooks/wsl-bridge-pty-presence' +import { shouldSkipCodexHomeEnvForWindowsShell as isWslTerminalSpawn } from './host-env/codex-home' export async function executePtySpawn( ctx: PtySpawnOperationState, @@ -248,6 +250,10 @@ export async function executePtySpawn( // A local WSL terminal is user-initiated, so background work held for this distro may run. noteWslDistroWoken(spawnedWslDistro) noteWslDistrosRunning([spawnedWslDistro]) + wslBridgePtyPresence.noteLive(ctx.result.id, spawnedWslDistro) + } else if (!args.connectionId && isWslBridgeSpawn(ctx.spawnOptions)) { + // A WSL shell whose distro the spawn didn't report runs in the default distro. + wslBridgePtyPresence.noteLive(ctx.result.id, null) } ctx.deps.runtime?.preparePtyExecutionContext?.(ctx.result.id, spawnedWslDistro) ctx.spawnTiming?.mark('provider_spawn') @@ -264,3 +270,7 @@ export async function executePtySpawn( } } } + +function isWslBridgeSpawn(options: { shellOverride?: string; cwd?: string | null }): boolean { + return isWslTerminalSpawn(options.shellOverride, options.cwd ?? undefined) +} diff --git a/src/main/ipc/pty/spawn-host-env.ts b/src/main/ipc/pty/spawn-host-env.ts index 655ac5daf2c..2d231d9a329 100644 --- a/src/main/ipc/pty/spawn-host-env.ts +++ b/src/main/ipc/pty/spawn-host-env.ts @@ -3,8 +3,10 @@ import type { AgentProviderSessionMetadata } from '../../../shared/agent-session import { getAppEnvironment } from '../../../shared/app-environment' import type { GlobalSettings } from '../../../shared/global-settings-types' import { stampRuntimeSourceEnv } from '../../../shared/runtime-source-env' +import { SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV } from '../../../shared/setup-agent-sequencing' import type { TuiAgent } from '../../../shared/tui-agent' import { isTuiAgent } from '../../../shared/tui-agent-config' +import { addWslEnvKeys } from '../../../shared/wsl-env' import { isAgentStatusHooksEnabled } from '../../agent-hooks/managed-agent-hook-controls' import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-agent-plugin-readiness' import { ensureCodexStateDbBackfillRecoveryStarted } from '../../codex/codex-state-db-backfill-recovery' @@ -245,6 +247,10 @@ export async function resolvePtySpawnHostEnv(args: PtySpawnHostEnvArgs): Promise getRuntimeSourceStamp(deps.runtime, getAppEnvironment().getPath('userData')) ) promoteAgentTeamsShimPath(env, args.requestedAgentTeamsPath) + if (process.platform === 'win32' && env[SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV]) { + // Why: same-protocol daemons from older builds don't add this WSLENV entry themselves. + addWslEnvKeys(env, [SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV]) + } } catch (err) { // Host prep creates hook/extension state; only this request's minted ID is safe to sweep. if (args.mintedSessionId) { diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 5dd0677ddfd..7952e55ef37 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -109,6 +109,7 @@ import { getAgentSessionAttachmentStore } from '../../native-chat/agent-session- import type { PluginService } from '../../plugins/plugin-service' import type { PluginMarketplaceHandlerServices } from '../plugin-marketplaces' import { settleWithinMs } from '../../quit-teardown-deadline' +import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/runtime-environment-registry-root' let registered = false // Same cap as the restart path's auth preservation: bookkeeping must not hold Restart on a stalled disk. @@ -269,7 +270,7 @@ export function registerCoreHandlers( ensureStructuredAgentSessionHostUnlessRefused(() => runtime.ensureStructuredAgentSessionHost()) registerAiVaultSearchHandlers({ callRuntimeSearch: (environmentId, method, params) => - callRuntimeSessionSearch(app.getPath('userData'), environmentId, method, params), + callRuntimeSessionSearch(getRuntimeEnvironmentRegistryRoot(), environmentId, method, params), ensureStructuredSessionOwnership }) registerAiVaultHandlers({ @@ -278,16 +279,16 @@ export function registerCoreHandlers( getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths, prepareSessionResume: lifecycleOptions.prepareAiVaultSessionResume, getActiveRuntimeAiVaultHostInfos: () => - getSavedRuntimeAiVaultHostInfos(app.getPath('userData')), + getSavedRuntimeAiVaultHostInfos(getRuntimeEnvironmentRegistryRoot()), scanRuntimeAiVaultSessions: async (environmentId, args, options) => - scanRuntimeAiVaultSessions(app.getPath('userData'), environmentId, args, options), + scanRuntimeAiVaultSessions(getRuntimeEnvironmentRegistryRoot(), environmentId, args, options), resolveRuntimeAiVaultSessionTitles: async (environmentId, args) => - resolveRuntimeAiVaultSessionTitles(app.getPath('userData'), environmentId, args), + resolveRuntimeAiVaultSessionTitles(getRuntimeEnvironmentRegistryRoot(), environmentId, args), prepareRuntimeSessionResume: async (environmentId, args) => - prepareRuntimeAiVaultSessionResume(app.getPath('userData'), environmentId, args) + prepareRuntimeAiVaultSessionResume(getRuntimeEnvironmentRegistryRoot(), environmentId, args) }) configureRuntimeAiVaultSessionDelete((environmentId, args) => - deleteRuntimeAiVaultSession(app.getPath('userData'), environmentId, args) + deleteRuntimeAiVaultSession(getRuntimeEnvironmentRegistryRoot(), environmentId, args) ) registerNativeChatHandlers() registerClipboardHandlers(store, { diff --git a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts b/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts index 19ac6c4257a..a01858708ea 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts @@ -1,4 +1,3 @@ -import { app } from 'electron' import { pairedRuntimeBrowserClientHostsPage } from '../../browser/paired-runtime-browser-client-host-runtime' import { listEnvironments } from '../../../shared/runtime-environment-store' import { @@ -30,6 +29,7 @@ import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-sub import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' import { onRuntimeEnvironmentStatusPublished } from './runtime-environment-status-owner' import { getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environment-registry-root' const retirementListeners = new Set<(environmentId: string) => void>() @@ -56,7 +56,7 @@ function isRelayableToPhones(environment: KnownRuntimeEnvironment): boolean { /** Relay requests use exact saved environment IDs. */ export function createRuntimeEnvironmentMobileRelayHosts(): MobileDesktopRelayHosts { - const userDataPath = app.getPath('userData') + const userDataPath = getRuntimeEnvironmentRegistryRoot() return { list: () => { const environments = listRelayableEnvironments(userDataPath) diff --git a/src/main/ipc/runtime-environments/runtime-environment-registry-root.ts b/src/main/ipc/runtime-environments/runtime-environment-registry-root.ts new file mode 100644 index 00000000000..9ce4b284af1 --- /dev/null +++ b/src/main/ipc/runtime-environments/runtime-environment-registry-root.ts @@ -0,0 +1,13 @@ +import { app } from 'electron' +import { resolveEnvironment } from '../../../shared/runtime-environment-store' + +/** Where the paired-runtime registry lives; read per call, after `app.setName` settles the casing. */ +export function getRuntimeEnvironmentRegistryRoot(): string { + return app.getPath('userData') +} + +/** The pairing a call to this environment should pin; throws for an environment no longer paired. */ +export function readRegisteredPairingRevision(environmentId: string): number { + const environment = resolveEnvironment(getRuntimeEnvironmentRegistryRoot(), environmentId) + return environment.pairingRevision ?? environment.createdAt +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts b/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts index 63631b1e1e0..c043a93606b 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts @@ -1,4 +1,5 @@ import { desktopChatCreationHistory } from '../../runtime/desktop-chat-creation-history' +import { revokeRemoteFilePreviewGrants } from '../../media/media-preview-protocol' import { clearBrowserRoutePartitionStorageForEnvironment } from '../../browser/browser-route-partition-storage-runtime' import { retireBrowserRoutePartitionStorageForEnvironment } from '../../browser/browser-route-partition-storage-retirement' import { clearRuntimeEnvironmentCapabilityEvidence } from './runtime-environment-capability-evidence' @@ -24,6 +25,7 @@ export function retireRemovedRuntimeEnvironment( void desktopChatCreationHistory(userDataPath).removeEnvironment(environmentId) } clearRuntimeEnvironmentCapabilityEvidence(environmentId) + revokeRemoteFilePreviewGrants(environmentId) // Retained session partitions make listings advertise the removed server as a known host. store.removeWorkspaceSessionHost(toRuntimeExecutionHostId(environmentId)) forgetRemoteLayoutSnapshot(store, environmentId) diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts b/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts index 7b40f92d25c..37490c151cd 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts @@ -27,6 +27,7 @@ import { advanceRuntimeEnvironmentTransportGeneration, getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' +import { declareWslHostClient } from '../../wsl/wsl-host-client-declaration' type CachedRuntimeConnection = { pairingKey: string @@ -269,13 +270,16 @@ function getSharedControlConnection( cached?.connection.close() const transportGeneration = getRuntimeEnvironmentTransportGeneration(environmentId) let answeredAt: number | null = null - cached = { - pairingKey, - answeredAt: () => answeredAt, - connection: new RemoteRuntimeSharedControlConnection(pairedConnection, { + const connection: RemoteRuntimeSharedControlConnection = + new RemoteRuntimeSharedControlConnection(pairedConnection, { environmentId, clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, ...sharedControlEnvironmentPolicy(environmentId), + // R39: every ready socket, including after a reconnect, re-declares this installation. + onReady: () => + declareWslHostClient(environmentId, (method, params, timeoutMs) => + connection.request(method, params, timeoutMs) + ), // Wall-clock time includes suspend, expiring pre-sleep answers. onAnswered: () => { answeredAt = Date.now() @@ -301,7 +305,7 @@ function getSharedControlConnection( ) } }) - } + cached = { pairingKey, answeredAt: () => answeredAt, connection } sharedControlConnections.set(environmentId, cached) const entry = cached // Ready requires this socket's own server frame, which stamps its answer time. diff --git a/src/main/ipc/runtime-environments/runtime-environments.ts b/src/main/ipc/runtime-environments/runtime-environments.ts index f29570e3cd4..0b06b0119d9 100644 --- a/src/main/ipc/runtime-environments/runtime-environments.ts +++ b/src/main/ipc/runtime-environments/runtime-environments.ts @@ -5,7 +5,8 @@ import { type RetainedRemoteRuntimeSubscription, type PendingRuntimeSubscription } from './runtime-environment-subscription-handlers' -import { app, ipcMain } from 'electron' +import { ipcMain } from 'electron' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environment-registry-root' import { listEnvironments } from '../../../shared/runtime-environment-store' import type { Store } from '../../persistence' import { recordRemoteLayoutFrame } from '../../remote-layout-snapshot/remote-layout-snapshot-recorder' @@ -49,7 +50,7 @@ import { isGatedOffWslHost } from '../../wsl/wsl-host-gate' import { resetDesktopBrowserBridgeEnvironment } from '../desktop-browser-bridge-reconcile' const remoteRuntimeSubscriptions = new Map() -const getUserDataPath = (): string => app.getPath('userData') +const getUserDataPath = getRuntimeEnvironmentRegistryRoot function closeSubscriptionsForEnvironment(environmentId: string): void { for (const pending of pendingSubscriptions.values()) { diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index 90aa679f3bd..9db44c0e190 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -43,8 +43,10 @@ import { } from '../../shared/computer-awake-mode' import { resolveAiVaultSearchSettings } from '../../shared/ai-vault-search-settings' import { applySessionSearchSettingsChange } from '../ai-vault-search/session-search-enablement' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' const SETTINGS_CHANGED_WHITELIST_SET = new Set(SETTINGS_CHANGED_WHITELIST) +const registryRoot = getRuntimeEnvironmentRegistryRoot type LegacyTerminalScrollbackSettingsUpdate = Partial & { terminalScrollbackBytes?: unknown @@ -95,7 +97,7 @@ export function registerSettingsHandlers( }) ipcMain.handle('settings:get', () => - readSettingsWithRuntimeEnvironmentPreference(store, app.getPath('userData')) + readSettingsWithRuntimeEnvironmentPreference(store, registryRoot()) ) ipcMain.handle( @@ -113,7 +115,7 @@ export function registerSettingsHandlers( // PTYs can bind before hydration; transport authority selection needs persisted settings synchronously. ipcMain.on('settings:get-sync', (event) => { - event.returnValue = readSettingsWithRuntimeEnvironmentPreference(store, app.getPath('userData')) + event.returnValue = readSettingsWithRuntimeEnvironmentPreference(store, registryRoot()) }) ipcMain.handle('settings:set', async (event, args: Partial) => { @@ -295,7 +297,7 @@ export function registerSettingsHandlers( } const requestedId = requestedEnvironmentId?.trim() || null const environmentId = - requestedId === null ? null : resolveEnvironment(app.getPath('userData'), requestedId).id + requestedId === null ? null : resolveEnvironment(registryRoot(), requestedId).id return store.updateSettings( { activeRuntimeEnvironmentId: environmentId }, { notifyListeners: true, originWebContentsId: event.sender.id } diff --git a/src/main/ipc/skill-cloud-ipc-handlers.test.ts b/src/main/ipc/skill-cloud-ipc-handlers.test.ts index 24aa32f0a24..89eaabb8a7a 100644 --- a/src/main/ipc/skill-cloud-ipc-handlers.test.ts +++ b/src/main/ipc/skill-cloud-ipc-handlers.test.ts @@ -1,14 +1,23 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { SkillShareProgress } from '../../shared/skill-sharing-contract' const { classifyInstallTargetMock, createDownloadGrantMock, + getAllWindowsMock, handlers, + mainRenderer, + otherRenderer, + trustedRendererMock, installSkillCloudGrantMock, registerInstallManagementMock } = vi.hoisted(() => ({ classifyInstallTargetMock: vi.fn(), createDownloadGrantMock: vi.fn(), + getAllWindowsMock: vi.fn(), + mainRenderer: { isDestroyed: vi.fn(() => false), send: vi.fn() }, + otherRenderer: { isDestroyed: vi.fn(() => false), send: vi.fn() }, + trustedRendererMock: vi.fn(), handlers: new Map unknown>(), installSkillCloudGrantMock: vi.fn(), registerInstallManagementMock: vi.fn() @@ -16,12 +25,13 @@ const { vi.mock('electron', () => ({ app: { getPath: () => '/test/user-data' }, - BrowserWindow: { getAllWindows: () => [] } -})) -vi.mock('./skill-ipc-main-window', () => ({ - handleMainWindowSkillIpc: (channel: string, handler: (...args: unknown[]) => unknown) => - handlers.set(channel, handler) + BrowserWindow: { getAllWindows: getAllWindowsMock }, + ipcMain: { + handle: (channel: string, handler: (...args: unknown[]) => unknown) => + handlers.set(channel, handler) + } })) +vi.mock('./ui', () => ({ getTrustedUIRendererWebContents: trustedRendererMock })) vi.mock('./skill-install-management-ipc-handlers', () => ({ registerSkillInstallManagementIpcHandlers: registerInstallManagementMock })) @@ -46,10 +56,21 @@ vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ })) import { registerSkillCloudIpcHandlers } from './skill-cloud-ipc-handlers' +import { SkillSharePreparationService } from '../skills/skill-share-preparation-service' describe('skill cloud IPC', () => { beforeEach(() => { handlers.clear() + mainRenderer.isDestroyed.mockReset().mockReturnValue(false) + mainRenderer.send.mockReset() + otherRenderer.send.mockReset() + trustedRendererMock.mockReset().mockReturnValue(mainRenderer) + getAllWindowsMock.mockReset().mockReturnValue( + [mainRenderer, otherRenderer].map((webContents) => ({ + isDestroyed: () => webContents.isDestroyed(), + webContents + })) + ) classifyInstallTargetMock.mockReset().mockResolvedValue('local') createDownloadGrantMock.mockReset().mockResolvedValue({ status: 'unconfigured', @@ -59,6 +80,8 @@ describe('skill cloud IPC', () => { installSkillCloudGrantMock.mockReset() }) + afterEach(() => vi.restoreAllMocks()) + it('requests a grant for the exact reviewed share version', async () => { const runtime = { createSkillDownloadGrant: createDownloadGrantMock } registerSkillCloudIpcHandlers(runtime as never, vi.fn()) @@ -66,7 +89,7 @@ describe('skill cloud IPC', () => { expect(installShare).toBeDefined() await installShare!( - { sender: {} }, + { sender: mainRenderer }, { shareId: 'share-1', versionId: 'version-reviewed', @@ -92,7 +115,7 @@ describe('skill cloud IPC', () => { await expect( installShare!( - { sender: {} }, + { sender: mainRenderer }, { shareId: 'share-1', versionId: 'version-reviewed', @@ -103,4 +126,76 @@ describe('skill cloud IPC', () => { ).rejects.toThrow('skill-package-version-mismatch') expect(installSkillCloudGrantMock).not.toHaveBeenCalled() }) + + const preparationId = 'cf38dbdc-bff0-4e87-a7ea-ef81b7edaa1a' + const progress: SkillShareProgress[] = [ + { preparationId, phase: 'uploading', bytesSent: 10, totalBytes: 20 }, + { preparationId, phase: 'finalizing', bytesSent: 20, totalBytes: 20 }, + { preparationId, phase: 'publishing', bytesSent: 20, totalBytes: 20 } + ] + + it('delivers share progress only to the invoking main renderer', async () => { + vi.spyOn(SkillSharePreparationService.prototype, 'publish').mockImplementation( + async (_input, onProgress) => { + for (const update of progress) { + onProgress?.(update) + } + return { status: 'unconfigured', message: 'not configured' } + } + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration captures the runtime; the publish spy never accesses it. + registerSkillCloudIpcHandlers({} as never, vi.fn()) + + await handlers.get('skills:publishShare')!( + { sender: mainRenderer }, + { preparationId, releaseNotes: 'Reviewed release' } + ) + + expect(mainRenderer.send.mock.calls).toEqual( + progress.map((update) => ['skills:shareProgress', update]) + ) + expect(otherRenderer.send).not.toHaveBeenCalled() + expect(getAllWindowsMock).not.toHaveBeenCalled() + }) + + it('stops delivery to a destroyed invoker without redirecting to a successor', async () => { + vi.spyOn(SkillSharePreparationService.prototype, 'publish').mockImplementation( + async (_input, onProgress) => { + onProgress?.(progress[0]) + mainRenderer.isDestroyed.mockReturnValue(true) + trustedRendererMock.mockReturnValue(otherRenderer) + for (const update of progress.slice(1)) { + onProgress?.(update) + } + return { status: 'unconfigured', message: 'not configured' } + } + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration captures the runtime; the publish spy never accesses it. + registerSkillCloudIpcHandlers({} as never, vi.fn()) + + await handlers.get('skills:publishShare')!( + { sender: mainRenderer }, + { preparationId, releaseNotes: 'Reviewed release' } + ) + + expect(mainRenderer.send.mock.calls).toEqual([['skills:shareProgress', progress[0]]]) + expect(otherRenderer.send).not.toHaveBeenCalled() + expect(getAllWindowsMock).not.toHaveBeenCalled() + }) + + it('rejects share publication from an unrelated renderer before starting it', () => { + const publish = vi.spyOn(SkillSharePreparationService.prototype, 'publish') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration captures the runtime; the publish spy never accesses it. + registerSkillCloudIpcHandlers({} as never, vi.fn()) + + expect(() => + handlers.get('skills:publishShare')!( + { sender: otherRenderer }, + { preparationId, releaseNotes: 'Reviewed release' } + ) + ).toThrow('Unauthorized skill IPC sender') + expect(publish).not.toHaveBeenCalled() + expect(mainRenderer.send).not.toHaveBeenCalled() + expect(otherRenderer.send).not.toHaveBeenCalled() + }) }) diff --git a/src/main/ipc/skill-cloud-ipc-handlers.ts b/src/main/ipc/skill-cloud-ipc-handlers.ts index 77c70fe9e49..06924e71aa6 100644 --- a/src/main/ipc/skill-cloud-ipc-handlers.ts +++ b/src/main/ipc/skill-cloud-ipc-handlers.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import { join } from 'node:path' -import { app, BrowserWindow } from 'electron' +import { app } from 'electron' import { z } from 'zod' import { SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } from '../../shared/skill-install-capability' import type { SkillDiscoveryResult, SkillDiscoveryTargetSchema } from '../../shared/skills' @@ -35,6 +35,7 @@ import { skillSharePrepareIpcSchema, skillSharePublishIpcSchema } from './skill-share-publishing-ipc-schemas' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' function registerSharingHandlers( runtime: OrcaRuntimeService, @@ -65,13 +66,11 @@ function registerSharingHandlers( packageId: input.packageId }) }) - handleMainWindowSkillIpc('skills:publishShare', async (_event, value: unknown) => { + handleMainWindowSkillIpc('skills:publishShare', async (event, value: unknown) => { const input = skillSharePublishIpcSchema.parse(value) return preparations.publish(input, (progress) => { - for (const window of BrowserWindow.getAllWindows()) { - if (!window.isDestroyed()) { - window.webContents.send('skills:shareProgress', progress) - } + if (!event.sender.isDestroyed()) { + event.sender.send('skills:shareProgress', progress) } }) }) @@ -147,7 +146,7 @@ function registerCloudInstallHandlers(runtime: OrcaRuntimeService): void { sendSkillInstallProgress(event, { operationId: input.operationId, phase: 'authorizing' }) if ( input.environmentId && - !(await supportsSkillRuntimeInstall(app.getPath('userData'), input.environmentId)) + !(await supportsSkillRuntimeInstall(getRuntimeEnvironmentRegistryRoot(), input.environmentId)) ) { return { status: 'unsupported' as const, message: SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } } @@ -169,7 +168,10 @@ function registerCloudInstallHandlers(runtime: OrcaRuntimeService): void { if ( input.environmentId && !input.environmentId.startsWith('ssh:') && - !(await supportsSkillRuntimeBundleInstall(app.getPath('userData'), input.environmentId)) + !(await supportsSkillRuntimeBundleInstall( + getRuntimeEnvironmentRegistryRoot(), + input.environmentId + )) ) { return { status: 'unsupported' as const, message: SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } } @@ -194,7 +196,7 @@ function registerCloudInstallHandlers(runtime: OrcaRuntimeService): void { sendSkillInstallProgress(event, { operationId: input.operationId, phase: 'authorizing' }) if ( input.environmentId && - !(await supportsSkillRuntimeInstall(app.getPath('userData'), input.environmentId)) + !(await supportsSkillRuntimeInstall(getRuntimeEnvironmentRegistryRoot(), input.environmentId)) ) { return { status: 'unsupported' as const, message: SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } } @@ -217,7 +219,10 @@ function registerCloudInstallHandlers(runtime: OrcaRuntimeService): void { if ( input.environmentId && !input.environmentId.startsWith('ssh:') && - !(await supportsSkillRuntimeBundleInstall(app.getPath('userData'), input.environmentId)) + !(await supportsSkillRuntimeBundleInstall( + getRuntimeEnvironmentRegistryRoot(), + input.environmentId + )) ) { return { status: 'unsupported' as const, message: SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } } @@ -249,11 +254,16 @@ function registerCloudInstallHandlers(runtime: OrcaRuntimeService): void { return { cancelled: runtime.cancelSharedSkillInstall(input.operationId) } } const transferCancelled = remoteInstallCancellation.cancel(input.operationId) - if (!(await supportsSkillRuntimeCancellation(app.getPath('userData'), input.environmentId))) { + if ( + !(await supportsSkillRuntimeCancellation( + getRuntimeEnvironmentRegistryRoot(), + input.environmentId + )) + ) { return { cancelled: transferCancelled } } const response = await callRuntimeEnvironment( - app.getPath('userData'), + getRuntimeEnvironmentRegistryRoot(), input.environmentId, 'skills.cancelInstall', { operationId: input.operationId }, diff --git a/src/main/ipc/skill-install-management-ipc-handlers.ts b/src/main/ipc/skill-install-management-ipc-handlers.ts index 88901b6ea86..7854223c5d6 100644 --- a/src/main/ipc/skill-install-management-ipc-handlers.ts +++ b/src/main/ipc/skill-install-management-ipc-handlers.ts @@ -21,6 +21,7 @@ import { import { listWslDistrosAsync } from '../wsl' import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' import { handleMainWindowSkillIpc } from './skill-ipc-main-window' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' const environmentIdSchema = z.string().min(1).max(128) const skillNameSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/) @@ -74,7 +75,7 @@ async function previewBundleInstall(runtime: OrcaRuntimeService, input: BundlePr destination: input.destination } const response = await callRuntimeEnvironment( - app.getPath('userData'), + getRuntimeEnvironmentRegistryRoot(), environmentId, 'skills.previewInstall', request, @@ -107,7 +108,7 @@ export function registerSkillInstallManagementIpcHandlers(runtime: OrcaRuntimeSe return listWslDistrosAsync() } const response = await callRuntimeEnvironment( - app.getPath('userData'), + getRuntimeEnvironmentRegistryRoot(), environmentId, 'host.wsl.listDistros', {}, @@ -154,8 +155,14 @@ export function registerSkillInstallManagementIpcHandlers(runtime: OrcaRuntimeSe .parse(value) if ( parsed.environmentId && - (!(await supportsSkillRuntimeManagement(app.getPath('userData'), parsed.environmentId)) || - !(await supportsSkillRuntimeBundleInstall(app.getPath('userData'), parsed.environmentId))) + (!(await supportsSkillRuntimeManagement( + getRuntimeEnvironmentRegistryRoot(), + parsed.environmentId + )) || + !(await supportsSkillRuntimeBundleInstall( + getRuntimeEnvironmentRegistryRoot(), + parsed.environmentId + ))) ) { return { status: 'unsupported' as const, message: SKILL_INSTALL_UPDATE_REQUIRED_MESSAGE } } diff --git a/src/main/ipc/speech-worker-exit-lifetime.test.ts b/src/main/ipc/speech-worker-exit-lifetime.test.ts index eb95c54a3a3..6dc898efa87 100644 --- a/src/main/ipc/speech-worker-exit-lifetime.test.ts +++ b/src/main/ipc/speech-worker-exit-lifetime.test.ts @@ -34,6 +34,8 @@ const environment = vi.hoisted( }) ) +const finishUploads: (() => void)[] = [] + const fileAccess = vi.hoisted(() => ({ write: vi.fn(), unlink: vi.fn() })) vi.mock('node:fs/promises', async (importOriginal) => ({ @@ -67,9 +69,9 @@ vi.mock('../speech/openai-api-key-store', () => ({ })) vi.mock('../speech/model-catalog', () => ({ SPEECH_MODEL_CATALOG: [], - getCatalogModel: () => ({ - id: 'test-model', - provider: 'local', + getCatalogModel: (id: string) => ({ + id, + provider: id === 'openai-gpt-4o-mini-transcribe' ? 'openai' : 'local', type: 'transducer', streaming: true, sampleRate: 16000, @@ -113,9 +115,17 @@ import { SttService as SpeechService } from '../speech/stt-service' import { handleSttWorkerFailure } from '../speech/stt-session-stop' import { RuntimeMobileDictationController } from '../runtime/runtime-mobile-dictation-controller' +class TestContents extends EventEmitter { + id = 9 + send = vi.fn() + isDestroyed(): boolean { + return false + } +} + class TestWindow extends EventEmitter { destroyed = false - webContents = { send: vi.fn() } + webContents = new TestContents() isDestroyed(): boolean { return this.destroyed } @@ -144,12 +154,183 @@ function service(): SttService { return environment.service } -const sender = { sender: { id: 9 } } +const sender = { + get sender(): TestContents { + if (!environment.window) { + throw new Error('No window') + } + return environment.window.webContents + } +} const start = (session = 'one'): Promise => handler('speech:startDictation')(sender, 'test-model', undefined, session) const stop = (session = 'one'): Promise => handler('speech:stopDictation')(sender, session) describe('speech worker exit ownership', () => { + it('discards retired cloud audio without uploading and accepts a replacement owner', async () => { + const upload = vi.fn() + vi.stubGlobal('fetch', upload) + await handler('speech:startDictation')(sender, 'openai-gpt-4o-mini-transcribe', undefined, '2') + service().feedAudio(new Float32Array(16000), 16000, 'desktop:9:0:2') + window.webContents.send.mockClear() + window.webContents.emit('render-process-gone') + expect(upload).not.toHaveBeenCalled() + expect(service()['state'].activeOwner).toBeNull() + expect(service()['state'].cloudSession).toBeNull() + expect(service()['state'].eventSink).toBeNull() + expect(window.webContents.send).not.toHaveBeenCalled() + await start('1') + expect(service()['state'].activeOwner).toBe('desktop:9:1:1') + await stop('1') + }) + + it('aborts an uploading retired owner and fences late completion from its successor', async () => { + const response = Promise.withResolvers() + finishUploads.push(() => response.resolve(new Response(JSON.stringify({ text: 'cleanup' })))) + const uploads: RequestInit[] = [] + vi.stubGlobal('fetch', (_url: string, init: RequestInit) => { + uploads.push(init) + return response.promise + }) + await handler('speech:startDictation')(sender, 'openai-gpt-4o-mini-transcribe', undefined, '2') + service().feedAudio(new Float32Array(16000), 16000, 'desktop:9:0:2') + const pendingStop = stop('2') + expect(uploads.at(-1)?.signal?.aborted).toBe(false) + window.webContents.emit('did-navigate') + expect(uploads.at(-1)?.signal?.aborted).toBe(true) + await start('1') + window.webContents.send.mockClear() + response.resolve(new Response(JSON.stringify({ text: 'obsolete text' }))) + await pendingStop + expect(service()['state'].activeOwner).toBe('desktop:9:1:1') + expect(service()['state'].eventSink).not.toBeNull() + expect(window.webContents.send).not.toHaveBeenCalled() + worker().emit('message', { type: 'partial', text: 'replacement text' }) + expect(window.webContents.send).toHaveBeenCalledWith('speech:partial', { + text: 'replacement text', + sessionId: '1' + }) + await stop('1') + }) + + it('coalesces explicit cloud stop and keeps its owner until final text is delivered', async () => { + const response = Promise.withResolvers() + finishUploads.push(() => response.resolve(new Response(JSON.stringify({ text: 'cleanup' })))) + const upload = vi.fn(() => response.promise) + vi.stubGlobal('fetch', upload) + await handler('speech:startDictation')(sender, 'openai-gpt-4o-mini-transcribe', undefined, '2') + service().feedAudio(new Float32Array(16000), 16000, 'desktop:9:0:2') + const firstStop = stop('2') + const secondStop = stop('2') + await expect(start('1')).rejects.toThrow('dictation_already_active') + expect(service()['state'].activeOwner).toBe('desktop:9:0:2') + response.resolve(new Response(JSON.stringify({ text: 'completed text' }))) + await Promise.all([firstStop, secondStop]) + expect(upload).toHaveBeenCalledTimes(1) + expect(window.webContents.send.mock.calls.filter(([name]) => name === 'speech:final')).toEqual([ + ['speech:final', { text: 'completed text', sessionId: '2' }] + ]) + expect(service()['state'].activeOwner).toBeNull() + expect(service()['state'].eventSink).toBeNull() + }) + + it('fences a late worker ready result after renderer document retirement', async () => { + environment.readyOnInit = false + const pending = start('2') + await vi.waitFor(() => expect(environment.workers).toHaveLength(1)) + window.webContents.send.mockClear() + window.webContents.emit('render-process-gone') + worker().emit('message', { type: 'ready' }) + await expect(pending).rejects.toThrow('dictation_canceled') + expect(window.webContents.send).not.toHaveBeenCalled() + expect(service()['state'].activeOwner).toBeNull() + expect(service()['state'].eventSink).toBeNull() + }) + + it('does not let a successor document join a retired pending start with the same run id', async () => { + environment.readyOnInit = false + const retired = start('1') + await vi.waitFor(() => expect(environment.workers).toHaveLength(1)) + window.webContents.emit('did-navigate') + await expect(start('1')).rejects.toThrow('dictation_already_active') + worker().emit('message', { type: 'ready' }) + await expect(retired).rejects.toThrow('dictation_canceled') + window.webContents.send.mockClear() + await start('1') + expect(window.webContents.send).toHaveBeenCalledWith('speech:ready', { sessionId: '1' }) + expect(service()['state'].activeOwner).toBe('desktop:9:1:1') + await stop('1') + }) + + it('preserves same-document dictation and bounds native listeners across replacements', async () => { + for (let index = 0; index < 10; index++) { + await start(String(index)) + window.webContents.emit('did-navigate-in-page', {}, '#section', true) + expect(service()['state'].activeOwner).toBe(`desktop:9:${index}:${index}`) + expect(window.webContents.listenerCount('did-navigate')).toBe(1) + window.webContents.emit(index % 2 === 0 ? 'render-process-gone' : 'did-navigate') + await vi.waitFor(() => expect(service()['state'].activeOwner).toBeNull()) + expect(window.webContents.eventNames()).toEqual([]) + expect(window.listenerCount('closed')).toBe(0) + } + expect(environment.workers).toHaveLength(1) + }) + + it('keeps a successor hotwords file until its worker has read it', async () => { + environment.readyOnInit = false + const write = Promise.withResolvers() + fileAccess.write.mockReturnValueOnce(write.promise) + const retired = handler('speech:startDictation')(sender, 'test-model', ['orca'], '2') + window.webContents.emit('render-process-gone') + const replacement = handler('speech:startDictation')(sender, 'test-model', ['orca'], '1') + await vi.waitFor(() => expect(environment.workers).toHaveLength(1)) + write.resolve() + const retirementError = await retired.then( + () => undefined, + (error: Error) => error.message + ) + const deletesBeforeReady = fileAccess.unlink.mock.calls.length + worker().emit('message', { type: 'ready' }) + await replacement + await stop('1') + expect(retirementError).toBeUndefined() + expect(deletesBeforeReady).toBe(0) + }) + + it.each(['render-process-gone', 'did-navigate'])( + 'releases renderer document dictation on %s and allows a replacement', + async (event) => { + await start('2') + const state = service()['state'] + const originalWorker = worker() + expect(state.activeOwner).toBe('desktop:9:0:2') + window.webContents.send.mockClear() + window.webContents.emit(event) + originalWorker.emit('message', { type: 'partial', text: 'retired text' }) + await Promise.resolve() + await Promise.resolve() + expect(state.activeOwner).toBeNull() + expect(state.eventSink).toBeNull() + expect(window.webContents.send).not.toHaveBeenCalled() + await start('1') + expect(state.activeOwner).toBe('desktop:9:1:1') + expect(worker()).toBe(originalWorker) + await stop('1') + } + ) + + it('prevents renderer document hotword preparation from starting after retirement', async () => { + const write = Promise.withResolvers() + fileAccess.write.mockReturnValueOnce(write.promise) + const pending = handler('speech:startDictation')(sender, 'test-model', ['orca'], '2') + window.webContents.emit('render-process-gone') + write.resolve() + await pending + expect(environment.workers).toHaveLength(0) + expect(service()['state'].activeOwner).toBeNull() + expect(window.webContents.send).not.toHaveBeenCalled() + }) + let window: TestWindow beforeEach(() => { environment.handlers.clear() @@ -171,11 +352,16 @@ describe('speech worker exit ownership', () => { registerSpeechHandlers({} as Store) }) afterEach(async () => { + for (const finish of finishUploads.splice(0)) { + finish() + } window.destroyed = true window.emit('closed') await Promise.resolve() await Promise.resolve() + await vi.waitFor(() => expect(service()['state'].activeOwner).toBeNull()) await service().prepareModelForDeletion('test-model') + vi.unstubAllGlobals() }) it('bounds close listeners through repeated starts and stops with no remaining worker', async () => { diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index 6b8e8d9d4a0..c20425843cb 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -1,4 +1,5 @@ import { ipcMain, BrowserWindow, systemPreferences } from 'electron' +import { abortWhenRendererGone } from './renderer-lifetime-abort' import { join } from 'node:path' import { writeFile, unlink } from 'node:fs/promises' import { createHash } from 'node:crypto' @@ -84,8 +85,27 @@ export function registerSpeechHandlers(store: Store): void { return join(getSpeechModelManager(store).getModelsDir(), `speech-hotwords-${digest}.txt`) } + const hotwordFileUsers = new Map() + const retainHotwordsFile = (path: string): ((written: boolean) => void) => { + const entry = hotwordFileUsers.get(path) ?? { users: 0, written: false } + entry.users += 1 + hotwordFileUsers.set(path, entry) + return (written) => { + entry.written ||= written + entry.users -= 1 + if (entry.users === 0) { + hotwordFileUsers.delete(path) + if (entry.written) { + unlink(path).catch(() => {}) + } + } + } + } + + // Renderer run ids restart per document; a retired document's owner must not be reused by its successor. + const retiredDocumentCounts = new Map() const getDesktopOwner = (senderId: number, sessionId: string): string => - `desktop:${senderId}:${sessionId}` + `desktop:${senderId}:${retiredDocumentCounts.get(senderId) ?? 0}:${sessionId}` const dictationListeners = new Map void }>() @@ -97,31 +117,33 @@ export function registerSpeechHandlers(store: Store): void { return } let resolvedHotwordsPath: string | undefined - let windowClosed = false + let releaseHotwords: ((written: boolean) => void) | undefined + let rendererRetired = false + const rendererLifetime = abortWhenRendererGone(event.sender) const senderId = event.sender.id const owner = getDesktopOwner(senderId, sessionId) let sessionListenerRemoved = false let sessionReady = false - const cleanupOnWindowClosed = (): void => { - windowClosed = true + const cleanupOnRendererGone = (): void => { + if (!rendererRetired && getDesktopOwner(senderId, sessionId) === owner) { + retiredDocumentCounts.set(senderId, (retiredDocumentCounts.get(senderId) ?? 0) + 1) + } + rendererRetired = true cleanupSessionListener() void getSpeechSttService(store) - .stopDictation(owner) - .finally(() => { - if (resolvedHotwordsPath) { - unlink(resolvedHotwordsPath).catch(() => {}) - } - }) + .stopDictation(owner, { discard: true }) .catch(() => {}) } const cleanupSessionListener = (): void => { sessionListenerRemoved = true - window.off('closed', cleanupOnWindowClosed) + window.off('closed', cleanupOnRendererGone) + rendererLifetime.dispose() if (dictationListeners.get(senderId)?.cleanup === cleanupSessionListener) { dictationListeners.delete(senderId) } } - window.once('closed', cleanupOnWindowClosed) + window.once('closed', cleanupOnRendererGone) + rendererLifetime.signal.addEventListener('abort', cleanupOnRendererGone, { once: true }) try { // macOS can return silent microphone streams without TCC permission; request it before capture. @@ -142,15 +164,13 @@ export function registerSpeechHandlers(store: Store): void { if (hotwords && hotwords.length > 0) { const content = `${hotwords.map((w) => `${w} :2.0`).join('\n')}\n` const hotwordsFilePath = getHotwordsFilePath(content) + releaseHotwords = retainHotwordsFile(hotwordsFilePath) await writeFile(hotwordsFilePath, content, 'utf-8') resolvedHotwordsPath = hotwordsFilePath } - if (windowClosed || window.isDestroyed()) { + if (rendererRetired || window.isDestroyed()) { cleanupSessionListener() - if (resolvedHotwordsPath) { - unlink(resolvedHotwordsPath).catch(() => {}) - } return } @@ -160,7 +180,7 @@ export function registerSpeechHandlers(store: Store): void { if (msg.type === 'ready') { sessionReady = true } - if (window.isDestroyed()) { + if (rendererRetired || window.isDestroyed()) { return } switch (msg.type) { @@ -198,15 +218,11 @@ export function registerSpeechHandlers(store: Store): void { } else { cleanupSessionListener() } - if (resolvedHotwordsPath) { - unlink(resolvedHotwordsPath).catch(() => {}) - } } catch (err) { cleanupSessionListener() - if (resolvedHotwordsPath) { - unlink(resolvedHotwordsPath).catch(() => {}) - } throw err + } finally { + releaseHotwords?.(resolvedHotwordsPath !== undefined) } } ) diff --git a/src/main/ipc/terminal-preview-document-lifetime.test.ts b/src/main/ipc/terminal-preview-document-lifetime.test.ts new file mode 100644 index 00000000000..e41a7b92cfe --- /dev/null +++ b/src/main/ipc/terminal-preview-document-lifetime.test.ts @@ -0,0 +1,147 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { handlers } = vi.hoisted(() => ({ + handlers: new Map unknown>() +})) + +vi.mock('electron', () => ({ + ipcMain: { + removeHandler: (channel: string) => handlers.delete(channel), + handle: (channel: string, handler: (...args: unknown[]) => unknown) => + handlers.set(channel, handler) + } +})) +vi.mock('../window/dashboard-popout-window', () => ({ isDashboardPopoutRenderer: () => true })) +vi.mock('./ui', () => ({ isTrustedUIRenderer: () => false })) + +import { registerTerminalPreviewHandlers } from './terminal-preview' + +type Snapshot = { data: string; cols: number; rows: number; seq: number } + +function setup() { + const data = new Set<(value: string) => void>() + const resize = new Set<(size: { cols: number; rows: number }) => void>() + const fits = new Set() + let rawViews = 0 + const runtime = { + serializeTerminalBuffer: vi.fn(async (): Promise => ({ + data: 'screen', + cols: 80, + rows: 24, + seq: 0 + })), + subscribeToTerminalData: vi.fn((_ptyId: string, listener: (value: string) => void) => { + data.add(listener) + return () => data.delete(listener) + }), + subscribeToTerminalResize: vi.fn( + (_ptyId: string, listener: (size: { cols: number; rows: number }) => void) => { + resize.add(listener) + return () => resize.delete(listener) + } + ), + registerRawTerminalViewSubscriber: vi.fn(() => { + rawViews += 1 + return () => (rawViews -= 1) + }), + writeTerminalPreviewInput: vi.fn(async () => true), + updateRemoteDesktopViewer: vi.fn(async (ptyId: string) => { + fits.add(ptyId) + return true + }), + unregisterRemoteDesktopViewer: vi.fn(async (ptyId: string) => { + fits.delete(ptyId) + return true + }), + getTerminalSize: vi.fn(() => ({ cols: 80, rows: 24 })) + } + const sender = Object.assign(new EventEmitter(), { + id: 17, + isDestroyed: () => false, + send: vi.fn() + }) + // SAFETY: The handler only uses the runtime methods implemented by this production-boundary fixture. + registerTerminalPreviewHandlers(runtime as never) + const call = (channel: string, args: unknown) => handlers.get(channel)!({ sender }, args) + return { + sender, + runtime, + data, + call, + counts: () => ({ data: data.size, resize: resize.size, raw: rawViews, fits: fits.size }) + } +} + +describe('terminal preview document lifetime', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + + it.each(['did-navigate', 'render-process-gone', 'destroyed'])( + 'releases all preview owners and queued output on %s', + async (event) => { + const { sender, data, call, counts } = setup() + await call('terminalPreview:connect', { ptyId: 'pane' }) + await call('terminalPreview:fit', { ptyId: 'pane', cols: 80, rows: 24 }) + const staleListeners = [...data] + staleListeners.forEach((listener) => listener('queued')) + expect(counts()).toEqual({ data: 1, resize: 1, raw: 1, fits: 1 }) + + sender.emit(event) + expect(counts()).toEqual({ data: 0, resize: 0, raw: 0, fits: 0 }) + staleListeners.forEach((listener) => listener('late output')) + await vi.runAllTimersAsync() + expect(sender.send).not.toHaveBeenCalled() + } + ) + + it('rejects a retired snapshot without disposing its replacement preview', async () => { + const { sender, runtime, call, counts } = setup() + const snapshot = Promise.withResolvers() + runtime.serializeTerminalBuffer.mockImplementationOnce(() => snapshot.promise) + const retired = call('terminalPreview:connect', { ptyId: 'pane' }) + sender.emit('render-process-gone') + await call('terminalPreview:connect', { ptyId: 'pane-b' }) + + snapshot.resolve({ data: 'old screen', cols: 80, rows: 24, seq: 0 }) + await expect(retired).resolves.toEqual({ snapshot: null, replay: [] }) + expect(counts()).toEqual({ data: 1, resize: 1, raw: 1, fits: 0 }) + sender.emit('destroyed') + expect(counts()).toEqual({ data: 0, resize: 0, raw: 0, fits: 0 }) + }) + + it('does not let an old fit completion release the replacement document claim', async () => { + const { sender, runtime, call, counts } = setup() + const pendingFit = Promise.withResolvers() + runtime.updateRemoteDesktopViewer.mockImplementationOnce(() => pendingFit.promise) + const retired = call('terminalPreview:fit', { ptyId: 'pane', cols: 90, rows: 30 }) + sender.emit('did-navigate') + await call('terminalPreview:fit', { ptyId: 'pane', cols: 80, rows: 24 }) + pendingFit.resolve(false) + await expect(retired).resolves.toBeNull() + expect(runtime.unregisterRemoteDesktopViewer).toHaveBeenCalledTimes(1) + expect(counts()).toEqual({ data: 0, resize: 0, raw: 0, fits: 1 }) + sender.emit('destroyed') + }) + + it('preserves same-document navigation and bounds listeners across ten replacements', async () => { + const { sender, data, call, counts } = setup() + for (let index = 0; index < 10; index += 1) { + await call('terminalPreview:connect', { ptyId: `pane-${index}` }) + await call('terminalPreview:fit', { ptyId: `pane-${index}`, cols: 80, rows: 24 }) + sender.emit('did-navigate-in-page', {}, '#section', true) + expect(counts()).toEqual({ data: 1, resize: 1, raw: 1, fits: 1 }) + data.forEach((listener) => listener('live output')) + await vi.advanceTimersByTimeAsync(5) + expect(sender.send).toHaveBeenCalledTimes(index + 1) + sender.emit(index % 2 === 0 ? 'did-navigate' : 'render-process-gone') + expect(counts()).toEqual({ data: 0, resize: 0, raw: 0, fits: 0 }) + expect(sender.listenerCount('did-navigate')).toBe(0) + expect(sender.listenerCount('render-process-gone')).toBe(0) + expect(sender.listenerCount('destroyed')).toBe(0) + } + }) +}) diff --git a/src/main/ipc/terminal-preview.test.ts b/src/main/ipc/terminal-preview.test.ts index 1c057ea19b6..6e78157be3c 100644 --- a/src/main/ipc/terminal-preview.test.ts +++ b/src/main/ipc/terminal-preview.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { handlers, ipcMainMock, isDashboardPopoutRendererMock, isTrustedUIRendererMock } = @@ -65,17 +66,14 @@ function makeRuntime() { } function makeSender(id = 1) { - const destroyedListeners: (() => void)[] = [] + const events = new EventEmitter() return { id, isDestroyed: () => false, send: vi.fn(), - once: (event: string, cb: () => void) => { - if (event === 'destroyed') { - destroyedListeners.push(cb) - } - }, - fireDestroyed: () => destroyedListeners.forEach((cb) => cb()) + on: events.on.bind(events), + removeListener: events.removeListener.bind(events), + fireDestroyed: () => events.emit('destroyed') } } diff --git a/src/main/ipc/terminal-preview.ts b/src/main/ipc/terminal-preview.ts index d0a023c97b4..a76c10a5e2a 100644 --- a/src/main/ipc/terminal-preview.ts +++ b/src/main/ipc/terminal-preview.ts @@ -6,6 +6,7 @@ import type { import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { isDashboardPopoutRenderer } from '../window/dashboard-popout-window' import { isTrustedUIRenderer } from './ui' +import { abortWhenRendererGone } from './renderer-lifetime-abort' import { TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES, TerminalPreviewOutputStream @@ -30,8 +31,9 @@ export function registerTerminalPreviewHandlers(runtime: OrcaRuntimeService): vo ipcMain.removeHandler('terminalPreview:fit') const subscriptionsByContents = new Map>() - // Track grid claims by WebContents so unsubscribe or destruction releases the host pane's geometry. + // Unsubscribe or renderer document retirement releases the host pane's grid claim. const fitClaimsByContents = new Map>() + const rendererLifetimes = new Map>() const previewViewerKey = (contentsId: number): string => `dashboard-popout:${contentsId}` @@ -56,6 +58,9 @@ export function registerTerminalPreviewHandlers(runtime: OrcaRuntimeService): vo } const disposeContents = (contentsId: number): void => { + const lifetime = rendererLifetimes.get(contentsId) + rendererLifetimes.delete(contentsId) + lifetime?.dispose() const perPty = subscriptionsByContents.get(contentsId) if (perPty) { for (const subscription of perPty.values()) { @@ -73,7 +78,9 @@ export function registerTerminalPreviewHandlers(runtime: OrcaRuntimeService): vo if (!perPty) { perPty = new Map() subscriptionsByContents.set(contents.id, perPty) - contents.once('destroyed', () => disposeContents(contents.id)) + const lifetime = abortWhenRendererGone(contents) + rendererLifetimes.set(contents.id, lifetime) + lifetime.signal.addEventListener('abort', () => disposeContents(contents.id), { once: true }) } return perPty } diff --git a/src/main/ipc/ui.test.ts b/src/main/ipc/ui.test.ts index 9fce31d313f..18f034433e7 100644 --- a/src/main/ipc/ui.test.ts +++ b/src/main/ipc/ui.test.ts @@ -1,4 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getDefaultUIState } from '../../shared/constants' +import type { PersistedUIState } from '../../shared/persisted-ui-state-types' const { fromIdMock, @@ -12,7 +14,7 @@ const { fromIdMock: vi.fn(), fromWebContentsMock: vi.fn(), getAllWebContentsMock: vi.fn(), - getAllWindowsMock: vi.fn(() => []), + getAllWindowsMock: vi.fn(), handleMock: vi.fn(), onMock: vi.fn(), removeAllListenersMock: vi.fn() @@ -44,7 +46,7 @@ import { function makeStore() { return { - onUIChanged: vi.fn(), + onUIChanged: vi.fn<(listener: (ui: PersistedUIState) => void) => () => void>(() => () => {}), getUI: vi.fn(() => ({})), updateUI: vi.fn(), recordFeatureInteraction: vi.fn() @@ -96,6 +98,38 @@ describe('UI IPC', () => { vi.unstubAllEnvs() }) + it('publishes UI state only to the trusted main renderer, never other windows', () => { + const mainSend = vi.fn() + const dashboardSend = vi.fn() + const spaceSend = vi.fn() + const main = { id: 17, isDestroyed: () => false, send: mainSend } + getAllWindowsMock.mockReturnValue( + [main, { id: 42, send: dashboardSend }, { id: 43, send: spaceSend }].map((contents) => ({ + isDestroyed: () => false, + webContents: { ...contents, isDestroyed: () => false } + })) + ) + fromIdMock.mockReturnValue(main) + const store = makeStore() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: UI handler registration uses only the supplied store methods. + registerUIHandlers(store as never) + const publish = store.onUIChanged.mock.calls[0]?.[0] + if (!publish) { + throw new Error('UI state publisher was not registered') + } + const ui = getDefaultUIState() + + publish(ui) + expect(mainSend).not.toHaveBeenCalled() + + setTrustedUIRendererWebContentsId(main.id) + publish(ui) + expect(mainSend).toHaveBeenCalledExactlyOnceWith('ui:stateChanged', ui) + expect(dashboardSend).not.toHaveBeenCalled() + expect(spaceSend).not.toHaveBeenCalled() + expect(getAllWindowsMock).not.toHaveBeenCalled() + }) + it('sends app events once to the trusted renderer without waking 100 browser guests', () => { const rendererSend = vi.fn() const guestSends = Array.from({ length: 100 }, () => vi.fn()) diff --git a/src/main/ipc/ui.ts b/src/main/ipc/ui.ts index 9e8b42d7b87..0fbe7b35175 100644 --- a/src/main/ipc/ui.ts +++ b/src/main/ipc/ui.ts @@ -57,14 +57,7 @@ export function registerUIHandlers( store: Store, options: { isDashboardPopoutRenderer?: (sender: WebContents) => boolean } = {} ): void { - // Broadcast UI state so desktop rehydrates mobile or sibling-window changes. - store.onUIChanged((ui) => { - for (const window of BrowserWindow.getAllWindows()) { - if (!window.isDestroyed() && !window.webContents.isDestroyed()) { - window.webContents.send('ui:stateChanged', ui) - } - } - }) + store.onUIChanged((ui) => sendToTrustedUIRenderer('ui:stateChanged', ui)) ipcMain.handle('ui:getJiraQuickFilters', () => normalizeJiraQuickFilterState(store.getUI().jiraQuickFilterState) diff --git a/src/main/ipc/workspace-cleanup-document-lifetime.test.ts b/src/main/ipc/workspace-cleanup-document-lifetime.test.ts new file mode 100644 index 00000000000..aee7d26a0a6 --- /dev/null +++ b/src/main/ipc/workspace-cleanup-document-lifetime.test.ts @@ -0,0 +1,174 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { GitStatusResult } from '../../shared/git-status-types' +import type { GitWorktreeInfo } from '../../shared/worktree/types' +import type * as RepoWorktrees from '../repo-worktrees' + +const boundary = vi.hoisted(() => ({ + handlers: new Map unknown>(), + list: vi.fn(), + status: vi.fn(), + persist: vi.fn() +})) +vi.mock('electron', () => ({ + ipcMain: { + handle: (name: string, fn: (event: unknown, args: unknown) => unknown) => + boundary.handlers.set(name, fn), + removeHandler: (name: string) => boundary.handlers.delete(name) + } +})) +vi.mock('node:fs/promises', () => ({ + lstat: vi.fn(async () => ({ mtimeMs: 0 })), + readFile: vi.fn(async () => { + throw new Error('no gitdir pointer') + }) +})) +vi.mock('../repo-worktrees', async (importOriginal) => ({ + ...(await importOriginal()), + listRepoWorktrees: boundary.list +})) +vi.mock('../git/status', () => ({ getStatus: boundary.status })) +vi.mock('../git/runner', () => ({ + gitExecFileAsync: vi.fn(async () => ({ stdout: '0\n', stderr: '' })) +})) +vi.mock('../project-runtime-git-options', () => ({ getLocalProjectWorktreeGitOptions: () => ({}) })) +vi.mock('../workspace-cleanup-scan-snapshot', () => ({ + persistWorkspaceCleanupScanResult: boundary.persist, + readWorkspaceCleanupScanSnapshot: vi.fn() +})) +vi.mock('../workspace-cleanup-removal-snapshot-prune', () => ({ + beginWorkspaceCleanupRemovalSnapshotPruneBatch: vi.fn(), + finishWorkspaceCleanupRemovalSnapshotPruneBatch: vi.fn(), + recordWorkspaceCleanupRemovalSnapshotPrune: vi.fn() +})) + +import { registerWorkspaceCleanupHandlers } from './workspace-cleanup' + +const NOW = Date.UTC(2025, 0, 1) +const STATUS: GitStatusResult = { + entries: [], + conflictOperation: 'unknown', + upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 } +} +class Sender extends EventEmitter { + id = 9 + send = vi.fn() + isDestroyed(): boolean { + return false + } +} +function rows(size: number, prefix = 'workspace'): GitWorktreeInfo[] { + return Array.from({ length: size }, (_, index) => ({ + path: `/${prefix}-${index}`, + head: 'abc', + branch: `refs/heads/branch-${index}`, + isBare: false, + isMainWorktree: false + })) +} +function setup() { + const store = { + getRepos: () => [ + { + id: 'repo', + path: '/repo', + displayName: 'Repo', + badgeColor: '#000', + addedAt: NOW, + symlinkPaths: [] + } + ], + getWorktreeMeta: () => ({ lastActivityAt: NOW - 40 * 24 * 60 * 60 * 1000 }), + getAllWorktreeMeta: () => ({}), + getGitHubCache: () => ({ pr: {}, issue: {} }), + getProfileStorageDirectory: () => 'unused' + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The actual scanner reads only these store methods; mergeWorktree supplies missing metadata defaults. + registerWorkspaceCleanupHandlers(store as never) + const handler = boundary.handlers.get('workspaceCleanup:scan') + if (!handler) { + throw new Error('Missing scan handler') + } + const sender = new Sender() + return { + sender, + scan: (scanId: string) => + Promise.resolve(handler({ sender }, { scanId, includeAllWorkspaces: true })) + } +} + +describe('workspace cleanup document ownership', () => { + beforeEach(() => { + vi.spyOn(Date, 'now').mockReturnValue(NOW) + boundary.handlers.clear() + boundary.list.mockReset().mockResolvedValue(rows(10)) + boundary.status.mockReset().mockResolvedValue(STATUS) + boundary.persist.mockReset().mockResolvedValue(undefined) + }) + afterEach(() => vi.restoreAllMocks()) + it.each( + [10, 100].flatMap((size) => + ['destroyed', 'render-process-gone', 'did-navigate'].map((event) => ({ size, event })) + ) + )( + 'cancels $size rows after $event without dispatching beyond active reads', + async ({ size, event }) => { + boundary.list.mockResolvedValue(rows(size)) + const pending = Promise.withResolvers() + boundary.status.mockReturnValue(pending.promise) + const { sender, scan } = setup() + const outcome = scan('retired').then( + () => 'complete', + () => 'cancelled' + ) + await vi.waitFor(() => expect(boundary.status).toHaveBeenCalledTimes(3)) + sender.send.mockClear() + sender.emit(event) + pending.resolve(STATUS) + expect(await outcome).toBe('cancelled') + expect(boundary.status).toHaveBeenCalledTimes(3) + expect(sender.send).not.toHaveBeenCalled() + expect(boundary.persist).not.toHaveBeenCalled() + expect(sender.eventNames()).toEqual([]) + } + ) + it('preserves same-document navigation and persists a completed scan', async () => { + const pending = Promise.withResolvers() + boundary.status.mockReturnValue(pending.promise) + const { sender, scan } = setup() + const result = scan('live') + await vi.waitFor(() => expect(boundary.status).toHaveBeenCalledTimes(3)) + sender.emit('did-navigate-in-page', {}, '#section', true) + pending.resolve(STATUS) + await result + expect(boundary.status).toHaveBeenCalledTimes(10) + expect(boundary.persist).toHaveBeenCalledTimes(1) + expect(sender.eventNames()).toEqual([]) + }) + it('lets a successor finish while late retired reads settle', async () => { + const pending = Promise.withResolvers() + boundary.list + .mockResolvedValueOnce(rows(10, 'retired')) + .mockResolvedValue(rows(10, 'replacement')) + boundary.status.mockImplementation((path: string) => + path.startsWith('/retired') ? pending.promise : Promise.resolve(STATUS) + ) + const { sender, scan } = setup() + const old = scan('retired').then( + () => 'complete', + () => 'cancelled' + ) + await vi.waitFor(() => expect(boundary.status).toHaveBeenCalledTimes(3)) + sender.emit('render-process-gone') + sender.send.mockClear() + await scan('replacement') + pending.resolve(STATUS) + expect(await old).toBe('cancelled') + expect(boundary.status).toHaveBeenCalledTimes(13) + expect(boundary.persist).toHaveBeenCalledTimes(1) + expect(sender.send.mock.calls.every(([, progress]) => progress.scanId === 'replacement')).toBe( + true + ) + expect(sender.eventNames()).toEqual([]) + }) +}) diff --git a/src/main/ipc/workspace-cleanup.ts b/src/main/ipc/workspace-cleanup.ts index d52cba21944..562aaefe849 100644 --- a/src/main/ipc/workspace-cleanup.ts +++ b/src/main/ipc/workspace-cleanup.ts @@ -11,7 +11,7 @@ import { import { parseExecutionHostId } from '../../shared/execution-host' import { getWorkspaceCleanupHostIdentity } from '../../shared/workspace-cleanup-host-identity' import { scanWorkspaceCleanup } from './workspace-cleanup-scan' -import { addFanoutListener } from '../event-listener-fanout' +import { abortWhenRendererGone } from './renderer-lifetime-abort' import { hasTargetedWorkspaceCleanupScan } from './workspace-cleanup-scan-targets' import { persistWorkspaceCleanupScanResult, @@ -63,14 +63,14 @@ export function registerWorkspaceCleanupHandlers(store: Store): void { broadScanControllersBySenderMode.set(broadScanKey, controller) } // Window retirement must cancel scan work, not merely mute its progress. - const onSenderDestroyed = (): void => controller.abort() - const releaseDestroyed = addFanoutListener(sender, 'destroyed', onSenderDestroyed) + const lifetime = abortWhenRendererGone(sender) + lifetime.signal.addEventListener('abort', () => controller.abort(), { once: true }) try { const result = await scanWorkspaceCleanup(store, scanArgs, { signal: controller.signal, onProgress: scanArgs.scanId ? (progress) => { - if (!sender.isDestroyed()) { + if (!controller.signal.aborted && !sender.isDestroyed()) { sender.send('workspaceCleanup:scanProgress', progress) } } @@ -82,7 +82,7 @@ export function registerWorkspaceCleanupHandlers(store: Store): void { } return result } finally { - releaseDestroyed() + lifetime.dispose() if (scanKey && activeScans.get(scanKey) === controller) { activeScans.delete(scanKey) } diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 8a299d9a544..75b3d6967d2 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -317,7 +317,8 @@ async function spawnLocalStartupAndSetupTerminals(args: { defaultTabs: CreateWorktreeResult['defaultTabs'] createdWithAgent: CreateWorktreeArgs['createdWithAgent'] }): Promise { - const { runtime, worktree, startup, setup, defaultTabs, createdWithAgent } = args + const { runtime, worktree, startup, defaultTabs, createdWithAgent } = args + let { setup } = args if (!startup || defaultTabs?.tabs.length) { return { didSpawnSetup: false } } @@ -345,6 +346,7 @@ async function spawnLocalStartupAndSetupTerminals(args: { ...(sequenced.startupEnv ? { env: { ...startup.env, ...sequenced.startupEnv } } : {}) } wrappedSetupCommandStr = sequenced.setupCommand + setup = { ...setup, envVars: { ...setup.envVars, ...sequenced.setupEnv } } } try { diff --git a/src/main/ipc/worktrees-failed-removal.test.ts b/src/main/ipc/worktrees-failed-removal.test.ts index a52abc37eb6..c1536fae308 100644 --- a/src/main/ipc/worktrees-failed-removal.test.ts +++ b/src/main/ipc/worktrees-failed-removal.test.ts @@ -15,6 +15,8 @@ import { worktreeCheckoutExists } from '../worktree-removal-table' import type * as WorktreeRemovalModule from '../git/worktree-removal' import type * as WorktreeRemovalTable from '../worktree-removal-table' import type * as WorktreeRemovalLeftover from '../worktree-removal-leftover' +import { removeLocalWorktreePath } from '../local-worktree-filesystem' +import type * as LocalWorktreeFilesystem from '../local-worktree-filesystem' import { _resetPendingWorktreeRemovalsForTests, _settlePendingWorktreeRemovalsForTests, @@ -108,6 +110,10 @@ vi.mock('../worktree-removal-table', async (importOriginal) => ({ ...(await importOriginal()), worktreeCheckoutExists: vi.fn(async () => true) })) +vi.mock('../local-worktree-filesystem', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, removeLocalWorktreePath: vi.fn(actual.removeLocalWorktreePath) } +}) vi.mock('../worktree-removal-leftover', async (importOriginal) => ({ ...(await importOriginal()), isUnregisteredRemovalLeftover: vi.fn(async () => true) @@ -115,6 +121,8 @@ vi.mock('../worktree-removal-leftover', async (importOriginal) => ({ const featureId = 'repo-1::/workspace/feature-wt' const GIT_ERROR = "error: failed to delete '/workspace/feature-wt': Operation not permitted" +const FOLLOW_UP_DELETE_ERROR = + "EPERM: operation not permitted, unlink '/workspace/feature-wt/locked'" function remove(args: Record): Promise { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: worktrees:remove resolves a RemoveWorktreeResult. @@ -182,15 +190,17 @@ describe('a failed delete Git no longer registers, over desktop IPC', () => { listWorktreesMock.mockResolvedValue([main]) throw new Error(GIT_ERROR) }) + // Orca's follow-up delete of the folder Git left also fails, so the row stays listed. + vi.mocked(removeLocalWorktreePath).mockRejectedValueOnce(new Error(FOLLOW_UP_DELETE_ERROR)) - await expect(remove({ worktreeId: featureId })).rejects.toThrow(/Operation not permitted/) + await expect(remove({ worktreeId: featureId })).rejects.toThrow(FOLLOW_UP_DELETE_ERROR) await _settlePendingWorktreeRemovalsForTests() expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'remove', pushTarget.remoteName], { cwd: '/workspace/repo' }) expect(await listFeature()).toMatchObject({ - removalError: expect.stringMatching(/Operation not permitted/) + removalError: expect.stringContaining(FOLLOW_UP_DELETE_ERROR) }) }) diff --git a/src/main/ipc/worktrees-local-create-flow.test.ts b/src/main/ipc/worktrees-local-create-flow.test.ts index 15cb18ab13d..0e1053c9b0f 100644 --- a/src/main/ipc/worktrees-local-create-flow.test.ts +++ b/src/main/ipc/worktrees-local-create-flow.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { resolve } from 'node:path' +import { SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV } from '../../shared/setup-agent-sequencing' +import type { CreateWorktreeResult } from '../../shared/worktree/create-types' import { resolveRegisteredWorktreePath } from './registered-worktree-roots-cache' import { computeWorkspaceRootAsync } from './worktree-logic' import type * as WorktreeLogic from './worktree-logic' @@ -779,15 +781,17 @@ describe('registerWorktreeHandlers', () => { request_kind: 'new' } } - })) as { setup?: { command?: string; runnerScriptPath: string } } + })) as { setup?: CreateWorktreeResult['setup'] } expect(result.setup).toEqual( expect.objectContaining({ runnerScriptPath: 'C:\\workspace\\repo\\.git\\orca\\setup-runner.sh', - command: expect.stringContaining('bash /mnt/c/workspace/repo/.git/orca/setup-runner.sh') + command: `bash -lc 'eval "\${${SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV}:?missing}"'` }) ) - expect(result.setup?.command).toContain('printf') + expect(result.setup?.envVars[SETUP_AGENT_SEQUENCE_SETUP_SCRIPT_ENV]).toContain( + 'bash /mnt/c/workspace/repo/.git/orca/setup-runner.sh' + ) }) it('opens Setup beside the startup terminal without surfacing the workspace', async () => { diff --git a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts index 7cd7941d0b7..5581eab1a0e 100644 --- a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts +++ b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts @@ -16,7 +16,7 @@ import { } from '../../../git/worktree' import { getWorktreeSharedLinkPaths } from '../../../git/worktree-shared-directories' import { cleanupLocalOrphanedWorktreeDirectory } from '../../../local-orphaned-worktree-cleanup' -import { recoverLocalWindowsWorktreeRemoval } from '../../../local-worktree-removal-recovery' +import { recoverPartialLocalWorktreeRemoval } from '../../../local-worktree-removal-recovery' import { withWorktreeRemoveStageSpan } from '../../../observability/instrumentation' import { assertNestedWorktreeRemovalApproval } from '../../../nested-worktree-removal-plan' import { findRegisteredDeletableWorktree } from '../../../worktree-removal-safety' @@ -233,8 +233,8 @@ async function finishLocalWorktreeRemoval({ if (usesNativeWindowsRemoval(canonicalWorktreePath, localWorktreeGitOptions)) { throw error } - // Git for Windows may deregister before recursive filesystem deletion fails. - const recoveredRemovalResult = await recoverLocalWindowsWorktreeRemoval({ + // Git deregisters even when its recursive filesystem deletion fails partway. + const recoveredRemovalResult = await recoverPartialLocalWorktreeRemoval({ error, force: args.force ?? false, canonicalWorktreePath, diff --git a/src/main/ipc/wsl-guest-windows-drive-path.ts b/src/main/ipc/wsl-guest-windows-drive-path.ts index b3712f77f4f..d641556ffe3 100644 --- a/src/main/ipc/wsl-guest-windows-drive-path.ts +++ b/src/main/ipc/wsl-guest-windows-drive-path.ts @@ -79,6 +79,11 @@ export function readGuestWindowsDriveMounts(): readonly string[] { return mounts } +/** Stand in for /proc/mounts so call-site tests can model a Windows drive; null re-reads. */ +export function _setGuestWindowsDriveMountsForTests(mounts: readonly string[] | null): void { + cachedGuestMounts = mounts +} + /** Keep CLI launches consistent with detection by removing Windows drive PATH entries only in WSL-host orcad. */ export function guestNativePathEnv( pathEnv: string | null | undefined, diff --git a/src/main/ipc/wsl-host-handlers-startup-reconcile.test.ts b/src/main/ipc/wsl-host-handlers-startup-reconcile.test.ts new file mode 100644 index 00000000000..bb3d6e2c11d --- /dev/null +++ b/src/main/ipc/wsl-host-handlers-startup-reconcile.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const order = vi.hoisted(() => ({ calls: new Array(), serving: true })) +vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, + ipcMain: { removeHandler: vi.fn(), handle: vi.fn() } +})) +vi.mock('../wsl/wsl-host-gate', async (importOriginal) => ({ + ...(await importOriginal>()), + wslHostsServing: () => order.serving +})) +vi.mock('../../shared/runtime-environment-wsl-host-store', async (importOriginal) => ({ + ...(await importOriginal>()), + reconcileWslHostBridgePorts: () => { + order.calls.push('reconcile') + return [] + } +})) +vi.mock('../wsl/wsl-host-connector', () => ({ createWslHostConnector: vi.fn() })) +vi.mock('../wsl/wsl-host-e2e-fake-connector', () => ({ + readFakeWslHostsConfig: () => ({ serverFiles: 'present' }), + createFakeWslHostConnector: () => { + order.calls.push('connector') + return { + connect: async () => { + order.calls.push('connect') + } + } + } +})) +vi.mock('../wsl/wsl-orphan-holder-release', () => ({ + releaseUnwantedWslHolders: async () => {}, + wslHolderKeepPolicy: () => () => true +})) +vi.mock('./wsl-host-automation-wake-wiring', () => ({ createWslHostAutomationWake: () => null })) +vi.mock('../wsl/wsl-host-service', () => ({ + WslHostService: class { + connector: { connect: (distro: string) => Promise } | null = null + attach(connector: { connect: (distro: string) => Promise }): void { + this.connector = connector + } + handleConnectionChange(): void {} + isKnownDistro(): boolean { + return true + } + hasUserVisibleWork(): boolean { + return false + } + // Startup's first bridge work: adopting holders, then any reconnect. + async start(): Promise { + order.calls.push('start') + await this.connector?.connect('Ubuntu') + } + } +})) +const instance = vi.hoisted((): { service: unknown } => ({ service: null })) +vi.mock('../wsl/wsl-host-service-instance', () => ({ + getWslHostService: () => instance.service, + setWslHostService: (service: unknown) => { + instance.service = service + } +})) + +import { registerWslHostHandlers } from './wsl-host-handlers' + +function register(): void { + registerWslHostHandlers({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: startup reads settings only through onSettingsChanged. + store: { getSettings: () => ({}), onSettingsChanged: vi.fn() } as never, + getUserDataPath: () => '/user-data', + invalidateTransport: vi.fn() + }) +} + +// A crash between a pairing save's two writes hides the host unless its record is realigned first. +describe('WSL host startup: the bridge-port reconcile', () => { + afterEach(() => { + order.calls = [] + order.serving = true + instance.service = null + }) + + it('realigns saved records before the connector exists or any bridge connects', async () => { + register() + await vi.waitFor(() => expect(order.calls).toContain('connect')) + expect(order.calls).toEqual(['reconcile', 'connector', 'start', 'connect']) + }) + + it('reads and writes no record while WSL hosts are not serving', () => { + order.serving = false + register() + expect(order.calls).toEqual([]) + expect(instance.service).toBeNull() + }) +}) diff --git a/src/main/ipc/wsl-host-handlers-user-actions.test.ts b/src/main/ipc/wsl-host-handlers-user-actions.test.ts index dff18aeb3b5..490414ef8c8 100644 --- a/src/main/ipc/wsl-host-handlers-user-actions.test.ts +++ b/src/main/ipc/wsl-host-handlers-user-actions.test.ts @@ -83,7 +83,7 @@ describe('WSL host IPC: the user Add and Remove (D3a)', () => { expect(heard).toEqual([{ kind: 'added', distro: 'Ubuntu' }]) }) - it('refuses an Add in serve-only, keeping saved hosts usable', async () => { + it('refuses an Add in serve-only and says so in its capability, keeping saved hosts usable', async () => { vi.stubEnv('ORCA_INTERNAL_WSL_HOSTS', undefined) register() @@ -92,6 +92,9 @@ describe('WSL host IPC: the user Add and Remove (D3a)', () => { kind: 'disabled' }) expect(service.add).not.toHaveBeenCalled() + expect(await handlers.get('wslHosts:getCapability')?.({})).toMatchObject({ + acceptsNewWork: false + }) await handlers.get('wslHosts:remove')?.({}, { environmentId: 'wsl:Ubuntu' }) expect(service.remove).toHaveBeenCalledWith('wsl:Ubuntu') }) diff --git a/src/main/ipc/wsl-host-handlers.ts b/src/main/ipc/wsl-host-handlers.ts index 28496d6306b..1fddb4c9b65 100644 --- a/src/main/ipc/wsl-host-handlers.ts +++ b/src/main/ipc/wsl-host-handlers.ts @@ -1,4 +1,5 @@ import { BrowserWindow, ipcMain } from 'electron' +import { abortWhenRendererGone } from './renderer-lifetime-abort' import { noteWslHostUserAction } from '../wsl/wsl-host-user-actions' import { WSL_HOST_STATUS_CHANNEL, @@ -29,6 +30,7 @@ import { getRuntimeEnvironmentStatus } from './runtime-environments/runtime-envi import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' import { isRemoteRuntimeConnectionReady } from './runtime-environments/runtime-environment-request-connections' import { resolveEnvironment } from '../../shared/runtime-environment-store' +import { reconcileWslHostBridgePorts } from '../../shared/runtime-environment-wsl-host-store' import { getPreferredPairedRuntimeConnection } from '../../shared/runtime-environments' import { requestOrcadTerminalCensus } from '../ssh/orcad-terminal-census-client' import type { WslHostRuntimeAccess } from '../wsl/wsl-host-server-stop' @@ -120,6 +122,14 @@ function createService(args: WslHostHandlerArgs): WslHostService | null { if (process.platform !== 'win32' && !fake) { return null } + // Before any bridge connects or the window lists servers: a crash mid-save must not hide a host. + try { + for (const environmentId of reconcileWslHostBridgePorts(args.getUserDataPath())) { + console.warn(`[wsl-hosts] Realigned ${environmentId}'s bridge port with its pairing.`) + } + } catch (error) { + console.warn('[wsl-hosts] Could not check WSL host records against their pairings:', error) + } let automationWake: WslHostAutomationWake | null = null const created = new WslHostService({ userDataPath: args.getUserDataPath, @@ -255,7 +265,8 @@ export function registerWslHostHandlers(args: WslHostHandlerArgs): void { ) => wsl.connect(request.environmentId, wslHostConnectOptions(request)) ) ipcMain.handle('wslHosts:getCapability', (): WslHostCapability => ({ - serverFiles: wsl.hasServerFiles() + serverFiles: wsl.hasServerFiles(), + acceptsNewWork: wslHostsGateOpen() })) ipcMain.handle('wslHosts:getStatuses', () => wsl.getStatuses()) const visibleWork = new WslHostVisibleWorkByWindow() @@ -264,7 +275,12 @@ export function registerWslHostHandlers(args: WslHostHandlerArgs): void { const windowId = sender.id const ids = Array.isArray(request.environmentIds) ? request.environmentIds : [] if (!visibleWork.has(windowId)) { - sender.once('destroyed', () => wsl.setVisibleWork(visibleWork.forget(windowId))) + const lifetime = abortWhenRendererGone(sender) + lifetime.signal.addEventListener( + 'abort', + () => wsl.setVisibleWork(visibleWork.forget(windowId)), + { once: true } + ) } wsl.setVisibleWork(visibleWork.report(windowId, ids)) }) diff --git a/src/main/ipc/wsl-host-visible-work-document-lifetime.test.ts b/src/main/ipc/wsl-host-visible-work-document-lifetime.test.ts new file mode 100644 index 00000000000..ee77cea5e9d --- /dev/null +++ b/src/main/ipc/wsl-host-visible-work-document-lifetime.test.ts @@ -0,0 +1,144 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' +const environment = vi.hoisted(() => ({ + handlers: new Map unknown>(), + getService: vi.fn() +})) +vi.mock('electron', () => ({ + ipcMain: { + removeHandler: vi.fn(), + handle: (name: string, fn: (event: unknown, request: unknown) => unknown) => + environment.handlers.set(name, fn) + }, + BrowserWindow: { getAllWindows: () => [] } +})) +vi.mock('../wsl/wsl-host-connector', () => ({ createWslHostConnector: () => undefined })) +vi.mock('../wsl/wsl-orphan-holder-release', () => ({ + releaseUnwantedWslHolders: () => undefined, + wslHolderKeepPolicy: () => undefined +})) +vi.mock('../wsl/wsl-host-e2e-fake-connector', () => ({ + createFakeWslHostConnector: () => undefined, + readFakeWslHostsConfig: () => undefined +})) +vi.mock('../orcad/orcad-artifact-materializer', () => ({ hasOrcadTemplate: () => undefined })) +vi.mock('./wsl-host-automation-wake-wiring', () => ({ + createWslHostAutomationWake: () => undefined +})) +vi.mock('../wsl/wsl-host-gate', () => ({ wslHostsGateOpen: () => undefined })) +vi.mock('../wsl/wsl-host-service-instance', () => ({ + getWslHostService: environment.getService, + setWslHostService: () => undefined +})) +vi.mock('./runtime-environments/runtime-environment-removal-cleanup', () => ({ + retireRemovedRuntimeEnvironment: () => undefined +})) +vi.mock('./runtime-environments/runtime-environment-status-probe', () => ({ + getRuntimeEnvironmentStatus: () => undefined +})) +vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: () => undefined +})) +vi.mock('./runtime-environments/runtime-environment-request-connections', () => ({ + isRemoteRuntimeConnectionReady: () => undefined +})) +vi.mock('../ssh/orcad-terminal-census-client', () => ({ + requestOrcadTerminalCensus: () => undefined +})) +vi.mock('../wsl/wsl-orcad-host-account-push', () => ({ + changesWslHostAccounts: () => undefined, + pushWslOrcadHostAccountEnv: () => undefined +})) +vi.mock('../wsl/wsl-orcad-host-environments', () => ({ wslOrcadHostSupports: () => undefined })) +vi.mock('../wsl/wsl-host-connection-record', () => ({ + readWslHostRecordsQuietly: () => [ + { environmentId: 'wsl:ubuntu', distro: 'Ubuntu' }, + { environmentId: 'wsl:debian', distro: 'Debian' } + ], + persistWslHostConnection: () => false, + toWslHostStatus: () => ({}) +})) +import { WslHostService } from '../wsl/wsl-host-service' +import { registerWslHostHandlers } from './wsl-host-handlers' + +class Sender extends EventEmitter { + constructor(readonly id: number) { + super() + } +} + +function setup() { + const service = new WslHostService({ + userDataPath: () => 'unused', + isEnabled: () => true, + hasServerFiles: () => true, + publish: vi.fn(), + pairingChanged: vi.fn(), + ready: vi.fn(), + removed: vi.fn() + }) + environment.getService.mockReturnValue(service) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The adopted service avoids startup, and visible-work reports never read the store. + const store = {} as never + registerWslHostHandlers({ store, getUserDataPath: () => 'unused', invalidateTransport: vi.fn() }) + const handler = environment.handlers.get('wslHosts:setVisibleWork') + if (!handler) { + throw new Error('Missing visible-work handler') + } + return { + service, + report: (sender: Sender, ids: string[]) => handler({ sender }, { environmentIds: ids }) + } +} + +describe('WSL visible work document ownership', () => { + beforeEach(() => environment.handlers.clear()) + it.each(['destroyed', 'render-process-gone', 'did-navigate'])( + 'releases a retired document and accepts its replacement after %s', + (event) => { + const { service, report } = setup() + const sender = new Sender(9) + report(sender, ['wsl:ubuntu']) + expect(service.hasUserVisibleWork('Ubuntu')).toBe(true) + sender.emit(event) + expect(service.hasUserVisibleWork('Ubuntu')).toBe(false) + expect(sender.eventNames()).toEqual([]) + report(sender, ['wsl:ubuntu']) + expect(service.hasUserVisibleWork('Ubuntu')).toBe(true) + expect(sender.listenerCount('did-navigate')).toBe(1) + sender.emit('destroyed') + expect(service.hasUserVisibleWork('Ubuntu')).toBe(false) + } + ) + + it('preserves same-document navigation and another window demand', () => { + const { service, report } = setup() + const sender = new Sender(9) + const other = new Sender(10) + report(sender, ['wsl:ubuntu']) + report(other, ['wsl:debian']) + sender.emit('did-navigate-in-page', {}, '#section', true) + expect(service.hasUserVisibleWork('Ubuntu')).toBe(true) + sender.emit('render-process-gone') + expect(service.hasUserVisibleWork('Ubuntu')).toBe(false) + expect(service.hasUserVisibleWork('Debian')).toBe(true) + other.emit('destroyed') + expect(service.hasUserVisibleWork('Debian')).toBe(false) + }) + + it('bounds listeners through repeated reports and ten replacement documents', () => { + const { service, report } = setup() + const sender = new Sender(9) + for (let index = 0; index < 10; index++) { + report(sender, ['wsl:ubuntu']) + report(sender, []) + report(sender, ['wsl:ubuntu']) + expect(sender.listenerCount('destroyed')).toBe(1) + expect(sender.listenerCount('did-navigate')).toBe(1) + expect(sender.listenerCount('render-process-gone')).toBe(1) + sender.emit(index % 2 === 0 ? 'did-navigate' : 'render-process-gone') + expect(sender.eventNames()).toEqual([]) + expect(service.hasUserVisibleWork('Ubuntu')).toBe(false) + } + }) +}) diff --git a/src/main/ipc/wsl-move-distro-in-use.ts b/src/main/ipc/wsl-move-distro-in-use.ts new file mode 100644 index 00000000000..e83d9978f55 --- /dev/null +++ b/src/main/ipc/wsl-move-distro-in-use.ts @@ -0,0 +1,57 @@ +/** Whether the move orchestrator still has a reason to keep a distro's record (D3a-2 pruning). */ +import { readWslHostDeployments } from '../../shared/wsl-host-deployment-store' +import { wslMoveJournalKey } from '../../shared/wsl-move/wsl-move-cutover' +import { parseWslUncPath } from '../../shared/wsl-paths' +import type { Store } from '../persistence' +import { + isLocalWslMoveRow, + wslMoveHostDistro +} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' +import { defaultWslOrcadEnvironmentId } from '../wsl/wsl-orcad-deploy' + +/** + * A bridge project of the distro (local, on its UNC path, not moved) or its WSL host record. A + * host file that cannot be read counts as in use: a failed read never makes a distro look gone. + */ +export function isDistroInUse( + store: Pick, + userDataPath: string, + distro: string +): boolean { + const environmentId = defaultWslOrcadEnvironmentId(distro) + try { + const hosts = readWslHostDeployments(userDataPath) + if ( + hosts.unreadableEnvironmentIds.has(environmentId) || + hosts.deployments.some((record) => record.environmentId === environmentId) + ) { + return true + } + } catch { + // A host file that cannot be read never makes a distro look gone. + return true + } + const key = wslMoveJournalKey(distro) + const onDistro = (path: string): boolean => { + const unc = parseWslUncPath(path) + return unc !== null && wslMoveJournalKey(unc.distro) === key + } + return ( + store + .getRepos() + .some( + (repo) => + isLocalWslMoveRow(repo) && + onDistro(repo.path) && + wslMoveHostDistro({ repoId: repo.id }) === null + ) || + store + .getFolderWorkspaces() + .some( + (folder) => + isLocalWslMoveRow(folder) && + onDistro(folder.folderPath) && + wslMoveHostDistro({ folderWorkspaceId: folder.id }) === null + ) + ) +} diff --git a/src/main/ipc/wsl-move-driver-handlers.test.ts b/src/main/ipc/wsl-move-driver-handlers.test.ts index 63d12888ddd..239c2ec77ca 100644 --- a/src/main/ipc/wsl-move-driver-handlers.test.ts +++ b/src/main/ipc/wsl-move-driver-handlers.test.ts @@ -16,6 +16,10 @@ const driver = vi.hoisted(() => ({ cancelWslMove: vi.fn(() => true) })) vi.mock('../persistence/moving-wsl-projects/wsl-move-driver', () => driver) +const running = vi.hoisted(() => ({ any: false })) +vi.mock('../persistence/moving-wsl-projects/wsl-move-running-moves', () => ({ + isAnyWslMoveRunning: () => running.any +})) const track = vi.hoisted(() => vi.fn()) vi.mock('../telemetry/client', () => ({ track })) @@ -86,4 +90,13 @@ describe('WSL move driver IPC', () => { } expect(driver.moveProjectsToWslHost).not.toHaveBeenCalled() }) + + // The quit prompt asks this; with the gate closed it is always false, so nothing prompts. + it('says whether a move is running, and never with the gate closed', async () => { + running.any = true + expect(await invoke('wslMove:isRunning')).toBe(true) + vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '') + expect(await invoke('wslMove:isRunning')).toBe(false) + running.any = false + }) }) diff --git a/src/main/ipc/wsl-move-driver-wiring.ts b/src/main/ipc/wsl-move-driver-wiring.ts index a6ca02c965c..b13d4391e60 100644 --- a/src/main/ipc/wsl-move-driver-wiring.ts +++ b/src/main/ipc/wsl-move-driver-wiring.ts @@ -23,6 +23,9 @@ import { HistoryReader } from '../daemon/history-reader' import { orcadMigrationDestinationFor } from '../managed-server/lifecycle/orcad-runtime-conversion-wiring' import type { Store } from '../persistence' import { exportWslMoveManifest } from '../persistence/moving-wsl-projects/wsl-move-manifest-export' +import { ensureWslMoveDestinationBrowserLogins } from '../persistence/moving-wsl-projects/wsl-move-browser-cookie-copy' +import { activeBrowserRoutePartitionOrcaProfileId } from '../browser/browser-route-partition-binding-runtime' +import { wslHostBrowserRouteStorage } from '../browser/wsl-host-browser-route-partition' import { runGatedWslMoveDesktopRewritePass } from '../persistence/moving-wsl-projects/wsl-move-desktop-rewrite' import type { WslMoveDriverDeps, @@ -248,7 +251,12 @@ async function connectWslMoveHost( if (!service || !(await connectWslMoveHostService(service, userDataPath, distro, mode))) { return null } - const environment = resolveEnvironment(userDataPath, environmentId) + const { environment, notCarried } = ensureWslMoveDestinationBrowserLogins({ + resolveEnvironment: () => resolveEnvironment(userDataPath, environmentId), + resaveConnection: () => service.resaveConnection(environmentId), + orcaProfileId: activeBrowserRoutePartitionOrcaProfileId, + resolveHostStorage: wslHostBrowserRouteStorage + }) const status = await getRuntimeEnvironmentStatus(userDataPath, environmentId) if (!status.ok) { return null @@ -261,6 +269,7 @@ async function connectWslMoveHost( name: environment.name, ...(distroGuid ? { distroGuid } : {}), capabilities: status.result.capabilities ?? [], + ...(notCarried ? { browserLoginsNotCarried: notCarried } : {}), catalog: orcadMigrationDestinationFor(environment), commitWithBlobs: (manifest, expectedBlobs) => commitRemoteOrcadMigrationCatalog(pairingCode, manifest, { ...options, expectedBlobs }), diff --git a/src/main/ipc/wsl-move-handlers.ts b/src/main/ipc/wsl-move-handlers.ts index 54452117ca8..e5b6af68098 100644 --- a/src/main/ipc/wsl-move-handlers.ts +++ b/src/main/ipc/wsl-move-handlers.ts @@ -28,6 +28,7 @@ import { import type { WslMoveDriverDeps } from '../persistence/moving-wsl-projects/wsl-move-driver-ports' import { listUnfinishedWslMoves } from '../persistence/moving-wsl-projects/wsl-move-host-automations-rewrite' import { runTrackedWslMove } from '../telemetry/wsl-move-telemetry' +import { isAnyWslMoveRunning } from '../persistence/moving-wsl-projects/wsl-move-running-moves' import { wslHostsGateOpen, wslHostsServing } from '../wsl/wsl-host-gate' import type { WslMoveUndoPorts } from './wsl-move-undo-wiring' import { releaseWslMovedProjectHere } from './wsl-move-release-here' @@ -39,6 +40,7 @@ export const WSL_MOVE_HANDLER_CHANNELS = [ 'wslMove:start', 'wslMove:cancel', 'wslMove:listUnfinished', + 'wslMove:isRunning', 'wslMove:useProjectHereAgain' ] as const @@ -128,6 +130,8 @@ function registerWslMoveDriverHandlers( ipcMain.handle('wslMove:listUnfinished', (): WslMoveUnfinished[] => wslHostsServing() ? listUnfinishedWslMoves(getUserDataPath()) : [] ) + // The quit prompt's question; a quit now loses the run, which the next launch undoes. + ipcMain.handle('wslMove:isRunning', (): boolean => wslHostsGateOpen() && isAnyWslMoveRunning()) ipcMain.handle( 'wslMove:cancel', (event: RendererEvent, distro: unknown): boolean => diff --git a/src/main/ipc/wsl-move-orchestrator-host-connect.test.ts b/src/main/ipc/wsl-move-orchestrator-host-connect.test.ts index b023a276462..c40b47ed0f3 100644 --- a/src/main/ipc/wsl-move-orchestrator-host-connect.test.ts +++ b/src/main/ipc/wsl-move-orchestrator-host-connect.test.ts @@ -74,6 +74,7 @@ function orchestratorOverHost(connector: ReturnType) { ), hostRemovalPending: (distro) => wslHostRemovalPending(userDataPath, distro), hasHost: () => service.recordForEnvironment(environmentId) !== null, + isDistroInUse: () => true, isHostReady, preview: async (distro) => { await driverConnect(distro) @@ -99,7 +100,8 @@ function orchestratorOverHost(connector: ReturnType) { save: () => {}, schedule: () => () => {}, track: () => {}, - publish: () => {} + publish: () => {}, + runAsUserAct: (_distro, act) => act() }) return { orchestrator, service, driverConnect } } diff --git a/src/main/ipc/wsl-move-orchestrator-wiring.test.ts b/src/main/ipc/wsl-move-orchestrator-wiring.test.ts index e981480bfd7..4e17f124a78 100644 --- a/src/main/ipc/wsl-move-orchestrator-wiring.test.ts +++ b/src/main/ipc/wsl-move-orchestrator-wiring.test.ts @@ -41,12 +41,26 @@ vi.mock('../../shared/runtime-environment-wsl-host-store', () => ({ findWslHostDeployment: (_userData: string, environmentId: string) => deployments.get(environmentId) ?? null })) +const hostFile = vi.hoisted(() => ({ unreadable: false })) +vi.mock('../../shared/wsl-host-deployment-store', () => ({ + readWslHostDeployments: () => { + if (hostFile.unreadable) { + throw new Error('orca-wsl-host-deployments.json is not valid') + } + return { deployments: [], unreadableEnvironmentIds: new Set() } + } +})) vi.mock('../wsl/wsl-distro-registry-id', () => ({ readWslDistroRegistrations: async () => null })) vi.mock('../wsl/wsl-orcad-deploy', () => ({ defaultWslOrcadEnvironmentId: (distro: string) => `wsl:${distro}` })) vi.mock('../wsl-background-distro-gate', () => ({ - readConfirmedRunningWslDistros: async () => host.running + readConfirmedRunningWslDistros: async () => host.running, + // The user-act gate notes a woken distro when the act settles. + noteWslDistroWoken: vi.fn(), + noteWslDistroMayHaveStopped: vi.fn(), + noteWslDistrosRunning: vi.fn(), + readWslDistroRunningState: vi.fn(async () => 'running') })) vi.mock('../wsl/wsl-host-service-instance', () => ({ getWslHostService: () => ({ @@ -134,10 +148,16 @@ function requestIdOf(payload: unknown): string { : '' } +/** The profile's projects: one bridge project on Ubuntu keeps its record from being pruned. */ +const profile = vi.hoisted(() => ({ + repos: [{ id: 'r1', path: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app', connectionId: null }] +})) + async function register(): Promise { const { registerWslMoveOrchestrator } = await import('./wsl-move-orchestrator-wiring') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The driver is mocked; the wiring only passes deps through. - registerWslMoveOrchestrator({} as never, () => ({ now: () => new Date(0) }) as never) + const store = { getRepos: () => profile.repos, getFolderWorkspaces: () => [] } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The wiring reads only the projects of the store, and the driver is mocked. + registerWslMoveOrchestrator(store as never, () => ({ now: () => new Date(0) }) as never) } /** Answers every slept-pane request the window has been sent. */ @@ -171,6 +191,7 @@ beforeEach(() => { host.running = { status: 'confirmed', distros: ['Ubuntu'] } host.added = [] releases.listeners.length = 0 + hostFile.unreadable = false hostActions.listeners.length = 0 deployments.clear() store.reads = 0 @@ -199,10 +220,12 @@ describe('WSL move orchestrator wiring', () => { ] await register() await answerWindow() - expect(driver.previewWslMove).toHaveBeenCalledWith(expect.anything(), { - distro: 'Ubuntu', - sleptPanes - }) + // The automatic mover's preview settles a move an update or crash interrupted, finishing at restart. + expect(driver.previewWslMove).toHaveBeenCalledWith( + expect.anything(), + { distro: 'Ubuntu', sleptPanes }, + { settleInterrupted: 'finish-at-restart' } + ) expect(driver.moveProjectsToWslHost).toHaveBeenCalledWith(expect.anything(), { distro: 'Ubuntu', sleptPanes @@ -306,7 +329,10 @@ describe('WSL move orchestrator wiring', () => { } const records = await handlers.get('wslMoveOrchestrator:list')?.({}) expect(records).toEqual([ - expect.objectContaining({ distro: 'Ubuntu', state: { kind: 'parked', reason: 'declined' } }) + expect.objectContaining({ + distro: 'Ubuntu', + state: { kind: 'parked', reason: 'declined', cause: 'released-here' } + }) ]) }) @@ -427,4 +453,94 @@ describe('WSL move orchestrator wiring', () => { expect(driver.previewWslMove).toHaveBeenCalledTimes(1) expect(driver.moveProjectsToWslHost).not.toHaveBeenCalled() }) + + // Pre-review #3: a host file that cannot be read must never make a distro look gone. + it('prunes nothing when the WSL host file cannot be read', async () => { + vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1') + hostFile.unreadable = true + const savedRepos = profile.repos + profile.repos = [] + store.records = new Map([ + [ + 'local-wsl:ubuntu', + { + distro: 'Ubuntu', + state: { kind: 'idle' }, + attempts: 0, + appVersion: '1.0.0', + updatedAt: 0 + } + ] + ]) + try { + await register() + expect(await handlers.get('wslMoveOrchestrator:list')?.({})).toEqual([ + expect.objectContaining({ distro: 'Ubuntu' }) + ]) + } finally { + profile.repos = savedRepos + } + }) + + it('prunes a distro with no host and no bridge projects once the file reads', async () => { + vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1') + const savedRepos = profile.repos + profile.repos = [] + store.records = new Map([ + [ + 'local-wsl:ubuntu', + { + distro: 'Ubuntu', + state: { kind: 'idle' }, + attempts: 0, + appVersion: '1.0.0', + updatedAt: 0 + } + ] + ]) + try { + await register() + expect(await handlers.get('wslMoveOrchestrator:list')?.({})).toEqual([]) + } finally { + profile.repos = savedRepos + } + }) + + // #34632's stopped-distro gates: Check again runs the driver as the user's act on its distro, + // so its reads of a just-connected distro pass; a wake's reads stay background work. + it('runs the driver for Check again as the user act, and for a wake as background work', async () => { + vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1') + const { isWslUserActFor } = await import('../wsl/wsl-user-act-scope') + const seen: boolean[] = [] + const original = driver.previewWslMove.getMockImplementation() + driver.previewWslMove.mockImplementation( + async (_deps: unknown, request: { distro: string }) => { + seen.push(isWslUserActFor(request.distro)) + return { + outcome: 'ready', + distro: request.distro, + repoIds: ['r1'], + folderWorkspaceIds: [], + changed: [], + heldByHost: [], + refused: [], + blockers: [] + } + } + ) + host.statuses = [ + { distro: 'Ubuntu', state: 'ready', environmentId: 'wsl:Ubuntu', detail: null } + ] + await register() + await answerWindow() + await handlers.get('wslMoveOrchestrator:userAction')?.( + { sender: { id: MAIN_WINDOW_ID } }, + { distro: 'Ubuntu', action: 'retry' } + ) + await answerWindow() + if (original) { + driver.previewWslMove.mockImplementation(original) + } + expect(seen).toEqual([false, true]) + }) }) diff --git a/src/main/ipc/wsl-move-orchestrator-wiring.ts b/src/main/ipc/wsl-move-orchestrator-wiring.ts index 350727b88b7..72316dc491f 100644 --- a/src/main/ipc/wsl-move-orchestrator-wiring.ts +++ b/src/main/ipc/wsl-move-orchestrator-wiring.ts @@ -37,11 +37,13 @@ import { import { runTrackedWslMove } from '../telemetry/wsl-move-telemetry' import { readWslDistroRegistrations } from '../wsl/wsl-distro-registry-id' import { wslHostsGateOpen } from '../wsl/wsl-host-gate' +import { runAsWslUserAct } from '../wsl/wsl-unc-access-gate' import { getWslHostService } from '../wsl/wsl-host-service-instance' import { onWslHostUserAction } from '../wsl/wsl-host-user-actions' import { getTrustedUIRendererWebContents, getTrustedUIRendererWindow } from './ui' import { onWslMoveReleasedByUser, releaseWslMoveChainHere } from './wsl-move-release-here' import { createWslMoveUndoPorts } from './wsl-move-undo-wiring' +import { isDistroInUse } from './wsl-move-distro-in-use' import { answerWslMoveSleptPanes, requestSleptPanes } from './wsl-move-orchestrator-slept-panes' import { wslHostRemovalPending } from './wsl-move-host-connect' @@ -121,15 +123,17 @@ function createOrchestrator( appVersion: app.getVersion(), autoMoveEnabled: () => process.env[WSL_MOVE_ORCHESTRATOR_AUTO_ENV] !== '0', prepareHost: (distro, stillWanted) => prepareHost(userDataPath, distro, stillWanted), + isDistroInUse: (distro) => isDistroInUse(store, userDataPath, distro), hostRemovalPending: (distro) => wslHostRemovalPending(userDataPath, distro), hasHost: (distro) => getWslHostService()?.recordForEnvironment(defaultWslOrcadEnvironmentId(distro)) != null, isHostReady, - preview: async (distro) => - previewWslMove(driverDeps(), { - distro, - sleptPanes: await requestSleptPanes() - }), + preview: async (distro, userAsked) => + previewWslMove( + driverDeps(), + { distro, sleptPanes: await requestSleptPanes() }, + { settleInterrupted: userAsked ? 'finish-now' : 'finish-at-restart' } + ), start: async (distro, stillWanted) => { const sleptPanes = await requestSleptPanes() // The user may have released or snoozed the distro while the window answered. @@ -156,7 +160,8 @@ function createOrchestrator( }, track: (trigger, record, cause) => trackWslMoveOrchestrator(wslMoveOrchestratorEventProps(trigger, record, cause)), - publish + publish, + runAsUserAct: runAsWslUserAct }) } @@ -268,10 +273,12 @@ export function registerWslMoveOrchestrator( const created = createOrchestrator(store, driverDeps) orchestrator = created followHostReadiness(created) - onWslMoveReleasedByUser((distro) => created.releasedByUser(distro)) + onWslMoveReleasedByUser((distro) => created.releasedByUser(distro, 'released-here')) // A Remove is the user declining the host; only their own Add (or Retry) takes it back. onWslHostUserAction(({ kind, distro }) => - kind === 'removed' ? created.releasedByUser(distro) : created.hostAddedByUser(distro) + kind === 'removed' + ? created.releasedByUser(distro, 'removed') + : created.hostAddedByUser(distro) ) } catch (error) { console.warn('[wsl-move] Move orchestrator did not start:', error) diff --git a/src/main/ipc/wsl-move-partial-undo.test.ts b/src/main/ipc/wsl-move-partial-undo.test.ts new file mode 100644 index 00000000000..c5297f2db57 --- /dev/null +++ b/src/main/ipc/wsl-move-partial-undo.test.ts @@ -0,0 +1,119 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WslMoveCutover } from '../../shared/wsl-move/wsl-move-cutover' +import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../shared/wsl-host-internal-gate' +import { wslMoveCutoverFixture as cutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' +import { seedWslMoveCutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' +import { listWslMoveCutovers } from '../persistence/moving-wsl-projects/wsl-move-cutover-journal' +import { + isWslMoveProjectBlocked, + loadWslMoveFence, + resetWslMoveFenceForTests +} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' +import { setWslMoveReloadableWindow } from '../persistence/moving-wsl-projects/wsl-move-window-write-hold' +import { + registerWslMoveDesktopRewriteStore, + resetWslMoveDesktopRewriteStoresForTests +} from '../persistence/moving-wsl-projects/wsl-move-desktop-rewrite-stores' + +type Handler = (event: unknown, request?: unknown) => unknown + +const handlers = vi.hoisted(() => new Map()) +vi.mock('electron', () => ({ + ipcMain: { + removeHandler: (channel: string) => handlers.delete(channel), + handle: (channel: string, handler: Handler) => handlers.set(channel, handler) + } +})) + +import { registerWslMoveHandlers } from './wsl-move-handlers' + +const MAIN_WINDOW_ID = 7 +const useHere = (repoId: string) => + handlers.get('wslMove:useProjectHereAgain')?.( + { sender: { id: MAIN_WINDOW_ID, session: { flushStorageData: vi.fn() } } }, + { kind: 'repo', id: repoId } + ) + +let userDataPath: string +const touched: string[] = [] +const record = (step: string) => (move: WslMoveCutover) => { + touched.push(`${step}:${move.migrationId}`) +} + +beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'wsl-move-partial-undo-')) + vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1') + registerWslMoveDesktopRewriteStore({ id: 'renderer-a', side: 'renderer' }) + touched.length = 0 + // P moved first; Q, a different project, moved after it to the same host. + const rewritten = { rewrittenStores: ['renderer-a'] } + seedWslMoveCutover(userDataPath, { ...cutover('move-p', 'retained'), ...rewritten }) + seedWslMoveCutover(userDataPath, { + ...cutover('move-q', 'retained', { supersedesMigrationId: 'move-p' }, { repoIds: ['repo-q'] }), + ...rewritten + }) + loadWslMoveFence(userDataPath) + registerWslMoveHandlers( + () => userDataPath, + (senderId) => senderId === MAIN_WINDOW_ID, + undefined, + () => ({ + stopHostAutomations: async (move) => { + record('automations')(move) + return { outcome: 'stopped', restore: async () => {}, applyHere: () => () => {} } + }, + stopHostCopies: async (move) => { + record('copies')(move) + return 'stopped' + }, + refocusHere: record('refocus') + }) + ) + setWslMoveReloadableWindow(() => null) +}) +afterEach(() => { + vi.unstubAllEnvs() + resetWslMoveDesktopRewriteStoresForTests() + resetWslMoveFenceForTests() + rmSync(userDataPath, { recursive: true, force: true }) +}) + +const journal = () => + listWslMoveCutovers(userDataPath) + .map((move) => move.migrationId) + .toSorted() +const moved = (repoId: string) => isWslMoveProjectBlocked(undefined, { repoId }) + +// Flag-on checklist "Partial undo of an older move (P then Q)": undo P alone, with Q moved after it. +describe('undo of an older move while a newer one stands', () => { + it('refuses P, naming Q, and leaves both moves, their host copies and automations as they were', async () => { + expect(await useHere('repo-1')).toEqual({ + released: false, + reason: 'superseded', + newerMove: { repoIds: ['repo-q'], folderWorkspaceIds: [] } + }) + expect(touched).toEqual([]) + expect(journal()).toEqual(['move-p', 'move-q']) + expect(listWslMoveCutovers(userDataPath).map((move) => move.rewrittenStores)).toEqual([ + ['renderer-a'], + ['renderer-a'] + ]) + expect([moved('repo-1'), moved('repo-q')]).toEqual([true, true]) + }) + + it('brings Q back alone, then P, each touching only its own move on the host', async () => { + expect(await useHere('repo-q')).toMatchObject({ released: true, repoIds: ['repo-q'] }) + expect(touched).toEqual(['automations:move-q', 'copies:move-q', 'refocus:move-q']) + expect(journal()).toEqual(['move-p']) + expect([moved('repo-1'), moved('repo-q')]).toEqual([true, false]) + + touched.length = 0 + expect(await useHere('repo-1')).toMatchObject({ released: true, repoIds: ['repo-1'] }) + expect(touched).toEqual(['automations:move-p', 'copies:move-p', 'refocus:move-p']) + expect(journal()).toEqual([]) + expect(moved('repo-1')).toBe(false) + }) +}) diff --git a/src/main/ipc/wsl-move-release-here.test.ts b/src/main/ipc/wsl-move-release-here.test.ts index d86a7128b8d..eb6ea4bbf7f 100644 --- a/src/main/ipc/wsl-move-release-here.test.ts +++ b/src/main/ipc/wsl-move-release-here.test.ts @@ -18,6 +18,13 @@ const window = vi.hoisted(() => ({ steps: new Array() })) const releaseFails = vi.hoisted(() => ({ value: false })) +const host = vi.hoisted(() => ({ listed: true, keptForPeers: false })) +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: () => (host.listed ? [{ id: 'wsl:Ubuntu' }] : []) +})) +vi.mock('../wsl/wsl-host-kept-for-peers', () => ({ + wasWslHostKeptForPeers: () => host.keptForPeers +})) function move(migrationId: string, repoId: string): Move { return { @@ -90,6 +97,8 @@ beforeEach(() => { window.fencesReleased = 0 releaseFails.value = false window.steps = [] + host.listed = true + host.keptForPeers = false }) describe('releasing moved projects here', () => { @@ -119,6 +128,26 @@ describe('releasing moved projects here', () => { expect(window.reloads).toBe(1) }) + // R39: removed here but kept running for another Orca, so only re-adding the host reaches it. + it('says a removed host kept for another Orca needs re-adding, not just connecting', async () => { + host.listed = false + host.keptForPeers = true + const result = await releaseWslMoveChainHere('/user-data', 'Ubuntu', [], () => ({ + stopHostCopies: vi.fn(async () => 'unreachable' as const) + })) + expect(result).toMatchObject({ + released: false, + reason: 'host-unreachable', + detail: 'host-kept-for-peers' + }) + // A host still listed that just isn't answering keeps the plain refusal. + host.listed = true + const unanswered = await releaseWslMoveChainHere('/user-data', 'Ubuntu', [], () => ({ + stopHostCopies: vi.fn(async () => 'unreachable' as const) + })) + expect(unanswered).not.toHaveProperty('detail') + }) + // Review #2: only the user's "Use on this computer again" parks the distro; Restore does not. it('tells listeners about a user release and not about a Restore', async () => { const heard = vi.fn() diff --git a/src/main/ipc/wsl-move-release-here.ts b/src/main/ipc/wsl-move-release-here.ts index ac62337d888..ae3c3b9a7d5 100644 --- a/src/main/ipc/wsl-move-release-here.ts +++ b/src/main/ipc/wsl-move-release-here.ts @@ -24,6 +24,8 @@ import { } from '../persistence/moving-wsl-projects/wsl-move-window-write-hold' import type { WslMoveUndoPorts } from './wsl-move-undo-wiring' import { runWslMoveHostAutomationsExclusive } from '../persistence/moving-wsl-projects/wsl-move-undo-host-automations' +import { listEnvironments } from '../../shared/runtime-environment-store' +import { wasWslHostKeptForPeers } from '../wsl/wsl-host-kept-for-peers' const COMMITTED_FROM = WSL_MOVE_CUTOVER_PHASES.indexOf('destination-committed') @@ -150,6 +152,18 @@ async function releaseWslMovesHere( } } +/** R39: removed here but kept running for another Orca; only re-adding the host reaches it again. */ +function wslMoveHostKeptForPeers(userDataPath: string, move: WslMoveCutover): boolean { + return ( + wasWslHostKeptForPeers(userDataPath, move.destinationEnvironmentId) && + !listEnvironments(userDataPath).some((env) => env.id === move.destinationEnvironmentId) + ) +} + +function keptForPeersRefusal(): WslMoveUseLocallyResult { + return { released: false, reason: 'host-unreachable', detail: 'host-kept-for-peers' } +} + /** One move: host automations off, host terminals stopped, then released; refused, all undone. */ async function releaseOneMoveHere( userDataPath: string, @@ -163,6 +177,9 @@ async function releaseOneMoveHere( applyHere: () => () => {} } if (automations.outcome !== 'stopped') { + if (automations.outcome === 'unreachable' && wslMoveHostKeptForPeers(userDataPath, move)) { + return keptForPeersRefusal() + } return { released: false, reason: automations.outcome === 'unreachable' ? 'host-unreachable' : 'failed', @@ -174,6 +191,9 @@ async function releaseOneMoveHere( const stop = await ports.stopHostCopies(move).catch(() => 'unreachable' as const) if (stop !== 'stopped') { await automations.restore() + if (stop === 'unreachable' && wslMoveHostKeptForPeers(userDataPath, move)) { + return keptForPeersRefusal() + } return { released: false, reason: stop === 'unreachable' ? 'host-unreachable' : 'host-still-running' diff --git a/src/main/ipc/wsl-move-undo-host-connect.test.ts b/src/main/ipc/wsl-move-undo-host-connect.test.ts new file mode 100644 index 00000000000..30a42ab3592 --- /dev/null +++ b/src/main/ipc/wsl-move-undo-host-connect.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest' +import { getDefaultWorkspaceSession } from '../../shared/constants' +import { wslMoveCutoverFixture } from '../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' +import { createWslMoveUndoPorts } from './wsl-move-undo-wiring' + +// The real connectWslMoveHostService runs here; only the host's records and runtime are faked. +const host = vi.hoisted(() => ({ + pendingStop: false, + connect: vi.fn(async () => {}), + call: vi.fn(async (..._args: unknown[]): Promise => ({ + ok: true, + result: { terminals: [], truncated: false } + })) +})) +vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: (...args: unknown[]) => host.call(...args) +})) +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: () => [{ id: 'wsl:Ubuntu' }] +})) +vi.mock('../../shared/runtime-environment-wsl-host-store', () => ({ + findWslHostDeployment: () => + host.pendingStop ? { environmentId: 'wsl:ubuntu', pendingStop: { at: 1 } } : null +})) +vi.mock('../wsl/wsl-host-service-instance', () => ({ + getWslHostService: () => ({ + recordForEnvironment: () => ({ environmentId: 'wsl:ubuntu', distro: 'Ubuntu' }), + getStatuses: () => [], + connect: host.connect, + ensureForRuntimeCall: vi.fn() + }) +})) + +const store = { + getWorkspaceSession: () => getDefaultWorkspaceSession(), + patchWorkspaceSession: vi.fn(), + listAutomations: () => [], + updateAutomation: vi.fn() +} + +describe("undo's stop of the host's terminals: connecting the host", () => { + const move = wslMoveCutoverFixture('move-1', 'retained', {}, { repoIds: ['repo-a'] }) + + it('connects a host that is not serving, as the user’s act', async () => { + host.pendingStop = false + host.connect.mockClear() + expect(await createWslMoveUndoPorts(store, '/user-data').stopHostCopies(move)).toBe('stopped') + expect(host.connect).toHaveBeenCalledTimes(1) + }) + + it('never connects a host whose Remove is pending (E11)', async () => { + host.pendingStop = true + host.connect.mockClear() + host.call.mockClear() + await createWslMoveUndoPorts(store, '/user-data').stopHostCopies(move) + expect(host.connect).not.toHaveBeenCalled() + // It got past the removed-host check, so the skip is the pending Remove's. + expect(host.call).toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/wsl-move-undo-wiring.test.ts b/src/main/ipc/wsl-move-undo-wiring.test.ts index b95d843ef04..c5656dbad67 100644 --- a/src/main/ipc/wsl-move-undo-wiring.test.ts +++ b/src/main/ipc/wsl-move-undo-wiring.test.ts @@ -17,7 +17,12 @@ const host = vi.hoisted(() => ({ enabledOnHost: new Map(), listed: true, unreadable: false, - removalPending: false + removalPending: false, + connect: vi.fn(async (..._args: unknown[]): Promise => true), + keptForPeers: false +})) +vi.mock('../wsl/wsl-host-kept-for-peers', () => ({ + wasWslHostKeptForPeers: () => host.keptForPeers })) vi.mock('../../shared/runtime-environment-store', () => ({ listEnvironments: () => { @@ -28,8 +33,10 @@ vi.mock('../../shared/runtime-environment-store', () => ({ } })) vi.mock('./wsl-move-host-connect', () => ({ - wslHostRemovalPending: () => host.removalPending + wslHostRemovalPending: () => host.removalPending, + connectWslMoveHostService: (...args: unknown[]) => host.connect(...args) })) +vi.mock('../wsl/wsl-host-service-instance', () => ({ getWslHostService: () => ({}) })) vi.mock('./wsl-host-automation-disable', () => ({ readWslHostAutomationStates: async (_userData: string, _environmentId: string, ids: string[]) => Object.fromEntries(ids.map((id) => [id, host.enabledOnHost.get(id) ?? false])), @@ -146,6 +153,22 @@ describe("undo's host automation port", () => { ).toBe('stopped') expect(host.disabled).toEqual([]) }) + + // R39: another Orca on this computer kept the removed host's server, so the move's copies may run. + it('refuses a removed host whose server was kept for another Orca', async () => { + host.disabled = [] + host.listed = false + host.keptForPeers = true + try { + const { store } = storeWith() + const ports = createWslMoveUndoPorts(store, '/user-data') + expect((await ports.stopHostAutomations?.(move))?.outcome).toBe('unreachable') + expect(await ports.stopHostCopies(move)).toBe('unreachable') + expect(host.disabled).toEqual([]) + } finally { + host.keptForPeers = false + } + }) }) describe("undo's host automation port, refusing", () => { @@ -277,3 +300,42 @@ describe("undo's stop of the host's terminals", () => { }) }) }) + +// After a relaunch the host has no open work, so a background-only reconnect refused every undo. +describe("undo's connect to the host", () => { + const move = wslMoveCutoverFixture('move-1', 'retained', {}, { repoIds: ['repo-a'] }) + const store = { + getWorkspaceSession: () => getDefaultWorkspaceSession(), + patchWorkspaceSession: vi.fn(), + listAutomations: () => [], + updateAutomation: vi.fn() + } + + it('connects the host as the user’s act before asking it anything', async () => { + host.listed = true + host.connect.mockClear() + rpc.call.mockReset() + rpc.call.mockResolvedValue({ ok: true, result: { terminals: [], truncated: false } }) + const ports = createWslMoveUndoPorts(store, '/user-data') + expect((await ports.stopHostAutomations?.(move))?.outcome).toBe('stopped') + expect(await ports.stopHostCopies(move)).toBe('stopped') + expect(host.connect.mock.calls.map(([, , distro, mode]) => [distro, mode])).toEqual([ + [move.manifest.source.distro, 'user'], + [move.manifest.source.distro, 'user'] + ]) + }) + + it('refuses as unreachable, asking the host nothing, when it does not connect', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + host.listed = true + host.disabled = [] + host.connect.mockRejectedValueOnce(new Error('distro failed to start')) + host.connect.mockRejectedValueOnce(new Error('distro failed to start')) + rpc.call.mockReset() + const ports = createWslMoveUndoPorts(store, '/user-data') + expect(await ports.stopHostAutomations?.(move)).toEqual({ outcome: 'unreachable' }) + expect(await ports.stopHostCopies(move)).toBe('unreachable') + expect(host.disabled).toEqual([]) + expect(rpc.call).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/wsl-move-undo-wiring.ts b/src/main/ipc/wsl-move-undo-wiring.ts index d1fa804bc34..77d7efafad1 100644 --- a/src/main/ipc/wsl-move-undo-wiring.ts +++ b/src/main/ipc/wsl-move-undo-wiring.ts @@ -16,13 +16,15 @@ import { wslMoveReleasedSessionFocusPatch } from '../persistence/moving-wsl-proj import { applyWslMoveSessionFocus } from '../persistence/moving-wsl-projects/wsl-move-main-rewrite-stores' import { listEnvironments } from '../../shared/runtime-environment-store' import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +import { wasWslHostKeptForPeers } from '../wsl/wsl-host-kept-for-peers' import { stopWslMoveHostAutomations, wslMoveMovedAutomationIds, type WslMoveHostAutomationStop } from '../persistence/moving-wsl-projects/wsl-move-undo-host-automations' import { scheduleWslMoveRewriteRetry } from '../persistence/moving-wsl-projects/wsl-move-rewrite-retry' -import { wslHostRemovalPending } from './wsl-move-host-connect' +import { connectWslMoveHostService, wslHostRemovalPending } from './wsl-move-host-connect' +import { getWslHostService } from '../wsl/wsl-host-service-instance' import { disableWslHostAutomations, readWslHostAutomationStates, @@ -54,6 +56,21 @@ const HOST_TERMINAL_LIST_LIMIT = 10_000 const SLEEP_TIMEOUT_MS = 60_000 const LIST_TIMEOUT_MS = 10_000 +/** Undo is the user's act: after a relaunch a host with no open work connects first, as Connect would. */ +async function connectUndoHost(userDataPath: string, move: WslMoveCutover): Promise { + const service = getWslHostService() + if (!service) { + return true + } + try { + await connectWslMoveHostService(service, userDataPath, move.manifest.source.distro, 'user') + return true + } catch (error) { + console.warn('[wsl-move] The host did not connect for undo:', error) + return false + } +} + export function createWslMoveUndoPorts( store: Pick< Store, @@ -63,15 +80,21 @@ export function createWslMoveUndoPorts( ): WslMoveUndoPorts { return { stopHostCopies: async (move) => { - // A host the user removed ran its terminals down with it; nothing of the project runs there. + // A host the user removed ran its terminals down with it, unless its Remove kept the server + // running for another Orca (R39): then its copies may still run, and nothing here reaches them. if (!listEnvironments(userDataPath).some((env) => env.id === move.destinationEnvironmentId)) { - return 'stopped' + return wasWslHostKeptForPeers(userDataPath, move.destinationEnvironmentId) + ? 'unreachable' + : 'stopped' } const scope = wslMoveRewriteScope(wslMoveDesktopRewriteContext(userDataPath, move)) const local = store.getWorkspaceSession(LOCAL_EXECUTION_HOST_ID) const hostIds = [...new Set(Object.keys(local.tabsByWorktree).filter(scope.inScope))].map( (id) => scope.worktreeId(id) ) + if (!(await connectUndoHost(userDataPath, move))) { + return 'unreachable' + } const call = async (method: string, params: unknown, timeoutMs: number) => { try { return await callRuntimeEnvironment( @@ -129,16 +152,21 @@ export function createWslMoveUndoPorts( stopHostAutomations: async (move) => { // Inside a try: a throw here would otherwise escape past undo's spawn fence. try { - // A removed host took its automations with it. + // A removed host took its automations with it, unless another Orca keeps its server (R39). if ( !listEnvironments(userDataPath).some((env) => env.id === move.destinationEnvironmentId) ) { - return { outcome: 'stopped', restore: async () => {}, applyHere: () => () => {} } + return wasWslHostKeptForPeers(userDataPath, move.destinationEnvironmentId) + ? { outcome: 'unreachable' } + : { outcome: 'stopped', restore: async () => {}, applyHere: () => () => {} } } // E11: a Remove that could not prove the server stopped; the host is not to be touched. if (wslHostRemovalPending(userDataPath, move.manifest.source.distro)) { return { outcome: 'removal-pending' } } + if (!(await connectUndoHost(userDataPath, move))) { + return { outcome: 'unreachable' } + } const environmentId = move.destinationEnvironmentId const stop = await stopWslMoveHostAutomations( userDataPath, diff --git a/src/main/jira/authenticated-request-image-limit.test.ts b/src/main/jira/authenticated-request-image-limit.test.ts index e6e39fcde9a..334024b7e71 100644 --- a/src/main/jira/authenticated-request-image-limit.test.ts +++ b/src/main/jira/authenticated-request-image-limit.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { jiraRequestBinary, type JiraClientForSite } from './authenticated-request' -const { fetchImage } = vi.hoisted(() => ({ fetchImage: vi.fn() })) +const { fetchImage } = vi.hoisted(() => ({ fetchImage: vi.fn() })) vi.mock('../network/http-client', () => ({ getMainHttpClient: () => ({ fetch: fetchImage, proxySession: () => null }) })) @@ -18,7 +18,9 @@ const client: JiraClientForSite = { site: { id: 'site', siteUrl: 'https://jira.test', email: '', accountId: '', displayName: '' }, authorization: 'secret' } -beforeEach(() => fetchImage.mockReset()) +beforeEach(() => { + fetchImage.mockReset() +}) describe('bounded Jira attachment downloads', () => { it('rejects oversized declared bodies before consuming any bytes', async () => { @@ -31,6 +33,7 @@ describe('bounded Jira attachment downloads', () => { await expect(jiraRequestBinary(client, '/image', { maxBytes: 8 })).rejects.toThrow('byte limit') expect(cancel).toHaveBeenCalledOnce() expect(arrayBuffer).not.toHaveBeenCalled() + expect(fetchImage.mock.calls[0]?.[1]?.signal?.aborted).toBe(true) }) it('caps chunked bodies even when Content-Length is missing', async () => { let part = 0 @@ -47,8 +50,9 @@ describe('bounded Jira attachment downloads', () => { await expect(jiraRequestBinary(client, '/image', { maxBytes: 8 })).rejects.toThrow('byte limit') expect(cancel).toHaveBeenCalledOnce() expect(part).toBeLessThanOrEqual(4) + expect(fetchImage.mock.calls[0]?.[1]?.signal?.aborted).toBe(true) }) - it('returns bounded bytes and forwards caller cancellation to the HTTP client', async () => { + it('returns complete bytes and releases its transport without aborting the caller', async () => { const controller = new AbortController() fetchImage.mockResolvedValue( new Response(Uint8Array.from([1, 2, 3]), { headers: { 'content-type': 'image/png' } }) @@ -58,7 +62,71 @@ describe('bounded Jira attachment downloads', () => { ).toEqual({ data: Uint8Array.from([1, 2, 3]).buffer, contentType: 'image/png' }) expect(fetchImage).toHaveBeenCalledWith( 'https://jira.test/image', - expect.objectContaining({ signal: controller.signal }) + expect.objectContaining({ signal: expect.any(AbortSignal) }) ) + expect(fetchImage.mock.calls[0]?.[1]?.signal?.aborted).toBe(true) + expect(controller.signal.aborted).toBe(false) }) + it.each(['transport', 'body'] as const)( + 'preserves the original %s error while releasing its request', + async (failure) => { + const error = new Error('original failure') + fetchImage.mockImplementation(async () => { + if (failure === 'transport') { + throw error + } + return new Response( + new ReadableStream({ + start(controller) { + controller.error(error) + } + }) + ) + }) + await expect(jiraRequestBinary(client, '/image')).rejects.toBe(error) + expect(fetchImage.mock.calls[0]?.[1]?.signal?.aborted).toBe(true) + } + ) + it('releases a rejected HTTP response while keeping its Jira status', async () => { + fetchImage.mockResolvedValue(new Response('denied', { status: 403, statusText: 'Forbidden' })) + await expect(jiraRequestBinary(client, '/image')).rejects.toMatchObject({ status: 403 }) + expect(fetchImage.mock.calls[0]?.[1]?.signal?.aborted).toBe(true) + }) + it.each([false, true])( + 'forwards caller cancellation and its reason (already aborted=%s)', + async (alreadyAborted) => { + const caller = new AbortController() + const error = new Error('caller cancelled') + if (alreadyAborted) { + caller.abort(error) + } + const started = Promise.withResolvers() + fetchImage.mockImplementation(async (_url, init) => { + const signal = init?.signal + if (!signal) { + throw new Error('Expected request cancellation signal') + } + if (signal.aborted) { + throw signal.reason + } + return new Response( + new ReadableStream({ + start(controller) { + signal.addEventListener('abort', () => controller.error(signal.reason), { + once: true + }) + started.resolve() + } + }) + ) + }) + const reading = jiraRequestBinary(client, '/image', { signal: caller.signal }) + if (!alreadyAborted) { + await started.promise + caller.abort(error) + } + await expect(reading).rejects.toBe(error) + expect(fetchImage.mock.calls[0]?.[1]?.signal?.reason).toBe(error) + } + ) }) diff --git a/src/main/jira/authenticated-request.ts b/src/main/jira/authenticated-request.ts index 62798e1314c..75df2044d28 100644 --- a/src/main/jira/authenticated-request.ts +++ b/src/main/jira/authenticated-request.ts @@ -183,21 +183,30 @@ export async function jiraRequestBinary( headers.set('Accept', '*/*') headers.set('User-Agent', JIRA_API_USER_AGENT) headers.set('Authorization', client.authorization) - const response = await jiraFetch(requestUrl.toString(), { - headers, - signal: options.signal, - ...(isJiraGatewayBaseUrl(apiBaseUrl(client.site)) ? { redirect: 'error' as const } : {}) - }) - if (!response.ok) { - throw await toJiraApiError(response, requestUrl.toString()) - } - const contentType = response.headers.get('content-type') || 'application/octet-stream' - const bytes = await readFetchResponseBytesWithinLimit( - response, - options.maxBytes ?? 2 * 1024 * 1024 - ) - return { - data: Uint8Array.from(bytes).buffer, - contentType + const controller = new AbortController() + const signal = options.signal + ? AbortSignal.any([options.signal, controller.signal]) + : controller.signal + try { + const response = await jiraFetch(requestUrl.toString(), { + headers, + signal, + ...(isJiraGatewayBaseUrl(apiBaseUrl(client.site)) ? { redirect: 'error' as const } : {}) + }) + if (!response.ok) { + throw await toJiraApiError(response, requestUrl.toString()) + } + const contentType = response.headers.get('content-type') || 'application/octet-stream' + const bytes = await readFetchResponseBytesWithinLimit( + response, + options.maxBytes ?? 2 * 1024 * 1024 + ) + return { + data: Uint8Array.from(bytes).buffer, + contentType + } + } finally { + // Cancelling the web body alone can leave Chromium's native request unfinished. + controller.abort() } } diff --git a/src/main/jira/favourite-filters-transport.test.ts b/src/main/jira/favourite-filters-transport.test.ts new file mode 100644 index 00000000000..a25881a3ae2 --- /dev/null +++ b/src/main/jira/favourite-filters-transport.test.ts @@ -0,0 +1,179 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { FetchResponseBodyTooLargeError } from '../../shared/fetch-response-body' +import { setMainHttpClient } from '../network/http-client' +import type { JiraClientForSite } from './authenticated-request' +import { listFavouriteFilters } from './favourite-filters' +import { JiraApiError } from './jira-api-error' + +const { getClients } = vi.hoisted(() => ({ getClients: vi.fn() })) +vi.mock('./client', () => ({ getClients })) +vi.mock('../network/proxy-settings', () => ({ + ensureElectronProxyFromEnvironment: vi.fn().mockResolvedValue(undefined) +})) +vi.mock('../observability/tracer', () => ({ + withSpan: ( + _name: string, + run: (span: { setAttribute: () => void; addEvent: () => void }) => Promise + ) => run({ setAttribute: () => {}, addEvent: () => {} }) +})) + +const client: JiraClientForSite = { + site: { + id: 'site-1', + siteUrl: 'https://jira.test', + email: '', + displayName: 'Jira', + accountId: 'me' + }, + authorization: 'Bearer fixture-token' +} +const maxBytes = 2 * 1024 * 1024 +const filter = { id: '1', name: 'Mine', jql: 'assignee = currentUser()' } +const encoder = new TextEncoder() + +function installTransport(read: (signal: AbortSignal) => Promise) { + const started = Promise.withResolvers() + const aborted = vi.fn() + const fetch = vi.fn(async (_url: string, init?: RequestInit) => { + const signal = init?.signal + if (!signal) { + throw new Error('Expected an operation signal') + } + signal.addEventListener('abort', aborted, { once: true }) + started.resolve(signal) + return read(signal) + }) + setMainHttpClient({ fetch, proxySession: () => null }) + return { started: started.promise, aborted, fetch } +} + +beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers() + getClients.mockReturnValue([client]) +}) + +afterEach(() => { + setMainHttpClient(null) + vi.useRealTimers() +}) + +describe('favourite filter transport ownership', () => { + it.each(['declared', 'streamed'] as const)( + 'aborts a rejected %s oversized response without aborting the caller', + async (kind) => { + const cancel = vi.fn() + const body = new ReadableStream({ + start(controller) { + if (kind === 'streamed') { + controller.enqueue(new Uint8Array(maxBytes + 1)) + } + }, + cancel + }) + const response = new Response(body, { + headers: kind === 'declared' ? { 'content-length': String(maxBytes + 1) } : {} + }) + const transport = installTransport(async () => response) + const parent = new AbortController() + + await expect(listFavouriteFilters('site-1', parent.signal)).rejects.toEqual( + new FetchResponseBodyTooLargeError(maxBytes + 1, maxBytes) + ) + + expect(cancel).toHaveBeenCalledOnce() + expect(transport.aborted).toHaveBeenCalledOnce() + expect(parent.signal.aborted).toBe(false) + expect(vi.getTimerCount()).toBe(0) + } + ) + + it('consumes the complete JSON body before retiring a successful transport', async () => { + const body = new TransformStream() + const writer = body.writable.getWriter() + const transport = installTransport(async () => new Response(body.readable)) + const parent = new AbortController() + const finished = vi.fn() + const read = listFavouriteFilters('site-1', parent.signal).finally(finished) + const signal = await transport.started + + await writer.write(encoder.encode('[')) + expect(signal.aborted).toBe(false) + expect(finished).not.toHaveBeenCalled() + await writer.write(encoder.encode(`${JSON.stringify(filter)}]`)) + expect(signal.aborted).toBe(false) + await writer.close() + + await expect(read).resolves.toEqual({ + filters: [{ ...filter, siteId: 'site-1' }], + truncated: false + }) + expect(transport.aborted).toHaveBeenCalledOnce() + expect(parent.signal.aborted).toBe(false) + expect(vi.getTimerCount()).toBe(0) + }) + + it.each(['transport', 'body'] as const)('preserves the original %s error', async (kind) => { + const error = new Error(`${kind} failed`) + const transport = installTransport(async () => { + if (kind === 'transport') { + throw error + } + return new Response( + new ReadableStream({ + start(controller) { + controller.error(error) + } + }) + ) + }) + const parent = new AbortController() + + await expect(listFavouriteFilters('site-1', parent.signal)).rejects.toBe(error) + + expect(transport.aborted).toHaveBeenCalledOnce() + expect(parent.signal.aborted).toBe(false) + expect(vi.getTimerCount()).toBe(0) + }) + + it('preserves HTTP status when an oversized error body is cancelled', async () => { + const cancel = vi.fn() + const transport = installTransport( + async () => + new Response(new ReadableStream({ cancel }), { + status: 403, + statusText: 'Forbidden', + headers: { 'content-length': String(maxBytes + 1) } + }) + ) + + await expect(listFavouriteFilters('site-1')).rejects.toEqual(new JiraApiError('Forbidden', 403)) + + expect(cancel).toHaveBeenCalledOnce() + expect(transport.aborted).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + }) + + it('cancels an active request at the deadline without aborting the caller', async () => { + const error = new DOMException('fixture request aborted', 'AbortError') + const transport = installTransport( + (signal) => + new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(error), { once: true }) + }) + ) + const parent = new AbortController() + const read = listFavouriteFilters('site-1', parent.signal) + const rejected = expect(read).rejects.toBe(error) + await transport.started + + await vi.advanceTimersByTimeAsync(24_999) + expect(transport.aborted).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + + await rejected + expect(transport.aborted).toHaveBeenCalledOnce() + expect(parent.signal.aborted).toBe(false) + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/src/main/jira/jira-read-failure.ts b/src/main/jira/jira-read-failure.ts index e2bee2285a7..37c9ea4e04a 100644 --- a/src/main/jira/jira-read-failure.ts +++ b/src/main/jira/jira-read-failure.ts @@ -6,7 +6,7 @@ export type JiraIssueSearchFailure = { auth: boolean } -/** Run against one signal that trips on the caller's abort or the request deadline. */ +/** Bound a fully consumed read by caller cancellation and a deadline, then retire its signal. */ export async function withJiraDeadline( signal: AbortSignal | undefined, timeoutMs: number, @@ -24,6 +24,7 @@ export async function withJiraDeadline( } finally { clearTimeout(timer) signal?.removeEventListener('abort', abort) + controller.abort() } } diff --git a/src/main/lib/html-to-pdf.test.ts b/src/main/lib/html-to-pdf.test.ts index 03ead7c66f1..96e739ccf76 100644 --- a/src/main/lib/html-to-pdf.test.ts +++ b/src/main/lib/html-to-pdf.test.ts @@ -25,6 +25,11 @@ vi.mock('electron', () => ({ once: (event: string, listener: (...args: unknown[]) => void) => { fake.handlers.set(event, listener) }, + removeListener: (event: string, listener: (...args: unknown[]) => void) => { + if (fake.handlers.get(event) === listener) { + fake.handlers.delete(event) + } + }, executeJavaScript: fake.images, printToPDF: fake.print } @@ -67,6 +72,56 @@ afterEach(() => { }) describe('htmlToPdf resource ownership', () => { + it('does not create a document for an already-aborted request', async () => { + const controller = new AbortController() + const error = new Error('request retired') + controller.abort(error) + + await expect(htmlToPdf(HTML, controller.signal)).rejects.toBe(error) + + expect(fake.write).not.toHaveBeenCalled() + expect(fake.construct).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(0) + }) + + it.each(['success', 'failure', 'abort'] as const)( + 'detaches conversion listeners after %s', + async (outcome) => { + const controller = new AbortController() + const added = vi.spyOn(controller.signal, 'addEventListener') + const removed = vi.spyOn(controller.signal, 'removeEventListener') + const images = Promise.withResolvers() + fake.images.mockReturnValueOnce(images.promise) + const error = new Error('request retired or renderer failed') + const result = htmlToPdf(HTML, controller.signal) + const assertion = + outcome === 'success' + ? expect(result).resolves.toBe(PDF) + : expect(result).rejects.toBe(error) + await vi.advanceTimersByTimeAsync(0) + expect(added).toHaveBeenCalledWith('abort', expect.any(Function), { once: true }) + + if (outcome === 'abort') { + controller.abort(error) + } else if (outcome === 'failure') { + images.reject(error) + } else { + images.resolve() + } + await assertion + + const listener = added.mock.calls.find(([event]) => event === 'abort')?.[1] + expect(listener).toBeTypeOf('function') + expect(removed).toHaveBeenCalledWith('abort', listener) + expect(fake.handlers.size).toBe(0) + expect(fake.files.size).toBe(0) + expect(fake.destroy).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + images.reject(new Error('late image failure')) + await Promise.resolve() + } + ) + it('removes the temporary document when window construction throws', async () => { const error = new Error('window construction failed') fake.construct.mockImplementation(() => { diff --git a/src/main/lib/html-to-pdf.ts b/src/main/lib/html-to-pdf.ts index 424d94c5578..440d0a46ded 100644 --- a/src/main/lib/html-to-pdf.ts +++ b/src/main/lib/html-to-pdf.ts @@ -27,13 +27,18 @@ new Promise((resolve) => { }) ` -export async function htmlToPdf(html: string): Promise { +export async function htmlToPdf(html: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const tempDir = app.getPath('temp') const tempPath = path.join(tempDir, `orca-export-${randomUUID()}.html`) // Exclusive creation prevents writing through pre-seated symlinks; EEXIST paths belong to someone else. try { - await writeFile(tempPath, html, { encoding: 'utf-8', flag: 'wx' }) + await writeFile(tempPath, html, { + encoding: 'utf-8', + flag: 'wx', + ...(signal ? { signal } : {}) + }) } catch (error) { if (isAlreadyExists(error)) { throw error @@ -43,6 +48,7 @@ export async function htmlToPdf(html: string): Promise { } try { + signal?.throwIfAborted() const win = new BrowserWindow({ show: false, webPreferences: { @@ -55,24 +61,49 @@ export async function htmlToPdf(html: string): Promise { }) let timer: NodeJS.Timeout | undefined + let removeAbortListener: (() => void) | undefined + let removeLoadListeners: (() => void) | undefined try { + const abortPromise = new Promise((_resolve, reject) => { + if (!signal) { + return + } + const abort = (): void => reject(signal.reason) + signal.addEventListener('abort', abort, { once: true }) + removeAbortListener = () => signal.removeEventListener('abort', abort) + if (signal.aborted) { + abort() + } + }) // Bound loading too: a non-yielding document script never fires load completion or failure. const timeoutPromise = new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new ExportTimeoutError()), EXPORT_TIMEOUT_MS) }) const loadAndPrint = (async (): Promise => { + signal?.throwIfAborted() const loadPromise = new Promise((resolve, reject) => { - win.webContents.once('did-finish-load', () => resolve()) - win.webContents.once('did-fail-load', (_event, errorCode, errorDescription) => { + const finish = (): void => resolve() + const fail = ( + _event: Electron.Event, + errorCode: number, + errorDescription: string + ): void => { reject(new Error(`Failed to load export document: ${errorDescription} (${errorCode})`)) - }) + } + win.webContents.once('did-finish-load', finish) + win.webContents.once('did-fail-load', fail) + removeLoadListeners = () => { + win.webContents.removeListener('did-finish-load', finish) + win.webContents.removeListener('did-fail-load', fail) + } }) - await win.loadFile(tempPath) - await loadPromise + await Promise.all([win.loadFile(tempPath), loadPromise]) + signal?.throwIfAborted() await win.webContents.executeJavaScript(WAIT_FOR_IMAGES_SCRIPT, true) + signal?.throwIfAborted() return win.webContents.printToPDF({ printBackground: true, pageSize: 'A4', @@ -85,8 +116,10 @@ export async function htmlToPdf(html: string): Promise { }) })() - return await Promise.race([loadAndPrint, timeoutPromise]) + return await Promise.race([loadAndPrint, timeoutPromise, abortPromise]) } finally { + removeAbortListener?.() + removeLoadListeners?.() if (timer) { clearTimeout(timer) } diff --git a/src/main/local-worktree-removal-recovery-live.test.ts b/src/main/local-worktree-removal-recovery-live.test.ts index 54ab64f9719..96f404c403e 100644 --- a/src/main/local-worktree-removal-recovery-live.test.ts +++ b/src/main/local-worktree-removal-recovery-live.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { afterEach, describe, expect, it } from 'vitest' -import { recoverLocalWindowsWorktreeRemoval } from './local-worktree-removal-recovery' +import { recoverPartialLocalWorktreeRemoval } from './local-worktree-removal-recovery' const tempRoots: string[] = [] @@ -105,7 +105,7 @@ describe('local Windows worktree removal recovery (live Git)', () => { await stopProcess(churn) await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr: removal.stderr }), diff --git a/src/main/local-worktree-removal-recovery.test.ts b/src/main/local-worktree-removal-recovery.test.ts index 0ec83a62af8..b63c8cce37c 100644 --- a/src/main/local-worktree-removal-recovery.test.ts +++ b/src/main/local-worktree-removal-recovery.test.ts @@ -24,9 +24,10 @@ vi.mock('./git/worktree', () => ({ })) import { - recoverLocalWindowsWorktreeRemoval, + recoverPartialLocalWorktreeRemoval, removeStaleLocalWorktreeRegistration } from './local-worktree-removal-recovery' +import { NESTED_WORKTREE_REMOVAL_PREFIX } from '../shared/worktree/nested-removal' async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): Promise { const original = process.platform @@ -38,7 +39,7 @@ async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): } } -describe('recoverLocalWindowsWorktreeRemoval', () => { +describe('recoverPartialLocalWorktreeRemoval', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() listWorktreesStrictMock.mockReset() @@ -58,7 +59,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { stderr: "error: failed to delete 'C:/repo/worktree/delete-e2e-held-cwd': Permission denied" }) - const result = await recoverLocalWindowsWorktreeRemoval({ + const result = await recoverPartialLocalWorktreeRemoval({ error, force: true, canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', @@ -74,15 +75,15 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { {}, undefined ) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['worktree', 'prune'], { - cwd: 'C:/repo' - }) - expect(result).toEqual({ - preservedBranch: { - branchName: 'delete-e2e-held-cwd', - head: 'abc123' - } - }) + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['worktree', 'prune'], + expect.anything() + ) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-d', '--', 'delete-e2e-held-cwd'], + expect.objectContaining({ cwd: 'C:/repo' }) + ) + expect(result).toEqual({}) }) }) @@ -93,7 +94,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { "error: failed to delete 'C:/repo/worktree/delete-e2e-held-cwd': Directory not empty" }) - const result = await recoverLocalWindowsWorktreeRemoval({ + const result = await recoverPartialLocalWorktreeRemoval({ error, force: false, canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', @@ -109,15 +110,15 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { {}, undefined ) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['worktree', 'prune'], { - cwd: 'C:/repo' - }) - expect(result).toEqual({ - preservedBranch: { - branchName: 'delete-e2e-held-cwd', - head: 'abc123' - } - }) + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['worktree', 'prune'], + expect.anything() + ) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-d', '--', 'delete-e2e-held-cwd'], + expect.objectContaining({ cwd: 'C:/repo' }) + ) + expect(result).toEqual({}) }) }) @@ -134,7 +135,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { }) await withPlatform('win32', async () => { await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: new Error('Git deregistered but left the checkout'), force: true, canonicalWorktreePath: 'C:/repo/worktree/feature', @@ -162,7 +163,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { const watcherError = new Error('file watcher process did not exit after termination deadline') await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: new Error('git worktree remove failed'), force: true, canonicalWorktreePath: 'C:/repo/worktree/feature', @@ -181,7 +182,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { it('recovers localized Windows failures after Git already removed the registration', async () => { await withPlatform('win32', async () => { - const result = await recoverLocalWindowsWorktreeRemoval({ + const result = await recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr: "Fehler: 'C:/repo/worktree/feature' konnte nicht gelöscht werden" }), @@ -216,7 +217,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { ]) await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr: 'Fehler: unerwarteter Git-Zustand' }), @@ -233,24 +234,90 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { }) }) - it('does not recover partial filesystem deletion wording off Windows', async () => { - await withPlatform('linux', async () => { - const error = Object.assign(new Error('git worktree remove failed'), { - stderr: "error: failed to delete 'C:/repo/worktree/delete-e2e-held-cwd': Permission denied" + it('finishes a macOS deletion Git deregistered before failing with Directory not empty', async () => { + await withPlatform('darwin', async () => { + const closeWatcher = vi.fn().mockResolvedValue(undefined) + + const result = await recoverPartialLocalWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: + "error: failed to delete '/Users/dev/orca/workspaces/feature': Directory not empty" + }), + force: true, + canonicalWorktreePath: '/Users/dev/orca/workspaces/feature', + repoPath: '/Users/dev/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: true, + closeWatcher }) + expect(closeWatcher).toHaveBeenCalledWith('/Users/dev/orca/workspaces/feature') + expect(removeLocalWorktreePathMock).toHaveBeenCalledWith( + '/Users/dev/orca/workspaces/feature', + {}, + undefined + ) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-d', '--', 'feature'], + expect.objectContaining({ cwd: '/Users/dev/repo' }) + ) + expect(result).toEqual({}) + }) + }) + + it('leaves an orphaned checkout to the orphan cleanup instead of deleting it', async () => { + await withPlatform('darwin', async () => { + const closeWatcher = vi.fn().mockResolvedValue(undefined) + await expect( - recoverLocalWindowsWorktreeRemoval({ - error, + recoverPartialLocalWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: "fatal: '/Users/dev/orca/workspaces/feature' is not a working tree" + }), force: true, - canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', - repoPath: 'C:/repo', + canonicalWorktreePath: '/Users/dev/orca/workspaces/feature', + repoPath: '/Users/dev/repo', localWorktreeGitOptions: {}, - registeredWorktree: { branch: 'refs/heads/delete-e2e-held-cwd', head: 'abc123' }, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, deleteBranch: true, - closeWatcher: vi.fn().mockResolvedValue(undefined) + closeWatcher }) ).resolves.toBeUndefined() + expect(closeWatcher).not.toHaveBeenCalled() + expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() + }) + }) + + it('does not delete a checkout that now contains a registered worktree', async () => { + await withPlatform('darwin', async () => { + listWorktreesStrictMock.mockResolvedValue([ + { + path: '/Users/dev/orca/workspaces/feature/nested', + head: 'def456', + branch: 'refs/heads/nested', + isBare: false, + isMainWorktree: false + } + ]) + const closeWatcher = vi.fn().mockResolvedValue(undefined) + + await expect( + recoverPartialLocalWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: + "error: failed to delete '/Users/dev/orca/workspaces/feature': Directory not empty" + }), + force: true, + canonicalWorktreePath: '/Users/dev/orca/workspaces/feature', + repoPath: '/Users/dev/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: true, + closeWatcher + }) + ).rejects.toThrow(NESTED_WORKTREE_REMOVAL_PREFIX) + expect(closeWatcher).not.toHaveBeenCalled() expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() }) }) @@ -266,7 +333,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { const closeWatcher = vi.fn().mockResolvedValue(undefined) await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr: 'error: failed to delete deep/file.txt: Filename too long' }), @@ -306,7 +373,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { const closeWatcher = vi.fn().mockResolvedValue(undefined) await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr }), force: true, canonicalWorktreePath: 'C:/repo/worktree/feature', @@ -331,7 +398,7 @@ describe('recoverLocalWindowsWorktreeRemoval', () => { const closeWatcher = vi.fn().mockResolvedValue(undefined) await expect( - recoverLocalWindowsWorktreeRemoval({ + recoverPartialLocalWorktreeRemoval({ error: Object.assign(new Error('git worktree remove failed'), { stderr: "error: failed to delete 'C:/repo/worktree/feature': Directory not empty" }), diff --git a/src/main/local-worktree-removal-recovery.ts b/src/main/local-worktree-removal-recovery.ts index 4fc6de09b39..14e957c79a0 100644 --- a/src/main/local-worktree-removal-recovery.ts +++ b/src/main/local-worktree-removal-recovery.ts @@ -3,11 +3,14 @@ import { pruneGitWorktrees } from './git/worktree-prune-guard' import type { GitWorktreeInfo } from '../shared/worktree/types' import { assertWorktreeUnlockedForRemoval } from '../shared/worktree/removal' import { areWorktreePathsEqual } from './git/worktree-path-comparison' -import { formatWorktreeRemovalError } from './ipc/worktree-logic' +import { formatWorktreeRemovalError, isOrphanedWorktreeError } from './ipc/worktree-logic' import { listWorktreesStrict, type GitWorktreeExecOptions } from './git/worktree' +import { normalizeLocalBranchRef } from './git/worktree-operation-options' +import { deleteBranchOfUnregisteredWorktree } from './git/worktree-removal' import { removeLocalWorktreePath } from './local-worktree-filesystem' +import { assertWorktreeDoesNotContainRegisteredWorktree } from './worktree-removal-safety' -type LocalWindowsRemovalRecoveryArgs = { +type LocalPartialRemovalRecoveryArgs = { error: unknown force: boolean canonicalWorktreePath: string @@ -20,7 +23,7 @@ type LocalWindowsRemovalRecoveryArgs = { } type StaleLocalWorktreeRegistrationArgs = Omit< - LocalWindowsRemovalRecoveryArgs, + LocalPartialRemovalRecoveryArgs, 'error' | 'force' | 'closeWatcher' | 'signal' > @@ -39,16 +42,12 @@ function preservedBranchResult( } } -function staleRegistrationRecoveryError( - error: unknown, - canonicalWorktreePath: string, - force: boolean -): Error { +function staleRegistrationRecoveryError(error: unknown, canonicalWorktreePath: string): Error { return new Error( `${formatWorktreeRemovalError( error, canonicalWorktreePath, - force + true )} Git still has stale worktree registration. Retry deletion after resolving the Git registration error.` ) } @@ -56,8 +55,7 @@ function staleRegistrationRecoveryError( async function verifyGitWorktreeRegistrationRemoved( repoPath: string, localWorktreeGitOptions: GitWorktreeExecOptions, - canonicalWorktreePath: string, - force: boolean + canonicalWorktreePath: string ): Promise { try { const remainingWorktrees = await listWorktreesStrict(repoPath, localWorktreeGitOptions) @@ -69,13 +67,12 @@ async function verifyGitWorktreeRegistrationRemoved( throw new Error('Git still reports the worktree registration after cleanup.') } } catch (error) { - throw staleRegistrationRecoveryError(error, canonicalWorktreePath, force) + throw staleRegistrationRecoveryError(error, canonicalWorktreePath) } } -async function removeRequiredGitWorktreeRegistration( - args: StaleLocalWorktreeRegistrationArgs, - forceForError = true +export async function removeStaleLocalWorktreeRegistration( + args: StaleLocalWorktreeRegistrationArgs ): Promise { assertWorktreeUnlockedForRemoval(args.registeredWorktree) @@ -93,25 +90,24 @@ async function removeRequiredGitWorktreeRegistration( await verifyGitWorktreeRegistrationRemoved( args.repoPath, args.localWorktreeGitOptions, - args.canonicalWorktreePath, - forceForError + args.canonicalWorktreePath ) } catch (verificationError) { throw removalError - ? staleRegistrationRecoveryError(removalError, args.canonicalWorktreePath, forceForError) + ? staleRegistrationRecoveryError(removalError, args.canonicalWorktreePath) : verificationError } // Preserve the branch when Git may have detached the row before reporting a filesystem error. return result ?? preservedBranchResult(args.registeredWorktree, args.deleteBranch) } -export async function recoverLocalWindowsWorktreeRemoval( - args: LocalWindowsRemovalRecoveryArgs +export async function recoverPartialLocalWorktreeRemoval( + args: LocalPartialRemovalRecoveryArgs ): Promise { // Reject Git locks before recovery can recursively delete files. assertWorktreeUnlockedForRemoval(args.registeredWorktree) - if (!(await isRecoverableWindowsFilesystemRemovalFailure(args))) { + if (!(await isRecoverablePartialRemovalFailure(args))) { return undefined } @@ -126,29 +122,41 @@ export async function recoverLocalWindowsWorktreeRemoval( } catch (error) { throw new Error(formatWorktreeRemovalError(error, args.canonicalWorktreePath, args.force)) } - return removeRequiredGitWorktreeRegistration(args, args.force) + const { branch, head } = args.registeredWorktree + // Same -d policy as a normal delete: merged branches go, unmerged ones are preserved. + return deleteBranchOfUnregisteredWorktree( + args.repoPath, + args.canonicalWorktreePath, + args.deleteBranch && branch ? { name: normalizeLocalBranchRef(branch), head } : null, + args.localWorktreeGitOptions + ) } -async function isRecoverableWindowsFilesystemRemovalFailure( - args: LocalWindowsRemovalRecoveryArgs +async function isRecoverablePartialRemovalFailure( + args: LocalPartialRemovalRecoveryArgs ): Promise { - if (process.platform !== 'win32' || typeof args.error !== 'object' || args.error === null) { + // Leave English orphan errors (Git refused before deleting) to the proven-orphan cleanup. + if ( + typeof args.error !== 'object' || + args.error === null || + isOrphanedWorktreeError(args.error) + ) { return false } + let worktrees: GitWorktreeInfo[] try { - const worktrees = await listWorktreesStrict(args.repoPath, args.localWorktreeGitOptions) - // Localized error text cannot prove removal started; require the Git row to be absent. - return !worktrees.some((worktree) => - areWorktreePathsEqual(worktree.path, args.canonicalWorktreePath) - ) + worktrees = await listWorktreesStrict(args.repoPath, args.localWorktreeGitOptions) } catch { return false } -} - -export async function removeStaleLocalWorktreeRegistration( - args: StaleLocalWorktreeRegistrationArgs -): Promise { - return removeRequiredGitWorktreeRegistration(args) + // Localized error text cannot prove removal started; require the Git row to be absent. + if ( + worktrees.some((worktree) => areWorktreePathsEqual(worktree.path, args.canonicalWorktreePath)) + ) { + return false + } + // A worktree registered inside the checkout during Git's delete must not be removed with it. + assertWorktreeDoesNotContainRegisteredWorktree(args.canonicalWorktreePath, worktrees) + return true } diff --git a/src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts b/src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts index 1d4124858c7..bba09ce31ac 100644 --- a/src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts +++ b/src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts @@ -32,7 +32,7 @@ vi.mock('../install/remote-versioned-install', async (importOriginal) => ({ })) vi.mock('../install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) vi.mock('../install/orcad-remote-preflight', () => ({ - preflightInstalledOrcad: vi.fn() + preflightInstalledOrcad: vi.fn(async () => ({})) })) vi.mock('../../ssh/orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'abc123def4567890' diff --git a/src/main/managed-server/host-state/orcad-state-mutation-timeout.test.ts b/src/main/managed-server/host-state/orcad-state-mutation-timeout.test.ts index 9bf747df1f0..b2715332c41 100644 --- a/src/main/managed-server/host-state/orcad-state-mutation-timeout.test.ts +++ b/src/main/managed-server/host-state/orcad-state-mutation-timeout.test.ts @@ -26,7 +26,7 @@ vi.mock('../install/remote-versioned-install', async (importOriginal) => ({ })) vi.mock('../install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) vi.mock('../install/orcad-remote-preflight', () => ({ - preflightInstalledOrcad: vi.fn() + preflightInstalledOrcad: vi.fn(async () => ({})) })) vi.mock('../../ssh/orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'abc123def4567890' diff --git a/src/main/managed-server/install/orcad-remote-context.ts b/src/main/managed-server/install/orcad-remote-context.ts index b7d3a7dfbd1..2e9f945a5a7 100644 --- a/src/main/managed-server/install/orcad-remote-context.ts +++ b/src/main/managed-server/install/orcad-remote-context.ts @@ -52,16 +52,23 @@ export async function resolveOrcadRemoteContext> { const host = detectedHost ?? (await detectRemoteHostPlatform(connection, { signal })) if (!host) { - throw new OrcadHostUnsupportedError('Orca’s server doesn’t support this SSH host’s platform.') + throw new OrcadHostUnsupportedError( + isWslOrcadHostTarget(target) + ? 'Orca’s server doesn’t support this WSL distro’s platform. Use an x64 or arm64 Linux distro.' + : 'Orca’s server doesn’t support this SSH host’s platform.' + ) } const remote = { conn: connection, host, signal } const { orcadHome: remoteHome, userDataDir } = await resolveOrcadMachineHome( remote, - !isWslOrcadHostTarget(target) + !isWslOrcadHostTarget(target), + knownLoginHome ) const serverTarget = await resolveOrcadRuntimeTarget({ conn: connection, @@ -99,12 +106,13 @@ export async function resolveOrcadRemoteContext { const { host } = remote if (!keyByMachine || isWindowsRemoteHost(host)) { const loginHome = normalizeRemoteHome( - await execOrcadRemote(remote, readRemoteHomeCommand(host)), + knownLoginHome ?? (await execOrcadRemote(remote, readRemoteHomeCommand(host))), host ) if (!validateRemoteHome(loginHome, host)) { diff --git a/src/main/managed-server/install/orcad-remote-gc.test.ts b/src/main/managed-server/install/orcad-remote-gc.test.ts index 044fc89c125..531cdb30911 100644 --- a/src/main/managed-server/install/orcad-remote-gc.test.ts +++ b/src/main/managed-server/install/orcad-remote-gc.test.ts @@ -132,7 +132,7 @@ describe('orcad GC', () => { listing: ['orcad-0.1.0+01d', 'orcad-0.2.0+9ee0', 'orcad-0.3.0+cc0'], removed }) - await gcOldOrcadVersions({ + const clean = await gcOldOrcadVersions({ conn, host, remoteHome: '/home/u', @@ -144,6 +144,8 @@ describe('orcad GC', () => { } }) expect(removed).toEqual(['orcad-0.1.0+01d']) + // Pinned versions are not stale, so the pass still counts as clean. + expect(clean).toBe(true) }) it('never removes the version a live daemon was forked from', async () => { @@ -167,7 +169,7 @@ describe('orcad GC', () => { liveness: { 'orcad-0.1.0+bb0': 'UNKNOWN', 'orcad-0.0.9+dead': 'DEAD' }, removed }) - await gcOldOrcadVersions({ + const clean = await gcOldOrcadVersions({ conn, host, remoteHome: '/home/u', @@ -175,6 +177,8 @@ describe('orcad GC', () => { record: emptyOrcadActivationRecord() }) expect(removed).toEqual(['orcad-0.0.9+dead']) + // A kept candidate must be retried by a later pass. + expect(clean).toBe(false) }) it('stops before later versions when liveness probe termination is unconfirmed', async () => { diff --git a/src/main/managed-server/install/orcad-remote-gc.ts b/src/main/managed-server/install/orcad-remote-gc.ts index f16fd044ee1..f9d4bac6069 100644 --- a/src/main/managed-server/install/orcad-remote-gc.ts +++ b/src/main/managed-server/install/orcad-remote-gc.ts @@ -39,13 +39,14 @@ type OrcadGcOptions = { signal?: AbortSignal } -export async function gcOldOrcadVersions(options: OrcadGcOptions): Promise { +/** True when no stale version dir was left behind (skipped, kept or unlistable ones make it false). */ +export async function gcOldOrcadVersions(options: OrcadGcOptions): Promise { const transaction = await readOrcadGcTransactionPins(options) if (transaction.state === 'keep-all') { console.warn('[orcad-gc] An activation transaction is unreadable or unjournaled; skipping GC.') - return + return false } - await gcOldRemoteInstallVersions( + const versionsClean = await gcOldRemoteInstallVersions( options.conn, ORCAD_INSTALL_MODEL, options.remoteHome, @@ -88,6 +89,7 @@ export async function gcOldOrcadVersions(options: OrcadGcOptions): Promise signal: options.signal }) } + return versionsClean } /** Null means unknown host state and keeps every candidate; otherwise pin anything not proven dead. */ diff --git a/src/main/managed-server/install/orcad-remote-preflight.ts b/src/main/managed-server/install/orcad-remote-preflight.ts index 79ef0b0b360..b09ff08138b 100644 --- a/src/main/managed-server/install/orcad-remote-preflight.ts +++ b/src/main/managed-server/install/orcad-remote-preflight.ts @@ -4,7 +4,8 @@ import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../shared/orcad-artifa import { ORCAD_PROFILE_PREFLIGHT_FLAG, ORCAD_PROFILE_PREFLIGHT_TIMEOUT_MS, - parseOrcadProfilePreflight + parseOrcadProfilePreflight, + type OrcadProfilePreflightResponse } from '../../../shared/orcad-profile-preflight' import { assertPosixOrcadHost } from './orcad-remote-host-support' import { @@ -27,7 +28,8 @@ import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' export function orcadProfilePreflightCommand( host: RemoteHostPlatform, directory: string, - nonce: string + nonce: string, + probeDaemonsUnder?: string ): string { assertPosixOrcadHost(host) // New candidates always use pinned Node; host Node fallback could mask an incomplete slot. @@ -39,28 +41,36 @@ export function orcadProfilePreflightCommand( '"$orcad_runtime"', '"$orcad_entry"', ORCAD_PROFILE_PREFLIGHT_FLAG, - quotePosixShell(nonce) + quotePosixShell(nonce), + ...(probeDaemonsUnder === undefined ? [] : [quotePosixShell(probeDaemonsUnder)]) ].join(' ') return `[ -e ${marker} ] || exit 78; ${orcadNodeSlotRuntimeCommand(host, directory)}${selectOrcadSlotEntryCommand(host, directory)}; ${launch}` } +/** Qualify the candidate; given the served data root, it also names the daemon generations alive there. */ export async function preflightInstalledOrcad(options: { conn: OrcadHostTransport host: RemoteHostPlatform remoteInstallDir: string + probeDaemonsUnder?: string fullVersion: string signal?: AbortSignal -}): Promise { +}): Promise { const nonce = randomUUID() const command = isWindowsRemoteHost(options.host) ? await windowsOrcadProfilePreflightCommand(options, nonce) - : orcadProfilePreflightCommand(options.host, options.remoteInstallDir, nonce) + : orcadProfilePreflightCommand( + options.host, + options.remoteInstallDir, + nonce, + options.probeDaemonsUnder + ) const output = await execCommand(options.conn, command, { signal: options.signal, timeoutMs: ORCAD_PROFILE_PREFLIGHT_TIMEOUT_MS, wrapCommand: !isWindowsRemoteHost(options.host) }) - parseOrcadProfilePreflight(output, nonce, ORCAD_NODE_RUNTIME_IDENTITY, options.fullVersion) + return parseOrcadProfilePreflight(output, nonce, ORCAD_NODE_RUNTIME_IDENTITY, options.fullVersion) } // Windows uses plain argv; orcad opens no window and needs no background-launch environment. @@ -69,6 +79,7 @@ async function windowsOrcadProfilePreflightCommand( conn: OrcadHostTransport host: RemoteHostPlatform remoteInstallDir: string + probeDaemonsUnder?: string signal?: AbortSignal }, nonce: string @@ -86,6 +97,7 @@ async function windowsOrcadProfilePreflightCommand( return orcadWindowsNodeCommandLine(runtime, [ readWindowsOrcadSlotEntry(slotAnswer, host, remoteInstallDir), ORCAD_PROFILE_PREFLIGHT_FLAG, - nonce + nonce, + ...(options.probeDaemonsUnder === undefined ? [] : [options.probeDaemonsUnder]) ]) } diff --git a/src/main/managed-server/install/orcad-remote-primitives.test.ts b/src/main/managed-server/install/orcad-remote-primitives.test.ts index 071534b41f3..70ebf43a094 100644 --- a/src/main/managed-server/install/orcad-remote-primitives.test.ts +++ b/src/main/managed-server/install/orcad-remote-primitives.test.ts @@ -282,4 +282,20 @@ describe('orcad remote context', () => { }) expect(order).toEqual(['prepare', 'record']) }) + + it('uses a WSL caller-known platform and login home instead of probing them', async () => { + vi.mocked(detectRemoteHostPlatform).mockClear() + const commands: string[] = [] + mockExec.mockImplementation(async (_conn, command: string) => { + commands.push(command) + return command.includes('ldd') ? 'ldd (GNU libc) 2.39\n' : '__ORCAD_RECORD_ABSENT__\n' + }) + const wslTarget = { kind: 'wsl', id: 'wsl:u', distro: 'U', label: 'U' } as const + + const context = await resolveOrcadRemoteContext(wslTarget, conn, undefined, linux, '/home/u\n') + + expect(context).toMatchObject({ remoteHome: '/home/u', userDataDir: '/home/u/.orca' }) + expect(detectRemoteHostPlatform).not.toHaveBeenCalled() + expect(commands.some((command) => command.includes('$HOME'))).toBe(false) + }) }) diff --git a/src/main/managed-server/install/remote-install-gc-termination.test.ts b/src/main/managed-server/install/remote-install-gc-termination.test.ts index 3efa393d9fa..c4af6031aec 100644 --- a/src/main/managed-server/install/remote-install-gc-termination.test.ts +++ b/src/main/managed-server/install/remote-install-gc-termination.test.ts @@ -34,7 +34,7 @@ function failAfter(replies: readonly string[], confirmed = false): Error { return error } -function collectVersions(): Promise { +function collectVersions(): Promise { return gcOldRemoteInstallVersions(conn, ORCAD_INSTALL_MODEL, home, currentDir, host, { isDirLive: async (dir) => (await execCommand(conn, `liveness ${dir}`)).trim() !== 'DEAD' }) diff --git a/src/main/managed-server/install/remote-install-gc.ts b/src/main/managed-server/install/remote-install-gc.ts index 71936f043cd..0300bdce6f3 100644 --- a/src/main/managed-server/install/remote-install-gc.ts +++ b/src/main/managed-server/install/remote-install-gc.ts @@ -49,7 +49,7 @@ export async function gcOldRemoteInstallVersions( currentDirAbsPath: string, host: RemoteHostPlatform = DEFAULT_REMOTE_HOST, options: RemoteInstallGcOptions -): Promise { +): Promise { const baseDir = joinRemotePath(host, remoteHome, RELAY_REMOTE_DIR) const currentDirName = remoteBasename(currentDirAbsPath, host) let listing: string @@ -63,7 +63,7 @@ export async function gcOldRemoteInstallVersions( if (isUnconfirmedSshCommandTermination(err)) { throw err } - return + return false } const entries = listing .split('\n') @@ -82,13 +82,13 @@ export async function gcOldRemoteInstallVersions( .filter((name) => !pinned.has(name)) if (candidates.length === 0) { - return + return true } const extraPins = options.resolveExtraPinnedDirNames ? await options.resolveExtraPinnedDirNames(candidates) : [] if (!extraPins) { - return + return false } const survivors = candidates.filter((name) => !extraPins.includes(name)) @@ -158,6 +158,7 @@ export async function gcOldRemoteInstallVersions( `[${model.id}] GC: removed ${removed.length} stale version dir(s): ${removed.join(', ')}${keptSuffix}` ) } + return kept.length === 0 } async function isCandidateSafeToRemove( diff --git a/src/main/managed-server/install/remote-versioned-install.test.ts b/src/main/managed-server/install/remote-versioned-install.test.ts index 7e18856e4a8..7422ca96552 100644 --- a/src/main/managed-server/install/remote-versioned-install.test.ts +++ b/src/main/managed-server/install/remote-versioned-install.test.ts @@ -465,7 +465,7 @@ describe('gcOldRemoteInstallVersions', () => { remoteHome = '/home/u', currentDir = '/home/u/.orca-remote/orcad-0.1.0+bbb', host?: RemoteHostPlatform - ): Promise => + ): Promise => gcOldRemoteInstallVersions(conn, ORCAD_INSTALL_MODEL, remoteHome, currentDir, host, { isDirLive: async (dir) => { const answer = await mockExec(conn, `liveness ${dir}`).catch((err: unknown) => { diff --git a/src/main/managed-server/lifecycle/orcad-managed-version-gc.test.ts b/src/main/managed-server/lifecycle/orcad-managed-version-gc.test.ts index e2c97214ffe..967f741702d 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-version-gc.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-version-gc.test.ts @@ -91,6 +91,23 @@ describe('managed orcad version GC after a deploy', () => { activeVersion: '2.0.0+b', readiness: readiness({ state: 'absent', buildVersion: null }) }) - ).resolves.toBeUndefined() + ).resolves.toBe(false) + }) + + it('reports clean only when GC ran and left nothing behind', async () => { + readRecordMock.mockResolvedValue({ active: '2.0.0+b' }) + const args = { + slot, + serverTarget: 'linux-x64-glibc' as const, + activeVersion: '2.0.0+b', + readiness: readiness({ state: 'absent', buildVersion: null }) + } + gcMock.mockResolvedValue(true) + await expect(pruneManagedOrcadVersions(args)).resolves.toBe(true) + gcMock.mockResolvedValue(false) + await expect(pruneManagedOrcadVersions(args)).resolves.toBe(false) + await expect( + pruneManagedOrcadVersions({ ...args, readiness: readiness(undefined) }) + ).resolves.toBe(false) }) }) diff --git a/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts b/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts index 569e4dc38ee..a600cd3d54a 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts @@ -14,19 +14,22 @@ export function provenLiveDaemonVersion(readiness: ServeReadiness): string | nul return daemon?.state === 'absent' ? null : undefined } -export async function pruneManagedOrcadVersions(args: { +export type ManagedOrcadPruneArgs = { slot: OrcadSlotOptions serverTarget: NodeRuntimeTarget activeVersion: string readiness: ServeReadiness -}): Promise { +} + +/** True only when GC ran and left no stale version dir behind. */ +export async function pruneManagedOrcadVersions(args: ManagedOrcadPruneArgs): Promise { const liveDaemonVersion = provenLiveDaemonVersion(args.readiness) // Unknown daemon versions could still execute from any candidate tree; skip GC. if (liveDaemonVersion === undefined) { - return + return false } try { - await gcOldOrcadVersions({ + return await gcOldOrcadVersions({ conn: args.slot.conn, host: args.slot.host, remoteHome: args.slot.remoteHome, @@ -40,5 +43,6 @@ export async function pruneManagedOrcadVersions(args: { } catch (error) { // Cleanup must not fail completed deploys; later connects retry. console.warn('[orcad-gc] Pruning old orcad versions failed:', error) + return false } } diff --git a/src/main/managed-server/lifecycle/orcad-runtime-target.ts b/src/main/managed-server/lifecycle/orcad-runtime-target.ts index e58ab279076..347cbf9ac83 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-target.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-target.ts @@ -5,6 +5,13 @@ import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' import { pinnedRuntimeTargetForHost } from '../../ssh/pinned-runtime-host-target' import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +/** Lets a caller that knows the host kind add its own fix; the message is the one SSH shows. */ +export class OrcadHostGlibcUnsupportedError extends OrcadHostUnsupportedError { + constructor(target: string, glibc: string) { + super(`No Orca runtime supports ${target} with glibc ${glibc}.`) + } +} + export async function resolveOrcadRuntimeTarget(options: { conn: OrcadHostTransport host: RemoteHostPlatform @@ -15,9 +22,7 @@ export async function resolveOrcadRuntimeTarget(options: { const target = pinnedRuntimeTargetForHost(facts) if (!target) { const glibc = facts.glibc ? `${facts.glibc.major}.${facts.glibc.minor}` : 'unknown' - throw new OrcadHostUnsupportedError( - `No Orca runtime supports ${facts.target} with glibc ${glibc}.` - ) + throw new OrcadHostGlibcUnsupportedError(facts.target, glibc) } return target } diff --git a/src/main/managed-server/posix-host-op-byte-budget.test.ts b/src/main/managed-server/posix-host-op-byte-budget.test.ts index 588bb3d783e..20dc33056c7 100644 --- a/src/main/managed-server/posix-host-op-byte-budget.test.ts +++ b/src/main/managed-server/posix-host-op-byte-budget.test.ts @@ -208,7 +208,8 @@ const BUILDERS: Readonly string>> = { remoteOrcadBuildHashCommand: ({ host }) => remoteOrcadBuildHashCommand(host, slotDir), sweepStaleRuntimeStagesCommand: ({ host }) => sweepStaleRuntimeStagesCommand(`${baseDir}/node-runtimes`, host), - orcadProfilePreflightCommand: ({ host }) => orcadProfilePreflightCommand(host, slotDir, token), + orcadProfilePreflightCommand: ({ host }) => + orcadProfilePreflightCommand(host, slotDir, token, userDataDir), recordedNodeRuntimeProbeCommand: ({ host, nodePath }) => recordedNodeRuntimeProbeCommand(host, nodePath, token), recordedRemoteNodeRuntimeProbeCommand: ({ host, nodePath, target }) => diff --git a/src/main/media/local-preview-grant-file.ts b/src/main/media/local-preview-grant-file.ts new file mode 100644 index 00000000000..45a2f3b6544 --- /dev/null +++ b/src/main/media/local-preview-grant-file.ts @@ -0,0 +1,27 @@ +import type { Store } from '../persistence' +import { filePreviewForPath, isDocumentPreview } from '../../shared/file-preview-kind' +import { resolveLocalFileRequestPath } from '../ipc/local-file-access-resolution' +import { openLocalRegularFile } from '../ipc/filesystem/local-regular-file-read' +import { guardWslUncPathAccess } from '../wsl/wsl-unc-access-gate' +import type { LocalPreviewTarget, PreviewGrant } from './preview-grant-registry' + +/** + * Opens a local grant's file for a lazy read. It never wakes a stopped WSL distro, and a document + * grant ends once its link points at another kind of file. + */ +export function openLocalPreviewGrantFile( + grant: Pick, + target: LocalPreviewTarget, + store: Store +): ReturnType { + return guardWslUncPathAccess(target.filePath, async () => { + const filePath = await resolveLocalFileRequestPath(target.filePath, target.access, store) + if ( + isDocumentPreview(grant.preview) && + filePreviewForPath(filePath)?.mimeType !== grant.mimeType + ) { + throw new Error('Preview is no longer available') + } + return openLocalRegularFile(filePath) + }) +} diff --git a/src/main/media/media-preview-protocol.test.ts b/src/main/media/media-preview-protocol.test.ts index bb51913ccbc..64367470d79 100644 --- a/src/main/media/media-preview-protocol.test.ts +++ b/src/main/media/media-preview-protocol.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../persistence' +import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' const { authorize } = vi.hoisted(() => ({ authorize: vi.fn(async (filePath: string) => filePath) @@ -15,7 +16,42 @@ vi.mock('../ipc/local-file-access-resolution', () => ({ resolveLocalFileRequestPath: authorize })) -import { handleMediaPreviewRequest, readMediaPreview } from './media-preview-protocol' +vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({ + readRegisteredPairingRevision: vi.fn(() => 9) +})) +vi.mock('./remote-file-preview-reader', async (importOriginal) => ({ + ...(await importOriginal()), + statRemotePreviewFile: vi.fn(), + readRemotePreviewChunk: vi.fn(), + readRemotePreviewRange: vi.fn(), + assertRemoteChunkReadsSupported: vi.fn() +})) + +import { + MEDIA_PREVIEW_CUSTOM_SCHEME, + grantRemoteFilePreview, + handleMediaPreviewRequest, + readLocalFilePreview, + revokeRemoteFilePreviewGrants +} from './media-preview-protocol' +import { + REMOTE_PREVIEW_UPDATE_REQUIRED_MESSAGE, + RemotePreviewPairingChangedError, + assertRemoteChunkReadsSupported, + readRemotePreviewChunk, + readRemotePreviewRange, + statRemotePreviewFile +} from './remote-file-preview-reader' +import type * as RemoteFilePreviewReader from './remote-file-preview-reader' + +function png(width: number, height: number): Uint8Array { + const bytes = new Uint8Array(33) + bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]) + new DataView(bytes.buffer).setUint32(16, width) + new DataView(bytes.buffer).setUint32(20, height) + bytes.set([8, 6, 0, 0, 0], 24) + return bytes +} describe('media preview protocol', () => { let directory: string @@ -47,7 +83,7 @@ describe('media preview protocol', () => { const filePath = join(directory, `clip.${extension}`) await writeFile(filePath, Uint8Array.from([0, 1, 2, 3, 4, 5])) const target = { filePath, access: { kind: 'user-file' } as const } - const result = readMediaPreview(event, target, store) + const result = await readLocalFilePreview(event, target, store, { documents: false }) expect(result).toMatchObject({ content: '', isBinary: true }) expect(result?.mediaUrl).not.toContain(filePath) if (!result) { @@ -65,7 +101,7 @@ describe('media preview protocol', () => { it('rechecks authorization for every seek and revokes URLs with the renderer', async () => { const filePath = join(directory, 'clip.mp4') await writeFile(filePath, 'video') - const result = readMediaPreview(event, { filePath }, store) + const result = await readLocalFilePreview(event, { filePath }, store, { documents: false }) if (!result) { throw new Error('Missing preview') } @@ -77,7 +113,12 @@ describe('media preview protocol', () => { }) it('rejects directories, forged URLs and non-media paths', async () => { - const result = readMediaPreview(event, { filePath: join(directory, 'folder.mp4') }, store) + const result = await readLocalFilePreview( + event, + { filePath: join(directory, 'folder.mp4') }, + store, + { documents: false } + ) if (!result) { throw new Error('Missing preview') } @@ -86,14 +127,101 @@ describe('media preview protocol', () => { expect((await handleMediaPreviewRequest(new Request('orca-media://file/unknown'))).status).toBe( 404 ) - expect(readMediaPreview(event, { filePath: join(directory, 'secret.txt') }, store)).toBeNull() + expect( + await readLocalFilePreview(event, { filePath: join(directory, 'secret.txt') }, store, { + documents: false + }) + ).toBeNull() + }) + + it('mints an image or PDF URL only for a viewer that asks, with its size', async () => { + const filePath = join(directory, 'shot.png') + await writeFile(filePath, png(4, 3)) + await expect( + readLocalFilePreview(event, { filePath }, store, { documents: false }) + ).resolves.toBeNull() + const result = await readLocalFilePreview(event, { filePath }, store, { documents: true }) + expect(result).toMatchObject({ isImage: true, mimeType: 'image/png', size: 33 }) + const response = await handleMediaPreviewRequest(new Request(result?.mediaUrl ?? '')) + // No CORS: no other origin can read these bytes with fetch. + expect(response.headers.get('Access-Control-Allow-Origin')).toBeNull() + expect(new Uint8Array(await response.arrayBuffer())).toEqual(png(4, 3)) + }) + + it('classifies a linked image or PDF by its target, then and on every read', async () => { + const filePath = join(directory, 'shot.png') + const drawing = join(directory, 'drawing.svg') + await writeFile(filePath, png(4, 3)) + await writeFile(drawing, '') + authorize.mockResolvedValueOnce(drawing) + await expect( + readLocalFilePreview(event, { filePath }, store, { documents: true }) + ).resolves.toMatchObject({ mimeType: 'image/svg+xml' }) + authorize.mockResolvedValueOnce(join(directory, 'notes.txt')) + expect(await readLocalFilePreview(event, { filePath }, store, { documents: true })).toBeNull() + const result = await readLocalFilePreview(event, { filePath }, store, { documents: true }) + authorize.mockResolvedValueOnce(drawing) + expect((await handleMediaPreviewRequest(new Request(result?.mediaUrl ?? ''))).status).toBe(404) + }) + + it('refuses an image whose header proves it too large to decode safely', async () => { + const filePath = join(directory, 'bomb.png') + await writeFile(filePath, png(100_000, 100_000)) + await expect( + readLocalFilePreview(event, { filePath }, store, { documents: true }) + ).rejects.toThrow('Image dimensions exceed the preview safety limit') + }) + + it('mints nothing for a renderer torn down while the image was being checked', async () => { + const filePath = join(directory, 'late.png') + await writeFile(filePath, png(4, 3)) + let release: () => void = () => {} + authorize.mockImplementationOnce( + (path) => new Promise((resolve) => (release = () => resolve(path))) + ) + const pending = readLocalFilePreview(event, { filePath }, store, { documents: true }) + await vi.waitFor(() => expect(authorize).toHaveBeenCalled()) + emitter.emit('destroyed') + release() + await expect(pending).rejects.toThrow() + }) + + it('gives another origin no CORS answer, preflight or not', async () => { + const filePath = join(directory, 'doc.pdf') + await writeFile(filePath, '%PDF-1.4') + const result = await readLocalFilePreview(event, { filePath }, store, { documents: true }) + const url = result?.mediaUrl ?? '' + const fromPage = await handleMediaPreviewRequest( + new Request(url, { headers: { origin: 'https://example.com' } }) + ) + expect(fromPage.headers.get('Access-Control-Allow-Origin')).toBeNull() + const preflight = await handleMediaPreviewRequest(new Request(url, { method: 'OPTIONS' })) + expect(preflight.status).toBe(405) + expect(preflight.headers.get('Access-Control-Allow-Origin')).toBeNull() + }) + + it('claims only the element-load privileges, never fetch or CORS', () => { + expect(MEDIA_PREVIEW_CUSTOM_SCHEME.privileges).toEqual({ + standard: true, + secure: true, + stream: true + }) + }) + + it('checks the image it serves, not just the one it minted', async () => { + const filePath = join(directory, 'swapped.png') + await writeFile(filePath, png(4, 3)) + const result = await readLocalFilePreview(event, { filePath }, store, { documents: true }) + await writeFile(filePath, png(100_000, 100_000)) + expect((await handleMediaPreviewRequest(new Request(result?.mediaUrl ?? ''))).status).toBe(404) }) it('does not try a local read for an SSH host', async () => { - const result = readMediaPreview( + const result = await readLocalFilePreview( event, { filePath: '/remote/clip.mp4', connectionId: 'ssh-owner' }, - store + store, + { documents: false } ) if (!result) { throw new Error('Missing preview') @@ -101,4 +229,211 @@ describe('media preview protocol', () => { expect((await handleMediaPreviewRequest(new Request(result.mediaUrl))).status).toBe(404) expect(authorize).not.toHaveBeenCalled() }) + + describe('remote targets', () => { + const addr = (relativePath: string): RemoteFilePreviewAddress => ({ + environmentId: 'env-1', + worktree: 'id:wt-1', + relativePath, + expectedEnvironmentPairingRevision: 3 + }) + const mint = async (relativePath = 'out/clip.webm'): Promise => { + const result = await grantRemoteFilePreview(event, addr(relativePath), store) + if (!result) { + throw new Error('Missing preview') + } + return result.mediaUrl + } + const range = (url: string, header = 'bytes=2-4') => + handleMediaPreviewRequest(new Request(url, { headers: { range: header } })) + let now = 1_000_000 + beforeEach(() => { + vi.spyOn(Date, 'now').mockImplementation(() => now) + vi.mocked(statRemotePreviewFile).mockReset().mockResolvedValue({ size: 6, mtime: 1 }) + vi.mocked(readRemotePreviewChunk) + .mockReset() + .mockResolvedValue(Uint8Array.from([2, 3, 4])) + vi.mocked(assertRemoteChunkReadsSupported).mockReset().mockResolvedValue(undefined) + }) + afterEach(() => vi.mocked(Date.now).mockRestore()) + + it('mints a stream for audio and video only, after one stat proves the file', async () => { + const result = await grantRemoteFilePreview(event, addr('out/clip.webm'), store) + expect(result).toMatchObject({ isBinary: true, mimeType: 'video/webm', content: '' }) + expect(result?.mediaUrl).toMatch(/^orca-media:\/\/file\/[^/?]+\?revision=/) + expect(statRemotePreviewFile).toHaveBeenCalledTimes(1) + await expect(grantRemoteFilePreview(event, addr('notes.txt'), store)).resolves.toBeNull() + expect(statRemotePreviewFile).toHaveBeenCalledTimes(1) + }) + + it('pins a grant the renderer sent unpinned to the pairing it was minted on', async () => { + const { expectedEnvironmentPairingRevision: _revision, ...unpinned } = addr('out/clip.mp4') + const result = await grantRemoteFilePreview(event, unpinned, store) + if (!result) { + throw new Error('Missing preview') + } + await (await range(result.mediaUrl)).arrayBuffer() + const pinned = { ...unpinned, expectedEnvironmentPairingRevision: 9 } + expect(statRemotePreviewFile).toHaveBeenCalledWith(pinned, expect.any(AbortSignal)) + expect(readRemotePreviewChunk).toHaveBeenCalledWith(pinned, 2, 3, expect.any(AbortSignal)) + }) + + it('streams a remote image or PDF to its viewer, refusing a proven-oversized image', async () => { + vi.mocked(readRemotePreviewRange).mockImplementation(async (address) => + address.relativePath.endsWith('.pdf') ? new TextEncoder().encode('%PDF-1.7') : png(4, 3) + ) + await expect( + grantRemoteFilePreview(event, addr('docs/shot.png'), store) + ).resolves.toMatchObject({ + isImage: true, + mimeType: 'image/png', + size: 6 + }) + await expect( + grantRemoteFilePreview(event, addr('docs/spec.pdf'), store) + ).resolves.toMatchObject({ + isImage: true, + mimeType: 'application/pdf' + }) + vi.mocked(readRemotePreviewRange).mockResolvedValue(png(100_000, 100_000)) + await expect(grantRemoteFilePreview(event, addr('docs/bomb.png'), store)).rejects.toThrow( + 'Image dimensions exceed the preview safety limit' + ) + vi.mocked(readRemotePreviewRange).mockImplementation(async (address) => + address.relativePath.endsWith('.pdf') ? new TextEncoder().encode('%PDF-1.7') : png(4, 3) + ) + vi.mocked(statRemotePreviewFile).mockResolvedValueOnce({ size: 60 * 1024 * 1024, mtime: 1 }) + // An decodes the whole file, so images keep the 50 MB cap; PDFs read by range don't. + await expect(grantRemoteFilePreview(event, addr('docs/huge.png'), store)).rejects.toThrow( + 'File too large' + ) + vi.mocked(statRemotePreviewFile).mockResolvedValueOnce({ size: 60 * 1024 * 1024, mtime: 1 }) + await expect( + grantRemoteFilePreview(event, addr('docs/huge.pdf'), store) + ).resolves.toMatchObject({ + size: 60 * 1024 * 1024 + }) + }) + + it("leaves an older host's images and PDFs on files.readPreview, and refuses a swapped image", async () => { + vi.mocked(assertRemoteChunkReadsSupported).mockRejectedValueOnce( + new Error(REMOTE_PREVIEW_UPDATE_REQUIRED_MESSAGE) + ) + await expect(grantRemoteFilePreview(event, addr('docs/spec.pdf'), store)).resolves.toBeNull() + + vi.mocked(readRemotePreviewRange).mockResolvedValueOnce(png(4, 3)) + const minted = await grantRemoteFilePreview(event, addr('docs/shot.png'), store) + vi.mocked(readRemotePreviewRange).mockResolvedValueOnce(png(100_000, 100_000)) + expect((await range(minted?.mediaUrl ?? '')).status).not.toBe(206) + }) + + it('leaves a remote image or PDF whose bytes are another kind to files.readPreview', async () => { + vi.mocked(readRemotePreviewRange).mockResolvedValue(new TextEncoder().encode('')) + await expect(grantRemoteFilePreview(event, addr('docs/shot.png'), store)).resolves.toBeNull() + await expect(grantRemoteFilePreview(event, addr('docs/spec.pdf'), store)).resolves.toBeNull() + await expect( + grantRemoteFilePreview(event, addr('docs/drawing.svg'), store) + ).resolves.toMatchObject({ mimeType: 'image/svg+xml' }) + vi.mocked(readRemotePreviewRange).mockResolvedValue(png(4, 3)) + await expect( + grantRemoteFilePreview(event, addr('docs/drawing.svg'), store) + ).resolves.toBeNull() + }) + + it('fails the mint, not the player, when the host cannot serve chunk reads', async () => { + vi.mocked(assertRemoteChunkReadsSupported).mockRejectedValue(new Error('update Orca')) + await expect(grantRemoteFilePreview(event, addr('out/clip.mp4'), store)).rejects.toThrow( + 'update Orca' + ) + }) + + it('a reload within the reuse window reports the size the reload saw', async () => { + const url = await mint() + await (await range(url)).arrayBuffer() + vi.mocked(statRemotePreviewFile).mockResolvedValue({ size: 100, mtime: 2 }) + const reloaded = await mint() + const response = await range(reloaded) + await response.arrayBuffer() + expect(response.headers.get('Content-Range')).toBe('bytes 2-4/100') + }) + + it('streams a remote range', async () => { + const response = await range(await mint()) + expect(response.status).toBe(206) + expect(response.headers.get('Content-Range')).toBe('bytes 2-4/6') + expect([...new Uint8Array(await response.arrayBuffer())]).toEqual([2, 3, 4]) + expect(readRemotePreviewChunk).toHaveBeenCalledWith( + addr('out/clip.webm'), + 2, + 3, + expect.any(AbortSignal) + ) + }) + + it('cancelling the response body aborts the in-flight remote chunk', async () => { + let chunkSignal: AbortSignal | undefined + vi.mocked(readRemotePreviewChunk).mockImplementation((_address, _offset, _length, signal) => { + chunkSignal = signal + return new Promise(() => {}) + }) + const response = await range(await mint()) + if (!response.body) { + throw new Error('Missing body') + } + const reader = response.body.getReader() + void reader.read() + await vi.waitFor(() => expect(chunkSignal).toBeDefined()) + expect(chunkSignal?.aborted).toBe(false) + await reader.cancel() + expect(chunkSignal?.aborted).toBe(true) + }) + + it('answers a burst of ranges without a stat per range, then re-stats so a growing file plays on', async () => { + const url = await mint() + vi.mocked(statRemotePreviewFile).mockClear() + const burst = await Promise.all([range(url), range(url, 'bytes=0-1'), range(url, 'bytes=3-')]) + await Promise.all(burst.map((response) => response.arrayBuffer())) + // The mint's own stat answers the first burst. + expect(statRemotePreviewFile).not.toHaveBeenCalled() + + vi.mocked(statRemotePreviewFile).mockResolvedValue({ size: 10, mtime: 2 }) + now += 1_500 + const later = await range(url) + await later.arrayBuffer() + expect(later.headers.get('Content-Range')).toBe('bytes 2-4/10') + }) + + it('a failed chunk errors that stream and the grant still serves the next request', async () => { + vi.mocked(readRemotePreviewChunk).mockRejectedValueOnce(new Error('boom')) + const url = await mint() + await expect((await range(url)).arrayBuffer()).rejects.toThrow() + const next = await range(url) + expect(next.status).toBe(206) + expect([...new Uint8Array(await next.arrayBuffer())]).toEqual([2, 3, 4]) + }) + + it('answers 502 for a lost host, and 410 then 404 once the pairing changed', async () => { + const url = await mint() + now += 1_500 + vi.mocked(statRemotePreviewFile).mockRejectedValueOnce(new Error('offline')) + expect((await range(url)).status).toBe(502) + now += 1_500 + vi.mocked(statRemotePreviewFile).mockRejectedValueOnce( + new RemotePreviewPairingChangedError('re-paired') + ) + expect((await range(url)).status).toBe(410) + expect((await range(url)).status).toBe(404) + }) + + it("revokes a removed environment's grants and the renderer's on teardown", async () => { + const removed = await mint() + revokeRemoteFilePreviewGrants('env-1') + expect((await range(removed)).status).toBe(404) + const fresh = await mint() + expect(fresh).not.toBe(removed) + expect((await range(fresh)).status).toBe(206) + emitter.emit('destroyed') + expect((await range(fresh)).status).toBe(404) + }) + }) }) diff --git a/src/main/media/media-preview-protocol.ts b/src/main/media/media-preview-protocol.ts index 9936d324cd3..4a7d859e50e 100644 --- a/src/main/media/media-preview-protocol.ts +++ b/src/main/media/media-preview-protocol.ts @@ -1,83 +1,225 @@ -import { randomUUID } from 'node:crypto' -import { extname } from 'node:path' -import { protocol, type WebContents } from 'electron' +import { protocol } from 'electron' import type { Store } from '../persistence' -import type { LocalFileAccess } from '../../shared/local-file-access' -import { MEDIA_FILE_MIME_TYPES, MEDIA_PREVIEW_SCHEME } from '../../shared/media-file-extensions' +import { MEDIA_PREVIEW_SCHEME } from '../../shared/media-file-extensions' +import { + filePreviewForPath, + isDocumentPreview, + streamsPreviewByRange, + type FilePreview +} from '../../shared/file-preview-kind' +import { + assertLocalPreviewRasterHeader, + assertPreviewableRasterHeader, + assertRemotePreviewRasterHeader, + incrementalPrefixReader +} from './preview-raster-header-check' +import { + DOCUMENT_SIGNATURE_PROBE_BYTES, + prefixFitsDocumentPreview +} from './preview-document-signature' +import { openLocalPreviewGrantFile } from './local-preview-grant-file' +import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' import { resolveLocalFileRequestPath } from '../ipc/local-file-access-resolution' import { openLocalRegularFile } from '../ipc/filesystem/local-regular-file-read' import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { createMediaRangeResponse } from './media-range-response' +import { + REMOTE_PREVIEW_UPDATE_REQUIRED_MESSAGE, + RemotePreviewPairingChangedError, + assertRemoteChunkReadsSupported, + readRemotePreviewChunk, + readRemotePreviewRange, + statRemotePreviewFile, + type RemotePreviewFileSnapshot +} from './remote-file-preview-reader' +import { readRegisteredPairingRevision } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { + grants, + mintPreviewUrl, + remoteSnapshot, + revokeGrant, + type LocalPreviewTarget, + type PreviewGrant, + type PreviewSender, + type PreviewUrl +} from './preview-grant-registry' -type MediaTarget = { filePath: string; connectionId?: string; access?: LocalFileAccess } -type MediaGrant = { target: MediaTarget; store: Store; mimeType: string } -const grants = new Map() -const senders = new Map>() +export { revokeRemoteFilePreviewGrants } from './preview-grant-registry' export const MEDIA_PREVIEW_CUSTOM_SCHEME: Electron.CustomScheme = { scheme: MEDIA_PREVIEW_SCHEME, + // No fetch or CORS: only /