diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d0b6347805d..4d52e46d4a1 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -123,6 +123,12 @@ graph. Local affected tests do not replace CI. Use `pnpm test`, not raw `vitest`: only it keeps the transform cache that makes repeat runs fast. +Most unit files share a worker and its module cache with the files before them. After each file +the worker undoes mocks, fake timers, stubs, env, cwd, and leftover timers, listeners, and globals. +Files using `vi.doMock`, `vi.resetModules`, a DOM environment, or direct `globalThis` writes keep +their own worker. If a file passes alone but fails after others, add `// @orca-isolated-worker` +to it; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak. + To reduce main-process rebuild CPU and memory when you do not need its source maps, set `ORCA_DEV_MAIN_SOURCEMAPS=0` before `pnpm dev`. In Bash/zsh: diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index edc22bc6505..c88dc0f782f 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -342,12 +342,6 @@ jobs: if [ "$PREFLIGHT_PHASE_SELECTED" != true ] || [ "$PREFLIGHT_PRIOR_SUCCESS" != true ]; then exit 0; fi node config/scripts/preflight/changed-checks/check-changed-code-quality.mjs "${{ github.event.pull_request.base.sha }}" - - name: Verify locked audit tools - if: needs.code_paths.outputs.static_analysis == 'true' - env: - ORCA_BACKGROUND_LAUNCH: '1' - run: node config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs - - name: Enforce React Doctor on changed lines if: needs.code_paths.outputs.static_analysis == 'true' run: node config/scripts/static-analysis/react-doctor/check-react-doctor-changed.mjs "${{ github.event.pull_request.base.sha }}" diff --git a/config/audit-tools/README.md b/config/audit-tools/README.md index 7ae8738106c..9c060fa55a2 100644 --- a/config/audit-tools/README.md +++ b/config/audit-tools/README.md @@ -13,4 +13,3 @@ To update a tool, change its exact version in this package's manifest, run `pnpm --dir config/audit-tools install --ignore-scripts`, and review both the manifest and generated lockfile. The workspace enforces a three-day release delay and disables install scripts. Keep its package-manager pin aligned with the root. -Run `node config/scripts/verify-locked-audit-tools.mjs` to exercise both tools. diff --git a/config/build-plugins/react-compiler.ts b/config/build-plugins/react-compiler.ts new file mode 100644 index 00000000000..fcdb314daa8 --- /dev/null +++ b/config/build-plugins/react-compiler.ts @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import type { Options } from '@vitejs/plugin-react' + +// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently. +const UNCOMPILED_FILE_LISTS = [ + 'config/react-compiler-uncompiled-files.txt', + 'config/render-path-translate-baseline.txt', + 'config/react-compiler-hazard-baseline.txt' +] + +function listedFiles(list: string): string[] { + return readFileSync(resolve(list), 'utf8') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + .map((line) => line.replace(/^\d+\s+/, '').split('#')[0]) +} + +export function reactCompilerExcludedFiles(): string[] { + return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))] +} + +export function isReactCompilerEnabled(): boolean { + return process.env.ORCA_REACT_COMPILER !== '0' +} + +export const REACT_COMPILER_OPTIONS = { target: '19' } as const + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +export function reactCompilerExcludePattern(): RegExp { + return new RegExp(`/(?:${reactCompilerExcludedFiles().map(escapeRegExp).join('|')})$`) +} + +// ORCA_REACT_COMPILER=0 builds without the compiler for bisecting. +export function reactPluginOptions(): Options { + if (!isReactCompilerEnabled()) { + return {} + } + return { + compiler: REACT_COMPILER_OPTIONS, + exclude: [/\/node_modules\//, reactCompilerExcludePattern()] + } +} diff --git a/config/build-plugins/vitest-compiler-runtime-fallback.ts b/config/build-plugins/vitest-compiler-runtime-fallback.ts new file mode 100644 index 00000000000..9c917969fb6 --- /dev/null +++ b/config/build-plugins/vitest-compiler-runtime-fallback.ts @@ -0,0 +1,25 @@ +import { createRequire } from 'node:module' + +// Why: hook-harness tests mock React or call hooks outside render; there, run uncached like uncompiled code. +const require = createRequire(import.meta.url) +const react: { + __CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE: { H: unknown } +} = require('react') +const internals = react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE +const runtime: { c: (size: number) => unknown[] } = require('react/compiler-runtime') +const sentinel = Symbol.for('react.memo_cache_sentinel') +const uncached = (size: number): unknown[] => Array.from({ length: size }, () => sentinel) + +export function c(size: number): unknown[] { + if (!internals.H) { + return uncached(size) + } + try { + return runtime.c(size) + } catch (error) { + if (error instanceof Error && error.message.startsWith('Invalid hook call')) { + return uncached(size) + } + throw error + } +} diff --git a/config/build-plugins/vitest-react-compiler.ts b/config/build-plugins/vitest-react-compiler.ts new file mode 100644 index 00000000000..1b3a180f43a --- /dev/null +++ b/config/build-plugins/vitest-react-compiler.ts @@ -0,0 +1,66 @@ +import { resolve } from 'node:path' +import { normalizePath, type Plugin } from 'vite' +import { + REACT_COMPILER_OPTIONS, + isReactCompilerEnabled, + reactCompilerExcludePattern +} from './react-compiler' + +const rendererSource = /\/src\/renderer\/src\/.*\.tsx?$/ +// Only shipped code is compiled; tests, fixtures, mocks and harnesses run as written. +const testSupport = + /\/__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/ +const importsVitest = /\bfrom ['"]vitest['"]/ +const runtimeFallback = normalizePath( + resolve(import.meta.dirname, 'vitest-compiler-runtime-fallback.ts') +) + +// Why: @vitejs/plugin-react skips the compiler for vitest's server consumer, so call it directly. +export function vitestReactCompiler(): Plugin[] { + if (!isReactCompilerEnabled()) { + return [] + } + const excluded = reactCompilerExcludePattern() + return [ + { + name: 'vitest-react-compiler', + enforce: 'pre', + configureVitest({ defineCacheKeyGenerator }) { + // Ratchet baselines move files in and out of compilation without touching their source. + defineCacheKeyGenerator(({ id }) => + excluded.test(normalizePath(id.split('?')[0])) ? 'react-compiler:excluded' : '' + ) + }, + async transform(source, id) { + const filename = normalizePath(id.split('?')[0]) + if ( + !rendererSource.test(filename) || + testSupport.test(filename) || + excluded.test(filename) || + importsVitest.test(source) + ) { + return null + } + const { transform } = await import('oxc-transform-react') + const result = await transform(filename, source, { + jsx: { runtime: 'automatic', development: true }, + reactCompiler: REACT_COMPILER_OPTIONS, + sourcemap: true + }) + const diagnostics = result.errors.map( + (e) => `${e.message}${e.codeframe ? `\n${e.codeframe}` : ''}` + ) + if (result.fatal) { + this.error(diagnostics.join('\n\n') || `React Compiler transform failed: ${filename}`) + } + return { + code: result.code.replace( + /from ["']react\/compiler-runtime["']/, + `from ${JSON.stringify(runtimeFallback)}` + ), + map: result.map + } + } + } + ] +} diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 1e553776daa..9e6d01f833d 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -225,7 +225,7 @@ 1 src/renderer/src/lib/default-creation-host.ts # the sanctioned reader of the default host 1 src/renderer/src/lib/launch-ai-vault-session.ts 1 src/renderer/src/lib/local-preflight-context.ts -2 src/renderer/src/lib/provider-runtime-context.ts +2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts 2 src/renderer/src/lib/repo-runtime-owner.ts 1 src/renderer/src/lib/runtime-session-mirror-owners.ts 1 src/renderer/src/lib/runtime-session-mirror-targets.ts diff --git a/config/host-list-render-baseline.txt b/config/host-list-render-baseline.txt index b1a39632401..09d3a029300 100644 --- a/config/host-list-render-baseline.txt +++ b/config/host-list-render-baseline.txt @@ -7,7 +7,7 @@ 1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx 1 src/renderer/src/components/settings/browser/routing/BrowserSshWorkspaceRoutingSetting.tsx 1 src/renderer/src/components/settings/quick-commands/QuickCommandsToolbar.tsx -1 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.tsx +1 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.tsx 1 src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostSshConfigPicker.tsx 4 src/renderer/src/components/status-bar/SshStatusSegment.tsx 1 src/renderer/src/components/status-bar/resource-usage-popover-body.tsx diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index 18549199187..4222e7a5add 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -60,31 +60,45 @@ "kind": "object-property:keywords", "text": "ghostty", "dynamic": false, - "count": 2 + "count": 1 + }, + { + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", + "kind": "object-property:keywords", + "text": "ghostty", + "dynamic": false, + "count": 1 }, { "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", "kind": "object-property:keywords", "text": "Ghostty", "dynamic": false, - "count": 2 + "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", + "kind": "object-property:keywords", + "text": "Ghostty", + "dynamic": false, + "count": 1 + }, + { + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "Kitty", "dynamic": false, "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "kitty", "dynamic": false, "count": 1 }, { - "filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts", + "filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts", "kind": "object-property:keywords", "text": "kitty.conf", "dynamic": false, diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt index a0a0ede85ea..3d31a05c9e5 100644 --- a/config/path-literal-baseline.txt +++ b/config/path-literal-baseline.txt @@ -6,7 +6,6 @@ config/scripts/performance/session-search/session-search-tool-heavy-corpus.ts src/main/ai-vault/session-transcript-reader.ts config/scripts/runtime-verification/desktop-transport/run-linux-lid-sleep-assertion-docker.mjs src/main/linux-lid-sleep-assertion.ts config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs src/main/ssh/ssh-relay-install-namespace.test.ts -config/scripts/session-search-file-id-e2e/run.ts src/main/ai-vault/session-scanner-service-entry.ts config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs src/renderer/src/runtime/remote-workspace-frozen/ config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/main/runtime/runtime-worktree-agent- config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-mutation-envelope diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index b1a89fbefe0..c4cd51da520 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -422,11 +422,11 @@ 1 src/renderer/src/components/settings/privacy/PrivacyPane.tsx 1 src/renderer/src/components/settings/quick-commands/QuickCommandsPane.tsx 1 src/renderer/src/components/settings/repository/RepositoryFormatterSection.tsx -2 src/renderer/src/components/settings/repository/RepositoryGitHubAccountSection.tsx +2 src/renderer/src/components/settings/repository/source-control/RepositoryGitHubAccountSection.tsx 3 src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.tsx -2 src/renderer/src/components/settings/repository/execution/RepositoryForkSyncSection.tsx -3 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupActions.tsx -2 src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.tsx +2 src/renderer/src/components/settings/repository/source-control/RepositoryForkSyncSection.tsx +3 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupActions.tsx +2 src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx 2 src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.tsx 1 src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx 9 src/renderer/src/components/settings/repository/source-control/repository-source-control-ai-global-ux.ts @@ -441,7 +441,7 @@ 1 src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx 2 src/renderer/src/components/settings/session-history/SessionHistorySettingsPane.tsx 1 src/renderer/src/components/settings/session-history/SessionSearchAdvancedSection.tsx -1 src/renderer/src/components/settings/session-history/use-session-search-status.ts +1 src/renderer/src/components/session-search/use-session-search-status.ts 1 src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx 2 src/renderer/src/components/settings/source-control/AutoRenameBranchFromWorkSetting.tsx 1 src/renderer/src/components/settings/source-control/CommitMessageAiPane.tsx @@ -449,7 +449,7 @@ 1 src/renderer/src/components/settings/ssh/SshPane.tsx 1 src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.tsx 1 src/renderer/src/components/settings/ssh/server-actions/SshHostKeepServerVersionDialog.tsx -1 src/renderer/src/components/settings/ssh/server-actions/SshHostMoveAnywayAction.tsx +1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx 1 src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.tsx 1 src/renderer/src/components/settings/ssh/server-actions/SshHostRestartServerAction.tsx 1 src/renderer/src/components/settings/ssh/ssh-hosts-header-slot.tsx diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt new file mode 100644 index 00000000000..7c7b729df86 --- /dev/null +++ b/config/react-compiler-uncompiled-files.txt @@ -0,0 +1,37 @@ +# Renderer files React Compiler skips; compiled, they would run differently. Hand-maintained. +# Files in config/render-path-translate-baseline.txt and config/react-compiler-hazard-baseline.txt +# are skipped too. Remove a line once its file is safe to compile. + +# Render-time reads of providerRuntimeSessionGeneration (lib/provider-runtime-context.ts; hazard live-read-in-memo-block). +src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx +src/renderer/src/components/feature-wall/use-integration-connection-status.ts +src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx +src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx +src/renderer/src/components/new-workspace/use-jira-source-connection.ts +src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx +src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts +src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts +src/renderer/src/components/task-page/jira/Content.tsx +src/renderer/src/components/task-page/jira/use-task-page-jira-list-projection.ts +src/renderer/src/components/task-page/jira/use-task-page-jira-list-state.ts +src/renderer/src/hooks/use-integration-provider-status-refresh.ts + +# structuredSessionSelectionAuthority/Controller read module state the selection lifetime replaces (live-read-in-memo-block). +src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-option-state.ts + +# applyTerminalColdActivation mutates controller refs during render on the terminal hot path. +src/renderer/src/components/use-terminal-controller.ts + +# Caches keyed on a TanStack virtualizer, which mutates in place (hazard virtualizer-in-memo-block). +src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx +src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.ts +src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts +src/renderer/src/components/github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx +src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx +src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx +src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx + +# The workbench subtree relies on the shell re-rendering on every app render. +src/renderer/src/app-shell/AppWorkspaceShell.tsx +src/renderer/src/app-shell/use-app-chrome-layout.ts diff --git a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs index 7d97c713144..a1d27b2dbec 100644 --- a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs +++ b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs @@ -5,11 +5,7 @@ import { withScratch, copyWrittenBundle } from '../../mobile-web-app/mobile-web-app-bundle-test-fixture.mjs' -import { - bundleMobileWebApp, - renameOutputsByContent, - routeChunkNames -} from './build-mobile-web-app-bundle.mjs' +import { bundleMobileWebApp } from './build-mobile-web-app-bundle.mjs' import { MOBILE_WEB_APP_ROUTE_ROOT } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs' import { verifyMobileWebAppBundle } from './verify-mobile-web-app-bundle.mjs' import { @@ -141,33 +137,3 @@ describe('the verifier', () => { 240_000 ) }) - -describe('naming an output by its bytes', () => { - it('refuses two outputs that name each other', () => { - const emitted = (text) => new TextEncoder().encode(text) - const metafile = { - outputs: { - 'dist/a.js': { imports: [{ path: 'dist/b.js', kind: 'import-statement' }] }, - 'dist/b.js': { imports: [{ path: 'dist/a.js', kind: 'import-statement' }] } - } - } - // Cycles have no final dependency names/content hash; fail if esbuild ever stops emitting a DAG. - expect(() => - renameOutputsByContent(metafile, [ - { path: 'dist/a.js', contents: emitted('import "/assets/b.js"') }, - { path: 'dist/b.js', contents: emitted('import "/assets/a.js"') } - ]) - ).toThrow(/output cycle/) - }) - - it('refuses a route it cannot find an output for', async () => { - await withScratch(async (scratch) => { - const module = join(scratch, 'index.tsx') - await writeFile(module, 'export default function Route() { return null }\n') - // Only metafile maps routes to chunks; missing output must fail before phones request undefined/404. - expect(() => - routeChunkNames({ outputs: {} }, [{ key: './index.tsx', module }], new Map()) - ).toThrow(/\.\/index\.tsx reached no output/) - }) - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs deleted file mode 100644 index e00c3366b52..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs +++ /dev/null @@ -1,50 +0,0 @@ -import { existsSync } from 'node:fs' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { - contentTypeForExtension, - hashedAsset, - sha256Hex, - writeMobileWebBundleTree -} from './mobile-web-bundle-manifest.mjs' - -describe('hashedAsset', () => { - it('refuses an extension with no registered content type', () => { - // Unknown content type must fail rather than leave phone guessing how to serve addressed bytes. - expect(() => hashedAsset(Buffer.from('body'), 'wasm')).toThrow(/no content type registered/) - }) -}) - -describe('writeMobileWebBundleTree', () => { - it('marks a dark build outside the manifest, so its buildId is the same tree’s', async () => { - const outDir = await mkdtemp(join(tmpdir(), 'mobile-web-bundle-manifest-')) - try { - const bytes = Buffer.from('\n', 'utf8') - const tree = (env) => - writeMobileWebBundleTree({ - outDir, - written: [ - { - path: 'index.html', - bytes, - sha256: sha256Hex(bytes), - byteLength: bytes.byteLength, - contentType: contentTypeForExtension('html') - } - ], - desktopVersion: '1.0.0', - protocolWindow: { runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 3 }, - env - }) - const dark = await tree({ ORCA_SIDEBAR_INPUTS: 'main' }) - expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(true) - const off = await tree({}) - expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(false) - expect(dark.manifest.buildId).toBe(off.manifest.buildId) - } finally { - await rm(outDir, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs deleted file mode 100644 index eb7522f2543..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS, - MobileWebBundleRouteSchema -} from '../../../../src/shared/mobile-web-bundle/manifest-contract.ts' -import { resolveMobileWebPageRoutes } from './build-mobile-web-app-bundle.mjs' -import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs' -import { routePathnameFromKey } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs' - -// Test declared screens separately from bundle mechanics so route inventory can grow without coupling builder test size. - -describe('the page routes the manifest declares', () => { - it('turns a route key into the URL pattern expo-router gives it', () => { - expect(routePathnameFromKey('./h/[hostId]/index.tsx')).toBe('/h/[hostId]') - expect(routePathnameFromKey('./h/[hostId]/tasks.tsx')).toBe('/h/[hostId]/tasks') - expect(routePathnameFromKey('./h/[hostId]/session/[worktreeId].tsx')).toBe( - '/h/[hostId]/session/[worktreeId]' - ) - }) - - it('answers null for a layout, which is not a screen anyone navigates to', () => { - expect(routePathnameFromKey('./h/_layout.tsx')).toBeNull() - expect(routePathnameFromKey('./h/[hostId]/_layout.tsx')).toBeNull() - }) - - // Synthetic optional-grant input checks member-by-member mapping; newly declared field must survive builder map before reaching phone. - it('carries an optional grant list through, and writes no key for a route without one', () => { - expect( - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'], - [ - { - pathname: '/h/[hostId]', - grants: ['navigate'], - optionalGrants: ['externalNavigation'] - }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'], optionalGrants: [] } - ] - ) - ).toEqual([ - { pathname: '/h/[hostId]', grants: ['navigate'], optionalGrants: ['externalNavigation'] }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ]) - }) - - it('carries the host-area declaration through, and writes no key where there is none', () => { - expect( - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'], - [ - { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ] - ) - ).toEqual([ - { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate'] } - ]) - }) - - /** - * The wide iPad's host-area session is granted every served route's list, so its in-page hops - * stay in the page. Bounded by what one route can be granted, so that grant never outgrows one route's. - */ - - // The phone refuses the whole manifest over one bad route, which takes every page down. - it('declares only routes the manifest schema accepts', () => { - for (const route of MOBILE_WEB_PAGE_ROUTES) { - expect( - MobileWebBundleRouteSchema.safeParse(route).error?.issues ?? [], - route.pathname - ).toEqual([]) - } - }) - - it('holds the optional lane to the manifest grammar and its own ceiling', () => { - // Released shells read each list against the ceiling on its own, so the writer bounds each the same way. - const withOptional = (optionalGrants, grants = []) => - MobileWebBundleRouteSchema.safeParse({ pathname: '/h/[hostId]', grants, optionalGrants }) - .success - expect(withOptional(['externalNavigation'])).toBe(true) - expect(withOptional(['native.externalNavigation'])).toBe(false) - const names = (count, prefix) => - Array.from({ length: count }, (_value, index) => `${prefix}${String(index)}`) - const cap = MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS - expect(withOptional(names(cap, 'opt'), names(cap, 'req'))).toBe(true) - expect(withOptional(names(cap + 1, 'opt'))).toBe(false) - }) - - it('fails the build on a declaration the bundle cannot render', () => { - // Declared-but-unbundled route opens page then paints Unmatched; catch mismatch at declaration. - expect(() => - resolveMobileWebPageRoutes( - ['./h/[hostId]/index.tsx'], - [{ pathname: '/h/[hostId]/gone', grants: [] }] - ) - ).toThrow('has no module in the bundle') - }) -}) diff --git a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs deleted file mode 100644 index e5df4594bb8..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-source-line-endings.test.mjs +++ /dev/null @@ -1,19 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { assertNoCarriageReturnsInSource } from './mobile-web-source-line-endings.mjs' - -describe('assertNoCarriageReturnsInSource', () => { - it('rejects a CRLF source file, because CRLF changes every asset hash and the buildId', async () => { - const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-eol-')) - try { - await writeFile(join(scratch, 'route.tsx'), 'const a = 1\r\nconst b = 2\r\n', 'utf8') - await expect(assertNoCarriageReturnsInSource(scratch)).rejects.toThrow( - /CRLF in mobile web source/ - ) - } finally { - await rm(scratch, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2a25d38facd..da79a66c8cf 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5190,8 +5190,8 @@ "src/renderer/src/components/github/github-work-item-mutation-target.test.ts": 348, "src/renderer/src/components/github/use-image-input.test.ts": 2619, "src/renderer/src/components/gitlab-item-dialog/use-gitlab-primary-actions.test.ts": 2141, - "src/renderer/src/components/host-picker/bounded-host-list.test.tsx": 667, - "src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx": 2963, + "src/renderer/src/components/host-picker/HostListSearchField.test.tsx": 667, + "src/renderer/src/components/sidebar/project-admission/host-selection/AddRepoHostSelector.large-config.test.tsx": 2963, "src/renderer/src/components/jira-attachment-image.test.tsx": 2117, "src/renderer/src/components/jira-connect-scoped-token.test.tsx": 1047, "src/renderer/src/components/jira-issue-assignee-control.test.tsx": 2875, @@ -5606,7 +5606,7 @@ "src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730, "src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273, "src/renderer/src/components/settings/shortcuts/ShortcutsPane.provenance.test.tsx": 2302, - "src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.test.tsx": 744, + "src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744, "src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438, "src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.test.tsx": 669, "src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699, @@ -5636,23 +5636,23 @@ "src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029, "src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463, "src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314, - "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007, - "src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 495, + "src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007, + "src/renderer/src/components/settings/repository/worktrees/RepositoryWorktreeDefaultsSection.test.tsx": 495, "src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.github-avatar-refresh.test.tsx": 615, "src/renderer/src/components/settings/runtime-environments/pairing/runtime-share-computer-button.test.tsx": 2092, "src/renderer/src/components/settings/navigation/settings-project-list.test.ts": 99, "src/renderer/src/components/settings/source-control/source-control-action-card-layout.test.tsx": 4551, "src/renderer/src/components/settings/source-control/source-control-action-permission-draft.test.tsx": 6938, - "src/renderer/src/components/settings/ssh/targets/ssh-target-draft.test.ts": 72, + "src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts": 72, "src/renderer/src/components/settings/ssh/targets/ssh-target-list-model.test.ts": 56, "src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414, "src/renderer/src/components/settings/appearance/themes/use-catalog-app-themes.test.ts": 2159, "src/renderer/src/components/settings/form-controls/use-debounced-settings-text-draft.test.ts": 308, - "src/renderer/src/components/settings/repository/execution/use-repository-hook-settings-draft.test.tsx": 586, + "src/renderer/src/components/settings/repository/hooks/use-repository-hook-settings-draft.test.tsx": 586, "src/renderer/src/components/settings/repository/hooks/use-repository-issue-command-wsl-stopped.test.ts": 523, "src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-catalog.test.tsx": 2252, "src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-mutation-actions.test.tsx": 2069, - "src/renderer/src/components/settings/session-history/use-session-search-status.test.tsx": 477, + "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477, "src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880, "src/renderer/src/lib/directory-path-suggestion-filter.scan-budget.test.ts": 68, "src/renderer/src/lib/directory-path-suggestion-filter.test.ts": 51, diff --git a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs b/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs deleted file mode 100644 index 400546950fb..00000000000 --- a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import assert from 'node:assert/strict' -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { join, resolve } from 'node:path' -import { parse } from 'yaml' -import { runProcessSync } from '@orca/process-host' -import { auditToolEntry, installAuditTools } from './run-audit-tool.mjs' - -const root = resolve(import.meta.dirname, '../../../..') -const installed = installAuditTools(root) -assert.equal(installed.code, 0, 'Frozen, script-free audit tool install failed') - -const scratch = join(root, 'tmp') -mkdirSync(scratch, { recursive: true }) -const fixture = mkdtempSync(join(scratch, 'locked audit tools ')) -const toolManifest = JSON.parse(readFileSync(join(root, 'config/audit-tools/package.json'), 'utf8')) - -function command(program, args, expectedCode = 0) { - const result = runProcessSync({ program, args, cwd: fixture, timeoutMs: 60_000 }) - assert.equal(result.timedOut, false, `${program} timed out`) - assert.equal(result.signal, null, `${program} received ${result.signal}`) - assert.equal(result.code, expectedCode, `${result.stdout}\n${result.stderr}`) - return result.stdout -} - -function tool(name, args, expectedCode = 0) { - return command(process.execPath, [auditToolEntry(name, root), ...args], expectedCode) -} - -function write(file, value) { - writeFileSync(join(fixture, file), value) -} - -const cleanComponent = 'export default function App() { return }\n' -const indexKeyComponent = - 'export default function App() { return
{["one"].map((text, index) => {text})}
}\n' -const doctorArgs = [ - '.', - '--yes', - '--no-dead-code', - '--no-supply-chain', - '--no-telemetry', - '--no-cache', - '--json', - '--blocking', - 'warning' -] - -try { - command('git', ['init', '--quiet']) - command('git', ['config', 'core.hooksPath', join(fixture, '.git', 'disabled-hooks')]) - command('git', ['config', 'commit.gpgSign', 'false']) - write( - 'package.json', - JSON.stringify({ name: 'locked-audit-smoke', private: true, dependencies: { react: '19.2.8' } }) - ) - write('App.tsx', cleanComponent) - write('knip.json', JSON.stringify({ entry: ['App.tsx'], project: ['*.tsx'] })) - - for (const name of ['react-doctor', 'knip']) { - assert.equal(tool(name, ['--version']).trim(), toolManifest.dependencies[name]) - } - - const clean = JSON.parse(tool('react-doctor', doctorArgs)) - assert.equal(clean.ok, true) - assert.ok(clean.projects.some((project) => project.analyzedFiles.includes('App.tsx'))) - tool('knip', ['--config', 'knip.json', '--files']) - - write('App.tsx', indexKeyComponent) - command('git', ['add', '.']) - command('git', [ - '-c', - 'user.name=Audit tool smoke', - '-c', - 'user.email=audit-smoke@example.invalid', - 'commit', - '--quiet', - '-m', - 'Baseline' - ]) - write('Changed.tsx', indexKeyComponent.replace('function App', 'function Changed')) - command('git', ['add', 'Changed.tsx']) - const changed = JSON.parse( - tool('react-doctor', [...doctorArgs, '--scope', 'lines', '--base', 'HEAD'], 1) - ) - assert.ok(changed.diagnostics.some((item) => item.filePath.endsWith('Changed.tsx'))) - assert.ok(changed.diagnostics.every((item) => !item.filePath.endsWith('App.tsx'))) - - write('Orphan.tsx', 'export const orphan = true\n') - assert.match(tool('knip', ['--config', 'knip.json', '--files'], 1), /Orphan\.tsx/) - - const stale = join(fixture, 'config', 'audit-tools') - mkdirSync(stale, { recursive: true }) - mkdirSync(join(fixture, 'config', 'patches'), { recursive: true }) - const toolPolicy = parse( - readFileSync(join(root, 'config/audit-tools/pnpm-workspace.yaml'), 'utf8') - ) - for (const patch of Object.values(toolPolicy.patchedDependencies ?? {})) { - copyFileSync(join(root, 'config/audit-tools', patch), join(stale, patch)) - } - for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) { - copyFileSync(join(root, 'config', 'audit-tools', file), join(stale, file)) - } - writeFileSync( - join(stale, 'package.json'), - JSON.stringify({ - ...toolManifest, - dependencies: { ...toolManifest.dependencies, knip: '0.0.0' } - }) - ) - const rejected = installAuditTools(fixture, (spec) => runProcessSync({ ...spec, stdio: 'pipe' })) - assert.notEqual(rejected.code, 0, 'A stale tool lockfile was accepted') - assert.match(`${rejected.stdout}\n${rejected.stderr}`, /OUTDATED_LOCKFILE/) - console.log( - 'Locked audit tools: real analysis, changed-line filtering, findings and stale-lock rejection passed' - ) -} finally { - rmSync(fixture, { recursive: true, force: true }) -} diff --git a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs index 047a8d72c74..f9ddb0587af 100644 --- a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs +++ b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import process from 'node:process' @@ -36,29 +36,4 @@ describe('validate-plugin-files', () => { expect(result.code).toBe(1) expect(result.stderr).toContain('panel/index.html') }, 60_000) - - it('passes a scaffolded plugin, explaining why there is no release entry outside Git', async () => { - const dir = path.join(await tempRoot(), 'dusk') - await createPluginFromTemplate({ dir, template: 'theme', publisher: 'acme' }) - const result = await validate(dir) - expect(result.code, result.stderr).toBe(0) - expect(result.stdout).toContain('not in a Git repository') - }, 60_000) - - it('passes a language pack that translates protected copy, warning that Orca ignores it', async () => { - const dir = path.join(await tempRoot(), 'portuguese') - await createPluginFromTemplate({ dir, template: 'language-pack', publisher: 'acme' }) - await writeFile( - path.join(dir, 'locales', 'pt-BR.json'), - JSON.stringify({ - common: { cancel: 'Cancelar' }, - components: { 'native-chat': { approval: { allow: 'Permitir', deny: 'Negar' } } } - }) - ) - const result = await validate(dir) - expect(result.code, result.stderr).toBe(0) - expect(result.stderr).toContain( - 'warning: contributes.languagePacks "pt-BR" (locales/pt-BR.json): 2 protected strings are ignored' - ) - }, 60_000) }) diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 3bf510cc912..99d3c46bff0 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -272,6 +272,7 @@ const RATCHET_SHARED_MODULES = { 'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [ 'check-react-compiler-compat-ratchet.mjs' ], + 'config/react-compiler-uncompiled-files.txt': ['check-react-compiler-compat-ratchet.mjs'], 'config/scripts/localization/reactive-translate/render-path-translate.mjs': [ 'check-render-path-translate-ratchet.mjs' ] diff --git a/config/scripts/session-search-file-id-e2e/README.md b/config/scripts/session-search-file-id-e2e/README.md deleted file mode 100644 index ae1de7fd994..00000000000 --- a/config/scripts/session-search-file-id-e2e/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Windows session-search file-ID integration reproduction - -Opt-in Windows/NTFS harness for #20551. Run from the fix workspace root with -dependencies, the Electron binary, and Git object `9845bef63a6` available. -Everything generated stays under ignored `notes/search-ipc/`; each run gets fresh -roots and a profile. No real transcripts, WSL discovery, desktop windows, or user -profile are used. The synthetic file is recreated until NTFS assigns a real inode -above `Number.MAX_SAFE_INTEGER`; failure to obtain one fails the test. - -```powershell -$env:ORCA_BACKGROUND_LAUNCH='1' -pnpm exec esbuild config/scripts/session-search-file-id-e2e/run.ts --bundle --platform=node --format=esm --packages=external --outfile=notes/search-ipc/run.mjs -node notes/search-ipc/run.mjs red -# Expected exit 1: initial indexing/query succeeds, subsequent reconciliation fails. -node notes/search-ipc/run.mjs green -# Expected exit 0 for both the lifecycle and fresh-host restart phases. -node config/scripts/session-search-file-id-e2e/verify.cjs -``` - -Run red and green sequentially: their build step reuses the exported source tree. -The verifier checks the expected red failure, green reports, identical oracle -expressions after formatting normalization, and that exactly the two file-ID -SELECT source files differ. It does not turn an arbitrary red failure into success. - -## Exact topology - -The runner exports **LOCAL integration overlay** #20516 head -`9845bef63a6d0b80ec37af82b5b275287b8e17df` with `git archive`, then bundles the real -scanner entry and parent modules with esbuild. It does not check out, stage, or -push overlay sources. Green changes only the two SELECT projections to the CAST -expressions in #20551; red retains the original projections. CLI #20514 is unused. - -An isolated, windowless Electron host installs the production child search -enablement using fixture settings. The production shared scanner client invokes -`spawnAiVaultServiceProcess`, which forks Electron with `ELECTRON_RUN_AS_NODE=1` -and the real `session-scanner-service-entry`. That child owns the production -instance, indexer, SQLite search engine, and IPC request handling. - -Marker queries come from **separate Node client processes over a real Windows -named pipe**, through production `UnixSocketTransport`, production `RpcDispatcher` -and `AI_VAULT_METHODS`, then the search registry/service and scanner IPC. Status -polls and default-off/disabled responses also exercise registered handlers directly. -An independent read-only SQLite connection verifies active FTS rows and committed -file metadata against filesystem size/mtime. The transcript-consumer observation -logs actual replace/append modes without supplying messages or search results. - -Labelled fixture seams, identical in both variants: - -- Parent root resolution returns the existing `isolatedScanRoots` fixture. -- `getSettings` supplies the isolated JSON policy; real enablement/settings-change functions apply it. -- The child's allowlisted environment includes `ORCA_BACKGROUND_LAUNCH=1`. -- Passive child PID, IPC, stderr, and transcript-read observations are added. -- The unused default RPC method catalog is excluded; the dispatcher receives the production `AI_VAULT_METHODS` explicitly. Its runtime context supplies only a fixture runtime ID. - -## Oracle and evidence - -Default-off creates no DB and returns disabled. Enablement indexes the marker; -two **real default 20-second recent timer cycles** and two explicit full passes -preserve it. An append becomes searchable; a rename replacement with equal byte -length and exactly restored mtime removes the old marker and adds the new one. -The scanner restarts, then a second Electron host opens the same profile/DB and -queries again. Disablement followed by an append, explicit reconcile, and 21-second -wait leaves the DB unchanged and the new marker absent. - -`red-latest.json` / `green-latest.json` locate each run. Reports contain parent and -scanner PIDs, executable/Node/Electron versions, IPC events, raw unsafe inode, -queries, DB metadata, read modes, and scanner exit codes. `*-stages.jsonl` gives -live progress; `process-*.log` preserves complete output. `comparison.json` records -the two-source-only comparison. The production scanner shutdown protocol closes -only recorded children; the runner waits for its own Electron hosts and external -clients. Profiles/DBs remain as evidence, not running services. - -## Boundaries not exercised - -This is not a packaged/full Orca desktop launch. The host and scanner are bundled -from production sources by this harness, not electron-vite's complete app build. -The actual runtime authentication/metadata server, CLI routing, remote SSH/relay -transport, and UI are not exercised. Named-pipe framing and dispatcher are real, -but the harness connects them directly with a fixture token; it makes no claim -about production authentication. No session-search UI exists in this topology. diff --git a/config/scripts/session-search-file-id-e2e/client.cjs b/config/scripts/session-search-file-id-e2e/client.cjs deleted file mode 100644 index 1922547f6ac..00000000000 --- a/config/scripts/session-search-file-id-e2e/client.cjs +++ /dev/null @@ -1,30 +0,0 @@ -const { connect } = require('node:net') -const assert = require('node:assert/strict') -assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') -const socket = connect(process.argv[2]) -let buffer = '' -socket.setEncoding('utf8') -socket.setTimeout(10_000, () => socket.destroy(new Error('RPC client timeout'))) -socket.on('connect', () => - socket.write( - `${JSON.stringify({ - id: 'file-id-query', - authToken: 'isolated-fixture', - method: 'aiVault.searchSessions', - params: JSON.parse(process.argv[3]) - })}\n` - ) -) -socket.on('data', (chunk) => { - buffer += String(chunk) - const newline = buffer.indexOf('\n') - if (newline === -1) { - return - } - console.log(JSON.stringify({ pid: process.pid, response: JSON.parse(buffer.slice(0, newline)) })) - socket.end() -}) -socket.on('error', (error) => { - console.error(error) - process.exitCode = 1 -}) diff --git a/config/scripts/session-search-file-id-e2e/host.cjs b/config/scripts/session-search-file-id-e2e/host.cjs deleted file mode 100644 index 17ddbb21ff8..00000000000 --- a/config/scripts/session-search-file-id-e2e/host.cjs +++ /dev/null @@ -1,325 +0,0 @@ -const { app } = require('electron') -const assert = require('node:assert/strict') -const fs = require('node:fs/promises') -const { existsSync, appendFileSync } = require('node:fs') -const { join } = require('node:path') -const { DatabaseSync } = require('node:sqlite') -const output = process.argv[2] -const phase = process.argv[3] -const profile = join(output, 'profile') -app.setPath('userData', profile) -app.setPath('sessionData', join(profile, 'chromium')) -app.disableHardwareAcceleration() -globalThis.__fileIdChildren = [] -const report = { - phase, - pid: process.pid, - execPath: process.execPath, - versions: process.versions, - stages: [], - children: [], - stderr: [], - ipc: [] -} -globalThis.__fileIdObserveChild = (child) => { - globalThis.__fileIdChildren.push(child) - child.stderr.on('data', (chunk) => report.stderr.push(String(chunk))) - child.on('message', (message) => - report.ipc.push({ pid: child.pid, type: message.type, operation: message.operation }) - ) -} -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) -const sessionId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' -const markers = { - initial: 'quartzinitialmarker', - append: 'cobaltappendedmarker', - replacement: 'velvetreplacedmarker', - disabled: 'tungstendisabledmarker' -} -let api -let registration -let transport -const endpoint = `\\\\.\\pipe\\orca-file-id-${process.pid}` -let settings = {} -let transcript -const database = join(profile, 'ai-vault', 'session-search.sqlite') -function record(stage, data = {}) { - const entry = { stage, at: Date.now(), ...data } - report.stages.push(entry) - appendFileSync(join(output, `${phase}-stages.jsonl`), `${JSON.stringify(entry)}\n`) - console.log(stage, JSON.stringify(data)) -} -function inspect(marker) { - const db = new DatabaseSync(database, { readOnly: true }) - try { - const query = db.prepare( - 'SELECT CAST(ino AS TEXT) AS ino, byte_offset, size_bytes, mtime_ms FROM files WHERE path = ?' - ) - const rows = db - .prepare(`SELECT s.session_id FROM messages_fts f JOIN messages m ON m.id=f.rowid - JOIN sessions s ON s.id=m.session_row_id WHERE messages_fts MATCH ?`) - .all(marker) - return { file: query.get(transcript), sessions: rows.map((row) => row.session_id) } - } finally { - db.close() - } -} -async function query(marker, present) { - const result = await api.runProcess({ - program: process.env.ORCA_FILE_ID_NODE, - args: [ - join(output, 'client.cjs'), - endpoint, - JSON.stringify({ query: `"${marker}"`, scope: 'conversation', freshness: 'indexed' }) - ], - env: process.env, - timeoutMs: 15_000 - }) - assert.equal(result.code, 0, result.stderr) - const external = JSON.parse(result.stdout) - assert.equal(external.response.ok, true, JSON.stringify(external)) - const response = external.response.result - assert.equal(response.kind, 'results', JSON.stringify(response)) - assert.equal( - response.hits.some((hit) => hit.sessionId === sessionId), - present, - `RPC ${marker}` - ) - const disk = inspect(marker) - assert.equal(disk.sessions.includes(sessionId), present, `DB ${marker}`) - const actual = await fs.stat(transcript) - assert.equal( - disk.file.byte_offset, - actual.size, - 'Committed cursor covers actual transcript bytes' - ) - assert.equal(disk.file.size_bytes, actual.size) - assert.equal(disk.file.mtime_ms, actual.mtimeMs) - record('query', { marker, present, clientPid: external.pid, endpoint, response, disk }) -} -async function status() { - return api.rpc('aiVault.searchStatus', {}) -} -async function waitFor(predicate, label, timeout = 30_000) { - const until = Date.now() + timeout - while (Date.now() < until) { - const current = await status() - if (predicate(current)) { - return current - } - await sleep(200) - } - throw new Error(`Timed out: ${label}`) -} -async function policy(next) { - const before = settings - settings = next - await fs.writeFile(join(profile, 'fixture-settings.json'), JSON.stringify(settings)) - api.applySessionSearchSettingsChange(before, settings) -} -async function stopChild() { - const children = [...globalThis.__fileIdChildren] - api.resetAiVaultScannerServiceForTests() - for (const child of children) { - const until = Date.now() + 5000 - while (child.exitCode === null && child.signalCode === null && Date.now() < until) { - await sleep(50) - } - assert.ok( - child.exitCode !== null || child.signalCode !== null, - `Child ${child.pid} did not exit` - ) - if (!report.children.some((row) => row.pid === child.pid)) { - report.children.push({ - pid: child.pid, - spawnfile: child.spawnfile, - spawnargs: child.spawnargs, - exitCode: child.exitCode, - signalCode: child.signalCode - }) - } - } -} -async function run() { - assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') - await fs.mkdir(profile, { recursive: true }) - api = require('./production.js') - api.setAppEnvironment({ - getPath: (name) => (name === 'userData' ? profile : app.getPath(name)), - getAppPath: () => output, - getVersion: () => app.getVersion(), - isPackaged: () => false, - onWillQuit: (handler) => app.on('will-quit', handler), - exit: (code) => app.exit(code), - getAppMetrics: () => app.getAppMetrics() - }) - const dispatcher = new api.RpcDispatcher({ - methods: api.AI_VAULT_METHODS, - runtime: { getRuntimeId: () => `file-id-${process.pid}` } - }) - transport = new api.UnixSocketTransport({ endpoint, kind: 'named-pipe' }) - transport.onMessage((message, reply) => { - void dispatcher - .dispatch(JSON.parse(message)) - .then((response) => reply(JSON.stringify(response))) - }) - await transport.start() - record('rpc-transport', { - endpoint, - auth: 'fixture; production auth/metadata server not booted', - methods: 'production AI_VAULT_METHODS', - dispatcher: 'production RpcDispatcher' - }) - const roots = { - ...api.isolatedScanRoots(join(output, 'roots')), - wslHomeDirs: [], - additionalCodexSessionsDirs: [], - executionHostId: 'local' - } - process.env.ORCA_FILE_ID_ROOTS = JSON.stringify(roots) - await fs.mkdir(roots.claudeProjectsDir, { recursive: true }) - transcript = join(roots.claudeProjectsDir, `${sessionId}.jsonl`) - if (phase === 'restart') { - settings = JSON.parse(await fs.readFile(join(profile, 'fixture-settings.json'), 'utf8')) - assert.equal(settings.aiVaultSearch.enabled, true) - const beforeRestart = inspect(markers.replacement) - registration = api.installChildSessionSearchService({ - dataRoot: profile, - getSettings: () => settings - }) - await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'Electron host restart') - await query(markers.append, false) - await query(markers.replacement, true) - assert.deepEqual(inspect(markers.replacement), beforeRestart) - record('app-host-restart-same-db') - await disableAndCheck() - return - } - const body = `${api.claudeLines([markers.initial], sessionId, 0).join('\n')}\n` - await fs.writeFile(transcript, body) - let raw = await fs.stat(transcript, { bigint: true }) - for (let n = 0; raw.ino <= BigInt(Number.MAX_SAFE_INTEGER) && n < 512; n++) { - await fs.unlink(transcript) - await fs.writeFile(transcript, body) - raw = await fs.stat(transcript, { bigint: true }) - } - assert.ok(raw.ino > BigInt(Number.MAX_SAFE_INTEGER), 'NTFS must supply an actual unsafe inode') - record('fixture', { - transcript, - rawIno: raw.ino.toString(), - numericIno: BigInt(Number(raw.ino)).toString() - }) - registration = api.installChildSessionSearchService({ - dataRoot: profile, - getSettings: () => settings - }) - assert.ok(registration) - assert.equal((await status()).enabled, false) - assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.initial }), { - kind: 'unavailable', - reason: 'disabled' - }) - assert.equal(existsSync(database), false) - record('default-off') - await policy({ aiVaultSearch: { enabled: true, historyDays: null } }) - const initial = await waitFor( - (s) => s.filesIndexed === 1 && s.phase === 'current', - 'initial indexing' - ) - assert.equal(inspect(markers.initial).file.ino, BigInt(Number(raw.ino)).toString()) - await query(markers.initial, true) - record('initial-indexing', { status: initial }) - let recent = initial - for (let n = 0; n < 2; n++) { - const previous = recent - recent = await waitFor( - (s) => s.lastReconcileAt > previous.lastReconcileAt, - 'recent timer reconciliation' - ) - assert.equal( - recent.lastSweepCompletedAt, - initial.lastSweepCompletedAt, - 'Expected a recent pass' - ) - await query(markers.initial, true) - record('recent-pass', { status: recent }) - } - for (let n = 0; n < 2; n++) { - await api.reconcileSessionSearchInService() - await query(markers.initial, true) - record('full-pass', { status: await status() }) - } - await fs.appendFile( - transcript, - `${api.claudeLines([markers.append], sessionId, 10).join('\n')}\n` - ) - const frozen = new Date(Math.floor((await fs.stat(transcript)).mtimeMs)) - await fs.utimes(transcript, frozen, frozen) - await api.reconcileSessionSearchInService() - await query(markers.append, true) - const before = await fs.stat(transcript) - const replacement = `${transcript}.replacement` - const replacementBody = (await fs.readFile(transcript, 'utf8')).replaceAll( - markers.append, - markers.replacement - ) - assert.equal(Buffer.byteLength(replacementBody), before.size) - await fs.writeFile(replacement, replacementBody) - await fs.rename(replacement, transcript) - await fs.utimes(transcript, before.atime, before.mtime) - const after = await fs.stat(transcript) - assert.equal(after.size, before.size) - assert.equal(after.mtimeMs, before.mtimeMs) - assert.notEqual(after.ino, before.ino) - await api.reconcileSessionSearchInService() - await query(markers.append, false) - await query(markers.replacement, true) - record('replacement', { beforeIno: before.ino, afterIno: after.ino }) - await stopChild() - await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'scanner restart') - await query(markers.append, false) - await query(markers.replacement, true) - record('service-restart') -} -async function disableAndCheck() { - await policy({ aiVaultSearch: { enabled: false, historyDays: null } }) - await waitFor((s) => !s.enabled, 'disable') - const snapshot = inspect(markers.replacement) - await fs.appendFile( - transcript, - `${api.claudeLines([markers.disabled], sessionId, 20).join('\n')}\n` - ) - await api.reconcileSessionSearchInService() - await sleep(21_000) - assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.disabled }), { - kind: 'unavailable', - reason: 'disabled' - }) - assert.deepEqual(inspect(markers.replacement), snapshot) - assert.deepEqual(inspect(markers.disabled).sessions, []) - record('disabled-no-indexing') -} -app.whenReady().then(async () => { - try { - await run() - report.ok = true - } catch (error) { - report.ok = false - report.error = error.stack - console.error(error) - } finally { - registration?.dispose() - await transport?.stop() - if (api) { - await stopChild().catch((error) => { - report.cleanupError = String(error) - report.ok = false - }) - } - if (report.stderr.some((text) => text.includes('[ai-vault-search]'))) { - report.ok = false - } - await fs.writeFile(join(output, `report-${phase}.json`), JSON.stringify(report, null, 2)) - app.exit(report.ok ? 0 : 1) - } -}) diff --git a/config/scripts/session-search-file-id-e2e/run.ts b/config/scripts/session-search-file-id-e2e/run.ts deleted file mode 100644 index 3ab6b5ae15d..00000000000 --- a/config/scripts/session-search-file-id-e2e/run.ts +++ /dev/null @@ -1,194 +0,0 @@ -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises' -import { resolve, join, relative } from 'node:path' -import { createHash } from 'node:crypto' -import { build } from 'esbuild' -import { runProcess } from '@orca/process-host' - -const root = process.cwd() -const evidence = resolve('notes/search-ipc') -const overlay = join(evidence, 'overlay') -const wiring = '9845bef63a6' -const mode = process.argv[2] -assert.equal(process.platform, 'win32', 'This harness requires native Windows and NTFS') -assert.ok(mode === 'red' || mode === 'green', 'Pass red or green') -assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1') -const output = join(evidence, mode, String(Date.now())) -await mkdir(output, { recursive: true }) - -async function command(program: string, args: string[]) { - const result = await runProcess({ program, args, cwd: root, timeoutMs: 120_000 }) - assert.equal(result.code, 0, result.stderr) - return result.stdout.trim() -} - -// The overlay is exported, never checked out or staged on the fix branch. -await mkdir(overlay, { recursive: true }) -await command('git', [ - 'archive', - '--format=tar', - `--output=${join(evidence, 'overlay.tar')}`, - wiring, - 'src' -]) -await command('tar', [ - '-xf', - relative(root, join(evidence, 'overlay.tar')), - '-C', - relative(root, overlay) -]) -const edits: { path: string; sha256: string }[] = [] -function replaceOnce(source: string, before: string, after: string) { - assert.equal(source.split(before).length, 2, `Expected exactly one injection: ${before}`) - return source.replace(before, after) -} - -const adapter = join(output, 'adapter.mjs') -const source = (path: string) => JSON.stringify(join(overlay, 'src', path)) -await writeFile( - adapter, - ` -export { installChildSessionSearchService, applySessionSearchSettingsChange } from ${source('main/ai-vault-search/session-search-enablement.ts')}; -export { resetAiVaultScannerServiceForTests, reconcileSessionSearchInService } from ${source('main/ai-vault/session-scanner-service-spawn.ts')}; -export { setAppEnvironment } from ${source('shared/app-environment.ts')}; -export { isolatedScanRoots } from ${source('main/ai-vault/session-scanner-test-fixtures.ts')}; -export { claudeLines } from ${source('main/ai-vault-search/session-search-indexer-test-fixture.ts')}; -export { runProcess } from '@orca/process-host'; -export { UnixSocketTransport } from ${source('main/runtime/rpc/unix-socket-transport.ts')}; -export { RpcDispatcher } from ${source('main/runtime/rpc/dispatcher.ts')}; -export { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')}; -import { buildRegistry } from ${source('main/runtime/rpc/core.ts')}; -import { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')}; -const registry = buildRegistry(AI_VAULT_METHODS); -export async function rpc(name, params) { - const method = registry.get(name); - if (!method || !name.startsWith('aiVault.search')) throw new Error('Unexpected method'); - return method.handler(method.params.parse(params), {}); -} -` -) - -await build({ - entryPoints: { - production: adapter, - 'session-scanner-service-entry': join( - overlay, - 'src/main/ai-vault/session-scanner-service-entry.ts' - ) - }, - outdir: output, - platform: 'node', - format: 'cjs', - bundle: true, - packages: 'external', - define: { ORCA_FEATURE_WALL_ENABLED: 'true' }, - plugins: [ - { - name: 'labelled-local-fixtures', - setup(api) { - api.onLoad({ filter: /\.ts$/ }, async (args) => { - let contents = await readFile(args.path, 'utf8') - const path = args.path.replaceAll('\\', '/') - if (path.endsWith('/runtime/rpc/methods/rpc-method-registry.ts')) { - // DispatcherOptions explicitly supplies AI_VAULT_METHODS; don't load unrelated default methods. - contents = 'export const ALL_RPC_METHODS = []' - } - if (path.endsWith('/cached-session-list.ts')) { - contents = replaceOnce( - contents, - ' const [additionalCodexHomes, wslHomeDirs] = await Promise.all([', - ' return JSON.parse(process.env.ORCA_FILE_ID_ROOTS!);\n const [additionalCodexHomes, wslHomeDirs] = await Promise.all([' - ) - } - if (path.endsWith('/session-scanner-service-env.ts')) { - contents = replaceOnce( - contents, - " env.ELECTRON_RUN_AS_NODE = '1'", - " env.ORCA_BACKGROUND_LAUNCH = '1'\n env.ELECTRON_RUN_AS_NODE = '1'" - ) - } - if (path.endsWith('/session-scanner-service-spawn.ts')) { - contents = replaceOnce( - contents, - ' lowerAiVaultServicePriority(child.pid)', - ' globalThis.__fileIdObserveChild?.(child)\n lowerAiVaultServicePriority(child.pid)' - ) - } - if (path.endsWith('/session-scanner-service-entry.ts')) { - contents = `import { registerTranscriptConsumer } from './session-transcript-consumers'; -registerTranscriptConsumer({beginRead: start => { console.error('[file-id-read]', JSON.stringify({mode:start.mode,path:start.candidate.file.path})); return null }}); -console.error('[file-id-child]', JSON.stringify({pid:process.pid,execPath:process.execPath,versions:process.versions,background:process.env.ORCA_BACKGROUND_LAUNCH}));\n${contents}` - } - if (mode === 'green' && path.endsWith('/session-search-store.ts')) { - contents = replaceOnce( - contents, - 'SELECT path, dev, ino, mtime_ms', - 'SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms' - ) - } - if (mode === 'green' && path.endsWith('/session-search-index-writer.ts')) { - contents = replaceOnce( - contents, - 'SELECT dev, ino, byte_offset', - 'SELECT CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, byte_offset' - ) - } - edits.push({ - path: path.replace(overlay.replaceAll('\\', '/'), ''), - sha256: createHash('sha256').update(contents).digest('hex') - }) - return { contents, loader: 'ts' } - }) - } - } - ] -}) -await copyFile( - join(root, 'config/scripts/session-search-file-id-e2e/host.cjs'), - join(output, 'host.cjs') -) -await copyFile( - join(root, 'config/scripts/session-search-file-id-e2e/client.cjs'), - join(output, 'client.cjs') -) -await writeFile( - join(output, 'topology.json'), - JSON.stringify( - { - wiring: await command('git', ['rev-parse', wiring]), - fix: await command('git', ['rev-parse', 'HEAD']), - mode, - injections: [ - 'isolated root resolver', - 'background child env', - 'child PID/error/read observation', - 'unused default RPC catalog excluded; explicit production AI_VAULT_METHODS' - ], - files: edits.sort((a, b) => a.path.localeCompare(b.path)) - }, - null, - 2 - ) -) -await writeFile(join(evidence, `${mode}-latest.json`), JSON.stringify({ output })) -for (const phase of ['lifecycle', 'restart']) { - console.log(JSON.stringify({ mode, phase, output })) - const result = await runProcess({ - program: join(root, 'node_modules/electron/dist/electron.exe'), - args: [join(output, 'host.cjs'), output, phase], - cwd: output, - env: { - ...process.env, - ORCA_BACKGROUND_LAUNCH: '1', - ELECTRON_RUN_AS_NODE: undefined, - ORCA_FILE_ID_NODE: process.execPath - }, - timeoutMs: 180_000 - }) - await writeFile(join(output, `process-${phase}.log`), result.stdout + result.stderr) - console.log(JSON.stringify({ mode, phase, code: result.code, timedOut: result.timedOut, output })) - process.exitCode = result.code ?? 1 - if (process.exitCode !== 0) { - break - } -} diff --git a/config/scripts/session-search-file-id-e2e/verify.cjs b/config/scripts/session-search-file-id-e2e/verify.cjs deleted file mode 100644 index 180bf4cf154..00000000000 --- a/config/scripts/session-search-file-id-e2e/verify.cjs +++ /dev/null @@ -1,62 +0,0 @@ -const assert = require('node:assert/strict') -const { readFileSync, writeFileSync } = require('node:fs') -const { join, resolve } = require('node:path') -const { createHash } = require('node:crypto') -const { transformSync } = require('esbuild') -const evidence = resolve('notes/search-ipc') -const json = (path) => JSON.parse(readFileSync(path, 'utf8')) -const red = json(join(evidence, 'red-latest.json')).output -const green = json(join(evidence, 'green-latest.json')).output -const before = json(join(red, 'topology.json')) -const after = json(join(green, 'topology.json')) -assert.equal(before.wiring, after.wiring) -assert.deepEqual(before.injections, after.injections) -const oldFiles = new Map(before.files.map((row) => [row.path, row.sha256])) -assert.equal(oldFiles.size, after.files.length) -const changed = after.files - .filter((row) => oldFiles.get(row.path) !== row.sha256) - .map((row) => row.path) - .sort() -assert.deepEqual(changed, [ - '/src/main/ai-vault-search/session-search-index-writer.ts', - '/src/main/ai-vault-search/session-search-store.ts' -]) -for (const name of ['host.cjs', 'client.cjs']) { - // Ignore formatter-only differences; preserve every expression and assertion. - const hash = (root) => - createHash('sha256') - .update( - transformSync(readFileSync(join(root, name), 'utf8'), { - loader: 'js', - minifyWhitespace: true - }).code - ) - .digest('hex') - assert.equal(hash(red), hash(green), `Identical oracle: ${name}`) -} -const failed = json(join(red, 'report-lifecycle.json')) -assert.equal(failed.ok, false) -assert.match(failed.stderr.join(''), /RangeError: Value is too large/) -assert.ok(failed.stages.some((row) => row.stage === 'initial-indexing')) -const reports = [ - json(join(green, 'report-lifecycle.json')), - json(join(green, 'report-restart.json')) -] -for (const report of reports) { - assert.equal(report.ok, true) - assert.ok(report.ipc.some((row) => row.operation === 'searchSessions')) - assert.ok(report.stages.some((row) => row.stage === 'query' && row.clientPid !== report.pid)) - assert.ok(report.children.every((child) => child.exitCode === 0)) -} -assert.notEqual(reports[0].pid, reports[1].pid) -const result = { - ok: true, - wiring: before.wiring, - changed, - red, - green, - parentPids: [failed.pid, ...reports.map((row) => row.pid)], - childPids: [failed, ...reports].flatMap((report) => report.children.map((child) => child.pid)) -} -writeFileSync(join(evidence, 'comparison.json'), JSON.stringify(result, null, 2)) -console.log(JSON.stringify(result)) diff --git a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs index 69c920f9add..714acf736a6 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs @@ -16,9 +16,15 @@ import { } from '../../ratchet-baseline/ratchet-baseline.mjs' import { HAZARD_FIXES, + LIVE_MODULE_READERS, + VIRTUALIZER_HOOKS, + findLiveReadWrappers, findMemoizedCalls, findSourceHazards, + findVirtualizerMemoFlows, + findVirtualizerWrappers, hookCallLines, + renderLiveReadLines, renderStoreReadLines } from './react-compiler-hazards.mjs' @@ -28,6 +34,8 @@ import { const SCAN_ROOT = 'src/renderer/src' const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt' const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt' +// The build leaves these files uncompiled, so their hazards cannot run. +const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt' const COMMAND = 'pnpm check:react-compiler-compat-ratchet' const NOT_SHIPPED = /(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/ @@ -93,6 +101,59 @@ function addTo(map, key, value) { map.set(key, [...(map.get(key) ?? []), value]) } +function readUncompiledFiles(root) { + const file = path.join(root, UNCOMPILED_LIST) + if (!fs.existsSync(file)) { + return new Set() + } + return new Set( + fs + .readFileSync(file, 'utf8') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + ) +} + +/** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */ +function collectVirtualizerHooks(sources) { + const hooks = new Map(VIRTUALIZER_HOOKS) + for (let grew = true; grew;) { + grew = false + for (const [rel, text] of sources) { + for (const { name, shape } of findVirtualizerWrappers(rel, text, hooks)) { + if (!hooks.has(name)) { + hooks.set(name, shape) + grew = true + } + } + } + } + return hooks +} + +/** Live module-state readers plus every plain function that calls one, followed through wrappers. */ +function collectLiveReaders(sources) { + const readers = new Set(LIVE_MODULE_READERS) + for (let grew = true; grew;) { + grew = false + for (const [rel, text] of sources) { + for (const name of findLiveReadWrappers(rel, text, readers)) { + if (!readers.has(name)) { + readers.add(name) + grew = true + } + } + } + } + return readers +} + +function sourceLineOf(text, snippet) { + const index = text.split('\n').findIndex((line) => line.includes(snippet.split('(')[0])) + return index === -1 ? '?' : index + 1 +} + async function scanFile(rel, text, result) { const output = await transform(rel, text, COMPILER_OPTIONS) if (output.fatal) { @@ -105,15 +166,37 @@ async function scanFile(rel, text, result) { const message = error.message.split('\n')[0] addTo(result.diagnostics, rel, { line: lineAt(bytes, error.labels[0]?.start ?? 0), message }) } + if (result.uncompiled.has(rel)) { + return + } + for (const { fn, text: snippet } of findVirtualizerMemoFlows( + rel, + text, + output.code, + result.virtualizerHooks + )) { + addTo( + result.hazards, + `${rel}#${fn}:virtualizer-in-memo-block`, + `${sourceLineOf(text, snippet)}: ${snippet}` + ) + } for (const hazard of findSourceHazards(rel, text)) { addTo(result.hazards, `${rel}#${hazard.fn}:${hazard.kind}`, `${hazard.line}: ${hazard.text}`) } const storeReadFns = new Set() - for (const { fn, kind, name } of findMemoizedCalls(rel, output.code)) { + for (const { fn, kind, name } of findMemoizedCalls(rel, output.code, result.liveReaders)) { if (kind === 'store-read') { storeReadFns.add(fn) continue } + if (kind === 'live-read') { + // A call inside the source's own useMemo or a closure keeps its written behavior. + for (const line of renderLiveReadLines(rel, text, fn, name)) { + addTo(result.hazards, `${rel}#${fn}:live-read-in-memo-block`, `${line}: ${name}()`) + } + continue + } const lines = hookCallLines(rel, text, fn, name) addTo(result.hazards, `${rel}#${fn}:hook-in-memo-block`, `${lines.join(', ')}: ${name}()`) } @@ -126,8 +209,17 @@ async function scanFile(rel, text, result) { } export async function scanRenderer(root = process.cwd()) { - const result = { files: 0, compiled: 0, diagnostics: new Map(), hazards: new Map() } - const pending = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)] + const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)] + const result = { + files: 0, + compiled: 0, + diagnostics: new Map(), + hazards: new Map(), + uncompiled: readUncompiledFiles(root), + virtualizerHooks: collectVirtualizerHooks(sources), + liveReaders: collectLiveReaders(sources) + } + const pending = [...sources] result.files = pending.length await Promise.all( Array.from({ length: IN_FLIGHT }, async () => { diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs index 0dee8c26189..fbe7590cf13 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs @@ -31,6 +31,16 @@ export const HAZARD_FIXES = { 'React Compiler caches this render-time `store.getState()` snapshot on unrelated inputs, so it', 'goes stale. Read it in the event handler or effect that uses it, or select it with a hook.' ], + 'virtualizer-in-memo-block': [ + 'A TanStack virtualizer is one object mutated in place, so React Compiler serves rows, sizes or', + 'child elements cached on it after every scroll. Add the file to', + 'config/react-compiler-uncompiled-files.txt, owners that pass the virtualizer down included.' + ], + 'live-read-in-memo-block': [ + 'React Compiler caches this render-time read of module state (a provider runtime context key or a', + 'structured selection) on its arguments, so it misses the module-level change. Add the file to', + 'config/react-compiler-uncompiled-files.txt, or subscribe to the state so a change re-renders.' + ], 'hook-in-memo-block': [ 'React Compiler memoizes this hook call inside a cached block, so it runs only when the block', 'recomputes (a conditional hook). Call the hook in its own top-level `const` and use the variable.' @@ -247,16 +257,19 @@ function isStoreRead(node) { ) } -function memoizedCallKind(node) { +function memoizedCallKind(node, liveReaders) { if (isStoreRead(node)) { return { kind: 'store-read', name: 'getState' } } - const hook = calleeName(node.expression) - return hook && HOOK_NAME.test(hook) ? { kind: 'hook', name: hook } : null + const callee = calleeName(node.expression) + if (callee && liveReaders.has(callee)) { + return { kind: 'live-read', name: callee } + } + return callee && HOOK_NAME.test(callee) ? { kind: 'hook', name: callee } : null } -/** Hook calls and `getState()` reads the compiler placed inside a memo-cache guarded block. */ -export function findMemoizedCalls(fileName, compiledCode) { +/** Hook calls, `getState()` reads and live module-state reads the compiler placed inside a memo-cache guarded block. */ +export function findMemoizedCalls(fileName, compiledCode, liveReaders = new Set()) { if (!compiledCode.includes('compiler-runtime')) { return [] } @@ -271,7 +284,7 @@ export function findMemoizedCalls(fileName, compiledCode) { if (isFunctionNode(node)) { return } - const call = ts.isCallExpression(node) ? memoizedCallKind(node) : null + const call = ts.isCallExpression(node) ? memoizedCallKind(node, liveReaders) : null // Nested guarded blocks are walked once per enclosing block; keying by node dedupes them. if (call) { found.set(node, { fn, ...call }) @@ -315,6 +328,20 @@ export function findMemoizedStoreReads(fileName, compiledCode) { /** Source lines of render-time `getState()` calls in `fnName`; a useMemo/callback read is excluded. */ export function renderStoreReadLines(fileName, text, fnName) { + return renderCallLines(fileName, text, fnName, isStoreRead) +} + +/** Source lines of render-time calls to `callee` in `fnName`; a useMemo/callback call is excluded. */ +export function renderLiveReadLines(fileName, text, fnName, callee) { + return renderCallLines( + fileName, + text, + fnName, + (node) => ts.isCallExpression(node) && calleeName(node.expression) === callee + ) +} + +function renderCallLines(fileName, text, fnName, matches) { const sourceFile = parseModule(fileName, text) const lines = new Set() for (const { name, node: root } of listReactFunctions(sourceFile)) { @@ -325,7 +352,7 @@ export function renderStoreReadLines(fileName, text, fnName) { if (node !== root && isFunctionNode(node)) { return } - if (isStoreRead(node)) { + if (matches(node)) { lines.add(lineOf(sourceFile, node)) } ts.forEachChild(node, visit) @@ -335,6 +362,69 @@ export function renderStoreReadLines(fileName, text, fnName) { return [...lines].sort((a, b) => a - b) } +// Reads of module-level state that changes without a React update; a cache keyed on props keeps the old value. +export const LIVE_MODULE_READERS = [ + // Both fold in providerRuntimeSessionGeneration (lib/provider-runtime-context.ts). + 'getProviderRuntimeContextKey', + 'getEnvironmentRuntimeContextKey', + // Both read the selection lifetime registry in structured-agent-session-selection-controller.ts. + 'structuredSessionSelectionAuthority', + 'structuredSessionSelectionController' +] + +function moduleFunctionName(node) { + if (ts.isFunctionDeclaration(node) && node.name) { + return node.name.text + } + const parent = node.parent + return (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && + ts.isVariableDeclaration(parent) && + ts.isIdentifier(parent.name) && + ts.isVariableStatement(parent.parent?.parent) + ? parent.name.text + : null +} + +/** Module-scope plain functions whose own body calls a live reader, so their result is live too. */ +export function findLiveReadWrappers(fileName, text, readers) { + if (![...readers].some((reader) => text.includes(reader))) { + return [] + } + const sourceFile = parseModule(fileName, text) + const wrappers = [] + for (const statement of sourceFile.statements) { + const candidates = ts.isFunctionDeclaration(statement) + ? [statement] + : ts.isVariableStatement(statement) + ? statement.declarationList.declarations + .map((declaration) => declaration.initializer && unwrap(declaration.initializer)) + .filter((init) => init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) + : [] + for (const fn of candidates) { + const name = moduleFunctionName(fn) + if (!name || isReactName(name) || readers.has(name)) { + continue + } + let calls = false + const visit = (node) => { + if (calls || (node !== fn && isFunctionNode(node))) { + return + } + if (ts.isCallExpression(node) && readers.has(calleeName(node.expression) ?? '')) { + calls = true + return + } + ts.forEachChild(node, visit) + } + visit(fn) + if (calls) { + wrappers.push(name) + } + } + } + return wrappers +} + /** Source lines of `hook` calls in `fnName` that sit inside a larger expression. */ export function hookCallLines(fileName, text, fnName, hook) { const sourceFile = parseModule(fileName, text) @@ -358,3 +448,204 @@ export function hookCallLines(fileName, text, fnName, hook) { } return lines.size > 0 ? [...lines].sort((a, b) => a - b) : ['?'] } + +// A TanStack virtualizer is one object mutated in place, so a cache keyed on it never refreshes. +export const VIRTUALIZER_HOOKS = new Map([ + ['useVirtualizer', 'direct'], + ['useWindowVirtualizer', 'direct'] +]) +const VIRTUALIZER_NAME = /^\w*[vV]irtualizer$/ +const VIRTUALIZER_TYPE = /\bVirtualizer\s* text.includes(hook))) { + return [] + } + const sourceFile = parseModule(fileName, text) + const wrappers = [] + for (const { name, node } of listReactFunctions(sourceFile)) { + if (!HOOK_NAME.test(name) || hooks.has(name)) { + continue + } + const bound = new Set() + let shape = null + const visit = (child) => { + if (child !== node && isFunctionNode(child)) { + return + } + if ( + ts.isVariableDeclaration(child) && + ts.isIdentifier(child.name) && + virtualizerHookShape(child.initializer, hooks) === 'direct' + ) { + bound.add(child.name.text) + } + if (ts.isReturnStatement(child) && child.expression) { + const value = unwrap(child.expression) + if ( + (ts.isIdentifier(value) && bound.has(value.text)) || + virtualizerHookShape(value, hooks) === 'direct' + ) { + shape = 'direct' + } else if ( + ts.isObjectLiteralExpression(value) && + value.properties.some( + (p) => p.name && ts.isIdentifier(p.name) && p.name.text === 'virtualizer' + ) + ) { + shape ??= 'property' + } + } + ts.forEachChild(child, visit) + } + visit(node) + if (shape) { + wrappers.push({ name, shape }) + } + } + return wrappers +} + +/** Prop and parameter names this module types as a Virtualizer. */ +function virtualizerTypedNames(fileName, text) { + const names = new Set() + if (!VIRTUALIZER_TYPE.test(text)) { + return names + } + const sourceFile = parseModule(fileName, text) + const visit = (node) => { + if ( + (ts.isPropertySignature(node) || ts.isParameter(node)) && + node.type && + ts.isIdentifier(node.name) && + VIRTUALIZER_TYPE.test(node.type.getText(sourceFile)) + ) { + names.add(node.name.text) + } + ts.forEachChild(node, visit) + } + visit(sourceFile) + return names +} + +/** Cache blocks keyed on a virtualizer that read it or pass it as a JSX prop: `{ fn, text }`. */ +export function findVirtualizerMemoFlows( + fileName, + sourceText, + compiledCode, + hooks = VIRTUALIZER_HOOKS +) { + if ( + !compiledCode.includes('compiler-runtime') || + !( + /[vV]irtualizer/.test(compiledCode) || + [...hooks.keys()].some((hook) => compiledCode.includes(hook)) + ) + ) { + return [] + } + const typed = virtualizerTypedNames(fileName, sourceText) + const sourceFile = parseModule(fileName, compiledCode) + const runtime = compilerCacheNames(sourceFile) + if (runtime.size === 0) { + return [] + } + const caches = new Set() + const bound = new Set() + const isVirtualizer = (expression) => { + const node = unwrap(expression) + if (ts.isIdentifier(node)) { + const name = node.text.replace(/_\d+$/, '') + return bound.has(node.text) || VIRTUALIZER_NAME.test(name) || typed.has(name) + } + if (ts.isPropertyAccessExpression(node)) { + const name = node.name.text + return VIRTUALIZER_NAME.test(name) || typed.has(name) + } + return false + } + const keyedOnVirtualizer = (condition) => { + let keyed = false + const visit = (node) => { + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken && + (isVirtualizer(node.left) || isVirtualizer(node.right)) + ) { + keyed = true + } + if (!keyed) { + ts.forEachChild(node, visit) + } + } + visit(condition) + return keyed + } + const found = new Map() + // Closures call the live virtualizer when they run; only render-time reads and props go stale. + const collect = (fn, node) => { + if (isFunctionNode(node)) { + return + } + const passed = + ts.isJsxAttribute(node) && + node.initializer && + ts.isJsxExpression(node.initializer) && + node.initializer.expression && + isVirtualizer(node.initializer.expression) + const read = + ts.isPropertyAccessExpression(node) && + isVirtualizer(node.expression) && + !(STABLE_VIRTUALIZER_METHODS.has(node.name.text) && !ts.isCallExpression(node.parent)) + if (passed || read) { + found.set(node, { fn, text: node.getText(sourceFile).split('\n')[0].slice(0, 100) }) + return + } + ts.forEachChild(node, (child) => collect(fn, child)) + } + const visit = (fn, node) => { + if (ts.isVariableDeclaration(node) && node.initializer) { + const init = unwrap(node.initializer) + const shape = virtualizerHookShape(init, hooks) + if (ts.isIdentifier(node.name)) { + if ( + ts.isCallExpression(init) && + ts.isIdentifier(init.expression) && + runtime.has(init.expression.text) + ) { + caches.add(node.name.text) + } else if (shape === 'direct' || isVirtualizer(init)) { + bound.add(node.name.text) + } + } else if (ts.isObjectBindingPattern(node.name)) { + for (const element of node.name.elements) { + const key = (element.propertyName ?? element.name).getText(sourceFile) + if (ts.isIdentifier(element.name) && (key === 'virtualizer' || typed.has(key))) { + bound.add(element.name.text) + } + } + } + } + if ( + ts.isIfStatement(node) && + readsCache(node.expression, caches) && + keyedOnVirtualizer(node.expression) + ) { + collect(fn, node.thenStatement) + } + const next = isFunctionNode(node) ? (reactFunctionName(node) ?? fn) : fn + ts.forEachChild(node, (child) => visit(next, child)) + } + visit('(module)', sourceFile) + return [...found.values()] +} diff --git a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs index e7ec711261d..5a249927121 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.test.mjs @@ -1,9 +1,14 @@ import { describe, expect, it } from 'vitest' import { + findLiveReadWrappers, + findMemoizedCalls, findMemoizedHookCalls, findMemoizedStoreReads, findSourceHazards, + findVirtualizerMemoFlows, + findVirtualizerWrappers, + renderLiveReadLines, renderStoreReadLines } from './react-compiler-hazards.mjs' @@ -101,3 +106,90 @@ describe('store reads in memo blocks', () => { expect(renderStoreReadLines('a.ts', src, 'useRoute')).toEqual([3]) }) }) + +describe('virtualizer flows into memo blocks', () => { + it('follows wrapper hooks and flags cached reads and props, not closures or bound methods', () => { + const wrapper = [ + 'export function useRows(n) {', + ' const virtualizer = useVirtualizer({ count: n })', + ' return { virtualizer, n }', + '}' + ].join('\n') + expect(findVirtualizerWrappers('w.ts', wrapper)).toEqual([ + { name: 'useRows', shape: 'property' } + ]) + const hooks = new Map([ + ['useVirtualizer', 'direct'], + ['useList', 'direct'] + ]) + const compiled = [ + 'import { c as _c } from "react/compiler-runtime";', + 'export function Pane() {', + ' const $ = _c(4);', + ' const list = useList();', + ' let t0;', + ' if ($[0] !== list) {', + ' t0 = list.scrollToIndex(0)} rowRef={list.measureElement} />;', + ' $[0] = list;', + ' $[1] = t0;', + ' } else {', + ' t0 = $[1];', + ' }', + ' let t1;', + ' if ($[2] !== list) {', + ' t1 = () => list.getVirtualItems();', + ' $[2] = list;', + ' $[3] = t1;', + ' } else {', + ' t1 = $[3];', + ' }', + ' return t0;', + '}' + ].join('\n') + expect( + findVirtualizerMemoFlows('a.jsx', '', compiled, hooks).map(({ fn, text }) => `${fn}:${text}`) + ).toEqual(['Pane:list={list}', 'Pane:list.getTotalSize']) + }) +}) + +describe('live module-state reads in memo blocks', () => { + it('follows plain wrappers and flags a render read the compiler caches, not a useMemo one', () => { + const lib = [ + 'export function scopeKey(s) {', + ' return s ? runtimeKey(s.env) : null', + '}', + 'export const later = (s) => () => runtimeKey(s)', + 'export function useScope(s) {', + ' return runtimeKey(s)', + '}' + ].join('\n') + expect(findLiveReadWrappers('lib.ts', lib, new Set(['runtimeKey']))).toEqual(['scopeKey']) + const compiled = [ + 'import { c as _c } from "react/compiler-runtime";', + 'export function Card(t0) {', + ' const $ = _c(2);', + ' const { settings } = t0;', + ' let t1;', + ' if ($[0] !== settings) {', + ' t1 = scopeKey(settings);', + ' $[0] = settings;', + ' $[1] = t1;', + ' } else {', + ' t1 = $[1];', + ' }', + ' return t1;', + '}' + ].join('\n') + const readers = new Set(['runtimeKey', 'scopeKey']) + expect(findMemoizedCalls('a.js', compiled, readers)).toEqual([ + { fn: 'Card', kind: 'live-read', name: 'scopeKey' } + ]) + const src = [ + 'export function Card({ settings }) {', + ' const kept = useMemo(() => scopeKey(settings), [settings])', + ' return [kept, scopeKey(settings)]', + '}' + ].join('\n') + expect(renderLiveReadLines('a.tsx', src, 'Card', 'scopeKey')).toEqual([3]) + }) +}) diff --git a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs deleted file mode 100644 index 7e0a827a2ff..00000000000 --- a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs +++ /dev/null @@ -1,66 +0,0 @@ -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, describe, expect, it } from 'vitest' -import { copyScriptWithLocalModules } from './script-module-dependencies.mjs' - -const fixtureDir = mkdtempSync(join(tmpdir(), 'script-module-dependencies-')) - -afterAll(() => { - rmSync(fixtureDir, { recursive: true, force: true }) -}) - -function sourceTree(files) { - const sourceDir = mkdtempSync(join(fixtureDir, 'source-')) - for (const [name, contents] of Object.entries(files)) { - writeFileSync(join(sourceDir, name), contents) - } - return sourceDir -} - -function copiedNames(files, entryName) { - const sourceDir = sourceTree(files) - const destinationDir = join(mkdtempSync(join(fixtureDir, 'dest-')), 'scripts') - copyScriptWithLocalModules(join(sourceDir, entryName), destinationDir) - const names = readdirSync(destinationDir).sort() - for (const name of names) { - expect(readFileSync(join(destinationDir, name), 'utf8'), name).toBe(files[name]) - } - return names -} - -describe('copyScriptWithLocalModules', () => { - it('preserves parent paths for modules shared with the runtime', () => { - const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' }) - mkdirSync(join(sourceDir, 'scripts')) - writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n") - const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-')) - copyScriptWithLocalModules( - join(sourceDir, 'scripts', 'entry.mjs'), - join(destinationRoot, 'scripts') - ) - expect(readFileSync(join(destinationRoot, 'runtime.ts'), 'utf8')).toBe( - 'export const value = 42\n' - ) - }) - - // Cover require-only CJS gate dependencies so copied fixture fails for target defect, not missing module. - - it('follows a require reached only through an imported module', () => { - const names = copiedNames( - { - 'entry.mjs': "import './middle.cjs'\n", - 'middle.cjs': "require('./leaf.cjs')\n", - 'leaf.cjs': 'module.exports = {}\n' - }, - 'entry.mjs' - ) - expect(names).toContain('leaf.cjs') - }) - - it('terminates on a cycle rather than recursing forever', () => { - expect( - copiedNames({ 'a.mjs': "import './b.mjs'\n", 'b.mjs': "import './a.mjs'\n" }, 'a.mjs') - ).toEqual(['a.mjs', 'b.mjs']) - }) -}) diff --git a/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs new file mode 100644 index 00000000000..dff75d916d4 --- /dev/null +++ b/config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs @@ -0,0 +1,201 @@ +// Shared-worker files run back to back in one module cache; undo each file's mocks and process state. +// A file that leaves timers, listeners or globals behind also drops the module cache, as isolation would. +// Plain JS: it rewires Vitest's mocker and the timer globals, which have no public types. +import { promisify } from 'node:util' +import { afterAll, vi } from 'vitest' + +const VITEST_INTERNAL = /\/vitest\/dist\/|\/@vitest\/|vitest-virtual-/ +// Registries their owners create on first use and look up again on every access. +const LAZY_GLOBAL_REGISTRY = /^(?:Symbol\(orca\.|__zod_global)/ +const PROCESS_KEYS = ['platform', 'arch', 'execPath', 'argv', 'exitCode'] + +function resetNode(node) { + node.evaluated = false + node.promise = undefined + node.exports = undefined +} + +// Same reset Vitest's isolation applies, limited to modules that saw the mocked one. +function resetImportersOf(modules, id) { + const pending = [...(modules.getModuleById(id)?.importers ?? [])] + const seen = new Set() + while (pending.length > 0) { + const importer = pending.pop() + if (seen.has(importer) || VITEST_INTERNAL.test(importer)) { + continue + } + seen.add(importer) + const node = modules.getModuleById(importer) + if (node) { + resetNode(node) + pending.push(...node.importers) + } + } +} + +function resetAllModules(modules) { + for (const [id, node] of modules.idToModuleMap) { + if (!VITEST_INTERNAL.test(id)) { + resetNode(node) + node.importers.clear() + } + } +} + +function trackTimers(state) { + const real = { setTimeout, setInterval, clearTimeout, clearInterval } + function trackedSetTimeout(callback, ms, ...args) { + if (typeof callback !== 'function') { + return real.setTimeout(callback, ms, ...args) + } + const handle = real.setTimeout( + (...callbackArgs) => { + state.pendingTimers.delete(handle) + callback(...callbackArgs) + }, + ms, + ...args + ) + state.pendingTimers.add(handle) + return handle + } + trackedSetTimeout[promisify.custom] = real.setTimeout[promisify.custom] + globalThis.setTimeout = trackedSetTimeout + globalThis.setInterval = (...args) => { + const handle = real.setInterval(...args) + state.pendingTimers.add(handle) + return handle + } + globalThis.clearTimeout = (handle) => { + state.pendingTimers.delete(handle) + real.clearTimeout(handle) + } + globalThis.clearInterval = (handle) => { + state.pendingTimers.delete(handle) + real.clearInterval(handle) + } + state.clearTimer = (handle) => { + real.clearTimeout(handle) + real.clearInterval(handle) + } +} + +// The mocker lives across files, unlike this module, so it carries the once-per-worker state. +function installOnce(mocker) { + if (mocker.orcaSharedWorkerState) { + return mocker.orcaSharedWorkerState + } + const mockPath = mocker.mockPath.bind(mocker) + // Modules cached by an earlier file hold the real binding; re-run them against this file's mock. + mocker.mockPath = (originalId, id, ...rest) => { + mockPath(originalId, id, ...rest) + resetImportersOf(mocker.evaluatedModules, id) + } + const reset = mocker.reset.bind(mocker) + // And re-run them against the real module before the next file imports them. + mocker.reset = () => { + for (const registry of mocker.registries.values()) { + for (const url of registry.keys()) { + resetImportersOf(mocker.evaluatedModules, registry.get(url).id) + } + } + reset() + } + const state = { pendingTimers: new Set(), clearTimer: () => {} } + trackTimers(state) + mocker.orcaSharedWorkerState = state + return state +} + +const mocker = globalThis.__vitest_mocker__ +const state = mocker ? installOnce(mocker) : undefined +state?.pendingTimers.clear() + +const initialGlobals = Object.getOwnPropertyDescriptors(globalThis) +const initialProcess = Object.fromEntries( + PROCESS_KEYS.map((key) => [key, Object.getOwnPropertyDescriptor(process, key)]) +) +const initialListeners = new Map( + process.eventNames().map((event) => [event, new Set(process.listeners(event))]) +) +const initialEnv = { ...process.env } +const initialCwd = process.cwd() +const evaluatedBefore = new Set( + [...(mocker?.evaluatedModules.idToModuleMap ?? [])] + .filter(([, node]) => node.evaluated) + .map(([id]) => id) +) + +/** Puts process state back and reports what this file had left behind. */ +function restoreProcessState() { + const leaks = { globals: [], process: [] } + for (const key of Reflect.ownKeys(globalThis)) { + if (!(key in initialGlobals) && !LAZY_GLOBAL_REGISTRY.test(String(key))) { + leaks.globals.push(String(key)) + Reflect.deleteProperty(globalThis, key) + } + } + for (const [key, descriptor] of Object.entries(initialGlobals)) { + const current = Object.getOwnPropertyDescriptor(globalThis, key) + if (!Object.is(current?.value, descriptor.value) || current?.get !== descriptor.get) { + leaks.globals.push(key) + try { + Object.defineProperty(globalThis, key, descriptor) + } catch { + // Non-configurable globals cannot be put back; the module reset below still applies. + } + } + } + for (const key of PROCESS_KEYS) { + const descriptor = initialProcess[key] + if (descriptor) { + Object.defineProperty(process, key, descriptor) + } else { + Reflect.deleteProperty(process, key) + } + } + for (const event of process.eventNames()) { + const before = initialListeners.get(event) + for (const listener of process.listeners(event)) { + if (!before?.has(listener)) { + leaks.process.push(`${String(event)} listener`) + process.removeListener(event, listener) + } + } + } + for (const handle of state?.pendingTimers ?? []) { + leaks.process.push('timer') + state.clearTimer(handle) + } + state?.pendingTimers.clear() + for (const key of Object.keys(process.env)) { + if (!(key in initialEnv)) { + delete process.env[key] + } + } + Object.assign(process.env, initialEnv) + if (process.cwd() !== initialCwd) { + process.chdir(initialCwd) + } + return leaks +} + +afterAll(() => { + // Runs Vitest's end-of-file spy restore now: a spy restored by hand would otherwise be re-applied after this hook. + vi.restoreAllMocks() + vi.useRealTimers() + vi.unstubAllEnvs() + vi.unstubAllGlobals() + const leaks = restoreProcessState() + if (mocker && leaks.process.length > 0) { + // Any cached module may own a cleared timer or listener. + resetAllModules(mocker.evaluatedModules) + } else if (mocker && leaks.globals.length > 0) { + // A module this file loaded may have installed the global it now expects. + for (const [id, node] of mocker.evaluatedModules.idToModuleMap) { + if (node.evaluated && !evaluatedBefore.has(id) && !VITEST_INTERNAL.test(id)) { + resetNode(node) + } + } + } +}) diff --git a/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs new file mode 100644 index 00000000000..e436fafecca --- /dev/null +++ b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs @@ -0,0 +1,94 @@ +import { readFileSync, statSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' + +// vitest-shared-worker-file-reset.mjs undoes mocks, timers, stubs, env and cwd after each file. +// These can't be undone between files, so a file that uses them keeps its own worker. +const ISOLATION_REQUIRING_API = new RegExp( + [ + // Opt-out for a file whose state leaks in ways the reset cannot see. + String.raw`@orca-isolated-worker\b`, + String.raw`\bvi\.(?:doMock|unmock|doUnmock|resetModules)\(`, + String.raw`@vitest-environment\s+(?!node\b)`, + String.raw`\bglobalThis(?:\.\w+|\[[^\]]+\])\s*=[^=]`, + String.raw`\bObject\.defineProperty\(\s*(?:globalThis|process|navigator|window|document)\b` + ].join('|') +) +const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"]([^'"]+)['"]/g +const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.mjs', '.js'] + +function isFile(path) { + try { + return statSync(path).isFile() + } catch { + return false + } +} + +function resolveLocal(fromFile, specifier, aliases) { + let base = null + if (specifier.startsWith('./') || specifier.startsWith('../')) { + base = resolve(dirname(fromFile), specifier) + } else { + const alias = aliases.find(({ find }) => specifier === find || specifier.startsWith(`${find}/`)) + if (!alias) { + return null + } + base = join(alias.replacement, specifier.slice(alias.find.length)) + } + const stem = base.replace(/\.[cm]?jsx?$/, '') + const candidates = [ + base, + ...SOURCE_EXTENSIONS.map((extension) => stem + extension), + ...SOURCE_EXTENSIONS.map((extension) => join(base, `index${extension}`)) + ] + return ( + candidates.find( + (candidate) => !/[\\/]node_modules[\\/]/.test(candidate) && isFile(candidate) + ) ?? null + ) +} + +/** + * Returns the test files (root-relative, forward slashes) that can share a worker's module cache. + * Only the test file and the test-support files it imports are scanned, not production modules. + */ +export function filesSafeToShareWorker(root, files, aliases = []) { + const sources = new Map() + const read = (file) => { + let source = sources.get(file) + if (source === undefined) { + source = readFileSync(file, 'utf8') + sources.set(file, source) + } + return source + } + const isTestSupport = (file) => /\bfrom\s+['"]vitest['"]/.test(read(file)) + const memo = new Map() + const visiting = new Set() + const requiresIsolation = (file) => { + const known = memo.get(file) + if (known !== undefined) { + return known + } + if (visiting.has(file)) { + return false + } + visiting.add(file) + const source = read(file) + let result = ISOLATION_REQUIRING_API.test(source) + for (const match of result ? [] : source.matchAll(IMPORT_SPECIFIER)) { + const target = resolveLocal(file, match[1], aliases) + if (target && isTestSupport(target) && requiresIsolation(target)) { + result = true + break + } + } + visiting.delete(file) + memo.set(file, result) + return result + } + return files + .map((file) => resolve(root, file)) + .filter((file) => isFile(file) && !requiresIsolation(file)) + .map((file) => relative(root, file).replaceAll('\\', '/')) +} diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 3fc7dd70837..11fa95a615f 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -58,7 +58,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/acp/session/acp-structured-sign-in.test.ts', 'src/main/acp/session/acp-structured-session-adapter.test.ts', 'src/main/acp/session/acp-structured-session-adapter-resume.test.ts', - 'src/main/acp/history/acp-history-scaling.test.ts', 'src/main/pi/rpc-turn-races.test.ts', 'src/main/acp/session/children/acp-structured-child-session-end.test.ts', 'src/main/acp/session/children/acp-structured-child-stop.test.ts', diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 3166e02549d..22cec99aa84 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -157,7 +157,6 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'config/scripts/native-build/windows/windows-pe-machine.test.mjs', 'config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs', 'config/scripts/desktop-distribution/runtime-verification/verify-packaged-windows-agent-hook.test.mjs', - 'config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs', 'src/main/windows/windows-registry-addon.test.ts', 'src/main/daemon/executable-host/windows/testing/daemon-host-process-package.test.ts', 'src/shared/windows-security-addon.win32.test.ts', diff --git a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs b/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs deleted file mode 100644 index 7e3a023c4f4..00000000000 --- a/config/scripts/workflow/source-routing/pr-unit-support-routing.test.mjs +++ /dev/null @@ -1,98 +0,0 @@ -import { beforeAll, describe, expect, it } from 'vitest' -import { - buildUnitDependencyGraph, - collectUnitDependencyGraph, - unitConsumers -} from '../../ci/unit-selection/dependency-graph/ci-unit-dependency-graph.mjs' -import { - CROSS_VERSION_WIRE_DIR, - discoverUnitFiles -} from '../../ci/unit-selection/dependency-graph/ci-unit-files.mjs' - -const harness = - 'src/renderer/src/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture.ts' -const structuredSessionHarness = - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx' - -const unitHarnesses = [ - harness, - structuredSessionHarness, - 'src/renderer/src/store/slices/editor/editor-slice-test-harness.ts', - 'src/renderer/src/store/slices/browser/browser-slice-test-harness.ts', - 'src/renderer/src/runtime/hosted-terminals/creation/testing/web-runtime-terminal-create.test-fixture.ts', - 'src/renderer/src/runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness.ts' -] -const supportBridges = new Set([ - // Launch request suites' store rig; it takes the terminal harness's workspace layout. - 'src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts', - 'src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts', - 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts', - // Autosave suites' store rig; it takes the editor harness's tab-layout maps. - 'src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts', - // Closed-saving-view save suites' rig; it builds on the autosave rig above. - 'src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts', - // Browser suites' store with main drawing their tabs; it takes the browser harness's store. - 'src/renderer/src/store/slices/browser/browser-slice-drawn-from-main.test-fixture.ts' -]) - -function productConsumers(file, graph, unitFiles) { - return [...unitConsumers([file], graph.reverse)].filter( - (consumer) => - consumer !== file && - !unitFiles.has(consumer) && - !(consumer.startsWith(CROSS_VERSION_WIRE_DIR) && consumer.endsWith('.unit.test.ts')) && - !supportBridges.has(consumer) - ) -} - -describe('unit support import ownership', () => { - let graph - let unitFiles - beforeAll(() => { - graph = collectUnitDependencyGraph() - unitFiles = new Set(discoverUnitFiles()) - }, 60_000) - - it.each(unitHarnesses)('rejects any product consumer of %s', (unitHarness) => { - expect(graph.files.has(unitHarness)).toBe(true) - expect( - [...unitConsumers([unitHarness], graph.reverse)].some((file) => unitFiles.has(file)) - ).toBe(true) - expect(productConsumers(unitHarness, graph, unitFiles)).toEqual([]) - }) - - it.each([ - "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'", - "export * from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'", - "import('@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture')", - "import type { Fixture } from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'" - ])('detects a product importer using %s', (source) => { - const importer = 'src/renderer/src/runtime/product.ts' - const test = 'src/renderer/src/runtime/ownership.test.ts' - const synthetic = buildUnitDependencyGraph( - new Map([ - [harness, 'export const value = 1'], - [importer, source], - [test, "import './web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"] - ]) - ) - expect(productConsumers(harness, synthetic, new Set([test]))).toEqual([importer]) - }) - - it('rejects product consumers reached through an audited support bridge', () => { - const bridge = - 'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts' - const importer = 'src/renderer/src/components/editor/product.ts' - const synthetic = buildUnitDependencyGraph( - new Map([ - [harness, 'export const value = 1'], - [ - bridge, - "import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'" - ], - [importer, "import './model-lifetime/retention/editor-model-lifetime-fixture'"] - ]) - ) - expect(productConsumers(harness, synthetic, new Set())).toEqual([importer]) - }) -}) diff --git a/config/vitest.config.ts b/config/vitest.config.ts index 6202566aa32..7dc0f04c525 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -1,4 +1,4 @@ -import { readFileSync } from 'node:fs' +import { globSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { resolve } from 'node:path' import { normalizePath, transformWithOxc, type Plugin } from 'vite' @@ -9,12 +9,14 @@ import { UNIT_SETUP_FILES } from './scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs' import TimingSequencer from './scripts/ci/sharding/ci-unit-sequencer.mjs' +import { filesSafeToShareWorker } from './scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs' import RuntimeSequencer from './scripts/test-runtime/execution-policy/vitest-runtime-sequencer.mjs' import { getNodeRuntimeInclude } from './scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs' import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-runtime-pool' import { readRunFilters } from './scripts/test-runtime/execution-policy/vitest-run-filters.mjs' import { createWorkspaceSourceResolver } from './scripts/workspace/source-exports/workspace-source-exports.mjs' import { moduleCacheResolutionKey } from './scripts/test-runtime/module-cache/vitest-module-cache-resolution-key' +import { vitestReactCompiler } from './build-plugins/vitest-react-compiler' const nodeRuntimeInclude = process.versions.bun ? getNodeRuntimeInclude({ filters: readRunFilters() }) @@ -44,6 +46,7 @@ const transforms = { } } satisfies Plugin, ...(moduleCachePath ? [moduleCacheResolutionKey()] : []), + ...vitestReactCompiler(), { // Unit tests have no asset server; retain real catalog parsing through fetch(data:). name: 'locale-catalog-test-assets', @@ -121,7 +124,46 @@ const bunProject = { sequence: { groupOrder: 1 } } } -const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject] +// Files whose state the per-file reset can undo share one worker's module cache instead of +// re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off. +const runtimeProject = process.versions.bun ? bunProject : nodeProject +const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/'))) +const sharedWorkerFiles = + process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1' + ? [] + : filesSafeToShareWorker( + process.cwd(), + globSync(UNIT_INCLUDE) + .map((file) => file.replaceAll('\\', '/')) + .filter((file) => !nodeRuntimeFiles.has(file)), + [ + { find: '@renderer', replacement: resolve('src/renderer/src') }, + { find: '@', replacement: resolve('src/renderer/src') } + ] + ) +const sharedProjects = + sharedWorkerFiles.length > 0 + ? [ + { + ...runtimeProject, + test: { + ...runtimeProject.test, + name: `${runtimeProject.test.name}-shared`, + include: sharedWorkerFiles, + isolate: false, + setupFiles: [ + ...runtimeProject.test.setupFiles, + resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs') + ] + } + } + ] + : [] +runtimeProject.test.exclude = [ + ...(runtimeProject.test.exclude ?? testOptions.exclude), + ...sharedWorkerFiles +] +const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject, ...sharedProjects] export default defineConfig({ ...transforms, diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 673eb8847e7..0a2e110aca1 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -15,6 +15,7 @@ import { createViteCacheRetentionPlugin } from './config/build-plugins/vite-cach import { MAIN_BUILD_ENTRY_POINTS } from './config/build-plugins/main-build-entry-points' import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard' import { createDevServeConfig } from './config/build-plugins/dev-serve-config' +import { reactPluginOptions } from './config/build-plugins/react-compiler' import { resolveBuildSourceCommit } from './config/scripts/build-identity/build-source-commit.mjs' const BUNDLED_MAIN_DEPENDENCIES = new Set([ @@ -284,7 +285,7 @@ export const electronViteConfig: UserConfig = { } }, plugins: [ - react(), + react(reactPluginOptions()), tailwindcss(), createPdfjsViewerAssetsPlugin(), createViteCacheRetentionPlugin() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt index d3df9fffb59..045cce54908 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt @@ -3,6 +3,9 @@ package expo.modules.orcamobilewebshell /** Shared page/native bridge contract; framework-free for off-device checks. */ internal const val MOBILE_WEB_SHELL_BRIDGE_OBJECT = "orcaBridge" +/** Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers. */ +internal const val MOBILE_WEB_SHELL_PARKED_FRAME = """{"v":1,"type":"parked"}""" + /** Enforce the shared UTF-8 JSON byte ceiling natively, before parsing. */ internal const val MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES = 640 * 1024 diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt new file mode 100644 index 00000000000..af1aff6a343 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt @@ -0,0 +1,413 @@ +package expo.modules.orcamobilewebshell + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Color +import android.net.Uri +import android.os.Message +import android.view.View +import android.view.ViewGroup +import android.webkit.RenderProcessGoneDetail +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.webkit.JavaScriptReplyProxy +import androidx.webkit.ScriptHandler +import androidx.webkit.WebMessageCompat +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import expo.modules.kotlin.exception.CodedException +import java.io.ByteArrayInputStream + +/** Publish host and manifest map atomically/volatily: main-thread writes race Chromium’s interceptor. */ +private class MobileWebShellServed( + val generation: MobileWebShellGeneration, + val originHost: String +) + +/** Where a document's reports go: the view showing it, or the spare pool while it is parked. */ +internal interface MobileWebShellDocumentSink { + fun documentLoadState(payload: Map) + fun documentBridgeMessage(json: String) + fun documentExternalNavigation(url: String) +} + +/** One WebView and every fence on it, apart from React. The view hosts it and lays it out. */ +@SuppressLint("SetJavaScriptEnabled") +internal class MobileWebShellDocument(private val context: Context) { + var sink: MobileWebShellDocumentSink? = null + private var bridgeInstalled = false + private val bridgeGate = MobileWebShellBridgeGate() + // The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads. + @Volatile private var replyProxy: JavaScriptReplyProxy? = null + private var applied: MobileWebShellAppliedProps? = null + private val loadState = MobileWebShellLoadStateMachine() + // Failure state crosses main-thread callbacks and Chromium’s background interceptor. + @Volatile private var documentFailed = false + @Volatile private var served: MobileWebShellServed? = null + private var blocker: ScriptHandler? = null + // Read by the interceptor thread when it reports a failed main-frame load. + @Volatile var webView: WebView? = createWebView() + private set + + /** Still showable: not torn down, and no terminal load failure or renderer loss. */ + val isUsable: Boolean get() = webView != null && !loadState.isTerminal + + /** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */ + fun apply(generationDirectory: String, sessionId: String, bridgeEnabled: Boolean) { + val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled) + if (applied?.matches(next) == true) return + applied = next + documentFailed = false + loadState.reset() + val view = webView + if (view == null) { + // A dead renderer requires a remount; changed props must still report failure. + emit(loadState.rendererStillGone()) + return + } + view.stopLoading() + emit(loadState.started()) + + val origin = mobileWebShellOrigin(sessionId) + val host = mobileWebShellOriginHost(sessionId) + if (origin == null || host == null) { + // The private origin is the isolation primitive; a malformed session id leaves us without one. + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + val loaded = MobileWebShellGeneration.load(generationDirectory) + if (loaded == null) { + failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE) + return + } + blocker?.remove() + blocker = installMobileWebShellNetworkApiBlocker(view, origin) + if (blocker == null) { + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + if (!applyBridgeListener(view, origin, bridgeEnabled)) { + failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) + return + } + served = MobileWebShellServed(loaded, host) + view.visibility = View.VISIBLE + view.loadUrl("$origin/") + } + + /** Retire the old visible generation even when the replacement fails. */ + private fun failPropUpdate(reason: MobileWebShellFailureReason) { + // Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies. + removeBridgeListener() + served = null + webView?.visibility = View.INVISIBLE + emit(loadState.failed(reason)) + } + + /** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */ + private fun applyBridgeListener(view: WebView, origin: String, bridgeEnabled: Boolean): Boolean { + removeBridgeListener() + val outcome = mobileWebShellBridgeInstall( + bridgeEnabled, + WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) + ) + if (outcome != MobileWebShellBridgeInstall.INSTALL) { + return outcome == MobileWebShellBridgeInstall.SKIP + } + return runCatching { + WebViewCompat.addWebMessageListener( + view, + MOBILE_WEB_SHELL_BRIDGE_OBJECT, + setOf(origin), + bridgeListener + ) + bridgeInstalled = true + }.isSuccess + } + + /** The one way the bridge goes away, so no disable path can leave a listener behind. */ + private fun removeBridgeListener() { + val view = webView + if (bridgeInstalled && view != null) { + WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT) + } + bridgeInstalled = false + replyProxy = null + } + + /** Chromium calls this on the UI thread, which is also the only thread that may reply. */ + private val bridgeListener = WebViewCompat.WebMessageListener { + _, message, _, isMainFrame, proxy -> + val isStringMessage = message.type == WebMessageCompat.TYPE_STRING + val json = if (isStringMessage) message.data else null + if ( + acceptsMobileWebShellBridgeFrame( + isMainFrame, + isStringMessage, + loadState.hasCommittedDocument + ) && json != null && + bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size) + ) { + replyProxy = proxy + sink?.documentBridgeMessage(json) + } + } + + /** Throw so a host chunking bug rejects rather than leaving its request unsettled. */ + fun postBridgeMessage(json: String) { + val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException() + val byteCount = json.toByteArray(Charsets.UTF_8).size + if (!acceptsMobileWebShellBridgeByteCount(byteCount)) { + throw MobileWebShellBridgeMessageTooLargeException(byteCount) + } + proxy.postMessage(json) + } + + /** A frame from the shell itself, to the frame that spoke. */ + fun postHostFrame(json: String) { + replyProxy?.postMessage(json) + } + + /** The view's attach and detach: off-window, the page reads hidden, as a buried WKWebView does on iOS. */ + fun resume() { + webView?.onResume() + } + + fun pause() { + webView?.onPause() + } + + /** The view is done with it, or onRenderProcessGone. */ + fun destroyWebView() { + val view = webView ?: return + removeBridgeListener() + loadState.documentEnded() + webView = null + blocker?.remove() + blocker = null + served = null + documentFailed = false + view.stopLoading() + (view.parent as? ViewGroup)?.removeView(view) + view.destroy() + } + + // Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options. + // B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape. + @Suppress("DEPRECATION") + private fun createWebView(): WebView { + val view = MobileWebShellSelectionView(context) + view.setBackgroundColor(Color.TRANSPARENT) + view.settings.apply { + javaScriptEnabled = true + domStorageEnabled = false + databaseEnabled = false + allowFileAccess = false + allowFileAccessFromFileURLs = false + allowUniversalAccessFromFileURLs = false + allowContentAccess = false + javaScriptCanOpenWindowsAutomatically = false + setSupportMultipleWindows(false) + mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW + cacheMode = WebSettings.LOAD_NO_CACHE + blockNetworkLoads = true + mediaPlaybackRequiresUserGesture = true + setGeolocationEnabled(false) + } + // clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store. + view.webViewClient = ShellWebViewClient() + view.webChromeClient = object : WebChromeClient() { + override fun onCreateWindow( + view: WebView?, + isDialog: Boolean, + isUserGesture: Boolean, + resultMsg: Message? + ): Boolean = false + } + view.setDownloadListener { _, _, _, _, _ -> } + // Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity. + ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets -> + ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets)) + } + return view + } + + private fun emit(emission: MobileWebShellLoadEmission?) { + if (emission != null) sink?.documentLoadState(emission.toPayload()) + } + + /** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */ + private fun reportDocumentFailure() { + replyProxy = null + // Drop replies synchronously before Chromium’s error document commits and the posted hide runs. + loadState.documentEnded() + // Set before posting: intervening onPageFinished must not restore ready or expose the error page. + documentFailed = true + val epoch = loadState.epoch + // The WebView's queue, like the view it sits in: a detached document reports once it attaches. + webView?.post { + if (!documentFailed) return@post + val emission = loadState.failedDuring( + epoch, + MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED + ) ?: return@post + webView?.visibility = View.INVISIBLE + emit(emission) + } + } + + private fun isDocumentUrl(url: Uri): Boolean { + val host = served?.originHost ?: return false + return resolveMobileWebShellRequestPath(requestParts(url), host) == "/" + } + + private fun requestParts( + url: Uri, + method: String = "GET", + hasRangeHeader: Boolean = false + ): MobileWebShellRequestParts = MobileWebShellRequestParts( + method = method, + hasRangeHeader = hasRangeHeader, + scheme = url.scheme, + host = url.host, + port = url.port, + userInfo = url.userInfo, + query = url.query, + fragment = url.fragment, + encodedPath = url.encodedPath, + urlLength = url.toString().length + ) + + private fun serveRequest(request: WebResourceRequest): WebResourceResponse? { + val current = served ?: return null + val parts = requestParts( + request.url, + method = request.method, + hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) } + ) + val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null + val asset = current.generation.entries[path] ?: return null + val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null + val headers = mobileWebShellResponseHeaders(path, bytes.size) + val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType) + return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes)) + } + + private fun refusedResponse(): WebResourceResponse = WebResourceResponse( + MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE, + MOBILE_WEB_SHELL_REFUSAL_CHARSET, + MOBILE_WEB_SHELL_REFUSAL_STATUS, + MOBILE_WEB_SHELL_REFUSAL_REASON, + MOBILE_WEB_SHELL_REFUSAL_HEADERS, + ByteArrayInputStream(mobileWebShellRefusalBody()) + ) + + private inner class ShellWebViewClient : WebViewClient() { + /** Never null, so no request can fall through to the network. */ + override fun shouldInterceptRequest( + view: WebView, + request: WebResourceRequest + ): WebResourceResponse { + val response = serveRequest(request) + if (response != null) return response + if (request.isForMainFrame) reportDocumentFailure() + return refusedResponse() + } + + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + // hasGesture gates only opener offers: human requests may omit it and subframes can target top without it. + val verdict = mobileWebShellNavigationVerdict( + url = request.url?.toString(), + isForMainFrame = request.isForMainFrame, + // Not reported here, unlike WKNavigationAction.sourceFrame on iOS. + isFromSubframe = false, + isDocumentUrl = !mobileWebShellDropsNavigation( + requestParts(request.url), + served?.originHost, + request.isForMainFrame + ), + // loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load. + isShellLoad = false, + hasGesture = request.hasGesture(), + isDownload = false + ) + if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) { + sink?.documentExternalNavigation(verdict.url) + } + return verdict !is MobileWebShellNavigationVerdict.Allow + } + + override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { + // Discard the replaced document’s reply proxy; the next page must send ready. + replyProxy = null + loadState.documentEnded() + if (documentFailed || !isDocumentUrl(Uri.parse(url))) return + // Arm at commit before page script runs. + loadState.committed() + emit(loadState.started()) + } + + // history.replaceState changes the document path before finish; commit state identifies the load. + override fun onPageFinished(view: WebView, url: String) { + if (documentFailed || !loadState.hasCommittedDocument) return + view.visibility = View.VISIBLE + // Remove history so the page cannot return to a replaced document. + view.clearHistory() + emit(loadState.finished()) + } + + override fun onReceivedError( + view: WebView, + request: WebResourceRequest, + error: WebResourceError + ) { + if (request.isForMainFrame) reportDocumentFailure() + } + + override fun onReceivedHttpError( + view: WebView, + request: WebResourceRequest, + errorResponse: WebResourceResponse + ) { + if (request.isForMainFrame) reportDocumentFailure() + } + + /** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */ + override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { + // Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's. + val host = view.parent as? View ?: view + val background = !host.isShown || host.windowVisibility != View.VISIBLE + destroyWebView() + emit(loadState.rendererGone(background, detail.didCrash())) + return true + } + } +} + +internal class MobileWebShellBridgeUnavailableException : + CodedException("The mobile web shell bridge is not installed on this view") + +internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException( + "A bridge message of $byteCount bytes exceeds the " + + "$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap" +) + +/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */ +private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat = + WindowInsetsCompat.Builder(insets) + .setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE) + .build() + +private val SHELL_OWNED_INSET_TYPES = + WindowInsetsCompat.Type.systemBars() or + WindowInsetsCompat.Type.displayCutout() or + WindowInsetsCompat.Type.ime() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt index 493e50b9b5b..93737f6dd66 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt @@ -26,6 +26,7 @@ internal data class MobileWebShellLoadEmission( /** Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. Cross-thread readers require volatile state. */ internal class MobileWebShellLoadStateMachine { private var terminal = false + val isTerminal: Boolean get() = terminal private var last: MobileWebShellLoadEmission? = null private var rendererLoss: Pair? = null diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt new file mode 100644 index 00000000000..791dbba21cf --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt @@ -0,0 +1,169 @@ +package expo.modules.orcamobilewebshell + +import android.app.Activity +import android.app.ActivityManager +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import java.util.Collections +import java.util.WeakHashMap + +/** More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. */ +private const val MINIMUM_TOTAL_MEMORY_BYTES = 3L shl 30 + +/** A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. */ +private const val CLAIM_EXPIRY_MS = 10_000L + +/** Holds a parked WebView under the app's content: invisible, untouchable and out of accessibility. */ +private class MobileWebShellParking(context: Context) : FrameLayout(context) { + init { + alpha = 0f + isFocusable = false + descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + } + + override fun dispatchTouchEvent(event: MotionEvent): Boolean = false +} + +/** + * A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for + * the view that adopts it: a parked page stops asking for init, so its ready is answered from here. + */ +internal class MobileWebShellSpare( + activity: Activity, + val directory: String, + val sessionId: String +) : MobileWebShellDocumentSink { + val document = MobileWebShellDocument(activity) + val parking: ViewGroup = MobileWebShellParking(activity) + private val loadStates = mutableListOf>() + private var ready: String? = null + + init { + document.sink = this + } + + override fun documentLoadState(payload: Map) { + loadStates += payload + if (payload["state"] == "failed") MobileWebShellSparePool.discard(this) + } + + /** Before init a page only sends ready, from its first document or one it reloaded. */ + override fun documentBridgeMessage(json: String) { + ready = json + document.postHostFrame(MOBILE_WEB_SHELL_PARKED_FRAME) + } + + // A parked page has no screen to have been tapped on. + override fun documentExternalNavigation(url: String) = Unit + + /** The adopting view sees what a fresh document would have reported, ready last. */ + fun handOver(sink: MobileWebShellDocumentSink) { + document.sink = sink + loadStates.forEach(sink::documentLoadState) + ready?.let(sink::documentBridgeMessage) + } + + fun destroy() { + document.destroyWebView() + (parking.parent as? ViewGroup)?.removeView(parking) + } +} + +/** + * At most one document booted ahead of its screen, only while no page document is shown. Main thread only. + * Parked attached under the content, not detached: a detached WebView took 0.3–1.9 s to paint after 30 s, vs 0.2 s. + */ +internal object MobileWebShellSparePool { + private val main = Handler(Looper.getMainLooper()) + private var parked: MobileWebShellSpare? = null + private var claimed: MobileWebShellSpare? = null + private val shown: MutableSet = + Collections.newSetFromMap(WeakHashMap()) + + /** Whether a spare for [directory] is parked after the call; never on a small phone or beside a page. */ + fun prepare(activity: Activity, directory: String, sessionId: String): Boolean { + if (!inForeground() || cannotAffordSpare(activity) || shown.any { it.webView != null }) return false + val current = parked + if (current != null && current.directory == directory && current.document.isUsable) return true + val decor = activity.window?.decorView as? ViewGroup ?: return false + // A claim no view adopted was abandoned; it must not outlive the spare that replaces it. + discardAll() + val spare = MobileWebShellSpare(activity, directory, sessionId) + val webView = spare.document.webView ?: return false + spare.parking.addView(webView, FrameLayout.LayoutParams(MATCH, MATCH)) + decor.addView(spare.parking, 0, FrameLayout.LayoutParams(MATCH, MATCH)) + parked = spare + spare.document.apply(directory, sessionId, bridgeEnabled = true) + // A load that failed at once has already discarded it. + return parked === spare + } + + /** The parked spare's session id for a screen opening [directory], handed out once. */ + fun claim(directory: String): String? { + val spare = parked ?: return null + if (spare.directory != directory || !spare.document.isUsable) return null + parked = null + claimed = spare + main.postDelayed({ if (claimed === spare) discard(spare) }, CLAIM_EXPIRY_MS) + return spare.sessionId + } + + /** The claimed spare when [sessionId] names it, else a fresh document, which leaves no room for a spare. */ + fun document( + context: Context, + sessionId: String, + sink: MobileWebShellDocumentSink + ): MobileWebShellDocument { + val spare = claimed + val document = if (spare != null && spare.sessionId == sessionId && spare.document.isUsable) { + claimed = null + spare.document.webView?.let { spare.parking.removeView(it) } + (spare.parking.parent as? ViewGroup)?.removeView(spare.parking) + spare.handOver(sink) + spare.document + } else { + discardAll() + MobileWebShellDocument(context).also { it.sink = sink } + } + shown += document + return document + } + + /** Memory pressure, the app leaving the foreground, files going away, or Home without a claim. */ + fun discardAll() { + listOfNotNull(parked, claimed).forEach(MobileWebShellSpare::destroy) + parked = null + claimed = null + } + + fun discard(spare: MobileWebShellSpare) { + when { + parked === spare -> parked = null + claimed === spare -> claimed = null + else -> return + } + spare.destroy() + } + + /** React Native keeps its activity after it stops, so ask the process's own importance. */ + private fun inForeground(): Boolean { + val state = ActivityManager.RunningAppProcessInfo() + ActivityManager.getMyMemoryState(state) + return state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND + } + + private fun cannotAffordSpare(activity: Activity): Boolean { + val manager = activity.getSystemService(ActivityManager::class.java) ?: return true + val memory = ActivityManager.MemoryInfo().also(manager::getMemoryInfo) + // Android 14 stopped sending RUNNING_LOW trims to foreground apps, so check pressure before booting. + return manager.isLowRamDevice || memory.totalMem <= MINIMUM_TOTAL_MEMORY_BYTES || memory.lowMemory + } +} + +private const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt index 32f824dff4c..506c6e03202 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt @@ -2,44 +2,16 @@ package expo.modules.orcamobilewebshell import android.annotation.SuppressLint import android.content.Context -import android.graphics.Bitmap -import android.graphics.Color -import android.net.Uri -import android.os.Message -import android.view.View -import android.webkit.RenderProcessGoneDetail -import android.webkit.WebChromeClient -import android.webkit.WebResourceError -import android.webkit.WebResourceRequest -import android.webkit.WebResourceResponse -import android.webkit.WebSettings -import android.webkit.WebView -import android.webkit.WebViewClient -import androidx.core.graphics.Insets -import androidx.core.view.ViewCompat -import androidx.core.view.WindowInsetsCompat -import androidx.webkit.JavaScriptReplyProxy -import androidx.webkit.ScriptHandler -import androidx.webkit.WebMessageCompat -import androidx.webkit.WebViewCompat -import androidx.webkit.WebViewFeature import expo.modules.kotlin.AppContext -import expo.modules.kotlin.exception.CodedException import expo.modules.kotlin.viewevent.EventDispatcher import expo.modules.kotlin.views.ExpoView -import java.io.ByteArrayInputStream -/** Publish host and manifest map atomically/volatily: main-thread writes race Chromium’s interceptor. */ -private class MobileWebShellServed( - val generation: MobileWebShellGeneration, - val originHost: String -) - -@SuppressLint("ViewConstructor", "SetJavaScriptEnabled") +/** React Native's handle on one document: it lays the WebView out and forwards what it reports. */ +@SuppressLint("ViewConstructor") internal class OrcaMobileWebShellView( context: Context, appContext: AppContext -) : ExpoView(context, appContext) { +) : ExpoView(context, appContext), MobileWebShellDocumentSink { private val onLoadState by EventDispatcher>() private val onBridgeMessage by EventDispatcher>() private val onExternalNavigation by EventDispatcher>() @@ -47,23 +19,8 @@ internal class OrcaMobileWebShellView( private var generationDirectory = "" private var sessionId = "" private var bridgeEnabled = false - private var bridgeInstalled = false - private val bridgeGate = MobileWebShellBridgeGate() - // The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads. - @Volatile private var replyProxy: JavaScriptReplyProxy? = null - private var applied: MobileWebShellAppliedProps? = null - private val loadState = MobileWebShellLoadStateMachine() - // Failure state crosses main-thread callbacks and Chromium’s background interceptor. - @Volatile private var documentFailed = false - @Volatile private var served: MobileWebShellServed? = null - private var blocker: ScriptHandler? = null - private var webView: WebView? = createWebView() - - init { - addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) - // Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches. - webView?.onPause() - } + /** Taken on the first prop commit, not in init: the session id says whether a spare was booted for it. */ + private var document: MobileWebShellDocument? = null fun setGenerationDirectory(value: String) { generationDirectory = value @@ -77,348 +34,43 @@ internal class OrcaMobileWebShellView( bridgeEnabled = value } - /** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */ fun propsDidUpdate() { - val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled) - if (applied?.matches(next) == true) return - applied = next - documentFailed = false - loadState.reset() - val view = webView - if (view == null) { - // A dead renderer requires a remount; changed props must still report failure. - emit(loadState.rendererStillGone()) - return - } - view.stopLoading() - emit(loadState.started()) - - val origin = mobileWebShellOrigin(sessionId) - val host = mobileWebShellOriginHost(sessionId) - if (origin == null || host == null) { - // The private origin is the isolation primitive; a malformed session id leaves us without one. - failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) - return - } - val loaded = MobileWebShellGeneration.load(generationDirectory) - if (loaded == null) { - failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE) - return - } - blocker?.remove() - blocker = installMobileWebShellNetworkApiBlocker(view, origin) - if (blocker == null) { - failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) - return - } - if (!applyBridgeListener(view, origin)) { - failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE) - return - } - served = MobileWebShellServed(loaded, host) - view.visibility = View.VISIBLE - view.loadUrl("$origin/") + val current = document ?: hostDocument().also { document = it } + current.apply(generationDirectory, sessionId, bridgeEnabled) } - /** Retire the old visible generation even when the replacement fails. */ - private fun failPropUpdate(reason: MobileWebShellFailureReason) { - // Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies. - removeBridgeListener() - served = null - webView?.visibility = View.INVISIBLE - emit(loadState.failed(reason)) + private fun hostDocument(): MobileWebShellDocument { + val document = MobileWebShellSparePool.document(context, sessionId, this) + addView(document.webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + // Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches. + if (!isAttachedToWindow) document.pause() + return document } - /** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */ - private fun applyBridgeListener(view: WebView, origin: String): Boolean { - removeBridgeListener() - val outcome = mobileWebShellBridgeInstall( - bridgeEnabled, - WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) - ) - if (outcome != MobileWebShellBridgeInstall.INSTALL) { - return outcome == MobileWebShellBridgeInstall.SKIP - } - return runCatching { - WebViewCompat.addWebMessageListener( - view, - MOBILE_WEB_SHELL_BRIDGE_OBJECT, - setOf(origin), - bridgeListener - ) - bridgeInstalled = true - }.isSuccess - } - - /** The one way the bridge goes away, so no disable path can leave a listener behind. */ - private fun removeBridgeListener() { - val view = webView - if (bridgeInstalled && view != null) { - WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT) - } - bridgeInstalled = false - replyProxy = null - } - - /** Chromium calls this on the UI thread, which is also the only thread that may reply. */ - private val bridgeListener = WebViewCompat.WebMessageListener { - _, message, _, isMainFrame, proxy -> - val isStringMessage = message.type == WebMessageCompat.TYPE_STRING - val json = if (isStringMessage) message.data else null - if ( - acceptsMobileWebShellBridgeFrame( - isMainFrame, - isStringMessage, - loadState.hasCommittedDocument - ) && json != null && - bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size) - ) { - replyProxy = proxy - onBridgeMessage(mapOf("json" to json)) - } - } - - /** Throw so a host chunking bug rejects rather than leaving its request unsettled. */ fun postBridgeMessage(json: String) { - val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException() - val byteCount = json.toByteArray(Charsets.UTF_8).size - if (!acceptsMobileWebShellBridgeByteCount(byteCount)) { - throw MobileWebShellBridgeMessageTooLargeException(byteCount) - } - proxy.postMessage(json) + val current = document ?: throw MobileWebShellBridgeUnavailableException() + current.postBridgeMessage(json) } override fun onAttachedToWindow() { super.onAttachedToWindow() - webView?.onResume() + document?.resume() } // Stay paused whenever off-window so the page reads hidden, as a buried WKWebView does on iOS. override fun onDetachedFromWindow() { - webView?.onPause() + document?.pause() super.onDetachedFromWindow() } - /** Expo calls this once React Native is done with the view, and onRenderProcessGone calls it. */ + /** Expo calls this once React Native is done with the view. */ fun destroyWebView() { - val view = webView ?: return - removeBridgeListener() - loadState.documentEnded() - webView = null - blocker?.remove() - blocker = null - served = null - documentFailed = false - view.stopLoading() - removeView(view) - view.destroy() + document?.destroyWebView() } - // Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options. - // B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape. - @Suppress("DEPRECATION") - private fun createWebView(): WebView { - val view = MobileWebShellSelectionView(context) - view.setBackgroundColor(Color.TRANSPARENT) - view.settings.apply { - javaScriptEnabled = true - domStorageEnabled = false - databaseEnabled = false - allowFileAccess = false - allowFileAccessFromFileURLs = false - allowUniversalAccessFromFileURLs = false - allowContentAccess = false - javaScriptCanOpenWindowsAutomatically = false - setSupportMultipleWindows(false) - mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW - cacheMode = WebSettings.LOAD_NO_CACHE - blockNetworkLoads = true - mediaPlaybackRequiresUserGesture = true - setGeolocationEnabled(false) - } - // clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store. - view.webViewClient = ShellWebViewClient() - view.webChromeClient = object : WebChromeClient() { - override fun onCreateWindow( - view: WebView?, - isDialog: Boolean, - isUserGesture: Boolean, - resultMsg: Message? - ): Boolean = false - } - view.setDownloadListener { _, _, _, _, _ -> } - // Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity. - ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets -> - ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets)) - } - return view - } + override fun documentLoadState(payload: Map) = onLoadState(payload) - private fun emit(emission: MobileWebShellLoadEmission?) { - if (emission != null) onLoadState(emission.toPayload()) - } + override fun documentBridgeMessage(json: String) = onBridgeMessage(mapOf("json" to json)) - /** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */ - private fun reportDocumentFailure() { - replyProxy = null - // Drop replies synchronously before Chromium’s error document commits and the posted hide runs. - loadState.documentEnded() - // Set before posting: intervening onPageFinished must not restore ready or expose the error page. - documentFailed = true - val epoch = loadState.epoch - post { - if (!documentFailed) return@post - val emission = loadState.failedDuring( - epoch, - MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED - ) ?: return@post - webView?.visibility = View.INVISIBLE - emit(emission) - } - } - - private fun isDocumentUrl(url: Uri): Boolean { - val host = served?.originHost ?: return false - return resolveMobileWebShellRequestPath(requestParts(url), host) == "/" - } - - private fun requestParts( - url: Uri, - method: String = "GET", - hasRangeHeader: Boolean = false - ): MobileWebShellRequestParts = MobileWebShellRequestParts( - method = method, - hasRangeHeader = hasRangeHeader, - scheme = url.scheme, - host = url.host, - port = url.port, - userInfo = url.userInfo, - query = url.query, - fragment = url.fragment, - encodedPath = url.encodedPath, - urlLength = url.toString().length - ) - - private fun serveRequest(request: WebResourceRequest): WebResourceResponse? { - val current = served ?: return null - val parts = requestParts( - request.url, - method = request.method, - hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) } - ) - val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null - val asset = current.generation.entries[path] ?: return null - val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null - val headers = mobileWebShellResponseHeaders(path, bytes.size) - val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType) - return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes)) - } - - private fun refusedResponse(): WebResourceResponse = WebResourceResponse( - MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE, - MOBILE_WEB_SHELL_REFUSAL_CHARSET, - MOBILE_WEB_SHELL_REFUSAL_STATUS, - MOBILE_WEB_SHELL_REFUSAL_REASON, - MOBILE_WEB_SHELL_REFUSAL_HEADERS, - ByteArrayInputStream(mobileWebShellRefusalBody()) - ) - - private inner class ShellWebViewClient : WebViewClient() { - /** Never null, so no request can fall through to the network. */ - override fun shouldInterceptRequest( - view: WebView, - request: WebResourceRequest - ): WebResourceResponse { - val response = serveRequest(request) - if (response != null) return response - if (request.isForMainFrame) reportDocumentFailure() - return refusedResponse() - } - - override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { - // hasGesture gates only opener offers: human requests may omit it and subframes can target top without it. - val verdict = mobileWebShellNavigationVerdict( - url = request.url?.toString(), - isForMainFrame = request.isForMainFrame, - // Not reported here, unlike WKNavigationAction.sourceFrame on iOS. - isFromSubframe = false, - isDocumentUrl = !mobileWebShellDropsNavigation( - requestParts(request.url), - served?.originHost, - request.isForMainFrame - ), - // loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load. - isShellLoad = false, - hasGesture = request.hasGesture(), - isDownload = false - ) - if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) { - onExternalNavigation(mapOf("url" to verdict.url)) - } - return verdict !is MobileWebShellNavigationVerdict.Allow - } - - override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { - // Discard the replaced document’s reply proxy; the next page must send ready. - replyProxy = null - loadState.documentEnded() - if (documentFailed || !isDocumentUrl(Uri.parse(url))) return - // Arm at commit before page script runs. - loadState.committed() - emit(loadState.started()) - } - - // history.replaceState changes the document path before finish; commit state identifies the load. - override fun onPageFinished(view: WebView, url: String) { - if (documentFailed || !loadState.hasCommittedDocument) return - view.visibility = View.VISIBLE - // Remove history so the page cannot return to a replaced document. - view.clearHistory() - emit(loadState.finished()) - } - - override fun onReceivedError( - view: WebView, - request: WebResourceRequest, - error: WebResourceError - ) { - if (request.isForMainFrame) reportDocumentFailure() - } - - override fun onReceivedHttpError( - view: WebView, - request: WebResourceRequest, - errorResponse: WebResourceResponse - ) { - if (request.isForMainFrame) reportDocumentFailure() - } - - /** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */ - override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { - // Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's. - val background = !isShown || windowVisibility != View.VISIBLE - destroyWebView() - emit(loadState.rendererGone(background, detail.didCrash())) - return true - } - } + override fun documentExternalNavigation(url: String) = onExternalNavigation(mapOf("url" to url)) } - -internal class MobileWebShellBridgeUnavailableException : - CodedException("The mobile web shell bridge is not installed on this view") - -internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException( - "A bridge message of $byteCount bytes exceeds the " + - "$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap" -) - -/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */ -private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat = - WindowInsetsCompat.Builder(insets) - .setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE) - .build() - -private val SHELL_OWNED_INSET_TYPES = - WindowInsetsCompat.Type.systemBars() or - WindowInsetsCompat.Type.displayCutout() or - WindowInsetsCompat.Type.ime() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt index c3d036b0416..81e5a16133a 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt @@ -1,17 +1,75 @@ package expo.modules.orcamobilewebshell import android.content.ActivityNotFoundException +import android.content.ComponentCallbacks2 +import android.content.Context import android.content.Intent +import android.content.res.Configuration import android.net.Uri +import android.os.Handler +import android.os.Looper import expo.modules.kotlin.exception.CodedException import expo.modules.kotlin.exception.Exceptions +import expo.modules.kotlin.functions.Queues import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition class OrcaMobileWebShellModule : Module() { + private val main = Handler(Looper.getMainLooper()) + // Kept so teardown unregisters from the same context after React has let go of it. + private var callbacksContext: Context? = null + + // A spare is the first thing to give back: nothing is shown by it. UI_HIDDEN, above RUNNING_LOW, is + // the app leaving the foreground; an activity pause is not, since a notification tap or deep link + // pauses it on the way to the screen that would claim the spare. + private val memoryCallbacks = object : ComponentCallbacks2 { + override fun onTrimMemory(level: Int) { + if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) discardSpare() + } + + override fun onConfigurationChanged(newConfig: Configuration) = Unit + + @Deprecated("Deprecated in Java") + override fun onLowMemory() = discardSpare() + } + + // Callbacks and OnDestroy can run off the main thread, and the pool's WebViews must not. + private fun discardSpare() { + main.post { MobileWebShellSparePool.discardAll() } + } + override fun definition() = ModuleDefinition { Name("OrcaMobileWebShell") + OnCreate { + callbacksContext = appContext.reactContext?.applicationContext?.also { + it.registerComponentCallbacks(memoryCallbacks) + } + } + + OnDestroy { + callbacksContext?.unregisterComponentCallbacks(memoryCallbacks) + callbacksContext = null + discardSpare() + } + + OnActivityDestroys { + discardSpare() + } + + AsyncFunction("prepareSpareDocument") { directory: String, sessionId: String -> + val activity = appContext.currentActivity ?: return@AsyncFunction false + MobileWebShellSparePool.prepare(activity, directory, sessionId) + }.runOnQueue(Queues.MAIN) + + AsyncFunction("claimSpareDocument") { directory: String -> + MobileWebShellSparePool.claim(directory) + }.runOnQueue(Queues.MAIN) + + AsyncFunction("discardSpareDocument") { + MobileWebShellSparePool.discardAll() + }.runOnQueue(Queues.MAIN) + // Takes a FileProvider content:// URI; the grant lets the chosen viewer read Orca's cache file. AsyncFunction("presentPdf") { uri: String -> val activity = appContext.currentActivity ?: throw Exceptions.MissingActivity() diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift index 6a8fb35df39..f3d6ebb5cb4 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift @@ -5,6 +5,9 @@ enum MobileWebShellBridge { /// Use the same injected global/handler name on Android and iOS. static let handlerName = "orcaBridge" + /// Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers. + static let parkedFrame = #"{"v":1,"type":"parked"}"# + /// Enforce the shared UTF-8 JSON byte ceiling natively, before parsing. static let maxMessageByteCount = 640 * 1024 diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift new file mode 100644 index 00000000000..ae372997bf4 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift @@ -0,0 +1,606 @@ +import ExpoModulesCore +import WebKit + +private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1" + +/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing. +private let networkBlockRules = """ + [ + { "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } }, + { "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } } + ] + """ + +/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only. +private enum NetworkBlockRuleList { + private static var compiled: WKContentRuleList? + + /// Synchronous once compiled in this process; nil means isolation is unavailable. + static func load(_ completion: @escaping (WKContentRuleList?) -> Void) { + if let compiled { + completion(compiled) + return + } + // Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead. + guard let store = WKContentRuleListStore.default() else { + completion(nil) + return + } + store.compileContentRuleList( + forIdentifier: networkBlockIdentifier, + encodedContentRuleList: networkBlockRules + ) { ruleList, _ in + DispatchQueue.main.async { + if let ruleList { + compiled = ruleList + } + completion(ruleList) + } + } + } +} + +/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs. +/// Match Android; both non-configurable and non-writable prevent page replacement. +private let networkApiBlocker = """ + (function(){ + var deny=function(){throw new TypeError('Network access is disabled')}; + try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){} + try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){} + try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){} + })(); + """ + +/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker. +/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement. +private let bridgeInstaller = """ + (function(){ + var sink=window.webkit.messageHandlers.orcaBridge; + var handler=null; + var bridge={}; + Object.defineProperty(bridge,'postMessage',{value:function(json){ + if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')} + sink.postMessage(json)},configurable:false,writable:false,enumerable:true}); + Object.defineProperty(bridge,'onmessage',{get:function(){return handler}, + set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true}); + Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}}, + configurable:false,writable:false,enumerable:false}); + Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true}); + })(); + """ + +/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts. +private let bridgeDeliver = """ + globalThis.orcaBridge.__deliver(m) + """ + +private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler { + /// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks. + private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read") + /// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception. + private var liveTasks: Set = [] + + var sessionId: String? + var generation: MobileWebShellGeneration? + + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { + let key = ObjectIdentifier(urlSchemeTask) + liveTasks.insert(key) + guard + let sessionId, + let generation, + let url = urlSchemeTask.request.url, + let parts = MobileWebShellRequestParts(request: urlSchemeTask.request), + let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId), + let asset = generation.entries[path] + else { + fail(urlSchemeTask, key) + return + } + readQueue.async { [weak self] in + let data = try? Data(contentsOf: asset.file) + DispatchQueue.main.async { + guard let self, self.liveTasks.contains(key) else { return } + guard + let data, + let response = Self.makeResponse( + url: url, + asset: asset, + byteCount: data.count, + path: path + ) + else { + self.fail(urlSchemeTask, key) + return + } + self.liveTasks.remove(key) + urlSchemeTask.didReceive(response) + urlSchemeTask.didReceive(data) + urlSchemeTask.didFinish() + } + } + } + + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { + liveTasks.remove(ObjectIdentifier(urlSchemeTask)) + } + + private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) { + guard liveTasks.remove(key) != nil else { return } + urlSchemeTask.didFailWithError(URLError(.resourceUnavailable)) + } + + private static func makeResponse( + url: URL, + asset: MobileWebShellAsset, + byteCount: Int, + path: String + ) -> HTTPURLResponse? { + HTTPURLResponse( + url: url, + statusCode: 200, + httpVersion: "HTTP/1.1", + headerFields: MobileWebShellResponseHeaders.forPath( + path, + contentType: asset.contentType, + byteCount: byteCount + ) + ) + } +} + +/// WKUserContentController retains handlers; a weak document reference prevents a React-unmount leak. +private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler { + weak var document: MobileWebShellDocument? + + func userContentController( + _ controller: WKUserContentController, + didReceive message: WKScriptMessage + ) { + document?.receiveBridgeMessage(message) + } +} + +/// The RN host sees this, never the page: it is the difference between a request that failed and +/// one that never settles. +internal final class MobileWebShellBridgeDeliveryFailedException: GenericException, + @unchecked Sendable { + override var reason: String { + "The mobile web shell bridge could not deliver a message: \(param)" + } +} + +internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable { + override var reason: String { + "The mobile web shell bridge is not installed on this view" + } +} + +/// Throw so a host chunking bug rejects rather than leaving its request unsettled. +internal final class MobileWebShellBridgeMessageTooLargeException: GenericException, + @unchecked Sendable { + override var reason: String { + "A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap" + } +} + +/// Where a document's reports go: the view showing it, or the spare pool while it is parked. +protocol MobileWebShellDocumentSink: AnyObject { + func documentLoadState(_ payload: [String: Any]) + func documentBridgeMessage(_ json: String) + func documentExternalNavigation(_ url: String) +} + +/// One WKWebView and every fence on it, apart from React. The view hosts it and lays it out. +final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate { + weak var sink: MobileWebShellDocumentSink? + let webView: WKWebView + + private let schemeHandler = MobileWebShellSchemeHandler() + private let bridgeReceiver = MobileWebShellBridgeReceiver() + private let bridgeGate = MobileWebShellBridgeGate() + private var bridgeInstalled = false + private var bridgeTarget = MobileWebShellBridgeTarget() + private var applied: MobileWebShellAppliedProps? + private var appliedSessionId: String? { applied?.sessionId } + private var pendingDocumentUrl: URL? + private var isolationReady = false + private var isolationFailed = false + private var destroyed = false + private let loadState = MobileWebShellLoadStateMachine() + private var keyboardPreparationPending = false + private var windowObservers: [NSObjectProtocol] = [] + + override init() { + let configuration = WKWebViewConfiguration() + configuration.allowsInlineMediaPlayback = true + configuration.mediaTypesRequiringUserActionForPlayback = .all + // WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction. + configuration.websiteDataStore = .nonPersistent() + configuration.preferences.javaScriptCanOpenWindowsAutomatically = false + // Disabling text interaction suppresses text after keydown; page user-select handles long-press selection. + configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme) + configuration.userContentController.addUserScript(Self.makeBlockerScript()) + webView = WKWebView(frame: .zero, configuration: configuration) + super.init() + bridgeReceiver.document = self + webView.navigationDelegate = self + webView.uiDelegate = self + webView.allowsBackForwardNavigationGestures = false + // WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame. + webView.isOpaque = false + webView.backgroundColor = .clear + webView.scrollView.backgroundColor = .clear + webView.scrollView.contentInsetAdjustmentBehavior = .never + hideKeyboardAccessoryBar(of: webView) + ignoreKeyboardNotifications(in: webView) + for name in [ + UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification, + UIApplication.didBecomeActiveNotification, + UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification, + UITextView.textDidEndEditingNotification + ] { + windowObservers.append(NotificationCenter.default.addObserver( + forName: name, object: nil, queue: .main + ) { [weak self] _ in + self?.loadWhenIsolated() + }) + } + installNetworkBlock(into: configuration.userContentController) + } + + deinit { + for observer in windowObservers { + NotificationCenter.default.removeObserver(observer) + } + } + + /// Still showable: not torn down, and no terminal load failure or content-process loss. + var isUsable: Bool { !destroyed && !loadState.isTerminal } + + /// The spare pool's teardown; the content process goes with the last reference. + func destroy() { + destroyed = true + sink = nil + clearBridgeTarget() + pendingDocumentUrl = nil + webView.stopLoading() + webView.removeFromSuperview() + } + + /// Apply unordered props together; identical triples do not retry (remount required). + /// Include bridgeEnabled: document-start scripts require a reload to change. + func apply(generationDirectory: String, sessionId: String, bridgeEnabled: Bool) { + let next = MobileWebShellAppliedProps( + generationDirectory: generationDirectory, + sessionId: sessionId, + bridgeEnabled: bridgeEnabled + ) + guard applied?.matches(next) != true else { return } + applied = next + clearBridgeTarget() + loadState.reset() + pendingDocumentUrl = nil + webView.stopLoading() + webView.isHidden = false + emit(loadState.started()) + guard + MobileWebShellOrigin.isValidSessionId(sessionId), + let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId) + else { + // The private origin is the isolation primitive; a malformed session id leaves us without one. + failPropUpdate(.isolationUnavailable) + return + } + guard + let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory) + else { + failPropUpdate(.generationUnreadable) + return + } + schemeHandler.sessionId = sessionId + schemeHandler.generation = generation + applyBridgeInstallation(bridgeEnabled) + if isolationFailed { + failPropUpdate(.isolationUnavailable) + return + } + pendingDocumentUrl = documentUrl + loadWhenIsolated() + } + + /// Retire the old visible generation even when the replacement fails. + private func failPropUpdate(_ reason: MobileWebShellFailureReason) { + clearBridgeTarget() + schemeHandler.sessionId = nil + schemeHandler.generation = nil + pendingDocumentUrl = nil + webView.stopLoading() + webView.isHidden = true + emit(loadState.failed(reason)) + } + + /// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker. + private static func makeBlockerScript() -> WKUserScript { + WKUserScript( + source: networkApiBlocker, + injectionTime: .atDocumentStart, + forMainFrameOnly: false + ) + } + + /// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical. + private func applyBridgeInstallation(_ bridgeEnabled: Bool) { + guard bridgeEnabled != bridgeInstalled else { return } + clearBridgeTarget() + let controller = webView.configuration.userContentController + if bridgeEnabled { + controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName) + controller.addUserScript( + WKUserScript( + source: bridgeInstaller, + injectionTime: .atDocumentStart, + // Main-frame injection is convenience; accepts must still refuse subframes that reach the handler. + forMainFrameOnly: true + ) + ) + } else { + controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName) + controller.removeAllUserScripts() + controller.addUserScript(Self.makeBlockerScript()) + } + bridgeInstalled = bridgeEnabled + } + + /// Use the loaded session, not latest props; the replaced same-origin document survives until commit. + fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) { + guard bridgeInstalled, let json = message.body as? String else { return } + let origin = message.frameInfo.securityOrigin + let source = MobileWebShellBridgeSource( + isOurWebView: message.webView === webView, + isMainFrame: message.frameInfo.isMainFrame, + hasCommittedDocument: loadState.hasCommittedDocument, + originProtocol: origin.`protocol`, + originHost: origin.host + ) + guard + MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""), + bridgeGate.accepts(byteCount: json.utf8.count) + else { return } + bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host) + sink?.documentBridgeMessage(json) + } + + /// Anything that ends the document the page spoke from ends the only target native has. + private func clearBridgeTarget() { + bridgeTarget.clear() + } + + /// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang. + func postBridgeMessage(_ json: String, promise: Promise) throws { + guard + MobileWebShellBridge.canPost( + toFrameOriginHost: bridgeTarget.originHost, + sessionId: appliedSessionId ?? "", + hasCommittedDocument: loadState.hasCommittedDocument + ), + let frame = bridgeTarget.frame + else { + throw MobileWebShellBridgeUnavailableException() + } + let byteCount = json.utf8.count + guard MobileWebShellBridge.acceptsByteCount(byteCount) else { + throw MobileWebShellBridgeMessageTooLargeException(byteCount) + } + // Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke. + webView.callAsyncJavaScript( + bridgeDeliver, + arguments: ["m": json], + in: frame, + in: .page + ) { result in + switch result { + case .success: + promise.resolve() + case .failure(let error): + promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription)) + } + } + } + + /// A frame from the shell itself, to the frame that spoke; nothing waits on its delivery. + func postHostFrame(_ json: String) { + guard let frame = bridgeTarget.frame else { return } + webView.callAsyncJavaScript(bridgeDeliver, arguments: ["m": json], in: frame, in: .page) { _ in } + } + + private func installNetworkBlock(into controller: WKUserContentController) { + NetworkBlockRuleList.load { [weak self] ruleList in + guard let self else { return } + guard let ruleList else { + self.isolationFailed = true + self.pendingDocumentUrl = nil + // Rule compilation can finish after refusal; the state machine prevents a second terminal reason. + if self.appliedSessionId != nil { + self.failPropUpdate(.isolationUnavailable) + } + return + } + controller.add(ruleList) + self.isolationReady = true + self.loadWhenIsolated() + } + } + + /// Load only in a foreground-active key window; the view calls this again when it moves to one. + func loadWhenIsolated() { + guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending, + let window = webView.window, window.isKeyWindow, + window.windowScene?.activationState == .foregroundActive else { return } + keyboardPreparationPending = true + DispatchQueue.main.async { [weak self, weak window] in + guard let self else { return } + guard let window, self.webView.window === window, window.isKeyWindow, + window.windowScene?.activationState == .foregroundActive else { + self.keyboardPreparationPending = false + self.loadWhenIsolated() + return + } + let delay: TimeInterval + switch MobileWebShellKeyboardWarmup.prepare(in: window) { + case .ready(let remainingDelay): + delay = remainingDelay + case .waitingForTextInput: + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in + guard let self else { return } + self.keyboardPreparationPending = false + self.loadWhenIsolated() + } + return + case .failed: + self.keyboardPreparationPending = false + self.failPropUpdate(.documentLoadFailed) + return + } + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in + guard let self else { return } + self.keyboardPreparationPending = false + guard let window, self.webView.window === window, window.isKeyWindow, + window.windowScene?.activationState == .foregroundActive else { + self.loadWhenIsolated() + return + } + guard self.isolationReady, let url = self.pendingDocumentUrl else { return } + self.pendingDocumentUrl = nil + self.loadState.shellLoadStarted() + self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)) + } + } + } + + private func emit(_ emission: MobileWebShellLoadEmission?) { + guard let emission else { return } + sink?.documentLoadState(emission.payload) + } + + private func reportDocumentFailure() { + clearBridgeTarget() + emit(loadState.failed(.documentLoadFailed)) + } + + /// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError. + private func reportNavigationFailure(_ error: Error) { + let error = error as NSError + guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else { + return + } + reportDocumentFailure() + } + + private func isDocumentUrl(_ url: URL?) -> Bool { + guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false } + return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: appliedSessionId ?? "") == "/" + } + + func webView( + _ webView: WKWebView, + decidePolicyFor navigationAction: WKNavigationAction, + decisionHandler: @escaping (WKNavigationActionPolicy) -> Void + ) { + var isDownload = false + if #available(iOS 14.5, *) { + isDownload = navigationAction.shouldPerformDownload + } + let isMainFrame = navigationAction.targetFrame?.isMainFrame == true + // linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load. + let verdict = MobileWebShellNavigationPolicy.verdict( + url: navigationAction.request.url?.absoluteString, + isMainFrame: isMainFrame, + isDocumentUrl: isDocumentUrl(navigationAction.request.url), + isShellLoad: loadState.isShellLoad, + hasGesture: navigationAction.navigationType == .linkActivated, + isDownload: isDownload + ) + if case let .cancelAndOffer(url) = verdict { + sink?.documentExternalNavigation(url) + } + if verdict == .allow && isMainFrame { + // Spend before handing back the decision so another main-frame action cannot reuse the allowance. + loadState.shellLoadConsumed() + } + decisionHandler(verdict == .allow ? .allow : .cancel) + } + + func webView( + _ webView: WKWebView, + decidePolicyFor navigationResponse: WKNavigationResponse, + decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void + ) { + // Only srcdoc subframes pass the action policy; refusing one must not fail the shell document. + guard navigationResponse.isForMainFrame else { + let url = navigationResponse.response.url?.absoluteString + decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel) + return + } + let allowed = navigationResponse.canShowMIMEType && + isDocumentUrl(navigationResponse.response.url) + if !allowed { + reportDocumentFailure() + } + decisionHandler(allowed ? .allow : .cancel) + } + + func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { + // Clear replies and acceptance when the document is replaced; its successor must commit and send ready. + clearBridgeTarget() + loadState.documentEnded() + guard appliedSessionId != nil else { return } + emit(loadState.started()) + } + + /// Arm at commit, before document-start messages and didFinish. + func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { + guard isDocumentUrl(webView.url) else { return } + // Commit rearms acceptance, so clear the replaced frame here as well as at provisional start. + clearBridgeTarget() + loadState.committed() + } + + /// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality. + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + MobileWebShellWarmUp.release() + emit(loadState.finished()) + } + + func webView( + _ webView: WKWebView, + didFailProvisionalNavigation navigation: WKNavigation!, + withError error: Error + ) { + MobileWebShellWarmUp.release() + reportNavigationFailure(error) + } + + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + MobileWebShellWarmUp.release() + reportNavigationFailure(error) + } + + /// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy. + func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + MobileWebShellWarmUp.release() + clearBridgeTarget() + // Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active. + let background = webView.window == nil || UIApplication.shared.applicationState != .active + emit(loadState.failed(.renderProcessGone, background: background)) + } + + func webView( + _ webView: WKWebView, + createWebViewWith configuration: WKWebViewConfiguration, + for navigationAction: WKNavigationAction, + windowFeatures: WKWindowFeatures + ) -> WKWebView? { + nil + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift index 5fb8544ef73..b3e1fef7005 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift @@ -28,7 +28,7 @@ struct MobileWebShellLoadEmission: Equatable { /// Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. final class MobileWebShellLoadStateMachine { - private var isTerminal = false + private(set) var isTerminal = false private var last: MobileWebShellLoadEmission? /// Accept messages only after the current props’ document commits; the replaced same-origin document can still speak before then. diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift new file mode 100644 index 00000000000..92e9ff89ffc --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift @@ -0,0 +1,150 @@ +import UIKit +import WebKit + +/// More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. +private let minimumPhysicalMemory: UInt64 = 3 << 30 + +/// A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. +private let claimExpirySeconds: TimeInterval = 10 + +/// A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for +/// the view that adopts it: a parked page stops asking for init, so its ready is answered from here. +final class MobileWebShellSpare: MobileWebShellDocumentSink { + let document = MobileWebShellDocument() + let directory: String + let sessionId: String + private var loadStates: [[String: Any]] = [] + private var ready: String? + + init(directory: String, sessionId: String) { + self.directory = directory + self.sessionId = sessionId + document.sink = self + } + + func documentLoadState(_ payload: [String: Any]) { + loadStates.append(payload) + if payload["state"] as? String == "failed" { + MobileWebShellSparePool.shared.discard(self) + } + } + + /// Before init a page only sends ready, from its first document or one it reloaded. + func documentBridgeMessage(_ json: String) { + ready = json + document.postHostFrame(MobileWebShellBridge.parkedFrame) + } + + /// A parked page has no screen to have been tapped on. + func documentExternalNavigation(_ url: String) {} + + /// The adopting view sees what a fresh document would have reported, ready last. + func handOver(to sink: MobileWebShellDocumentSink) { + document.sink = sink + loadStates.forEach(sink.documentLoadState) + if let ready { + sink.documentBridgeMessage(ready) + } + } +} + +/// At most one document booted ahead of its screen, only while no page document is shown. Main thread only. +/// Parked in the key window at alpha 0: WebKit suspends an off-window view (0.5–1.3 s to paint after 30 s, vs 0.1 s). +final class MobileWebShellSparePool { + static let shared = MobileWebShellSparePool() + + private var parked: MobileWebShellSpare? + private var claimed: MobileWebShellSpare? + private let shown = NSHashTable.weakObjects() + + /// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown page. + func prepare(directory: String, sessionId: String) -> Bool { + guard + ProcessInfo.processInfo.physicalMemory > minimumPhysicalMemory, + UIApplication.shared.applicationState == .active, + shown.allObjects.isEmpty, + let window = keyWindow() + else { return false } + if let parked, parked.directory == directory, parked.document.isUsable { + return true + } + // A claim no view adopted was abandoned; it must not outlive the spare that replaces it. + discardAll() + let spare = MobileWebShellSpare(directory: directory, sessionId: sessionId) + let webView = spare.document.webView + webView.alpha = 0 + webView.isUserInteractionEnabled = false + webView.accessibilityElementsHidden = true + webView.frame = window.bounds + webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + window.insertSubview(webView, at: 0) + parked = spare + spare.document.apply(generationDirectory: directory, sessionId: sessionId, bridgeEnabled: true) + // A load that failed at once has already discarded it. + return parked === spare + } + + /// The parked spare's session id for a screen opening `directory`, handed out once. + func claim(directory: String) -> String? { + guard let spare = parked, spare.directory == directory, spare.document.isUsable else { + return nil + } + parked = nil + claimed = spare + DispatchQueue.main.asyncAfter(deadline: .now() + claimExpirySeconds) { [weak self, weak spare] in + if let self, let spare, self.claimed === spare { + self.discard(spare) + } + } + return spare.sessionId + } + + /// The claimed spare when `sessionId` names it, else a fresh document, which leaves no room for a spare. + func document(for sessionId: String, sink: MobileWebShellDocumentSink) -> MobileWebShellDocument { + let document: MobileWebShellDocument + if let spare = claimed, spare.sessionId == sessionId, spare.document.isUsable { + claimed = nil + document = spare.document + let webView = document.webView + webView.removeFromSuperview() + webView.alpha = 1 + webView.isUserInteractionEnabled = true + webView.accessibilityElementsHidden = false + webView.autoresizingMask = [] + spare.handOver(to: sink) + } else { + discardAll() + document = MobileWebShellDocument() + document.sink = sink + } + shown.add(document) + return document + } + + /// Memory pressure, the app leaving the foreground, files going away, or Home without a claim. + func discardAll() { + for spare in [parked, claimed].compactMap({ $0 }) { + spare.document.destroy() + } + parked = nil + claimed = nil + } + + fileprivate func discard(_ spare: MobileWebShellSpare) { + if parked === spare { + parked = nil + } else if claimed === spare { + claimed = nil + } else { + return + } + spare.document.destroy() + } + + private func keyWindow() -> UIWindow? { + UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .flatMap(\.windows) + .first(where: \.isKeyWindow) + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift index d341acab6bc..91aa028d7fa 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift @@ -1,190 +1,8 @@ import ExpoModulesCore import WebKit -private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1" - -/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing. -private let networkBlockRules = """ - [ - { "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } }, - { "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } } - ] - """ - -/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only. -private enum NetworkBlockRuleList { - private static var compiled: WKContentRuleList? - - /// Synchronous once compiled in this process; nil means isolation is unavailable. - static func load(_ completion: @escaping (WKContentRuleList?) -> Void) { - if let compiled { - completion(compiled) - return - } - // Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead. - guard let store = WKContentRuleListStore.default() else { - completion(nil) - return - } - store.compileContentRuleList( - forIdentifier: networkBlockIdentifier, - encodedContentRuleList: networkBlockRules - ) { ruleList, _ in - DispatchQueue.main.async { - if let ruleList { - compiled = ruleList - } - completion(ruleList) - } - } - } -} - -/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs. -/// Match Android; both non-configurable and non-writable prevent page replacement. -private let networkApiBlocker = """ - (function(){ - var deny=function(){throw new TypeError('Network access is disabled')}; - try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){} - try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){} - try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){} - })(); - """ - -/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker. -/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement. -private let bridgeInstaller = """ - (function(){ - var sink=window.webkit.messageHandlers.orcaBridge; - var handler=null; - var bridge={}; - Object.defineProperty(bridge,'postMessage',{value:function(json){ - if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')} - sink.postMessage(json)},configurable:false,writable:false,enumerable:true}); - Object.defineProperty(bridge,'onmessage',{get:function(){return handler}, - set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true}); - Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}}, - configurable:false,writable:false,enumerable:false}); - Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true}); - })(); - """ - -/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts. -private let bridgeDeliver = """ - globalThis.orcaBridge.__deliver(m) - """ - -private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler { - /// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks. - private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read") - /// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception. - private var liveTasks: Set = [] - - var sessionId: String? - var generation: MobileWebShellGeneration? - - func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { - let key = ObjectIdentifier(urlSchemeTask) - liveTasks.insert(key) - guard - let sessionId, - let generation, - let url = urlSchemeTask.request.url, - let parts = MobileWebShellRequestParts(request: urlSchemeTask.request), - let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId), - let asset = generation.entries[path] - else { - fail(urlSchemeTask, key) - return - } - readQueue.async { [weak self] in - let data = try? Data(contentsOf: asset.file) - DispatchQueue.main.async { - guard let self, self.liveTasks.contains(key) else { return } - guard - let data, - let response = Self.makeResponse( - url: url, - asset: asset, - byteCount: data.count, - path: path - ) - else { - self.fail(urlSchemeTask, key) - return - } - self.liveTasks.remove(key) - urlSchemeTask.didReceive(response) - urlSchemeTask.didReceive(data) - urlSchemeTask.didFinish() - } - } - } - - func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { - liveTasks.remove(ObjectIdentifier(urlSchemeTask)) - } - - private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) { - guard liveTasks.remove(key) != nil else { return } - urlSchemeTask.didFailWithError(URLError(.resourceUnavailable)) - } - - private static func makeResponse( - url: URL, - asset: MobileWebShellAsset, - byteCount: Int, - path: String - ) -> HTTPURLResponse? { - HTTPURLResponse( - url: url, - statusCode: 200, - httpVersion: "HTTP/1.1", - headerFields: MobileWebShellResponseHeaders.forPath( - path, - contentType: asset.contentType, - byteCount: byteCount - ) - ) - } -} - -/// WKUserContentController retains handlers; a weak view reference prevents a React-unmount leak. -private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler { - weak var view: OrcaMobileWebShellView? - - func userContentController( - _ controller: WKUserContentController, - didReceive message: WKScriptMessage - ) { - view?.receiveBridgeMessage(message) - } -} - -/// The RN host sees this, never the page: it is the difference between a request that failed and -/// one that never settles. -internal final class MobileWebShellBridgeDeliveryFailedException: GenericException, - @unchecked Sendable { - override var reason: String { - "The mobile web shell bridge could not deliver a message: \(param)" - } -} - -internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable { - override var reason: String { - "The mobile web shell bridge is not installed on this view" - } -} - -/// Throw so a host chunking bug rejects rather than leaving its request unsettled. -internal final class MobileWebShellBridgeMessageTooLargeException: GenericException, - @unchecked Sendable { - override var reason: String { - "A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap" - } -} - -final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate, +/// React Native's handle on one document: it lays the WebView out and owns the back-edge swipe. +final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink, UIGestureRecognizerDelegate { let onLoadState = EventDispatcher() let onBridgeMessage = EventDispatcher() @@ -193,58 +11,28 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate // The page's own Back: the stack's swipe is off while the page claims Back, and a strip overlay would eat taps. private let backEdgePan = UIPanGestureRecognizer() - private let schemeHandler = MobileWebShellSchemeHandler() - private let bridgeReceiver = MobileWebShellBridgeReceiver() - private let bridgeGate = MobileWebShellBridgeGate() - private var bridgeEnabled = false - private var bridgeInstalled = false - private var bridgeTarget = MobileWebShellBridgeTarget() - private var webView: WKWebView! + /// Taken on the first prop commit, not in init: the session id says whether a spare was booted for it. + private var document: MobileWebShellDocument? private var generationDirectory = "" private var sessionId = "" - private var applied: MobileWebShellAppliedProps? - private var appliedSessionId: String? { applied?.sessionId } - private var pendingDocumentUrl: URL? - private var isolationReady = false - private var isolationFailed = false - private let loadState = MobileWebShellLoadStateMachine() - private var keyboardPreparationPending = false - private var windowObservers: [NSObjectProtocol] = [] + private var bridgeEnabled = false override func didMoveToWindow() { super.didMoveToWindow() - loadWhenIsolated() - } - - deinit { - for observer in windowObservers { - NotificationCenter.default.removeObserver(observer) - } + document?.loadWhenIsolated() } required init(appContext: AppContext? = nil) { super.init(appContext: appContext) - let configuration = WKWebViewConfiguration() - configuration.allowsInlineMediaPlayback = true - configuration.mediaTypesRequiringUserActionForPlayback = .all - // WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction. - configuration.websiteDataStore = .nonPersistent() - configuration.preferences.javaScriptCanOpenWindowsAutomatically = false - // Disabling text interaction suppresses text after keydown; page user-select handles long-press selection. - configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme) - configuration.userContentController.addUserScript(Self.makeBlockerScript()) - bridgeReceiver.view = self - webView = WKWebView(frame: bounds, configuration: configuration) - webView.navigationDelegate = self - webView.uiDelegate = self - webView.allowsBackForwardNavigationGestures = false - // WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame. - webView.isOpaque = false - webView.backgroundColor = .clear - webView.scrollView.backgroundColor = .clear - webView.scrollView.contentInsetAdjustmentBehavior = .never - hideKeyboardAccessoryBar(of: webView) - ignoreKeyboardNotifications(in: webView) + backEdgePan.isEnabled = false + backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:))) + backEdgePan.delegate = self + addGestureRecognizer(backEdgePan) + } + + private func hostDocument() -> MobileWebShellDocument { + let document = MobileWebShellSparePool.shared.document(for: sessionId, sink: self) + let webView = document.webView webView.translatesAutoresizingMaskIntoConstraints = false addSubview(webView) NSLayoutConstraint.activate([ @@ -253,24 +41,8 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate webView.leadingAnchor.constraint(equalTo: leadingAnchor), webView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) - for name in [ - UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification, - UIApplication.didBecomeActiveNotification, - UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification, - UITextView.textDidEndEditingNotification - ] { - windowObservers.append(NotificationCenter.default.addObserver( - forName: name, object: nil, queue: .main - ) { [weak self] _ in - self?.loadWhenIsolated() - }) - } - installNetworkBlock(into: configuration.userContentController) - backEdgePan.isEnabled = false - backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:))) - backEdgePan.delegate = self - addGestureRecognizer(backEdgePan) webView.scrollView.panGestureRecognizer.require(toFail: backEdgePan) + return document } func setBackEdgeSwipe(_ value: Bool) { @@ -310,332 +82,30 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate bridgeEnabled = value } - /// Apply unordered props together; identical triples do not retry (remount required). - /// Include bridgeEnabled: document-start scripts require a reload to change. func propsDidUpdate() { - let next = MobileWebShellAppliedProps( + let document = self.document ?? hostDocument() + self.document = document + document.apply( generationDirectory: generationDirectory, sessionId: sessionId, bridgeEnabled: bridgeEnabled ) - guard applied?.matches(next) != true else { return } - applied = next - clearBridgeTarget() - loadState.reset() - pendingDocumentUrl = nil - webView.stopLoading() - webView.isHidden = false - emit(loadState.started()) - guard - MobileWebShellOrigin.isValidSessionId(sessionId), - let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId) - else { - // The private origin is the isolation primitive; a malformed session id leaves us without one. - failPropUpdate(.isolationUnavailable) - return - } - guard - let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory) - else { - failPropUpdate(.generationUnreadable) - return - } - schemeHandler.sessionId = sessionId - schemeHandler.generation = generation - applyBridgeInstallation() - if isolationFailed { - failPropUpdate(.isolationUnavailable) - return - } - pendingDocumentUrl = documentUrl - loadWhenIsolated() } - /// Retire the old visible generation even when the replacement fails. - private func failPropUpdate(_ reason: MobileWebShellFailureReason) { - clearBridgeTarget() - schemeHandler.sessionId = nil - schemeHandler.generation = nil - pendingDocumentUrl = nil - webView.stopLoading() - webView.isHidden = true - emit(loadState.failed(reason)) + func postBridgeMessage(_ json: String, promise: Promise) throws { + guard let document else { throw MobileWebShellBridgeUnavailableException() } + try document.postBridgeMessage(json, promise: promise) } - /// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker. - private static func makeBlockerScript() -> WKUserScript { - WKUserScript( - source: networkApiBlocker, - injectionTime: .atDocumentStart, - forMainFrameOnly: false - ) + func documentLoadState(_ payload: [String: Any]) { + onLoadState(payload) } - /// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical. - private func applyBridgeInstallation() { - guard bridgeEnabled != bridgeInstalled else { return } - clearBridgeTarget() - let controller = webView.configuration.userContentController - if bridgeEnabled { - controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName) - controller.addUserScript( - WKUserScript( - source: bridgeInstaller, - injectionTime: .atDocumentStart, - // Main-frame injection is convenience; accepts must still refuse subframes that reach the handler. - forMainFrameOnly: true - ) - ) - } else { - controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName) - controller.removeAllUserScripts() - controller.addUserScript(Self.makeBlockerScript()) - } - bridgeInstalled = bridgeEnabled - } - - /// Use the loaded session, not latest props; the replaced same-origin document survives until commit. - fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) { - guard bridgeInstalled, let json = message.body as? String else { return } - let origin = message.frameInfo.securityOrigin - let source = MobileWebShellBridgeSource( - isOurWebView: message.webView === webView, - isMainFrame: message.frameInfo.isMainFrame, - hasCommittedDocument: loadState.hasCommittedDocument, - originProtocol: origin.`protocol`, - originHost: origin.host - ) - guard - MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""), - bridgeGate.accepts(byteCount: json.utf8.count) - else { return } - bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host) + func documentBridgeMessage(_ json: String) { onBridgeMessage(["json": json]) } - /// Anything that ends the document the page spoke from ends the only target native has. - private func clearBridgeTarget() { - bridgeTarget.clear() - } - - /// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang. - func postBridgeMessage(_ json: String, promise: Promise) throws { - guard - MobileWebShellBridge.canPost( - toFrameOriginHost: bridgeTarget.originHost, - sessionId: appliedSessionId ?? "", - hasCommittedDocument: loadState.hasCommittedDocument - ), - let frame = bridgeTarget.frame - else { - throw MobileWebShellBridgeUnavailableException() - } - let byteCount = json.utf8.count - guard MobileWebShellBridge.acceptsByteCount(byteCount) else { - throw MobileWebShellBridgeMessageTooLargeException(byteCount) - } - // Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke. - webView.callAsyncJavaScript( - bridgeDeliver, - arguments: ["m": json], - in: frame, - in: .page - ) { result in - switch result { - case .success: - promise.resolve() - case .failure(let error): - promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription)) - } - } - } - - private func installNetworkBlock(into controller: WKUserContentController) { - NetworkBlockRuleList.load { [weak self] ruleList in - guard let self else { return } - guard let ruleList else { - self.isolationFailed = true - self.pendingDocumentUrl = nil - // Rule compilation can finish after refusal; the state machine prevents a second terminal reason. - if self.appliedSessionId != nil { - self.failPropUpdate(.isolationUnavailable) - } - return - } - controller.add(ruleList) - self.isolationReady = true - self.loadWhenIsolated() - } - } - - private func loadWhenIsolated() { - guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending, - let window, window.isKeyWindow, - window.windowScene?.activationState == .foregroundActive else { return } - keyboardPreparationPending = true - DispatchQueue.main.async { [weak self, weak window] in - guard let self else { return } - guard let window, self.window === window, window.isKeyWindow, - window.windowScene?.activationState == .foregroundActive else { - self.keyboardPreparationPending = false - self.loadWhenIsolated() - return - } - let delay: TimeInterval - switch MobileWebShellKeyboardWarmup.prepare(in: window) { - case .ready(let remainingDelay): - delay = remainingDelay - case .waitingForTextInput: - DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in - guard let self else { return } - self.keyboardPreparationPending = false - self.loadWhenIsolated() - } - return - case .failed: - self.keyboardPreparationPending = false - self.failPropUpdate(.documentLoadFailed) - return - } - DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in - guard let self else { return } - self.keyboardPreparationPending = false - guard let window, self.window === window, window.isKeyWindow, - window.windowScene?.activationState == .foregroundActive else { - self.loadWhenIsolated() - return - } - guard self.isolationReady, let url = self.pendingDocumentUrl else { return } - self.pendingDocumentUrl = nil - self.loadState.shellLoadStarted() - self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)) - } - } - } - - private func emit(_ emission: MobileWebShellLoadEmission?) { - guard let emission else { return } - onLoadState(emission.payload) - } - - private func reportDocumentFailure() { - clearBridgeTarget() - emit(loadState.failed(.documentLoadFailed)) - } - - /// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError. - private func reportNavigationFailure(_ error: Error) { - let error = error as NSError - guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else { - return - } - reportDocumentFailure() - } - - private func isDocumentUrl(_ url: URL?) -> Bool { - guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false } - return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId) == "/" - } - - func webView( - _ webView: WKWebView, - decidePolicyFor navigationAction: WKNavigationAction, - decisionHandler: @escaping (WKNavigationActionPolicy) -> Void - ) { - var isDownload = false - if #available(iOS 14.5, *) { - isDownload = navigationAction.shouldPerformDownload - } - let isMainFrame = navigationAction.targetFrame?.isMainFrame == true - // linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load. - let verdict = MobileWebShellNavigationPolicy.verdict( - url: navigationAction.request.url?.absoluteString, - isMainFrame: isMainFrame, - isDocumentUrl: isDocumentUrl(navigationAction.request.url), - isShellLoad: loadState.isShellLoad, - hasGesture: navigationAction.navigationType == .linkActivated, - isDownload: isDownload - ) - if case let .cancelAndOffer(url) = verdict { - onExternalNavigation(["url": url]) - } - if verdict == .allow && isMainFrame { - // Spend before handing back the decision so another main-frame action cannot reuse the allowance. - loadState.shellLoadConsumed() - } - decisionHandler(verdict == .allow ? .allow : .cancel) - } - - func webView( - _ webView: WKWebView, - decidePolicyFor navigationResponse: WKNavigationResponse, - decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void - ) { - // Only srcdoc subframes pass the action policy; refusing one must not fail the shell document. - guard navigationResponse.isForMainFrame else { - let url = navigationResponse.response.url?.absoluteString - decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel) - return - } - let allowed = navigationResponse.canShowMIMEType && - isDocumentUrl(navigationResponse.response.url) - if !allowed { - reportDocumentFailure() - } - decisionHandler(allowed ? .allow : .cancel) - } - - func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { - // Clear replies and acceptance when the document is replaced; its successor must commit and send ready. - clearBridgeTarget() - loadState.documentEnded() - guard appliedSessionId != nil else { return } - emit(loadState.started()) - } - - /// Arm at commit, before document-start messages and didFinish. - func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { - guard isDocumentUrl(webView.url) else { return } - // Commit rearms acceptance, so clear the replaced frame here as well as at provisional start. - clearBridgeTarget() - loadState.committed() - } - - /// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality. - func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { - MobileWebShellWarmUp.release() - emit(loadState.finished()) - } - - func webView( - _ webView: WKWebView, - didFailProvisionalNavigation navigation: WKNavigation!, - withError error: Error - ) { - MobileWebShellWarmUp.release() - reportNavigationFailure(error) - } - - func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { - MobileWebShellWarmUp.release() - reportNavigationFailure(error) - } - - /// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy. - func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { - MobileWebShellWarmUp.release() - clearBridgeTarget() - // Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active. - let background = window == nil || UIApplication.shared.applicationState != .active - emit(loadState.failed(.renderProcessGone, background: background)) - } - - func webView( - _ webView: WKWebView, - createWebViewWith configuration: WKWebViewConfiguration, - for navigationAction: WKNavigationAction, - windowFeatures: WKWindowFeatures - ) -> WKWebView? { - nil + func documentExternalNavigation(_ url: String) { + onExternalNavigation(["url": url]) } } diff --git a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift index 0f3bcaa5ca7..ed5e81770d1 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift @@ -1,12 +1,53 @@ import ExpoModulesCore import QuickLook +import UIKit public class OrcaMobileWebShellModule: Module { private var pdfPreview: MobileWebShellPdfPreview? + private var memoryWarningObserver: NSObjectProtocol? public func definition() -> ModuleDefinition { Name("OrcaMobileWebShell") + // A spare is the first thing to give back: nothing is shown by it. + OnCreate { + memoryWarningObserver = NotificationCenter.default.addObserver( + forName: UIApplication.didReceiveMemoryWarningNotification, + object: nil, + queue: .main + ) { _ in + MobileWebShellSparePool.shared.discardAll() + } + } + + OnDestroy { + if let memoryWarningObserver { + NotificationCenter.default.removeObserver(memoryWarningObserver) + } + DispatchQueue.main.async { + MobileWebShellSparePool.shared.discardAll() + } + } + + // Home boots the next one after its next foreground idle. + OnAppEntersBackground { + DispatchQueue.main.async { + MobileWebShellSparePool.shared.discardAll() + } + } + + AsyncFunction("prepareSpareDocument") { (directory: String, sessionId: String) -> Bool in + MobileWebShellSparePool.shared.prepare(directory: directory, sessionId: sessionId) + }.runOnQueue(.main) + + AsyncFunction("claimSpareDocument") { (directory: String) -> String? in + MobileWebShellSparePool.shared.claim(directory: directory) + }.runOnQueue(.main) + + AsyncFunction("discardSpareDocument") { + MobileWebShellSparePool.shared.discardAll() + }.runOnQueue(.main) + // Home calls this once it has a paired host, so a user with nothing to open pays nothing. Function("warmUp") { // A second's delay keeps the warm-up off the launch's first frames. diff --git a/mobile/modules/orca-mobile-web-shell/src/spare-document.ts b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts new file mode 100644 index 00000000000..ca9ba5c1f85 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts @@ -0,0 +1,27 @@ +import { requireOptionalNativeModule } from 'expo-modules-core' + +type SpareDocumentModule = { + prepareSpareDocument?: (directory: string, sessionId: string) => Promise + claimSpareDocument?: (directory: string) => Promise + discardSpareDocument?: () => Promise +} + +// A binary built before the spare existed has the module without these functions. +const spareModule = (): SpareDocumentModule | null => + requireOptionalNativeModule('OrcaMobileWebShell') + +// Boot a page from `directory` under `sessionId` and park it, invisible, until a screen claims it. +// False when native declined: a phone under 4 GB, the app not active, or a page document shown. +export async function prepareSpareDocument(directory: string, sessionId: string): Promise { + return (await spareModule()?.prepareSpareDocument?.(directory, sessionId)) ?? false +} + +// The parked spare's session id when it was booted from `directory`, handed out once. The view +// mounted under that id adopts the booted page. +export async function claimSpareDocument(directory: string): Promise { + return (await spareModule()?.claimSpareDocument?.(directory)) ?? null +} + +export async function discardSpareDocument(): Promise { + await spareModule()?.discardSpareDocument?.() +} diff --git a/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json b/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json index 3b737599abd..1ccd86c7a3e 100644 --- a/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json +++ b/mobile/rpc-foundation/goldens/settings-repo-metadata-refuse-after-data.json @@ -35,17 +35,6 @@ "ordinal": 9, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"ssh.listTargetSummaries\"}" }, - "18c2b8e092d7": { - "name": "streams-registered-at-teardown", - "ordinal": 26, - "value": [ - { - "cancelled": true, - "method": "runtime.clientEvents.subscribe", - "payload": "runtime.clientEvents.subscribe#1" - } - ] - }, "20200b8feac4": { "name": "host.platform#1", "ordinal": 6, @@ -106,6 +95,17 @@ "startedAt": 0 } }, + "44eb39507b75": { + "name": "streams-registered-at-teardown", + "ordinal": 23, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, "564f54c8d902": { "name": "host.platform#1", "ordinal": 6, @@ -137,11 +137,6 @@ "ordinal": 13, "value": [["ssh:ssh-1", "SSH"]] }, - "59ab92fbdbc0": { - "name": "hostPlatform", - "ordinal": 25, - "value": "linux" - }, "6770aa1912e4": { "name": "repo.list#2", "ordinal": 15, @@ -411,11 +406,6 @@ "status": "pending", "startedAt": 0 }, - "9c290301a4bc": { - "name": "hostHealthById", - "ordinal": 23, - "value": [] - }, "b2746491ac07": { "name": "repo.list#1", "ordinal": 2, @@ -642,11 +632,6 @@ "name": "hostPlatform", "ordinal": 14, "value": "linux" - }, - "fb797b9761e1": { - "name": "hostLabelById", - "ordinal": 24, - "value": [["ssh:ssh-1", "SSH"]] } }, "recording": { @@ -795,10 +780,7 @@ "8cfdd18c5fe6", "84c1dde54c62", "56ab81cb67dc", - "f9193cae5824", - "9c290301a4bc", - "fb797b9761e1", - "59ab92fbdbc0" + "f9193cae5824" ] } }, @@ -838,10 +820,7 @@ "84c1dde54c62", "56ab81cb67dc", "f9193cae5824", - "9c290301a4bc", - "fb797b9761e1", - "59ab92fbdbc0", - "18c2b8e092d7" + "44eb39507b75" ] } } diff --git a/mobile/src/app-update/app-update-checker.test.ts b/mobile/src/app-update/app-update-checker.test.ts index 1652654f393..6cfa6ab6e16 100644 --- a/mobile/src/app-update/app-update-checker.test.ts +++ b/mobile/src/app-update/app-update-checker.test.ts @@ -84,15 +84,6 @@ describe('app update checker', () => { expect(h.checker.getSnapshot().checking).toBe(false) }) - it('joins a manual check to one already in flight', async () => { - const h = harness({ stored: { lastCheckedAt: T0 }, replies: [{ kind: 'current' }] }) - h.checker.start() - await vi.advanceTimersByTimeAsync(0) - const [first, second] = [h.checker.checkNow(), h.checker.checkNow()] - await expect(Promise.all([first, second])).resolves.toEqual(['up-to-date', 'up-to-date']) - expect(checks(h)).toBe(1) - }) - it('keeps the 1 h retry for a manual check that fails while the store is still loading', async () => { let finishLoad: () => void = () => {} const h = harness({ @@ -112,15 +103,6 @@ describe('app update checker', () => { expect(checks(h)).toBe(2) }) - it('applies one load and runs one check across a StrictMode-style double start', async () => { - const h = harness({}) - h.checker.start()() - h.checker.start() - await vi.advanceTimersByTimeAsync(0) - expect(h.deps.loadPreferences).toHaveBeenCalledTimes(1) - expect(checks(h)).toBe(1) - }) - function deferredReply() { let answer: (result: AppUpdateCheckResult) => void = () => {} const reply = new Promise((resolve) => { diff --git a/mobile/src/browser/browser-screencast-request.web.test.ts b/mobile/src/browser/browser-screencast-request.web.test.ts deleted file mode 100644 index cbf56338cea..00000000000 --- a/mobile/src/browser/browser-screencast-request.web.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { BRIDGE_MAX_MESSAGE_BYTES } from '../mobile-web-shell/bridge/bridge-caps' -import { buildMobileBrowserScreencastRequest } from './browser-screencast-request' -import { - base64Characters, - binaryEventEnvelopeBytes, - budgetedMobileViewDeviceScaleFactor, - buildMobileBrowserScreencastRequest as buildOnWeb, - WORST_CASE_JPEG_BYTES_PER_PIXEL -} from './browser-screencast-request.web' - -/** A phone's measured browser area, in CSS pixels. */ -const PHONE = { width: 390, height: 712 } - -/** What the shell would have to post for a frame of this area at the worst case JPEG has. */ -function frameMessageBytes(areaPixels: number): number { - const imageBytes = Math.ceil(areaPixels * WORST_CASE_JPEG_BYTES_PER_PIXEL) - return base64Characters(imageBytes) + binaryEventEnvelopeBytes() -} - -function mobileFrameArea( - layout: { width: number; height: number }, - request: { deviceScaleFactor?: number } | null -): number { - const scale = request?.deviceScaleFactor - if (scale === undefined) { - throw new Error('the request carried no device scale factor') - } - return Math.round(layout.width) * Math.round(layout.height) * scale * scale -} - -describe('the mobile-view area budget', () => { - // Native density at same phone size exceeds bridge cap; without web budget shell drops frame. - it('is needed: the native request overflows the frame cap on a phone', () => { - const native = buildMobileBrowserScreencastRequest(PHONE, 2, 'mobile') - - expect(native?.deviceScaleFactor).toBe(2) - expect(frameMessageBytes(mobileFrameArea(PHONE, native))).toBeGreaterThan( - BRIDGE_MAX_MESSAGE_BYTES - ) - }) - - it('keeps the worst case frame inside one bridge message', () => { - const budgeted = buildOnWeb(PHONE, 2, 'mobile') - - expect(frameMessageBytes(mobileFrameArea(PHONE, budgeted))).toBeLessThanOrEqual( - BRIDGE_MAX_MESSAGE_BYTES - ) - }) - - it('uses the largest hundredth of density whose frame fits the cap', () => { - const scale = budgetedMobileViewDeviceScaleFactor(PHONE) - expect( - frameMessageBytes(mobileFrameArea(PHONE, { deviceScaleFactor: scale + 0.01 })) - ).toBeGreaterThan(BRIDGE_MAX_MESSAGE_BYTES) - }) - - it('leaves web mode byte-identical to the native request', () => { - expect(buildOnWeb(PHONE, 2, 'web')).toEqual( - buildMobileBrowserScreencastRequest(PHONE, 2, 'web') - ) - expect(buildOnWeb(PHONE, 2)).toEqual(buildMobileBrowserScreencastRequest(PHONE, 2)) - }) - - it('never asks for more density than native, on a viewport the budget does not bind', () => { - expect(budgetedMobileViewDeviceScaleFactor({ width: 200, height: 200 })).toBe(2) - }) - - it('stops at one device pixel per CSS pixel on a viewport no scale would fit', () => { - // Never request fewer device pixels than CSS pixels; shell drops frames still too large at density 1. - expect(budgetedMobileViewDeviceScaleFactor({ width: 2000, height: 1400 })).toBe(1) - }) - - it('answers the native factor when there is no layout to budget against', () => { - expect(budgetedMobileViewDeviceScaleFactor(null)).toBe(2) - expect(buildOnWeb(null, 2, 'mobile')).toBeNull() - expect(buildOnWeb({ width: 0, height: 712 }, 2, 'mobile')).toBeNull() - }) -}) - -it('counts base64 padding for an image that does not fill its last group', () => { - expect(base64Characters(3001)).toBe(4004) -}) - -describe('web-mode request work', () => { - for (const mode of [undefined, 'web'] as const) { - it(`skips discarded mobile density work in ${mode ?? 'default'} view`, () => { - const layouts = [ - { width: 360, height: 640 }, - { width: 390, height: 712 }, - { width: 402, height: 593 }, - { width: 319.49, height: 239.51 }, - { width: 1200, height: 1200 }, - { width: 2000, height: 1400 } - ] - const expected = layouts.map((layout) => buildMobileBrowserScreencastRequest(layout, 2, mode)) - const stringify = vi.spyOn(JSON, 'stringify') - const sqrt = vi.spyOn(Math, 'sqrt') - let actual: ReturnType[] = [] - let envelopeCalls = 0 - let sqrtCalls = 0 - try { - actual = layouts.map((layout) => buildOnWeb(layout, 2, mode)) - envelopeCalls = stringify.mock.calls.length - sqrtCalls = sqrt.mock.calls.length - } finally { - stringify.mockRestore() - sqrt.mockRestore() - } - - expect(actual).toEqual(expected) - expect(envelopeCalls).toBe(0) - expect(sqrtCalls).toBe(0) - }) - } -}) diff --git a/mobile/src/browser/browser-url.test.ts b/mobile/src/browser/browser-url.test.ts deleted file mode 100644 index a0d2a7f11f4..00000000000 --- a/mobile/src/browser/browser-url.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { normalizeBrowserUrl } from './browser-url' - -describe('normalizeBrowserUrl', () => { - it('keeps localhost-style addresses as http URLs', () => { - expect(normalizeBrowserUrl('localhost:3000')).toBe('http://localhost:3000/') - expect(normalizeBrowserUrl('127.0.0.1:6769/web-index.html')).toBe( - 'http://127.0.0.1:6769/web-index.html' - ) - }) -}) diff --git a/mobile/src/browser/mobile-browser-view-mode-state.test.ts b/mobile/src/browser/mobile-browser-view-mode-state.test.ts deleted file mode 100644 index 495955a3cc2..00000000000 --- a/mobile/src/browser/mobile-browser-view-mode-state.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - clearMobileBrowserViewModeState, - getInitialMobileBrowserViewMode, - saveMobileBrowserViewMode -} from './mobile-browser-view-mode-state' - -describe('mobile browser view mode state', () => { - beforeEach(() => { - clearMobileBrowserViewModeState() - }) - - it('defaults each browser page to web view', () => { - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-1', null)).toBe('web') - }) - - it('defaults local HTML reports to mobile view', () => { - expect( - getInitialMobileBrowserViewMode( - 'folder:workspace-1', - 'page-1', - 'file:///Users/me/report%20one.HTML?generated=1' - ) - ).toBe('mobile') - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///C:/Users/me/report.htm') - ).toBe('mobile') - }) - - it('keeps remote HTML URLs and non-HTML files in web view', () => { - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'https://example.com/report.html') - ).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///repo/notes.txt')).toBe( - 'web' - ) - }) - - it('restores the last mode for the same browser page after remount', () => { - saveMobileBrowserViewMode('worktree-1', 'page-1', 'mobile') - - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('mobile') - expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2')).toBe('web') - expect(getInitialMobileBrowserViewMode('worktree-2', 'page-1')).toBe('web') - }) - - it('preserves an explicit web choice for a local HTML report', () => { - saveMobileBrowserViewMode('worktree-1', 'page-1', 'web') - - expect( - getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'file:///repo/report.html') - ).toBe('web') - }) -}) diff --git a/mobile/src/components/DragReorderList.test.tsx b/mobile/src/components/DragReorderList.test.tsx index bd3cb5aeb07..defe697b10a 100644 --- a/mobile/src/components/DragReorderList.test.tsx +++ b/mobile/src/components/DragReorderList.test.tsx @@ -25,17 +25,6 @@ describe('drag completion and cancellation', () => { await act(async () => fixture.root.unmount()) }) - it('commits the moved order once on a successful drop', async () => { - const fixture = await mounted() - await act(async () => { - fixture.gesture.start!({ absoluteY: 100, translationY: 0 }, true) - fixture.gesture.update!({ absoluteY: 180, translationY: 80 }, true) - fixture.gesture.finalize!({ absoluteY: 180, translationY: 80 }, true) - }) - expect(fixture.onReorder.mock.calls).toEqual([[['b', 'a']]]) - await act(async () => fixture.root.unmount()) - }) - it('does not write after a failed activation or an unchanged drop', async () => { const fixture = await mounted() await act(async () => { @@ -286,56 +275,3 @@ it('keeps measured rows still on hold, restores cancellation, and drops by moved expect(move).toHaveBeenCalledExactlyOnceWith({ movedId: 'a', afterId: 'c' }) await act(async () => root!.unmount()) }) - -it.each([100, 1000])( - 'bounds accessibility work for %i rows while excluded slots stay fixed', - async (count) => { - const ids = Array.from({ length: count }, (_, at) => - at === 1 ? 'fixed' : at === 2 ? 'busy' : `row-${at}` - ) - let keyReads = 0 - let membership = 0 - const onMove = vi.fn() - const onReorder = vi.fn() - function Harness({ items = ids }: { items?: string[] }) { - return createElement(DragReorderList, { - items, - itemKey: (id) => { - keyReads++ - return id - }, - canMove: (id) => { - membership++ - return id !== 'fixed' && id !== 'busy' - }, - rowHeight: 56, - renderRow: (id, handle) => createElement('Text', null, id, handle), - onMove, - onReorder, - scrollRef: useAnimatedRef(), - scrollOffsetY: useSharedValue(0), - scrollContentHeight: useSharedValue(count * 56) - }) - } - let root: ReturnType - await act(async () => { - root = create(createElement(Harness)) - }) - const first = root!.root.findAll( - (node) => node.type === Animated.View && node.props.onAccessibilityAction - )[0]! - const accessibilityAction = first.props.onAccessibilityAction - keyReads = membership = 0 - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveUp' } })) - expect(onMove).not.toHaveBeenCalled() - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } })) - expect(keyReads).toBeLessThanOrEqual(3 * count) - expect(membership).toBeLessThanOrEqual(3 * count) - expect(onReorder.mock.calls[0]![0].slice(0, 4)).toEqual(['row-3', 'fixed', 'busy', 'row-0']) - expect(onMove).toHaveBeenCalledExactlyOnceWith({ movedId: 'row-0', beforeId: 'row-4' }) - await act(async () => root!.update(createElement(Harness, { items: ids.slice(1) }))) - await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } })) - expect(onMove).toHaveBeenCalledOnce() - await act(async () => root!.unmount()) - } -) diff --git a/mobile/src/components/HostRouteNoticeBanner.test.tsx b/mobile/src/components/HostRouteNoticeBanner.test.tsx deleted file mode 100644 index 7726ba372a9..00000000000 --- a/mobile/src/components/HostRouteNoticeBanner.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', async () => { - const React = await import('react') - return { - Pressable: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Pressable', props, children), - Text: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Text', props, children), - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles } - } -}) -vi.mock('lucide-react-native', () => ({ X: 'X' })) - -import { HostRouteNoticeBanner } from './HostRouteNoticeBanner' - -// Announce inserted banner because list reader may be below it; failure interrupts, bounced-route context stays polite so urgency retains meaning. -describe('the host route notice banner announces itself', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - function banner(tone?: 'notice' | 'failure') { - act(() => { - renderer = create( - createElement(HostRouteNoticeBanner, { - message: 'Nothing happened', - tone, - onDismiss: () => {} - }) - ) - }) - if (renderer === null) { - throw new Error('the banner did not render') - } - // Match host name to avoid ElementType cast for arbitrary RN strings; first match is banner root carrying tested props. - return renderer.root.findAll((node) => String(node.type) === 'View')[0] - } - - it('interrupts for a failure, which is an action that did not happen', () => { - const root = banner('failure') - expect(root.props.accessibilityRole).toBe('alert') - expect(root.props.accessibilityLiveRegion).toBe('assertive') - }) - - it('waits its turn for a notice, which is context rather than a refusal', () => { - const root = banner('notice') - expect(root.props.accessibilityLiveRegion).toBe('polite') - // No alert role: nothing here failed, and an alert is what the tone above is for. - expect(root.props.accessibilityRole).toBeUndefined() - }) - - it('treats the default tone as the notice one, which is what the route caller passes', () => { - const root = banner(undefined) - expect(root.props.accessibilityLiveRegion).toBe('polite') - expect(root.props.accessibilityRole).toBeUndefined() - }) -}) diff --git a/mobile/src/components/MobileMarkdown.test.ts b/mobile/src/components/MobileMarkdown.test.ts index 455c05f153d..1eade1f67f5 100644 --- a/mobile/src/components/MobileMarkdown.test.ts +++ b/mobile/src/components/MobileMarkdown.test.ts @@ -1,22 +1,6 @@ import { describe, expect, it } from 'vitest' -import { isMobileMermaidLanguage } from './mobile-mermaid-language' import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html' -describe('isMobileMermaidLanguage', () => { - it('matches mermaid case-insensitively after trim', () => { - expect(isMobileMermaidLanguage('mermaid')).toBe(true) - expect(isMobileMermaidLanguage('Mermaid')).toBe(true) - expect(isMobileMermaidLanguage(' MERMAID ')).toBe(true) - }) - - it('rejects non-mermaid languages and missing language', () => { - expect(isMobileMermaidLanguage(undefined)).toBe(false) - expect(isMobileMermaidLanguage('')).toBe(false) - expect(isMobileMermaidLanguage('ts')).toBe(false) - expect(isMobileMermaidLanguage('mermaidx')).toBe(false) - }) -}) - describe('normalizeMobileMarkdownPreviewHtml', () => { it('normalizes common README HTML into readable Markdown preview text', () => { const normalized = normalizeMobileMarkdownPreviewHtml(` diff --git a/mobile/src/components/MobileRepoIcon.test.tsx b/mobile/src/components/MobileRepoIcon.test.tsx deleted file mode 100644 index 09355287677..00000000000 --- a/mobile/src/components/MobileRepoIcon.test.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { Folder } from 'lucide-react-native' -import { createElement } from 'react' -import { Image } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MobileRepoIcon } from './MobileRepoIcon' - -vi.mock('react-native', () => ({ - Image: 'Image', - StyleSheet: { create: (styles: T) => styles }, - Text: 'Text', - View: 'View' -})) -// Each icon renders as an element named after it. -vi.mock( - 'lucide-react-native', - () => new Proxy({}, { has: () => true, get: (_, name) => String(name) }) -) -vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' })) - -let renderer: ReactTestRenderer | null = null -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -function imageIcon(src: string) { - return createElement(MobileRepoIcon, { repoIcon: { type: 'image', src, label: 'owner/repo' } }) -} - -describe('MobileRepoIcon', () => { - it('shows the folder after an image fails, and tries a changed image again', () => { - act(() => { - renderer = create(imageIcon('https://github.com/owner.png?size=64')) - }) - act(() => renderer!.root.findByType(Image).props.onError()) - expect(renderer!.root.findAllByType(Image)).toHaveLength(0) - expect(renderer!.root.findAllByType(Folder)).toHaveLength(1) - - act(() => renderer!.update(imageIcon('data:image/png;base64,AAAA'))) - expect(renderer!.root.findByType(Image).props.source).toEqual({ - uri: 'data:image/png;base64,AAAA' - }) - }) -}) diff --git a/mobile/src/components/MobileRichMarkdownToolbar.test.tsx b/mobile/src/components/MobileRichMarkdownToolbar.test.tsx deleted file mode 100644 index 6cdbcbd498a..00000000000 --- a/mobile/src/components/MobileRichMarkdownToolbar.test.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', () => ({ - Pressable: 'Pressable', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - View: 'View' -})) - -vi.mock('lucide-react-native', () => ({ - Bold: 'Bold', - Code2: 'Code2', - FileCode2: 'FileCode2', - Heading1: 'Heading1', - Heading2: 'Heading2', - Heading3: 'Heading3', - ImageIcon: 'ImageIcon', - Italic: 'Italic', - Link: 'Link', - List: 'List', - ListOrdered: 'ListOrdered', - ListTodo: 'ListTodo', - Pilcrow: 'Pilcrow', - Quote: 'Quote', - Strikethrough: 'Strikethrough' -})) - -import { MobileRichMarkdownToolbar } from './MobileRichMarkdownToolbar' -import type { MobileRichMarkdownCommand } from './mobile-rich-markdown-editor-contract' - -let renderer: ReactTestRenderer | null = null - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -function render(editable: boolean, onCommand: (command: MobileRichMarkdownCommand) => void) { - act(() => { - renderer = create(createElement(MobileRichMarkdownToolbar, { editable, onCommand })) - }) - return renderer!.root.findAll((node) => String(node.type) === 'Pressable') -} - -describe('the rich Markdown toolbar', () => { - it('routes named controls to their editor commands', () => { - const onCommand = vi.fn() - const buttons = render(true, onCommand) - for (const [label, command] of [ - ['Bold', 'bold'], - ['Link', 'link'], - ['Inline code', 'inlineCode'] - ] as const) { - onCommand.mockClear() - const button = buttons.find((candidate) => candidate.props.accessibilityLabel === label) - expect(button).toBeDefined() - act(() => button!.props.onPress()) - expect(onCommand.mock.calls).toEqual([[command]]) - } - }) - - it('disables every button against a document that cannot be edited', () => { - const buttons = render(false, vi.fn()) - expect(buttons.filter((button) => button.props.disabled !== true)).toEqual([]) - }) -}) diff --git a/mobile/src/components/ProtocolBlockScreen.test.ts b/mobile/src/components/ProtocolBlockScreen.test.ts index f8560e28cbe..3b79cc9543e 100644 --- a/mobile/src/components/ProtocolBlockScreen.test.ts +++ b/mobile/src/components/ProtocolBlockScreen.test.ts @@ -72,34 +72,6 @@ describe('ProtocolBlockScreen', () => { renderer = null }) - // Why: the protocol wall shipped before the bundle one; its copy is what users already see. - it('keeps the existing protocol wall rendering unchanged', () => { - const mobile = render({ - kind: 'blocked', - reason: 'mobile-too-old', - desktopVersion: 5, - requiredMobileVersion: 99 - }) - expect(mobile).toContain('Update Orca Mobile') - expect(mobile).toContain( - 'This desktop needs a newer Orca Mobile app. Update Orca Mobile from the App Store, then try this host again.' - ) - expect(mobile).toContain('Open App Store') - act(() => renderer?.unmount()) - - const desktop = render({ - kind: 'blocked', - reason: 'desktop-too-old', - desktopVersion: 0, - requiredDesktopVersion: 2 - }) - expect(desktop).toContain('Update Orca on your computer') - expect(desktop).toContain( - 'This paired desktop app is too old for your current Orca Mobile app. Update Orca on your computer, then try this host again.' - ) - expect(desktop).toContain('Open GitHub Releases') - }) - it('tells a host without a bundle, or without this screen, the desktop is too old', () => { for (const reason of ['bundle-unavailable', 'page-route-unlisted'] as const) { const output = render({ kind: 'blocked', reason }) @@ -112,12 +84,6 @@ describe('ProtocolBlockScreen', () => { } }) - it('sends a screen that needs a grant this app lacks to the mobile update', () => { - const output = render({ kind: 'blocked', reason: 'page-route-grant-missing' }) - expect(output).toContain('Update Orca Mobile') - expect(output).toContain("This desktop's mobile workspace needs a newer Orca Mobile app.") - }) - it('sends an unknown manifest schema to the mobile update', () => { const output = render({ kind: 'blocked', @@ -169,44 +135,13 @@ describe('ProtocolBlockScreen', () => { expect(primaryActionUrl()).toBe(RELEASES_URL) }) - it('sends a desktop whose page is older than this shell to the desktop update', () => { - const output = render({ - kind: 'blocked', - reason: 'bundle-incompatible', - side: 'desktop', - pageVersion: 0, - requiredPageVersion: 1 - }) - expect(output).toContain('Update Orca on your computer') - expect(output).toContain('This paired desktop app is too old for your current Orca Mobile app') - expect(primaryActionUrl()).toBe(RELEASES_URL) - }) - - it('routes an Android bundle wall to GitHub Releases, not a store that has no listing', () => { - nativeTestState.platform.OS = 'android' - const output = render({ - kind: 'blocked', - reason: 'bundle-shell-too-old', - schemaVersion: 2 - }) - expect(output).toContain('Update Orca Mobile from GitHub Releases') - expect(primaryActionUrl()).toBe(RELEASES_URL) - }) - - it('keeps the update walls on two buttons and the full recovery note', () => { - const output = render({ kind: 'blocked', reason: 'bundle-unavailable' }) - expect(output).toContain('Already updated? Go back to Hosts and refresh the connection.') - // The presence precondition for the absence asserted on the refresh wall above. - expect(pressableCount()).toBe(2) - }) - describe('with the newest release known', () => { const release = { version: '0.0.52', url: 'https://github.com/stablyai/orca/releases/tag/mobile-v0.0.52' } - it.each(['ios', 'android'] as const)('opens that exact release on %s', (os) => { + it.each(['android'] as const)('opens that exact release on %s', (os) => { nativeTestState.platform.OS = os const output = render( { kind: 'blocked', reason: 'bundle-shell-too-old', schemaVersion: 2 }, diff --git a/mobile/src/files/MobileFilePreviewEditDraft.tsx b/mobile/src/files/MobileFilePreviewEditDraft.tsx index 13ede3827b2..bea1c2ab81b 100644 --- a/mobile/src/files/MobileFilePreviewEditDraft.tsx +++ b/mobile/src/files/MobileFilePreviewEditDraft.tsx @@ -6,9 +6,11 @@ import { } from '../drafts/use-document-edit-draft' import { useClipboardWriter } from '../platform/clipboard' import { triggerError, triggerSuccess } from '../platform/haptics' +import { useKeyboardOcclusion } from '../platform/keyboard-occlusion' import { spacing } from '../theme/mobile-theme' import { useSafeAreaInsets } from 'react-native-safe-area-context' import type { MobileFilePreviewSource } from './mobile-file-preview-request' +import { resolveMarkdownFloatingActionsBottom } from './session-documents/markdown-floating-actions-layout' /** Only terminal artifacts are editable in the file preview. */ export function filePreviewEditDraftKey( @@ -43,10 +45,15 @@ function OfferBar(props: { }) { const clipboard = useClipboardWriter() const insets = useSafeAreaInsets() + const keyboardHeight = useKeyboardOcclusion() return ( void clipboard.writeText(props.offer.content).then(triggerSuccess, triggerError) } diff --git a/mobile/src/files/session-documents/MobileMarkdownReader.tsx b/mobile/src/files/session-documents/MobileMarkdownReader.tsx deleted file mode 100644 index 5dcecdbb970..00000000000 --- a/mobile/src/files/session-documents/MobileMarkdownReader.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import { useRef, useState } from 'react' -import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { ChevronDown, Keyboard as KeyboardIcon, RefreshCw } from 'lucide-react-native' -import { - MobileRichMarkdownEditor, - type MobileRichMarkdownEditorHandle -} from '../../components/MobileRichMarkdownEditor' -import { colors, spacing, pressedStyle } from '../../theme/mobile-theme' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { - resolveMarkdownFloatingActionsBottom, - shouldShowMarkdownFloatingActions -} from './markdown-floating-actions-layout' -import type { MarkdownDocState } from './session-document-state' -import { styles } from '../../session/mobile-session-styles' -import { MobileLoadErrorState, MobileStateView } from '../../components/MobileStateView' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' - -type Props = { - documentId: string - doc: MarkdownDocState | undefined - onRefresh: () => void - onChange: (content: string) => void - onSave: () => void - onCopy: () => void - onDiscard: () => void - keyboardLift: number -} - -export function MobileMarkdownReader({ - documentId, - doc, - onRefresh, - onChange, - onSave, - onCopy, - onDiscard, - keyboardLift -}: Props) { - useMobileColorScheme() - const t = useMobileTranslation() - const editorRef = useRef(null) - // Native Keyboard events under-report the WebView editor's covered area, so prefer the larger WebView-measured inset. - const [webviewKeyboardInset, setWebviewKeyboardInset] = useState(0) - const effectiveKeyboardLift = Math.max(keyboardLift, webviewKeyboardInset) - const keyboardOpen = effectiveKeyboardLift > 0 - - if (!doc || doc.status === 'loading') { - return ( - - ) - } - if (doc.status === 'error') { - return - } - - const statusText = doc.saveError - ? doc.saveError - : doc.readOnlyReason - ? t('session.markdownReader.readOnly', 'Read only') - : doc.stale - ? t('session.markdownReader.changedOnDesktop', 'Changed on desktop') - : null - const showRefresh = Boolean((doc.stale && !doc.isDirty) || !doc.editable) - const showCopy = Boolean(doc.saveError || !doc.editable) - const showSave = Boolean(doc.isDirty || doc.saving) - const showFloatingActions = shouldShowMarkdownFloatingActions({ - keyboardLift: effectiveKeyboardLift, - hasStatus: statusText != null, - showRefresh, - showCopy, - showSave - }) - - return ( - - - {showFloatingActions ? ( - - {statusText ? ( - - {statusText} - - ) : null} - - {keyboardOpen ? ( - [ - styles.markdownFloatingButton, - styles.markdownKeyboardDismissButton, - pressed && pressedStyle - ]} - onPress={() => editorRef.current?.dismissKeyboard()} - hitSlop={8} - accessibilityRole="button" - accessibilityLabel={t('session.markdownReader.dismissKeyboard', 'Dismiss keyboard')} - accessibilityHint={t( - 'session.markdownReader.dismissKeyboardHint', - 'Hides the software keyboard and keeps the markdown editor open.' - )} - > - - - - - - ) : null} - {showCopy ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onCopy} - > - {t('common.copy', 'Copy')} - - ) : null} - {showRefresh ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onRefresh} - > - - - {t('common.refresh', 'Refresh')} - - - ) : null} - {doc.isDirty ? ( - [styles.markdownFloatingButton, pressed && pressedStyle]} - onPress={onDiscard} - > - - {t('session.markdownReader.discard', 'Discard')} - - - ) : null} - {showSave ? ( - [ - styles.markdownFloatingButton, - styles.markdownSaveButton, - (!doc.editable || !doc.isDirty || doc.saving) && styles.markdownButtonDisabled, - pressed && pressedStyle - ]} - disabled={!doc.editable || !doc.isDirty || doc.saving} - onPress={onSave} - > - {doc.saving ? ( - - ) : ( - {t('common.save', 'Save')} - )} - - ) : null} - - - ) : null} - - ) -} diff --git a/mobile/src/files/session-documents/markdown-floating-actions-layout.ts b/mobile/src/files/session-documents/markdown-floating-actions-layout.ts index bc506a88a9d..06aa5b9223f 100644 --- a/mobile/src/files/session-documents/markdown-floating-actions-layout.ts +++ b/mobile/src/files/session-documents/markdown-floating-actions-layout.ts @@ -9,19 +9,3 @@ export function resolveMarkdownFloatingActionsBottom({ }): number { return keyboardLift > 0 ? keyboardLift + liftedClearance : restingBottom } - -export function shouldShowMarkdownFloatingActions({ - keyboardLift, - hasStatus, - showRefresh, - showCopy, - showSave -}: { - keyboardLift: number - hasStatus: boolean - showRefresh: boolean - showCopy: boolean - showSave: boolean -}): boolean { - return keyboardLift > 0 || hasStatus || showRefresh || showCopy || showSave -} diff --git a/mobile/src/files/session-documents/mobile-markdown-reader-status.ts b/mobile/src/files/session-documents/mobile-markdown-reader-status.ts index 9e79d7adce9..e238cda5922 100644 --- a/mobile/src/files/session-documents/mobile-markdown-reader-status.ts +++ b/mobile/src/files/session-documents/mobile-markdown-reader-status.ts @@ -1,3 +1,4 @@ +import { translate } from '../../i18n/mobile-i18n' import { formatPreviewByteLength } from '../mobile-file-preview-response' import type { MarkdownDocState } from './session-document-state' @@ -9,11 +10,17 @@ export function markdownReaderStatusText( } if (doc.truncated) { return doc.byteLength === undefined - ? 'Preview truncated.' - : `Preview truncated. File size: ${formatPreviewByteLength(doc.byteLength)}.` + ? translate('session.markdownReader.previewTruncated', 'Preview truncated.') + : translate( + 'files.filePreviewSourceText.truncatedNote', + 'Preview truncated. File size: {{size}}.', + { size: formatPreviewByteLength(doc.byteLength) } + ) } if (doc.readOnlyReason) { - return 'Read only' + return translate('session.markdownReader.readOnly', 'Read only') } - return doc.stale ? 'Changed on desktop' : null + return doc.stale + ? translate('session.markdownReader.changedOnDesktop', 'Changed on desktop') + : null } diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index fadfbfcd5aa..11c0274f3a1 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -29,6 +29,7 @@ import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit' import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label' import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route' import { useMobileHomeData } from './use-mobile-home-data' +import { useHomeSparePage } from './use-home-spare-page' import { HOME_TABS, type HomeTabId } from './tabs/home-tabs' import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab' import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab' @@ -45,6 +46,7 @@ export function MobileHomeScreen() { const t = useMobileTranslation() useMobileColorScheme() const data = useMobileHomeData() + useHomeSparePage(data.hostCatalogLoaded ? data.sortedHosts.map((host) => host.id) : []) const insets = useSafeAreaInsets() const openMobileHostEdit = useOpenMobileHostEdit() const openMobileTasks = useOpenMobileTasks() diff --git a/mobile/src/home/use-home-spare-page.ts b/mobile/src/home/use-home-spare-page.ts new file mode 100644 index 00000000000..58aa55953c6 --- /dev/null +++ b/mobile/src/home/use-home-spare-page.ts @@ -0,0 +1,48 @@ +import { useFocusEffect } from 'expo-router' +import { useCallback } from 'react' +import { AppState } from 'react-native' +import { setForegroundTimer } from '../mobile-web-shell/foreground-timer' +import { + enterHomeSparePage, + leaveHomeSparePage, + prepareHomeSparePage +} from '../mobile-web-shell/home-spare-page' +import { processGenerationStore } from '../mobile-web-shell/process-generation-store' + +// Past Home's first paint and its first reads, so the boot never competes with them. +const HOME_SPARE_IDLE_MS = 1000 + +const HOST_ID_SEPARATOR = '\n' + +// While Home is shown, keep one page booted for the most recently connected host with a cached build. +// Native drops it when the app leaves the foreground, so every return to it arms again. +export function useHomeSparePage(hostIds: readonly string[]): void { + const hosts = hostIds.join(HOST_ID_SEPARATOR) + useFocusEffect( + useCallback(() => { + if (hosts === '') { + return undefined + } + enterHomeSparePage() + let cancelTimer = (): void => undefined + const arm = (): void => { + cancelTimer() + cancelTimer = setForegroundTimer( + () => void prepareHomeSparePage(processGenerationStore(), hosts.split(HOST_ID_SEPARATOR)), + HOME_SPARE_IDLE_MS + ) + } + arm() + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + arm() + } + }) + return () => { + subscription.remove() + cancelTimer() + leaveHomeSparePage() + } + }, [hosts]) + ) +} diff --git a/mobile/src/host-screen/host-list-queries.ts b/mobile/src/host-screen/host-list-queries.ts index c65ded233ea..caa752201fd 100644 --- a/mobile/src/host-screen/host-list-queries.ts +++ b/mobile/src/host-screen/host-list-queries.ts @@ -1,5 +1,10 @@ import * as z from 'zod' -import { getRepoExecutionHostId, parseExecutionHostId } from '../../../src/shared/execution-host' +import { + getRepoExecutionHostId, + parseExecutionHostId, + type ExecutionHostId +} from '../../../src/shared/execution-host' +import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' import type { MobileRelayHost } from '../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract' import type { Query, QueryClient } from '@tanstack/react-query' import { defineHostQuery } from '../query/host-query' @@ -18,8 +23,13 @@ import { } from '../worktree/worktree-catalog-snapshot-client' import type { Worktree } from '../worktree/workspace-list-types' import { getCachedWorktrees } from '../cache/worktree-cache' -import { hostRepoCatalogRepos, type HostRepoCatalogRow } from './host-screen-reply-schema' +import { + hostRepoCatalogRepos, + hostSshTargetSummarySchema, + type HostRepoCatalogRow +} from './host-screen-reply-schema' import { hostPlatformRead, hostRepoCatalogSnapshotRead } from './host-screen-operations' +import { NODE_PLATFORM_NAMES } from '../transport/connection/mobile-runtime-host-platform' import { acceptedMetadata, readHostSshTargetLabels, @@ -119,6 +129,18 @@ const serverRowSnapshots = { full: new ServerRowSnapshots(false) } +/** + * The server rows' input. Before the host's status is read it names the key a current desktop stores them + * under, so they paint from the store: the page came from that desktop, which sends the deltas capability. + */ +export function hostServerWorkspacesInput(hostCapabilities: readonly string[] | null): { + deltas: boolean +} { + return { + deltas: hostCapabilities?.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) ?? true + } +} + // Workspaces on the servers this desktop relays to; a server whose read fails keeps its rows. export const hostServerWorkspacesQuery = defineHostQuery<{ deltas: boolean }, ServerWorkspaces>({ family: 'relayHosts.workspaces', @@ -187,10 +209,18 @@ export function catalogNeedsHostLabels(catalog: readonly HostRepoCatalogRow[]): return hostIds.size > 1 || [...hostIds].some((id) => parseExecutionHostId(id)?.kind === 'ssh') } -export type HostRepoLabels = Awaited> & { +export type HostRepoLabels = { + sshTargetSummaries: z.output[] + // Entries rather than a Map, so the record can be stored. + hostLabels: [ExecutionHostId, string][] platform: NodeJS.Platform | null } +const storedHostLabelSchema = z.tuple([ + z.custom((id) => typeof id === 'string' && parseExecutionHostId(id) !== null), + z.string() +]) + export const hostRepoLabelsQuery = defineHostQuery({ family: 'repo.hostLabels', fetch: async (client) => { @@ -198,13 +228,25 @@ export const hostRepoLabelsQuery = defineHostQuery hostPlatformRead.request(client)) ]) - return { ...labels, platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null } + return { + sshTargetSummaries: labels.sshTargetSummaries, + hostLabels: [...labels.hostLabelById], + platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null + } }, staleTime: 60_000, gcTime: 30 * 60_000, refetchOnWindowFocus: true, // SSH health and the host's own label overrides. - signal: { events: ['reposChanged', 'sshStateChanged'] } + signal: { events: ['reposChanged', 'sshStateChanged'] }, + persist: { + version: 1, + dataSchema: z.object({ + sshTargetSummaries: z.array(hostSshTargetSummarySchema), + hostLabels: z.array(storedHostLabelSchema), + platform: z.enum(NODE_PLATFORM_NAMES).nullable() + }) + } }) // The host list's own reads, which pull to refresh repeats; project.sections lives with its hook. diff --git a/mobile/src/host-screen/host-screen-reply-schema.ts b/mobile/src/host-screen/host-screen-reply-schema.ts index 7afeb0e3cea..171400b27eb 100644 --- a/mobile/src/host-screen/host-screen-reply-schema.ts +++ b/mobile/src/host-screen/host-screen-reply-schema.ts @@ -83,20 +83,17 @@ export const hostRepoCatalogSnapshotSchema = z.union([ ]) // Keep target parsing total: absent/malformed targets yield [] and labels degrade to host ids on older hosts. A throw here would also skip the subsequent platform write. +export const hostSshTargetSummarySchema = z.looseObject({ + id: z.string(), + label: z.string(), + // Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict. + connected: salvagedOptional('connected', z.boolean()), + connectionStatus: salvagedOptional('connectionStatus', z.string()) +}) + export const hostSshTargetSummariesSchema = z .looseObject({ - targets: salvagedOptional( - 'targets', - salvagingArray( - z.looseObject({ - id: z.string(), - label: z.string(), - // Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict. - connected: salvagedOptional('connected', z.boolean()), - connectionStatus: salvagedOptional('connectionStatus', z.string()) - }) - ) - ) + targets: salvagedOptional('targets', salvagingArray(hostSshTargetSummarySchema)) }) .transform((reply) => reply.targets ?? []) .catch(() => []) diff --git a/mobile/src/host-screen/use-host-repo-metadata.ts b/mobile/src/host-screen/use-host-repo-metadata.ts index 6a7475b1dd3..2d306455441 100644 --- a/mobile/src/host-screen/use-host-repo-metadata.ts +++ b/mobile/src/host-screen/use-host-repo-metadata.ts @@ -66,7 +66,7 @@ export function useHostRepoMetadata(args: { useEffect(() => { if (needsLabels && labels.data) { setHostHealthById(buildSshHostHealthById(labels.data.sshTargetSummaries)) - setHostLabelById(labels.data.hostLabelById) + setHostLabelById(new Map(labels.data.hostLabels)) setHostPlatform(labels.data.platform) } else if (repos.data && !needsLabels) { // Clear labels for departed hosts so stale metadata cannot badge remaining rows. diff --git a/mobile/src/host-screen/use-host-screen-controller.ts b/mobile/src/host-screen/use-host-screen-controller.ts index 8d9b449a25e..983fa99eb96 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -60,7 +60,8 @@ export function useHostScreenController({ const relayRecovery = useRelayRecoveryStatus(hostId) const forgetHostClient = useForgetHostClient() const forceReconnectHost = useForceReconnect() - const { hostCapabilities, floatingWorkspaceEnabled, hostInstallationId } = useHostProtocolGates() + const { hostCapabilities, statusReadable, floatingWorkspaceEnabled, hostInstallationId } = + useHostProtocolGates() const state = useHostScreenState(hostId, peekStoredHost(hostId)) const settings = useHostViewSettings({ client, connState, state }) const connectionVerdict = classifyConnection({ @@ -83,6 +84,7 @@ export function useHostScreenController({ connState, embedded, hostCapabilities, + hostStatusReadable: statusReadable, hostId, sidebarFeed: sidebarFeed?.triggers ?? null, state, diff --git a/mobile/src/host-screen/use-host-worktree-catalog.ts b/mobile/src/host-screen/use-host-worktree-catalog.ts index c4cd1db1da9..ca3715baef2 100644 --- a/mobile/src/host-screen/use-host-worktree-catalog.ts +++ b/mobile/src/host-screen/use-host-worktree-catalog.ts @@ -1,4 +1,3 @@ -import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' import { WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/worktree-runtime-capabilities' import { readWorktreeFirstPage } from '../worktree/worktree-catalog-first-page' import type { Worktree } from '../worktree/workspace-list-types' @@ -32,6 +31,7 @@ import { HOST_LIST_BACKSTOP_POLL_MS, HOST_LIST_POLL_MS, HOST_LIST_TARGET, + hostServerWorkspacesInput, hostServerWorkspacesQuery, hostWorktreeCatalogKey, hostWorktreeCatalogQuery, @@ -54,6 +54,8 @@ export function useHostWorktreeCatalog(args: { connState: ConnectionState embedded: boolean hostCapabilities: readonly string[] + // Whether the host answered its status: capabilities are unknown, not absent, until it has. + hostStatusReadable: boolean hostId: string | undefined sidebarFeed: HostSidebarFeedTriggers | null state: HostScreenState @@ -64,6 +66,7 @@ export function useHostWorktreeCatalog(args: { connState, embedded, hostCapabilities, + hostStatusReadable, hostId, sidebarFeed, state, @@ -117,11 +120,13 @@ export function useHostWorktreeCatalog(args: { ) // An older desktop or shell lists no server rows, rather than rows that could not open. const relays = client !== null && relaysToServers(client, hostCapabilities) + // Until the host's status is read, stored server rows paint and nothing reads them. + const relaysRuledOut = hostStatusReadable && !relays const servers = useHostQuery( hostServerWorkspacesQuery, host, HOST_LIST_TARGET, - { deltas: hostCapabilities.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) }, + hostServerWorkspacesInput(hostStatusReadable ? hostCapabilities : null), // Execution hosts' notices are not relayed, so server rows keep the full poll. { enabled: !!hostId && relays, subscribed, refetchInterval: pollMs } ) @@ -210,12 +215,13 @@ export function useHostWorktreeCatalog(args: { }, [catalog.status, catalog.errorUpdatedAt]) useEffect(() => { - if (!relays) { - setServerWorkspaces(NO_SERVER_WORKSPACES) - } else if (servers.data) { + if (servers.data && !relaysRuledOut) { setServerWorkspaces(servers.data) + } else if (!relays) { + // Also drops a previous host's rows when the sidebar switches to one with none stored. + setServerWorkspaces(NO_SERVER_WORKSPACES) } - }, [relays, servers.data]) + }, [relays, relaysRuledOut, servers.data]) const fetchWorktrees = useCallback( async (options: { allowDuringModal?: boolean } = {}) => { diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index a2da39a8e47..2a9c0de8508 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2193,8 +2193,7 @@ "copyPathLabel": "Pfad der Markdown-Datei kopieren", "copySource": "Markdown-Quelltext kopieren", "discard": "Verwerfen", - "dismissKeyboard": "Tastatur ausblenden", - "dismissKeyboardHint": "Blendet die Bildschirmtastatur aus und lässt den Markdown-Editor geöffnet.", + "previewTruncated": "Vorschau gekürzt.", "readOnly": "Schreibgeschützt" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 92a11862440..fc4eaba6cd2 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -1962,8 +1962,7 @@ "markdownReader": { "readOnly": "Read only", "changedOnDesktop": "Changed on desktop", - "dismissKeyboard": "Dismiss keyboard", - "dismissKeyboardHint": "Hides the software keyboard and keeps the markdown editor open.", + "previewTruncated": "Preview truncated.", "discard": "Discard", "copyLoadedSource": "Copy loaded Markdown source", "copySource": "Copy Markdown source", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index 615bc3008fa..2afe3233ac1 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copiar la ruta del archivo Markdown", "copySource": "Copiar el código fuente Markdown", "discard": "Descartar", - "dismissKeyboard": "Ocultar teclado", - "dismissKeyboardHint": "Oculta el teclado en pantalla y mantiene abierto el editor de Markdown.", + "previewTruncated": "Vista previa truncada.", "readOnly": "Solo lectura" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index b4968d0c4b4..fbfb961983b 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copier le chemin du fichier Markdown", "copySource": "Copier la source Markdown", "discard": "Abandonner", - "dismissKeyboard": "Masquer le clavier", - "dismissKeyboardHint": "Masque le clavier virtuel et laisse l'éditeur Markdown ouvert.", + "previewTruncated": "Aperçu tronqué.", "readOnly": "Lecture seule" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 41b59f00545..954f8547baf 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "Markdown ファイルのパスをコピー", "copySource": "Markdown ソースをコピー", "discard": "破棄", - "dismissKeyboard": "キーボードを閉じる", - "dismissKeyboardHint": "Markdown エディターを開いたまま、ソフトウェアキーボードを非表示にします。", + "previewTruncated": "プレビューは一部省略されています。", "readOnly": "読み取り専用" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 7c34395812a..826352f43aa 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "Markdown 경로 복사", "copySource": "Markdown 소스 복사", "discard": "버리기", - "dismissKeyboard": "키보드 닫기", - "dismissKeyboardHint": "소프트웨어 키보드를 숨기고 Markdown 편집기를 열린 상태로 유지합니다.", + "previewTruncated": "미리보기가 일부만 표시됩니다.", "readOnly": "읽기 전용" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index fb83a84674d..ffa929cb422 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2260,8 +2260,7 @@ "copyPathLabel": "Copiar caminho do arquivo Markdown", "copySource": "Copiar código-fonte Markdown", "discard": "Descartar", - "dismissKeyboard": "Ocultar teclado", - "dismissKeyboardHint": "Oculta o teclado virtual e mantém o editor Markdown aberto.", + "previewTruncated": "Pré-visualização truncada.", "readOnly": "Somente leitura" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 9ced7c69b59..946c5ce0a27 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2327,8 +2327,7 @@ "copyPathLabel": "Скопировать путь к файлу Markdown", "copySource": "Скопировать исходный текст Markdown", "discard": "Отменить изменения", - "dismissKeyboard": "Скрыть клавиатуру", - "dismissKeyboardHint": "Скрывает экранную клавиатуру и оставляет редактор Markdown открытым.", + "previewTruncated": "Показана часть файла.", "readOnly": "Только чтение" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index f103d17aec0..5e3a4d21824 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2193,8 +2193,7 @@ "copyPathLabel": "Markdown yolunu kopyala", "copySource": "Markdown kaynağını kopyala", "discard": "Vazgeç", - "dismissKeyboard": "Klavyeyi gizle", - "dismissKeyboardHint": "Ekran klavyesini gizler ve Markdown düzenleyicisini açık tutar.", + "previewTruncated": "Önizleme kısaltıldı.", "readOnly": "Salt okunur" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index b41f7765fec..9c74b7b9ccd 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "複製 Markdown 路徑", "copySource": "複製 Markdown 原始碼", "discard": "放棄", - "dismissKeyboard": "收起鍵盤", - "dismissKeyboardHint": "隱藏螢幕鍵盤,並保持 Markdown 編輯器開啟。", + "previewTruncated": "預覽內容已截斷。", "readOnly": "唯讀" }, "nativeChatAttachActions": { diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index b99d10462d5..0e08b7072b4 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2189,8 +2189,7 @@ "copyPathLabel": "复制 Markdown 文件路径", "copySource": "复制 Markdown 源码", "discard": "放弃", - "dismissKeyboard": "关闭键盘", - "dismissKeyboardHint": "隐藏软键盘,并保持 Markdown 编辑器打开。", + "previewTruncated": "预览已截断。", "readOnly": "只读" }, "nativeChatAttachActions": { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts index f36beea592f..57c5300af27 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts @@ -20,6 +20,7 @@ export type BridgeInboundFramePort = { acceptState: (connection: BridgeConnectionSnapshot) => void acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void acceptBack: () => void + acceptParked: () => void acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void } @@ -66,6 +67,9 @@ export function createBridgeInboundFrameReader( case 'back': port.acceptBack() return + case 'parked': + port.acceptParked() + return case 'terminalKey': port.acceptTerminalKey(message.key, message.inputOwner) return diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 2cef127bfe6..31458b9f69d 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -236,6 +236,8 @@ const BridgeHostMessageSchema = z.union([ }), // Back names no destination; only the native stack knows what screen lies beneath. z.object({ v: versionSchema, type: z.literal(BRIDGE_BACK_FRAME) }), + // Native booted this page ahead of its screen and keeps its ready for the screen that adopts it. + z.object({ v: versionSchema, type: z.literal('parked') }), // One press on the shell's key rail. Sent only to a page granted the rail, which knows the frame. z.object({ v: versionSchema, diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts index 11cc2190538..e9a62282aa2 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts @@ -198,6 +198,8 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp acceptState: (connection) => acceptState(cache.apply(connection)), acceptConnectionPath: (connection) => acceptState(cache.applyPath(connection)), acceptBack: back.press, + // Only a page booted before its screen, with no init yet, is parked; the shell answers its ready on adoption. + acceptParked: handshake.stop, acceptTerminalKey: (key, inputOwner) => terminalKeys.accept(key, inputOwner) }) diff --git a/mobile/src/mobile-web-shell/generation-host-directories.ts b/mobile/src/mobile-web-shell/generation-host-directories.ts new file mode 100644 index 00000000000..fa56421bd66 --- /dev/null +++ b/mobile/src/mobile-web-shell/generation-host-directories.ts @@ -0,0 +1,27 @@ +import { joinUri } from './generation-cache-uri' +import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system' +import { isHostCacheKey } from './host-cache-key' + +export const GENERATIONS_DIRECTORY_NAME = 'generations' + +// One directory per host under the cache root; anything else there is not the store's. +export async function listGenerationHostDirectories( + fs: GenerationFileSystem +): Promise { + const entries = await fs.list(fs.rootUri) + return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name)) +} + +// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them. +export async function listActivatedGenerationHosts( + fs: GenerationFileSystem +): Promise { + const activated: string[] = [] + for (const host of await listGenerationHostDirectories(fs)) { + const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME)) + if (generations.some((entry) => entry.isDirectory)) { + activated.push(host.name) + } + } + return activated +} diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts index 257aeb9f58f..4d381f688ba 100644 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ b/mobile/src/mobile-web-shell/generation-store.test.ts @@ -544,4 +544,22 @@ describe('an update staged behind a live page', () => { expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD) expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true) }) + + it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => { + const fs = createFakeFileSystem() + const onDisk: boolean[] = [] + let reading = BUILD + const store = createGenerationStore({ + fileSystem: fs, + beforeHostFilesDeleted: async (hostKey) => { + onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`)) + } + }) + await activate(store, HOST) + onDisk.length = 0 + await activate(store, HOST, buildResult(SECOND)) + reading = SECOND_BUILD + await store.deleteHostCache(HOST) + expect(onDisk).toEqual([true, true]) + }) }) diff --git a/mobile/src/mobile-web-shell/generation-store.ts b/mobile/src/mobile-web-shell/generation-store.ts index 73d2d0bcf91..67da4168d49 100644 --- a/mobile/src/mobile-web-shell/generation-store.ts +++ b/mobile/src/mobile-web-shell/generation-store.ts @@ -10,7 +10,12 @@ import { MANIFEST_FILE_NAME } from './generation-asset-path' import { parseGenerationManifest, readWaitingStage } from './generation-manifest-read' import { reusableAssetsOf, reusableAssetsOfHosts } from './generation-reuse' import { stagingAssetsOf } from './generation-staging-assets' -import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system' +import type { GenerationFileSystem } from './generation-store-file-system' +import { + GENERATIONS_DIRECTORY_NAME, + listActivatedGenerationHosts, + listGenerationHostDirectories +} from './generation-host-directories' import { isHostCacheKey } from './host-cache-key' import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure' import { @@ -19,7 +24,6 @@ import { recordUpdateFailureIn } from './mobile-web-shell-update-failure-log' -const GENERATIONS_DIRECTORY_NAME = 'generations' const STAGING_DIRECTORY_NAME = 'tmp' export const MAX_CACHED_HOSTS = 6 @@ -66,6 +70,8 @@ export type GenerationStore = { export function createGenerationStore(options: { fileSystem: GenerationFileSystem + // Runs before a host's built files are deleted, so nothing still reading them outlives them. + beforeHostFilesDeleted?: (hostKey: string) => Promise }): GenerationStore { const fs = options.fileSystem const hostOrder = createGenerationHostOrder(fs) @@ -87,31 +93,15 @@ export function createGenerationStore(options: { const stagingRoot = (hostKey: string): string => joinUri(hostRoot(hostKey), STAGING_DIRECTORY_NAME) - async function listHostDirectories(): Promise { - const entries = await fs.list(fs.rootUri) - return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name)) - } - - // Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them. - async function listActivatedHosts(): Promise { - const activated: string[] = [] - for (const host of await listHostDirectories()) { - const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME)) - if (generations.some((entry) => entry.isDirectory)) { - activated.push(host.name) - } - } - return activated - } - async function dropHostTree(hostKey: string): Promise { activeMemo.delete(hostKey) deferred.drop(hostKey) + await options.beforeHostFilesDeleted?.(hostKey) await fs.delete(hostRoot(hostKey)) } async function enforceHostLimit(order: readonly string[]): Promise { - const hosts = await listActivatedHosts() + const hosts = await listActivatedGenerationHosts(fs) // Unlisted hosts sort first after index loss; keep the just-activated host last so it survives eviction. const evicted = new Set( [...hosts] @@ -238,6 +228,7 @@ export function createGenerationStore(options: { if (!(await fs.fileExists(joinUri(staged.directory, MANIFEST_FILE_NAME)))) { throw new Error(`staged generation ${staged.buildId} is no longer on disk`) } + await options.beforeHostFilesDeleted?.(staged.hostKey) // Delete old generations before rename: a crash then leaves no activation, whereas renaming first can leave two with no way to choose. for (const entry of entries) { await fs.delete(joinUri(generations, entry.name)) @@ -276,7 +267,9 @@ export function createGenerationStore(options: { async function openReusable(hostKey: string): Promise { const hosts = [ hostKey, - ...(await listHostDirectories()).map((host) => host.name).filter((key) => key !== hostKey) + ...(await listGenerationHostDirectories(fs)) + .map((host) => host.name) + .filter((key) => key !== hostKey) ] // Reuse discovery must not clean up another shell's active or staged files. const reusable = await reusableAssetsOfHosts(fs, hosts, (key) => readActive(key, false)) @@ -290,7 +283,7 @@ export function createGenerationStore(options: { return } // Interrupted downloads may belong to a host this launch never opens, so visit every host's tmp tree. - for (const host of await listHostDirectories()) { + for (const host of await listGenerationHostDirectories(fs)) { // Unreadable (undefined) is not corrupt: leave that tree for a later launch rather than fail every read. const waiting = await readWaitingStage(fs, host.name, stagingRoot(host.name)).catch( () => undefined diff --git a/mobile/src/mobile-web-shell/home-spare-page.ts b/mobile/src/mobile-web-shell/home-spare-page.ts new file mode 100644 index 00000000000..1456e5909b1 --- /dev/null +++ b/mobile/src/mobile-web-shell/home-spare-page.ts @@ -0,0 +1,91 @@ +import { + claimSpareDocument, + discardSpareDocument, + prepareSpareDocument +} from '../../modules/orca-mobile-web-shell/src/spare-document' +import type { GenerationStore } from './generation-store' +import { generationDirectoryPath } from './generation-store-file-system' +import { deriveHostCacheKey } from './host-cache-key' +import { mintShellSessionId } from './shell-session-id' + +// A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer. +const HOME_SPARE_CLAIM_GRACE_MS = 2000 + +// What JS last asked native to park, until a claim or a drop. Native may since have dropped it on +// its own (background, memory); this only saves the claim's native round trip when nothing can match. +let parkedDirectory: string | null = null +let dropTimer: ReturnType | null = null +// A prepare still reading the store when Home goes must not park a spare after the drop ran. +let homeShown = false + +function cancelDrop(): void { + if (dropTimer !== null) { + clearTimeout(dropTimer) + dropTimer = null + } +} + +// Boot one page from the first of `hostIds` (most recently connected first) that has a cached build. +export async function prepareHomeSparePage( + store: GenerationStore, + hostIds: readonly string[] +): Promise { + try { + for (const hostId of hostIds) { + const hostKey = deriveHostCacheKey(hostId) + const active = await store.readActiveGeneration(hostKey) + if (active === null) { + continue + } + if (!homeShown) { + return + } + const directory = generationDirectoryPath(active.directory) + const prepared = await prepareSpareDocument(directory, mintShellSessionId()) + if (prepared && !homeShown) { + await dropHomeSparePage() + } else if (prepared) { + parkedDirectory = directory + } + return + } + } catch { + // A spare only saves time; the next entry boots its own page without one. + } +} + +// The spare's session id when Home booted it from `directory`; the view mounted with it adopts that page. +export async function claimHomeSparePage(directory: string): Promise { + if (parkedDirectory !== directory) { + return null + } + parkedDirectory = null + cancelDrop() + try { + return await claimSpareDocument(directory) + } catch { + return null + } +} + +// Home is shown; a spare still inside the grace after leaving it stays. +export function enterHomeSparePage(): void { + homeShown = true + cancelDrop() +} + +// Home lost focus: a page opening from it claims the spare within the grace, anything else drops it. +export function leaveHomeSparePage(): void { + homeShown = false + cancelDrop() + dropTimer = setTimeout(() => { + dropTimer = null + void dropHomeSparePage() + }, HOME_SPARE_CLAIM_GRACE_MS) +} + +// Also runs before any host's built files go: that is rare, and a spare must not outlive its files. +export function dropHomeSparePage(): Promise { + parkedDirectory = null + return discardSpareDocument().catch(() => undefined) +} diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts index 1d7d38cdab3..d4c7b198524 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts @@ -165,6 +165,7 @@ async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise createGenerationStore({ fileSystem }), mintSessionId: () => 'session-id', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts index e9aff1ac061..44e53bfd614 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts @@ -1,12 +1,9 @@ -import * as ExpoCrypto from 'expo-crypto' -import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding' import { BRIDGE_READY_RETRY_MAX_MS } from './bridge/bridge-client-init-handshake' import type { GenerationStore } from './generation-store' import { processGenerationStore } from './process-generation-store' import { setForegroundTimer } from './foreground-timer' - -// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin. -const SESSION_ID_BYTES = 32 +import { claimHomeSparePage } from './home-spare-page' +import { mintShellSessionId } from './shell-session-id' // Allow five ready-backoff ceilings before treating a loaded document as silent; startup import failures may prevent every ready attempt. export const PAGE_READY_DEADLINE_MS = BRIDGE_READY_RETRY_MAX_MS * 5 @@ -17,6 +14,8 @@ export const DOCUMENT_LOAD_DEADLINE_MS = 20_000 export type MobileWebShellRuntime = { createStore(): GenerationStore mintSessionId(): string + // The session id of a page Home booted from this directory, so the view adopts it instead of a new one. + claimSpareSessionId(directory: string): Promise now(): number // Count only foreground time and return cancellation; tests replace this seam instead of waiting on wall time. setForegroundTimer(run: () => void, delayMs: number): () => void @@ -25,7 +24,8 @@ export type MobileWebShellRuntime = { export function createMobileWebShellRuntime(): MobileWebShellRuntime { return { createStore: processGenerationStore, - mintSessionId: () => encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)), + mintSessionId: mintShellSessionId, + claimSpareSessionId: claimHomeSparePage, now: Date.now, setForegroundTimer } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts index 5af588e13bc..b023ae70955 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts @@ -103,6 +103,7 @@ describe('a download that reuses the cached generation', () => { runtime: { createStore: () => store, mintSessionId: () => 's', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} }, diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts index 05605735d45..c5995d21023 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts @@ -264,17 +264,20 @@ export async function runShellEffect( context.manifest.current = null await (effect.kind === 'download' ? download : stageUpdate)({ ...context, opened }) return - case 'open-generation': + case 'open-generation': { + // A remount mints its own id below; only a first open adopts a page Home booted. + const spare = await runtime.claimSpareSessionId(effect.directory) send({ type: 'activated', flow, generationDirectory: effect.directory, - sessionId: runtime.mintSessionId(), + sessionId: spare ?? runtime.mintSessionId(), buildId: effect.buildId, totalBytes: effect.totalBytes, elapsedMs: runtime.now() - context.startedAt }) return + } case 'remount': { const remount = (): void => send({ type: 'remounted', flow, sessionId: runtime.mintSessionId() }) diff --git a/mobile/src/mobile-web-shell/page-frames-without-host.ts b/mobile/src/mobile-web-shell/page-frames-without-host.ts new file mode 100644 index 00000000000..86e6c55ce88 --- /dev/null +++ b/mobile/src/mobile-web-shell/page-frames-without-host.ts @@ -0,0 +1,40 @@ +import { readBridgeClientMessage } from './bridge/bridge-envelope' +import { frameWithoutHostLine } from './shell-bridge-log-lines' +import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder' + +export type FrameWithoutHostFacts = { hostId: string; clientReady: boolean; snapshotReady: boolean } + +export type PageFramesWithoutHost = { + /** A frame no host serves yet; `facts` is null when a retired session's host is still mounted. */ + receive: (sessionId: string, json: string, facts: FrameWithoutHostFacts | null) => void + /** Hands the page's latest ready for this session to the host just built for it, once. */ + replayReady: (sessionId: string, host: { receive: (json: string) => void }) => void +} + +// Keep the ready instead of dropping it, so init does not wait on the page's 50 ms to 2 s backoff. +export function createPageFramesWithoutHost(): PageFramesWithoutHost { + let loggedSessionId: string | null = null + let ready: { sessionId: string; json: string } | null = null + return { + receive: (sessionId, json, facts) => { + if (facts !== null && loggedSessionId !== sessionId) { + loggedSessionId = sessionId + recordShellLifecycleLine(facts.hostId, frameWithoutHostLine(facts)) + } + const read = readBridgeClientMessage(json) + if (read.ok && read.message.type === 'ready') { + ready = { sessionId, json } + } else if (read.ok && read.message.type === 'close') { + // The document that asked is gone, so its ready must not be answered. + ready = null + } + }, + replayReady: (sessionId, host) => { + const kept = ready + ready = null + if (kept?.sessionId === sessionId) { + host.receive(kept.json) + } + } + } +} diff --git a/mobile/src/mobile-web-shell/process-generation-store.ts b/mobile/src/mobile-web-shell/process-generation-store.ts index 205abf1145c..1087603b3e0 100644 --- a/mobile/src/mobile-web-shell/process-generation-store.ts +++ b/mobile/src/mobile-web-shell/process-generation-store.ts @@ -1,11 +1,15 @@ import { createGenerationStore, type GenerationStore } from './generation-store' import { createExpoGenerationFileSystem } from './generation-store-file-system' +import { dropHomeSparePage } from './home-spare-page' let processStore: GenerationStore | null = null // Share one store queue across native callers so host removal cannot interleave with generation/index/failure-log writes. export function processGenerationStore(): GenerationStore { - processStore ??= createGenerationStore({ fileSystem: createExpoGenerationFileSystem() }) + processStore ??= createGenerationStore({ + fileSystem: createExpoGenerationFileSystem(), + beforeHostFilesDeleted: dropHomeSparePage + }) return processStore } diff --git a/mobile/src/mobile-web-shell/shell-session-id.ts b/mobile/src/mobile-web-shell/shell-session-id.ts new file mode 100644 index 00000000000..3b28baf87e4 --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-session-id.ts @@ -0,0 +1,9 @@ +import * as ExpoCrypto from 'expo-crypto' +import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding' + +// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin. +const SESSION_ID_BYTES = 32 + +export function mintShellSessionId(): string { + return encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)) +} diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts index d18449d42b9..95ce881b9e4 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts @@ -14,6 +14,7 @@ import { import type { BridgeErrorCapture } from './bridge/bridge-error-capture' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { FakeRpcClient } from './bridge-host-test-fakes' +import type { PageHostSnapshot } from './use-page-host-snapshot' const doubles = vi.hoisted((): { client: FakeRpcClient | null } => ({ client: null })) @@ -82,6 +83,7 @@ function FakeShellView(props: { function Harness(props: { session: MobileWebShellSessionState sessionEstablished?: boolean + snapshot?: PageHostSnapshot | null posted: PostedFrame[] probe: Probe faults: BridgeErrorCapture[] @@ -121,7 +123,7 @@ function Harness(props: { props.probe.backPops += 1 return 'popped' }, - snapshot: SNAPSHOT, + snapshot: props.snapshot === undefined ? SNAPSHOT : props.snapshot, readStorage: () => ({ storage: STORAGE, storageOversize: [] }), onStorageWrite: (key, value) => props.probe.storageWrites.push({ key, value }), // Use fresh callbacks each render; rebuilding for them would settle pending requests. @@ -198,7 +200,8 @@ afterEach(async () => { async function mount( session: MobileWebShellSessionState, - sessionEstablished?: boolean + sessionEstablished?: boolean, + snapshot?: PageHostSnapshot | null ): Promise { const posted: PostedFrame[] = [] const probe: Probe = { @@ -219,6 +222,7 @@ async function mount( createElement(Harness, { session: next, ...(sessionEstablished === undefined ? {} : { sessionEstablished }), + ...(snapshot === undefined ? {} : { snapshot }), posted, probe, faults, @@ -312,3 +316,26 @@ describe('a session that handshook before this host existed', () => { expect(fakeClient().requests).toEqual([]) }) }) + +describe('a ready the page sent before its host existed', () => { + it('is answered with one init as soon as the host snapshot arrives', async () => { + const mounted = await mount(readyState('session-one'), undefined, null) + await mounted.deliver(clientFrame({ type: 'ready' })) + expect(mounted.posted).toEqual([]) + await act(async () => { + mounted.tree.update( + createElement(Harness, { + session: readyState('session-one'), + snapshot: SNAPSHOT, + posted: mounted.posted, + probe: mounted.probe, + faults: mounted.faults, + readies: mounted.readies + }) + ) + }) + expect(mounted.frames('session-one')).toEqual([ + expect.objectContaining({ type: 'init', sessionId: 'session-one', buildId: 'build-a' }) + ]) + }) +}) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 04bfaa84363..07a5f2cba67 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -5,14 +5,14 @@ import type { BridgeTerminalKeyRail } from './bridge/bridge-terminal-key' import type { BridgePageGeometry } from './bridge/bridge-page-geometry' -import { useCallback, useEffect, useLayoutEffect, useRef } from 'react' +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import type { MobileWebShellBridgeMessagePayload, OrcaMobileWebShellViewHandle } from '../../modules/orca-mobile-web-shell/src' import { useHostClient } from '../transport/connection/host-client-hooks' import { createBridgeDiagnosticReporter } from './bridge-diagnostic-log' -import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines' +import { bridgeDiagnosticLine } from './shell-bridge-log-lines' import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder' import type { BridgeColorScheme, BridgeInitRoute, BridgeUiLocale } from './bridge/bridge-envelope' import type { BridgeClearableRouteParam } from './bridge/bridge-route-update' @@ -27,6 +27,7 @@ import type { BridgeErrorCapture } from './bridge/bridge-error-capture' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { PageHostSnapshot } from './use-page-host-snapshot' import type { PageStorageForInit } from './page-storage-keys' +import { createPageFramesWithoutHost } from './page-frames-without-host' class BridgeViewGoneError extends Error { constructor() { @@ -135,7 +136,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW // Read identity lazily without rebuilding a live host just to refresh a string. const clientIdRef = useRef(clientId) const clientRef = useRef(client) - const droppedFrameLoggedRef = useRef(null) + const [framesWithoutHost] = useState(createPageFramesWithoutHost) // Update refs on every commit before host construction; native frames may arrive before passive effects. useLayoutEffect(() => { argsRef.current = args @@ -207,13 +208,14 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW hostRef.current = { sessionId, host } // Reset host-owned drop totals on rebuild so a new lower count cannot look like frames being recovered. latest.onBinaryFramesDropped(0) + framesWithoutHost.replayReady(sessionId, host) return () => { // Capture Back before disposal so the next host for this document inherits it. establishedBackRef.current = { sessionId, back: host.readSessionBack() } hostRef.current = null host.dispose() } - }, [buildId, client, sessionId, snapshot]) + }, [buildId, client, framesWithoutHost, sessionId, snapshot]) useEffect(() => { const mounted = hostRef.current @@ -246,25 +248,24 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW (event: MobileWebShellBridgeMessageEvent) => { const mounted = hostRef.current if (mounted === null || mounted.sessionId !== sessionId) { - if ( - mounted === null && - sessionId !== null && - droppedFrameLoggedRef.current !== sessionId - ) { - droppedFrameLoggedRef.current = sessionId - recordShellLifecycleLine( - argsRef.current.hostId, - frameWithoutHostLine({ - clientReady: clientRef.current !== null, - snapshotReady: argsRef.current.snapshot !== null - }) + if (sessionId !== null) { + framesWithoutHost.receive( + sessionId, + event.nativeEvent.json, + mounted === null + ? { + hostId: argsRef.current.hostId, + clientReady: clientRef.current !== null, + snapshotReady: argsRef.current.snapshot !== null + } + : null ) } return } mounted.host.receive(event.nativeEvent.json) }, - [sessionId] + [framesWithoutHost, sessionId] ), // Fenced on the session the same way inbound frames are: a host left over from a session this // render has moved past must not be handed this one's route. diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts index 65f65113c20..c5b70b1822f 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts @@ -264,7 +264,8 @@ afterEach(async () => { async function mount( store: GenerationStore, - setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'] + setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'], + claimSpareSessionId: MobileWebShellRuntime['claimSpareSessionId'] = async () => null ): Promise { const timers = createTimerSeam() // Mint distinct ids so a remount's replacement view can be told from the one it retires. @@ -297,6 +298,7 @@ async function mount( runtime: { createStore: () => store, mintSessionId: () => `session-${++minted}`, + claimSpareSessionId, now: () => 0, setForegroundTimer: setForegroundTimer ?? timers.setTimer } @@ -374,6 +376,19 @@ describe('the wait for the page to speak', () => { expect(mounted.states().at(-1)?.kind).toBe('ready') }) + it('opens a page Home booted under its session id, and remounts under a fresh one', async () => { + const fake = createFakeStore() + const mounted = await mount(fake.store, undefined, async () => 'home-spare') + fake.settleCacheRead(activeGeneration()) + await flush() + expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'home-spare' }) + await act(async () => { + mounted.shellFailed('document-load-failed') + }) + await flush() + expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'session-1' }) + }) + it('stays ready when the page speaks after document load and the timers fire', async () => { const mounted = await ready() await act(async () => { @@ -401,6 +416,7 @@ describe('the wait for the page to speak', () => { runtime: { createStore: () => fake.store, mintSessionId: () => 'session-id', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: createTimerSeam().setTimer } diff --git a/mobile/src/new-workspace/NewWorkspacePageScreen.tsx b/mobile/src/new-workspace/NewWorkspacePageScreen.tsx index 87d2dd18388..c067d406cfa 100644 --- a/mobile/src/new-workspace/NewWorkspacePageScreen.tsx +++ b/mobile/src/new-workspace/NewWorkspacePageScreen.tsx @@ -20,7 +20,7 @@ export function NewWorkspacePageScreen() { const { hostCapabilities } = useHostProtocolGates() const connected = connState === 'connected' const worktrees = useHostWorktreeRows(client, connected, hostId) - const hostLabelById = useHostLabelById(client, connected) + const hostLabelById = useHostLabelById(client, connected, hostId) const worktreePaths = useMemo(() => worktrees.map((worktree) => worktree.path), [worktrees]) return ( diff --git a/mobile/src/new-workspace/use-host-label-by-id.ts b/mobile/src/new-workspace/use-host-label-by-id.ts index 40f56029255..6ea165fc630 100644 --- a/mobile/src/new-workspace/use-host-label-by-id.ts +++ b/mobile/src/new-workspace/use-host-label-by-id.ts @@ -1,32 +1,26 @@ -import { useEffect, useState } from 'react' +import { useMemo } from 'react' import type { ExecutionHostId } from '../../../src/shared/execution-host' -import { readHostSshTargetLabels } from '../host-screen/host-ssh-target-labels-read' +import { + HOST_LIST_TARGET, + hostRepoLabelsQuery, + NO_HOST_LIST_INPUT +} from '../host-screen/host-list-queries' +import { useHostQuery } from '../query/host-query' import type { RpcClient } from '../transport/rpc/rpc-client-contract' const NO_HOST_LABELS: ReadonlyMap = new Map() +// The host list's labels: the drawer shows the stored ones at once and the read refreshes them. export function useHostLabelById( client: RpcClient | null, - connected: boolean + connected: boolean, + hostId: string ): ReadonlyMap { - const [labels, setLabels] = useState(NO_HOST_LABELS) - - useEffect(() => { - if (!client || !connected) { - return - } - let live = true - readHostSshTargetLabels(client) - .then(({ hostLabelById }) => { - if (live) { - setLabels(hostLabelById) - } - }) - .catch(() => {}) - return () => { - live = false - } - }, [client, connected]) - - return labels + const { data } = useHostQuery( + hostRepoLabelsQuery, + { hostId, client: connected ? client : null }, + HOST_LIST_TARGET, + NO_HOST_LIST_INPUT + ) + return useMemo(() => (data ? new Map(data.hostLabels) : NO_HOST_LABELS), [data]) } diff --git a/mobile/src/query/first-paint-query-keys.ts b/mobile/src/query/first-paint-query-keys.ts index 609962e2284..b916cae5a07 100644 --- a/mobile/src/query/first-paint-query-keys.ts +++ b/mobile/src/query/first-paint-query-keys.ts @@ -2,6 +2,9 @@ import { normalizeExecutionHostId } from '../../../src/shared/execution-host' import { HOST_LIST_TARGET, hostRepoCatalogQuery, + hostRepoLabelsQuery, + hostServerWorkspacesInput, + hostServerWorkspacesQuery, hostWorktreeCatalogKey, hostWorktreeCatalogQuery, NO_HOST_LIST_INPUT @@ -37,15 +40,38 @@ export function firstPaintQueryKeys(hostId: string, route: URL): PersistedHostQu if (screen === 'tasks') { return firstPaintTaskKeys(hostId) } + if (screen === 'new-workspace') { + // The drawer's existing-workspace check and host labels. + return [ + persistedHostQueryKey(hostWorktreeCatalogQuery, hostWorktreeCatalogKey(hostId)), + persistedHostQueryKey( + hostRepoLabelsQuery, + hostQueryKey(hostId, hostRepoLabelsQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + ) + ].filter((key) => key !== null) + } const keys = screen === undefined ? [ persistedHostQueryKey(hostWorktreeCatalogQuery, hostWorktreeCatalogKey(hostId)), persistedHostQueryKey(hostViewFamily, hostViewKey(hostId)), + persistedHostQueryKey( + hostServerWorkspacesQuery, + hostQueryKey( + hostId, + hostServerWorkspacesQuery.family, + HOST_LIST_TARGET, + hostServerWorkspacesInput(null) + ) + ), persistedHostQueryKey( hostRepoCatalogQuery, hostQueryKey(hostId, hostRepoCatalogQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) ), + persistedHostQueryKey( + hostRepoLabelsQuery, + hostQueryKey(hostId, hostRepoLabelsQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + ), persistedHostQueryKey( hostProjectSectionsQuery, hostQueryKey( diff --git a/mobile/src/query/host-query.ts b/mobile/src/query/host-query.ts index 4d65785430e..209ad828d2e 100644 --- a/mobile/src/query/host-query.ts +++ b/mobile/src/query/host-query.ts @@ -141,6 +141,28 @@ export async function readHostQueryLive( return data } +// A cached read through the screen's `read`: reuses a fresh answer and joins a read already out. An answer +// an event marked stale as it landed predates that change, so it is read again. +export async function fetchHostQuery( + queryClient: QueryClient, + query: HostQuery, + host: { hostId: string; client: RpcClient }, + target: HostQueryTarget, + input: TInput, + read: () => Promise +): Promise { + const options = { + ...hostQueryOptions(query, host.client, host.hostId, target, input), + queryFn: read + } + let data = await queryClient.fetchQuery(options) + // Each pass needs a newer event, so this ends with the event burst. + while (queryClient.getQueryState(options.queryKey)?.isInvalidated) { + data = await queryClient.fetchQuery(options) + } + return data +} + // A read ahead of the user: skipped while the key holds current data, joins a read already out. export function prefetchHostQuery( queryClient: QueryClient, diff --git a/mobile/src/session/mobile-structured-composer-command.ts b/mobile/src/session/mobile-structured-composer-command.ts index b2c75949dff..04d80c271fb 100644 --- a/mobile/src/session/mobile-structured-composer-command.ts +++ b/mobile/src/session/mobile-structured-composer-command.ts @@ -46,6 +46,8 @@ export async function dispatchMobileStructuredCommand(input: { waitsInLine: (command: AgentSessionConversationCommand) => boolean /** `refusedWhile`: what the phone showed the refused command waiting on. */ onError: MobileNativeChatSendErrorReporter + /** Called as a /clear goes out; the returned restore runs unless the host accepts it. */ + onClearSent?: () => () => void timeoutMs: number }): Promise { if ( @@ -98,6 +100,8 @@ export async function dispatchMobileStructuredCommand(input: { } } input.pending.current = true + const restoreClear = command === 'clear' ? input.onClearSent?.() : undefined + let accepted = false try { const result = await requestStructuredAgentSessionMutation({ @@ -133,6 +137,7 @@ export async function dispatchMobileStructuredCommand(input: { startFailures: input.startFailures(), say: sayMobileAgentSessionFailure }) + accepted = reply.accepted // A refusal names its cause only when the phone showed it, as on desktop. return { accepted: reply.accepted, @@ -146,6 +151,9 @@ export async function dispatchMobileStructuredCommand(input: { } } finally { input.pending.current = false + if (!accepted) { + restoreClear?.() + } } } }) diff --git a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx index 434cdbfddd3..649307a056f 100644 --- a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx @@ -285,6 +285,7 @@ function MobileNativeChatOverlayContent({ status={session.status} error={session.error} readFailedFinally={session.readFailedFinally === true} + clearing={session.clearing === true} agent={controller.nativeChatAgent} sessionLive={controller.nativeChatSessionLive} agentWorking={controller.nativeChatTurnActive} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.tsx b/mobile/src/session/native-chat/MobileNativeChatView.tsx index a98345f4ea4..b3eead5e801 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatView.tsx @@ -77,6 +77,8 @@ type ChatViewProps = MobileNativeChatSendProps & error?: string // Permanent read failure replaces the pane because further chat actions cannot succeed. readFailedFinally?: boolean + /** A sent /clear hid the old rows: show a blank list until its divider lands, not the new-chat copy. */ + clearing?: boolean agent?: string | null sessionLive?: boolean /** The turn is live: working, or waiting on the reader. */ @@ -138,6 +140,7 @@ export function MobileNativeChatView({ status, error, readFailedFinally = false, + clearing = false, agent, sessionLive, agentWorking, @@ -235,7 +238,6 @@ export function MobileNativeChatView({ : (ask ?? permission ?? question ?? collapsedPrompt ?? awaitingInput) != null, send: onSend }) - const { lockReason } = offlineQueue const handleSend = useCallback( async (...send: Parameters): Promise => { // Retire the previous notice before this action can report a new one. @@ -313,10 +315,10 @@ export function MobileNativeChatView({ // Changing text scale relays out every row, so preserve the page’s reading anchor. const layoutKey = `${fontScale}` const footer = mobileNativeChatListFooter(liveStatus, turns.waitingRows, renderItem) - const emptyState = mobileNativeChatEmptyState(status, agent ?? null, error, sessionLive) + const emptyState = mobileNativeChatEmptyState(status, agent, error, sessionLive, clearing) const composerPlaceholder = mobileNativeChatComposerPlaceholder( - lockReason, + offlineQueue.lockReason, turnIndicator?.afterStop ) const promptOwnsInput = useMobileNativeChatPromptInputOwner( @@ -346,7 +348,7 @@ export function MobileNativeChatView({ collapsedPrompt={collapsedPrompt} /> diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx new file mode 100644 index 00000000000..ba720a54a09 --- /dev/null +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx @@ -0,0 +1,160 @@ +import { createElement } from 'react' +import { act, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent-session/agent-session-wire' +import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' +import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' +import { + SESSION_ID, + mutationOk, + ok, + snapshotEvent +} from './use-mobile-structured-agent-session-queued.test-fixture' + +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() } +})) + +const row = ( + sequence: number, + role: 'user' | 'assistant', + text: string +): AgentJournalRenderItem => ({ + itemId: `row-${sequence}`, + sequence, + revision: 1, + observedAt: sequence, + body: { kind: 'message', role, blocks: [{ type: 'text', text }] } +}) +const divider = (sequence: number): AgentJournalRenderItem => ({ + ...row(sequence, 'assistant', ''), + body: { + kind: 'status', + text: 'Context cleared', + presentation: 'context-cleared', + contextClear: { operationId: `clear-${sequence}`, afterFence: 3, clearedAt: sequence } + } +}) +const dividerLands = (sequence: number): AgentSessionSubscribeEvent => ({ + type: 'batch', + sessionId: SESSION_ID, + batch: { + cursor: { epoch: 'epoch-1', sequence }, + items: [divider(sequence)], + removedItemIds: [], + submissions: [] + } +}) + +describe('useMobileStructuredAgentSession /clear', () => { + let renderer: ReactTestRenderer | null = null + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + async function mount() { + let listener: ((value: unknown) => void) | null = null + let reply: ((response: RpcResponse) => void) | null = null + const client: Pick = { + getState: () => 'connected', + onStateChange: () => () => {}, + sendRequest: vi.fn(async (method: string): Promise => { + if (method === 'agentSession.options') { + return ok({ models: [], current: {}, conversationCommands: ['clear'] }) + } + if (method === 'agentSession.conversationCommand') { + return new Promise((resolve) => { + reply = resolve + }) + } + return ok({}) + }), + subscribe: vi.fn((method: string, _params: unknown, onData: (value: unknown) => void) => { + if (method === 'agentSession.subscribe') { + listener = onData + } + return () => {} + }) + } + const rendered: { hook: ReturnType | null } = { + hook: null + } + function Harness(): null { + rendered.hook = useMobileStructuredAgentSession({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook's request, subscription and connection members are provided. + client: client as RpcClient, + pairedHostClient: null, + sessionId: SESSION_ID, + enabled: true, + connected: true, + hostSupport: null, + agent: 'claude', + onSendError: vi.fn() + }) + return null + } + act(() => { + renderer = createWithQueryClient(createElement(Harness)) + }) + await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) + act(() => + listener?.( + snapshotEvent({ items: [row(1, 'user', 'question'), row(2, 'assistant', 'reply')] }) + ) + ) + await vi.waitFor(() => expect(rendered.hook?.conversationCommands).toEqual(['clear'])) + const shown = () => ({ + text: rendered.hook!.session.messages.flatMap((message) => + message.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + ), + clearing: rendered.hook!.session.clearing + }) + const sendClear = async () => { + let outcome: Promise | undefined + act(() => { + outcome = rendered.hook!.sendWithOutcome('/clear') + }) + await vi.waitFor(() => expect(reply).toEqual(expect.any(Function))) + // Wrapped so awaiting the press does not wait for the reply. + return { outcome: outcome! } + } + return { + shown, + sendClear, + push: (event: AgentSessionSubscribeEvent) => act(() => listener?.(event)), + reply: async (value: unknown) => { + await act(async () => reply?.(mutationOk(value))) + } + } + } + + it('hides the old transcript from the press until the divider lands', async () => { + const chat = await mount() + expect(chat.shown()).toEqual({ text: ['question', 'reply'], clearing: false }) + + const { outcome } = await chat.sendClear() + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + // The host's reply can reach the phone before the divider it already wrote. + await chat.reply({ command: 'clear', state: 'completed' }) + await expect(outcome).resolves.toBe('accepted') + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + chat.push(dividerLands(3)) + expect(chat.shown()).toEqual({ text: ['Context cleared'], clearing: false }) + }) + + it('shows the old transcript again when the host refuses the /clear', async () => { + const chat = await mount() + const { outcome } = await chat.sendClear() + expect(chat.shown()).toEqual({ text: [], clearing: true }) + + await chat.reply({ command: 'clear', state: 'completed', error: 'Could not clear.' }) + await expect(outcome).resolves.toBe('rejected') + expect(chat.shown()).toEqual({ text: ['question', 'reply'], clearing: false }) + }) +}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts index d8f5893538b..9065b441ab8 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts @@ -62,9 +62,11 @@ function mobileNativeChatEmptyStateCopy( export function mobileNativeChatEmptyState( status: MobileNativeChatStatus, - agent: string | null, + agent: string | null | undefined, error?: string, - sessionLive = false + sessionLive = false, + /** A sent /clear hid the old rows: a blank list until its divider lands, not new-chat copy. */ + clearing = false ): NativeChatEmptyStateCopy | null { const agentLabel = agent ? formatAgentTypeLabel(agent) @@ -77,7 +79,7 @@ export function mobileNativeChatEmptyState( case 'awaiting-transcript': return mobileNativeChatEmptyStateCopy(sessionLive ? 'empty' : 'notFound', agentLabel) case 'ready': - return mobileNativeChatEmptyStateCopy('empty', agentLabel) + return clearing ? null : mobileNativeChatEmptyStateCopy('empty', agentLabel) case 'error': { const copy = mobileNativeChatEmptyStateCopy('error', agentLabel) return error ? { ...copy, subtitle: describeLoadError(error, translate).message } : copy diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts index 93f6956dc93..c1952510c32 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts @@ -39,6 +39,8 @@ export type MobileNativeChatSession = { /** The read failed for good (damage, or a newer Orca's chat): the error says why, once, and * there is nothing to send into. */ readFailedFinally?: boolean + /** This phone's /clear is out and its divider has not landed: the old rows are hidden. */ + clearing?: boolean hasMore: boolean /** `olderPages === 'loading'`, kept because recorded RPC fixtures read it. */ loadingEarlier: boolean diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index d0011546821..f15182b48eb 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -128,11 +128,8 @@ export function useMobileStructuredAgentSession( onSendError, confirmRecorded: useMobileStructuredSendRecorded(client, sessionId, hostSupport) }) - const { transcriptItems, messages, receipts } = useMobileStructuredTranscript( - agent, - state, - sends.optimistic - ) + const transcript = useMobileStructuredTranscript(agent, state, sends.optimistic, sessionKey) + const { clearing, transcriptItems, messages, receipts } = transcript const turnTiming = useMobileStructuredAgentTurnTiming( { ...state, items: transcriptItems }, turnId @@ -190,6 +187,7 @@ export function useMobileStructuredAgentSession( stopping: turnIndicator.stopping, ...sends, commandPending: commandPendingRef, + onClearSent: transcript.onClearSent, sendsOut, controller: goal.commands, sessionCommands: args.sessionCommands, @@ -273,7 +271,8 @@ export function useMobileStructuredAgentSession( transcriptLoading: status === 'loading', error: state.error, readFailedFinally: status === 'error' && isFinalAgentSessionReadRefusal(state.readRefusal), - hasMore: state.hasOlder && olderPages !== 'unavailable', + clearing, + hasMore: state.hasOlder && olderPages !== 'unavailable' && !clearing, loadingEarlier: olderPages === 'loading', olderPages, loadEarlier diff --git a/mobile/src/session/use-mobile-structured-send-with-outcome.ts b/mobile/src/session/use-mobile-structured-send-with-outcome.ts index 0f3273fc4e6..be4dd2ea649 100644 --- a/mobile/src/session/use-mobile-structured-send-with-outcome.ts +++ b/mobile/src/session/use-mobile-structured-send-with-outcome.ts @@ -63,6 +63,7 @@ export function useMobileStructuredSendWithOutcome(args: { reject: MobileStructuredSends['reject'] holdUnconfirmed: MobileStructuredSends['holdUnconfirmed'] commandPending: { current: boolean } + onClearSent: () => () => void /** This chat's message sends still out, which a command waits behind as on desktop. */ sendsOut: MobileStructuredSendsOut controller: Pick< @@ -99,6 +100,7 @@ export function useMobileStructuredSendWithOutcome(args: { commandsWait, controller, enabled, + onClearSent, reject, holdUnconfirmed, onSendError, @@ -193,6 +195,7 @@ export function useMobileStructuredSendWithOutcome(args: { selectAgentSessionCurrentRequests(stateRef.current) ), onError: onSendError, + onClearSent, timeoutMs }) if (commandOutcome !== null) { @@ -275,6 +278,7 @@ export function useMobileStructuredSendWithOutcome(args: { commandsWait, controller, enabled, + onClearSent, reject, holdUnconfirmed, onSendError, diff --git a/mobile/src/session/use-mobile-structured-transcript.ts b/mobile/src/session/use-mobile-structured-transcript.ts index 992e9a9495f..f4fa032ca3c 100644 --- a/mobile/src/session/use-mobile-structured-transcript.ts +++ b/mobile/src/session/use-mobile-structured-transcript.ts @@ -1,5 +1,9 @@ -import { useMemo } from 'react' -import { agentSessionTranscriptRows } from '../../../src/shared/agent-session/agent-session-context-clear' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + agentSessionContextClearOutstanding, + agentSessionTranscriptRows, + latestAgentSessionContextClearSequence +} from '../../../src/shared/agent-session/agent-session-context-clear' import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' import { projectStructuredAgentSessionMessages } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' @@ -12,18 +16,50 @@ const mobileStructuredTranscript = createStructuredQuestionProjection( projectStructuredAgentStartItem ) -/** The chat's transcript rows, its messages with this phone's sends in flight, and the prompts they resolved. */ +/** The chat's transcript rows, its messages with this phone's sends in flight, and the prompts they resolved. + * From this phone's /clear press until its divider lands, the rows drawn at the press stay hidden: + * the host stops the old agent before it writes the divider. */ export function useMobileStructuredTranscript( agent: string | null, - state: Pick, - optimistic: Parameters[1] + state: Pick, + optimistic: Parameters[1], + sessionKey: string ) { + const [clearSent, setClearSent] = useState<{ + sessionKey: string + epoch: string | null + tail: number + } | null>(null) + // The newest row the last commit drew: the rows a press hides. + const tail = state.items.at(-1)?.sequence ?? 0 + const drawnTail = useRef(tail) + useEffect(() => { + drawnTail.current = tail + }, [tail]) + const onClearSent = useCallback(() => { + const sent = { sessionKey, epoch: state.epoch, tail: drawnTail.current } + setClearSent(sent) + return () => setClearSent((current) => (current === sent ? null : current)) + }, [sessionKey, state.epoch]) + // A rewind's new epoch restarts sequences, so the press's rows are not in it. + const clearSentTail = + clearSent?.sessionKey === sessionKey && clearSent.epoch === state.epoch ? clearSent.tail : null + const latestClear = useMemo( + () => latestAgentSessionContextClearSequence(state.items), + [state.items] + ) + const clearing = agentSessionContextClearOutstanding(state.items, latestClear, clearSentTail) + // Retire a press that hides nothing (its divider landed, or its rows left), so a later trim cannot re-arm it. + if (clearSent?.sessionKey === sessionKey && !clearing) { + setClearSent(null) + } + const floor = clearing ? clearSentTail + 1 : latestClear const transcriptItems = useMemo( () => - withNativeChatCutTurnNotices(agentSessionTranscriptRows(state.items), { + withNativeChatCutTurnNotices(agentSessionTranscriptRows(state.items, floor), { agentName: agent ? (tuiAgentDisplayName(agent) ?? agent) : undefined }), - [agent, state.items] + [agent, floor, state.items] ) const messages = useMemo( () => @@ -39,6 +75,8 @@ export function useMobileStructuredTranscript( [transcriptItems, optimistic, state.submissions] ) return { + clearing, + onClearSent, transcriptItems, messages, receipts: mobileStructuredTranscript.transcript(transcriptItems).receipts diff --git a/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts new file mode 100644 index 00000000000..1a85fde8f6e --- /dev/null +++ b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts @@ -0,0 +1,53 @@ +import type { QueryClient } from '@tanstack/react-query' +import { defineHostQuery, fetchHostQuery } from '../../query/host-query' +import { hostQueryKey, type HostQueryTarget } from '../../query/host-query-key' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { gitStatusQuery } from '../mobile-git-status-query' +import type { BranchCompareLoadResult } from './mobile-diff-review-loaders' + +export type ReviewBranchCompareKey = { baseRef: string; head: string } + +// Read by Review with the base ref it resolved. A desktop git change can move the base and leave status as it was, +// so the change that re-reads status also marks these stale. +const reviewBranchCompareQuery = defineHostQuery({ + family: 'git.branchCompare', + signal: gitStatusQuery.signal +}) + +export async function readCachedReviewBranchCompare( + queryClient: QueryClient, + host: { hostId: string; client: RpcClient }, + target: HostQueryTarget, + key: ReviewBranchCompareKey, + read: () => Promise +): Promise { + const loaded = await fetchHostQuery( + queryClient, + reviewBranchCompareQuery, + host, + target, + key, + read + ) + // Only a compare that landed for this head is worth reusing; cached status can trail a commit. + if (loaded.result?.summary.headOid !== key.head) { + queryClient.removeQueries({ + queryKey: hostQueryKey(host.hostId, reviewBranchCompareQuery.family, target, key), + exact: true + }) + } + return loaded +} + +// Marked by a git change and not being read again, so only a new build brings the current compare. +export function reviewBranchCompareNeedsRead( + queryClient: QueryClient, + hostId: string, + target: HostQueryTarget, + key: ReviewBranchCompareKey +): boolean { + const state = queryClient.getQueryState( + hostQueryKey(hostId, reviewBranchCompareQuery.family, target, key) + ) + return state?.isInvalidated === true && state.fetchStatus === 'idle' +} diff --git a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts new file mode 100644 index 00000000000..0ea1695e085 --- /dev/null +++ b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.test.ts @@ -0,0 +1,89 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { documentQueryClient } from '../../test-support/rpc-recording/hook-mount' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' +import { useMobileDiffReviewSnapshot } from './use-mobile-diff-review-snapshot' + +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) + +const WORKTREE = 'repo-m::/r/wt' +let renderer: ReactTestRenderer | undefined +const queries = documentQueryClient() + +afterEach(async () => { + act(() => renderer?.unmount()) + renderer = undefined + await queries.end() +}) + +it('re-reads the branch compare when a desktop git change moves the base but not status', async () => { + let branchFiles = ['a.ts', 'b.ts'] + let emit: (event: unknown) => void = () => {} + const results: Record = { + 'git.status': { + entries: [], + conflictOperation: 'unknown', + head: 'h1', + branch: 'refs/heads/wt' + }, + 'worktree.show': { worktree: { baseRef: 'main', branch: 'refs/heads/wt', head: 'h1' } }, + 'repo.list': { repos: [] }, + 'settings.get': { settings: {} } + } + const client = stubRpcClient({ + getLastConnectedAt: () => 1, + onStateChange: () => () => {}, + subscribe: (_method, _params, onData) => { + emit = onData + return () => {} + }, + sendRequest: async (method): Promise => ({ + id: 'r', + ok: true, + result: + method === 'git.branchCompare' + ? { + summary: { + baseRef: 'main', + compareRef: 'HEAD', + changedFiles: branchFiles.length, + status: 'ready', + headOid: 'h1', + mergeBase: branchFiles.length === 2 ? 'm1' : 'm2' + }, + entries: branchFiles.map((path) => ({ path, status: 'modified' })) + } + : results[method] + }) + }) + let shown: string[] | undefined + function Review(): null { + const { screenState } = useMobileDiffReviewSnapshot({ + client, + connState: 'connected', + hostId: 'h', + worktreeId: WORKTREE, + commitOid: null, + filter: 'all', + setActionError: () => {} + }) + shown = + screenState.kind === 'ready' + ? screenState.branchCompare?.entries?.map((entry) => entry.path) + : undefined + return null + } + await act(async () => { + renderer = create(queries.wrap(createElement(Review))) + }) + act(() => emit({ type: 'ready', subscriptionId: 's' })) + await vi.waitFor(() => expect(shown).toEqual(['a.ts', 'b.ts'])) + + // a.ts was merged into main from another checkout; this worktree's status is unchanged. + branchFiles = ['b.ts'] + act(() => emit({ type: 'gitStatusChanged', repoId: 'repo-m' })) + + await vi.waitFor(() => expect(shown).toEqual(['b.ts']), { timeout: 3_000 }) +}) diff --git a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts index 1a724609276..10fe03182a0 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts @@ -10,6 +10,11 @@ import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../../transport/connection/connection-state' import { loadMobileDiffReviewCommitSnapshot } from './mobile-diff-review-commit-loader' import type { MobileBranchCompareCache } from './mobile-diff-review-loaders' +import { + readCachedReviewBranchCompare, + reviewBranchCompareNeedsRead, + type ReviewBranchCompareKey +} from './mobile-diff-review-branch-compare-cache' import type { MobileDiffReviewQueueFilter } from './mobile-diff-review-queue' import type { ReviewScreenState } from './mobile-diff-review-screen-model' import { @@ -59,11 +64,17 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { ) // The same git.status entry Changes shows, so Review opened from it starts from those rows. const worktreeReview = worktreeId !== '' && commitOid === null && filter !== 'commit' - const { data: statusRead } = useHostQuery(gitStatusQuery, { hostId, client }, target, NO_INPUT, { - enabled: worktreeReview - }) + const { data: statusRead, dataUpdatedAt: statusReadAt } = useHostQuery( + gitStatusQuery, + { hostId, client }, + target, + NO_INPUT, + { enabled: worktreeReview } + ) // The status read the shown snapshot was built from; AWAITING while a build waits for its first read. const builtFromRef = useRef(undefined) + // The compare the current build read, so a git change that marked it stale rebuilds even when status held. + const builtCompareRef = useRef(null) // Reloads after a write wait for the rebuild they cause, so the screen's buttons match the new files. const buildWaitersRef = useRef<(() => void)[]>([]) const settleWaiters = () => { @@ -72,23 +83,12 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { } } - const cacheBranchCompare = useCallback( - async (key, read) => { - const queryKey = hostQueryKey(hostId, 'git.branchCompare', target, key) - const loaded = await queryClient.fetchQuery({ queryKey, queryFn: read }) - // Only a compare that landed for this head is worth reusing; cached status can trail a commit. - if (loaded.result?.summary.headOid !== key.head) { - queryClient.removeQueries({ queryKey, exact: true }) - } - return loaded - }, - [hostId, queryClient, target] - ) - - const buildSnapshot = useEffectEvent(async (status: GitStatusRead | undefined) => { + // `sameStatus`: only the compare moved, so worktree diffs keyed to the shown status read still hold. + const buildSnapshot = useEffectEvent(async (status?: GitStatusRead, sameStatus = false) => { const generation = loadGenerationRef.current + 1 loadGenerationRef.current = generation const isCurrent = () => generation === loadGenerationRef.current + builtCompareRef.current = null try { if (!worktreeId) { setScreenState({ @@ -170,6 +170,14 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { throw err } ) + const cacheBranchCompare: MobileBranchCompareCache = async (key, read) => { + // A superseded build's compare is never shown. + if (!isCurrent()) { + return { result: null } + } + builtCompareRef.current = key + return readCachedReviewBranchCompare(queryClient, { hostId, client }, target, key, read) + } const { snapshot, branch } = startMobileDiffReviewSnapshot(client, worktreeId, { status: statusInput, compareAgainstUpstream, @@ -183,7 +191,9 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { if (!isCurrent()) { return } - setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) + if (!sameStatus) { + setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) + } if (loaded) { setScreenState(withMobileDiffReviewBranch(state, loaded, worktreeId)) setActionError(loaded.error ?? null) @@ -224,12 +234,27 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { }, [client, commitOid, connState, queryClient, reloadNonce, statusKey, worktreeReview]) // A status read that changed what Changes shows rebuilds the snapshot; one in flight already brings its own. - useEffect(() => { + // A read that lands unchanged rebuilds too once a git change marked the shown compare stale; a compare + // still out is read again by its own build when it lands marked. + const rebuildOnStatusRead = useEffectEvent((read: GitStatusRead) => { const built = builtFromRef.current - if (worktreeReview && statusRead !== undefined && built !== AWAITING && statusRead !== built) { - void buildSnapshot(statusRead) + if (built === AWAITING) { + return } - }, [statusRead, worktreeReview]) + const compare = builtCompareRef.current + const compareMarked = + compare !== null && reviewBranchCompareNeedsRead(queryClient, hostId, target, compare) + if (read !== built) { + void buildSnapshot(read) + } else if (compareMarked) { + void buildSnapshot(read, true) + } + }) + useEffect(() => { + if (worktreeReview && statusRead !== undefined) { + rebuildOnStatusRead(statusRead) + } + }, [statusRead, statusReadAt, worktreeReview]) // The compare base is read when a snapshot is built; a later setting change rebuilds without re-reading status. const shownCompareSettingRef = useRef(compareAgainstUpstream) diff --git a/mobile/src/test-support/spare-document-node.ts b/mobile/src/test-support/spare-document-node.ts new file mode 100644 index 00000000000..13723e207eb --- /dev/null +++ b/mobile/src/test-support/spare-document-node.ts @@ -0,0 +1,4 @@ +// Alias the native spare pool for Vitest: no spare is ever parked, so every entry boots its own page. +export const prepareSpareDocument = (): Promise => Promise.resolve(false) +export const claimSpareDocument = (): Promise => Promise.resolve(null) +export const discardSpareDocument = (): Promise => Promise.resolve() diff --git a/mobile/vitest.config.ts b/mobile/vitest.config.ts index e9861769f75..53fb31a4987 100644 --- a/mobile/vitest.config.ts +++ b/mobile/vitest.config.ts @@ -22,6 +22,12 @@ export default defineConfig({ new URL('./src/test-support/expo-crypto-node.ts', import.meta.url) ) }, + { + find: /^.*\/orca-mobile-web-shell\/src\/spare-document$/, + replacement: fileURLToPath( + new URL('./src/test-support/spare-document-node.ts', import.meta.url) + ) + }, { find: 'expo-haptics', replacement: fileURLToPath( diff --git a/package.json b/package.json index 4014ada5610..faf04c0f277 100644 --- a/package.json +++ b/package.json @@ -207,7 +207,6 @@ "bench:wsl-git-shell": "node config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs", "bench:hang-watchdog-memory": "pnpm run ensure:electron-runtime && node config/scripts/diagnostics/hang-watchdog/hang-watchdog-memory-benchmark.mjs", "bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/main-thread-jank-bench.mjs", - "bench:worktree-deletion": "node tests/tools/benchmarks/worktree-deletion-dev-bench.mjs", "bench:zustand-selector-fanout": "node config/scripts/performance/renderer-projection/zustand-selector-fanout-benchmark.mjs", "bench:agent-inspection-cadence": "node config/scripts/performance/agent-lineage/agent-inspection-cadence-batching-benchmark.mjs", "bench:renderer-quadratic-scans": "node config/scripts/performance/renderer-markdown/renderer-quadratic-scan-benchmark.mjs", @@ -232,7 +231,7 @@ "check:import-boundaries": "bun config/scripts/static-analysis/process-boundaries/check-import-boundaries.mjs" }, "dependencies": { - "@anthropic-ai/claude-agent-sdk": "0.3.284", + "@anthropic-ai/claude-agent-sdk": "0.3.318", "@floating-ui/dom": "1.8.0", "@linear/sdk": "^97.0.0", "@orca/process-host": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2e0691a065..228db2cb82d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -227,8 +227,8 @@ importers: .: dependencies: '@anthropic-ai/claude-agent-sdk': - specifier: 0.3.284 - version: 0.3.284(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7) + specifier: 0.3.318 + version: 0.3.318(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7) '@floating-ui/dom': specifier: 1.8.0 version: 1.8.0 @@ -763,9 +763,9 @@ packages: '@antfu/install-pkg@1.1.0': resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==} - '@anthropic-ai/claude-agent-sdk@0.3.284': - resolution: {integrity: sha512-NSoJwEq6nFSf8dtaacYx37QdGgqApI3eHFUlxclMLYi8irb6ZJwEaUnPnLUCyAyg9W/tMkgZC0GXWLRCc01I0w==} - engines: {node: '>=18.0.0'} + '@anthropic-ai/claude-agent-sdk@0.3.318': + resolution: {integrity: sha512-z5WHCUeW52SKQ3rnvI3zt8X5h2QQ5o3Cgg5xarO5Rimfe67f3pOJt2aOh00S8t/nRzqfs+8nCb9o1EoXe+yccA==} + engines: {node: '>=18.14.0'} peerDependencies: '@anthropic-ai/sdk': '>=0.93.0' '@modelcontextprotocol/sdk': ^1.29.0 @@ -8342,7 +8342,7 @@ snapshots: package-manager-detector: 1.6.0 tinyexec: 1.1.2 - '@anthropic-ai/claude-agent-sdk@0.3.284(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)': + '@anthropic-ai/claude-agent-sdk@0.3.318(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 0.122.0(zod@4.6.7) '@modelcontextprotocol/sdk': 1.32.1(supports-color@7.2.0)(zod@4.6.7) diff --git a/src/cli/browser/browser-extension.ts b/src/cli/browser/browser-extension.ts new file mode 100644 index 00000000000..8a95b6c7a4a --- /dev/null +++ b/src/cli/browser/browser-extension.ts @@ -0,0 +1,47 @@ +import type { + BrowserExtensionSummaryListResult, + BrowserExtensionReloadResult +} from '../../shared/browser/extensions/browser-extension-types' +import type { CommandHandler } from '../dispatch' +import { getPresentStringFlag } from '../flags' +import { printResult } from '../format' +import { resolveRepoPathArgument } from '../repo-path-arguments' + +export const BROWSER_EXTENSION_HANDLERS: Record = { + 'extension list': async ({ flags, client, json }) => { + const profileId = getPresentStringFlag(flags, 'profile') + const result = await client.call( + 'browser.extensionList', + profileId !== undefined ? { profileId } : {} + ) + printResult(result, json, ({ active, extensions }) => + !active + ? 'Browser extensions are disabled in Settings › Experimental.' + : extensions.length === 0 + ? 'No browser extensions installed.' + : extensions + .map( + (extension) => + `${extension.id}\t${extension.name}\t${extension.version}\t${extension.enabled ? 'enabled' : 'disabled'}\t${extension.source}\t${extension.path}` + ) + .join('\n') + ) + }, + 'extension reload': async ({ flags, client, cwd, json }) => { + const extensionId = getPresentStringFlag(flags, 'extension-id') + const path = getPresentStringFlag(flags, 'path') + const result = await client.call('browser.extensionReload', { + ...(extensionId !== undefined ? { extensionId } : {}), + ...(path !== undefined + ? { + path: resolveRepoPathArgument(path, cwd, client.isRemote, 'Remote extension source') + } + : {}) + }) + printResult( + result, + json, + (value) => `Reloaded extension ${value.extensionId} across all profiles where it is enabled.` + ) + } +} diff --git a/src/cli/browser/browser-handler-groups.ts b/src/cli/browser/browser-handler-groups.ts index 48b89c4d065..356fcc787f7 100644 --- a/src/cli/browser/browser-handler-groups.ts +++ b/src/cli/browser/browser-handler-groups.ts @@ -2,6 +2,11 @@ import { ORCA_BROWSER_CLI_COMMAND_KEYS } from '../../shared/orca-browser-cli-com import type { HandlerGroup } from '../handler-group-manifest' export const BROWSER_HANDLER_GROUPS: readonly HandlerGroup[] = [ + { + name: 'browser-extension', + keys: ORCA_BROWSER_CLI_COMMAND_KEYS['browser-extension'], + load: async () => (await import('./browser-extension.js')).BROWSER_EXTENSION_HANDLERS + }, { name: 'browser-identity', keys: ORCA_BROWSER_CLI_COMMAND_KEYS['browser-identity'], diff --git a/src/cli/command-scoped-flag-help.ts b/src/cli/command-scoped-flag-help.ts index 0c9a294dcaa..fc5c6c56006 100644 --- a/src/cli/command-scoped-flag-help.ts +++ b/src/cli/command-scoped-flag-help.ts @@ -3,6 +3,11 @@ const FILE_OPEN_FOCUS_HELP = "--focus Bring the user to the file (switches Orca's window to its worktree)" const COMMAND_SCOPED_FLAG_HELP: Record> = { + 'extension reload': { + 'extension-id': + '--extension-id Installed unpacked extension ID; also accepted positionally', + path: '--path Source folder of exactly one installed unpacked extension' + }, 'reference add': { url: '--url Full review/issue URL or Jira key; use positionals or repeated --url', 'reference-site': '--reference-site Jira site for bare keys; see orca jira connection' diff --git a/src/cli/format-recovery.test.ts b/src/cli/format-recovery.test.ts index 7a1bc9b5582..d5fdda58ca5 100644 --- a/src/cli/format-recovery.test.ts +++ b/src/cli/format-recovery.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { formatCliError, reportCliError } from './format' -import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' +import { reportCliError } from './format' +import { RuntimeRpcFailureError } from './runtime-client' function selectorAmbiguous(): RuntimeRpcFailureError { return new RuntimeRpcFailureError({ @@ -32,29 +32,6 @@ describe('ambiguous selector recovery', () => { }) log.mockRestore() }) - - it('gives only the repair step when two folder workspaces share an id', () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const repair = 'Remove one of these folder workspaces in the Orca app and add its folder again.' - - reportCliError( - new RuntimeRpcFailureError({ - id: 'req_selector', - ok: false, - error: { - code: 'selector_ambiguous', - message: 'selector_ambiguous', - data: { selector: 'folder:hub-a', duplicateFolderId: 'hub-a', nextSteps: [repair] } - }, - _meta: { runtimeId: 'runtime_local' } - }), - true, - { commandPath: ['worktree', 'rm'], worktreeSelector: 'folder:hub-a' } - ) - - expect(JSON.parse(String(log.mock.calls[0]?.[0])).error.data.nextSteps).toEqual([repair]) - log.mockRestore() - }) }) describe('worktree selector recovery', () => { @@ -90,36 +67,3 @@ describe('worktree selector recovery', () => { log.mockRestore() }) }) - -describe('CLI error recovery', () => { - it('prefers structured recovery over generic computer hints in text output', () => { - const error = new RuntimeClientError('invalid_argument', 'Unknown flag --forcce', { - nextSteps: ['Did you mean: --force'] - }) - - const output = formatCliError(error, { commandPath: ['computer', 'click'] }) - - expect(output).toContain('Next step: Did you mean: --force') - expect(output).not.toContain('Fix the command flags or RPC params') - }) - - it('preserves the local request-id protection for an RPC runtime-unavailable error', () => { - const error = new RuntimeRpcFailureError({ - id: 'req_rpc_runtime_mutation', - ok: false, - error: { - code: 'runtime_unavailable', - message: 'Re-issue the same RPC command with --retry-request mutation_2.', - data: { - orchestrationRequestId: 'mutation_2', - nextSteps: ['Read the RPC mutation status before retrying.'] - } - }, - _meta: { runtimeId: 'runtime_local' } - }) - - expect(formatCliError(error)).toBe( - 'Re-issue the same RPC command with --retry-request mutation_2.' - ) - }) -}) diff --git a/src/cli/handlers/project.ts b/src/cli/handlers/project.ts index 324f8ec660c..798eaa8bdb6 100644 --- a/src/cli/handlers/project.ts +++ b/src/cli/handlers/project.ts @@ -156,6 +156,7 @@ export const PROJECT_HANDLERS: Record = { client.isRemote, 'Project setup clone' ), + folderName: getOptionalStringFlag(flags, 'folder-name'), displayName: getOptionalStringFlag(flags, 'display-name'), projectId: await resolveProjectIdSelector(client, getRequiredStringFlag(flags, 'project')) } diff --git a/src/cli/handlers/serve-reset-identity.test.ts b/src/cli/handlers/serve-reset-identity.test.ts index eb4fa8d2c89..d5e975892f9 100644 --- a/src/cli/handlers/serve-reset-identity.test.ts +++ b/src/cli/handlers/serve-reset-identity.test.ts @@ -1,11 +1,14 @@ -import { chmodSync, mkdtempSync, statSync } from 'node:fs' +import { chmodSync, existsSync, mkdtempSync, statSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { resetServeHostIdentity } from './serve-reset-identity' import { loadOrCreateE2EEKeypair } from '../../main/runtime/rpc/server/pairing/e2ee-keypair' import { DeviceRegistry } from '../../main/runtime/rpc/server/pairing/device-registry' -import { acquireOrcadInstanceLock } from '../../main/orcad/orcad-instance-lock' +import { + acquireOrcadInstanceLock, + ORCAD_LOCK_FILE_NAME +} from '../../main/orcad/orcad-instance-lock' import { ensureHostInstanceIdentity, hostInstanceIdFromEnv @@ -35,6 +38,26 @@ describe('resetServeHostIdentity', () => { expect(loadOrCreateE2EEKeypair(before.dir).publicKeyB64).toBe(publicKeyB64) }) + it('keeps the notice that the last run crashed, and leaves no lock after a clean one', async () => { + const before = pairedProfile() + const lockPath = join(before.dir, ORCAD_LOCK_FILE_NAME) + await resetServeHostIdentity(before.dir) + expect(existsSync(lockPath)).toBe(false) + + // What an orcad killed before releasing its lock leaves behind; the pid is past any pid_max. + const crashed = acquireOrcadInstanceLock(before.dir) + crashed.release() + writeFileSync(lockPath, JSON.stringify({ ...crashed.record, pid: 99_999_999 })) + await resetServeHostIdentity(before.dir) + + const next = acquireOrcadInstanceLock(before.dir) + try { + expect(next.previousUnexpectedExit).toMatchObject({ pid: 99_999_999 }) + } finally { + next.release() + } + }) + it('refuses while an Orca holds the profile lock and changes nothing', async () => { const before = pairedProfile() const lock = acquireOrcadInstanceLock(before.dir) diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 569ae4564f5..6ad30800fca 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -216,6 +216,8 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' tab profile clone Clone a browser tab into another profile', ' tab switch Switch the active browser tab by --index or --page', ' tab close Close a browser tab by --index/--page or the current tab', + ' extension list List installed browser extensions', + ' extension reload Reload an unpacked extension across enabled profiles', ' snapshot Accessibility snapshot with element refs (e.g. @e1, @e2)', ' goto Navigate the active tab to --url', ' click Click element by --element ref', diff --git a/src/cli/specs/browser-advanced.ts b/src/cli/specs/browser-advanced.ts index 229c0e54c3b..39cbcee9105 100644 --- a/src/cli/specs/browser-advanced.ts +++ b/src/cli/specs/browser-advanced.ts @@ -3,6 +3,25 @@ import { GLOBAL_FLAGS } from '../args' import { withBrowserPageTarget } from './browser-page-target' export const BROWSER_ADVANCED_COMMAND_SPECS: CommandSpec[] = withBrowserPageTarget([ + { + path: ['extension', 'list'], + summary: 'List installed browser extensions and their enabled state', + usage: 'orca extension list [--profile ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'profile'], + notes: ['Desktop only. Defaults to the default browser profile on this Orca host.'] + }, + { + path: ['extension', 'reload'], + summary: 'Reload an installed unpacked browser extension', + usage: + 'orca extension reload [--json] | orca extension reload --path [--json]', + positionalArgs: ['extension-id'], + allowedFlags: [...GLOBAL_FLAGS, 'extension-id', 'path'], + notes: [ + 'Desktop only. --path selects an already installed unpacked source folder; it never installs one.', + 'Like the Settings reload button, this restarts the extension in every profile where it is enabled.' + ] + }, { path: ['cookie', 'get'], summary: 'Get cookies for the active tab (optionally filter by URL)', diff --git a/src/cli/specs/browser-page-target.ts b/src/cli/specs/browser-page-target.ts index 175b5f58333..ab303ca29f7 100644 --- a/src/cli/specs/browser-page-target.ts +++ b/src/cli/specs/browser-page-target.ts @@ -2,6 +2,8 @@ import type { CommandSpec } from '../args' // These open, list or configure pages, so there is no one page to target. const NOT_PAGE_TARGETED = new Set([ + 'extension list', + 'extension reload', 'open-url', 'tab list', 'tab current', diff --git a/src/cli/specs/project.ts b/src/cli/specs/project.ts index 2de579cc117..1f7d989b8ba 100644 --- a/src/cli/specs/project.ts +++ b/src/cli/specs/project.ts @@ -48,10 +48,19 @@ export const PROJECT_COMMAND_SPECS: CommandSpec[] = [ path: ['project', 'setup-clone'], summary: 'Make a project available on a host by cloning a repository', usage: - 'orca project setup-clone --project --host --url --destination [--display-name ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'project', 'host', 'url', 'destination', 'display-name'], + 'orca project setup-clone --project --host --url --destination [--folder-name ] [--display-name ] [--json]', + allowedFlags: [ + ...GLOBAL_FLAGS, + 'project', + 'host', + 'url', + 'destination', + 'folder-name', + 'display-name' + ], notes: [ 'For remote runtimes, --destination must be an absolute parent directory on the remote server.', + '--folder-name sets the folder created inside --destination; it defaults to the repository name from the URL.', '--host takes local, ssh:, runtime:, or the bare host name `orca host list` prints for any of them.', 'SSH targets are cloned through the desktop UI because the desktop client owns SSH connections.' ], diff --git a/src/main/acp/history/acp-history-scaling.test.ts b/src/main/acp/history/acp-history-scaling.test.ts deleted file mode 100644 index 12848a2e6ec..00000000000 --- a/src/main/acp/history/acp-history-scaling.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, expect, it } from 'vitest' - -import '../../../shared/agent-session/journal/agent-session-journal-item-key' -import '../../../shared/agent-session/lifecycle/agent-session-turn-record' -import '../../../shared/agent-session/failures/agent-session-failure' -import '../../../shared/agent-session/failures/agent-session-failure-words' -import { - AGENT, - SESSION, - NAMESPACE, - closeProviderTimelineRigs -} from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import '../../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' -import '../../native-chat/agent-session-timeline/provider-timeline-history' -import '../../native-chat/agent-session-wire/termination/testing/structured-agent-session-observed-exit.test-fixture' -import '../../native-chat/agent-session-wire/termination/structured-agent-session-unfinished-work' -import '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import './acp-history-catch-up' -import './acp-history-catch-up.test-support' -import { acpHistoryTurns, type AcpLoadHistoryFrame } from './acp-history-replay' -import { translateHistoryTurn, type AcpHistoryScope } from './acp-history-translation' -import './acp-history-turn-matching' -import '../timeline/acp-turn-messages' -import { OPENCODE_ACP_DIALECT } from '../acp-dialects/opencode-dialect' -import '../acp-dialects/grok-dialect' -import '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' -import '../../native-chat/agent-session-journal/writing/journal-lifecycle-mutation' - -afterEach(closeProviderTimelineRigs) -const scope: AcpHistoryScope = { - agent: AGENT, - sessionId: SESSION, - providerSessionId: NAMESPACE, - identity: 'user-message-id', - dialect: OPENCODE_ACP_DIALECT -} -const frame = ( - update: Record, - meta?: Record -): AcpLoadHistoryFrame => ({ - method: 'session/update', - params: { sessionId: NAMESPACE, update, ...(meta ? { _meta: meta } : {}) } -}) -const user = (id: string, text: string) => - frame({ sessionUpdate: 'user_message_chunk', messageId: id, content: { type: 'text', text } }) - -it('imports a whole historical turn with more than 128 still-open message segments', () => { - const frames = [user('long-turn', 'Review the repository')] - for (let index = 0; index < 160; index += 1) { - frames.push( - frame({ - sessionUpdate: 'agent_message_chunk', - messageId: `answer-${index}`, - content: { type: 'text', text: 'Retained segment' } - }) - ) - } - frames.push( - frame({ - sessionUpdate: 'agent_message_chunk', - messageId: 'answer-0', - content: { type: 'text', text: ' and its late tail' } - }) - ) - const turn = acpHistoryTurns(frames, scope.identity)[0] - if (!turn || turn.turn === null) { - throw new Error('Missing identified historical turn') - } - const items = translateHistoryTurn(scope, { ...turn, turn: turn.turn }) - const answers = items.flatMap((item) => - item.body.kind === 'message' && item.body.role === 'assistant' ? [item.body] : [] - ) - expect(answers).toHaveLength(160) - expect(answers[0]).toMatchObject({ - blocks: [{ type: 'text', text: 'Retained segment and its late tail' }] - }) -}) diff --git a/src/main/acp/options/acp-session-option-write.ts b/src/main/acp/options/acp-session-option-write.ts index 6600f26026a..d04bdb01779 100644 --- a/src/main/acp/options/acp-session-option-write.ts +++ b/src/main/acp/options/acp-session-option-write.ts @@ -9,18 +9,22 @@ export type AcpOptionWriteBound = { onUncertain?: (error: Error) => void } +/** A native setter carries its own call deadline, so an unanswered one fails only its send. */ export function writeAcpSessionOption( connection: Pick, options: AcpStructuredOptions, write: AcpOptionWrite, - bound: AcpOptionWriteBound & { key: string; value: string } + { onUncertain: _retire, ...bound }: AcpOptionWriteBound & { key: string; value: string } ): Promise { + const { timeoutMs } = bound return boundAcpOptionWrite(options, bound, () => write.method === 'config' ? connection - .setConfigOption(write.configId, write.value) + .setConfigOption(write.configId, write.value, undefined, undefined, timeoutMs) .then((result) => () => options.adoptConfigOptions(result.configOptions)) - : connection.setModel(write.modelId).then(() => () => options.adoptModel(write.modelId)) + : connection + .setModel(write.modelId, undefined, timeoutMs) + .then(() => () => options.adoptModel(write.modelId)) ) } @@ -38,26 +42,51 @@ export function boundAcpOptionWrite( const revision = ++options.writeRevision options.invalidateInput(bound.key) options.writing += 1 + let failed = false + let native: Promise<() => string | void> | null = null let completed = false - const applied = send().then((apply) => { - completed = true - if (options.writeRevision !== revision) { - throw new Error(`${agent} option write was superseded`) - } - const resolved = apply() - options.adoptOwnWrite(bound.key, bound.value, resolved ?? undefined) - }) + // A withdrawn control may still land, so this one is sent only after it settles. + const applied = options + .whenControlsSettle() + .then(() => { + if (failed) { + throw new Error(`${agent} option write was withdrawn before it was sent`) + } + native = send() + // Orca's own write stays in flight until the agent answers, so its echo is not drift. + const released = (): void => { + options.writing -= 1 + } + native.then(released, released) + return native + }) + .then((apply) => { + completed = true + if (options.writeRevision !== revision) { + throw new Error(`${agent} option write was superseded`) + } + const resolved = apply() + options.adoptOwnWrite(bound.key, bound.value, resolved ?? undefined) + }) void applied.catch(() => { completed = true }) return new Promise((resolve, reject) => { + let settled = false const fail = (error: Error): void => { + if (settled) { + return + } if (options.writeRevision === revision) { options.writeRevision += 1 } + failed = true settle() - // A local deadline/abort cannot cancel an already-sent native control. - if (!completed) { + if (native === null) { + options.writing -= 1 + } else if (!completed) { + // A local deadline/abort cannot cancel an already-sent native control. + options.holdUntilSettled(native, bound.key) bound.onUncertain?.(error) } reject(error) @@ -71,7 +100,6 @@ export function boundAcpOptionWrite( () => fail(new Error(`${agent} did not answer an option write within ${timeoutMs}ms`)), timeoutMs ) - let settled = false const settle = (): void => { if (settled) { return @@ -79,7 +107,6 @@ export function boundAcpOptionWrite( settled = true clearTimeout(timer) signal?.removeEventListener('abort', onAbort) - options.writing -= 1 } signal?.addEventListener('abort', onAbort, { once: true }) applied.then(() => { @@ -88,3 +115,24 @@ export function boundAcpOptionWrite( }, fail) }) } + +/** A prompt waits for withdrawn controls, each bounded by its call deadline, or for its own abort. */ +export async function acpControlsSettled( + session: { options: AcpStructuredOptions }, + signal?: AbortSignal +): Promise { + if (!signal) { + return session.options.whenControlsSettle() + } + signal.throwIfAborted() + let onAbort = (): void => {} + const aborted = new Promise((_resolve, reject) => { + onAbort = () => reject(abortSignalReason(signal)) + signal.addEventListener('abort', onAbort, { once: true }) + }) + try { + await Promise.race([session.options.whenControlsSettle(), aborted]) + } finally { + signal.removeEventListener('abort', onAbort) + } +} diff --git a/src/main/acp/options/acp-structured-options.ts b/src/main/acp/options/acp-structured-options.ts index 8fe1895e87b..5327bde5116 100644 --- a/src/main/acp/options/acp-structured-options.ts +++ b/src/main/acp/options/acp-structured-options.ts @@ -64,6 +64,26 @@ export class AcpStructuredOptions { // selector, so a concrete change away from this retires it; ordinary control proof never does. private selectorProof: Readonly> | null = null + // Native controls a withdrawn send stopped waiting for; their call deadline bounds each one. + private readonly unsettled = new Set>() + + /** Later controls and prompts wait for it, and its key is re-sent once it settles. */ + holdUntilSettled(native: Promise, key: string): void { + this.unsettled.add(native) + const settled = (): void => { + this.unsettled.delete(native) + this.invalidateInput(key) + } + native.then(settled, settled) + } + + /** Resolves once no withdrawn control can still land at the agent. */ + async whenControlsSettle(): Promise { + while (this.unsettled.size > 0) { + await Promise.allSettled(this.unsettled) + } + } + invalidateInput(key: string): void { this.appliedInput.delete(key) if (key === 'model') { diff --git a/src/main/acp/protocol/acp-session-call.ts b/src/main/acp/protocol/acp-session-call.ts index 3057ddd33e6..1d330a49345 100644 --- a/src/main/acp/protocol/acp-session-call.ts +++ b/src/main/acp/protocol/acp-session-call.ts @@ -13,10 +13,13 @@ export function callAcpSession( params: unknown, schema: z.ZodType, answered: ((signedIn: boolean) => void) | undefined, - received?: (response: T) => void + received?: (response: T) => void, + timeoutMs: number | null = null ): Promise { return peer.request(method, params, { - timeoutMs: null, + timeoutMs, + // A bounded session control fails only itself; the agent is asked to drop it. + ...(timeoutMs === null ? {} : { onTimeout: 'cancel' as const }), settle: (response) => { if ('error' in response) { const error = response.error diff --git a/src/main/acp/protocol/acp-session-runtime.ts b/src/main/acp/protocol/acp-session-runtime.ts index 3b8959705ab..517142f647c 100644 --- a/src/main/acp/protocol/acp-session-runtime.ts +++ b/src/main/acp/protocol/acp-session-runtime.ts @@ -201,19 +201,31 @@ export class AcpSessionRuntime { } return this.peer.request(method, params, { timeoutMs }) } - async setModel(modelId: string, meta?: Meta): Promise { + /** `timeoutMs` drops an unanswered call from the pending set; null waits for the answer. */ + async setModel( + modelId: string, + meta?: Meta, + timeoutMs: number | null = null + ): Promise { const params: SetSessionModelRequest = { sessionId: this.sessionId(), modelId, ...withMeta(meta) } - return this.call('session/set_model', params, SetSessionModelResponseSchema) + return this.call( + 'session/set_model', + params, + SetSessionModelResponseSchema, + undefined, + timeoutMs + ) } async setConfigOption( configId: SetSessionConfigOptionRequest['configId'], value: SetSessionConfigOptionRequest['value'], meta?: Meta, - received?: (response: SetSessionConfigOptionResponse) => void + received?: (response: SetSessionConfigOptionResponse) => void, + timeoutMs: number | null = null ): Promise { const params = { configId, sessionId: this.sessionId(), ...withMeta(meta) } const request = @@ -224,7 +236,8 @@ export class AcpSessionRuntime { 'session/set_config_option', request, SetSessionConfigOptionResponseSchema, - received + received, + timeoutMs ) } @@ -248,9 +261,18 @@ export class AcpSessionRuntime { method: string, params: unknown, schema: z.ZodType, - received?: (response: T) => void + received?: (response: T) => void, + timeoutMs: number | null = null ): Promise { - return callAcpSession(this.peer, method, params, schema, this.options.onAuthAnswered, received) + return callAcpSession( + this.peer, + method, + params, + schema, + this.options.onAuthAnswered, + received, + timeoutMs + ) } private handleRequest(method: string, params: unknown, context: AcpRequestContext): unknown { diff --git a/src/main/acp/session/acp-session-ending.ts b/src/main/acp/session/acp-session-ending.ts index 3a5a6ef7eb6..690f2a7ba15 100644 --- a/src/main/acp/session/acp-session-ending.ts +++ b/src/main/acp/session/acp-session-ending.ts @@ -41,16 +41,15 @@ export function endAcpStructuredSession( if (session.ended) { return } + // Publishing the ending can re-enter cleanup, so attribution comes from before it. + const failureClose = session.failureClose session.ended = true session.events?.observeExit?.(undefined, observedAt) session.exitObservedAt = observedAt const stderr = session.connection.stderrTail() const how = providerExitStatusText(session.connection.exitStatus) - // Process exit can follow stream loss; keep that earlier reason when stderr is absent. - const lead = - session.journalClosed !== null && !stderr - ? session.journalClosed - : `${session.spec.agent} ACP agent exited` + // Orca's own close (stream loss, refusal) names the cause; the agent's stderr stays beside it. + const lead = failureClose ?? session.journalClosed ?? `${session.spec.agent} ACP agent exited` const reason = session.closeRequested ? `${session.spec.agent} ACP agent closed by Orca` : `${lead}${how ? ` ${how}` : ''}${stderr ? `: ${stderr}` : ''}` @@ -77,6 +76,7 @@ export function endAcpStructuredSession( ? agentSessionFailureFact('hostFault') : agentSessionFailureFact('providerExited', detail ? { detail } : {}), cause: session.closeRequested ? 'requested-close' : 'unexpected-exit', + ...(failureClose !== null && !session.closeRequested ? { closedByOrca: true as const } : {}), fence: session.fence, acquisitionGeneration: session.acquisitionGeneration, observedAt diff --git a/src/main/acp/session/acp-structured-acquire.ts b/src/main/acp/session/acp-structured-acquire.ts index 88d8a8163a0..8cb822ebf5f 100644 --- a/src/main/acp/session/acp-structured-acquire.ts +++ b/src/main/acp/session/acp-structured-acquire.ts @@ -46,7 +46,7 @@ export async function acquireAcpStructuredSession(input: { /** Protocol loss may precede process exit; null means startup has not produced a session. */ onConnectionLost: (session: AcpStructuredChild | null, error: Error) => void onSettled: AcpStructuredTurnsDeps['settle'] - forceClose: (sessionId: string) => void + forceClose: (sessionId: string, reason: string) => void }): Promise<{ acquisition: AgentSessionAcquisition session: AcpStructuredChild @@ -214,7 +214,11 @@ export async function acquireAcpStructuredSession(input: { session.turns?.accept(clientMessageId) } }, - onFailed: () => input.forceClose(sessionId) + onFailed: (reason) => + input.forceClose( + sessionId, + `Orca stopped ${agentName} after its chat journal refused a write (${reason})` + ) }) slot.lane = lane slot.reattaching = attaching @@ -260,6 +264,7 @@ export async function acquireAcpStructuredSession(input: { prompts, childStops: undefined, closeRequested: false, + failureClose: null, journalClosed: null, ended: false, exitObservedAt: null, diff --git a/src/main/acp/session/acp-structured-option-write-deadline.test.ts b/src/main/acp/session/acp-structured-option-write-deadline.test.ts new file mode 100644 index 00000000000..55fdf7193fa --- /dev/null +++ b/src/main/acp/session/acp-structured-option-write-deadline.test.ts @@ -0,0 +1,143 @@ +import { afterEach, expect, it } from 'vitest' +import { + closeProviderTimelineRigs, + SESSION +} from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { FakeFrame } from '../process/testing/acp-scripted-agent.test-support' +import { + GROK_CONFIG_OPTIONS, + openAcpAdapterRig, + waitFor, + type AcpAdapterRig +} from './testing/acp-structured-adapter.test-support' + +afterEach(closeProviderTimelineRigs) + +const HELLO: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'hello' }] +} + +function send( + rig: AcpAdapterRig, + clientMessageId: string, + executionOptions: { model?: string; effort?: string }, + signal?: AbortSignal +) { + return rig.adapter.dispatch({ + sessionId: SESSION, + clientMessageId, + body: HELLO, + fence: 1, + executionOptions, + ...(signal ? { signal } : {}) + }) +} + +/** Holds the first model/effort write unanswered; answers every later one. */ +async function openWithHeldFirstWrite( + optionWriteTimeoutMs: number +): Promise<{ rig: AcpAdapterRig; held: () => FakeFrame }> { + let held: FakeFrame | undefined + const rig = await openAcpAdapterRig({ + deps: { optionWriteTimeoutMs }, + script: (agent) => { + agent.on('session/set_config_option', (frame) => { + if (!held) { + held = frame + return + } + agent.reply(frame, { configOptions: GROK_CONFIG_OPTIONS }) + }) + } + }) + await rig.acquire() + return { + rig, + held: () => { + if (!held) { + throw new Error('no option write held yet') + } + return held + } + } +} + +it('refuses only the message whose model write went unanswered, keeping the agent running', async () => { + const { rig, held } = await openWithHeldFirstWrite(100) + + await expect(send(rig, 'send-1', { model: 'grok-4.6' })).rejects.toThrow() + + // The unanswered call is withdrawn at the agent, and the agent process is never ended for it. + const cancel = await rig.frame('$/cancel_request') + expect(cancel.params).toEqual({ requestId: held().id }) + await rig.settle() + expect(rig.ended).toEqual([]) + expect(rig.child().closes).toBe(0) + expect(rig.spawned.filter((step) => step === 'spawn')).toHaveLength(1) + + await expect(send(rig, 'send-2', { model: 'grok-4.6' })).resolves.toEqual({ state: 'admitted' }) + expect(rig.sent('session/set_config_option')).toHaveLength(2) + await rig.frame('session/prompt') +}) + +it('holds later controls and prompts until a withdrawn write is answered', async () => { + // Long enough that no deadline expires; the held write settles only when answered below. + const { rig, held } = await openWithHeldFirstWrite(10_000) + const withdrawn = new AbortController() + const first = send(rig, 'send-1', { effort: 'low' }, withdrawn.signal) + await waitFor(() => held()) + withdrawn.abort(new Error('replaced by a newer message')) + await expect(first).rejects.toThrow('replaced by a newer message') + + const second = send(rig, 'send-2', { model: 'grok-4.6' }) + await rig.settle() + // The withdrawn effort write may still land, so nothing follows it to the agent yet. + expect(rig.sent('session/set_config_option')).toHaveLength(1) + expect(rig.sent('session/prompt')).toEqual([]) + + rig.child().agent.reply(held(), { configOptions: GROK_CONFIG_OPTIONS }) + await expect(second).resolves.toEqual({ state: 'admitted' }) + expect(rig.sent('session/set_config_option')).toHaveLength(2) + await rig.frame('session/prompt') + expect(rig.ended).toEqual([]) +}) + +it.each([ + { + end: 'the agent exits on its own', + trigger: (rig: AcpAdapterRig) => rig.child().exit(), + closedByOrca: undefined, + reason: /^grok ACP agent exited/ + }, + { + end: 'Orca loses its connection to the agent', + trigger: (rig: AcpAdapterRig) => rig.child().agent.stdin.destroy(), + closedByOrca: true, + reason: /^grok ACP connection closed/ + } +])( + 'keeps who ended the agent when its final journal write is refused: $end', + async ({ trigger, closedByOrca, reason }) => { + const rig = await openAcpAdapterRig() + let refusing = false + const events = rig.rig.eventSink + const append = events.tryAppendTransition?.bind(events) + rig.rig.eventSink = { + ...events, + tryAppendTransition: (transition) => + refusing ? { accepted: false, reason: 'failed' } : append!(transition) + } + await rig.acquire() + refusing = true + trigger(rig) + const [ended] = await waitFor(() => { + expect(rig.ended).toHaveLength(1) + return rig.ended + }) + expect(ended?.closedByOrca).toBe(closedByOrca) + expect(ended?.reason).toMatch(reason) + } +) diff --git a/src/main/acp/session/acp-structured-session-adapter.ts b/src/main/acp/session/acp-structured-session-adapter.ts index 77fb871ea49..c7c4c31a36a 100644 --- a/src/main/acp/session/acp-structured-session-adapter.ts +++ b/src/main/acp/session/acp-structured-session-adapter.ts @@ -23,7 +23,7 @@ import { type AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' import { readAcpLiveOptions } from '../options/acp-live-options' -import { writeAcpSessionOption } from '../options/acp-session-option-write' +import { acpControlsSettled, writeAcpSessionOption } from '../options/acp-session-option-write' import { acpOptionWriteBound, withAcpModelFallback } from '../turns/acp-model-command' import { stopAcpChildren, acpChildStopCapabilities } from '../turns/acp-structured-child-stop' import * as childState from './children/acp-structured-child' @@ -125,6 +125,7 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { if (!optionsApplied) { return rejectedAcpDispatch(session) } + await acpControlsSettled(session, signal) input.signal?.throwIfAborted() await input.beforeDispatch?.() input.signal?.throwIfAborted() @@ -141,8 +142,11 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { }) } - compact: NonNullable = async (input) => - this.live(input.sessionId).turns.compact(input.command) + compact: NonNullable = async (input) => { + const session = this.live(input.sessionId) + await acpControlsSettled(session) + return session.turns.compact(input.command) + } cancelTurn: SessionAdapter['cancelTurn'] = async (input) => { const session = this.live(input.sessionId) diff --git a/src/main/acp/session/acp-structured-session-contract.ts b/src/main/acp/session/acp-structured-session-contract.ts index 5e3388a4b69..5af81feb4e2 100644 --- a/src/main/acp/session/acp-structured-session-contract.ts +++ b/src/main/acp/session/acp-structured-session-contract.ts @@ -24,6 +24,8 @@ export type AcpStructuredSession = { options: AcpStructuredOptions turns: AcpStructuredTurns closeRequested: boolean + /** Why Orca stopped this agent after its own failure (stream loss, a refused journal write). */ + failureClose: string | null /** Null while provider events can still reach the journal. */ journalClosed: string | null /** Exit was proven and reported to the host. */ diff --git a/src/main/acp/session/children/acp-structured-child-lifecycle.ts b/src/main/acp/session/children/acp-structured-child-lifecycle.ts index 73d4f023feb..1a0a6a4f4f1 100644 --- a/src/main/acp/session/children/acp-structured-child-lifecycle.ts +++ b/src/main/acp/session/children/acp-structured-child-lifecycle.ts @@ -60,7 +60,12 @@ export class AcpStructuredChildren { (pending() || lane.hasPendingDiagnostic(input.clientMessageId)) } - stopAfterFailure(sessionId: string): void { + stopAfterFailure(sessionId: string, reason: string): void { + const session = this.sessions.get(sessionId) + // An ending already under way (agent exit, requested close) keeps its own attribution. + if (session && !session.ended && !session.closeRequested) { + session.failureClose ??= reason + } void this.stop(sessionId, false).catch((error: unknown) => { const logger = neverThrowingStructuredAgentSessionLogger( this.deps.logger ?? createStructuredAgentSessionLogger() @@ -228,12 +233,11 @@ export class AcpStructuredChildren { session.journalClosed = error.message || error.name return } - closeAcpSessionJournal( - session, - `${session.spec.agent} ACP connection closed: ${error.message || error.name}`, - error - ) - this.stopAfterFailure(session.sessionId) + const reason = `${session.spec.agent} ACP connection closed: ${error.message || error.name}` + // Record the cause first: publishing the close can re-enter cleanup through a refused write. + session.failureClose ??= reason + closeAcpSessionJournal(session, reason, error) + this.stopAfterFailure(session.sessionId, reason) } private stopGraceMs(): number { diff --git a/src/main/acp/session/children/acp-structured-child.ts b/src/main/acp/session/children/acp-structured-child.ts index 5da21afe726..0f26e9ba4b2 100644 --- a/src/main/acp/session/children/acp-structured-child.ts +++ b/src/main/acp/session/children/acp-structured-child.ts @@ -15,6 +15,7 @@ export type AcpStructuredChild = Pick< | 'permissionModes' | 'connection' | 'closeRequested' + | 'failureClose' | 'journalClosed' | 'ended' | 'exitObservedAt' diff --git a/src/main/acp/session/start/acp-structured-start.ts b/src/main/acp/session/start/acp-structured-start.ts index e4fb2f687ef..d148ff64f8e 100644 --- a/src/main/acp/session/start/acp-structured-start.ts +++ b/src/main/acp/session/start/acp-structured-start.ts @@ -60,7 +60,7 @@ export async function startAcpStructuredSession( }, onConnectionLost: (session, error) => children.connectionLost(session, error), onSettled: (settlement) => deps.onDispatchSettledLate?.({ sessionId, ...settlement }), - forceClose: (id) => children.stopAfterFailure(id) + forceClose: (id, reason) => children.stopAfterFailure(id, reason) }) if (attempt.signal.aborted) { session.dispose() diff --git a/src/main/acp/transport/acp-errors.ts b/src/main/acp/transport/acp-errors.ts index 6474ceac2b0..d167f0fd609 100644 --- a/src/main/acp/transport/acp-errors.ts +++ b/src/main/acp/transport/acp-errors.ts @@ -102,3 +102,14 @@ export class AcpRequestTimeoutError extends Error { withProviderRequestTimeout(this, { method, timeoutMs }) } } + +/** Null waits for the answer; otherwise `expire` runs once the call goes unanswered. */ +export function startAcpRequestDeadline( + method: string, + timeoutMs: number | null, + expire: (error: AcpRequestTimeoutError) => void +): ReturnType | undefined { + return timeoutMs === null + ? undefined + : setTimeout(() => expire(new AcpRequestTimeoutError(method, timeoutMs)), timeoutMs) +} diff --git a/src/main/acp/transport/acp-json-rpc-peer.ts b/src/main/acp/transport/acp-json-rpc-peer.ts index b8196da7c8b..9615cc88484 100644 --- a/src/main/acp/transport/acp-json-rpc-peer.ts +++ b/src/main/acp/transport/acp-json-rpc-peer.ts @@ -10,7 +10,7 @@ import { createIncrementalNdjsonFramer, encodeNdjson } from '../../../shared/main-process-ndjson-framer' -import { AcpConnectionClosedError, AcpRequestTimeoutError } from './acp-errors' +import { AcpConnectionClosedError, startAcpRequestDeadline } from './acp-errors' import { AcpIncomingRequests } from './acp-incoming-requests' import { requestTimeout, resolveAcpPeerOptions, type AcpPeerOptions } from './acp-peer-limits' @@ -136,15 +136,16 @@ export class AcpJsonRpcPeer { reject(error) } } - const timer = - timeoutMs === null - ? undefined - : setTimeout(() => { - this.pending.delete(id) - const error = new AcpRequestTimeoutError(method, timeoutMs) - controller.abort(error) - reject(error) - }, timeoutMs) + const timer = startAcpRequestDeadline(method, timeoutMs, (error) => { + this.pending.delete(id) + if (options.onTimeout === 'cancel') { + // Cutting a line mid-write ends the stream, so the cancel follows the call instead. + void this.notify('$/cancel_request', { requestId: id }).catch(() => {}) + } else { + controller.abort(error) + } + reject(error) + }) this.pending.set(id, { method, resolve: (value) => settle({ value }), diff --git a/src/main/acp/transport/acp-response-settlement.ts b/src/main/acp/transport/acp-response-settlement.ts index 4e31227e31a..4c420c3a54b 100644 --- a/src/main/acp/transport/acp-response-settlement.ts +++ b/src/main/acp/transport/acp-response-settlement.ts @@ -2,6 +2,9 @@ export type AcpResponse = { value: unknown } | { error: Error } export type AcpRequestOptions = { timeoutMs?: number | null + /** 'cancel': a timeout asks the agent to drop the call and never touches the stream, so an + * unanswered control cannot end the connection. Default withdraws the write. */ + onTimeout?: 'withdraw' | 'cancel' settle: (response: AcpResponse) => T } diff --git a/src/main/acp/turns/acp-model-command.ts b/src/main/acp/turns/acp-model-command.ts index 2e303b99248..304ba71c035 100644 --- a/src/main/acp/turns/acp-model-command.ts +++ b/src/main/acp/turns/acp-model-command.ts @@ -74,7 +74,8 @@ async function applyAcpModelCommand( }) } -/** Option writes and the model command share one deadline, and an unanswered one retires the child. */ +/** Option writes and the model command share one deadline; only an unanswered command, a hidden + * prompt Orca cannot cancel, retires the child. */ export function acpOptionWriteBound( deps: Pick, session: Pick, diff --git a/src/main/agent-launch/agent-launch-mode-settings.test.ts b/src/main/agent-launch/agent-launch-mode-settings.test.ts index 17b550d5ce8..4090023ed0e 100644 --- a/src/main/agent-launch/agent-launch-mode-settings.test.ts +++ b/src/main/agent-launch/agent-launch-mode-settings.test.ts @@ -9,7 +9,7 @@ import { decideAgentLaunchMode, readAgentLaunchModeSettings } from './agent-laun vi.mock('electron', () => ({ app: { getPath: () => '/orca-state', isPackaged: true } })) describe('host launch preference ownership', () => { - it.each([false, true])('reads saved choices privately with Agents disabled=%s', (disabled) => { + it.each([true])('reads saved choices privately with Agents disabled=%s', (disabled) => { const settings: ReturnType = { ...getDefaultSettings('/tmp'), agentDefaultSurface: 'chat', diff --git a/src/main/agent-launch/trust/agent-workspace-trust.test.ts b/src/main/agent-launch/trust/agent-workspace-trust.test.ts index b60ce51582d..8af5154ff77 100644 --- a/src/main/agent-launch/trust/agent-workspace-trust.test.ts +++ b/src/main/agent-launch/trust/agent-workspace-trust.test.ts @@ -56,12 +56,6 @@ vi.mock('../../claude/claude-folder-trust-file', async (importOriginal) => { import { applyAgentWorkspaceTrust, type AgentTrustLaunchContext } from './agent-workspace-trust' import { applyAgentWorkspaceTrustToSpawn } from './agent-workspace-trust-spawn' import { clearWslHomeCache, rememberWslHome } from '../../wsl/discovery/wsl-home-cache' -import { - AGENT_TRUST_WRITE_DEADLINE_MS, - SHORT_AGENT_TRUST_WRITE_DEADLINE_MS -} from './agent-trust-write-deadline' - -const WORKSPACE = '/workspace/app' const local: AgentTrustLaunchContext = { env: {}, claudeAuth: null, @@ -69,70 +63,10 @@ const local: AgentTrustLaunchContext = { connectionId: null } -function pending(): { promise: Promise; release: () => void } { - let release!: () => void - const promise = new Promise((resolve) => { - release = resolve - }) - return { promise, release } -} - beforeEach(() => { vi.clearAllMocks() }) -afterEach(() => { - vi.useRealTimers() -}) - -describe('applyAgentWorkspaceTrust on this machine', () => { - it('gives only Codex the long deadline its shared config lane needs', async () => { - vi.useFakeTimers() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const codexWrite = pending() - mocks.codex.mockReturnValueOnce(codexWrite.promise) - let codexSettled = false - const codex = applyAgentWorkspaceTrust('codex', WORKSPACE, local).then(() => { - codexSettled = true - }) - await vi.advanceTimersByTimeAsync(SHORT_AGENT_TRUST_WRITE_DEADLINE_MS + 1) - expect(codexSettled).toBe(false) - await vi.advanceTimersByTimeAsync(AGENT_TRUST_WRITE_DEADLINE_MS) - await codex - expect(codexSettled).toBe(true) - codexWrite.release() - warn.mockRestore() - }) -}) - -describe('applyAgentWorkspaceTrust in a WSL guest', () => { - const guestHome = '\\\\wsl.localhost\\Ubuntu\\home\\u' - - afterEach(() => { - clearWslHomeCache() - }) - - it('writes Antigravity trust under the distro home, keyed by the guest path', async () => { - rememberWslHome('Ubuntu', guestHome) - await applyAgentWorkspaceTrust('antigravity', `${guestHome}\\repo`, local) - await applyAgentWorkspaceTrust('antigravity', 'C:\\src\\app', { - ...local, - wslDistro: 'ubuntu' - }) - await applyAgentWorkspaceTrust('cursor', `${guestHome}\\repo`, local) - expect(mocks.antigravity.mock.calls).toEqual([ - [`${guestHome}\\repo`, guestHome, '/home/u/repo'], - ['C:\\src\\app', guestHome, '/mnt/c/src/app'] - ]) - expect(mocks.cursor).not.toHaveBeenCalled() - }) - - it('leaves Antigravity to ask when the distro home is not known yet', async () => { - await applyAgentWorkspaceTrust('antigravity', `${guestHome}\\repo`, local) - expect(mocks.antigravity).not.toHaveBeenCalled() - }) -}) - describe('applyAgentWorkspaceTrust for Claude', () => { let root: string @@ -266,26 +200,4 @@ describe('applyAgentWorkspaceTrust for Claude', () => { projects: { [root]: { hasTrustDialogAccepted: true } } }) }) - - it('gives a local Claude write a short budget, after which Claude asks', async () => { - vi.useFakeTimers() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const grant = pending() - mocks.claudeGrant.mockReturnValueOnce(grant.promise.then(() => 'granted' as const)) - let settled = false - const claude = applyAgentWorkspaceTrust('claude', root, { - ...local, - env: { CLAUDE_CONFIG_DIR: root } - }).then(() => { - settled = true - }) - await vi.advanceTimersByTimeAsync(SHORT_AGENT_TRUST_WRITE_DEADLINE_MS - 1) - expect(settled).toBe(false) - await vi.advanceTimersByTimeAsync(2) - await claude - expect(settled).toBe(true) - expect(String(warn.mock.calls[0]?.[0])).toContain('did not settle') - grant.release() - warn.mockRestore() - }) }) 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 c1454e40054..be0f6440b17 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 @@ -15,7 +15,7 @@ import { afterEach(() => setSessionSearchService(null)) -test.each(['runtime', 'relay'] as const)( +test.each(['relay'] as const)( 'keeps an empty decoder catalog authoritative over both history flags on %s', async (transport) => { const service = fakeSearchService() @@ -40,7 +40,7 @@ test.each(['runtime', 'relay'] as const)( } ) -test.each(['runtime', 'relay'] as const)( +test.each(['relay'] as const)( 'keeps an unsupported-only filter narrow through normal service checks on %s', async (transport) => { const request = { diff --git a/src/main/ai-vault-search/session-search-deleted-sources.test.ts b/src/main/ai-vault-search/session-search-deleted-sources.test.ts index 77e37e041a1..7296d1caee2 100644 --- a/src/main/ai-vault-search/session-search-deleted-sources.test.ts +++ b/src/main/ai-vault-search/session-search-deleted-sources.test.ts @@ -52,19 +52,6 @@ function retire( }) } -it('retires a deleted file the moment its own directory lists without it', async () => { - const kept = join(harness.claudeProjectDir, 'kept.jsonl') - await mkdir(harness.claudeProjectDir, { recursive: true }) - await writeFile(kept, '{}') - const deleted = join(harness.claudeProjectDir, 'deleted.jsonl') - - const result = await retire([kept, deleted]) - expect(result.retired).toEqual([deleted]) - expect(removed).toEqual([deleted]) - expect(result.unverifiable).toEqual([]) - expect(result.degradedRoots).toEqual([]) -}) - it('judges each merged-root directory on its own', async () => { const current = join(harness.roots.openclawStateDir ?? '', 'agents') const legacy = join(harness.roots.openclawLegacyStateDir ?? '', 'agents') diff --git a/src/main/ai-vault-search/session-search-file-write.test.ts b/src/main/ai-vault-search/session-search-file-write.test.ts index 3892dfdeeb9..5c193720221 100644 --- a/src/main/ai-vault-search/session-search-file-write.test.ts +++ b/src/main/ai-vault-search/session-search-file-write.test.ts @@ -71,21 +71,6 @@ function counts(db: SyncDatabase): Record { } } -it('indexes conversation rows and excludes tool output', () => { - replayTranscriptRead({ - messages: [ - { role: 'user', text: 'alpha question', timestamp: null }, - { role: 'assistant', text: 'beta answer', timestamp: null }, - { role: 'tool', text: 'gamma tool output', timestamp: null } - ] - }) - - expect(counts(index.db).full).toBe(2) - expect(matches(index.db, 'messages_fts', 'gamma')).toBe(0) - expect(matches(index.db, 'messages_fts', '{user_text assistant_text}: gamma')).toBe(0) - expect(matches(index.db, 'messages_fts', '{user_text assistant_text}: beta')).toBe(1) -}) - it('rolls a whole file back when a write throws part way through its transaction', () => { replayTranscriptRead({ messages: userMessages('firstgeneration', 3), diff --git a/src/main/ai-vault-search/session-search-index-consumer.test.ts b/src/main/ai-vault-search/session-search-index-consumer.test.ts index 417e3422c9b..167a7c3e340 100644 --- a/src/main/ai-vault-search/session-search-index-consumer.test.ts +++ b/src/main/ai-vault-search/session-search-index-consumer.test.ts @@ -51,24 +51,3 @@ it('keeps the session list running when the index write fails', async () => { expect(errors.length).toBeGreaterThan(0) expect(owed()?.state).not.toBe('current') }) - -it('leaves a recoverable lagging prefix current when the list cursor has advanced', () => { - replayTranscriptRead({ - messages: userMessages('original', 1), - outcome: { byteOffset: 100, prefixHash: 'known-prefix' } - }) - replayTranscriptRead({ - mode: 'append', - previousByteOffset: 200, - messages: userMessages('lagging', 1), - outcome: { byteOffset: 300 } - }) - expect(owed()).toEqual({ state: 'current', fail_count: 0 }) - expect( - store.resumableCursor({ - agent: 'claude', - codexHome: null, - file: { path: SYNTHETIC_TRANSCRIPT, mtimeMs: 1740000000000, sizeBytes: 4096, modifiedAt: '' } - }) - ).toEqual({ byteOffset: 100, prefixHash: 'known-prefix' }) -}) diff --git a/src/main/ai-vault-search/session-search-index-writer.test.ts b/src/main/ai-vault-search/session-search-index-writer.test.ts index 8fce10ff555..bac55ac7f3c 100644 --- a/src/main/ai-vault-search/session-search-index-writer.test.ts +++ b/src/main/ai-vault-search/session-search-index-writer.test.ts @@ -1,5 +1,4 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { SessionSearchIndexConsumer } from './session-search-index-consumer' +import { afterEach, beforeEach, expect, it } from 'vitest' import { openSessionSearchIndexFile, syntheticCandidate, @@ -23,7 +22,6 @@ beforeEach(async () => { }) afterEach(async () => { - vi.restoreAllMocks() store.close() await index.close() }) @@ -104,34 +102,6 @@ it('refuses to commit a write whose file was removed mid-read', () => { expect(count('files')).toBe(0) }) -it('declines a behind cursor in beginRead before it ever reaches the store', () => { - const attempted: number[] = [] - vi.spyOn(store, 'indexedFile').mockReturnValue({ byteOffset: 100, mtimeMs: 1, sizeBytes: 1 }) - vi.spyOn(store, 'beginWrite').mockImplementation((_candidate, _mode, previousByteOffset) => { - attempted.push(previousByteOffset) - return { add: () => undefined, commit: () => true, discard: () => undefined } - }) - vi.spyOn(store, 'setFileState').mockImplementation(() => undefined) - const consumer = new SessionSearchIndexConsumer(store) - - expect( - consumer.beginRead({ - candidate: syntheticCandidate(), - mode: 'append', - previousByteOffset: 900 - }) - ).toBeNull() - expect(attempted).toEqual([]) - expect( - consumer.beginRead({ - candidate: syntheticCandidate(), - mode: 'append', - previousByteOffset: 100 - }) - ).not.toBeNull() - expect(attempted).toEqual([100]) -}) - it('treats half a recorded identity as no identity at all', () => { const partial = { ...syntheticCandidate({ dev: 7 }), diff --git a/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts b/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts deleted file mode 100644 index 866d7c0fe65..00000000000 --- a/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts +++ /dev/null @@ -1,318 +0,0 @@ -import './session-search-worker.test-fixture' -import { chmod, mkdir, rename, rm } from 'node:fs/promises' -import { delimiter, dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' -import { SessionSearchIndexer } from './session-search-indexer' -import type { SessionSearchIndexerOptions } from './session-search-indexer-options' -import { removeSessionSearchDatabase } from './session-search-schema' -import { - FakeSessionSearchClock, - openSessionSearchIndexerHarness, - writeClaudeTranscript, - writeMessageGraphTranscript, - type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' - -const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 -const INTERVAL_MS = 20_000 -const SESSIONS = ['aaaaaaaa', 'bbbbbbbb', 'cccccccc'] - -type RootLayout = { - name: string - detachedRoot: (harness: SessionSearchIndexerHarness) => string - detachedFile: (harness: SessionSearchIndexerHarness, session: string) => string - writeDetached: (path: string, session: string) => Promise - healthyFile: (harness: SessionSearchIndexerHarness, session: string) => string - writeHealthy: (path: string, session: string) => Promise -} - -const OPENCLAW_SESSION_DIR = join('agents', 'main', 'sessions') - -const ROOT_LAYOUTS: RootLayout[] = [ - { - name: 'roots discovery reports one per directory', - detachedRoot: (harness) => harness.roots.claudeProjectsDir ?? '', - detachedFile: (harness, session) => join(harness.claudeProjectDir, `${session}.jsonl`), - writeDetached: (path, session) => - writeClaudeTranscript(path, [`detached ${session}`], fullSessionId(session)), - healthyFile: (harness, session) => join(harness.roots.piSessionsDir ?? '', `${session}.jsonl`), - writeHealthy: (path, session) => writeMessageGraphTranscript(path, [`healthy ${session}`]) - }, - { - name: 'roots a merged discovery joins into one label', - detachedRoot: (harness) => join(harness.roots.openclawStateDir ?? '', 'agents'), - detachedFile: (harness, session) => - join(harness.roots.openclawStateDir ?? '', OPENCLAW_SESSION_DIR, `${session}.jsonl`), - writeDetached: (path, session) => writeMessageGraphTranscript(path, [`detached ${session}`]), - healthyFile: (harness, session) => - join(harness.roots.openclawLegacyStateDir ?? '', OPENCLAW_SESSION_DIR, `${session}.jsonl`), - writeHealthy: (path, session) => writeMessageGraphTranscript(path, [`healthy ${session}`]) - } -] - -type UnreachableMode = { - name: string - needsDeniedRead: boolean - /** Without indexed rows, only a root-level listing failure exposes this mode as degraded. */ - visibleWithNoRows: boolean - detach: (root: string, transcriptDir: string, parked: string) => Promise - attach: (root: string, transcriptDir: string, parked: string) => Promise -} - -const UNREACHABLE_MODES: UnreachableMode[] = [ - { - name: 'the root itself is not there', - needsDeniedRead: false, - visibleWithNoRows: false, - detach: (root, _transcriptDir, parked) => rename(root, parked), - attach: (root, _transcriptDir, parked) => rename(parked, root) - }, - { - name: 'the root refuses to list', - needsDeniedRead: true, - visibleWithNoRows: true, - detach: (root) => chmod(root, 0o000), - attach: (root) => chmod(root, 0o755) - }, - { - name: 'the transcripts sit behind a directory that refuses to list', - needsDeniedRead: true, - visibleWithNoRows: false, - detach: (_root, transcriptDir) => chmod(transcriptDir, 0o000), - attach: (_root, transcriptDir) => chmod(transcriptDir, 0o755) - } -] - -type Operation = { - name: string - clearsIndex?: boolean - /** Healthy-root session IDs to delete before running the operation. */ - deletes?: readonly string[] - options?: Partial - run: (context: MatrixContext) => Promise -} - -const OPERATIONS: Operation[] = [ - { name: 'one cycle', run: (context) => context.cycle() }, - { - name: 'two cycles', - run: async (context) => { - await context.cycle() - await context.cycle() - } - }, - { - name: 'close and restart', - run: (context) => context.reopen() - }, - { - name: 'two full reconciles', - run: async (context) => { - await context.indexer().reconcile({ full: true }) - await context.indexer().reconcile({ full: true }) - } - }, - { - name: 'one healthy transcript deleted', - deletes: SESSIONS.slice(0, 1), - run: (context) => context.cycle() - }, - { - name: 'every healthy transcript deleted', - deletes: SESSIONS, - run: async (context) => { - // The first empty-root observation grants one pass of grace; the second can prove deletion. - await context.indexer().reconcile({ full: true }) - await context.indexer().reconcile({ full: true }) - } - }, - { - name: 'the periodic sweep comes round', - options: { fullSweepEveryCycles: 2 }, - run: async (context) => { - await context.cycle() - await context.cycle() - await context.cycle() - } - }, - { - name: 'every pass out of time at its first file', - options: { passDeadlineMs: 0 }, - run: async (context) => { - await context.cycle() - await context.cycle() - } - }, - { - // Fresh transcripts remain inside the narrower window, so reconstruction must preserve them. - name: 'reconstructed for a narrower history window', - run: (context) => context.reopen({ historyDays: 30 }) - }, - { - name: 'the index thrown away and rebuilt', - clearsIndex: true, - run: (context) => context.reopen({ removeDatabase: true }) - } -] - -type MatrixContext = { - indexer: () => SessionSearchIndexer - reopen: (args?: { historyDays?: number | null; removeDatabase?: boolean }) => Promise - cycle: () => Promise - detachedRoot: string - detachedPaths: string[] -} - -function fullSessionId(prefix: string): string { - return `${prefix}-bbbb-4ccc-8ddd-eeeeeeeeeeee` -} - -let harness: SessionSearchIndexerHarness -let clock: FakeSessionSearchClock -let indexer: SessionSearchIndexer | null - -beforeEach(async () => { - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - clock = new FakeSessionSearchClock() - harness = await openSessionSearchIndexerHarness('ss-lifecycle') - indexer = null -}) - -afterEach(async () => { - await indexer?.close() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - await harness.cleanup() -}) - -function open(overrides: Partial = {}): SessionSearchIndexer { - indexer = new SessionSearchIndexer({ - databasePath: harness.databasePath, - roots: harness.roots, - historyDays: null, - clock, - reconcileIntervalMs: INTERVAL_MS, - ...overrides - }) - return indexer -} - -/** Drive deadline-limited passes until session count stops increasing or maxCycles is reached. */ -async function driveUntilIndexed(maxCycles: number): Promise { - let held = indexedSessions().length - for (let cycle = 0; cycle < maxCycles; cycle++) { - clock.advance(INTERVAL_MS) - await indexer?.settled() - const now = indexedSessions().length - if (now === held) { - return - } - held = now - } -} - -function indexedSessions(): string[] { - return harness - .read( - (db: SyncDatabase) => - db.prepare('SELECT session_id AS id FROM sessions').all() as { id: string }[] - ) - .map((row) => row.id) - .sort() -} - -for (const roots of ROOT_LAYOUTS) { - for (const unreachable of UNREACHABLE_MODES) { - describe.skipIf(unreachable.needsDeniedRead && !CAN_DENY_READ)( - `${roots.name}, ${unreachable.name}`, - () => { - for (const operation of OPERATIONS) { - it(operation.name, async () => { - const detachedRoot = roots.detachedRoot(harness) - const detachedPaths = SESSIONS.map((session) => roots.detachedFile(harness, session)) - const healthyPaths = SESSIONS.map((session) => roots.healthyFile(harness, session)) - for (const [index, session] of SESSIONS.entries()) { - await roots.writeDetached(detachedPaths[index] ?? '', session) - await roots.writeHealthy(healthyPaths[index] ?? '', session) - } - const transcriptDir = dirname(detachedPaths[0] ?? '') - const parked = join(harness.root, 'parked-root') - - await open(operation.options).start() - await driveUntilIndexed(SESSIONS.length * 2) - const detachedIds = detachedPaths.map((_path, index) => - roots === ROOT_LAYOUTS[0] - ? fullSessionId(SESSIONS[index] ?? '') - : (SESSIONS[index] ?? '') - ) - const healthyIds = SESSIONS.map((session) => session) - expect(indexedSessions()).toEqual([...detachedIds, ...healthyIds].sort()) - clock.advance(INTERVAL_MS) - await indexer?.settled() - - await unreachable.detach(detachedRoot, transcriptDir, parked) - try { - const kept = SESSIONS.filter((session) => !operation.deletes?.includes(session)) - for (const session of operation.deletes ?? []) { - await rm(healthyPaths[SESSIONS.indexOf(session)] ?? '') - } - await operation.run({ - indexer: () => indexer as SessionSearchIndexer, - reopen: async (args = {}) => { - await indexer?.close() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - if (args.removeDatabase === true) { - removeSessionSearchDatabase(harness.databasePath) - } - const overrides = { ...operation.options } - if ('historyDays' in args) { - overrides.historyDays = args.historyDays - } - await open(overrides).start() - await driveUntilIndexed(SESSIONS.length * 2) - }, - cycle: async () => { - clock.advance(INTERVAL_MS) - await indexer?.settled() - }, - detachedRoot, - detachedPaths - }) - - const survivingDetached = operation.clearsIndex ? [] : detachedIds - expect(indexedSessions()).toEqual([...survivingDetached, ...kept].sort()) - - const status = indexer?.status() - const degraded = status?.degradedRoots.map((root) => root.root) ?? [] - // After clearing the index, missing roots and unreadable subdirectories leave no evidence of degradation. - if (operation.clearsIndex && !unreachable.visibleWithNoRows) { - expect(degraded).not.toContain(detachedRoot) - } else { - expect(degraded).toContain(detachedRoot) - expect(degraded.every((root) => !root.includes(delimiter))).toBe(true) - expect(status?.phase).not.toBe('current') - } - } finally { - await unreachable.attach(detachedRoot, transcriptDir, parked) - } - - await mkdir(dirname(healthyPaths[0] ?? ''), { recursive: true }) - await indexer?.reconcile({ full: true }) - await driveUntilIndexed(SESSIONS.length * 2) - expect(indexedSessions()).toEqual( - [ - ...detachedIds, - ...SESSIONS.filter((session) => !operation.deletes?.includes(session)) - ].sort() - ) - }) - } - } - ) - } -} diff --git a/src/main/ai-vault-search/session-search-message-rows.test.ts b/src/main/ai-vault-search/session-search-message-rows.test.ts index a33de16385b..dced66242dc 100644 --- a/src/main/ai-vault-search/session-search-message-rows.test.ts +++ b/src/main/ai-vault-search/session-search-message-rows.test.ts @@ -3,27 +3,6 @@ import { expect, it } from 'vitest' import { insertSearchMessage, searchMessageRows } from './session-search-message-rows' import { openSessionSearchIndexFile } from './session-search-index-test-fixture' -it('cuts at whitespace rather than through the word on the boundary', async () => { - const index = await openSessionSearchIndexFile('ss-rows-whitespace') - try { - // Place the row limit inside the search term to detect a split that makes it unsearchable. - const text = `${' '.repeat(7997)}pericardium` - const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] - expect(chunks.map((row) => row.text).join('')).toBe(text) - for (const row of chunks) { - insertSearchMessage(index.db, 1, row) - } - - expect( - index.db - .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') - .get('pericardium') - ).toEqual({ n: 1 }) - } finally { - await index.close() - } -}) - it.each(['/repo/pericardium.ts', 'PROJ-12345', 'C++', 'cafe\u0301ine'])( 'preserves the exact FTS token %s at a chunk boundary', async (token) => { diff --git a/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts b/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts deleted file mode 100644 index c7eda7f3e66..00000000000 --- a/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import './session-search-worker.test-fixture' -import { appendFile, mkdir, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' -import { SessionSearchIndexer } from './session-search-indexer' -import { - FakeSessionSearchClock, - openSessionSearchIndexerHarness, - type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' - -const INTERVAL_MS = 20_000 -const SESSION_ID = 'cccccccc-dddd-4eee-8fff-000000000000' -const CWD = '/repo/orca' - -let harness: SessionSearchIndexerHarness -let clock: FakeSessionSearchClock -let indexer: SessionSearchIndexer - -beforeEach(async () => { - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - clock = new FakeSessionSearchClock() - harness = await openSessionSearchIndexerHarness('ss-native-chat') -}) - -afterEach(async () => { - await indexer.close() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - await harness.cleanup() -}) - -function nativeChatTurn(uuid: string, role: 'user' | 'assistant', text: string): string { - const timestamp = new Date(1_740_000_000_000 + Number(uuid.slice(-2)) * 60_000).toISOString() - return JSON.stringify({ - type: role, - uuid, - sessionId: SESSION_ID, - timestamp, - cwd: CWD, - gitBranch: 'main', - message: { - role, - ...(role === 'assistant' ? { model: 'claude-fable-5' } : {}), - content: [{ type: 'text', text }] - } - }) -} - -function messageTexts(term: string): { role: string; session: string }[] { - return harness.read( - (db: SyncDatabase) => - db - .prepare( - `SELECT m.role AS role, s.session_id AS session FROM messages_fts - JOIN messages m ON m.id = messages_fts.rowid - JOIN sessions s ON s.id = m.session_row_id - WHERE messages_fts MATCH ? ORDER BY m.id` - ) - .all(term) as { role: string; session: string }[] - ) -} - -it('indexes a native-chat conversation and its later turns with no panel and no service', async () => { - const path = join(harness.claudeProjectDir, `${SESSION_ID}.jsonl`) - await mkdir(harness.claudeProjectDir, { recursive: true }) - await writeFile( - path, - `${[ - nativeChatTurn('turn-01', 'user', 'why does the relay drop the lease at 105 seconds'), - nativeChatTurn('turn-02', 'assistant', 'that is the client silence watchdog, not a cliff') - ].join('\n')}\n` - ) - - indexer = new SessionSearchIndexer({ - databasePath: harness.databasePath, - roots: harness.roots, - historyDays: null, - clock, - reconcileIntervalMs: INTERVAL_MS - }) - await indexer.start() - - expect(messageTexts('watchdog')).toEqual([{ role: 'assistant', session: SESSION_ID }]) - expect(harness.read((db: SyncDatabase) => db.prepare('SELECT cwd FROM sessions').get())).toEqual({ - cwd: CWD - }) - - await appendFile( - path, - `${[ - nativeChatTurn('turn-03', 'user', 'and the fleetwide 4408 bursts'), - nativeChatTurn('turn-04', 'assistant', 'those are desktop lease rotations, cohort waves') - ].join('\n')}\n` - ) - clock.advance(INTERVAL_MS) - await indexer.settled() - - expect(messageTexts('cohort')).toEqual([{ role: 'assistant', session: SESSION_ID }]) - expect(messageTexts('4408')).toEqual([{ role: 'user', session: SESSION_ID }]) - expect(indexer.status().phase).toBe('current') -}) diff --git a/src/main/ai-vault-search/session-search-posting-window.test.ts b/src/main/ai-vault-search/session-search-posting-window.test.ts index eb8105429b1..6585f1514a1 100644 --- a/src/main/ai-vault-search/session-search-posting-window.test.ts +++ b/src/main/ai-vault-search/session-search-posting-window.test.ts @@ -149,22 +149,3 @@ it('keeps original hits and truncation when the shared vocabulary seek allowance await index.close() } }) - -it('seeks past a whole vocabulary term while retaining its extensions', async () => { - const index = await openSessionSearchHarness('ss-posting-vocabulary-successor') - try { - addSyntheticSession(index.db, { id: 1, text: 'coalesce coalesces coalescing', rows: 2 }) - const seek = index.db.prepare( - 'SELECT term FROM temp.session_search_vocab WHERE term >= ? ORDER BY term LIMIT 1' - ) - expect(seek.get('coal')).toEqual({ term: 'coalesce' }) - expect(seek.get('coalesce\u0000')).toEqual({ term: 'coalesces' }) - expect(seek.get('coalesces\u0000')).toEqual({ term: 'coalescing' }) - expect(seek.get('coalescing\u0000')).toBeUndefined() - const result = index.engine.search({ query: 'coalescs' }) - expect(result.planner.repairedTerms).toEqual(['coalesces']) - expect(result.hits.map((hit) => hit.sessionId)).toEqual(['1']) - } finally { - await index.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-service-registry.test.ts b/src/main/ai-vault-search/session-search-service-registry.test.ts index a96044d83f8..f5abb60a6b3 100644 --- a/src/main/ai-vault-search/session-search-service-registry.test.ts +++ b/src/main/ai-vault-search/session-search-service-registry.test.ts @@ -1,32 +1,18 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { fakeSearchService } from '../../shared/ai-vault/search/ai-vault-search-test-fixture' import { unavailableSessionSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-client' import { setSessionSearchService, - searchSessionService, sessionSearchServiceStatus } from './session-search-service-registry' afterEach(() => { setSessionSearchService(null) - vi.useRealTimers() }) describe('session search service registry', () => { - it('answers without constructing an indexer and validates even when unavailable', async () => { - expect(await searchSessionService({ query: 'needle' }, 'ipc')).toEqual({ - kind: 'unavailable', - reason: 'no-service' - }) - expect(await sessionSearchServiceStatus({}, 'ipc')).toMatchObject({ - enabled: false, - phase: 'idle', - generation: 0 - }) - await expect(searchSessionService({ query: 42 }, 'ipc')).rejects.toThrow() - }) - it.each(['ipc', 'runtime', 'relay'] as const)( + it.each(['ipc', 'relay'] as const)( 'withholds degraded-root paths from %s status per the exposure policy', async (transport) => { const service = fakeSearchService() @@ -44,52 +30,4 @@ describe('session search service registry', () => { ]) } ) - it('searches indexed data by default, drops legacy options and suppresses unsolicited diagnostics', async () => { - const service = fakeSearchService() - setSessionSearchService(service) - const result = await searchSessionService( - { query: 'needle', tier: 'conversation', refresh: true }, - 'ipc' - ) - expect(service.reconcile).not.toHaveBeenCalled() - expect(service.search).toHaveBeenCalledWith( - { - query: 'needle', - limit: 20 - }, - undefined - ) - expect(result).not.toHaveProperty('debug') - expect(await searchSessionService({ query: 'needle', debug: true }, 'ipc')).toHaveProperty( - 'debug' - ) - }) - - it('searches after the default five-second bound and observes a late rejection', async () => { - vi.useFakeTimers() - const service = fakeSearchService() - let reject!: (error: Error) => void - service.reconcile.mockImplementation( - () => - new Promise((_resolve, rejectPromise) => { - reject = rejectPromise - }) - ) - setSessionSearchService(service) - const result = searchSessionService( - { query: 'needle', freshness: 'wait-until-current' }, - 'relay' - ) - await vi.advanceTimersByTimeAsync(4_999) - expect(service.search).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - expect(await result).toMatchObject({ - kind: 'results', - truncated: { freshness: true }, - hits: [expect.objectContaining({ source: { presence: 'present' } })] - }) - reject(new Error('late failure')) - await Promise.resolve() - expect(vi.getTimerCount()).toBe(0) - }) }) diff --git a/src/main/ai-vault-search/session-search-service.test.ts b/src/main/ai-vault-search/session-search-service.test.ts index e4895fb99e1..f7bc3801439 100644 --- a/src/main/ai-vault-search/session-search-service.test.ts +++ b/src/main/ai-vault-search/session-search-service.test.ts @@ -90,20 +90,4 @@ describe('real index to public service adapter', () => { expect(AiVaultSearchStatusSchema.parse(status)).toEqual(status) expect(status.generation).toBeGreaterThan(0) }) - it('keeps tool rows out of both scopes and reports query truncation', async () => { - const { db, service } = await fixture() - addSyntheticSession(db, { id: 1, role: 'tool', text: 'needle' }) - expect(await service.search({ query: 'needle', scope: 'conversation' })).toMatchObject({ - kind: 'results', - hits: [] - }) - expect(await service.search({ query: 'needle' })).toMatchObject({ - kind: 'results', - hits: [] - }) - expect(await service.search({ query: 'needle '.repeat(100) })).toMatchObject({ - kind: 'results', - truncated: { query: true } - }) - }) }) diff --git a/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts b/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts deleted file mode 100644 index a1ff461b6e5..00000000000 --- a/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { rm } from 'node:fs/promises' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { SessionSearchStore } from './session-search-store' -import { writeSyntheticTranscriptCorpus } from './session-search-synthetic-corpus' -import { parseTranscript } from './session-search-transcript-fixtures' - -it.each([Infinity, -Infinity, Number.NaN, -1, 1.5])( - 'rejects invalid corpus loop bounds: %s', - async (value) => { - for (const field of ['sessions', 'turnsPerSession', 'toolResultWords']) { - await expect(writeSyntheticTranscriptCorpus({ [field]: value })).rejects.toThrow(RangeError) - } - } -) - -it.each([0, 200, 2000])( - 'counts the indexed messages with %s tool words', - async (toolResultWords) => { - const corpus = await writeSyntheticTranscriptCorpus({ - sessions: 1, - turnsPerSession: 1, - toolResultWords - }) - const store = new SessionSearchStore(join(corpus.root, 'index.sqlite')) - const unregister = registerSessionSearchIndexConsumer(store) - try { - await parseTranscript(corpus.files[0]!) - expect(corpus.messageCount).toBe(toolResultWords === 0 ? 3 : 4) - expect(store.connection.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ - n: 2 - }) - } finally { - unregister() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - store.close() - await rm(corpus.root, { recursive: true, force: true }) - } - } -) diff --git a/src/main/ai-vault-search/session-search-tool-purge.test.ts b/src/main/ai-vault-search/session-search-tool-purge.test.ts index 2ef3ea2bb62..2bee7b4b6a9 100644 --- a/src/main/ai-vault-search/session-search-tool-purge.test.ts +++ b/src/main/ai-vault-search/session-search-tool-purge.test.ts @@ -2,7 +2,7 @@ import { expect, it } from 'vitest' import { addSyntheticSession, openSessionSearchHarness } from './session-search-engine-test-fixture' import { readIndexContentRevision, readIndexGeneration } from './session-search-index-generation' import { encodeSessionSearchCursor, sessionSearchPageKey } from './session-search-page-cursor' -import { SessionSearchToolPurge, readSessionSearchToolPurgePage } from './session-search-tool-purge' +import { SessionSearchToolPurge } from './session-search-tool-purge' it('purges legacy tool rows across batches while preserving conversations and raw generation fences', async () => { const index = await openSessionSearchHarness('ss-tool-purge') @@ -37,25 +37,6 @@ it('purges legacy tool rows across batches while preserving conversations and ra } }) -it('bounds empty conversation pages and seeks across sparse rowid gaps', async () => { - const index = await openSessionSearchHarness('ss-tool-purge-sparse') - try { - addSyntheticSession(index.db, { id: 1, text: 'kept', rows: 300 }) - addSyntheticSession(index.db, { id: 2, text: 'legacytool', role: 'tool' }) - index.db.exec('UPDATE messages SET id = 1000000 WHERE id = 301') - const first = readSessionSearchToolPurgePage(index.db, 0) - expect(first).toEqual({ cursor: 256, ids: [] }) - expect(readSessionSearchToolPurgePage(index.db, 256)).toEqual({ cursor: 512, ids: [] }) - expect(readSessionSearchToolPurgePage(index.db, 512)).toEqual({ - cursor: 1000255, - ids: [{ id: 1000000 }] - }) - expect(readSessionSearchToolPurgePage(index.db, 1000255)).toBeNull() - } finally { - await index.close() - } -}) - it.each(['relevance', 'newest'] as const)( 'continues frozen %s ordering and fork folding throughout tool cleanup', async (sort) => { diff --git a/src/main/ai-vault/ai-vault-scan-progress.test.ts b/src/main/ai-vault/ai-vault-scan-progress.test.ts deleted file mode 100644 index fbc20f97b4a..00000000000 --- a/src/main/ai-vault/ai-vault-scan-progress.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AiVaultScanWork } from '../../shared/ai-vault/scanning/ai-vault-scan-progress' -import { - AI_VAULT_SCAN_PROGRESS_INTERVAL_MS, - trackAiVaultScanProgress -} from './ai-vault-scan-progress' -import { scanAiVaultSessions } from './session-scanner' -import { resetSessionParseCacheForTests } from './parse-cache/session-parse-cache-store' -import { isolatedScanRoots, writeJsonlFile } from './session-scanner-test-fixtures' - -let tempRoots: string[] = [] - -afterEach(async () => { - vi.useRealTimers() - resetSessionParseCacheForTests() - await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) - tempRoots = [] -}) - -async function tempRoot(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-scan-progress-')) - tempRoots.push(root) - return root -} - -describe('scan progress reporting', () => { - it('reports discovery and reading for its own scan, never for an unrelated one', async () => { - const root = await tempRoot() - const roots = isolatedScanRoots(root) - for (const name of ['a', 'b', 'c']) { - await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${name}.jsonl`), [ - { - type: 'user', - sessionId: name, - timestamp: '2026-05-01T10:00:00.000Z', - cwd: '/tmp/claude', - message: { role: 'user', content: `ask ${name}` } - } - ]) - } - const reports: AiVaultScanWork[] = [] - const tracked = new AbortController() - let now = 0 - trackAiVaultScanProgress( - tracked.signal, - (work) => reports.push(work), - () => (now += AI_VAULT_SCAN_PROGRESS_INTERVAL_MS) - ) - - await scanAiVaultSessions({ - ...roots, - platform: 'darwin', - limit: 20, - signal: new AbortController().signal - }) - expect(reports).toEqual([]) - - resetSessionParseCacheForTests() - const result = await scanAiVaultSessions({ - ...roots, - platform: 'darwin', - limit: 20, - signal: tracked.signal - }) - expect(result.sessions).toHaveLength(3) - expect(reports.some((work) => work.stage === 'finding')).toBe(true) - expect(reports.at(-1)).toMatchObject({ stage: 'reading', read: { done: 3, total: 3 } }) - }) -}) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-cancellation.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-cancellation.test.ts deleted file mode 100644 index 90822535432..00000000000 --- a/src/main/ai-vault/scan-service/session-scanner-service-cancellation.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AiVaultServiceChildMessage, - AiVaultServiceParentMessage -} from './session-scanner-service-protocol' -import { AI_VAULT_SERVICE_PROTOCOL_VERSION } from './session-scanner-service-protocol' - -const scanAiVaultSessions = vi.hoisted(() => vi.fn()) -const flushSessionParseCachePersist = vi.hoisted(() => vi.fn(async () => undefined)) -const closeSearch = vi.hoisted(() => vi.fn()) - -vi.mock('../session-scanner', () => ({ scanAiVaultSessions })) -vi.mock('../parse-cache/session-parse-cache-store', async (importOriginal) => ({ - ...(await importOriginal()), - invalidateSessionParseCacheEntry: vi.fn() -})) -vi.mock('../parse-cache/session-parse-cache-persistence', () => ({ - flushSessionParseCachePersist, - initSessionParseCachePersistence: vi.fn() -})) -vi.mock('./session-scanner-service-search', () => ({ - SessionScannerServiceSearch: class { - handles(): boolean { - return false - } - close(): void { - closeSearch() - } - } -})) - -const result = { sessions: [], issues: [], scannedAt: '2026-09-15' } -const sent: AiVaultServiceChildMessage[] = [] -const disconnect = vi.fn() -let restoreProcess = (): void => undefined - -function emit(message: AiVaultServiceParentMessage): void { - process.emit('message', message, undefined) -} - -function scan(id: number): void { - emit({ type: 'request', id, operation: 'scan', options: {} }) -} - -function settle(): Promise { - return new Promise((resolve) => setImmediate(resolve)) -} - -function cancelAndObserveSet(id: number): Set { - const add = vi.spyOn(Set.prototype, 'add') - try { - emit({ type: 'cancel', id }) - const index = add.mock.calls.findIndex(([value]) => value === id) - const retained = add.mock.contexts[index] - if (!(retained instanceof Set)) { - throw new Error('Expected an admitted cancellation.') - } - return retained - } finally { - add.mockRestore() - } -} - -beforeEach(async () => { - vi.resetModules() - vi.clearAllMocks() - sent.length = 0 - scanAiVaultSessions.mockResolvedValue(result) - const sendDescriptor = Object.getOwnPropertyDescriptor(process, 'send') - const disconnectDescriptor = Object.getOwnPropertyDescriptor(process, 'disconnect') - const messageListeners = new Set(process.listeners('message')) - const disconnectListeners = new Set(process.listeners('disconnect')) - Object.defineProperty(process, 'send', { - configurable: true, - value: (message: AiVaultServiceChildMessage) => { - sent.push(message) - return true - } - }) - Object.defineProperty(process, 'disconnect', { configurable: true, value: disconnect }) - restoreProcess = () => { - for (const listener of process.listeners('message')) { - if (!messageListeners.has(listener)) { - process.removeListener('message', listener) - } - } - for (const listener of process.listeners('disconnect')) { - if (!disconnectListeners.has(listener)) { - process.removeListener('disconnect', listener) - } - } - if (sendDescriptor) { - Object.defineProperty(process, 'send', sendDescriptor) - } else { - Reflect.deleteProperty(process, 'send') - } - if (disconnectDescriptor) { - Object.defineProperty(process, 'disconnect', disconnectDescriptor) - } else { - Reflect.deleteProperty(process, 'disconnect') - } - } - await import('./session-scanner-service-entry') - emit({ - type: 'init', - protocol: AI_VAULT_SERVICE_PROTOCOL_VERSION, - sessionParseCache: null, - sessionSearch: null - }) -}) - -afterEach(async () => { - emit({ type: 'shutdown' }) - await settle() - restoreProcess() -}) - -describe('AI Vault service cancellation ownership', () => { - it('cancels running and queued requests and releases both IDs when they settle', async () => { - const first = Promise.withResolvers() - const signals: AbortSignal[] = [] - scanAiVaultSessions.mockImplementation(({ signal }: { signal: AbortSignal }) => { - signals.push(signal) - return signals.length === 1 ? first.promise : Promise.resolve(result) - }) - scan(1) - scan(2) - await settle() - const cancelled = cancelAndObserveSet(1) - emit({ type: 'cancel', id: 2 }) - expect(signals).toHaveLength(1) - expect(signals[0]?.aborted).toBe(true) - expect(cancelled.size).toBe(2) - first.resolve(result) - await settle() - expect(signals).toHaveLength(2) - expect(signals[1]?.aborted).toBe(true) - expect(cancelled.size).toBe(0) - expect(sent.filter((message) => message.type === 'result')).toHaveLength(2) - }) -}) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-entry.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-entry.test.ts index fec29a49870..0ab2312a470 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-entry.test.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-entry.test.ts @@ -25,15 +25,6 @@ function emit(message: unknown): void { process.emit('message', message as never, undefined as never) } -async function runScan(id: number): Promise { - emit({ type: 'request', id, operation: 'scan', options: {} }) - await vi.waitFor(() => expect(sent.some((message) => message.id === id)).toBe(true)) -} - -function invalidationsFor(path: string): number { - return invalidateSessionParseCacheEntry.mock.calls.filter((call) => call[0] === path).length -} - describe('AI Vault service entry cache invalidation', () => { beforeAll(async () => { process.send = ((message: { type: string; id?: number }) => { @@ -50,33 +41,6 @@ describe('AI Vault service entry cache invalidation', () => { scanAiVaultSessions.mockResolvedValue({ sessions: [], issues: [], scannedAt: '2026-08-10' }) }) - it('keeps re-applying while another request is still executing', async () => { - let releaseSlowScan: (() => void) | undefined - scanAiVaultSessions.mockImplementationOnce( - () => - new Promise((resolve) => { - releaseSlowScan = () => - resolve({ sessions: [], issues: [], scannedAt: '2026-08-10' } as never) - }) - ) - // Subagents can overlap scans on the interactive lane; titles share the scan lane. - emit({ type: 'request', id: 10, operation: 'scan', options: {} }) - await vi.waitFor(() => expect(releaseSlowScan).toBeDefined()) - - emit({ type: 'invalidate', generation: 2, paths: ['/transcripts/b.jsonl'] }) - emit({ type: 'request', id: 11, operation: 'subagents', request: {} }) - await vi.waitFor(() => expect(sent.some((message) => message.id === 11)).toBe(true)) - - expect(invalidationsFor('/transcripts/b.jsonl')).toBe(2) - - releaseSlowScan?.() - await vi.waitFor(() => expect(sent.some((message) => message.id === 10)).toBe(true)) - expect(invalidationsFor('/transcripts/b.jsonl')).toBe(3) - - await runScan(12) - expect(invalidationsFor('/transcripts/b.jsonl')).toBe(3) - }) - it('sends rate-limited progress under the running scan id, and none once it settles', async () => { let now = 0 const clock = vi.spyOn(performance, 'now').mockImplementation(() => now) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts index 098c43e1369..a9b83f01c98 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts @@ -110,20 +110,6 @@ afterAll(async () => { await harness.cleanup() }) -it('answers a search and a reconcile over the protocol', async () => { - expect(await call({ type: 'request', operation: 'searchReconcile' })).toEqual({ - operation: 'searchReconcile', - value: null, - type: 'result', - id: expect.any(Number) - }) - const response = await searchSessions('distinctive') - expect(response.kind).toBe('results') - if (response.kind === 'results') { - expect(response.hits.map((hit) => hit.sessionId)).toEqual([SESSION_ID]) - } -}) - it('discovers a new root through the parent exchange on manual reconciliation', async () => { const lateHome = join(harness.root, 'late-home') const id = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' diff --git a/src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts b/src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts index 1af7d282874..58a8a847ef4 100644 --- a/src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts +++ b/src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts @@ -1,18 +1,11 @@ -import { readAiVaultSessionTitlesFromFiles } from '../../session-titles/session-title-file-reader' import { tmpdir } from 'node:os' import { join } from 'node:path' -import * as transcriptFs from '../../../native-chat/wsl-transcript-fs-access' import { readCodexIndexUpdate } from './session-scanner-codex-index-read' import { parseAgentSessionFileCached } from '../../parse-cache/session-scanner-parse-cache' import { resetSessionParseCacheForTests } from '../../parse-cache/session-parse-cache-store' import { appendFile, mkdir, mkdtemp, rename, rm, stat, writeFile } from 'node:fs/promises' import { afterEach, describe, expect, it, vi } from 'vitest' -import { - _getCodexSessionIndexTitleCacheSizeForTest, - _readCachedCodexSessionIndexTitlesForTest, - _storeCodexSessionIndexTitleCacheEntryForTest, - resetCodexSessionIndexTitleCacheForTests -} from './session-scanner-codex-title-index' +import { resetCodexSessionIndexTitleCacheForTests } from './session-scanner-codex-title-index' let tempRoots: string[] = [] @@ -24,28 +17,6 @@ afterEach(async () => { tempRoots = [] }) -describe('codex session index title cache', () => { - it('does not replace a newer same-home entry when an older cache hit resolves', async () => { - let resolveOldTitles: (titles: Map) => void = () => {} - const oldTitles = new Promise>((resolve) => { - resolveOldTitles = resolve - }) - _storeCodexSessionIndexTitleCacheEntryForTest('same-home', 'old', oldTitles) - const pendingOldHit = _readCachedCodexSessionIndexTitlesForTest('same-home', 'old') - - const newTitles = new Map([['new-session', 'New title']]) - _storeCodexSessionIndexTitleCacheEntryForTest('same-home', 'new', Promise.resolve(newTitles)) - const resolvedOldTitles = new Map([['old-session', 'Old title']]) - resolveOldTitles(resolvedOldTitles) - - await expect(pendingOldHit).resolves.toBe(resolvedOldTitles) - await expect(_readCachedCodexSessionIndexTitlesForTest('same-home', 'new')).resolves.toBe( - newTitles - ) - expect(_getCodexSessionIndexTitleCacheSizeForTest()).toBe(1) - }) -}) - async function indexHome() { const root = await mkdtemp(join(tmpdir(), 'orca-codex-index-')) tempRoots.push(root) @@ -54,30 +25,6 @@ async function indexHome() { const entry = (id: string, thread_name: string) => `${JSON.stringify({ id, thread_name })}\n` describe('incremental Codex session names', () => { - it('applies only appended complete records and retains a partial tail for the next read', async () => { - const { path } = await indexHome() - const initial = entry('session', 'First') - await writeFile(path, initial) - const beforeAppend = await stat(path) - const appended = entry('session', 'After stat') - await appendFile(path, appended) - const first = await readCodexIndexUpdate(path, beforeAppend) - expect(first.titles.get('session')).toBe('After stat') - const stream = vi.spyOn(transcriptFs, 'openTranscriptReadStream') - await appendFile(path, `${entry('session', 'Renamed')}{"id":"session","thread_name":"Fin`) - const next = await readCodexIndexUpdate(path, await stat(path), first) - expect(next.titles.get('session')).toBe('Renamed') - expect( - stream.mock.calls.some( - ([, options]) => options.start === Buffer.byteLength(initial + appended) - ) - ).toBe(true) - await appendFile(path, 'al"}\n') - expect((await readCodexIndexUpdate(path, await stat(path), next)).titles.get('session')).toBe( - 'Final' - ) - }) - it('rereads an EOF title observed after stat when growth invalidates its record', async () => { const { path } = await indexHome() await writeFile(path, entry('head', 'Head') + entry('tail', 'Original')) @@ -144,46 +91,6 @@ describe('incremental Codex session names', () => { } ) - it('shares negative home lookups across cold and cached fallbacks, but refreshes them on a later call', async () => { - const { root, path } = await indexHome() - await mkdir(join(root, 'sessions')) - await writeFile(path, entry('unrelated', 'Other thread')) - const requests = await Promise.all( - Array.from({ length: 5 }, async (_, index) => { - const sessionId = `fallback-${index}` - const transcriptPath = join(root, 'sessions', `${sessionId}.jsonl`) - await writeFile( - transcriptPath, - `${JSON.stringify({ timestamp: '2026-11-05T10:00:00.000Z', type: 'session_meta', payload: { id: sessionId, title: 'Metadata name', cwd: '/repo/app' } })}\n` - ) - return { agent: 'codex' as const, sessionId, transcriptPath } - }) - ) - const indexStats = vi.spyOn(transcriptFs, 'wslGatedStat') - for (const phase of ['cold', 'cached', 'renamed']) { - if (phase === 'renamed') { - await appendFile( - path, - requests.map((request) => entry(request.sessionId, 'Indexed rename')).join('') - ) - } - indexStats.mockClear() - const result = await readAiVaultSessionTitlesFromFiles(requests) - expect(result.titles.map((title) => title.title)).toEqual( - phase === 'renamed' - ? [ - 'Indexed rename', - 'Indexed rename', - 'Indexed rename', - 'Indexed rename', - 'Indexed rename' - ] - : ['Metadata name', 'Metadata name', 'Metadata name', 'Metadata name', 'Metadata name'] - ) - expect(indexStats.mock.calls.filter(([file]) => file === path)).toHaveLength(1) - } - }) - it('keeps the indexed rename over a recorded session_meta title when the rollout grows', async () => { const { root, path } = await indexHome() const rollout = join(root, 'sessions', 'rollout.jsonl') diff --git a/src/main/antigravity/antigravity-chat-user-skills.test.ts b/src/main/antigravity/antigravity-chat-user-skills.test.ts deleted file mode 100644 index 2ad430400ed..00000000000 --- a/src/main/antigravity/antigravity-chat-user-skills.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type * as FsPromises from 'node:fs/promises' -import { mkdir, mkdtemp, readFile, readlink, rm, rmdir, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { linkAntigravityUserSkills } from './antigravity-chat-user-skills' - -const fsCalls = vi.hoisted(() => ({ count: 0 })) -vi.mock('node:fs/promises', async (importOriginal) => { - const real = await importOriginal() - const counted = - (fn: (...args: A) => Promise) => - (...args: A) => { - fsCalls.count++ - return fn(...args) - } - return { ...real, lstat: counted(real.lstat), rmdir: vi.fn(real.rmdir) } -}) - -let root: string -let chatHome: string -let userHome: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'agy-user-skills-')) - chatHome = join(root, 'antigravity-chat') - userHome = join(root, 'home') - await mkdir(join(userHome, '.gemini', 'config', 'skills', 'orca-cli'), { recursive: true }) - await writeFile(join(userHome, '.gemini', 'config', 'skills', 'orca-cli', 'SKILL.md'), 'skill') -}) - -afterEach(async () => { - vi.mocked(rmdir).mockRestore() - await rm(root, { recursive: true, force: true }) -}) - -it('replaces the empty placeholder with a link to the user skills', async () => { - await mkdir(join(chatHome, 'config', 'skills'), { recursive: true }) - - await linkAntigravityUserSkills(chatHome, userHome) - - const linked = join(chatHome, 'config', 'skills', 'orca-cli', 'SKILL.md') - expect(await readFile(linked, 'utf8')).toBe('skill') - // No ~/.gemini/antigravity-cli/skills, so nothing is linked there. - await expect(readlink(join(chatHome, 'antigravity-cli', 'skills'))).rejects.toThrow() -}) - -it('removes a link whose target is gone', async () => { - const link = join(chatHome, 'antigravity-cli', 'skills') - const target = join(userHome, '.gemini', 'antigravity-cli', 'skills') - await mkdir(join(chatHome, 'antigravity-cli'), { recursive: true }) - await mkdir(target, { recursive: true }) - // Windows creates directory links without extra rights only as junctions, to a target that exists. - await symlink(target, link, process.platform === 'win32' ? 'junction' : 'dir') - await rm(target, { recursive: true }) - - await linkAntigravityUserSkills(chatHome, userHome) - - await expect(readlink(link)).rejects.toThrow() -}) - -it('lets one launch finish linking before another starts on the same chat home', async () => { - const realRmdir = vi.mocked(rmdir).getMockImplementation()! - await mkdir(join(chatHome, 'config', 'skills'), { recursive: true }) - let release!: () => void - const held = new Promise((resolve) => (release = resolve)) - let first!: () => void - const firstRemoving = new Promise((resolve) => (first = resolve)) - vi.mocked(rmdir).mockImplementationOnce(async (path) => { - first() - await held - return realRmdir(path) - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const one = linkAntigravityUserSkills(chatHome, userHome) - await firstRemoving - const before = fsCalls.count - const two = linkAntigravityUserSkills(chatHome, userHome) - // A second launch that started at once would already have looked at the folder. - expect(fsCalls.count).toBe(before) - release() - await Promise.all([one, two]) - - expect(warn).not.toHaveBeenCalled() - const linked = join(chatHome, 'config', 'skills', 'orca-cli', 'SKILL.md') - expect(await readFile(linked, 'utf8')).toBe('skill') - warn.mockRestore() -}) diff --git a/src/main/browser/extensions/browser-extension-commands.test.ts b/src/main/browser/extensions/browser-extension-commands.test.ts new file mode 100644 index 00000000000..659a8f021cf --- /dev/null +++ b/src/main/browser/extensions/browser-extension-commands.test.ts @@ -0,0 +1,95 @@ +import { mkdtemp, mkdir, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + BrowserExtensionActionResult, + InstalledBrowserExtension +} from '../../../shared/browser/extensions/browser-extension-types' + +const mocks = vi.hoisted(() => { + const installed: InstalledBrowserExtension[] = [] + return { + installed, + reload: vi.fn(async (): Promise => ({ ok: true })) + } +}) +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: {} })) +vi.mock('./installation/browser-extension-install-store', () => ({ + getBrowserExtensionInstallStore: () => ({ list: () => mocks.installed }) +})) +vi.mock('./browser-extension-management', () => ({ + reloadUnpackedBrowserExtension: mocks.reload +})) +import { desktopBrowserExtensions } from './browser-extension-commands' + +const ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +let directory: string + +function extension(overrides: Partial = {}): InstalledBrowserExtension { + return { + id: ID, + name: 'Dev', + version: '1', + path: directory, + source: 'unpacked', + iconPath: null, + permissions: [], + hostPermissions: [], + optionsPage: null, + ...overrides + } +} + +beforeEach(async () => { + vi.clearAllMocks() + mocks.installed = [] + directory = await mkdtemp(join(tmpdir(), 'orca-extension-command-')) +}) +afterEach(async () => rm(directory, { recursive: true, force: true })) + +describe('desktop extension reload', () => { + it('reloads the installed unpacked extension whose source folder matches through an alias', async () => { + const source = join(directory, 'source') + const alias = join(directory, 'alias') + await mkdir(source) + await symlink(source, alias, 'junction') + mocks.installed = [extension({ path: source })] + await expect(desktopBrowserExtensions.reload({ path: alias })).resolves.toEqual({ + extensionId: ID + }) + expect(mocks.reload).toHaveBeenCalledWith(ID) + }) + + it('rejects a source folder shared by two installs without reloading either', async () => { + mocks.installed = [extension(), extension({ id: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' })] + await expect(desktopBrowserExtensions.reload({ path: directory })).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(mocks.reload).not.toHaveBeenCalled() + }) + + it('never installs or reloads a folder that is not installed', async () => { + await expect(desktopBrowserExtensions.reload({ path: directory })).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(mocks.reload).not.toHaveBeenCalled() + }) + + it('refuses Web Store extensions', async () => { + mocks.installed = [extension({ source: 'webstore' })] + await expect(desktopBrowserExtensions.reload({ extensionId: ID })).rejects.toMatchObject({ + code: 'invalid_argument' + }) + expect(mocks.reload).not.toHaveBeenCalled() + }) + + it('surfaces a manager failure instead of reporting success', async () => { + mocks.installed = [extension()] + mocks.reload.mockResolvedValueOnce({ ok: false, error: 'Extensions disabled' }) + await expect(desktopBrowserExtensions.reload({ extensionId: ID })).rejects.toMatchObject({ + code: 'runtime_error', + message: 'Extensions disabled' + }) + }) +}) diff --git a/src/main/browser/extensions/browser-extension-commands.ts b/src/main/browser/extensions/browser-extension-commands.ts new file mode 100644 index 00000000000..04d4916a17d --- /dev/null +++ b/src/main/browser/extensions/browser-extension-commands.ts @@ -0,0 +1,91 @@ +import { realpath, stat } from 'node:fs/promises' +import { isAbsolute } from 'node:path' +import type { + BrowserExtensionListParams, + BrowserExtensionReloadParams, + BrowserExtensionReloadResult, + BrowserExtensionSummaryListResult, + InstalledBrowserExtension +} from '../../../shared/browser/extensions/browser-extension-types' +import { BrowserError } from '../browser-error' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' +import { getBrowserExtensionInstallStore } from './installation/browser-extension-install-store' +import { + listBrowserExtensionsForProfile, + reloadUnpackedBrowserExtension +} from './browser-extension-management' + +/** Finds the one installed unpacked extension whose canonical source folder is `path`. */ +async function extensionIdForSourceFolder( + path: string, + installed: InstalledBrowserExtension[] +): Promise { + if (!isAbsolute(path)) { + throw new BrowserError('invalid_argument', 'Extension source folder must be an absolute path') + } + const directory = await realpath(path).catch(() => null) + if (!directory || !(await stat(directory).catch(() => null))?.isDirectory()) { + throw new BrowserError('invalid_argument', 'Extension source folder was not found') + } + const matches = await Promise.all( + installed + .filter((extension) => extension.source === 'unpacked') + .map(async (extension) => + (await realpath(extension.path).catch(() => null)) === directory ? extension.id : null + ) + ) + const ids = matches.filter((id) => id !== null) + if (ids.length !== 1) { + throw new BrowserError( + 'invalid_argument', + ids.length === 0 + ? 'No installed unpacked extension matches this source folder' + : 'Multiple installed unpacked extensions match this source folder; use an extension ID' + ) + } + return ids[0] +} + +/** Selection shape and ID format are checked by the RPC params schema. */ +export const desktopBrowserExtensions = { + async list({ + profileId = 'default' + }: BrowserExtensionListParams): Promise { + if (!browserSessionRegistry.getProfile(profileId)) { + throw new BrowserError('invalid_argument', `Browser profile ${profileId} was not found`) + } + const { active, extensions } = await listBrowserExtensionsForProfile(profileId) + return { + active, + extensions: extensions.map(({ id, name, version, source, path, enabled, loadError }) => ({ + id, + name, + version, + source, + path, + enabled, + loadError + })) + } + }, + /** Reloads every profile where the extension is enabled, like the Settings reload button. */ + async reload(params: BrowserExtensionReloadParams): Promise { + const installed = getBrowserExtensionInstallStore().list() + const extensionId = + params.path !== undefined + ? await extensionIdForSourceFolder(params.path, installed) + : params.extensionId + const extension = installed.find((record) => record.id === extensionId) + if (!extension) { + throw new BrowserError('invalid_argument', 'Extension is not installed') + } + if (extension.source !== 'unpacked') { + throw new BrowserError('invalid_argument', 'Only unpacked extensions can be reloaded') + } + const result = await reloadUnpackedBrowserExtension(extension.id) + if (!result.ok) { + throw new BrowserError('runtime_error', result.error) + } + return { extensionId: extension.id } + } +} diff --git a/src/main/browser/extensions/browser-extension-management.ts b/src/main/browser/extensions/browser-extension-management.ts index dbd4c9e178d..fda54bc4fde 100644 --- a/src/main/browser/extensions/browser-extension-management.ts +++ b/src/main/browser/extensions/browser-extension-management.ts @@ -58,6 +58,7 @@ async function settle(action: () => Promise): Promise { @@ -72,6 +73,7 @@ export async function listBrowserExtensionsForProfile( name: extension.name, version: extension.version, source: extension.source, + path: extension.path, enabled: enabled.has(extension.id), iconDataUrl: await readBrowserExtensionIconDataUrl(extension.path, extension.iconPath), hasOptionsPage: extension.optionsPage !== null, @@ -182,6 +184,8 @@ export function reloadUnpackedBrowserExtension( } store.save(record, true) await reloadBrowserExtensionWhereEnabled(record, { refresh: true }) + // Why: a CLI reload can change name, version or options page while Settings is open. + notifyBrowserExtensionListChanged() }) ) } diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts index b52c38e018e..742e76bdbed 100644 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts @@ -1,3 +1,4 @@ +// @orca-isolated-worker: the Electron app, mock server and temp root live at module level, one per test file. import type { PopupCompatibilityStatus } from './browser-popup-compatibility-status' import { spawnProcess } from '@orca/process-host' import { createServer } from 'node:http' diff --git a/src/main/claude/claude-naming-generation.test.ts b/src/main/claude/claude-naming-generation.test.ts new file mode 100644 index 00000000000..acbd4653976 --- /dev/null +++ b/src/main/claude/claude-naming-generation.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi } from 'vitest' +import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection' +import { createClaudeNamingGeneration } from './claude-naming-generation' + +describe('createClaudeNamingGeneration', () => { + it("passes a close's options through to the connection it watches", async () => { + const close = vi.fn(async () => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach and the close wrapper read only close and exitVerdict. + const connection = { + close, + exitVerdict: { root: 'exited' } + } as unknown as ClaudeStreamJsonConnection + createClaudeNamingGeneration('chat', undefined, 'native', () => {}).attach(connection) + + await connection.close({ grace: 'brief' }) + + expect(close).toHaveBeenCalledWith({ grace: 'brief' }) + }) +}) diff --git a/src/main/claude/claude-naming-generation.ts b/src/main/claude/claude-naming-generation.ts index 8cf86ae5260..2edde684fd4 100644 --- a/src/main/claude/claude-naming-generation.ts +++ b/src/main/claude/claude-naming-generation.ts @@ -55,9 +55,9 @@ export function createClaudeNamingGeneration( generation.phase = 'initializing' } const close = connection.close - connection.close = () => { + connection.close = (...args) => { generation.phase = 'closing' - const done = close.call(connection) + const done = close.apply(connection, args) generation.closing = done notify() return done.finally(() => { diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index b2654e1e03f..07ea066980f 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -24,6 +24,7 @@ import type { ClaudeStructuredSdkOptions } from './structured/launch/claude-stru import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing' import { claudeStreamJsonExitError } from './claude-stream-json-exit-error' import { withObservedProviderExit } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +import type { ProviderProcessCloseOptions } from '../provider-process/provider-process-close' export { ClaudeControlRequestError } @@ -95,7 +96,7 @@ export type ClaudeStreamJsonConnection = ClaudeControlSurface & { resumeReading?: () => void send: (message: Record, beforeDispatch?: () => Promise) => Promise /** Resolves true after processless settlement, or root exit plus observed tree exit. */ - close: () => Promise + close: (options?: ProviderProcessCloseOptions) => Promise } export async function openClaudeStreamJsonConnection( @@ -270,14 +271,14 @@ export async function openClaudeStreamJsonConnection( return inbox.push(message as unknown as SDKUserMessage, beforeDispatch) } - const close = (): Promise => { + const close = (options?: ProviderProcessCloseOptions): Promise => { closePromise ??= (async () => { closing = true resumeReading() // Capture before stopping: exited roots can leave reparented descendants undiscoverable. await (tree.refresh?.() ?? tree.capture()) inbox.end() - const result = await managed.closeWriter(tree) + const result = await managed.closeWriter(tree, options) const proven = claudeChildCloseProven(result) || result.killDelivered === true inbox.fail(new Error('claude stream-json connection closed')) if (!proven) { diff --git a/src/main/claude/claude-supervised-stop.integration.test.ts b/src/main/claude/claude-supervised-stop.integration.test.ts index 5386723cf0d..82e6d20fd65 100644 --- a/src/main/claude/claude-supervised-stop.integration.test.ts +++ b/src/main/claude/claude-supervised-stop.integration.test.ts @@ -11,7 +11,7 @@ import { PROVIDER_STDIN_END_GRACE_MS, PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../provider-process/provider-process-supervisor' -import { proveClaudeChildExit } from './claude-agent-sdk-exit-proof' +import { createClaudeChildTreeReaper, proveClaudeChildExit } from './claude-agent-sdk-exit-proof' import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' // EOF leaves the turn running; SIGTERM reaps a detached tool but preserves a double-forked daemon. @@ -195,6 +195,26 @@ describe.runIf(process.platform !== 'win32')('Claude under the POSIX provider su expect(alive(pids.claude)).toBe(false) }) + it('forces a Claude that ignores SIGTERM soon after a brief close, with its exit proven', async () => { + const { managed, exit, pids } = await spawnClaude({ ORCA_TEST_CLAUDE_IGNORES_SIGTERM: '1' }) + const tree = createClaudeChildTreeReaper(managed.child, { + exited: () => managed.rootVerdict === 'exited' + }) + + // ast-grep-ignore: test-no-wall-clock -- the brief grace is the behaviour under test + const startedAt = Date.now() + await expect(managed.close(tree, { grace: 'brief' })).resolves.toEqual({ + root: 'exited', + tree: 'exited' + }) + + // ast-grep-ignore: test-no-wall-clock -- the full SIGTERM grace is 3 s; a brief close must not wait it out + expect(Date.now() - startedAt).toBeLessThan(2_500) + await expect(exit).resolves.toEqual({ code: null, signal: 'SIGTERM', processless: false }) + expect(alive(pids.claude)).toBe(false) + expect(alive(pids.tool)).toBe(false) + }) + it("stops Claude and its tool when Orca's main dies, and leaves a daemon that left its tree alone", async () => { const specs: ProcessSpec[] = [] createClaudeCodeProcessSpawn((spec) => { diff --git a/src/main/claude/structured/claude-structured-acquisition-release.ts b/src/main/claude/structured/claude-structured-acquisition-release.ts index b501b571264..6f5c32a838b 100644 --- a/src/main/claude/structured/claude-structured-acquisition-release.ts +++ b/src/main/claude/structured/claude-structured-acquisition-release.ts @@ -10,19 +10,23 @@ import type { ClaudeSessionExit, ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' +import type { ProviderProcessCloseOptions } from '../../provider-process/provider-process-close' + +export type ClaudeReleaseRequest = { sessionId: string; closeOptions?: ProviderProcessCloseOptions } /** An observed exit still requires connection cleanup; absence alone cannot prove release. */ -export async function releaseClaudeAcquisition(input: { - sessionId: string - sessions: Map - acquisitions: ClaudeAcquisitionRegistry - exits: Map - onExitProven?: (sessionId: string, exit: ClaudeSessionExit) => Promise - persistHandle?: ClaudeStructuredSessionAdapterDeps['persistHandle'] - onEvent?: ClaudeStructuredSessionAdapterDeps['onEvent'] - logger?: ClaudeStructuredSessionAdapterDeps['logger'] - settledExitErrors?: Map -}): Promise { +export async function releaseClaudeAcquisition( + input: ClaudeReleaseRequest & { + sessions: Map + acquisitions: ClaudeAcquisitionRegistry + exits: Map + onExitProven?: (sessionId: string, exit: ClaudeSessionExit) => Promise + persistHandle?: ClaudeStructuredSessionAdapterDeps['persistHandle'] + onEvent?: ClaudeStructuredSessionAdapterDeps['onEvent'] + logger?: ClaudeStructuredSessionAdapterDeps['logger'] + settledExitErrors?: Map + } +): Promise { const exit = input.exits.get(input.sessionId) if (!exit || input.sessions.has(input.sessionId) || input.acquisitions.get(input.sessionId)) { return closeClaudeSession(input) diff --git a/src/main/claude/structured/claude-structured-session-adapter.ts b/src/main/claude/structured/claude-structured-session-adapter.ts index 506eadfc65c..c72b025529e 100644 --- a/src/main/claude/structured/claude-structured-session-adapter.ts +++ b/src/main/claude/structured/claude-structured-session-adapter.ts @@ -9,7 +9,10 @@ import type { } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { stopCurrentClaudeBackgroundTasks } from './claude-structured-control-actions' import { claudeHeldSends, claudeHoldsDispatch } from '../claude-command-lifecycle' -import { releaseClaudeAcquisition } from './claude-structured-acquisition-release' +import { + releaseClaudeAcquisition, + type ClaudeReleaseRequest +} from './claude-structured-acquisition-release' import { acquireClaudeSession } from './claude-structured-session-acquisition' import { supportsClaudeStructuredLocation } from './launch/claude-structured-location-support' import * as claudeOptions from './launch/claude-structured-options' @@ -97,7 +100,7 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda finishClaudeCloseAfterExit({ sessions: this.sessions, exits: this.exits, - closeExit: this.releaseProviderSession, + closeExit: (sessionId) => this.releaseProviderSession({ sessionId }), sessionId, connection: attempt.connection, deps: { ...this.deps, settledExitErrors: this.settledExitErrors }, @@ -227,9 +230,9 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda }) readOptions = (input: { sessionId: string; fence: number }) => readClaudeStructuredSessionOptions(this.session(input.sessionId)) - releaseAcquisition = (input: { sessionId: string }): Promise => { + releaseAcquisition = (input: ClaudeReleaseRequest): Promise => { this.endings.retire(input.sessionId) - return this.afterClose(input.sessionId, () => this.releaseProviderSession(input.sessionId)) + return this.afterClose(input.sessionId, () => this.releaseProviderSession(input)) } acknowledgeSessionRelease = (sessionId: string): void => { this.settledExitErrors.delete(sessionId) @@ -260,9 +263,9 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda } } - private releaseProviderSession = (sessionId: string): Promise => + private releaseProviderSession = (request: ClaudeReleaseRequest): Promise => releaseClaudeAcquisition({ - sessionId, + ...request, sessions: this.sessions, acquisitions: this.acquisitions, exits: this.exits, @@ -272,8 +275,12 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda ...this.deps }) - closeSession = (sessionId: string): Promise => - this.releaseAcquisition({ sessionId }).finally(() => { + closeSession: NonNullable = ( + sessionId, + _, + options + ) => + this.releaseAcquisition({ sessionId, closeOptions: options }).finally(() => { const receipt = this.settledExitErrors.get(sessionId) if ( !( diff --git a/src/main/claude/structured/claude-structured-session-close.ts b/src/main/claude/structured/claude-structured-session-close.ts index 524867ed56a..4eb98131f6d 100644 --- a/src/main/claude/structured/claude-structured-session-close.ts +++ b/src/main/claude/structured/claude-structured-session-close.ts @@ -21,6 +21,7 @@ import { claudeHeldSends } from '../claude-command-lifecycle' import { settledClaudeTurnEndLeaf } from './claude-structured-resume-point' import { settleClaudeTurnEndWaiters } from '../claude-request-end-wait' import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { ProviderProcessCloseOptions } from '../../provider-process/provider-process-close' /** Root exit releases the lease even with unverified descendants; a failed spawn proves no exit. */ export function claudeRootExitObserved( @@ -105,6 +106,7 @@ type CloseClaudePublishedSessionInput = { onEvent?: (event: ClaudeStructuredSessionEvent) => void logger?: StructuredAgentSessionLogger settledExitErrors?: Map + closeOptions?: ProviderProcessCloseOptions } async function finalizeClaudePublishedSession( @@ -116,7 +118,7 @@ async function finalizeClaudePublishedSession( for (const prompt of session.prompts.clear()) { prompt.settle(null) } - const connectionClosed = await session.connection.close() + const connectionClosed = await session.connection.close(input.closeOptions) session.unbindReadingControl?.() const rootExitVerdict = claudeCloseReport( session.connection, diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts index 096321a9716..e462e89a305 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts @@ -55,9 +55,7 @@ export function withClaudeArtifactDefault( return chosen ? env : { ...env, [CLAUDE_ARTIFACT_ENV]: '1' } } -type ClaudePermissionOptions = Pick & { - resolvePermissionModeInCli?: true -} +type ClaudePermissionOptions = Pick export type ClaudeStructuredSdkOptions = Pick< ClaudeAgentSdkOptions, @@ -100,8 +98,8 @@ export function claudeStructuredPermissionOptions( mode: AgentChatPermissionChoice ): ClaudePermissionOptions { if (mode === 'own') { - // upstream request: https://github.com/anthropics/claude-agent-sdk-typescript/issues/519 - return { resolvePermissionModeInCli: true } + // An omitted mode lets the CLI apply the user's settings defaultMode. + return {} } return mode === 'full-access' ? { extraArgs: { 'dangerously-skip-permissions': null } } diff --git a/src/main/codex/app-server/codex-app-server-notification-schema.ts b/src/main/codex/app-server/codex-app-server-notification-schema.ts index a7319273cdb..4c84ff59b71 100644 --- a/src/main/codex/app-server/codex-app-server-notification-schema.ts +++ b/src/main/codex/app-server/codex-app-server-notification-schema.ts @@ -1,16 +1,24 @@ -// Stable ServerNotification method discriminators generated by codex-cli 0.147.0. +// Stable ServerNotification method discriminators generated by codex-cli 0.167.0. export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [ 'error', 'thread/started', 'thread/status/changed', + 'thread/readState/changed', 'thread/archived', 'thread/deleted', 'thread/unarchived', 'thread/closed', + 'thread/reverted', 'skills/changed', 'thread/name/updated', + 'thread/section/changed', + 'thread/attachment/updated', 'thread/goal/updated', + 'thread/prediction/updated', 'thread/goal/cleared', + 'thread/queue/changed', + 'project/changed', + 'thread/project/updated', 'thread/environment/connected', 'thread/environment/disconnected', 'thread/settings/updated', @@ -24,6 +32,7 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [ 'item/started', 'item/autoApprovalReview/started', 'item/autoApprovalReview/completed', + 'autoApprovalReview/strictReviewRequired', 'item/completed', 'rawResponseItem/completed', 'rawResponse/completed', @@ -40,7 +49,9 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [ 'item/mcpToolCall/progress', 'mcpServer/oauthLogin/completed', 'mcpServer/startupStatus/updated', + 'mcpServer/event/stream/notification', 'account/updated', + 'account/gatewayOAuth/changed', 'account/rateLimits/updated', 'app/list/updated', 'remoteControl/status/changed', @@ -53,6 +64,8 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [ 'thread/compacted', 'model/rerouted', 'model/verification', + 'modelProvider/authRecoveryStarted', + 'modelProvider/authRecoveryCompleted', 'turn/moderationMetadata', 'model/safetyBuffering/updated', 'warning', @@ -63,6 +76,9 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [ 'fuzzyFileSearch/sessionCompleted', 'thread/realtime/started', 'thread/realtime/itemAdded', + 'thread/realtime/item/started', + 'thread/realtime/item/transcript/delta', + 'thread/realtime/item/completed', 'thread/realtime/transcript/delta', 'thread/realtime/transcript/done', 'thread/realtime/outputAudio/delta', diff --git a/src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts b/src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts index c8486c164e7..a5cd6fbf1ff 100644 --- a/src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts +++ b/src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts @@ -1,4 +1,5 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' // Mark fallback copies so sync can refresh/remove them without touching user-created resources. @@ -19,11 +20,9 @@ export function markCopiedResource( }) } -function readCopiedResourceSourcePath(managedHomePath: string, entryName: string): string | null { +function parseCopiedResourceSourcePath(text: string): string | null { try { - const parsed: unknown = JSON.parse( - readFileSync(getResourceCopyMarkerPath(managedHomePath, entryName), 'utf-8') - ) + const parsed: unknown = JSON.parse(text) if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return null } @@ -34,6 +33,27 @@ function readCopiedResourceSourcePath(managedHomePath: string, entryName: string } } +function readCopiedResourceSourcePath(managedHomePath: string, entryName: string): string | null { + try { + return parseCopiedResourceSourcePath( + readFileSync(getResourceCopyMarkerPath(managedHomePath, entryName), 'utf-8') + ) + } catch { + return null + } +} + +/** The source an Orca fallback copy mirrors; null when the entry is a link or the user's own. */ +export async function readCopiedResourceSource( + managedHomePath: string, + entryName: string +): Promise { + const text = await readFile(getResourceCopyMarkerPath(managedHomePath, entryName), 'utf-8').catch( + () => null + ) + return text === null ? null : parseCopiedResourceSourcePath(text) +} + export function clearCopiedResourceMarker(managedHomePath: string, entryName: string): void { // Malformed marker directories must not block resource repair or Codex launch. rmSync(getResourceCopyMarkerPath(managedHomePath, entryName), { diff --git a/src/main/codex/structured/catalog/codex-at-rest-skills-probe-pools.ts b/src/main/codex/structured/catalog/codex-at-rest-skills-probe-pools.ts index d7d23978c4f..30055b42bca 100644 --- a/src/main/codex/structured/catalog/codex-at-rest-skills-probe-pools.ts +++ b/src/main/codex/structured/catalog/codex-at-rest-skills-probe-pools.ts @@ -7,7 +7,6 @@ const FAILED_START_BACKOFF_MS = [10_000, 30_000, 90_000, 5 * 60_000] as const export type FolderRequest = { cwd: string - generation: number isCurrent: () => boolean admitted: () => void answer: PromiseWithResolvers diff --git a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts b/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts index 6c05e8ca12f..070f724816b 100644 --- a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts +++ b/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts @@ -1,6 +1,5 @@ import { delayUnlessAborted } from '../../../../shared/abort-aware-delay' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' -import { createHash } from 'node:crypto' import * as Pools from './codex-at-rest-skills-probe-pools' import { isLegacyAgentSessionAccountHome, @@ -26,6 +25,7 @@ import { codexReportCommandRows, isCodexSkillsListUnsupported } from './codex-skill-list' +import { createCodexSkillSourcesStamp } from './codex-skill-sources-stamp' import { isNativeLocalLocation as supportsCodexStructuredLocation } from '../../../../shared/execution-host' import { resolveHiddenProbeCwd } from '../../../rate-limits/hidden-probe-cwd' import { @@ -64,6 +64,7 @@ function definedEnv(env: NodeJS.ProcessEnv | undefined): Record export function createCodexAtRestSkillCatalog(deps: CodexAtRestSkillsDeps): AtRestCommandCatalog { const now = deps.now ?? Date.now const { pools, start, expire, dispose } = Pools.createCodexSkillsProbePools(deps, probe) + const stampSources = createCodexSkillSourcesStamp(deps.now ? { now: deps.now } : {}) return new AtRestCommandCatalog({ label: 'codex', @@ -73,6 +74,8 @@ export function createCodexAtRestSkillCatalog(deps: CodexAtRestSkillsDeps): AtRe isLegacyAgentSessionAccountHome(record.accountHome), resolveWorkspacePath: deps.resolveWorkspacePath, dispose, + stamp: (record, cwd, signal) => + stampSources(requireLegacyAgentSessionAccountHome(record.accountHome).path, cwd, signal), scan: async (record, cwd, isCurrent, generation, signal, admitted) => { const accountHomePath = requireLegacyAgentSessionAccountHome(record.accountHome).path const { command, prefixArgs, environment } = await resolveCodexStructuredInvocation({ @@ -90,14 +93,10 @@ export function createCodexAtRestSkillCatalog(deps: CodexAtRestSkillsDeps): AtRe return NO_SCAN } const env = definedEnv(environment) - const key = JSON.stringify([ - accountHomePath, - command, - args, - createHash('sha256') - .update(JSON.stringify(Object.entries(env).sort())) - .digest('hex') - ]) + // Not the env itself: the shell capture refreshes every 10 s with volatile values (prompt + // session keys), which would start a second probe. Settings and account env changes retire + // the generation; a running probe keeps the env it started with for its ~70 s life. + const key = JSON.stringify([accountHomePath, command, args, generation]) const pool = pools.get(key) ?? { failedStarts: 0, retryAt: 0, lastDemandAt: now() } pools.set(key, pool) pool.lastDemandAt = now() @@ -117,7 +116,6 @@ export function createCodexAtRestSkillCatalog(deps: CodexAtRestSkillsDeps): AtRe } const request: Pools.FolderRequest = { cwd, - generation, isCurrent, admitted, answer: Promise.withResolvers(), @@ -161,7 +159,6 @@ export async function probe( onStarted: () => void ): Promise { const now = deps.now ?? Date.now - let reloaded = Math.max(...[...pool.pending].map((request) => request.generation)) await (deps.runSession ?? runCodexAppServerSession)( { command: pool.command, @@ -210,13 +207,10 @@ export async function probe( pool.cursor = undefined } if (batch.length > 0) { - const forceReload = batch.some((request) => request.generation > reloaded) try { deps.prepareHome?.(pool.accountHomePath) batch.forEach((request) => request.admitted()) - if (await answer(rpc, batch, forceReload, signal)) { - reloaded = Math.max(reloaded, ...batch.map((request) => request.generation)) - } + await answer(rpc, batch, signal) } catch (error) { batch.forEach((request) => Pools.settle(request, error instanceof Error ? error : new Error(String(error))) @@ -249,27 +243,27 @@ export async function probe( async function answer( rpc: CodexAppServerRpc, batch: Pools.FolderRequest[], - forceReload: boolean, signal: AbortSignal -): Promise { +): Promise { let reply: unknown try { reply = await rpc.request( CODEX_SKILLS_LIST_METHOD, - { cwds: batch.map((request) => request.cwd), ...(forceReload ? { forceReload: true } : {}) }, + // A probe answers several menus in its lifetime; without this Codex can repeat its cached list. + { cwds: batch.map((request) => request.cwd), forceReload: true }, { timeoutMs: ANSWER_TIMEOUT_MS } ) } catch (error) { if (isCodexSkillsListUnsupported(error)) { // An older Codex has no list to give; the client keeps its folder scan. batch.forEach((request) => Pools.settle(request, { commands: undefined, fromAgent: true })) - return false + return } // The process still settles: ending it early would interrupt plugin sync, including after a list failure. batch.forEach((request) => Pools.settle(request, error instanceof Error ? error : new Error(String(error))) ) - return false + return } signal.throwIfAborted() for (const request of batch) { @@ -290,5 +284,4 @@ async function answer( : new Error(`codex listed no skills entry for ${request.cwd}`) ) } - return true } diff --git a/src/main/codex/structured/catalog/codex-skill-sources-stamp.test.ts b/src/main/codex/structured/catalog/codex-skill-sources-stamp.test.ts new file mode 100644 index 00000000000..56782bd37ef --- /dev/null +++ b/src/main/codex/structured/catalog/codex-skill-sources-stamp.test.ts @@ -0,0 +1,123 @@ +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createCodexSkillSourcesStamp } from './codex-skill-sources-stamp' + +let root: string +let clock = 0 + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'codex-skill-stamp-')) + await mkdir(join(root, 'home', '.agents', 'skills'), { recursive: true }) + await mkdir(join(root, 'codex-home'), { recursive: true }) + await mkdir(join(root, 'repo', '.git'), { recursive: true }) + await writeFile(join(root, 'codex-home', 'config.toml'), TRUSTED) +}) + +const TRUSTED = '[projects."/tmp/a"]\ntrust_level = "trusted"\n' + +afterEach(async () => { + await rm(root, { recursive: true, force: true }) +}) + +async function writeSkill(directory: string, name: string): Promise { + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n`) +} + +function stamper(accountHome = join(root, 'codex-home')) { + const stamp = createCodexSkillSourcesStamp({ + now: () => clock, + homeDir: () => join(root, 'home'), + systemCodexHome: () => join(root, 'codex-home'), + managedCodexHome: () => join(root, 'managed-home') + }) + return async () => { + // Step past the shared per-root reuse window between reads. + clock += 10_000 + return stamp(accountHome, join(root, 'repo'), new AbortController().signal) + } +} + +describe('Codex skill sources stamp', () => { + it.each([ + ['a user skill', () => writeSkill(join(root, 'home', '.agents', 'skills', 'perf-scan'), 'p')], + [ + 'a linked user skill', + async () => { + await writeSkill(join(root, 'elsewhere', 'perf-scan'), 'p') + await symlink( + join(root, 'elsewhere', 'perf-scan'), + join(root, 'home', '.agents', 'skills', 'perf-scan'), + 'dir' + ) + } + ], + [ + 'a nested user skill', + () => writeSkill(join(root, 'home', '.agents', 'skills', 'synced', 'x', 'perf-scan'), 'p') + ], + ['a repo skill', () => writeSkill(join(root, 'repo', '.agents', 'skills', 'perf-scan'), 'p')], + [ + 'a project plugin', + async () => { + await mkdir(join(root, 'repo', '.codex'), { recursive: true }) + await writeFile( + join(root, 'repo', '.codex', 'config.toml'), + '[plugins."docs@openai"]\nenabled = true\n' + ) + } + ], + [ + 'a quoted plugin table', + () => + writeFile( + join(root, 'codex-home', 'config.toml'), + `${TRUSTED}['plugins'.'demo@local']\nenabled = true\n` + ) + ], + [ + 'a dotted plugin key', + () => + writeFile( + join(root, 'codex-home', 'config.toml'), + `plugins."demo@local".enabled = true\n${TRUSTED}` + ) + ], + [ + 'a disabled skill', + () => + writeFile( + join(root, 'codex-home', 'config.toml'), + `${TRUSTED}[[skills.config]]\npath = "/s/SKILL.md"\nenabled = false\n` + ) + ] + ])('changes when %s is added', async (_label, change) => { + const read = stamper() + const before = await read() + await change() + const after = await read() + expect(before).toBeDefined() + expect(after).not.toBe(before) + }) + + it('ignores config edits outside skills and plugins', async () => { + const read = stamper() + const before = await read() + await writeFile( + join(root, 'codex-home', 'config.toml'), + `${TRUSTED}[projects."/tmp/new-worktree"]\ntrust_level = "trusted"\n` + ) + expect(await read()).toBe(before) + }) + + it("ignores the managed home's config copy, which the probe rewrites from the source", async () => { + const managed = join(root, 'managed-home') + await mkdir(managed, { recursive: true }) + const read = stamper(managed) + const before = await read() + await writeFile(join(managed, 'config.toml'), '[plugins."docs@openai"]\nenabled = true\n') + expect(await read()).toBe(before) + }) +}) diff --git a/src/main/codex/structured/catalog/codex-skill-sources-stamp.ts b/src/main/codex/structured/catalog/codex-skill-sources-stamp.ts new file mode 100644 index 00000000000..01f2272866d --- /dev/null +++ b/src/main/codex/structured/catalog/codex-skill-sources-stamp.ts @@ -0,0 +1,196 @@ +import { createHash } from 'node:crypto' +import { readFile, stat } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import { findSkillFiles } from '../../../skills/discovery/skill-root-file-walk' +import { runSkillCandidateTasks } from '../../../skills/filesystem/skill-candidate-concurrency' +import { + getSystemCodexHomePath, + resolveOrcaManagedCodexHomePath +} from '../../configuration/homes/codex-home-paths' +import { readCopiedResourceSource } from '../../configuration/homes/codex-managed-home-resource-copy-marker' +import { parse as parseToml } from 'smol-toml' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' + +// Mirrors Codex's skill walk (codex-rs ext/skills loader: MAX_SCAN_DEPTH). +const CODEX_SKILL_SCAN_DEPTH = 6 +/** Menu bursts across chats and phones share one walk per root. */ +const ROOT_STAMP_REUSE_MS = 1_000 +/** A slow read is reused longer, keeping a huge root's I/O near 2% of wall time. */ +const ROOT_STAMP_REUSE_PER_WALK_MS = 50 +/** A read that timed out (hung network drive) is not retried until this passes. */ +const TIMED_OUT_ROOT_RETRY_MS = 60_000 +/** Half the libuv pool, so a stamp never starves other main-process I/O. */ +const STAT_CONCURRENCY = 2 +/** Per read and overall: a slow root (network drive) yields no stamp; the TTL rescan covers it. */ +const STAMP_TIMEOUT_MS = 2_000 + +type Remembered = { until: number; value: Promise } + +// Every filesystem read goes through one of these: a hung mount parks at most one libuv worker per key. +function createTimedMemo(now: () => number) { + const entries = new Map>() + return (key: string, caller: AbortSignal, read: (signal: AbortSignal) => Promise) => { + const at = now() + let entry = entries.get(key) + if (!entry || at >= entry.until) { + for (const [path, old] of entries) { + if (at >= old.until) { + entries.delete(path) + } + } + // Shared work owns only its time limit, so one chat's cancel never fails another's read. + const limit = AbortSignal.timeout(STAMP_TIMEOUT_MS) + // A hung readdir or stat never settles on abort; racing lets the timed-out mark replace it. + const value = waitForPromiseWithSignal(read(limit), limit) + // In flight: concurrent menus join this read. + const created: Remembered = { until: Number.POSITIVE_INFINITY, value } + value.then( + () => { + const done = now() + created.until = + done + Math.max(ROOT_STAMP_REUSE_MS, (done - at) * ROOT_STAMP_REUSE_PER_WALK_MS) + }, + () => { + created.until = now() + TIMED_OUT_ROOT_RETRY_MS + } + ) + entries.set(key, created) + entry = created + } + return waitForPromiseWithSignal(entry.value, caller) + } +} + +/** Fingerprint of everything Codex reads skills from; a changed value means skills/list may differ. */ +export function createCodexSkillSourcesStamp( + options: { + now?: () => number + homeDir?: () => string + systemCodexHome?: () => string + managedCodexHome?: () => string + } = {} +) { + const now = options.now ?? Date.now + const home = options.homeDir ?? homedir + const systemCodexHome = options.systemCodexHome ?? getSystemCodexHomePath + const managedCodexHome = options.managedCodexHome ?? resolveOrcaManagedCodexHomePath + const roots = createTimedMemo(now) + const chains = createTimedMemo(now) + const markers = createTimedMemo(now) + const configReads = createTimedMemo(now) + const configs = new Map() + + const rootStamp = (root: string, caller: AbortSignal): Promise => + roots(root, caller, async (signal) => { + const files = await findSkillFiles(root, CODEX_SKILL_SCAN_DEPTH, signal, { + skipHiddenDirectories: true, + stopAtSkillDirectories: true + }) + const facts = await runSkillCandidateTasks( + files.map((file) => async () => { + signal.throwIfAborted() + // ctime catches copies that preserve mtime (cp -p, unpacked archives). + const info = await stat(file).catch(() => null) + return info ? `${file}:${info.ino}:${info.ctimeMs}:${info.size}` : `${file}:-` + }), + STAT_CONCURRENCY + ) + return facts.join('\n') + }) + + // Only skill and plugin tables matter: Orca adds a trust entry each time a chat opens in a new folder. + const configStamp = async (path: string): Promise => { + const info = await stat(path).catch(() => null) + if (!info) { + return `${path}:-` + } + const key = `${info.ino}:${info.mtimeMs}:${info.size}` + const cached = configs.get(path) + if (cached?.key === key) { + return cached.digest + } + const text = await readFile(path, 'utf8').catch(() => '') + let kept: string + try { + // Parsed, so headers, dotted keys and inline tables all count. + const { skills, plugins } = parseToml(text) + kept = JSON.stringify([skills ?? null, plugins ?? null]) + } catch { + kept = text + } + const digest = `${path}:${createHash('sha1').update(kept).digest('hex')}` + configs.set(path, { key, digest }) + return digest + } + + return async ( + accountHomePath: string, + cwd: string, + signal: AbortSignal + ): Promise => { + const bounded = AbortSignal.any([signal, AbortSignal.timeout(STAMP_TIMEOUT_MS)]) + const work = async (): Promise => { + // Orca's managed home holds copies the probe rewrites; stamping them would rescan forever. + const mirrored = + normalizeRuntimePathForComparison(accountHomePath) === + normalizeRuntimePathForComparison(managedCodexHome()) + const copiedFrom = mirrored + ? await markers(accountHomePath, signal, () => + readCopiedResourceSource(accountHomePath, 'skills') + ) + : null + const skills = copiedFrom ?? join(accountHomePath, 'skills') + const project = await chains(cwd, signal, (limit) => projectDirectories(cwd, limit)) + const sources = [ + skills, + join(skills, '.system'), + join(home(), '.agents', 'skills'), + ...(process.platform === 'win32' ? [] : ['/etc/codex/skills']), + ...project.flatMap((directory) => [ + join(directory, '.agents', 'skills'), + join(directory, '.codex', 'skills') + ]) + ] + const parts: string[] = [] + // One root at a time: each walk already keeps up to three reads in flight. + for (const root of sources) { + parts.push(root, await rootStamp(root, signal)) + } + // Trusted projects can enable plugins in their own config too. + for (const config of new Set([ + ...(mirrored ? [] : [join(accountHomePath, 'config.toml')]), + join(systemCodexHome(), 'config.toml'), + ...project.map((directory) => join(directory, '.codex', 'config.toml')) + ])) { + parts.push(await configReads(config, signal, () => configStamp(config))) + } + return createHash('sha1').update(parts.join('\n')).digest('hex') + } + // Caps the menu's wait even while a joined root walk is still running. + return waitForPromiseWithSignal(work(), bounded).catch(() => undefined) + } +} + +/** Codex reads project skills and config in each folder from the git root down to cwd. */ +async function projectDirectories(cwd: string, signal: AbortSignal): Promise { + const chain: string[] = [] + for (let directory = cwd; ; directory = dirname(directory)) { + signal.throwIfAborted() + chain.push(directory) + if ( + await stat(join(directory, '.git')).then( + () => true, + () => false + ) + ) { + break + } + if (dirname(directory) === directory) { + chain.splice(1) + break + } + } + return chain +} diff --git a/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts b/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts index 67df104b1d1..74ed29258d7 100644 --- a/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts +++ b/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts @@ -198,6 +198,25 @@ describe('codex journal translation', () => { expect(tap.rows.filter((row) => row.key.includes('provider-frame-suppressed'))).toHaveLength(1) }) + it('journals no row for app-server notifications that carry provider text', () => { + const { translator, tap, window } = translatorWith() + + translator.handle(TURN_STARTED) + translator.handle( + notification('thread/prediction/updated', { threadId: THREAD_ID, text: 'Predicted reply' }) + ) + translator.handle( + notification('modelProvider/authRecoveryStarted', { message: 'Reconnecting to provider' }) + ) + translator.handle( + notification('modelProvider/authRecoveryCompleted', { message: 'Reconnected' }) + ) + translator.handle(notification('account/gatewayOAuth/changed', { error: 'Sign-in expired' })) + window.fire() + + expect(tap.rows.filter((row) => row.body.kind === 'status')).toEqual([]) + }) + it('writes nothing more after dispose', () => { const { translator, tap, window } = translatorWith() diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts index ee7d10934a6..54f6f9c7e86 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts @@ -330,8 +330,8 @@ export class CodexStructuredSessionAdapter implements SessionAdapter { projectOptions = (sessionId: string, options: Readonly>) => projectCodexSessionOptions(this.sessions.get(sessionId), options) - closeSession: NonNullable = (...args) => - this.teardown.close(...args) + closeSession: NonNullable = (sessionId, observeClose) => + this.teardown.close(sessionId, observeClose) forceCloseSession = (sessionId: string): Promise => this.teardown.forceClose(sessionId) disposeSession: NonNullable = this.closeSession closeAll = (): Promise => this.teardown.closeAll() diff --git a/src/main/ephemeral-vm/runtime-resume-pairing.test.ts b/src/main/ephemeral-vm/runtime-resume-pairing.test.ts index 8fe94cfd5d8..1cb7937226d 100644 --- a/src/main/ephemeral-vm/runtime-resume-pairing.test.ts +++ b/src/main/ephemeral-vm/runtime-resume-pairing.test.ts @@ -7,8 +7,7 @@ import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairin import { addEnvironmentFromPairingCode, listEnvironments, - resolveEnvironmentPairingOffer, - updateEnvironmentFromPairingCode + resolveEnvironmentPairingOffer } from '../../shared/remote-runtime/host-store/runtime-environment-store' import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error' import { DeviceRegistry } from '../runtime/rpc/server/pairing/device-registry' @@ -114,17 +113,6 @@ describe('resuming a recipe VM server', () => { expect(listEnvironments(desktopDataPath)[0]!.pairingRevision).toBe(before.pairingRevision) }) - it('grows one device row per resume when every resume re-pairs (previous behaviour)', () => { - const environmentId = provision() - for (let cycle = 1; cycle <= 20; cycle++) { - updateEnvironmentFromPairingCode(desktopDataPath, environmentId, { - pairingCode: bootVm(serverDataPath, `wss://vm-${cycle}.example/runtime`) - }) - connect(serverDataPath, desktopDataPath, environmentId) - } - expect(new DeviceRegistry(serverDataPath).listDevices()).toHaveLength(21) - }) - it('leaves the store untouched but still drops the transport when nothing moved', async () => { const environmentId = provision() const before = listEnvironments(desktopDataPath)[0]! diff --git a/src/main/git/clone-target-check.test.ts b/src/main/git/clone-target-check.test.ts new file mode 100644 index 00000000000..53ec030409c --- /dev/null +++ b/src/main/git/clone-target-check.test.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import type { Repo } from '../../shared/repo-types' +import { checkCloneTarget } from './clone-target-check' +import { getClonePathComparisonKey } from './repo-clone-path' + +const roots: string[] = [] + +function parentFolder(): string { + const root = mkdtempSync(join(tmpdir(), 'orca-clone-target-')) + roots.push(root) + return root +} + +function savedClone(path: string, originUrl: string): Repo { + execFileSync('git', ['init', '-q', path]) + execFileSync('git', ['-C', path, 'remote', 'add', 'origin', originUrl]) + execFileSync('git', [ + '-C', + path, + '-c', + 'user.name=t', + '-c', + 'user.email=t@t.invalid', + 'commit', + '-q', + '--allow-empty', + '-m', + 'init' + ]) + return { + id: path, + path, + displayName: 'orca-plugins', + badgeColor: '#fff', + addedAt: 1, + kind: 'git' + } +} + +const check = (repos: Repo[], url: string, destination: string) => + checkCloneTarget( + { url, destination }, + (keys) => repos.find((repo) => keys.includes(getClonePathComparisonKey(repo.path))), + LOCAL_EXECUTION_HOST_ID + ) + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describe('checkCloneTarget', () => { + it('suggests an owner-named folder when a same-named repository from another owner is there', async () => { + const parent = parentFolder() + const official = savedClone( + join(parent, 'orca-plugins'), + 'https://github.com/stablyai/orca-plugins.git' + ) + + await expect( + check([official], 'https://github.com/aamonnaig4/orca-plugins', parent) + ).resolves.toEqual({ + status: 'taken', + folderName: 'orca-plugins', + reason: 'other-repository', + suggestedFolderName: 'orca-plugins-aamonnaig4' + }) + + mkdirSync(join(parent, 'orca-plugins-aamonnaig4')) + writeFileSync(join(parent, 'orca-plugins-aamonnaig4', 'notes.txt'), '') + await expect( + check([official], 'git@github.com:aamonnaig4/orca-plugins.git', parent) + ).resolves.toMatchObject({ status: 'taken', suggestedFolderName: 'orca-plugins-2' }) + }) + + it('leaves the default folder alone when it already holds this repository', async () => { + const parent = parentFolder() + const official = savedClone( + join(parent, 'orca-plugins'), + 'https://github.com/stablyai/orca-plugins.git' + ) + + await expect( + check([official], 'git@github.com:stablyai/orca-plugins.git', parent) + ).resolves.toEqual({ status: 'free', folderName: 'orca-plugins' }) + }) +}) diff --git a/src/main/git/clone-target-check.ts b/src/main/git/clone-target-check.ts new file mode 100644 index 00000000000..dbd2ac5b305 --- /dev/null +++ b/src/main/git/clone-target-check.ts @@ -0,0 +1,87 @@ +import { basename, join } from 'node:path' +import { lstat, readdir } from 'node:fs/promises' +import type { ExecutionHostId } from '../../shared/execution-host' +import type { CloneTargetArgs, CloneTargetCheck } from '../../shared/git/clone/clone-target-check' +import { isFolderRepo } from '../../shared/repo-kind' +import type { Repo } from '../../shared/repo-types' +import { + deriveCloneOwnerFromUrl, + deriveValidatedClonePath, + getSavedProjectPathKeys +} from './repo-clone-path' +import { reuseSavedCloneTarget } from './saved-clone-target' + +/** Finds the project saved at any of these path keys on the clone's host. */ +export type FindSavedCloneProject = (pathKeys: string[]) => Repo | undefined + +const MAX_NUMBERED_SUGGESTIONS = 20 + +/** Git refuses a non-empty destination, and reuseSavedCloneTarget refuses another repository's project. */ +async function findCloneTargetConflict( + clonePath: string, + url: string, + findSaved: FindSavedCloneProject, + hostId: ExecutionHostId +): Promise<'other-repository' | 'not-empty' | null> { + const pathKeys = await getSavedProjectPathKeys(clonePath) + const saved = findSaved(pathKeys) + if (saved && !isFolderRepo(saved)) { + try { + await reuseSavedCloneTarget(() => findSaved(pathKeys), url, hostId) + return null + } catch { + return 'other-repository' + } + } + return (await isNonEmptyPath(clonePath)) ? 'not-empty' : null +} + +async function isNonEmptyPath(path: string): Promise { + try { + const stats = await lstat(path) + return !stats.isDirectory() || (await readdir(path)).length > 0 + } catch { + // Missing or unreadable: the clone itself reports anything other than a free folder. + return false + } +} + +async function suggestFreeFolderName( + args: CloneTargetArgs, + folderName: string, + findSaved: FindSavedCloneProject, + hostId: ExecutionHostId +): Promise { + const owner = deriveCloneOwnerFromUrl(args.url) + const candidates = [ + ...(owner ? [`${folderName}-${owner}`] : []), + ...Array.from({ length: MAX_NUMBERED_SUGGESTIONS }, (_, i) => `${folderName}-${i + 2}`) + ] + for (const candidate of candidates) { + // A candidate already holding this repository's project is fine: the clone reuses it. + const path = join(args.destination, candidate) + if (!(await findCloneTargetConflict(path, args.url, findSaved, hostId))) { + return candidate + } + } + return null +} + +export async function checkCloneTarget( + args: CloneTargetArgs, + findSaved: FindSavedCloneProject, + hostId: ExecutionHostId +): Promise { + const clonePath = deriveValidatedClonePath(args) + const folderName = basename(clonePath) + const reason = await findCloneTargetConflict(clonePath, args.url, findSaved, hostId) + if (!reason) { + return { status: 'free', folderName } + } + return { + status: 'taken', + folderName, + reason, + suggestedFolderName: await suggestFreeFolderName(args, folderName, findSaved, hostId) + } +} diff --git a/src/main/git/repo-clone-path.ts b/src/main/git/repo-clone-path.ts index 1186656f6dd..726ae5f026a 100644 --- a/src/main/git/repo-clone-path.ts +++ b/src/main/git/repo-clone-path.ts @@ -15,25 +15,46 @@ export type ClaimedCloneTarget = { type CloneDirectoryIdentity = Pick -export function deriveCloneRepoNameFromUrl(url: string): string { - // Reject dot destinations before cleanup could remove a parent or unrelated folder. +/** Path part of a clone source: scp-style host prefixes removed, URL schemes kept. */ +function cloneSourcePath(url: string): { path: string; windows: boolean } { const source = url.replace(/\.git\/?$/, '') - const isWindowsLocalSource = /^[A-Za-z]:[\\/]/.test(source) || source.startsWith('\\\\') - const scpPath = - !isWindowsLocalSource && !source.includes('://') - ? source.match(/^(?:[^@/:]+@)?(?:\[[^\]]+\]|[^:/\s]+):(.+)$/)?.[1] - : undefined - const repoName = isWindowsLocalSource ? win32.basename(source) : posix.basename(scpPath ?? source) - if (!repoName || repoName === '.' || repoName === '..') { - throw new Error('Invalid repository name derived from URL') + if (/^[A-Za-z]:[\\/]/.test(source) || source.startsWith('\\\\')) { + return { path: source, windows: true } } - if (repoName.includes('/') || repoName.includes('\\')) { - throw new Error('Invalid repository name derived from URL') - } - return repoName + const scpPath = !source.includes('://') + ? source.match(/^(?:[^@/:]+@)?(?:\[[^\]]+\]|[^:/\s]+):(.+)$/)?.[1] + : undefined + return { path: scpPath ?? source, windows: false } } -export function deriveValidatedClonePath(args: { url: string; destination: string }): string { +function assertCloneFolderName(name: string, message: string): string { + if (!name || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) { + throw new Error(message) + } + return name +} + +export function deriveCloneRepoNameFromUrl(url: string): string { + // Reject dot destinations before cleanup could remove a parent or unrelated folder. + const { path, windows } = cloneSourcePath(url) + const repoName = windows ? win32.basename(path) : posix.basename(path) + return assertCloneFolderName(repoName, 'Invalid repository name derived from URL') +} + +/** The segment above the repository (GitHub owner, GitLab group), or null when there is none. */ +export function deriveCloneOwnerFromUrl(url: string): string | null { + const { path, windows } = cloneSourcePath(url) + const pathOps = windows ? win32 : posix + const repoPath = windows ? path : path.replace(/^[a-z][\w+.-]*:\/\/[^/]*/i, '') + const owner = pathOps.basename(pathOps.dirname(repoPath)) + return owner && owner !== '.' && owner !== '..' && !owner.includes(':') ? owner : null +} + +export function deriveValidatedClonePath(args: { + url: string + destination: string + folderName?: string +}): string { if ( !args.destination || !isAbsolute(args.destination) || @@ -42,7 +63,10 @@ export function deriveValidatedClonePath(args: { url: string; destination: strin throw new Error('Clone destination must be an absolute path') } - const repoName = deriveCloneRepoNameFromUrl(args.url) + const requestedFolderName = args.folderName?.trim() + const repoName = requestedFolderName + ? assertCloneFolderName(requestedFolderName, 'Invalid clone folder name') + : deriveCloneRepoNameFromUrl(args.url) const clonePath = join(args.destination, repoName) const resolvedDestination = resolve(args.destination) diff --git a/src/main/git/saved-clone-target.ts b/src/main/git/saved-clone-target.ts index f264f3c173f..998c69e009d 100644 --- a/src/main/git/saved-clone-target.ts +++ b/src/main/git/saved-clone-target.ts @@ -138,6 +138,6 @@ export async function reuseSavedCloneTarget( storedOrigin ? 'Orca has that project recorded as a different repository' : 'Orca has no record of which repository that project holds, so it cannot tell whether the folder is missing or holds something else' - }. Remove the project from Orca or choose another folder.` + }. Clone into a different folder name, or remove the project from Orca.` ) } diff --git a/src/main/host/electron-browser-commands.ts b/src/main/host/electron-browser-commands.ts index ae3a0858879..5bb39288dcb 100644 --- a/src/main/host/electron-browser-commands.ts +++ b/src/main/host/electron-browser-commands.ts @@ -1,3 +1,4 @@ +import { desktopBrowserExtensions } from '../browser/extensions/browser-extension-commands' import { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' import { setRuntimeBrowserCommandsFactory } from '../runtime/browser/installation/runtime-browser-commands-factory' import { setBrowserHostClientProfileResolver } from '../runtime/browser-host/profiles/browser-host-client-profile-metadata' @@ -9,7 +10,8 @@ import { deleteManagedBrowserProfile } from '../browser/sessions/profiles/browse export function installElectronBrowserCommands(): void { setRuntimeBrowserCommandsFactory((host) => new RuntimeBrowserCommands(host), { supportsGoogleCookieClear: () => true, - clientHosting: true + clientHosting: true, + extensions: desktopBrowserExtensions }) setBrowserHostClientProfileResolver((browserProfileId) => { const profile = browserSessionRegistry.getProfile(browserProfileId) diff --git a/src/main/ipc/agent-pane-retirement-ipc.test.ts b/src/main/ipc/agent-pane-retirement-ipc.test.ts index a2db1dd1bec..5fd961719d9 100644 --- a/src/main/ipc/agent-pane-retirement-ipc.test.ts +++ b/src/main/ipc/agent-pane-retirement-ipc.test.ts @@ -30,12 +30,9 @@ beforeEach(() => { }) describe('pane retirement IPC request identity', () => { - it.each([null, '', 'bad-id', 42, {}, `${id} `])( - 'rejects malformed request identity %j', - (requestId) => { - mocks.handlers.get('agentStatus:retirePaneAuthority')?.({}, paneKey, requestId) - expect(mocks.retire).not.toHaveBeenCalled() - expect(mocks.clear).not.toHaveBeenCalled() - } - ) + it.each([null, 'bad-id', `${id} `])('rejects malformed request identity %j', (requestId) => { + mocks.handlers.get('agentStatus:retirePaneAuthority')?.({}, paneKey, requestId) + expect(mocks.retire).not.toHaveBeenCalled() + expect(mocks.clear).not.toHaveBeenCalled() + }) }) diff --git a/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts b/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts index 734d9d7cb0b..550f1e43618 100644 --- a/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts +++ b/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts @@ -73,21 +73,7 @@ describe('browser:publishClientPageMetadata', () => { it.each([ ['no environment', { environmentId: '', params: PARAMS }], ['a non-string environment', { environmentId: 7, params: PARAMS }], - ['no params at all', { environmentId: 'environment-a' }], - [ - 'a revision below the protocol floor', - { - environmentId: 'environment-a', - params: { ...PARAMS, revision: 0 } - } - ], - [ - 'a page id the protocol rejects', - { - environmentId: 'environment-a', - params: { ...PARAMS, browserPageId: '' } - } - ] + ['no params at all', { environmentId: 'environment-a' }] ])('refuses %s without reaching the lease', async (_case, args) => { await expect(publishMetadata(args)).resolves.toEqual({ status: 'refused' }) expect(mocks.publish).not.toHaveBeenCalled() diff --git a/src/main/ipc/codex-config-sync.test.ts b/src/main/ipc/codex-config-sync.test.ts index 33f1933dc47..7136807dfd5 100644 --- a/src/main/ipc/codex-config-sync.test.ts +++ b/src/main/ipc/codex-config-sync.test.ts @@ -65,19 +65,6 @@ describe('codexConfigSync:status handler', () => { }) }) - it('reports synced when the selection runs directly on the real home', () => { - // System default uses no mirror; stale shared homes must not produce warnings. - const staleSharedHome = join(root, 'codex-runtime-home', 'home') - mkdirSync(staleSharedHome, { recursive: true }) - writeFileSync(join(staleSharedHome, 'config.toml'), 'model = "stale"\n', 'utf-8') - - expect(invokeHandler(null)).toEqual({ - state: 'synced', - reason: null, - systemConfigPath: join(root, '.codex', 'config.toml') - }) - }) - it('reports a stall when the selected home baseline cannot be read', () => { const perAccountHome = join(root, 'codex-accounts', 'acct-1', 'home') mkdirSync(perAccountHome, { recursive: true }) diff --git a/src/main/ipc/filesystem/filesystem-mutations.test.ts b/src/main/ipc/filesystem/filesystem-mutations.test.ts index cea6a25543c..2eb47d4b578 100644 --- a/src/main/ipc/filesystem/filesystem-mutations.test.ts +++ b/src/main/ipc/filesystem/filesystem-mutations.test.ts @@ -85,17 +85,6 @@ describe('registerFilesystemMutationHandlers', () => { registerFilesystemMutationHandlers(store as never) }) - it('rejects file creation when path already exists (wx flag)', async () => { - // wx rejects collisions atomically without an existence-check race. - writeFileMock.mockRejectedValue(Object.assign(new Error('EEXIST'), { code: 'EEXIST' })) - - await expect( - handlers.get('fs:createFile')!(null, { - filePath: path.resolve('/workspace/repo/existing.ts') - }) - ).rejects.toThrow("A file or folder named 'existing.ts' already exists in this location") - }) - it('rejects file creation outside allowed roots', async () => { mockRealpath({ [path.resolve('/workspace/repo/link.ts')]: path.resolve('/private/secret.ts') diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts index 3f08f58d0a8..30e6077d2c8 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts @@ -1,3 +1,4 @@ +// @orca-isolated-worker: initial capacity requires a fresh process-wide registry. import { afterEach, describe, expect, it, vi } from 'vitest' import { MAX_PHYSICAL_WATCHER_CHILDREN, diff --git a/src/main/ipc/mobile.test.ts b/src/main/ipc/mobile.test.ts index 95dfe0f9c20..87b303a5f91 100644 --- a/src/main/ipc/mobile.test.ts +++ b/src/main/ipc/mobile.test.ts @@ -1,34 +1,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeOs from 'node:os' -const { defaultRouteInterfaceNamesMock, handleMock, networkInterfacesMock } = vi.hoisted(() => ({ - defaultRouteInterfaceNamesMock: vi.fn(), - handleMock: vi.fn(), - networkInterfacesMock: vi.fn() -})) +const { handleMock } = vi.hoisted(() => ({ handleMock: vi.fn() })) vi.mock('electron', () => ({ app: { isPackaged: false }, ipcMain: { handle: handleMock }, shell: { openExternal: vi.fn() } })) - -vi.mock('qrcode', () => ({ - default: { - create: vi.fn().mockReturnValue({ modules: { size: 21 } }), - toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,qr') - } -})) - -// Mock interface enumeration only; integration fixtures still need real os.tmpdir. -vi.mock('os', async (importOriginal) => ({ - ...(await importOriginal()), - networkInterfaces: networkInterfacesMock -})) - -vi.mock('../runtime/rpc/server/pairing/network/windows-default-route-interfaces', () => ({ - getWindowsDefaultRouteInterfaceNames: defaultRouteInterfaceNamesMock -})) import { registerMobileHandlers } from './mobile' describe('registerMobileHandlers', () => { @@ -37,58 +15,11 @@ describe('registerMobileHandlers', () => { beforeEach(() => { handlers.clear() handleMock.mockReset() - networkInterfacesMock.mockReset() - networkInterfacesMock.mockReturnValue({}) - defaultRouteInterfaceNamesMock.mockReset().mockResolvedValue(new Set()) handleMock.mockImplementation((channel: string, handler: (...args: unknown[]) => unknown) => { handlers.set(channel, handler) }) }) - // All accepted loopback spellings must honor an explicit this-computer reach. - - // Custom loopback frontends can tunnel to this host's LAN address; do not infer local-only intent from their shape. - - it('mints desktop pairing offers with the QR and link TTLs and returns their expiry', async () => { - const createMobilePairingOffer = vi.fn().mockResolvedValue({ - available: true, - pairingUrl: 'orca://pair#mobile', - endpoint: 'ws://192.168.1.24:6768', - deviceId: 'mobile-1', - connectionMode: 'automatic', - offerExpiresAt: 1_000 - }) - const createPairingOffer = vi.fn().mockReturnValue({ - available: true, - pairingUrl: 'orca://pair#runtime', - webClientUrl: 'http://192.168.1.24:6768/web-index.html?pairing=runtime', - endpoint: 'ws://192.168.1.24:6768', - deviceId: 'runtime-1', - offerExpiresAt: 2_000 - }) - registerMobileHandlers( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers only call the three stubbed server members. - { - createMobilePairingOffer, - createPairingOffer, - ensureNetworkExposure: vi.fn().mockResolvedValue(undefined) - } as never - ) - - await expect( - handlers.get('mobile:getPairingQR')?.(null, { address: '192.168.1.24' }) - ).resolves.toMatchObject({ available: true, expiresAt: 1_000 }) - expect(createMobilePairingOffer).toHaveBeenCalledWith( - expect.objectContaining({ offerTtlMs: 10 * 60_000 }) - ) - await expect( - handlers.get('mobile:getRuntimePairingUrl')?.(null, { address: '192.168.1.24' }) - ).resolves.toMatchObject({ available: true, expiresAt: 2_000 }) - expect(createPairingOffer).toHaveBeenCalledWith( - expect.objectContaining({ offerTtlMs: 60 * 60_000 }) - ) - }) - it('rejects firewall mutation from a non-window renderer', async () => { const runPowerShell = vi.fn() const rpcServer = { getWebSocketEndpoint: () => 'ws://0.0.0.0:6768' } diff --git a/src/main/ipc/profiles/orca-profiles.test.ts b/src/main/ipc/profiles/orca-profiles.test.ts deleted file mode 100644 index bc1f3665038..00000000000 --- a/src/main/ipc/profiles/orca-profiles.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import type * as NewProfileStateModule from '../../orca-profiles/new-profile-state' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ProfileStoragePaths from '../../orca-profiles/profile-storage-paths' -import type * as ProfileCloudService from '../../orca-profiles/profile-cloud-service' - -const { - handlers, - appExitMock, - appQuitMock, - appRelaunchMock, - relaunchAppMock, - destroySystemTrayMock, - createLocalOrcaProfileMock, - createCloudLinkedOrcaProfileMock, - getOrcaProfileListStateMock, - initializeNewOrcaProfileStateMock, - setActiveOrcaProfileMock, - transferOrcaProfileProjectMock, - hasOrcaProfileStateDatabaseMock -} = vi.hoisted(() => ({ - handlers: new Map unknown>(), - appExitMock: vi.fn(), - appQuitMock: vi.fn(), - appRelaunchMock: vi.fn(), - relaunchAppMock: vi.fn(), - destroySystemTrayMock: vi.fn(), - createLocalOrcaProfileMock: vi.fn(), - createCloudLinkedOrcaProfileMock: vi.fn(), - getOrcaProfileListStateMock: vi.fn(), - initializeNewOrcaProfileStateMock: vi.fn(), - setActiveOrcaProfileMock: vi.fn(), - transferOrcaProfileProjectMock: vi.fn(), - hasOrcaProfileStateDatabaseMock: vi.fn() -})) - -vi.mock('electron', () => ({ - app: { - exit: appExitMock, - quit: appQuitMock, - relaunch: appRelaunchMock - }, - ipcMain: { - handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { - handlers.set(channel, handler) - }) - } -})) - -vi.mock('../../tray/system-tray', () => ({ - destroySystemTray: destroySystemTrayMock -})) - -vi.mock('../../startup/quit/app-relaunch', () => ({ - relaunchApp: relaunchAppMock -})) - -vi.mock('../../orca-profiles/profile-index-store', () => ({ - createLocalOrcaProfile: createLocalOrcaProfileMock, - getOrcaProfileListState: getOrcaProfileListStateMock, - initializeNewOrcaProfileState: initializeNewOrcaProfileStateMock, - setActiveOrcaProfile: setActiveOrcaProfileMock -})) - -vi.mock('../../orca-profiles/new-profile-state', async (importOriginal) => ({ - ...(await importOriginal()), - initializeNewOrcaProfileState: initializeNewOrcaProfileStateMock -})) - -vi.mock('../../orca-profiles/profile-cloud-service', async (importOriginal) => ({ - ...(await importOriginal()), - createCloudLinkedOrcaProfile: createCloudLinkedOrcaProfileMock -})) - -function makeStoreMock(flushPendingOrThrowAsync = vi.fn()) { - const freezeWrites = vi.fn() - const resumeMaintenance = vi.fn(async () => {}) - return { - flushPendingOrThrowAsync, - freezeWrites, - resumeMaintenance, - beginProfileMaintenance: vi.fn(async (options: unknown) => { - await flushPendingOrThrowAsync(options) - freezeWrites() - return { resume: resumeMaintenance } - }), - getSettings: () => ({}) - } -} - -vi.mock('../../orca-profiles/profile-project-transfer', () => ({ - transferOrcaProfileProject: transferOrcaProfileProjectMock -})) - -vi.mock('../../orca-profiles/profile-storage-paths', async (importOriginal) => ({ - ...(await importOriginal()), - hasOrcaProfileStateDatabase: hasOrcaProfileStateDatabaseMock -})) - -import { registerOrcaProfileHandlers } from './orca-profiles' -import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' - -const ipcEvent = { sender: { isDestroyed: () => false, send: vi.fn() } } - -describe('registerOrcaProfileHandlers', () => { - beforeEach(() => { - // Reinstall AppEnvironment per test after global beforeEach resets its fake. - installFakeAppEnvironment({ getPath: () => '/tmp/orca-user-data' }) - vi.useFakeTimers() - handlers.clear() - ipcEvent.sender.send.mockClear() - appExitMock.mockReset() - appQuitMock.mockReset() - appRelaunchMock.mockReset() - relaunchAppMock.mockReset() - relaunchAppMock.mockImplementation(() => appRelaunchMock()) - destroySystemTrayMock.mockReset() - createLocalOrcaProfileMock.mockReset() - createCloudLinkedOrcaProfileMock.mockReset() - getOrcaProfileListStateMock.mockReset() - initializeNewOrcaProfileStateMock.mockReset() - setActiveOrcaProfileMock.mockReset() - transferOrcaProfileProjectMock.mockReset() - hasOrcaProfileStateDatabaseMock.mockReset().mockReturnValue(false) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('initializes the selected workspace for a newly created local profile', () => { - const created = { profile: { id: 'local-work', name: 'Work' } } - createLocalOrcaProfileMock.mockReturnValue(created) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Profile creation uses only the mocked store methods. - registerOrcaProfileHandlers(makeStoreMock() as never) - - expect(handlers.get('orcaProfiles:createLocal')?.(ipcEvent, { name: 'Work' })).toBe(created) - expect(initializeNewOrcaProfileStateMock).toHaveBeenCalledWith('local-work', undefined) - }) - - it('initializes Home for a newly created cloud-linked profile', async () => { - const created = { - status: 'created', - auth: { activeProfileId: 'local-default' }, - activeProfileId: 'local-default', - profiles: [], - profile: { id: 'cloud-1' } - } - createCloudLinkedOrcaProfileMock.mockResolvedValue(created) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Profile creation uses only the mocked store methods. - registerOrcaProfileHandlers(makeStoreMock() as never) - - await expect( - handlers.get('orcaProfiles:createCloudLinked')?.(ipcEvent, { orgId: 'org-1', name: 'Work' }) - ).resolves.toBe(created) - expect(initializeNewOrcaProfileStateMock).toHaveBeenCalledWith('cloud-1', undefined) - }) -}) diff --git a/src/main/ipc/pty-claude-agent-view-readiness.test.ts b/src/main/ipc/pty-claude-agent-view-readiness.test.ts index 0247392ffbe..98f2bf3f711 100644 --- a/src/main/ipc/pty-claude-agent-view-readiness.test.ts +++ b/src/main/ipc/pty-claude-agent-view-readiness.test.ts @@ -56,50 +56,47 @@ describe.each(['local', 'daemon'] as const)('%s PTY navigation readiness', (prov const { handlers, mainWindow, spawnAndGetEnv } = setupPtyIpcSuite() const { daemonSpawnAndGetEnv } = createDaemonActiveProviderFixtures({ handlers, mainWindow }) - it.each([false, true])( - 'spawns a plain shell while reconciliation is pending (navigation: %s)', - async (enabled) => { - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const config = join(tmpdir(), 'orca-spawn-pending-agent-view-config') - vi.stubEnv('CLAUDE_CONFIG_DIR', config) - const reconcileConfig = vi.fn(() => gate) - const service = new agentView.ClaudeAgentViewService( - join(tmpdir(), 'orca-spawn-pending-agent-view'), - { - reconcileConfig, - ensurePlugin: async () => join(tmpdir(), 'orca-spawn-agent-view-plugin'), - loginEnv: async () => ({ CLAUDE_CONFIG_DIR: config }), - listProfiles: async () => [] - } - ) - const settings = createGlobalSettingsFixture({ claudeSubagentNavigationEnabled: enabled }) - let reconciled = false - const reconcile = service.reconcile(settings).then(() => { - reconciled = true - }) - await vi.waitFor(() => expect(reconcileConfig).toHaveBeenCalledOnce()) - const serviceSpy = vi.spyOn(agentView, 'getClaudeAgentViewService').mockReturnValue(service) - let env: Record | undefined - const spawn = ( - provider === 'daemon' - ? daemonSpawnAndGetEnv({}, undefined, () => settings) - : spawnAndGetEnv({}, undefined, undefined, () => settings) - ).then((result) => { - env = result - }) - try { - await vi.waitFor(() => expect(env).toBeDefined()) - expect(reconciled).toBe(false) - expect(env).not.toHaveProperty('ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR') - } finally { - release() - await Promise.all([reconcile, spawn]) - serviceSpy.mockRestore() - vi.unstubAllEnvs() + it('spawns a plain shell while reconciliation is pending', async () => { + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + const config = join(tmpdir(), 'orca-spawn-pending-agent-view-config') + vi.stubEnv('CLAUDE_CONFIG_DIR', config) + const reconcileConfig = vi.fn(() => gate) + const service = new agentView.ClaudeAgentViewService( + join(tmpdir(), 'orca-spawn-pending-agent-view'), + { + reconcileConfig, + ensurePlugin: async () => join(tmpdir(), 'orca-spawn-agent-view-plugin'), + loginEnv: async () => ({ CLAUDE_CONFIG_DIR: config }), + listProfiles: async () => [] } + ) + const settings = createGlobalSettingsFixture({ claudeSubagentNavigationEnabled: true }) + let reconciled = false + const reconcile = service.reconcile(settings).then(() => { + reconciled = true + }) + await vi.waitFor(() => expect(reconcileConfig).toHaveBeenCalledOnce()) + const serviceSpy = vi.spyOn(agentView, 'getClaudeAgentViewService').mockReturnValue(service) + let env: Record | undefined + const spawn = ( + provider === 'daemon' + ? daemonSpawnAndGetEnv({}, undefined, () => settings) + : spawnAndGetEnv({}, undefined, undefined, () => settings) + ).then((result) => { + env = result + }) + try { + await vi.waitFor(() => expect(env).toBeDefined()) + expect(reconciled).toBe(false) + expect(env).not.toHaveProperty('ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR') + } finally { + release() + await Promise.all([reconcile, spawn]) + serviceSpy.mockRestore() + vi.unstubAllEnvs() } - ) + }) }) 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 fb6e84fec1f..1fb8d8d0e46 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 @@ -76,15 +76,14 @@ describe('a spawn by its folder, between quiesce and commit', () => { await expect(acceptCwd(cwd)).rejects.toBeInstanceOf(WslMoveProjectFencedError) }) - it.each([ - ['a floating terminal', 'global-floating-terminal'], - ['another project', 'repo-2::/x'], - ['a folder workspace', 'folder:folder-9'] - ])('refuses %s that starts in a moving folder', async (_label, worktreeId) => { - await expect(acceptCwd('/home/dev/repo-1/src', worktreeId)).rejects.toBeInstanceOf( - WslMoveProjectFencedError - ) - }) + it.each([['a folder workspace', 'folder:folder-9']])( + 'refuses %s that starts in a moving folder', + async (_label, worktreeId) => { + await expect(acceptCwd('/home/dev/repo-1/src', worktreeId)).rejects.toBeInstanceOf( + WslMoveProjectFencedError + ) + } + ) it('stops at the commit, once the host owns the folder', async () => { seedWslMoveCutover(userDataPath, cutover('move-1', 'destination-committed')) diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 434e9207253..af8b9c5fe8f 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -52,6 +52,7 @@ export function registerRepoHandlers( ipcMain.removeHandler('repos:pickFolders') ipcMain.removeHandler('repos:pickDirectory') ipcMain.removeHandler('repos:clone') + ipcMain.removeHandler('repos:checkCloneTarget') ipcMain.removeHandler('repos:cloneAbort') ipcMain.removeHandler('repos:isGitAvailable') ipcMain.removeHandler('repos:getDefaultCreateProjectParent') diff --git a/src/main/ipc/repos/repo-clone-lifecycle.ts b/src/main/ipc/repos/repo-clone-lifecycle.ts index 1cadfe8e428..bd68750b60e 100644 --- a/src/main/ipc/repos/repo-clone-lifecycle.ts +++ b/src/main/ipc/repos/repo-clone-lifecycle.ts @@ -10,6 +10,8 @@ import { DEFAULT_REPO_BADGE_COLOR } from '../../../shared/constants' import { getGitCloneFailureMessage } from '../../../shared/git/remotes/git-clone-failure-message' import { gitSpawnAfterWindowsEnvironmentReady, promptGuardGitEnv } from '../../git/runner' import { reuseSavedCloneTarget } from '../../git/saved-clone-target' +import { checkCloneTarget } from '../../git/clone-target-check' +import type { CloneTargetArgs } from '../../../shared/git/clone/clone-target-check' import { getRepoName, inspectGitRepoForRegistrationAsync } from '../../git/repo' import type { ClaimedCloneTarget } from '../../git/repo-clone-path' import { @@ -115,214 +117,217 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor } }) - ipcMain.handle( - 'repos:clone', - async (_event, args: { url: string; destination: string }): Promise => { - const clonePath = deriveValidatedClonePath(args) - const clonePathKey = getClonePathComparisonKey(clonePath) - let savedPathKeys: string[] = [] - // Remote projects can share this path string without belonging to this clone host. - const findSaved = (): Repo | undefined => - store - .getRepos() - .find( - (r) => - savedPathKeys.includes(getClonePathComparisonKey(r.path)) && - getRepoExecutionHostId(r) === LOCAL_EXECUTION_HOST_ID - ) - return runWithClonePathLock(clonePathKey, async () => { - await pendingAbortCleanupByPath.get(clonePathKey) - // Read after the lock so lookup sees what a queued clone of this path registered. - savedPathKeys = await getSavedProjectPathKeys(clonePath) - const cloneMetadataRef: { current: ActiveCloneMetadata | null } = { current: null } - let claimedTarget: ClaimedCloneTarget - let proc: Awaited> - // Register before saved-project reads so Cancel can abort those Git calls too. - const pendingController = new AbortController() - pendingLocalCloneControllers.add(pendingController) - try { - const reused = await reuseSavedCloneTarget( - findSaved, - args.url, - LOCAL_EXECUTION_HOST_ID, - pendingController.signal - ) - if (reused) { - emitRepoAdded('clone_url', true, true) - return reused - } - // Fresh installs may lack the destination used as the clone process cwd. - await mkdir(args.destination, { recursive: true }) - claimedTarget = await claimCloneTarget(clonePath) - // Stream progress to avoid execFile buffer limits; --progress also works without a TTY. - try { - // Destination cwd enables WSL routing; '--' prevents URL content from becoming Git flags. - proc = await gitSpawnAfterWindowsEnvironmentReady( - ['clone', '--progress', '--', args.url, clonePath], - { - cwd: args.destination, - // Host Git on purpose: the clone makes a new repo no project owns, even inside one. - hostGit: true, - admissionTier: 'interactive', - // Suppress Windows Git Credential Manager OAuth windows during noninteractive cloning (#7652). - env: promptGuardGitEnv(), - signal: pendingController.signal, - stdio: ['ignore', 'ignore', 'pipe'] - } - ) - } catch (err) { - await cleanupClaimedCloneTarget(clonePath, claimedTarget) - const message = err instanceof Error ? err.message : String(err) - throw new Error(`Clone failed: ${message}`) - } - } finally { - pendingLocalCloneControllers.delete(pendingController) + // Remote projects can share this path string without belonging to this clone host. + const findLocalSaved = (pathKeys: string[]): Repo | undefined => + store + .getRepos() + .find( + (r) => + pathKeys.includes(getClonePathComparisonKey(r.path)) && + getRepoExecutionHostId(r) === LOCAL_EXECUTION_HOST_ID + ) + + ipcMain.handle('repos:checkCloneTarget', (_event, args: CloneTargetArgs) => + checkCloneTarget(args, findLocalSaved, LOCAL_EXECUTION_HOST_ID) + ) + + ipcMain.handle('repos:clone', async (_event, args: CloneTargetArgs): Promise => { + const clonePath = deriveValidatedClonePath(args) + const clonePathKey = getClonePathComparisonKey(clonePath) + let savedPathKeys: string[] = [] + const findSaved = (): Repo | undefined => findLocalSaved(savedPathKeys) + return runWithClonePathLock(clonePathKey, async () => { + await pendingAbortCleanupByPath.get(clonePathKey) + // Read after the lock so lookup sees what a queued clone of this path registered. + savedPathKeys = await getSavedProjectPathKeys(clonePath) + const cloneMetadataRef: { current: ActiveCloneMetadata | null } = { current: null } + let claimedTarget: ClaimedCloneTarget + let proc: Awaited> + // Register before saved-project reads so Cancel can abort those Git calls too. + const pendingController = new AbortController() + pendingLocalCloneControllers.add(pendingController) + try { + const reused = await reuseSavedCloneTarget( + findSaved, + args.url, + LOCAL_EXECUTION_HOST_ID, + pendingController.signal + ) + if (reused) { + emitRepoAdded('clone_url', true, true) + return reused } - await new Promise((resolve, reject) => { - const generation = nextCloneGeneration++ - latestCloneGenerationByPath.set(clonePathKey, generation) - const metadata: ActiveCloneMetadata = { - path: clonePath, - pathKey: clonePathKey, - claimedTarget, - process: proc, - abortRequested: false, - generation, - pendingAbortCleanup: null, - resolvePendingAbortCleanup: null - } - cloneMetadataRef.current = metadata - activeClone = metadata - - let stderrTail = '' - let settled = false - proc.stderr!.on('data', (chunk: Buffer) => { - const text = chunk.toString() - stderrTail = (stderrTail + text).slice(-4096) - - // Git progress uses carriage-return fragments, matching the SSH clone parser. - emitCloneProgressFromText(mainWindow, text) - }) - - const finishClone = async ( - code: number | null, - signal: NodeJS.Signals | null, - err?: Error - ) => { - if (settled) { - return - } - settled = true - // Abort-and-retry may already have replaced the active process. - if (activeClone?.process === proc) { - activeClone = null + // Fresh installs may lack the destination used as the clone process cwd. + await mkdir(args.destination, { recursive: true }) + claimedTarget = await claimCloneTarget(clonePath) + // Stream progress to avoid execFile buffer limits; --progress also works without a TTY. + try { + // Destination cwd enables WSL routing; '--' prevents URL content from becoming Git flags. + proc = await gitSpawnAfterWindowsEnvironmentReady( + ['clone', '--progress', '--', args.url, clonePath], + { + cwd: args.destination, + // Host Git on purpose: the clone makes a new repo no project owns, even inside one. + hostGit: true, + admissionTier: 'interactive', + // Suppress Windows Git Credential Manager OAuth windows during noninteractive cloning (#7652). + env: promptGuardGitEnv(), + signal: pendingController.signal, + stdio: ['ignore', 'ignore', 'pipe'] } + ) + } catch (err) { + await cleanupClaimedCloneTarget(clonePath, claimedTarget) + const message = err instanceof Error ? err.message : String(err) + throw new Error(`Clone failed: ${message}`) + } + } finally { + pendingLocalCloneControllers.delete(pendingController) + } + await new Promise((resolve, reject) => { + const generation = nextCloneGeneration++ + latestCloneGenerationByPath.set(clonePathKey, generation) + const metadata: ActiveCloneMetadata = { + path: clonePath, + pathKey: clonePathKey, + claimedTarget, + process: proc, + abortRequested: false, + generation, + pendingAbortCleanup: null, + resolvePendingAbortCleanup: null + } + cloneMetadataRef.current = metadata + activeClone = metadata - const cloneSucceeded = !err && code === 0 && !signal - if (!cloneSucceeded) { - // Failed-clone cleanup belongs only to the process that created this target. - await cleanupOwnedCloneTarget(metadata) - } - if (metadata.abortRequested && !cloneSucceeded) { - settleCloneAbortCleanup(metadata) - } - if (latestCloneGenerationByPath.get(metadata.pathKey) === metadata.generation) { - latestCloneGenerationByPath.delete(metadata.pathKey) - } + let stderrTail = '' + let settled = false + proc.stderr!.on('data', (chunk: Buffer) => { + const text = chunk.toString() + stderrTail = (stderrTail + text).slice(-4096) - if (err) { - reject(new Error(`Clone failed: ${err.message}`)) - } else if (signal === 'SIGTERM') { - reject(new Error('Clone aborted')) - } else if (code === 0) { - resolve() - } else { - reject( - new Error(`Clone failed: ${getGitCloneFailureMessage(stderrTail, { clonePath })}`) - ) - } - } - - proc.on('error', (err) => { - void finishClone(null, null, err) - }) - - proc.on('close', (code, signal) => { - void finishClone(code, signal) - }) + // Git progress uses carriage-return fragments, matching the SSH clone parser. + emitCloneProgressFromText(mainWindow, text) }) - try { - // Clone may land in an existing folder project; upgrade it instead of duplicating registration. - savedPathKeys = await getSavedProjectPathKeys(clonePath) - const existing = findSaved() - if (existing) { - const conversion = await resolveClonedFolderConversion(store, existing) - const current = findSaved() - if ( - current && - conversion && - findExtraFolderWorkspaceIds(current, store.getAllWorktreeMeta()).length === 0 && - current.path === existing.path && - isFolderRepo(current) && - getRepoExecutionHostId(current) === getRepoExecutionHostId(existing) - ) { - const updated = store.updateRepo(current, { - kind: 'git', - ...conversion, - projectHostSetupMethod: 'cloned' - }) - if (updated) { - await prepareLocalWorktreeRootForRepo(store, updated) - invalidateAuthorizedRootsCache() - notifyReposChanged(mainWindow) - // Folder-to-Git conversion counts as new Git provisioning. - emitRepoAdded('clone_url', false, true) - return updated - } - } - // Recreating the folder loses its worktree root and invalidates cached authorization. - if (current) { - await prepareLocalWorktreeRootForRepo(store, current) - invalidateAuthorizedRootsCache() - notifyReposChanged(mainWindow) - emitRepoAdded('clone_url', true, true) - return current - } + const finishClone = async ( + code: number | null, + signal: NodeJS.Signals | null, + err?: Error + ) => { + if (settled) { + return + } + settled = true + // Abort-and-retry may already have replaced the active process. + if (activeClone?.process === proc) { + activeClone = null } - // Register Git's checkout path so the clone stays its own selected checkout. - const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath - const detected = await detectRepoIconAndUpstream({ - repoPath, - kind: 'git', - executionHostId: LOCAL_EXECUTION_HOST_ID - }) - const repo: Repo = { - id: randomUUID(), - path: repoPath, - displayName: getRepoName(clonePath), - badgeColor: DEFAULT_REPO_BADGE_COLOR, - ...detected, - addedAt: Date.now(), - kind: 'git', - externalWorktreeVisibilityLegacy: false, - projectHostSetupMethod: 'cloned' + const cloneSucceeded = !err && code === 0 && !signal + if (!cloneSucceeded) { + // Failed-clone cleanup belongs only to the process that created this target. + await cleanupOwnedCloneTarget(metadata) } - - store.addRepo(repo) - await prepareLocalWorktreeRootForRepo(store, repo) - invalidateAuthorizedRootsCache() - notifyReposChanged(mainWindow) - emitRepoAdded('clone_url', false, true) - return repo - } finally { - const metadata = cloneMetadataRef.current - if (metadata?.abortRequested) { + if (metadata.abortRequested && !cloneSucceeded) { settleCloneAbortCleanup(metadata) } + if (latestCloneGenerationByPath.get(metadata.pathKey) === metadata.generation) { + latestCloneGenerationByPath.delete(metadata.pathKey) + } + + if (err) { + reject(new Error(`Clone failed: ${err.message}`)) + } else if (signal === 'SIGTERM') { + reject(new Error('Clone aborted')) + } else if (code === 0) { + resolve() + } else { + reject( + new Error(`Clone failed: ${getGitCloneFailureMessage(stderrTail, { clonePath })}`) + ) + } } + + proc.on('error', (err) => { + void finishClone(null, null, err) + }) + + proc.on('close', (code, signal) => { + void finishClone(code, signal) + }) }) - } - ) + + try { + // Clone may land in an existing folder project; upgrade it instead of duplicating registration. + savedPathKeys = await getSavedProjectPathKeys(clonePath) + const existing = findSaved() + if (existing) { + const conversion = await resolveClonedFolderConversion(store, existing) + const current = findSaved() + if ( + current && + conversion && + findExtraFolderWorkspaceIds(current, store.getAllWorktreeMeta()).length === 0 && + current.path === existing.path && + isFolderRepo(current) && + getRepoExecutionHostId(current) === getRepoExecutionHostId(existing) + ) { + const updated = store.updateRepo(current, { + kind: 'git', + ...conversion, + projectHostSetupMethod: 'cloned' + }) + if (updated) { + await prepareLocalWorktreeRootForRepo(store, updated) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + // Folder-to-Git conversion counts as new Git provisioning. + emitRepoAdded('clone_url', false, true) + return updated + } + } + // Recreating the folder loses its worktree root and invalidates cached authorization. + if (current) { + await prepareLocalWorktreeRootForRepo(store, current) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + emitRepoAdded('clone_url', true, true) + return current + } + } + + // Register Git's checkout path so the clone stays its own selected checkout. + const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath + const detected = await detectRepoIconAndUpstream({ + repoPath, + kind: 'git', + executionHostId: LOCAL_EXECUTION_HOST_ID + }) + const repo: Repo = { + id: randomUUID(), + path: repoPath, + displayName: getRepoName(clonePath), + badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...detected, + addedAt: Date.now(), + kind: 'git', + externalWorktreeVisibilityLegacy: false, + projectHostSetupMethod: 'cloned' + } + + store.addRepo(repo) + await prepareLocalWorktreeRootForRepo(store, repo) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + emitRepoAdded('clone_url', false, true) + return repo + } finally { + const metadata = cloneMetadataRef.current + if (metadata?.abortRequested) { + settleCloneAbortCleanup(metadata) + } + } + }) + }) } diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.test.ts b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.test.ts index 32458ce43ee..57d579197a4 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.test.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.test.ts @@ -73,3 +73,83 @@ it.each([true, false])( }) } ) + +it.each([ + { tail: '', sourceEmpty: true, items: 0 }, + { tail: '{"type":"future-metadata"}', sourceEmpty: true, items: 0 }, + { tail: '{"message":{"role":"user","content":"existing prompt"}}', sourceEmpty: false, items: 0 }, + { + tail: '{"type":"future-turn","message":{"role":"user","content":"existing prompt"}}', + sourceEmpty: false, + items: 0 + }, + { tail: '{"type":"summary","message":null}', sourceEmpty: false, items: 0 }, + { tail: '{"type":"user","uuid":"u1"}', sourceEmpty: false, items: 0 }, + { tail: '{"type":7}', sourceEmpty: false, items: 0 }, + { tail: '{"type":""}', sourceEmpty: false, items: 0 }, + { tail: '{}', sourceEmpty: false, items: 0 }, + { tail: 'null', sourceEmpty: false, items: 0 }, + { tail: '[]', sourceEmpty: false, items: 0 }, + { tail: '{"type":"user","message":{"role":"us', sourceEmpty: false, items: 0 }, + { + tail: '{"type":"user","isMeta":true,"message":{"role":"user","content":"Local command"}}', + sourceEmpty: true, + items: 0 + }, + { + tail: '{"type":"user","isMeta":true,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"saved output"}]}}', + sourceEmpty: false, + items: 1, + shows: 'saved output' + }, + { + tail: '{"type":"user","message":{"role":"user","content":"/rename"}}', + sourceEmpty: false, + items: 1, + shows: '/rename' + }, + { + tail: '{"type":"user","message":{"role":"user","content":[{"type":"future-content","text":"existing prompt"}]}}', + sourceEmpty: false, + items: 0 + } +])( + 'reads a Claude file nothing was sent in as empty, unlike one with a turn it cannot decode: %j', + async ({ + tail, + sourceEmpty, + items, + shows + }: { + tail: string + sourceEmpty: boolean + items: number + shows?: string + }) => { + const filePath = join(root, 'claude-unused.jsonl') + const metadata = [ + { type: 'file-history-snapshot', messageId: 'm1', snapshot: { trackedFileBackups: {} } }, + { + type: 'summary', + summary: 'New session', + leafUuid: 'l1', + cwd: root, + sessionId: 'claude-unused' + } + ] + await writeFile(filePath, `${[...metadata.map((m) => JSON.stringify(m)), tail].join('\n')}\n`) + // Adoption always names the conversation it expects, as Continue in Chat's create does. + const source = { providerSessionId: 'claude-unused', workspaceCwd: root } + const prepared = await prepareLegacyTranscriptImport({ + agent: 'claude', + sessionId: 'claude-unused', + options: { filePath, source } + }) + expect(prepared.ok).toBe(true) + expect(prepared.ok && prepared.items.length).toBe(items) + if (shows) { + expect(JSON.stringify(prepared.ok && prepared.items)).toContain(shows) + } + expect(prepared.ok && prepared.sourceEmpty).toBe(sourceEmpty) + } +) diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts index 671148e67c4..bfc020a501c 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts @@ -16,6 +16,7 @@ import { resolveNativeChatTranscriptAgent } from '../../../../shared/native-chat import { resolveSessionFilePath, type ResolveSessionFileOptions } from '../../session-file-resolver' import { readLegacyImportTranscript, TRANSCRIPT_DECODERS } from './journal-legacy-transcript-stream' import { readOpenCodeNativeChatTranscriptFull } from '../../transcript-opencode' +import { mayBeClaudeConversationRecord } from '../../transcript-line-decoders-claude' import { createLegacyIdentityTracker } from './journal-legacy-identity' import { createPiTranscriptCollector } from './journal-pi-active-branch' import { createNewestItemWindow } from './journal-newest-item-window' @@ -107,7 +108,7 @@ export async function prepareLegacyTranscriptImport(input: { } try { - const { items, consumedBytes, forkTipItemIds } = await decodeReplacementItems({ + const { items, sourceEmpty, forkTipItemIds } = await decodeReplacementItems({ filePath, transcriptAgent, agent: input.agent, @@ -120,7 +121,7 @@ export async function prepareLegacyTranscriptImport(input: { decodedMessageIdentities: options.decodedMessageIdentities, limits }) - return { ok: true, items, sourceEmpty: consumedBytes === 0, forkTipItemIds } + return { ok: true, items, sourceEmpty, forkTipItemIds } } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err) } } @@ -213,7 +214,7 @@ async function decodeReplacementItems(input: { codexSessionsDirs?: string[] signal?: AbortSignal limits: JournalPayloadLimits -}): Promise<{ items: JournalReplacementItem[]; consumedBytes: number; forkTipItemIds: string[] }> { +}): Promise<{ items: JournalReplacementItem[]; sourceEmpty: boolean; forkTipItemIds: string[] }> { const source = input.source ? adoptedTranscriptSourceObserver({ agent: input.agent, @@ -241,6 +242,8 @@ async function decodeReplacementItems(input: { : null const forkTip = createImportedForkTip() let lineIndex = 0 + // A Claude file of metadata alone is one nothing was sent in; an undecodable turn still counts. + let conversation = input.transcriptAgent !== 'claude' try { const { consumedBytes } = await readLegacyImportTranscript( { @@ -261,6 +264,7 @@ async function decodeReplacementItems(input: { return null } const message = TRANSCRIPT_DECODERS[input.transcriptAgent](line, fallbackId) + conversation ||= !!message || mayBeClaudeConversationRecord(line) if (message) { const identity = recordId || input.decodedMessageIdentities @@ -285,13 +289,15 @@ async function decodeReplacementItems(input: { } : undefined ) - if (consumedBytes > 0) { + // A file with no conversation adopts nothing, so it has no identity to prove. + if (consumedBytes > 0 && conversation) { await source?.validate() } if (pi) { await pi.project(retained.push) } - return { items: retained.items(), consumedBytes, forkTipItemIds: forkTip.settledItems() } + const sourceEmpty = consumedBytes === 0 || !conversation + return { items: retained.items(), sourceEmpty, forkTipItemIds: forkTip.settledItems() } } finally { pi?.close() } diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command.test.ts index 0caee9c3dc9..0ca17eca0c0 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command.test.ts @@ -175,4 +175,11 @@ describe('same-conversation clear', () => { store.getOperationRow(caller.callerKey, params.envelope.clientOperationId)?.outcome.status ).toBe('succeeded') }) + + it('stops the old agent with a brief grace, since the divider waits on that stop', async () => { + await clearCommits() + expect(adapter.closeSession).toHaveBeenCalledWith(HOST_TEST_SESSION, undefined, { + grace: 'brief' + }) + }) }) diff --git a/src/main/native-chat/agent-session-wire/options/at-rest-command-catalog.ts b/src/main/native-chat/agent-session-wire/options/at-rest-command-catalog.ts index e5a15bf3bd8..cb6e01cd3ee 100644 --- a/src/main/native-chat/agent-session-wire/options/at-rest-command-catalog.ts +++ b/src/main/native-chat/agent-session-wire/options/at-rest-command-catalog.ts @@ -11,6 +11,12 @@ import { atRestCommandContextReady } from './at-rest-command-context' import { stat } from 'node:fs/promises' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { + type AtRestCommandStamp, + type AtRestCommandStamped, + rescanIfStampChanged, + stampBeforeScan +} from './at-rest-command-stamp' /** Running chats supply their own lists; rescan resting folders/accounts after this TTL. */ export const AT_REST_COMMANDS_TTL_MS = 5 * 60_000 @@ -40,6 +46,8 @@ export type AtRestCommandSource = { admitted: () => void, demand: AtRestCommandDemand ) => Promise + /** A menu open rescans before the TTL once this changes. */ + stamp?: AtRestCommandStamp scanTimeoutMs?: number maxFailedScans?: number | null evictUnreadMs?: number | null @@ -66,6 +74,8 @@ type Entry = { attempt?: AbortController lastReadAt: number settled: Set<() => void> + stamped?: AtRestCommandStamped + restamping?: Promise } /** Cache commands from each resting chat’s launch folder; publish changed scan results. */ @@ -79,7 +89,10 @@ export class AtRestCommandCatalog implements StructuredAgentSessionAtRestCommand constructor(private readonly source: AtRestCommandSource) {} retireContext = (workspaceId?: string): void => { - this.generation += 1 + // One folder's retirement keeps the launch context other folders' probes share. + if (workspaceId === undefined) { + this.generation += 1 + } for (const [key, entry] of this.entries) { if (workspaceId !== undefined && entry.workspaceId !== workspaceId) { continue @@ -127,6 +140,15 @@ export class AtRestCommandCatalog implements StructuredAgentSessionAtRestCommand settled = async (record: AgentSessionRecord, budgetMs: number, independent = false) => { const deadline = Date.now() + budgetMs + // Menu opens only; dispose empties entries, so a disposed catalog finds none. + const opened = + independent && this.source.accepts(record) ? this.entries.get(this.key(record)) : undefined + if (opened && this.source.stamp) { + const owned = (): boolean => this.entries.get(opened.key) === opened + await rescanIfStampChanged(opened, this.source.stamp, owned, () => + this.scanInto(opened, record, true) + ) + } for (;;) { const entry = this.readEntry(record, independent) if (!entry) { @@ -229,7 +251,7 @@ export class AtRestCommandCatalog implements StructuredAgentSessionAtRestCommand admittedAt ??= this.now() } entry.scanning = true - void (async () => { + void (async (): Promise => { const wait = (work: Promise): Promise => waitForPromiseWithSignal(work, attempt.signal) await wait(Promise.resolve(atRestCommandContextReady())) @@ -252,19 +274,21 @@ export class AtRestCommandCatalog implements StructuredAgentSessionAtRestCommand } return { commands: undefined, fromAgent: false } } + const stamped = await wait(stampBeforeScan(this.source.stamp, chat, cwd, attempt.signal)) const answer = await wait( this.source.scan(chat, cwd, isCurrent, entry.generation, attempt.signal, admitted, demand) ) attempt.signal.throwIfAborted() - return answer + return { ...answer, stamped } })() .then( - ({ commands, fromAgent }) => { + ({ commands, fromAgent, stamped }) => { if (!isCurrent()) { return } entry.scannedAt = admittedAt ?? this.now() entry.failures = 0 + entry.stamped = stamped // Refresh settles even when fallback cannot supersede an agent-provided list. if (entry.fromAgent && !fromAgent) { return diff --git a/src/main/native-chat/agent-session-wire/options/at-rest-command-stamp.ts b/src/main/native-chat/agent-session-wire/options/at-rest-command-stamp.ts new file mode 100644 index 00000000000..a06092b51f6 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/options/at-rest-command-stamp.ts @@ -0,0 +1,61 @@ +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' + +/** Cheap fingerprint of what a scan reads; undefined when it can't be read in time. */ +export type AtRestCommandStamp = ( + record: AgentSessionRecord, + cwd: string, + signal: AbortSignal +) => Promise + +/** What the last good scan read, so a menu open can tell whether its sources changed since. */ +export type AtRestCommandStamped = { record: AgentSessionRecord; cwd: string; stamp: string } + +type StampedEntry = { + stamped?: AtRestCommandStamped + restamping?: Promise + scanning: boolean + failures: number +} + +/** Finished before the scan reads, so a change made while it runs still differs next time. */ +export async function stampBeforeScan( + stamp: AtRestCommandStamp | undefined, + record: AgentSessionRecord, + cwd: string, + signal: AbortSignal +): Promise { + // Never rejects: the scan may fail first and leave this unawaited. + const value = await stamp?.(record, cwd, signal).catch(() => undefined) + return value === undefined ? undefined : { record, cwd, stamp: value } +} + +/** Unchanged sources keep the cached list without starting a scan; concurrent opens share one check. */ +export function rescanIfStampChanged( + entry: StampedEntry, + stamp: AtRestCommandStamp, + owned: () => boolean, + rescan: () => void +): Promise | undefined { + const last = entry.stamped + // After a failed scan the catalog's retry schedule decides, not every menu open. + if (!last || entry.scanning || entry.failures > 0) { + return undefined + } + entry.restamping ??= stamp(last.record, last.cwd, new AbortController().signal) + .catch(() => undefined) + .then((value) => { + if ( + value !== undefined && + value !== last.stamp && + entry.stamped === last && + !entry.scanning && + owned() + ) { + rescan() + } + }) + .finally(() => { + entry.restamping = undefined + }) + return entry.restamping +} diff --git a/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts b/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts new file mode 100644 index 00000000000..c62864170c5 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts @@ -0,0 +1,77 @@ +import { tmpdir } from 'node:os' +import { describe, expect, it, vi } from 'vitest' +import { hostTestRestingOptionsRecord } from '../../host/testing/structured-agent-session-host-test-data' +import { AtRestCommandCatalog } from '../at-rest-command-catalog' + +function catalogWithSkills() { + let stamp = 'a' + let skills = ['old-skill'] + let scans = 0 + let failing = false + const catalog = new AtRestCommandCatalog({ + label: 'test', + accepts: () => true, + resolveWorkspacePath: async () => tmpdir(), + stamp: async () => stamp, + scan: async () => { + scans += 1 + if (failing) { + throw new Error('skills/list timed out') + } + return { + commands: skills.map((name) => ({ name, kind: 'skill' as const, path: `/s/${name}` })), + fromAgent: true + } + } + }) + return { + catalog, + scans: () => scans, + install: (name: string, nextStamp: string) => { + skills = [...skills, name] + stamp = nextStamp + }, + failScans: () => { + failing = true + } + } +} + +const names = (commands: { name: string }[] | undefined) => commands?.map(({ name }) => name) + +describe('at-rest commands before the TTL', () => { + it('rescans on a menu open once the skill sources changed', async () => { + const { catalog, scans, install } = catalogWithSkills() + const record = hostTestRestingOptionsRecord() + expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill']) + + install('perf-scan', 'b') + expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill', 'perf-scan']) + expect(scans()).toBe(2) + catalog.dispose() + }) + + it('keeps the cached list without a scan while the sources are unchanged', async () => { + const { catalog, scans } = catalogWithSkills() + const record = hostTestRestingOptionsRecord() + await catalog.settled(record, 1_000, true) + await catalog.settled(record, 1_000, true) + await catalog.settled(record, 1_000, true) + expect(scans()).toBe(1) + catalog.dispose() + }) + + it('leaves a failed rescan to the retry schedule instead of rescanning on every open', async () => { + const { catalog, scans, install, failScans } = catalogWithSkills() + const record = hostTestRestingOptionsRecord() + vi.spyOn(console, 'warn').mockImplementation(() => {}) + await catalog.settled(record, 1_000, true) + failScans() + install('perf-scan', 'b') + await catalog.settled(record, 1_000, true) + await catalog.settled(record, 1_000, true) + await catalog.settled(record, 1_000, true) + expect(scans()).toBe(2) + catalog.dispose() + }) +}) diff --git a/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts b/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts index 85bb374034c..cc31e15d12d 100644 --- a/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts +++ b/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts @@ -24,8 +24,16 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'thread/deleted': 'status-chrome', 'thread/unarchived': 'status-chrome', 'thread/closed': 'status-chrome', + 'thread/readState/changed': 'suppressed-benign', + 'thread/reverted': 'status-chrome', 'skills/changed': 'status-chrome', 'thread/name/updated': 'status-chrome', + 'thread/section/changed': 'suppressed-benign', + 'thread/attachment/updated': 'status-chrome', + 'thread/prediction/updated': 'suppressed-benign', + 'thread/queue/changed': 'status-chrome', + 'project/changed': 'suppressed-benign', + 'thread/project/updated': 'suppressed-benign', // Goal frames are the only authoritative evidence because goal calls are never emitted as items. 'thread/goal/updated': 'timeline-substantive', 'thread/goal/cleared': 'timeline-substantive', @@ -43,6 +51,7 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'item/started': 'timeline-substantive', 'item/autoApprovalReview/started': 'status-chrome', 'item/autoApprovalReview/completed': 'status-chrome', + 'autoApprovalReview/strictReviewRequired': 'status-chrome', 'item/completed': 'timeline-substantive', 'rawResponseItem/completed': 'suppressed-benign', 'rawResponse/completed': 'suppressed-benign', @@ -59,7 +68,9 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'item/mcpToolCall/progress': 'status-chrome', 'mcpServer/oauthLogin/completed': 'status-chrome', 'mcpServer/startupStatus/updated': 'status-chrome', + 'mcpServer/event/stream/notification': 'suppressed-benign', 'account/updated': 'status-chrome', + 'account/gatewayOAuth/changed': 'status-chrome', 'account/rateLimits/updated': 'suppressed-benign', 'app/list/updated': 'status-chrome', 'remoteControl/status/changed': 'status-chrome', @@ -72,6 +83,8 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'thread/compacted': 'timeline-substantive', 'model/rerouted': 'status-chrome', 'model/verification': 'status-chrome', + 'modelProvider/authRecoveryStarted': 'status-chrome', + 'modelProvider/authRecoveryCompleted': 'status-chrome', 'turn/moderationMetadata': 'suppressed-benign', 'model/safetyBuffering/updated': 'status-chrome', warning: 'error-surface', @@ -82,6 +95,9 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'fuzzyFileSearch/sessionCompleted': 'suppressed-benign', 'thread/realtime/started': 'status-chrome', 'thread/realtime/itemAdded': 'timeline-substantive', + 'thread/realtime/item/started': 'status-chrome', + 'thread/realtime/item/transcript/delta': 'stream-into-item', + 'thread/realtime/item/completed': 'timeline-substantive', 'thread/realtime/transcript/delta': 'stream-into-item', 'thread/realtime/transcript/done': 'timeline-substantive', 'thread/realtime/outputAudio/delta': 'stream-into-item', diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts index 1715f58ba09..3427d6bf0c6 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts @@ -231,17 +231,17 @@ export class StructuredAgentSessionAdapterRouter implements Adapter { return adapter.copyConversation(input) } - closeSession: NonNullable = (sessionId, observeClose) => - this.stopSession(sessionId, (adapter) => adapter.closeSession?.(sessionId, observeClose)) + closeSession: NonNullable = (...args) => + this.stopSession(args[0], (adapter) => adapter.closeSession?.(...args)) forceCloseSession = (sessionId: string): Promise => this.stopSession(sessionId, (adapter) => (adapter.forceCloseSession ?? adapter.closeSession)?.call(adapter, sessionId) ) - disposeSession: NonNullable = (sessionId, observeClose) => - this.stopSession(sessionId, (adapter) => - (adapter.disposeSession ?? adapter.closeSession)?.call(adapter, sessionId, observeClose) + disposeSession: NonNullable = (...args) => + this.stopSession(args[0], (adapter) => + (adapter.disposeSession ?? adapter.closeSession)?.call(adapter, ...args) ) private async stopSession( diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts index 6d787d22af4..8c897fb5c3d 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts @@ -1,4 +1,5 @@ import type { PrepareStructuredRewind } from './structured-agent-session-rewind-contract' +import type { ProviderProcessCloseOptions } from '../../../provider-process/provider-process-close' import type { NativeCopyCoverage } from '../../agent-session-journal/context-epochs/journal-history-origin' import type { StructuredAgentSessionConversationCopyInput } from './structured-agent-session-conversation-copy-input' import type { CodexAccountUsageRead } from '../../../rate-limits/codex-rpc-rate-limit-mapper' @@ -109,6 +110,8 @@ export type StructuredAgentSessionEndedEvent = { /** Absent means provider exit without extra detail; host faults retain their own classification. */ failure?: SubmissionRejectionFact cause: 'unexpected-exit' | 'requested-close' + /** An unexpected exit Orca caused by stopping the agent after its own failure; log only. */ + closedByOrca?: true deathEvidenceKind?: 'kill-delivered' /** Execution-host observations from a requested provider close, when available. */ processExit?: { @@ -345,11 +348,19 @@ export type StructuredAgentSessionAdapter = StructuredAgentSessionAdapterStop & }): Promise | undefined stopProviderNaming?(): void /** True proves child exit; root/processless verdicts throw only after finalization (stopAgentSessionProviderRoot). */ - closeSession?(sessionId: string, observeClose?: AgentSessionCloseObserver): Promise + closeSession?( + sessionId: string, + observeClose?: AgentSessionCloseObserver, + options?: ProviderProcessCloseOptions + ): Promise /** Sink-failure shutdown leaves exit recovery unexpected. */ forceCloseSession?(sessionId: string): Promise /** Teardown without requiring a future-resume cursor. */ - disposeSession?(sessionId: string, observeClose?: AgentSessionCloseObserver): Promise + disposeSession?( + sessionId: string, + observeClose?: AgentSessionCloseObserver, + options?: ProviderProcessCloseOptions + ): Promise /** Acknowledge only after dead-child, lease and journal ownership release. */ acknowledgeSessionRelease?(sessionId: string, acquisition?: AcquisitionReceipt): void } diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-close.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-close.ts index e928ffa32d0..13a933687c5 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-close.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-close.ts @@ -24,7 +24,7 @@ export async function joinStructuredAgentSessionChildClose( ): Promise { // Capture startup state before provider release loses that evidence. const unanswered = child.phase === 'starting' - const closed = await closeProviderRoot(context, sessionId, observeClose) + const closed = await closeProviderRoot(context, sessionId, child, observeClose) if (!closed) { return 'unverifiable' } @@ -71,7 +71,7 @@ export async function joinClosingStructuredAgentSessionChild( return { ok: true } } const unanswered = child.phase === 'starting' - const closing = closeProviderRoot(context, sessionId) + const closing = closeProviderRoot(context, sessionId, child) const closed = await (lock ? lock.wait(closing) : closing) if (closed) { const end = () => @@ -96,6 +96,7 @@ export async function joinClosingStructuredAgentSessionChild( function closeProviderRoot( context: StructuredAgentSessionLifetimeContext, sessionId: string, + child: StructuredAgentSessionProviderChild, observeClose?: AgentSessionCloseObserver ): Promise { const { adapter, logger } = context.deps @@ -107,7 +108,12 @@ function closeProviderRoot( return stopAgentSessionProviderRoot( async () => { const close = adapter.disposeSession ?? adapter.closeSession - return (await close?.call(adapter, sessionId, observeClose)) === true + // The clear's divider waits on this stop, so the old agent gets only a brief grace. + const closing = + child.close?.cause === 'context-clear' + ? close?.call(adapter, sessionId, observeClose, { grace: 'brief' }) + : close?.call(adapter, sessionId, observeClose) + return (await closing) === true }, // Proven exit stands; descendant/follow-up failures are log-only. (error) => diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit-record.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit-record.ts new file mode 100644 index 00000000000..c77b1f82789 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit-record.ts @@ -0,0 +1,29 @@ +import type { SubmissionRejectionFact } from '../../../../shared/agent-session/failures/agent-session-failure' +import type { StructuredAgentSessionEndedEvent } from '../providers/structured-agent-session-adapter' + +export type StructuredAgentSessionChildExit = { + deathEvidenceKind?: 'kill-delivered' + heldSends?: ReadonlySet + expected: boolean + /** Log only; failure supplies user-facing wording. */ + reason: string + failure?: SubmissionRejectionFact + observedAt?: number + startupUnanswered?: true + /** Orca stopped the agent after its own failure; the exit stays unexpected for the turn. */ + closedByOrca?: true +} + +export function structuredAgentSessionEndedEventExit( + event: StructuredAgentSessionEndedEvent +): StructuredAgentSessionChildExit { + return { + expected: event.cause === 'requested-close', + ...(event.deathEvidenceKind ? { deathEvidenceKind: event.deathEvidenceKind } : {}), + reason: event.reason, + ...(event.failure ? { failure: event.failure } : {}), + ...(event.observedAt === undefined ? {} : { observedAt: event.observedAt }), + ...(event.startupUnanswered ? { startupUnanswered: event.startupUnanswered } : {}), + ...(event.closedByOrca ? { closedByOrca: true as const } : {}) + } +} diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts index fe82ef80f6c..66b8e459c31 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts @@ -1,10 +1,7 @@ // First-hand writer death evidence ends the child record in finally. Attempt/report every bookkeeping step; // expected changes presentation, never whether the dead child remains recorded. -import { - agentSessionFailureFact, - type SubmissionRejectionFact -} from '../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure' import { PROVIDER_EXIT_ROW_PREFIX } from '../../../../shared/agent-session/lifecycle/agent-session-stop-row-identity' import { isQueuedAgentJournalSubmission } from '../../../../shared/agent-session/requests/agent-session-queued-submission' import { structuredAgentSessionFailureWordsContext } from '../operations/structured-agent-session-send-preparation' @@ -33,21 +30,13 @@ import { } from './structured-agent-session-unfinished-work' import type { StructuredAgentSessionLogger } from '../host/structured-agent-session-logger' import { evictStructuredAgentSession } from './structured-agent-session-eviction' +import type { StructuredAgentSessionChildExit } from './structured-agent-session-child-exit-record' +import { structuredAgentSessionEndedEventExit } from './structured-agent-session-child-exit-record' +import { logExitFailure, logProviderChildExit } from './structured-agent-session-provider-exit-log' import type { StructuredAgentSessionHostRuntimeState } from '../host/structured-agent-session-host-runtime-state' import type { StructuredAgentSessionStartFlights } from '../startup/structured-agent-session-start-flight' import type { StructuredAgentSessionStartupAttempts } from '../startup/structured-agent-session-startup-attempt' -export type StructuredAgentSessionChildExit = { - deathEvidenceKind?: 'kill-delivered' - heldSends?: ReadonlySet - expected: boolean - /** Log only; failure supplies user-facing wording. */ - reason: string - failure?: SubmissionRejectionFact - observedAt?: number - startupUnanswered?: true -} - export type StructuredAgentSessionChildExitSession = Pick< StructuredAgentSessionHostSession, 'child' | 'lastEndedChild' @@ -117,18 +106,7 @@ export function settleStructuredAgentSessionChildExit< }) } -export function structuredAgentSessionEndedEventExit( - event: StructuredAgentSessionEndedEvent -): StructuredAgentSessionChildExit { - return { - expected: event.cause === 'requested-close', - ...(event.deathEvidenceKind ? { deathEvidenceKind: event.deathEvidenceKind } : {}), - reason: event.reason, - ...(event.failure ? { failure: event.failure } : {}), - ...(event.observedAt === undefined ? {} : { observedAt: event.observedAt }), - ...(event.startupUnanswered ? { startupUnanswered: event.startupUnanswered } : {}) - } -} +export { structuredAgentSessionEndedEventExit, type StructuredAgentSessionChildExit } export async function endExitedStructuredAgentSessionChildUnderSerialize< TSession extends StructuredAgentSessionChildExitSession @@ -189,6 +167,12 @@ export async function endExitedStructuredAgentSessionChildUnderSerialize< ...(exit.deathEvidenceKind ? { deathEvidenceKind: exit.deathEvidenceKind } : {}), ...(expected && close ? { endedAt: close.requestedAt } : {}) }) + logProviderChildExit(context.logger, sessionId, child, { + expected, + failure, + exit, + duringStartup: exitedDuringStartup + }) context.generationEnded(sessionId) const endChild = (): void => { context.startupAttempts?.childEnded(sessionId, child, { @@ -321,12 +305,3 @@ export async function endExitedStructuredAgentSessionChildUnderSerialize< wakeQueuedDelivery() } } - -function logExitFailure( - context: Pick, - sessionId: string, - scope: string, - error: unknown -): void { - context.logger.warn('settling a provider exit did not finish', { scope, sessionId, error }) -} diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-provider-exit-log.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-provider-exit-log.ts new file mode 100644 index 00000000000..9a7955b01f6 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-provider-exit-log.ts @@ -0,0 +1,57 @@ +import type { SubmissionRejectionFact } from '../../../../shared/agent-session/failures/agent-session-failure' +import { redactString } from '../../../observability/redactor' +import { startSpan } from '../../../observability/tracer' +import type { StructuredAgentSessionProviderChild } from '../host/structured-agent-session-host-types' +import type { StructuredAgentSessionLogger } from '../host/structured-agent-session-logger' +import type { StructuredAgentSessionChildExit } from './structured-agent-session-child-exit-record' + +/** One record per ended agent process naming who ended it, so a bare exit code is attributable. */ +export function logProviderChildExit( + logger: StructuredAgentSessionLogger, + sessionId: string, + child: Pick, + end: { + expected: boolean + exit: Pick + failure: SubmissionRejectionFact | undefined + duringStartup: boolean + } +): void { + const { close } = child + const fields = { + scope: 'provider-exit', + sessionId, + generation: child.generation, + // A close Orca made after its own failure still reads as unexpected to the turn. + endedBy: end.expected || close || end.exit.closedByOrca ? 'orca' : 'agent', + // The reason can carry the agent's stderr tail; the console line is not redacted downstream. + reason: redactString(end.exit.reason), + duringStartup: end.duringStartup, + ...(close + ? { closeCause: close.cause, closeReason: close.reason && redactString(close.reason) } + : {}), + ...(close?.quit ? { quit: true } : {}), + ...(end.failure ? { failure: end.failure.kind } : {}) + } + // A host-fault close counts as unexpected upstream, so it warns too. + if (!end.expected) { + logger.warn('agent process ended', fields) + return + } + // A requested end is normal; record it without a failed span. + try { + startSpan('agentSession.provider-exit', { attributes: fields }).end() + console.info('[agent-session] provider-exit: agent process ended by Orca', fields) + } catch { + // Diagnostics never fail the exit they describe. + } +} + +export function logExitFailure( + context: { logger: StructuredAgentSessionLogger }, + sessionId: string, + scope: string, + error: unknown +): void { + context.logger.warn('settling a provider exit did not finish', { scope, sessionId, error }) +} diff --git a/src/main/native-chat/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-line-decoders-claude.ts index 00290c78a84..2e256af18e4 100644 --- a/src/main/native-chat/transcript-line-decoders-claude.ts +++ b/src/main/native-chat/transcript-line-decoders-claude.ts @@ -209,3 +209,26 @@ function parseTimestamp(value: unknown): number | null { const parsed = timestampMs(value) return Number.isFinite(parsed) ? parsed : null } + +/** Anything but a typed record with no message, or a user record Claude flags as meta, may be a + * turn: what a transcript nothing was sent in lacks. */ +export function mayBeClaudeConversationRecord(line: string): boolean { + let record: unknown + try { + record = JSON.parse(line) + } catch { + return true + } + if (!record || typeof record !== 'object' || Array.isArray(record)) { + return true + } + // A local command's caveat or output; the decoder still keeps any meta record it can show. + if ('isMeta' in record && record.isMeta === true && 'type' in record && record.type === 'user') { + return false + } + if ('message' in record) { + return true + } + const type = 'type' in record ? record.type : undefined + return typeof type !== 'string' || !type.trim() || type === 'user' || type === 'assistant' +} diff --git a/src/main/opencode/opencode-root-model-launch.test.ts b/src/main/opencode/opencode-root-model-launch.test.ts index 4158475d6db..1913e5d1a21 100644 --- a/src/main/opencode/opencode-root-model-launch.test.ts +++ b/src/main/opencode/opencode-root-model-launch.test.ts @@ -29,16 +29,6 @@ const launch = (version: string, command: string, envToDelete: string[] = []) => beforeEach(() => run.mockReset()) -it('starts OpenCode 2 on its own server with the picked model in its launch config', async () => { - const result = await launch('2.0.21', "opencode '--model' 'opencode/big-pickle'") - expect(result.command).toBe('opencode --standalone') - expect(JSON.parse(result.env?.OPENCODE_CONFIG_CONTENT ?? '')).toEqual({ - autoupdate: false, - model: 'opencode/big-pickle', - agents: { build: { model: 'opencode/big-pickle' } } - }) -}) - it('keeps the overlay when the caller asked to drop inherited OpenCode config', async () => { const result = await launch('2.0.21', "opencode '--model' 'opencode/big-pickle'", [ 'OPENCODE_CONFIG_CONTENT' diff --git a/src/main/orcad/orcad-host-identity-reset.ts b/src/main/orcad/orcad-host-identity-reset.ts index 0afe2c36631..c0f21f9a70d 100644 --- a/src/main/orcad/orcad-host-identity-reset.ts +++ b/src/main/orcad/orcad-host-identity-reset.ts @@ -45,7 +45,8 @@ export function resetHostIdentityUnderLock(userDataPath: string): HostIdentityRe ? { status: 'failed', message } : { status: 'incomplete', message } } finally { - lock.release() + // A reset is not a run; the next start must still report a crash that preceded it. + lock.release({ keepUnexpectedExit: true }) } return { status: 'reset' } } diff --git a/src/main/orcad/orcad-instance-lock-hold.ts b/src/main/orcad/orcad-instance-lock-hold.ts index ad6cddca5e4..31542c1703a 100644 --- a/src/main/orcad/orcad-instance-lock-hold.ts +++ b/src/main/orcad/orcad-instance-lock-hold.ts @@ -13,7 +13,9 @@ export type OrcadInstanceLock = { readonly path: string readonly record: OrcadLockRecord readonly previousUnexpectedExit: OrcadUnexpectedExit | null - release(): void + /** `keepUnexpectedExit` puts back the crashed run's record this lock reclaimed, so the next + * start still reports that run; for one-shot tools that must not consume the notice. */ + release(options?: { keepUnexpectedExit?: boolean }): void } type OrcadLockBeat = 'held' | 'lost' | 'unproven' @@ -78,8 +80,14 @@ export function holdOrcadInstanceLock( publish: () => boolean, { previousUnexpectedExit, + restoreReclaimedRecord, onExclusivityLost - }: { previousUnexpectedExit: OrcadUnexpectedExit | null; onExclusivityLost: () => void } + }: { + previousUnexpectedExit: OrcadUnexpectedExit | null + /** Republishes the reclaimed record without overwriting a successor's lock. */ + restoreReclaimedRecord?: () => void + onExclusivityLost: () => void + } ): OrcadInstanceLock { let released = false const stopHeartbeat = startOrcadLockHeartbeat(() => { @@ -92,7 +100,7 @@ export function holdOrcadInstanceLock( path: lockPath, record, previousUnexpectedExit, - release: () => { + release: (options) => { if (released) { return } @@ -108,6 +116,9 @@ export function holdOrcadInstanceLock( } catch { // Dead-PID leftovers can be reclaimed on the next start. } + if (options?.keepUnexpectedExit && previousUnexpectedExit) { + restoreReclaimedRecord?.() + } } } } diff --git a/src/main/orcad/orcad-instance-lock.ts b/src/main/orcad/orcad-instance-lock.ts index 0012cc218df..bdb64f16201 100644 --- a/src/main/orcad/orcad-instance-lock.ts +++ b/src/main/orcad/orcad-instance-lock.ts @@ -142,11 +142,11 @@ export function acquireOrcadInstanceLock( const platform = hooks.platform ?? process.platform const self = orcadLockSelf(record, Date.parse(record.acquiredAt), hooks.bootStartedAtMs?.()) - // Stage then hard-link so canonical records are always complete. - const publish = (): boolean => { + // Stage then hard-link so canonical records are always complete and never overwrite a holder. + const publishContents = (contents: string): boolean => { const staged = `${lockPath}.staged-${process.pid}-${randomUUID()}` try { - writeFileSync(staged, serialized, { flag: 'wx', mode: 0o600 }) + writeFileSync(staged, contents, { flag: 'wx', mode: 0o600 }) linkSync(staged, lockPath) return true } catch (error) { @@ -161,10 +161,23 @@ export function acquireOrcadInstanceLock( unlinkQuietly(staged) } } + const publish = (): boolean => publishContents(serialized) - const lockFor = (previousUnexpectedExit: OrcadUnexpectedExit | null = null): OrcadInstanceLock => + const lockFor = ( + previousUnexpectedExit: OrcadUnexpectedExit | null = null, + reclaimedContents?: string + ): OrcadInstanceLock => holdOrcadInstanceLock(lockPath, record, publish, { previousUnexpectedExit, + restoreReclaimedRecord: reclaimedContents + ? () => { + try { + publishContents(reclaimedContents) + } catch { + // Losing the notice is better than failing the caller's release. + } + } + : undefined, onExclusivityLost: hooks.onExclusivityLost ?? (() => {}) }) if (publish()) { @@ -257,7 +270,7 @@ export function acquireOrcadInstanceLock( ) } reclaimAndPublish(lockPath, dataRoot, existingContents, publish, recoveryOwner) - return lockFor(reclaimedUnexpectedExit(existing, record, self.bootStartedAtMs)) + return lockFor(reclaimedUnexpectedExit(existing, record, self.bootStartedAtMs), existingContents) } function possiblyReusedPidError( diff --git a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts b/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts index 65ad62692d8..3fe20170630 100644 --- a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts +++ b/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts @@ -326,8 +326,7 @@ describe.skipIf(skip || process.platform === 'win32')('packaged plain-Node struc '--output-format', '--include-partial-messages', '--replay-user-messages', - '--permission-prompt-tool', - 'stdio', + '--permission-prompt-tool=stdio', `--session-id=${claudeSessionIdForOrcaSession(sessionId)}`, '--setting-sources=user,project,local', '--dangerously-skip-permissions' diff --git a/src/main/orcad/orcad-unexpected-exit.test.ts b/src/main/orcad/orcad-unexpected-exit.test.ts index b55017171e7..b43300a56f1 100644 --- a/src/main/orcad/orcad-unexpected-exit.test.ts +++ b/src/main/orcad/orcad-unexpected-exit.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -62,6 +62,30 @@ describe('the previous orcad run on a data root', () => { ) }) + it('keeps reporting that exit after a release that asks to keep it', () => { + const root = makeRoot() + leaveLockOf(root, 'boot-a') + + acquireOrcadInstanceLock(root, onBoot('boot-a')).release({ keepUnexpectedExit: true }) + + expect(acquireOrcadInstanceLock(root, onBoot('boot-a')).previousUnexpectedExit).toMatchObject({ + pid: 424242 + }) + }) + + it('never puts the crashed record over a lock another start took meanwhile', () => { + const root = makeRoot() + leaveLockOf(root, 'boot-a') + const reclaimed = acquireOrcadInstanceLock(root, onBoot('boot-a')) + unlinkSync(join(root, ORCAD_LOCK_FILE_NAME)) + const successor = acquireOrcadInstanceLock(root, onBoot('boot-a')) + + reclaimed.release({ keepUnexpectedExit: true }) + + successor.release() + expect(acquireOrcadInstanceLock(root, onBoot('boot-a')).previousUnexpectedExit).toBe(null) + }) + it('reports nothing when the host rebooted since that run', () => { const root = makeRoot() leaveLockOf(root, 'boot-a') diff --git a/src/main/provider-process/managed-provider-process.ts b/src/main/provider-process/managed-provider-process.ts index 218efc485b2..3abd330609f 100644 --- a/src/main/provider-process/managed-provider-process.ts +++ b/src/main/provider-process/managed-provider-process.ts @@ -3,6 +3,7 @@ import { spawnProcess } from '@orca/process-host' import { RetryableProcessExitProof } from '@orca/process-host/retryable-process-exit-proof' import type { ProviderProcessLaunch } from './provider-process-launch' import { + PROVIDER_BRIEF_SIGTERM_GRACE_MS, PROVIDER_SUPERVISOR_MAX_STOP_MS, createProviderSpawnSpec, type ProviderSupervisorLifetime @@ -19,6 +20,7 @@ import { acceptProviderWriterClose, closeProviderProcess, rootOnlyProviderClosePolicy, + type ProviderProcessCloseOptions, type ProviderProcessClosePolicy, type ProviderProcessCloseResult, type ProviderProcessTree @@ -72,9 +74,16 @@ export type ManagedProviderProcess = { stderrTail(): string onExit(listener: (exit: ProviderProcessExit) => void): void terminateTree(): Promise - close(tree?: ProviderProcessTree): Promise + /** A close joining one already in flight shares that close's grace. */ + close( + tree?: ProviderProcessTree, + options?: ProviderProcessCloseOptions + ): Promise /** Writer retirement can finish while explicitly stricter tree cleanup remains retryable. */ - closeWriter(tree: ProviderProcessTree): Promise + closeWriter( + tree: ProviderProcessTree, + options?: ProviderProcessCloseOptions + ): Promise } export function spawnManagedProviderProcess( @@ -199,7 +208,10 @@ export function spawnManagedProviderProcess( return lastCloseResult?.killDelivered ? lastCloseResult : null } - const close = (tree?: ProviderProcessTree): Promise => + const close = ( + tree?: ProviderProcessTree, + closeOptions?: ProviderProcessCloseOptions + ): Promise => exitProof.run(async () => { const known = knownWriterClose(tree) if (known && !options.acceptClose) { @@ -217,7 +229,10 @@ export function spawnManagedProviderProcess( supervised: spec.supervised, policy, tree, - terminateTree + terminateTree, + ...(closeOptions?.grace === 'brief' + ? { briefGraceMs: PROVIDER_BRIEF_SIGTERM_GRACE_MS } + : {}) }) lastCloseResult = { ...result, @@ -261,9 +276,9 @@ export function spawnManagedProviderProcess( }, terminateTree, close, - closeWriter(tree) { + closeWriter(tree, closeOptions) { const known = knownWriterClose(tree) - return known ? Promise.resolve(known) : close(tree) + return known ? Promise.resolve(known) : close(tree, closeOptions) } } } diff --git a/src/main/provider-process/provider-process-close.ts b/src/main/provider-process/provider-process-close.ts index 839351239e2..f8f2dd21b8d 100644 --- a/src/main/provider-process/provider-process-close.ts +++ b/src/main/provider-process/provider-process-close.ts @@ -1,7 +1,10 @@ import type { SpawnedProcess } from '@orca/process-host/process-spec' import type { DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' import { waitForProcessExitUntil } from './provider-process-exit-deadline' -import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from './provider-process-supervisor' +import { + PROVIDER_SUPERVISOR_MAX_STOP_MS, + PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL +} from './provider-process-supervisor' import type { ProviderProcessTeardownVerdict } from './provider-process-teardown' export type ProviderProcessTree = { @@ -30,8 +33,13 @@ export type ProviderProcessCloseInput = { policy: ProviderProcessClosePolicy tree?: ProviderProcessTree terminateTree: () => Promise + /** Time after stdin end/SIGTERM before a supervisor is asked to reap now, or an unsupervised root is forced. */ + briefGraceMs?: number } +/** 'brief' is for a stop the user is waiting on; providers without a SIGTERM ladder may ignore it. */ +export type ProviderProcessCloseOptions = { grace?: 'brief' } + export type ProviderProcessCloseResult = { root: DescendantTreeVerdict /** Null when this close made no observation of the descendants. */ @@ -56,6 +64,25 @@ export function acceptProviderWriterClose(result: ProviderProcessCloseResult): b return result.root === 'exited' || result.killDelivered === true } +// A supervised close without its SIGTERM has no ladder to shorten, so it keeps the full wait. +async function waitForGracefulExit( + input: ProviderProcessCloseInput, + signalled: boolean +): Promise { + const { gracefulExitMs } = input.policy + if (input.briefGraceMs === undefined || (input.supervised && !signalled)) { + return waitForProcessExitUntil(input.exitPromise, gracefulExitMs) + } + const briefMs = Math.min(input.briefGraceMs, gracefulExitMs) + await waitForProcessExitUntil(input.exitPromise, briefMs) + if (!signalled || input.rootVerdict() === 'exited') { + return + } + // The supervisor still owns the reap: asked now, it SIGKILLs its group instead of waiting out the grace. + input.child.kill(PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL) + await waitForProcessExitUntil(input.exitPromise, gracefulExitMs - briefMs) +} + /** The supervisor owns the POSIX signal ladder; its wrapper must outlive that ladder. */ export async function closeProviderProcess( input: ProviderProcessCloseInput @@ -69,14 +96,18 @@ export async function closeProviderProcess( } catch { // A broken pipe still owes the reap. } - if (input.supervised && policy.signalSupervisorOnClose && input.rootVerdict() !== 'exited') { + const signalled = + input.supervised === true && + policy.signalSupervisorOnClose === true && + input.rootVerdict() !== 'exited' + if (signalled) { child.kill('SIGTERM') } let reaped = false let fallbackTree: DescendantTreeVerdict | null = null let killDelivered = false if (input.rootVerdict() !== 'exited') { - await waitForProcessExitUntil(input.exitPromise, policy.gracefulExitMs) + await waitForGracefulExit(input, signalled) if (input.rootVerdict() !== 'exited') { reaped = true await tree?.refresh?.() diff --git a/src/main/provider-process/provider-process-supervisor.integration.test.ts b/src/main/provider-process/provider-process-supervisor.integration.test.ts index e1b42641f63..5dceaea779c 100644 --- a/src/main/provider-process/provider-process-supervisor.integration.test.ts +++ b/src/main/provider-process/provider-process-supervisor.integration.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { PROVIDER_STDIN_END_GRACE_MS, PROVIDER_SUPERVISOR_MAX_STOP_MS, + PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL, supervisedPosixLaunch, type ProviderSupervisorOptions } from './provider-process-supervisor' @@ -14,7 +15,9 @@ import { supervisedProviderSpawnFailure } from './provider-spawn-failure-report' // The provider leads its own group; its grandchild shares that group and ignores SIGTERM. const PROVIDER = String.raw` const { spawn } = require('node:child_process') - if (process.env.ORCA_TEST_PROVIDER_IGNORES_SIGTERM) process.on('SIGTERM', () => {}) + if (process.env.ORCA_TEST_PROVIDER_IGNORES_SIGTERM) { + process.on('SIGTERM', () => console.log(JSON.stringify({ sigterm: process.pid }))) + } if (process.env.ORCA_TEST_PROVIDER_SIGNAL_FILE) { process.on('SIGTERM', () => { require('node:fs').writeFileSync(process.env.ORCA_TEST_PROVIDER_SIGNAL_FILE, 'SIGTERM') @@ -267,6 +270,25 @@ describe.runIf(process.platform !== 'win32')('POSIX provider supervisor processe expect(alive(grandchild)).toBe(false) }) + it('reaps the group at once when a stopping supervisor is asked to', async () => { + const { supervisor, exit } = launchSupervisor({}, { ORCA_TEST_PROVIDER_IGNORES_SIGTERM: '1' }) + const { provider, grandchild } = await readPids(supervisor, ['provider', 'grandchild']) + + // ast-grep-ignore: test-no-wall-clock -- the cut SIGTERM grace is the behaviour under test + const startedAt = Date.now() + supervisor.kill('SIGTERM') + // Repeat only once the first stop reached the group, so the two signals cannot coalesce. + await readPids(supervisor, ['sigterm']) + expect(alive(-provider)).toBe(true) + supervisor.kill(PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL) + + await expect(exit).resolves.toEqual({ code: null, signal: 'SIGTERM' }) + // ast-grep-ignore: test-no-wall-clock -- the full grace is 3 s; a reap-now request must not wait it out + expect(Date.now() - startedAt).toBeLessThan(1_500) + expect(alive(provider)).toBe(false) + expect(alive(grandchild)).toBe(false) + }) + it('lets a session provider group finish its SIGTERM cleanup after the provider exits', async () => { const cleanupFile = join(tempDir(), 'grandchild-cleaned-up') const { supervisor, exit } = launchSupervisor( diff --git a/src/main/provider-process/provider-process-supervisor.ts b/src/main/provider-process/provider-process-supervisor.ts index f664769aa9a..eb505b1c34b 100644 --- a/src/main/provider-process/provider-process-supervisor.ts +++ b/src/main/provider-process/provider-process-supervisor.ts @@ -5,6 +5,11 @@ import { PROVIDER_SPAWN_FAILURE_MARKER } from './provider-spawn-failure-report' export const PROVIDER_STDIN_END_GRACE_MS = 1_000 /** Time the provider group gets to flush and exit after SIGTERM, before SIGKILL. */ export const PROVIDER_SIGTERM_GRACE_MS = 3_000 +/** A stop the user waits on (context clear) asks the supervisor to reap its group after this; + * Claude itself usually exits within it, so only a straggler in its group gets killed. */ +export const PROVIDER_BRIEF_SIGTERM_GRACE_MS = 1_000 +/** Asks a stopping supervisor to reap its group now; a repeated SIGTERM stays a plain stop. */ +export const PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL = 'SIGUSR2' /** Bound kernel kill completion; a process stuck on a hung drive must not hang close/recovery forever. */ export const PROVIDER_GROUP_REAP_TIMEOUT_MS = 1_500 /** Longest a supervisor waits, after its provider exits, to relay output still in the pipes. */ @@ -24,6 +29,10 @@ const [providerCommand, ...providerArgs] = process.argv.slice(1) const ownerGone = () => process.ppid !== spec.ownerPid // Registered before the spawn, so a stop that lands while the provider starts still reaps it. for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => stopProviderGroup(signal)) +process.on(${JSON.stringify(PROVIDER_SUPERVISOR_REAP_NOW_SIGNAL)}, () => { + sigtermGraceCut = true + stopProviderGroup('SIGTERM') +}) // Orca can die before this runs; spawning then would start a provider nothing watches. if (ownerGone()) process.exit(1) const childEnv = { ...process.env, ...spec.nodeEnv } @@ -63,6 +72,7 @@ if (reports) { let timer let ownerShutdownTimer let settling = false +let sigtermGraceCut = false let providerExited = false const providerGroupExists = () => { if (!child.pid) return false @@ -73,10 +83,10 @@ const providerGroupExists = () => { return Boolean(error && error.code !== 'ESRCH') } } -const waitForProviderGroupExit = async (timeoutMs, untilProviderExits = false) => { +const waitForProviderGroupExit = async (timeoutMs, stopWaiting = () => false) => { const deadline = Date.now() + timeoutMs while (providerGroupExists()) { - if (Date.now() >= deadline || (untilProviderExits && providerExited)) return false + if (Date.now() >= deadline || stopWaiting()) return false await new Promise((resolve) => setTimeout(resolve, 25)) } return true @@ -94,8 +104,8 @@ const finishWithProviderOutcome = (code, signal) => { process.removeAllListeners(signal) process.kill(process.pid, signal) } -// Every stop is the same: SIGTERM the group, SIGKILL it after its grace, and exit only once it is -// gone. Whoever stops this pid judges the provider by it, so a dead supervisor means a dead group. +// Every stop is the same: SIGTERM the group, SIGKILL it after its grace (or once asked to reap now), and exit +// only once it is gone. Whoever stops this pid judges the provider by it, so a dead supervisor means a dead group. const stopProviderGroup = (receivedSignal) => { if (settling) return settling = true @@ -103,7 +113,8 @@ const stopProviderGroup = (receivedSignal) => { if (ownerShutdownTimer) clearTimeout(ownerShutdownTimer) try { process.kill(-child.pid, 'SIGTERM') } catch {} // A one-shot's helpers die with it once it has exited; a session's keep the grace to clean up. - void waitForProviderGroupExit(spec.sigtermGraceMs, spec.lifetime === 'one-shot') + const graceOver = () => sigtermGraceCut || (spec.lifetime === 'one-shot' && providerExited) + void waitForProviderGroupExit(spec.sigtermGraceMs, graceOver) .then((exited) => exited || reapOwnedProviderGroup()) .then((reaped) => { if (!reaped) return process.exit(1) diff --git a/src/main/runtime/browser/installation/runtime-browser-commands-factory.ts b/src/main/runtime/browser/installation/runtime-browser-commands-factory.ts index 610c7811ad8..addff04997f 100644 --- a/src/main/runtime/browser/installation/runtime-browser-commands-factory.ts +++ b/src/main/runtime/browser/installation/runtime-browser-commands-factory.ts @@ -1,3 +1,9 @@ +import type { + BrowserExtensionListParams, + BrowserExtensionReloadParams, + BrowserExtensionReloadResult, + BrowserExtensionSummaryListResult +} from '../../../../shared/browser/extensions/browser-extension-types' import { BrowserError } from '../../../browser/browser-error' import '../../../../shared/runtime-types' import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-session-contracts' @@ -16,6 +22,11 @@ export type RuntimeBrowserCommandsFactory = ( export type RuntimeBrowserCommandsFactoryOptions = { /** The provider creates pages against this runtime's client-host lease registry. */ clientHosting?: boolean + /** Only the desktop installs access to its local extension manager. */ + extensions?: { + list(params: BrowserExtensionListParams): Promise + reload(params: BrowserExtensionReloadParams): Promise + } supportsGoogleCookieClear?: () => boolean /** Client pages live in this runtime's own registries, so they need no healthy engine. */ clientHostingWithoutEngine?: boolean @@ -117,3 +128,20 @@ export function browserUnavailableError(): BrowserError { 'Browser automation is unavailable on this host.' ) } + +/** Requires an available desktop extension provider; headless and remote browser providers are unsupported. */ +export function getRuntimeBrowserExtensions(): NonNullable< + RuntimeBrowserCommandsFactoryOptions['extensions'] +> { + if ( + !runtimeBrowserCommandsFactoryIsAvailable() || + currentOptions.headless || + !currentOptions.extensions + ) { + throw new BrowserError( + 'browser_unavailable', + 'Browser extension management requires the Orca desktop on this host; it is unavailable in headless or remote browser providers.' + ) + } + return currentOptions.extensions +} diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index b297b9631d4..b1515e72345 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -280,7 +280,7 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW getStore: () => this.store, listRepos: () => this.listRepos(), addRepo: (path, kind, hostId) => this.addRepo(path, kind, hostId), - cloneRepo: (url, destination, hostId) => this.cloneRepo(url, destination, hostId), + cloneRepo: (args) => this.cloneRepo(args.url, args.destination, args.hostId, args.folderName), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), invalidateWorktreeScan: (repoId) => this.invalidateWorktreeScanCacheForRepo(repoId), notifyReposChanged: () => this.notifyReposChanged(), diff --git a/src/main/runtime/host-instance-identity.test.ts b/src/main/runtime/host-instance-identity.test.ts index ffc5594c52e..beb5bf32bbb 100644 --- a/src/main/runtime/host-instance-identity.test.ts +++ b/src/main/runtime/host-instance-identity.test.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import { cpSync, mkdtempSync, readdirSync, readFileSync } from 'node:fs' +import { cpSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it } from 'vitest' @@ -131,6 +131,26 @@ describe('ensureHostInstanceIdentity', () => { expect((await identity(dir)).registry.validateToken(before.token)).not.toBeNull() }) + it('deletes files staged by a rotation that crashed before its marker, keeping the identity', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + // A crash mid-staging leaves `.next` files (one holds a secret key) and no `rotating` marker. + writeNewE2EEKeypair(dir, (path, value) => writeDurableSecureJsonFile(`${path}.next`, value)) + writeDurableSecureJsonFile(join(dir, `${DEVICE_REGISTRY_FILENAME}.next`), []) + + expect(ensureHostInstanceIdentity(dir, vmA)).toEqual({ kind: 'unchanged' }) + expect(readdirSync(dir).filter((name) => name.endsWith('.next'))).toEqual([]) + const after = await identity(dir) + expect(after.publicKeyB64).toBe(before.publicKeyB64) + expect(after.registry.validateToken(before.token)).not.toBeNull() + + // A marker that cannot be read might have said `rotating`; its staged files stay. + writeDurableSecureJsonFile(join(dir, `${DEVICE_REGISTRY_FILENAME}.next`), []) + writeFileSync(join(dir, HOST_INSTANCE_FILENAME), '{not json') + ensureHostInstanceIdentity(dir, null) + expect(readdirSync(dir).filter((name) => name.endsWith('.next'))).toHaveLength(1) + }) + it('finishes a publish interrupted after the marker on the next start, without the variable', async () => { ensureHostInstanceIdentity(dir, vmA) const before = await pairedHost(dir) diff --git a/src/main/runtime/host-instance-identity.ts b/src/main/runtime/host-instance-identity.ts index f327cf246b6..4ecaa1066f4 100644 --- a/src/main/runtime/host-instance-identity.ts +++ b/src/main/runtime/host-instance-identity.ts @@ -66,28 +66,36 @@ function isMissing(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ENOENT' } -function readMarker(markerPath: string): HostInstanceMarker | null { +/** `malformed` means a file exists but its contents could not be trusted. */ +function readMarkerFile(markerPath: string): { + marker: HostInstanceMarker | null + malformed: boolean +} { let raw: string try { raw = readFileSync(markerPath, 'utf8') } catch (error) { if (isMissing(error)) { - return null + return { marker: null, malformed: false } } throw error } if (raw.length > MAX_HOST_INSTANCE_FILE_BYTES) { - return null + return { marker: null, malformed: true } } try { const parsed = HostInstanceMarkerSchema.safeParse(JSON.parse(raw)) - return parsed.success ? parsed.data : null + return { marker: parsed.success ? parsed.data : null, malformed: !parsed.success } } catch { // Writes are atomic, so a bad file was edited by hand; re-record it rather than unpair. - return null + return { marker: null, malformed: true } } } +function readMarker(markerPath: string): HostInstanceMarker | null { + return readMarkerFile(markerPath).marker +} + function markerFor(instanceId: string | undefined): HostInstanceMarker { return { v: 1, ...(instanceId ? { instanceId } : {}) } } @@ -116,7 +124,7 @@ function discardStagedIdentity(userDataPath: string): void { try { rmSync(staged, { force: true }) } catch { - // A leftover staged file is ignored until a later rotation overwrites it. + // A leftover staged file is retried on the next start and never published without `rotating`. } } } @@ -256,7 +264,7 @@ export function ensureHostInstanceIdentity( write: HostIdentityWrite = writeDurableSecureJsonFile ): HostIdentityOutcome { const markerPath = join(userDataPath, HOST_INSTANCE_FILENAME) - const stored = readMarker(markerPath) + const { marker: stored, malformed } = readMarkerFile(markerPath) if (stored?.rotating) { publishStagedIdentity( userDataPath, @@ -265,6 +273,12 @@ export function ensureHostInstanceIdentity( ) return { kind: 'rotated', reason: 'interrupted_rotation' } } + // Without `rotating`, staged files are from a rotation that crashed before its marker; drop + // them so a secret key does not sit beside the live one until the next rotation. An unreadable + // marker may have said `rotating`, so its staged files are left for recovery by hand. + if (!malformed) { + discardStagedIdentity(userDataPath) + } if (!instanceId || stored?.instanceId === instanceId) { return { kind: 'unchanged' } } diff --git a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts index e29c4afc4de..87fd723ece6 100644 --- a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts +++ b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts @@ -51,7 +51,7 @@ type RuntimeProjectHostSetupDependencies = { getStore: () => RuntimeStore | null listRepos: () => Repo[] addRepo: (path: string, kind: 'folder' | 'git', hostId: ExecutionHostId) => Promise - cloneRepo: (url: string, destination: string, hostId: ExecutionHostId) => Promise + cloneRepo: (args: ProjectHostSetupCloneArgs) => Promise invalidateResolvedWorktrees: () => void invalidateWorktreeScan: (repoId: string) => void notifyReposChanged: () => void @@ -151,7 +151,7 @@ export class RuntimeProjectHostSetupController { async setupClone(args: ProjectHostSetupCloneArgs): Promise { assertCloneHostIsSupported(args.hostId) const knownRepoIds = new Set(this.deps.listRepos().map((repo) => repo.id)) - const repo = await this.deps.cloneRepo(args.url, args.destination, args.hostId) + const repo = await this.deps.cloneRepo(args) return this.completeSetup( { ...args, path: repo.path, kind: 'git', setupMethod: 'cloned' }, repo, diff --git a/src/main/runtime/repositories/runtime-repository-clone-controller.ts b/src/main/runtime/repositories/runtime-repository-clone-controller.ts index 9d6706fe5e5..7d74b2272e3 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-controller.ts @@ -16,6 +16,11 @@ import { import { gitSpawnAfterWindowsEnvironmentReady } from '../../git/command-runner/git-spawn' import { promptGuardGitEnv } from '../../git/command-runner/git-process-env' import { reuseSavedCloneTarget } from '../../git/saved-clone-target' +import { checkCloneTarget } from '../../git/clone-target-check' +import type { + CloneTargetArgs, + CloneTargetCheck +} from '../../../shared/git/clone/clone-target-check' import { runWithGitReadCacheInvalidation } from '../../git/source-control/git-read-cache-invalidation' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' @@ -34,15 +39,46 @@ type RuntimeRepositoryCloneDependencies = { notifyReposChanged: () => void } +// Git runs here; an SSH row with the same path refers to another machine. +function findRegistrationCandidateAt( + store: RuntimeStore, + pathKeys: string[], + executionHostId?: ExecutionHostId | null +): Repo | undefined { + return store + .getRepos() + .find( + (repo) => + pathKeys.includes(getClonePathComparisonKey(repo.path)) && + runtimeRepoIsRegistrationCandidate(repo, executionHostId) + ) +} + export class RuntimeRepositoryCloneController { private readonly inFlightByPath = new Map>() constructor(private readonly deps: RuntimeRepositoryCloneDependencies) {} + async checkTarget( + args: CloneTargetArgs, + executionHostId?: ExecutionHostId | null + ): Promise { + const store = this.deps.getStore() + if (!store) { + throw new Error('runtime_unavailable') + } + return checkCloneTarget( + { ...args, url: args.url.trim(), destination: args.destination.trim() }, + (pathKeys) => findRegistrationCandidateAt(store, pathKeys, executionHostId), + LOCAL_EXECUTION_HOST_ID + ) + } + async clone( url: string, destination: string, - executionHostId?: ExecutionHostId | null + executionHostId?: ExecutionHostId | null, + folderName?: string ): Promise { if (!this.deps.getStore()) { throw new Error('runtime_unavailable') @@ -52,7 +88,11 @@ export class RuntimeRepositoryCloneController { if (!trimmedDestination) { throw new Error('Clone destination is required') } - const clonePath = deriveValidatedClonePath({ url: trimmedUrl, destination: trimmedDestination }) + const clonePath = deriveValidatedClonePath({ + url: trimmedUrl, + destination: trimmedDestination, + folderName + }) await refuseWslHostWindowsDrivePath(trimmedDestination) const clonePathKey = getClonePathComparisonKey(clonePath) const previous = this.inFlightByPath.get(clonePathKey) ?? Promise.resolve() @@ -89,14 +129,8 @@ export class RuntimeRepositoryCloneController { throw new Error('runtime_unavailable') } let savedPathKeys = await getSavedProjectPathKeys(clonePath) - // Git runs here; an SSH row with the same path refers to another machine. const findSaved = (): Repo | undefined => - store.getRepos().find((repo) => { - return ( - savedPathKeys.includes(getClonePathComparisonKey(repo.path)) && - runtimeRepoIsRegistrationCandidate(repo, executionHostId) - ) - }) + findRegistrationCandidateAt(store, savedPathKeys, executionHostId) const reused = await reuseSavedCloneTarget(findSaved, trimmedUrl, LOCAL_EXECUTION_HOST_ID) if (reused) { return reused diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index c533644ee71..928c9142fc4 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -64,6 +64,7 @@ export type RuntimeRepositoryCommandSurface = { addRepo: RuntimeRepositoryRegistrationController['add'] createRepo: RuntimeRepositoryRegistrationController['create'] cloneRepo: RuntimeRepositoryCloneController['clone'] + checkCloneTarget: RuntimeRepositoryCloneController['checkTarget'] showRepo: RuntimeRepositorySettingsController['show'] setRepoBaseRef: RuntimeRepositorySettingsController['setBaseRef'] updateRepo: RuntimeRepositorySettingsController['update'] @@ -142,6 +143,7 @@ export function installRuntimeRepositoryCommandSurface( addRepo: registrations.add.bind(registrations), createRepo: registrations.create.bind(registrations), cloneRepo: clones.clone.bind(clones), + checkCloneTarget: clones.checkTarget.bind(clones), showRepo: settings.show.bind(settings), setRepoBaseRef: settings.setBaseRef.bind(settings), updateRepo: settings.update.bind(settings), diff --git a/src/main/runtime/rpc/methods/browser/browser-core.ts b/src/main/runtime/rpc/methods/browser/browser-core.ts index 9e4ab2379e3..d9d6d14ed1f 100644 --- a/src/main/runtime/rpc/methods/browser/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser/browser-core.ts @@ -1,3 +1,4 @@ +import { BROWSER_EXTENSION_METHODS } from './browser-extension-rpc-methods' import { defineMethod } from '../../core' import { BrowserTarget, @@ -145,6 +146,7 @@ export const BROWSER_CORE_METHODS = [ handler: async (params, { runtime }) => runtime.browserTabClose(params) }), ...BROWSER_PROFILE_METHODS, + ...BROWSER_EXTENSION_METHODS, defineMethod({ name: 'browser.hover', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts b/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts new file mode 100644 index 00000000000..0ccb61c2dca --- /dev/null +++ b/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts @@ -0,0 +1,21 @@ +import { defineMethod } from '../../core' +import { + ExtensionList, + ExtensionReload +} from '../../../../../shared/rpc-contract/browser-extension-params' +import { getRuntimeBrowserExtensions } from '../../../browser/installation/runtime-browser-commands-factory' + +export const BROWSER_EXTENSION_METHODS = [ + defineMethod({ + name: 'browser.extensionList', + permission: 'workspace', + params: ExtensionList, + handler: async (params) => getRuntimeBrowserExtensions().list(params) + }), + defineMethod({ + name: 'browser.extensionReload', + permission: 'workspace', + params: ExtensionReload, + handler: async (params) => getRuntimeBrowserExtensions().reload(params) + }) +] diff --git a/src/main/runtime/rpc/methods/projects/repo.ts b/src/main/runtime/rpc/methods/projects/repo.ts index a745f852106..e3987d8a38d 100644 --- a/src/main/runtime/rpc/methods/projects/repo.ts +++ b/src/main/runtime/rpc/methods/projects/repo.ts @@ -173,11 +173,22 @@ export const REPO_METHODS = [ params: RepoClone, handler: async (params, context) => ({ repo: projectRepoVisibilityForClient( - await context.runtime.cloneRepo(params.url, params.destination), + await context.runtime.cloneRepo( + params.url, + params.destination, + undefined, + params.folderName + ), context ) }) }), + defineMethod({ + name: 'repo.checkCloneTarget', + permission: 'workspace', + params: RepoClone, + handler: async (params, { runtime }) => ({ target: await runtime.checkCloneTarget(params) }) + }), defineMethod({ name: 'repo.show', permission: 'workspace', diff --git a/src/main/skills/discovery/skill-root-file-walk.ts b/src/main/skills/discovery/skill-root-file-walk.ts index edd7bb19b29..7fbf87d4fa2 100644 --- a/src/main/skills/discovery/skill-root-file-walk.ts +++ b/src/main/skills/discovery/skill-root-file-walk.ts @@ -18,20 +18,38 @@ function isWithinDepth(rootPath: string, childPath: string, maxDepth: number): b return rel.split(sep).length <= maxDepth } +/** Codex's own walk skips hidden folders; stopping at a skill folder skips its references and scripts. */ +export type SkillFileWalkOptions = { + skipHiddenDirectories?: boolean + stopAtSkillDirectories?: boolean +} + +function entersDirectory(name: string, options: SkillFileWalkOptions): boolean { + return ( + name !== SKILL_FILE_NAME && + !isSkillStagingEntryName(name) && + !(options.skipHiddenDirectories && name.startsWith('.')) + ) +} + +function holdsSkillFile(entries: readonly Dirent[]): boolean { + return entries.some((entry) => entry.name === SKILL_FILE_NAME && !entry.isDirectory()) +} + /** Entry indexes of the plain child directories a walk enters. */ function enteredChildIndexes( rootPath: string, maxDepth: number, dirPath: string, - entries: readonly Dirent[] + entries: readonly Dirent[], + options: SkillFileWalkOptions ): number[] { + if (options.stopAtSkillDirectories && holdsSkillFile(entries)) { + return [] + } const indexes: number[] = [] for (const [index, entry] of entries.entries()) { - if ( - !entry.isDirectory() || - entry.name === SKILL_FILE_NAME || - isSkillStagingEntryName(entry.name) - ) { + if (!entry.isDirectory() || !entersDirectory(entry.name, options)) { continue } // Directory entry names add one segment, so siblings share the depth verdict. @@ -47,14 +65,15 @@ function enteredChildIndexes( export async function findSkillFiles( rootPath: string, maxDepth: number, - signal?: AbortSignal + signal?: AbortSignal, + options: SkillFileWalkOptions = {} ): Promise { const out: string[] = [] const visitedDirectoryPaths = new Set() const readAhead = createDirectoryReadAhead({ signal, enteredChildIndexes: (dirPath, entries) => - enteredChildIndexes(rootPath, maxDepth, dirPath, entries) + enteredChildIndexes(rootPath, maxDepth, dirPath, entries, options) }) async function visit(dirPath: string, order: WalkOrder): Promise { // Reject on abort; a cached truncated listing would falsely report skills removed. @@ -68,7 +87,8 @@ export async function findSkillFiles( if (!entries) { return } - const childIndexes = new Set(enteredChildIndexes(rootPath, maxDepth, dirPath, entries)) + const childIndexes = new Set(enteredChildIndexes(rootPath, maxDepth, dirPath, entries, options)) + const leaf = options.stopAtSkillDirectories === true && holdsSkillFile(entries) for (const [index, entry] of entries.entries()) { signal?.throwIfAborted() // Hide transaction siblings so in-flight skills cannot appear twice or be deleted again. @@ -98,7 +118,12 @@ export async function findSkillFiles( } continue } - if (entry.isSymbolicLink() && isWithinDepth(rootPath, entryPath, maxDepth)) { + if ( + !leaf && + entry.isSymbolicLink() && + entersDirectory(entry.name, options) && + isWithinDepth(rootPath, entryPath, maxDepth) + ) { // Follow provider directory links but guard realpaths against cycles. let linksToDirectory = false try { diff --git a/src/main/skills/filesystem/skill-candidate-concurrency.ts b/src/main/skills/filesystem/skill-candidate-concurrency.ts index c81f1942ce9..8f2a714470f 100644 --- a/src/main/skills/filesystem/skill-candidate-concurrency.ts +++ b/src/main/skills/filesystem/skill-candidate-concurrency.ts @@ -1,7 +1,8 @@ const MAX_CONCURRENT_SKILL_CANDIDATES = 4 export async function runSkillCandidateTasks( - tasks: readonly (() => Promise)[] + tasks: readonly (() => Promise)[], + limit = MAX_CONCURRENT_SKILL_CANDIDATES ): Promise { const results = Array.from({ length: tasks.length }) let nextIndex = 0 @@ -17,8 +18,6 @@ export async function runSkillCandidateTasks( } } - await Promise.all( - Array.from({ length: Math.min(MAX_CONCURRENT_SKILL_CANDIDATES, tasks.length) }, () => worker()) - ) + await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, () => worker())) return results } diff --git a/src/main/startup/cli-command-names.ts b/src/main/startup/cli-command-names.ts index 867e15b0fa0..9a09163faf7 100644 --- a/src/main/startup/cli-command-names.ts +++ b/src/main/startup/cli-command-names.ts @@ -28,6 +28,7 @@ export const CLI_COMMAND_NAMES = [ 'environment', 'eval', 'exec', + 'extension', 'file', 'fill', 'find', diff --git a/src/main/telemetry/client-protected-milestones.test.ts b/src/main/telemetry/client-protected-milestones.test.ts index 3b0dd9e715a..954c93ca98b 100644 --- a/src/main/telemetry/client-protected-milestones.test.ts +++ b/src/main/telemetry/client-protected-milestones.test.ts @@ -227,29 +227,6 @@ describe('protected telemetry milestones', () => { expect(captured('meaningful_activity_day')[0].properties.trigger).toBe('native_chat') }) - it('counts a provider-accepted phone prompt as an interaction and an active day', () => { - track('native_chat_prompt_submitted', { - agent_kind: 'claude-code', - runtime: 'unknown', - client: 'mobile' - }) - - expect(captured('first_agent_interaction')[0].properties).toMatchObject({ - source: 'mobile_chat', - agent_kind: 'claude-code' - }) - expect(captured('meaningful_activity_day')[0].properties).toMatchObject({ - trigger: 'mobile_chat', - install_cohort: 'fresh' - }) - }) - - it('reports profiles without a frozen cohort as existing', () => { - state.settings.telemetry = telemetry({}) - track('agent_started', sidebarLaunch) - expect(captured('meaningful_activity_day')[0].properties.install_cohort).toBe('existing') - }) - it('marks terminal activity once per day across restart and UTC rollover', () => { observeTerminalUserInput() restart() diff --git a/src/preload/api/repos-bridge.ts b/src/preload/api/repos-bridge.ts index a5c1ec58e36..af5c8549aa7 100644 --- a/src/preload/api/repos-bridge.ts +++ b/src/preload/api/repos-bridge.ts @@ -35,6 +35,8 @@ export const reposApi = { clone: (args) => ipcRenderer.invoke('repos:clone', args), + checkCloneTarget: (args) => ipcRenderer.invoke('repos:checkCloneTarget', args), + cloneAbort: () => ipcRenderer.invoke('repos:cloneAbort'), onCloneProgress: (callback: (data: { phase: string; percent: number }) => void): (() => void) => { diff --git a/src/preload/api/repository-api.ts b/src/preload/api/repository-api.ts index 0b134c50cc9..e74b1a80af9 100644 --- a/src/preload/api/repository-api.ts +++ b/src/preload/api/repository-api.ts @@ -1,4 +1,5 @@ import type { RepoCreateFailure } from '../../shared/repo-create-failure-copy' +import type { CloneTargetArgs, CloneTargetCheck } from '../../shared/git/clone/clone-target-check' import type { ExecutionHostId } from '../../shared/execution-host' import type { GhAccountBinding } from '../../shared/github/account-binding' import type { @@ -80,7 +81,8 @@ export type RepositoryApi = { pickFolder: () => Promise pickFolders: () => Promise pickDirectory: () => Promise - clone: (args: { url: string; destination: string }) => Promise + clone: (args: CloneTargetArgs) => Promise + checkCloneTarget: (args: CloneTargetArgs) => Promise cloneAbort: () => Promise create: (args: { parentPath: string diff --git a/src/renderer/src/app-shell/AppRootSurfaces.tsx b/src/renderer/src/app-shell/AppRootSurfaces.tsx index 4288c87f2f4..e97fe473f52 100644 --- a/src/renderer/src/app-shell/AppRootSurfaces.tsx +++ b/src/renderer/src/app-shell/AppRootSurfaces.tsx @@ -57,7 +57,7 @@ const ProjectAddedDialog = lazy( () => import('../components/sidebar/project-admission/completion/ProjectAddedDialog') ) const NodeDistMirrorDialog = lazy( - () => import('../components/settings/advanced/network/NodeDistMirrorDialog') + () => import('../components/ssh-host-recovery/NodeDistMirrorDialog') ) const AiVaultSessionHistoryDialog = lazy( () => import('../components/right-sidebar/ai-vault/session-list/AiVaultSessionHistoryDialog') diff --git a/src/renderer/src/app-shell/visible-review-reporting.test.ts b/src/renderer/src/app-shell/visible-review-reporting.test.ts deleted file mode 100644 index 9166bb4661c..00000000000 --- a/src/renderer/src/app-shell/visible-review-reporting.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createTestStore, makePRRefreshWorktree } from '../store/github/github-slice-test-harness' - -import { visibleReviewWorktreeIdsForState } from './use-visible-review-refresh-reporting' - -function state() { - const store = createTestStore() - store.setState({ - repos: [ - { id: 'repo-1', path: '/repo', displayName: 'repo', badgeColor: '', addedAt: 1, kind: 'git' } - ], - worktreesByRepo: { - 'repo-1': [makePRRefreshWorktree({ id: 'selected' }), makePRRefreshWorktree({ id: 'card' })] - }, - activeWorktreeId: 'selected', - activeView: 'terminal', - rightSidebarOpen: true, - rightSidebarTab: 'checks', - visibleReviewCardWorktreeIds: [] - }) - return store -} - -describe('review surface visibility union', () => { - it('keeps the selected panel when the left sidebar has no visible cards', () => { - expect(visibleReviewWorktreeIdsForState(state().getState())).toEqual(['selected']) - }) - it('unions cards and the panel without duplicate requests', () => { - const store = state() - store.setState({ visibleReviewCardWorktreeIds: ['card', 'selected'] }) - expect(visibleReviewWorktreeIdsForState(store.getState())).toEqual(['card', 'selected']) - }) - it('drops the selected panel when closed or suppressed by the active view', () => { - const store = state() - store.setState({ visibleReviewCardWorktreeIds: ['card'], activeView: 'settings' }) - expect(visibleReviewWorktreeIdsForState(store.getState())).toEqual(['card']) - store.setState({ activeView: 'terminal', rightSidebarOpen: false }) - expect(visibleReviewWorktreeIdsForState(store.getState())).toEqual(['card']) - }) -}) diff --git a/src/renderer/src/components/ClaudeAccountSwitchDialog.tsx b/src/renderer/src/components/ClaudeAccountSwitchDialog.tsx index 74f2a7af5ea..4b0d67fd7e1 100644 --- a/src/renderer/src/components/ClaudeAccountSwitchDialog.tsx +++ b/src/renderer/src/components/ClaudeAccountSwitchDialog.tsx @@ -18,7 +18,7 @@ import { getClaudeAccountSwitchPrompt, subscribeClaudeAccountSwitchPrompt, type ClaudeAccountSwitchPrompt -} from '@/lib/claude-account-switch-sessions' +} from '@/lib/provider-accounts/claude-account-switch-sessions' export default function ClaudeAccountSwitchDialog(): React.JSX.Element | null { const prompt = useSyncExternalStore( diff --git a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx index f4e08c63edf..be5f1670689 100644 --- a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx +++ b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx @@ -4,12 +4,12 @@ import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { AgentIcon } from '@/lib/agent-catalog' import { formatAgentTypeLabel } from '../../../shared/agent-status/presentation/agent-type-label' -import type { ClaudeAccountSwitchPromptSessions } from '@/lib/claude-account-switch-sessions' +import type { ClaudeAccountSwitchPromptSessions } from '@/lib/provider-accounts/claude-account-switch-sessions' import { isClaudePaneMidTurn, type ClaudeSessionCantMoveReason, type ClaudeSessionMoveCandidate -} from '@/lib/claude-session-account-move' +} from '@/lib/agent-session/accounts/claude/claude-session-account-move' import { resolveWorktreeBranchLabel, resolveWorktreeDisplayName diff --git a/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx b/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx index 0097a89881c..375c806f1a9 100644 --- a/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx +++ b/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx @@ -17,7 +17,7 @@ import { describe, expect, it, vi } from 'vitest' import type { JiraIssue, JiraMutationResult } from '../../../shared/jira/jira-types' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' import { getDefaultSettings } from '../../../shared/constants' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { TooltipProvider } from '@/components/ui/tooltip' import JiraIssueWorkspace from './JiraIssueWorkspace' diff --git a/src/renderer/src/components/JiraIssueWorkspace.tsx b/src/renderer/src/components/JiraIssueWorkspace.tsx index e60f084f845..aa280b752ff 100644 --- a/src/renderer/src/components/JiraIssueWorkspace.tsx +++ b/src/renderer/src/components/JiraIssueWorkspace.tsx @@ -21,7 +21,7 @@ import { useJiraIssueWorkspaceActions } from './jira-issue-workspace-actions' import { getJiraReadIdentity } from '@/store/slices/jira/jira-read-coordination' import { defaultScopeHost } from '@/lib/default-creation-host' import { taskSourceRuntimeTarget } from '@/lib/task-source-runtime-target' -import { getEnvironmentRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getEnvironmentRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { runtimeTargetEnvironmentId } from '@/runtime/rpc/targets/runtime-client-target' import { editedJiraIssueFields } from './jira-issue-workspace-hydration' import { enqueueJiraIssueMutation, jiraIssueRequestScope } from './jira-issue-mutation-queue' diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx deleted file mode 100644 index 56244dbde40..00000000000 --- a/src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { renderCard } from './NewWorkspaceComposerCard.test-fixture' - -const storeMocks = vi.hoisted(() => ({ - closeModal: vi.fn(), - openModal: vi.fn(), - openSettingsPage: vi.fn(), - openSettingsTarget: vi.fn() -})) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: unknown) => unknown) => - selector({ - closeModal: storeMocks.closeModal, - openModal: storeMocks.openModal, - openSettingsPage: storeMocks.openSettingsPage, - openSettingsTarget: storeMocks.openSettingsTarget, - setRuntimeEnvironmentStatus: vi.fn(), - setupProjectExistingFolder: vi.fn(), - setupProjectClone: vi.fn(), - activeModal: 'new-workspace-composer', - settings: { defaultTuiAgent: null, disabledTuiAgents: [] }, - updateSettings: vi.fn(), - projects: [], - repos: [] - }), - { getState: () => ({}) } - ) -})) - -vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({ - useContextualTour: vi.fn() -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children} -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children} -})) - -vi.mock('@/components/agent/AgentCombobox', () => ({ - default: () => -})) - -vi.mock('@/components/sidebar/host-admission/ssh/AddRemoteHostDialog', () => ({ - AddRemoteHostDialog: () => null -})) - -vi.mock('@/components/sparse/SparseCheckoutPresetSelect', () => ({ - default: () => null -})) - -vi.mock('@/components/new-workspace/SmartWorkspaceNameField', () => ({ - default: () => -})) - -vi.mock('@/components/new-workspace/ProjectCombobox', () => ({ - default: () =>
-})) - -vi.mock('@/components/new-workspace/SetProjectLocationDialog', () => ({ - SetProjectLocationDialog: ({ - option, - projectName, - onClose, - onReady - }: { - option: { label: string } | null - projectName: string - onClose: () => void - onReady: (setupId: string) => void - }) => - option ? ( -
- - -
- ) : null -})) - -describe('NewWorkspaceComposerCard set location', () => { - let container: HTMLDivElement | null = null - - beforeEach(() => { - storeMocks.closeModal.mockReset() - storeMocks.openModal.mockReset() - storeMocks.openSettingsPage.mockReset() - }) - - afterEach(() => { - container?.remove() - container = null - }) - - // Flush lazy resolution; the click mounts Suspense before the chunk arrives. - it('opens set-location over the composer without leaving the create dialog', async () => { - const nestedOpenChanges: boolean[] = [] - container = await renderCard({ - onNestedDialogOpenChange: (open) => nestedOpenChanges.push(open) - }) - - act(() => { - container?.querySelector('div[data-run-target-combobox-root="true"]')?.click() - }) - const setLocation = [...document.body.querySelectorAll('button')].find( - (button) => button.textContent?.includes('Set project location') - ) - expect(setLocation).toBeTruthy() - act(() => setLocation?.click()) - await act(async () => {}) - - const dialog = document.body.querySelector('[data-testid="set-project-location-dialog"]') - expect(dialog?.getAttribute('data-host')).toBe('Devbox') - expect(dialog?.getAttribute('data-project')).toBe('Platform') - expect(nestedOpenChanges).toEqual([true]) - expect(storeMocks.closeModal).not.toHaveBeenCalled() - expect(storeMocks.openModal).not.toHaveBeenCalled() - expect(storeMocks.openSettingsPage).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.test-fixture.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.test-fixture.tsx deleted file mode 100644 index 3f61a31494e..00000000000 --- a/src/renderer/src/components/NewWorkspaceComposerCard.test-fixture.tsx +++ /dev/null @@ -1,127 +0,0 @@ -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import NewWorkspaceComposerCard from './NewWorkspaceComposerCard' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' - -const cardRoots = new WeakMap() -export function unmountCard(container: HTMLDivElement): void { - act(() => cardRoots.get(container)?.unmount()) - cardRoots.delete(container) - container.remove() -} - -export const projectOptions: NewWorkspaceProjectOption[] = [ - { - kind: 'project-group', - id: 'project-group:platform', - projectGroupId: 'platform', - displayName: 'Platform', - badgeColor: 'var(--muted-foreground)', - detail: '/workspace/platform', - parentPath: '/workspace/platform', - connectionId: null - } -] - -export const hostOptions: ProjectHostSetupOption[] = [ - { - kind: 'ready', - id: 'setup-local', - projectId: 'project-group:platform', - hostId: 'local', - repoId: 'repo-a', - label: 'Local Mac', - detail: 'Orca', - path: '/Users/alice/orca' - }, - { - kind: 'needs-setup', - id: 'needs-setup:ssh:devbox', - projectId: 'project-group:platform', - hostId: 'ssh:devbox', - label: 'Devbox', - detail: 'Project location not set', - isAvailable: true, - attention: false, - canSetLocation: true - } -] - -export async function renderCard( - overrides: Partial> = {} -): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - cardRoots.set(container, root) - act(() => { - root.render( - {}} - eligibleRepos={[]} - repoId="repo-a" - projectOptions={projectOptions} - selectedProjectId="project-group:platform" - selectedRepoIsGit - onRepoChange={() => {}} - onProjectChange={() => {}} - primaryActionLabel="Create workspace" - name="" - onNameValueChange={() => {}} - onSmartGitHubItemSelect={() => {}} - onSmartGitLabItemSelect={() => {}} - onSmartBranchSelect={() => {}} - onSmartLinearIssueSelect={() => {}} - smartNameSelection={null} - onClearSmartNameSelection={() => {}} - canReuseSelectedBranch={false} - reuseSelectedBranch={false} - onReuseSelectedBranchChange={() => {}} - forkPushWarning={null} - detectedAgentIds={null} - onOpenAgentSettings={() => {}} - advancedOpen={false} - onToggleAdvanced={() => {}} - parentWorktreeId={null} - onParentWorktreeIdChange={() => {}} - createDisabled={false} - projectError={null} - creating={false} - onCreate={() => {}} - note="" - onNoteChange={() => {}} - setupConfig={null} - requiresExplicitSetupChoice={false} - setupDecision={null} - onSetupDecisionChange={() => {}} - setupAgentStartupPolicy="start-immediately" - onSetupAgentStartupPolicyChange={() => {}} - shouldWaitForSetupCheck={false} - resolvedSetupDecision={null} - createError={null} - selectedRepoConnectionId={null} - selectedRepoSshStatus={null} - selectedRepoRequiresConnection={false} - selectedRepoConnectInProgress={false} - onConnectSelectedRepo={async () => {}} - canUseSparseCheckout={false} - sparsePresets={[]} - sparseSelectedPresetId={null} - onSparseSelectPreset={() => {}} - branchNameOverride={undefined} - onBranchNameOverrideChange={() => {}} - branchesEnabled={false} - setupControlsEnabled={false} - sparseControlsEnabled={false} - projectHostSetupOptions={hostOptions} - selectedProjectHostSetupId="setup-local" - {...overrides} - /> - ) - }) - // Settle mount-time warm before clicking; Vitest serializes overlapping imports unlike browsers. - await act(async () => {}) - return container -} diff --git a/src/renderer/src/components/activity/activity-clear-completed-hmr.test.ts b/src/renderer/src/components/activity/activity-clear-completed-hmr.test.ts deleted file mode 100644 index 395ef76fb99..00000000000 --- a/src/renderer/src/components/activity/activity-clear-completed-hmr.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' -import type { ActivityEvent, AgentPaneThread } from './activity-thread-types' -import { makeTab, makeWorktree } from './ActivityPrototypePage-test-fixtures' - -const mockStore = vi.hoisted(() => { - const activityClearedAtByPaneKey: Record = {} - const agentStatusByPaneKey: Record = {} - const retainedAgentsByPaneKey: Record = {} - const retentionSuppressedPaneKeys: Record = {} - const state = { - activityClearedAtByPaneKey, - agentStatusByPaneKey, - retainedAgentsByPaneKey, - retentionSuppressedPaneKeys, - applyActivityClearedAt: vi.fn((patch: Record) => { - const next = { ...state.activityClearedAtByPaneKey } - for (const [key, value] of Object.entries(patch)) { - if (value === null) { - delete next[key] - } else { - next[key] = value - } - } - state.activityClearedAtByPaneKey = next - }), - dismissRetainedAgents: vi.fn((paneKeys: readonly string[]) => { - const next = { ...state.retainedAgentsByPaneKey } - for (const key of paneKeys) { - if (state.agentStatusByPaneKey[key]) { - state.retentionSuppressedPaneKeys[key] = true - } - delete next[key] - } - state.retainedAgentsByPaneKey = next - }), - clearRetentionSuppressedPaneKeys: vi.fn((paneKeys: string[]) => { - for (const key of paneKeys) { - delete state.retentionSuppressedPaneKeys[key] - } - }), - retainAgents: vi.fn((entries: RetainedAgentEntry[]) => { - const next = { ...state.retainedAgentsByPaneKey } - for (const retained of entries) { - next[retained.entry.paneKey] = retained - } - state.retainedAgentsByPaneKey = next - }) - } - return state -}) - -const toastSpy = vi.hoisted(() => vi.fn()) - -vi.mock('@/store', () => ({ - useAppStore: { getState: () => mockStore } -})) -vi.mock('sonner', () => ({ toast: toastSpy })) - -import { - CLEAR_COMPLETED_EVICTION_FALLBACK_MS, - disposePendingClearCompletedEvictionListener, - clearCompletedActivity, - flushPendingClearCompletedEvictions -} from './activity-clear-completed' - -function makeThread(paneKey: string, overrides: Partial = {}): AgentPaneThread { - return { - paneKey, - tab: makeTab(), - worktree: makeWorktree(), - repo: null, - currentAgentState: null, - currentAgentEntry: null, - latestEvent: null, - latestTimestamp: 5_000, - agentType: 'claude', - unread: false, - paneTitle: `Agent ${paneKey}`, - responsePreview: '', - events: [], - ...overrides - } -} - -function doneEvent(interrupted: boolean): ActivityEvent { - return { - id: 'evt', - state: 'done', - timestamp: 5_000, - observedAt: 5_000, - worktree: makeWorktree(), - repo: null, - entry: { ...makeRetained('t-done:1').entry, interrupted }, - tab: makeTab(), - agentType: 'claude', - agentAlive: false, - unread: false - } -} - -const doneThread = makeThread('t-done:1', { latestEvent: doneEvent(false) }) - -function makeRetained(paneKey: string): RetainedAgentEntry { - return { - entry: { - state: 'done', - prompt: 'retained run', - updatedAt: 5_000, - stateStartedAt: 5_000, - paneKey, - stateHistory: [], - agentType: 'claude' - }, - worktreeId: 'wt-1', - tab: makeTab(), - agentType: 'claude', - startedAt: 5_000 - } -} - -const drop = vi.fn() -const domWindow = window -beforeEach(() => { - vi.useFakeTimers() - Object.assign(domWindow, { api: { agentStatus: { dropPersistedBatch: drop } } }) - mockStore.retainedAgentsByPaneKey = { 't-done:1': makeRetained('t-done:1') } - mockStore.activityClearedAtByPaneKey = {} - mockStore.retentionSuppressedPaneKeys = {} -}) -afterEach(() => { - flushPendingClearCompletedEvictions() - vi.useRealTimers() - vi.clearAllMocks() -}) - -it('preserves Undo after HMR without dropping the restored persisted row', () => { - clearCompletedActivity([doneThread]) - disposePendingClearCompletedEvictionListener() - const options = toastSpy.mock.calls.at(-1)?.[1] - options.action.onClick() - domWindow.dispatchEvent(new Event('pagehide')) - vi.advanceTimersByTime(CLEAR_COMPLETED_EVICTION_FALLBACK_MS) - expect(drop).not.toHaveBeenCalled() - expect(mockStore.retainedAgentsByPaneKey['t-done:1']).toBeDefined() -}) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx deleted file mode 100644 index c4cd46c9ff6..00000000000 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { ComponentProps } from 'react' -import type * as LaunchSetup from './AgentLaunchSetupButton' -import { AgentLaunchSetupButton } from './AgentLaunchSetupButton' -import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, - DropdownMenuSub, - DropdownMenuSubTrigger -} from '@/components/ui/dropdown-menu' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' - -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) -vi.mock('./AgentLaunchSetupButton', async (importOriginal) => ({ - ...(await importOriginal()), - AgentLaunchSetupButton: vi.fn((props: ComponentProps) => ( - - - {props.renderAnchor?.()} - - - )) -})) -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -it('skips unchanged search rows on unrelated inventory updates and launches current choices', () => { - const codex: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'cli' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [ - { - id: 'host-model', - label: 'Host model', - isDefault: true, - efforts: [{ value: 'low', label: 'Low' }] - } - ] - } - } - const claude: AgentPickerEntry = { - ...codex, - agent: 'claude', - label: 'Claude', - rows: [{ agent: 'claude', kind: 'cli' }], - catalog: { origin: 'probe', fetchedAt: 1, models: [] } - } - const launch = vi.fn() - const menu = (entries: AgentPickerEntry[]) => ( - - Open - - - - - ) - const view = render(menu([codex, claude])) - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'host low' } }) - expect(screen.getByRole('menuitem').textContent).toContain('Codex · Host model · Low') - expect(vi.mocked(AgentLaunchSetupButton).mock.lastCall?.[0].seed).toEqual({ - agent: 'codex', - surface: 'terminal', - choices: { model: 'host-model', options: { effort: 'low' } }, - acceptedEdits: { choices: { model: 'host-model', options: { effort: 'low' } } }, - delegated: [], - literalKeys: [] - }) - vi.mocked(AgentLaunchSetupButton).mockClear() - view.rerender( - menu([codex, { ...claude, catalog: { origin: 'probe', fetchedAt: 2, models: [] } }]) - ) - expect(AgentLaunchSetupButton).not.toHaveBeenCalled() - - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'host' } }) - expect(AgentLaunchSetupButton).toHaveBeenCalled() - fireEvent.click(screen.getByRole('menuitem')) - expect(launch).toHaveBeenCalledWith( - expect.objectContaining({ agent: 'codex', kind: 'cli' }), - { - agent: 'codex', - surface: 'terminal', - choices: { model: 'host-model' }, - acceptedEdits: { choices: { model: 'host-model', options: {} } }, - delegated: [], - literalKeys: [] - }, - codex - ) -}) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx index 12f62eb21f7..7b314f5c2a9 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx @@ -71,11 +71,7 @@ it.each(['claude', 'codex'] as const)( fireEvent.click(panel().querySelector('[cmdk-item]')!) fireEvent.click(getByRole(document.body, 'radio', { name: 'High' })) // A speed edit copies the current Arguments into the draft; later settings must still win. - fireEvent.click( - agent === 'claude' - ? getByRole(document.body, 'button', { name: 'Fast' }) - : getByRole(document.body, 'radio', { name: 'Fast' }) - ) + fireEvent.click(getByRole(document.body, 'button', { name: 'Fast' })) changePrompt( panel().querySelector('[contenteditable]')!, 'keep @/repo/exact-file.ts' diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index 7e420a90701..f1674e82ec5 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -27,7 +27,7 @@ import { AgentDefaultArgsInput } from './launch-settings/AgentLaunchDefaultsEdit import { NativeChatSessionOptionRows } from '../native-chat/session/options/controls/NativeChatSessionOptionRows' import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible' import type { SessionOptionDescriptor } from '../../../../shared/native-chat/input/native-chat-session-options' -import { AgentPermissionMenu } from './launch-settings/AgentPermissionChoiceControls' +import { AgentPermissionMenu } from './launch-settings/AgentPermissionMenu' import { AgentLaunchSetupFooter, agentLaunchSetupArgumentsNote, diff --git a/src/renderer/src/components/agent/launch-settings/AgentArgsChoiceChips.tsx b/src/renderer/src/components/agent/launch-settings/AgentArgsChoiceChips.tsx new file mode 100644 index 00000000000..e5ea2e81420 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/AgentArgsChoiceChips.tsx @@ -0,0 +1,125 @@ +import type { Ref } from 'react' +import { X } from 'lucide-react' +import { useTranslate } from '../../../i18n/use-translate' +import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' +import type { AgentArgsChoice } from './agent-args-choice' + +function AgentArgsChoiceChip({ + label, + flag, + onRemove, + disabled, + chipRef, + buttonRef, + choiceKey, + source +}: { + label: string + flag: string + onRemove: () => void + disabled?: boolean + chipRef?: Ref + buttonRef?: Ref + choiceKey: string + source?: 'arguments' +}): React.JSX.Element { + const t = useTranslate() + return ( + + + + {flag} + + + + + {source === 'arguments' + ? t('agentPicker.argumentsHint', 'Applies only to CLI launches.') + : choiceKey !== 'permissionMode' + ? t( + 'settings.agents.choiceChipTooltip', + 'Added by {{choice}}. Remove it to use the default.', + { + choice: + choiceKey === 'model' + ? t('settings.sourceControl.actionModel.model', 'Model') + : t('settings.sourceControl.actionModel.effort', 'Effort') + } + ) + : t( + 'settings.agents.permissionChipTooltip', + 'Added by Permissions. Remove it to use {{agent}}’s own settings.', + { agent: label } + )} + + + ) +} + +export function AgentArgsChoiceChips({ + chips, + disabled, + chipRef, + buttonRef, + onRemove +}: { + chips: readonly AgentArgsChoice[] + disabled?: boolean + chipRef?: Ref + buttonRef?: Ref + onRemove: (chip: AgentArgsChoice) => void +}): React.JSX.Element { + return ( + + {chips.map((chip, index) => ( + onRemove(chip)} + /> + ))} + + ) +} diff --git a/src/renderer/src/components/agent/launch-settings/AgentChatChoiceControls.tsx b/src/renderer/src/components/agent/launch-settings/AgentChatChoiceControls.tsx index 8d325ff20ec..10c739f54dd 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChatChoiceControls.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChatChoiceControls.tsx @@ -4,15 +4,13 @@ import { useTranslate } from '@/i18n/use-translate' import { antigravityChatSignInRunning } from '@/runtime/provider-accounts/sign-in/antigravity-chat-sign-in-status' import { useManagedRuntimeInstall } from '@/runtime/hosts/installation/use-managed-runtime-install' import { ManagedRuntimeInstallRow } from '../../managed-runtime/ManagedRuntimeInstallRow' -import { useAntigravityChatSignIn } from '../../provider-accounts/AntigravityChatSignInRow' -import { - AntigravityProviderSignInArea, - antigravityProviderSignInShown -} from '../../provider-accounts/AntigravityProviderSignInArea' +import { useAntigravityChatSignIn } from '../../provider-accounts/use-antigravity-chat-sign-in' +import { AntigravityProviderSignInArea } from '../../provider-accounts/AntigravityProviderSignInArea' +import { antigravityProviderSignInShown } from '../../provider-accounts/antigravity-chat-runtime-sign-in-policy' import { getHostRuntimeLabel, getRuntimeSentenceLabel -} from '../../settings/accounts/scope/accounts-pane-runtime' +} from '../../../lib/provider-accounts/account-runtime-label' import type { AgentOpensAs } from '../../../lib/agent-session/launch/native-chat-provider-choice' import { SettingsSegmentedControl } from '../../settings/form-controls/SettingsFormControls' import { structuredChatUnavailableOnPlatform } from '../../../../../shared/agent-session/structured-chat-platform-support' diff --git a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx index 0f5d09aecd0..f79f0fc0178 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx @@ -2,13 +2,11 @@ import type { AgentChoicePatch, AgentDedicatedChoices } from '../../../../../shared/agent-launch/choices/agent-launch-choices' - import { reconcileAgentChoiceArgs } from '../../../../../shared/agent-launch/choices/agent-choice-reconciliation' import { findCatalogModel, getAgentSessionOptionLaunchCatalog } from '../../../../../shared/agent-session/options/agent-session-option-catalog' - import { sourceControlActionAgentPicksModel, sourceControlActionOptions @@ -16,7 +14,7 @@ import { import { encodeCatalogOptionValue } from '../../../../../shared/agent-session/options/structured-agent-session-option-codec' import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import { AgentChoiceMenu } from './AgentChoiceMenu' -import { sourceControlActionRouteHint } from './AgentChoiceOptionField' +import { sourceControlActionRouteHint } from './agent-choice-route-hint' import { useTranslate } from '@/i18n/use-translate' const AGENT_DEFAULT_VALUE = '__agent_default__' diff --git a/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx b/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx index 6d1c2c9a4f3..476815e0c6b 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx @@ -2,9 +2,6 @@ import type { ReactNode } from 'react' import { Label } from '../../ui/label' import { SelectTrigger, SelectValue } from '../../ui/select' import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' -import { translate } from '@/i18n/i18n' -import type { Translate } from '@/i18n/use-translate' -import type { SourceControlActionChoiceRoute } from '../../../../../shared/source-control/ai/recipes/source-control-action-options' export function SourceControlActionOptionField({ label, @@ -24,18 +21,6 @@ export function SourceControlActionOptionField({ ) } -/** Says which launches a saved choice reaches when it is not both. */ -export function sourceControlActionRouteHint( - route: SourceControlActionChoiceRoute, - t: Translate = translate -): string | null { - return route === 'chats' - ? t('settings.sourceControl.actionModel.chatsOnly', 'Applies to chats only') - : route === 'terminals' - ? t('settings.sourceControl.actionModel.terminalsOnly', 'Applies to terminals only') - : null -} - export function SourceControlActionOptionTrigger({ label, disabled diff --git a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx index 578f84149b1..6e95245b19c 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx @@ -5,13 +5,12 @@ import { type AgentChoicePatch } from '../../../../../shared/agent-launch/choices/agent-launch-choices' import { AgentDefaultArgsInput } from './AgentLaunchDefaultsEditor' -import { AgentPermissionMenu, type AgentPermissionChoiceRow } from './AgentPermissionChoiceControls' +import { AgentPermissionMenu } from './AgentPermissionMenu' +import type { AgentPermissionChoiceRow } from './agent-permission-choice-row' import { agentModelChoiceChips } from './agent-model-choice-chips' import { useAgentLaunchFieldWrite } from './use-agent-launch-field-write' import { reconcileAgentChoiceArgs } from '../../../../../shared/agent-launch/choices/agent-choice-reconciliation' - import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' - import { useTranslate } from '@/i18n/use-translate' import { AgentChoiceFields } from './AgentChoiceControls' diff --git a/src/renderer/src/components/agent/launch-settings/AgentLaunchDefaultsEditor.tsx b/src/renderer/src/components/agent/launch-settings/AgentLaunchDefaultsEditor.tsx index f6ec4790271..2880c1a64ed 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentLaunchDefaultsEditor.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentLaunchDefaultsEditor.tsx @@ -9,7 +9,8 @@ import { type AgentDefaultEnvDraftInvalidReason } from './agent-default-env-draft' import { useAgentLaunchFieldWrite } from './use-agent-launch-field-write' -import { AgentArgsChoiceChips, type AgentArgsChoice } from './AgentPermissionChoiceControls' +import { AgentArgsChoiceChips } from './AgentArgsChoiceChips' +import type { AgentArgsChoice } from './agent-args-choice' export function AgentCommandOverrideInput({ defaultCmd, diff --git a/src/renderer/src/components/agent/launch-settings/AgentPermissionChoiceControls.tsx b/src/renderer/src/components/agent/launch-settings/AgentPermissionChoiceControls.tsx deleted file mode 100644 index e0e630ca7cb..00000000000 --- a/src/renderer/src/components/agent/launch-settings/AgentPermissionChoiceControls.tsx +++ /dev/null @@ -1,386 +0,0 @@ -import { AgentPermissionMenuOptions } from './AgentPermissionMenuOptions' -import { ChevronDown, X } from 'lucide-react' -import type { Ref } from 'react' -import type { AgentChatPermissionMode } from '../../../../../shared/agent-launch/permissions/agent-chat-permission-mode' -import type { AgentPermissionChoice } from '../../../../../shared/agent-launch/permissions/tui-agent-permission-choice' -import { translate } from '@/i18n/i18n' -import { useTranslate } from '@/i18n/use-translate' -import type { Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' -import { Button } from '../../ui/button' -import { Label } from '../../ui/label' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuRadioGroup, - DropdownMenuTrigger -} from '../../ui/dropdown-menu' -import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' -import { nativeChatPermissionModeLabel } from '../../native-chat/session/options/controls/native-chat-permission-mode-labels' -import { AgentPermissionChoiceItems, AgentPermissionChoiceName } from './AgentPermissionChoiceItems' - -/** Use chat-mode wording; own names the agent when available. */ -export function agentPermissionChoiceLabel( - choice: AgentPermissionChoice, - agentLabel: string | null, - t: Translate = translate -): string { - if (choice !== 'own') { - return nativeChatPermissionModeLabel(choice, t) - } - return agentLabel - ? t('settings.agents.permissionOwnAgent', "Use {{agent}}'s own settings", { - agent: agentLabel - }) - : t('settings.agents.permissionOwnAll', "Agents' own settings") -} - -export function AllAgentsPermissionSetting({ - chatOwnSupported = false, - choice, - withoutAutoChoice, - onChange, - onChangeWithoutAuto -}: { - chatOwnSupported?: boolean - choice: AgentPermissionChoice | null - /** What the agents without Approve for me share; null when they differ. */ - withoutAutoChoice: AgentPermissionChoice | null - onChange: (choice: AgentPermissionChoice) => void - onChangeWithoutAuto: (choice: AgentPermissionChoice) => void -}): React.JSX.Element { - const t = useTranslate() - const title = t('settings.agents.permissionsTitle', 'Permissions') - const ownLabel = t('settings.agents.permissionEachOwn', "Each agent's own settings") - const withoutAutoTitle = t( - 'settings.agents.otherAgentsPermissionsLabel', - 'Permissions for other agents' - ) - return ( -
-
-

{title}

- - - - - - - - - - -
-

- {t( - 'settings.agents.permissionsChoiceExplanation', - 'What every agent may do without asking. You can set one agent differently below.' - )} -

-
- {choice === 'auto' ? ( -
- - {t('settings.agents.permissionWithoutAuto', 'Agents without Approve for me')} - - - - - - - - - - - -
- ) : null} -
-
- ) -} - -export type AgentPermissionChoiceRow = { - chatOwnSupported?: boolean - choices: readonly AgentPermissionChoice[] - choice: AgentPermissionChoice - source: 'agent' | 'all' - terminalChoice?: AgentPermissionChoice - chatChoice?: AgentChatPermissionMode | null - /** What this agent gets from the all-agents choice. */ - defaultChoice: AgentPermissionChoice - onSelect: (choice: AgentPermissionChoice | 'default') => void - /** The flag terminals add, shown as a chip in Arguments; empty when none. */ - flag: string - /** The agent's own Arguments set permissions, so terminals use those instead. */ - argsSetPermission: boolean -} - -export function AgentPermissionMenu({ - agentId, - label, - permission, - inheritLabel, - onOpenChange, - disabled, - size = 'xs', - layout = 'inline', - showInherited = true, - rawValue -}: { - agentId: string - label: string - permission: AgentPermissionChoiceRow - inheritLabel?: string - onOpenChange?: (open: boolean) => void - disabled?: boolean - size?: 'xs' | 'sm' - /** Row: muted label left and the menu right, like the chat composer's option rows. */ - layout?: 'inline' | 'stacked' | 'row' - showInherited?: boolean - rawValue?: string -}): React.JSX.Element { - const t = useTranslate() - const followAll = inheritLabel ?? t('settings.agents.permissionSameAsAll', 'Same as all agents') - const ownLabel = agentPermissionChoiceLabel('own', label, t) - return ( -
- {layout === 'row' ? ( - - {t('settings.agents.rowPermissions', 'Permissions')} - - ) : layout === 'stacked' ? ( - - ) : ( - - {t('settings.agents.rowPermissions', 'Permissions')} - - )} - - - - - - - - - {permission.terminalChoice === 'own' && permission.chatChoice ? ( - - {t( - 'settings.agents.permissionSurfaceDifference', - 'Terminals use the agent’s own settings; new chats use {{mode}}.', - { mode: nativeChatPermissionModeLabel(permission.chatChoice, t) } - )} - - ) : null} -
- ) -} - -function AgentArgsChoiceChip({ - label, - flag, - onRemove, - disabled, - chipRef, - buttonRef, - choiceKey, - source -}: { - label: string - flag: string - onRemove: () => void - disabled?: boolean - chipRef?: Ref - buttonRef?: Ref - choiceKey: string - source?: 'arguments' -}): React.JSX.Element { - const t = useTranslate() - return ( - - - - {flag} - - - - - {source === 'arguments' - ? t('agentPicker.argumentsHint', 'Applies only to CLI launches.') - : choiceKey !== 'permissionMode' - ? t( - 'settings.agents.choiceChipTooltip', - 'Added by {{choice}}. Remove it to use the default.', - { - choice: - choiceKey === 'model' - ? t('settings.sourceControl.actionModel.model', 'Model') - : t('settings.sourceControl.actionModel.effort', 'Effort') - } - ) - : t( - 'settings.agents.permissionChipTooltip', - 'Added by Permissions. Remove it to use {{agent}}’s own settings.', - { agent: label } - )} - - - ) -} - -export type AgentArgsChoice = { - key: string - label: string - flag: string - onRemove: (text: string) => string - source?: 'arguments' -} - -export function AgentArgsChoiceChips({ - chips, - disabled, - chipRef, - buttonRef, - onRemove -}: { - chips: readonly AgentArgsChoice[] - disabled?: boolean - chipRef?: Ref - buttonRef?: Ref - onRemove: (chip: AgentArgsChoice) => void -}): React.JSX.Element { - return ( - - {chips.map((chip, index) => ( - onRemove(chip)} - /> - ))} - - ) -} diff --git a/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx new file mode 100644 index 00000000000..5755c37a089 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx @@ -0,0 +1,107 @@ +import { useTranslate } from '../../../i18n/use-translate' +import { cn } from '../../../lib/utils' +import { ChevronDown } from 'lucide-react' +import { Button } from '../../ui/button' +import { Label } from '../../ui/label' +import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '../../ui/dropdown-menu' +import { nativeChatPermissionModeLabel } from '../../native-chat/session/options/controls/native-chat-permission-mode-labels' +import { AgentPermissionChoiceName } from './AgentPermissionChoiceItems' +import { AgentPermissionMenuOptions } from './AgentPermissionMenuOptions' +import type { AgentPermissionChoiceRow } from './agent-permission-choice-row' +import { agentPermissionChoiceLabel } from './agent-permission-choice-label' + +export function AgentPermissionMenu({ + agentId, + label, + permission, + inheritLabel, + onOpenChange, + disabled, + size = 'xs', + layout = 'inline', + showInherited = true, + rawValue +}: { + agentId: string + label: string + permission: AgentPermissionChoiceRow + inheritLabel?: string + onOpenChange?: (open: boolean) => void + disabled?: boolean + size?: 'xs' | 'sm' + /** Row: muted label left and the menu right, like the chat composer's option rows. */ + layout?: 'inline' | 'stacked' | 'row' + showInherited?: boolean + rawValue?: string +}): React.JSX.Element { + const t = useTranslate() + const followAll = inheritLabel ?? t('settings.agents.permissionSameAsAll', 'Same as all agents') + const ownLabel = agentPermissionChoiceLabel('own', label, t) + return ( +
+ {layout === 'row' ? ( + + {t('settings.agents.rowPermissions', 'Permissions')} + + ) : layout === 'stacked' ? ( + + ) : ( + + {t('settings.agents.rowPermissions', 'Permissions')} + + )} + + + + + + + + + {permission.terminalChoice === 'own' && permission.chatChoice ? ( + + {t( + 'settings.agents.permissionSurfaceDifference', + 'Terminals use the agent’s own settings; new chats use {{mode}}.', + { mode: nativeChatPermissionModeLabel(permission.chatChoice, t) } + )} + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/agent/launch-settings/AgentPermissionMenuOptions.tsx b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenuOptions.tsx index 952fcc138b4..c5469c2802a 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentPermissionMenuOptions.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenuOptions.tsx @@ -1,4 +1,4 @@ -import type { AgentPermissionChoiceRow } from './AgentPermissionChoiceControls' +import type { AgentPermissionChoiceRow } from './agent-permission-choice-row' import { AgentPermissionChoiceItems, AgentPermissionChoiceName } from './AgentPermissionChoiceItems' import { DropdownMenuRadioGroup, diff --git a/src/renderer/src/components/agent/launch-settings/agent-args-choice.ts b/src/renderer/src/components/agent/launch-settings/agent-args-choice.ts new file mode 100644 index 00000000000..1ce39193b46 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/agent-args-choice.ts @@ -0,0 +1,7 @@ +export type AgentArgsChoice = { + key: string + label: string + flag: string + onRemove: (text: string) => string + source?: 'arguments' +} diff --git a/src/renderer/src/components/agent/launch-settings/agent-choice-route-hint.ts b/src/renderer/src/components/agent/launch-settings/agent-choice-route-hint.ts new file mode 100644 index 00000000000..bbdb0704342 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/agent-choice-route-hint.ts @@ -0,0 +1,15 @@ +import { translate } from '../../../i18n/i18n' +import type { Translate } from '../../../i18n/use-translate' +import type { SourceControlActionChoiceRoute } from '../../../../../shared/source-control/ai/recipes/source-control-action-options' + +/** Says which launches a saved choice reaches when it is not both. */ +export function sourceControlActionRouteHint( + route: SourceControlActionChoiceRoute, + t: Translate = translate +): string | null { + return route === 'chats' + ? t('settings.sourceControl.actionModel.chatsOnly', 'Applies to chats only') + : route === 'terminals' + ? t('settings.sourceControl.actionModel.terminalsOnly', 'Applies to terminals only') + : null +} diff --git a/src/renderer/src/components/agent/launch-settings/agent-model-choice-chips.ts b/src/renderer/src/components/agent/launch-settings/agent-model-choice-chips.ts index b3b66c6a36a..6a7f68d79bf 100644 --- a/src/renderer/src/components/agent/launch-settings/agent-model-choice-chips.ts +++ b/src/renderer/src/components/agent/launch-settings/agent-model-choice-chips.ts @@ -10,7 +10,7 @@ import type { } from '../../../../../shared/agent-launch/choices/agent-launch-choices' import type { AgentArgsProjectionContext } from '../../../../../shared/agent-launch/picker/agent-launch-picker-arguments' import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' -import type { AgentArgsChoice } from './AgentPermissionChoiceControls' +import type { AgentArgsChoice } from './agent-args-choice' export function agentModelChoiceChips( agent: TuiAgent | null | undefined, diff --git a/src/renderer/src/components/agent/launch-settings/agent-permission-choice-label.ts b/src/renderer/src/components/agent/launch-settings/agent-permission-choice-label.ts new file mode 100644 index 00000000000..5ebe2a5a566 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/agent-permission-choice-label.ts @@ -0,0 +1,20 @@ +import type { AgentPermissionChoice } from '../../../../../shared/agent-launch/permissions/tui-agent-permission-choice' +import { translate } from '../../../i18n/i18n' +import type { Translate } from '../../../i18n/use-translate' +import { nativeChatPermissionModeLabel } from '../../native-chat/session/options/controls/native-chat-permission-mode-labels' + +/** Use chat-mode wording; own names the agent when available. */ +export function agentPermissionChoiceLabel( + choice: AgentPermissionChoice, + agentLabel: string | null, + t: Translate = translate +): string { + if (choice !== 'own') { + return nativeChatPermissionModeLabel(choice, t) + } + return agentLabel + ? t('settings.agents.permissionOwnAgent', "Use {{agent}}'s own settings", { + agent: agentLabel + }) + : t('settings.agents.permissionOwnAll', "Agents' own settings") +} diff --git a/src/renderer/src/components/agent/launch-settings/agent-permission-choice-row.ts b/src/renderer/src/components/agent/launch-settings/agent-permission-choice-row.ts new file mode 100644 index 00000000000..9e282eb6f39 --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/agent-permission-choice-row.ts @@ -0,0 +1,18 @@ +import type { AgentChatPermissionMode } from '../../../../../shared/agent-launch/permissions/agent-chat-permission-mode' +import type { AgentPermissionChoice } from '../../../../../shared/agent-launch/permissions/tui-agent-permission-choice' + +export type AgentPermissionChoiceRow = { + chatOwnSupported?: boolean + choices: readonly AgentPermissionChoice[] + choice: AgentPermissionChoice + source: 'agent' | 'all' + terminalChoice?: AgentPermissionChoice + chatChoice?: AgentChatPermissionMode | null + /** What this agent gets from the all-agents choice. */ + defaultChoice: AgentPermissionChoice + onSelect: (choice: AgentPermissionChoice | 'default') => void + /** The flag terminals add, shown as a chip in Arguments; empty when none. */ + flag: string + /** The agent's own Arguments set permissions, so terminals use those instead. */ + argsSetPermission: boolean +} diff --git a/src/renderer/src/components/automations/ExternalAutomationManagers.tsx b/src/renderer/src/components/automations/ExternalAutomationManagers.tsx index a7edf9e576d..16d1f70dab8 100644 --- a/src/renderer/src/components/automations/ExternalAutomationManagers.tsx +++ b/src/renderer/src/components/automations/ExternalAutomationManagers.tsx @@ -2,7 +2,7 @@ import React from 'react' import { Play, RefreshCw, Trash2 } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' -import { SettingsSwitch } from '@/components/settings/form-controls/SettingsFormControls' +import { Switch } from '@/components/ui/switch' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import type { ExternalAutomationAction, @@ -182,13 +182,13 @@ export function ExternalAutomationManagers({ runningActionKey === actionKey('resume') ? ( ) : null} - + onCheckedChange={() => onAction(manager, job, job.enabled ? 'pause' : 'resume', scope) } disabled={disabledMessage !== null} - ariaLabelledBy={nameId} + aria-labelledby={nameId} /> diff --git a/src/renderer/src/components/automations/automation-captured-owner.test.ts b/src/renderer/src/components/automations/automation-captured-owner.test.ts index 4d7c268fa66..bfed0d073d2 100644 --- a/src/renderer/src/components/automations/automation-captured-owner.test.ts +++ b/src/renderer/src/components/automations/automation-captured-owner.test.ts @@ -1,63 +1,9 @@ import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationOwnerRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationHostRow } from './automation-host-cache-types' import { automationActionAvailability, - captureAutomationOwners, isAutomationActionEnabled } from './automation-captured-owner' -const DESKTOP_SELF: AutomationOwnerRef = { - authority: { kind: 'desktop' }, - selector: { kind: 'self' } -} - -const RUNTIME_SELF: AutomationOwnerRef = { - authority: { kind: 'runtime', environmentId: 'gpu', pairingRevision: 1 }, - selector: { kind: 'self' } -} - -function automation(overrides: Partial = {}): Automation { - return { - id: 'a-1', - name: 'Nightly', - prompt: 'sweep', - precheck: null, - agentId: 'claude', - runContext: null, - projectId: 'repo-1', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: 1, - enabled: true, - nextRunAt: 2, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -function row(overrides: Partial): AutomationHostRow { - return { - automation: automation(), - owner: DESKTOP_SELF, - selector: { kind: 'self' }, - usageSummary: null, - usageKnown: false, - ...overrides - } -} - describe('captured owner availability', () => { it('keeps delete and pause fenceable on an orphan while refusing to run it', () => { const orphan = { owner: null, selector: { kind: 'orphan' as const, issue: 'gone' } } @@ -71,16 +17,4 @@ describe('captured owner availability', () => { expect(isAutomationActionEnabled(orphan, 'run')).toBe(false) expect(isAutomationActionEnabled(orphan, 'delete')).toBe(true) }) - - it("keeps both authorities' owners when they hold the same automation ID", () => { - const captured = captureAutomationOwners([ - { rowKey: 'row|desktop|a-1', row: row({ automation: automation({ id: 'a-1' }) }) }, - { - rowKey: 'row|runtime|a-1', - row: row({ automation: automation({ id: 'a-1' }), owner: RUNTIME_SELF }) - } - ]) - expect(captured.get('row|desktop|a-1')?.owner).toEqual(DESKTOP_SELF) - expect(captured.get('row|runtime|a-1')?.owner).toEqual(RUNTIME_SELF) - }) }) diff --git a/src/renderer/src/components/automations/automation-host-invalidation.test.ts b/src/renderer/src/components/automations/automation-host-invalidation.test.ts deleted file mode 100644 index 85559723498..00000000000 --- a/src/renderer/src/components/automations/automation-host-invalidation.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** Scoped events invalidate one entry, unscoped events their authority, and neither crosses authority boundaries. */ - -import { describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' - -import type { - StableAutomationAuthorityRef, - StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import { createAutomationHostCache, type AutomationHostCache } from './automation-host-cache' -import type { AutomationHostRow } from './automation-host-cache-types' -import { createAutomationHostInvalidation } from './automation-host-invalidation' - -const DESKTOP: StableAutomationAuthorityRef = { kind: 'desktop' } -const RUNTIME: StableAutomationAuthorityRef = { kind: 'runtime', environmentId: 'env-1' } -const DESKTOP_SELF: StableAutomationCatalogRef = { authority: DESKTOP, selector: { kind: 'self' } } -const DESKTOP_SSH: StableAutomationCatalogRef = { - authority: DESKTOP, - selector: { kind: 'ssh', targetId: 'target-1' } -} -const RUNTIME_SELF: StableAutomationCatalogRef = { authority: RUNTIME, selector: { kind: 'self' } } - -function row(id: string): AutomationHostRow { - return { - automation: { id } as Automation, - owner: null, - selector: { kind: 'self' }, - usageSummary: null, - usageKnown: false - } -} - -function seeded(): AutomationHostCache { - const cache = createAutomationHostCache({ - catalogGeneration: () => 0, - connectionGeneration: () => 0 - }) - for (const ref of [DESKTOP_SELF, DESKTOP_SSH, RUNTIME_SELF]) { - cache.commit(cache.beginRequest(ref), { rows: [row('a')] }) - } - return cache -} - -describe('automation host invalidation', () => { - it('drops queued work once disposed', async () => { - const cache = seeded() - const onInvalidated = vi.fn() - const invalidation = createAutomationHostInvalidation({ cache, onInvalidated }) - invalidation.handle({ authority: DESKTOP }) - invalidation.dispose() - await Promise.resolve() - expect(onInvalidated).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/automations/automation-list-view.test.ts b/src/renderer/src/components/automations/automation-list-view.test.ts deleted file mode 100644 index 1a408982695..00000000000 --- a/src/renderer/src/components/automations/automation-list-view.test.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRunStatus } from '../../../../shared/automations/history/automation-run' -import type { - ExternalAutomationJob, - ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' -import { - EMPTY_AUTOMATION_LIST_FILTER, - filterAutomationListRows, - filterExternalAutomationListEntries, - type AutomationListFilter -} from './automation-list-view' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { AutomationListRow } from './automation-list-row-identity' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' - -function makeAutomation(overrides: Partial = {}): Automation { - return { - id: 'automation-1', - name: 'Zebra job', - prompt: 'run', - precheck: null, - agentId: 'codex', - projectId: 'repo-1', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'existing', - workspaceId: 'worktree-1', - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: 1, - enabled: true, - nextRunAt: 2, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -function makeExternalEntry( - overrides: Partial = {} -): ExternalAutomationListEntry { - const manager: ExternalAutomationManager = { - id: 'manager-1', - provider: 'openclaw', - label: 'Local OpenClaw', - targetLabel: 'Local', - target: { type: 'local' }, - status: 'available', - error: null, - canManage: true, - jobs: [] - } - const job: ExternalAutomationJob = { - id: 'job-1', - managerId: manager.id, - provider: 'openclaw', - name: 'Alpha digest', - schedule: '0 9 * * 1-5', - rawSchedule: null, - enabled: true, - state: 'enabled', - prompt: null, - promptPreview: '', - nextRunAt: null, - lastRunAt: '2026-08-12T01:00:00Z', - lastStatus: 'failed', - lastError: null, - workdir: null, - runCount: 1, - runs: [], - ...overrides - } - return { - key: `${manager.id}:${job.id}`, - scope: { - owner: { authority: { kind: 'desktop' }, selector: { kind: 'self' } }, - provider: manager.provider - }, - manager, - job - } -} - -/** A catalog row with an optional projected last-run status, keyed like a real host row. */ -function makeCatalogRow( - id: string, - overrides: Partial = {}, - lastRunStatus?: AutomationRunStatus -): AutomationListRow { - return { - key: `row|host|${id}`, - automation: makeAutomation({ id, ...overrides }), - hostLabel: 'This computer', - usageSummary: lastRunStatus - ? { - knownRuns: 1, - unavailableRuns: 0, - inputTokens: 0, - outputTokens: 0, - cacheTokens: 0, - reasoningOutputTokens: 0, - totalTokens: 0, - estimatedCostUsd: null, - lastRunStatus, - lastRunAt: 111 - } - : null - } -} - -describe('automation-list-view', () => { - it('filters catalog rows by status, agent, and the projected last-run status', () => { - const rows = [ - makeCatalogRow('paused-codex', { enabled: false, agentId: 'codex' }), - makeCatalogRow('failed-claude', { agentId: 'claude' }, 'dispatch_failed'), - makeCatalogRow('succeeded-codex', { agentId: 'codex' }, 'completed'), - makeCatalogRow('never-codex', { agentId: 'codex' }) - ] - const ids = (filter: Partial) => - filterAutomationListRows(rows, { - ...EMPTY_AUTOMATION_LIST_FILTER, - ...filter - }).map((row) => row.automation.id) - - expect(ids({ status: 'paused' })).toEqual(['paused-codex']) - expect(ids({ agentIds: ['claude'] })).toEqual(['failed-claude']) - expect(ids({ lastRun: 'failed' })).toEqual(['failed-claude']) - expect(ids({ lastRun: 'succeeded' })).toEqual(['succeeded-codex']) - expect(ids({ lastRun: 'never' })).toEqual(['paused-codex', 'never-codex']) - // Inactive filter keeps the input identity so nothing re-renders for it. - expect(filterAutomationListRows(rows, EMPTY_AUTOMATION_LIST_FILTER)).toBe(rows) - }) - - it('narrows rows to any of the selected hosts and drops pre-catalog rows', () => { - const hostRow = (id: string, targetId: string | null): AutomationListRow => ({ - key: `row|${targetId ?? 'unscoped'}|${id}`, - automation: makeAutomation({ id }), - catalogRef: - targetId === null - ? null - : { - authority: { kind: 'desktop' }, - selector: { kind: 'ssh', targetId } - }, - hostLabel: targetId ?? '', - usageSummary: null - }) - const rows = [hostRow('on-a', 'ssh-a'), hostRow('on-b', 'ssh-b'), hostRow('legacy', null)] - const keyOf = (row: AutomationListRow): string => - row.catalogRef ? hostStableKey(row.catalogRef) : '' - const ids = (hostStableKeys: readonly string[]) => - filterAutomationListRows(rows, { - ...EMPTY_AUTOMATION_LIST_FILTER, - hostStableKeys - }).map((row) => row.automation.id) - - // Multi-select is any-of; a pre-catalog row names no host and is excluded. - expect(ids([keyOf(rows[0]), keyOf(rows[1])])).toEqual(['on-a', 'on-b']) - expect(ids([keyOf(rows[1])])).toEqual(['on-b']) - }) - - it('excludes external jobs from any agent filter and honors their status', () => { - const entries = [makeExternalEntry({ enabled: false, state: 'disabled' })] - expect( - filterExternalAutomationListEntries(entries, { - ...EMPTY_AUTOMATION_LIST_FILTER, - agentIds: ['codex'] - }) - ).toEqual([]) - expect( - filterExternalAutomationListEntries(entries, { - ...EMPTY_AUTOMATION_LIST_FILTER, - status: 'paused' - }) - ).toHaveLength(1) - expect( - filterExternalAutomationListEntries(entries, { - ...EMPTY_AUTOMATION_LIST_FILTER, - status: 'enabled' - }) - ).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/automations/automation-usage-model.test.ts b/src/renderer/src/components/automations/automation-usage-model.test.ts deleted file mode 100644 index a4ccbc78c20..00000000000 --- a/src/renderer/src/components/automations/automation-usage-model.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { summarizeAutomationRunUsage } from '../../../../shared/automations/history/automation-usage-summary' - -function makeRun(overrides: Partial): AutomationRun { - return { - id: 'run-1', - automationId: 'automation-1', - title: 'Run 1', - scheduledFor: 1, - status: 'completed', - trigger: 'manual', - workspaceId: 'wt1', - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: 'tab-1', - terminalPaneKey: 'tab-1:11111111-1111-4111-8111-111111111111', - terminalPtyId: 'pty-1', - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: 1, - dispatchedAt: 1, - createdAt: 1, - ...overrides - } -} - -describe('automation usage model', () => { - it('rolls known run usage up while preserving unavailable coverage', () => { - const summary = summarizeAutomationRunUsage([ - makeRun({ - usage: { - status: 'known', - provider: 'codex', - model: 'gpt-5.4', - inputTokens: 1000, - outputTokens: 300, - cacheReadTokens: 400, - cacheWriteTokens: null, - reasoningOutputTokens: 50, - totalTokens: 1350, - estimatedCostUsd: 0.0042, - estimatedCostSource: 'api_equivalent', - providerSessionId: 'session-1', - attribution: 'provider_session_time_window', - collectedAt: 1, - unavailableReason: null, - unavailableMessage: null - } - }), - makeRun({ - id: 'run-3', - createdAt: 3, - dispatchedAt: 3, - usage: { - status: 'known', - provider: 'claude', - model: 'sonnet', - inputTokens: 200, - outputTokens: 700, - cacheReadTokens: null, - cacheWriteTokens: 50, - reasoningOutputTokens: null, - totalTokens: 900, - estimatedCostUsd: 0.0042, - estimatedCostSource: 'api_equivalent', - providerSessionId: 'session-3', - attribution: 'provider_session_time_window', - collectedAt: 3, - unavailableReason: null, - unavailableMessage: null - } - }), - makeRun({ - id: 'run-2', - usage: { - status: 'unavailable', - provider: 'claude', - model: null, - inputTokens: null, - outputTokens: null, - cacheReadTokens: null, - cacheWriteTokens: null, - reasoningOutputTokens: null, - totalTokens: null, - estimatedCostUsd: null, - estimatedCostSource: null, - providerSessionId: null, - attribution: null, - collectedAt: 2, - unavailableReason: 'no_matching_session', - unavailableMessage: 'No matching session' - } - }) - ]) - - expect(summary).toEqual({ - knownRuns: 2, - unavailableRuns: 1, - inputTokens: 1200, - outputTokens: 1000, - cacheTokens: 450, - reasoningOutputTokens: 50, - totalTokens: 2250, - estimatedCostUsd: 0.0084, - lastRunStatus: 'completed', - lastRunAt: 3 - }) - }) -}) diff --git a/src/renderer/src/components/automations/external-automation-list-entries.test.ts b/src/renderer/src/components/automations/external-automation-list-entries.test.ts deleted file mode 100644 index 6f1e6a6dab3..00000000000 --- a/src/renderer/src/components/automations/external-automation-list-entries.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation' -import { buildExternalAutomationListEntries } from './external-automation-list-entries' -import type { ScopedExternalAutomationManager } from './external-automation-scope-client' - -function manager(overrides: Partial = {}): ExternalAutomationManager { - return { - id: 'openclaw:ssh:openclaw', - provider: 'openclaw', - label: 'OpenClaw on openclaw', - targetLabel: 'openclaw', - target: { type: 'ssh', connectionId: 'openclaw' }, - status: 'unavailable', - error: 'SSH target is not connected.', - canManage: false, - jobs: [], - ...overrides - } -} - -function job(id = 'job-1'): ExternalAutomationManager['jobs'][number] { - return { - id, - managerId: 'openclaw:ssh:openclaw', - provider: 'openclaw', - name: 'Nightly', - schedule: '0 9 * * *', - rawSchedule: '0 9 * * *', - enabled: true, - state: 'active', - prompt: 'do work', - promptPreview: 'do work', - nextRunAt: null, - lastRunAt: null, - lastStatus: null, - lastError: null, - workdir: null, - runCount: 1, - runs: [] - } -} - -function scoped( - environmentId: string | null, - overrides: Partial = {} -): ScopedExternalAutomationManager { - return { - scope: { - owner: { - authority: - environmentId === null - ? { kind: 'desktop' } - : { kind: 'runtime', environmentId, pairingRevision: 1 }, - selector: { kind: 'self' } - }, - provider: 'openclaw' - }, - manager: manager(overrides) - } -} - -describe('buildExternalAutomationListEntries', () => { - it('separates identical manager and job IDs reported by two authorities', () => { - // Manager/job IDs collide across authorities; qualify row identity to preserve independent selection, dialogs and reconciliation. - const entries = buildExternalAutomationListEntries([ - scoped(null, { id: 'openclaw:local', target: { type: 'local' }, jobs: [job()] }), - scoped('env-7', { id: 'openclaw:local', target: { type: 'local' }, jobs: [job()] }) - ]) - - expect(entries).toHaveLength(2) - expect(entries[0]?.key).not.toBe(entries[1]?.key) - }) -}) diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx index 6fa362ff9bf..bab415abcf3 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx @@ -197,96 +197,6 @@ describe('ClientHostedBrowserPagePane', () => { expect(screen.getByText('Client-hosted browser unavailable')).not.toBeNull() expect(document.querySelector('webview')).toBeNull() }) - - it('requests the one-time intro tour on the first active client-hosted page', async () => { - vi.useFakeTimers() - const { useAppStore } = await import('@/store') - const prior = { - persistedUIReady: useAppStore.getState().persistedUIReady, - contextualToursSeenIds: useAppStore.getState().contextualToursSeenIds, - activeContextualTourId: useAppStore.getState().activeContextualTourId - } - useAppStore.setState({ - persistedUIReady: true, - contextualToursSeenIds: [], - activeContextualTourId: null - }) - const { webview } = createWebview() - mocks.attach.mockReturnValue(retainedAttachment(webview)) - try { - render( - - ) - // Why: happy-dom rects are zero-sized and the tour gate requires a measurable target. - const target = document.querySelector( - '[data-contextual-tour-target="client-hosted-browser-controls"]' - ) - expect(target).not.toBeNull() - target!.getBoundingClientRect = () => new DOMRect(0, 0, 400, 32) - await act(async () => { - await vi.advanceTimersByTimeAsync(0) - }) - expect(useAppStore.getState().activeContextualTourId).toBe('client-hosted-browser') - } finally { - useAppStore.setState(prior) - vi.useRealTimers() - } - }) - - it('never re-requests the intro tour once it has been seen', async () => { - vi.useFakeTimers() - const { useAppStore } = await import('@/store') - const prior = { - persistedUIReady: useAppStore.getState().persistedUIReady, - contextualToursSeenIds: useAppStore.getState().contextualToursSeenIds, - activeContextualTourId: useAppStore.getState().activeContextualTourId - } - useAppStore.setState({ - persistedUIReady: true, - contextualToursSeenIds: ['client-hosted-browser'], - activeContextualTourId: null - }) - const { webview } = createWebview() - mocks.attach.mockReturnValue(retainedAttachment(webview)) - try { - render( - - ) - // Why: same measurable target as the positive case — only seenIds differs. - const target = document.querySelector( - '[data-contextual-tour-target="client-hosted-browser-controls"]' - ) - expect(target).not.toBeNull() - target!.getBoundingClientRect = () => new DOMRect(0, 0, 400, 32) - await act(async () => { - await vi.advanceTimersByTimeAsync(0) - }) - expect(useAppStore.getState().activeContextualTourId).toBeNull() - } finally { - useAppStore.setState(prior) - vi.useRealTimers() - } - }) }) describe('ClientHostedBrowserPagePane address bar parity', () => { diff --git a/src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts b/src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts index c2b5fdb82f7..b0079dabb8e 100644 --- a/src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts @@ -103,18 +103,6 @@ describe('formatBrowserAnnotationsAsMarkdown', () => { expect(markdown).not.toContain('\n## injected') }) - it('heads document preview annotations with the Windows file path', () => { - const annotation = makeAnnotation() - const sanitizedUrl = 'C:\\repo\\docs\\report.html' - const markdown = formatBrowserAnnotationsAsMarkdown([ - makeAnnotation({ - payload: { ...annotation.payload, page: { ...annotation.payload.page, sanitizedUrl } } - }) - ]) - - expect(markdown).toContain(`## Design Feedback: ${sanitizedUrl}`) - }) - it('does not split surrogate pairs at the inline annotation cap', () => { const annotation = makeAnnotation() const selectedText = `${'x'.repeat(BROWSER_ANNOTATION_INLINE_TEXT_MAX_LENGTH - 1)}😀tail` diff --git a/src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx b/src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx index dc279e30bd6..75877305444 100644 --- a/src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx +++ b/src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx @@ -287,27 +287,6 @@ describe('browser grab toast owner', () => { expect(next.view.result.current.grabToast).toBeNull() expect(vi.getTimerCount()).toBe(0) }) - it.each(['clipboard', 'interaction'] as const)( - 'honors reentrant cleanup during %s delivery', - async (point) => { - const payload = makePayload() - extract.mockResolvedValue({ ok: true, payload }) - const { view, bounds } = mount() - if (point === 'clipboard') { - writes.mockImplementationOnce(() => view.unmount()) - } else { - state.recordFeatureInteraction.mockImplementationOnce(() => view.unmount()) - } - await act(async () => { - view.result.current.handleGrabActionShortcut('c') - await Promise.resolve() - }) - expect(writes.mock.calls).toEqual([[formatGrabPayloadAsText(payload)]]) - expect(state.recordFeatureInteraction.mock.calls).toEqual([['browser-grab']]) - expect(bounds).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - } - ) it('preserves latest target reads and screenshot completion after cleanup', async () => { const extraction = deferred() const image = deferred<{ ok: true; screenshot: typeof screenshot }>() diff --git a/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts b/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts deleted file mode 100644 index ea8e840138c..00000000000 --- a/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' - -const mocks = vi.hoisted(() => ({ - createWebRuntimeSessionBrowserTab: vi.fn(async (_args: Record) => true) -})) - -vi.mock('@/runtime/browser/creation/web-runtime-browser-creation', () => ({ - createWebRuntimeSessionBrowserTab: mocks.createWebRuntimeSessionBrowserTab -})) - -import { resolveBrowserReopenOnServerUrl } from './browser-reopen-on-server' - -describe('resolveBrowserReopenOnServerUrl', () => { - it('reopens blank rather than replaying something the new engine cannot restore', () => { - expect(resolveBrowserReopenOnServerUrl(ORCA_BROWSER_BLANK_URL)).toBeUndefined() - expect(resolveBrowserReopenOnServerUrl('about:blank')).toBeUndefined() - expect(resolveBrowserReopenOnServerUrl('file:///etc/hosts')).toBeUndefined() - expect(resolveBrowserReopenOnServerUrl('')).toBeUndefined() - expect(resolveBrowserReopenOnServerUrl(null)).toBeUndefined() - expect(resolveBrowserReopenOnServerUrl(undefined)).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.test.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.test.ts deleted file mode 100644 index 243b075427a..00000000000 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// @vitest-environment happy-dom -import { expect, it, vi } from 'vitest' -import { publishNativeChatVisualGuestTheme } from '@/components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' - -vi.mock('@/components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher', () => ({ - publishNativeChatVisualGuestTheme: vi.fn() -})) -import { acquireWebviewsDragPassthrough } from '../host-guest/webview-drag-passthrough' -import { webviewRegistry } from '../host-guest/webview-registry' -import { attachDocPreviewWebview } from './doc-preview-webview-attach' - -function attach(previewId: string, container: HTMLDivElement) { - return attachDocPreviewWebview({ - previewId, - container, - url: 'orca-preview://grant/index.html', - ariaLabel: 'HTML preview', - onLoadStarted: vi.fn(), - onLoadStopped: vi.fn(), - onLoadFailed: vi.fn(), - onNavigated: vi.fn(), - onTitleUpdated: vi.fn(), - onViewportMessage: vi.fn() - }) -} - -it('restores pointer input when a drag ends after attaching a document preview', () => { - const container = document.createElement('div') - document.body.appendChild(container) - const append = vi.spyOn(container, 'appendChild') - append.mockImplementation((node) => { - expect(publishNativeChatVisualGuestTheme).toHaveBeenCalledTimes(1) - expect((node as HTMLElement).style.pointerEvents).toBe('none') - return Node.prototype.appendChild.call(container, node) - }) - const release = acquireWebviewsDragPassthrough() - const attached = attach('preview-drag', container) - - try { - expect(webviewRegistry.get('preview-drag')).toBe(attached.webview) - expect(attached.webview.style.pointerEvents).toBe('none') - release() - expect(attached.webview.style.pointerEvents).toBe('') - } finally { - release() - attached.detach() - container.remove() - append.mockRestore() - } - expect(webviewRegistry.has('preview-drag')).toBe(false) -}) diff --git a/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts b/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts deleted file mode 100644 index 1d68afea4c9..00000000000 --- a/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getContextualTour } from '../../../../shared/contextual-tours' -import { getContextualTourDisplayProgress } from './contextual-tour-overlay-measurement' - -const tour = getContextualTour('workspace-agent-sessions') - -function progress(visibleStepIndexes: number[], stepIndex: number) { - return getContextualTourDisplayProgress({ - tour, - visibleStepIndexes, - stepIndex, - activeStep: tour.steps[stepIndex] - }) -} - -describe('workspace agent sessions tour progress', () => { - it('keeps the split lesson counted after a chat split focuses its landing', () => { - expect(progress([0, 1, 3], 1)).toEqual({ current: 2, total: 3 }) - expect(progress([0, 3], 3)).toEqual({ current: 3, total: 3 }) - }) - - it('counts a still-visible split lesson once', () => { - expect(progress([0, 2, 3], 3)).toEqual({ current: 3, total: 3 }) - }) -}) diff --git a/src/renderer/src/components/dashboard/AgentDashboardExperimentalSetting.tsx b/src/renderer/src/components/dashboard/AgentDashboardExperimentalSetting.tsx index 727effa98b1..a2e48e51396 100644 --- a/src/renderer/src/components/dashboard/AgentDashboardExperimentalSetting.tsx +++ b/src/renderer/src/components/dashboard/AgentDashboardExperimentalSetting.tsx @@ -2,10 +2,8 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import { useTranslate } from '@/i18n/use-translate' import { Label } from '../ui/label' import { SearchableSetting } from '../settings/section-layout/SearchableSetting' -import { - SettingsSegmentedControl, - SettingsSwitch -} from '../settings/form-controls/SettingsFormControls' +import { SettingsSegmentedControl } from '../settings/form-controls/SettingsFormControls' +import { Switch } from '@/components/ui/switch' import { getExperimentalSearchEntry } from '../settings/advanced/experimental-search' import { canOpenAgentDashboardPopout } from './agent-dashboard-open-mode' @@ -45,13 +43,13 @@ export function AgentDashboardExperimentalSetting({ )}

- updateSettings({ experimentalAgentDashboardPopout: !enabled })} + onCheckedChange={() => updateSettings({ experimentalAgentDashboardPopout: !enabled })} /> {enabled && canOpenAgentDashboardPopout() ? ( diff --git a/src/renderer/src/components/dashboard/AgentDashboardSettingsMenu.tsx b/src/renderer/src/components/dashboard/AgentDashboardSettingsMenu.tsx index 0da15b80f6e..8057893c52d 100644 --- a/src/renderer/src/components/dashboard/AgentDashboardSettingsMenu.tsx +++ b/src/renderer/src/components/dashboard/AgentDashboardSettingsMenu.tsx @@ -8,10 +8,8 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { - SettingsSegmentedControl, - SettingsSwitch -} from '../settings/form-controls/SettingsFormControls' +import { SettingsSegmentedControl } from '../settings/form-controls/SettingsFormControls' +import { Switch } from '@/components/ui/switch' import type { AgentDashboardMode } from '../../../../shared/ui-chrome-types' import { useTranslate } from '@/i18n/use-translate' import { canOpenAgentDashboardPopout } from './agent-dashboard-open-mode' @@ -124,14 +122,14 @@ export function AgentDashboardSettingsMenu({ )} - { + onCheckedChange={() => { void updateSettings({ experimentalAgentDashboardShowIdle: !showIdle }) }} - ariaLabel={t('dashboardPopout.settings.showIdle', 'Show idle agents')} + aria-label={t('dashboardPopout.settings.showIdle', 'Show idle agents')} /> diff --git a/src/renderer/src/components/editor/PdfViewer.tsx b/src/renderer/src/components/editor/PdfViewer.tsx index d9c0118e538..36da94c441a 100644 --- a/src/renderer/src/components/editor/PdfViewer.tsx +++ b/src/renderer/src/components/editor/PdfViewer.tsx @@ -113,7 +113,7 @@ function PdfDocumentViewer({ viewerDiv, doc, scrollCacheKey, - scalePreference: scalePreferenceRef.current, + getScalePreference: () => scalePreferenceRef.current, scaleBounds: SCALE_BOUNDS, onScaleChanging: setScale, onWheelZoom: recordScalePreference diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.copy.test.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.copy.test.tsx deleted file mode 100644 index ca923ea65b8..00000000000 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.copy.test.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import type { PRCheckDetail, PRCheckRunDetails } from '../../../../../../shared/github/check-types' -import { CheckRunDetailsPanel } from './CheckRunDetailsPanel' - -import { useAppStore } from '@/store/index' -import { createEditorTabsStore } from '@/store/slices/editor/editor-slice-test-harness' -import { scrollTopCache } from '@/lib/scroll-cache' -import { readingCheck, readingDetails } from '../reading/check-details-reading-fixture' -import { StrictMode } from 'react' - -const writeClipboardText = vi.fn<(text: string) => Promise>() -const prCheckDetails = vi.fn() -const runtimeCall = vi.fn() - -vi.mock('@/i18n/i18n', () => ({ - getIntlLocale: () => 'en', - i18n: { language: 'en' }, - translate: (_key: string, fallback: string, values?: Record) => - fallback.replace(/{{(\w+)}}/g, (_match, key) => String(values?.[key] ?? '')) -})) - -vi.mock('@/components/sidebar/CommentMarkdown', () => ({ - default: ({ content }: { content: string }) => content -})) - -vi.mock('@/components/right-sidebar/source-control/panel/source-control-fix-split-button', () => ({ - SourceControlFixSplitButton: () => null -})) - -vi.mock('../actions/check-run-details-fix-with-ai', () => ({ - useCheckRunDetailsFixWithAI: () => ({ - canFixWithAI: false, - disabledReason: null, - isFixing: false, - fixPrompt: '', - repoId: null, - connectionId: null, - launchPlatform: null, - savedAgentId: null, - savedCommandInputTemplate: null, - savedAgentArgs: [], - saveLaunchActionDefault: vi.fn(), - openSourceControlAiSettings: vi.fn(), - fixWithAI: vi.fn() - }) -})) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) - -beforeEach(() => { - writeClipboardText.mockReset().mockResolvedValue(undefined) - prCheckDetails.mockReset() - runtimeCall.mockReset() - Object.assign(window, { - api: { - ui: { writeClipboardText }, - gh: { prCheckDetails }, - runtime: { call: runtimeCall }, - runtimeEnvironments: { call: runtimeCall, subscribe: runtimeCall } - } - }) -}) - -const check: PRCheckDetail = { - name: 'package', - status: 'completed', - conclusion: 'failure', - url: null, - checkRunId: 42 -} - -const details: PRCheckRunDetails = { - name: 'package', - status: 'completed', - conclusion: 'failure', - url: null, - detailsUrl: null, - startedAt: null, - completedAt: null, - title: 'Build failed', - summary: 'One test failed.', - text: 'Run the suite locally.', - annotations: [ - { - path: 'src/main.ts', - startLine: 10, - endLine: 10, - annotationLevel: 'failure', - title: 'Type error', - message: 'Expected string', - rawDetails: 'Actual: number' - } - ], - jobs: [ - { - id: 1, - name: 'unit', - status: 'completed', - conclusion: 'failure', - startedAt: null, - completedAt: null, - url: null, - logTail: 'AssertionError: expected true', - steps: [ - { - name: 'test', - status: 'completed', - conclusion: 'failure', - startedAt: null, - completedAt: null - } - ] - } - ] -} - -function panel(payload = details, loading = false, error: string | null = null) { - return ( - - {}} - /> - - ) -} - -describe('failure presentation and combined refresh', () => { - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('resets only the disclosure when a successful setup-only job becomes failed', () => { - const setup = { - name: 'setup only', - status: 'completed', - conclusion: 'success', - startedAt: null, - completedAt: null - } - const first = { - ...details, - conclusion: 'success', - jobs: [{ ...details.jobs[0], conclusion: 'success', steps: [setup] }] - } - const { rerender, container } = render(panel(first)) - const pre = container.querySelector('pre.max-h-72') - expect(screen.getByRole('button', { name: '1 succeeded' }).getAttribute('aria-expanded')).toBe( - 'true' - ) - rerender( - panel({ - ...first, - conclusion: 'failure', - jobs: [{ ...first.jobs[0], conclusion: 'startup_failure' }] - }) - ) - expect(screen.getByRole('button', { name: '1 succeeded' }).getAttribute('aria-expanded')).toBe( - 'false' - ) - expect(container.querySelector('pre.min-h-48')).toBe(pre) - expect(screen.queryByText('setup only')).toBeNull() - }) - - it('keeps stable job viewers when equal-named jobs reorder under new payload objects', () => { - const one = details.jobs[0] - const two = { ...one, id: 2, logTail: 'Error: second synthetic failure' } - const { container, rerender } = render(panel({ ...details, jobs: [one, two] })) - const first = container.querySelector('pre') - if (!first) { - throw new Error('Missing job viewer') - } - first.scrollTop = 180 - rerender(panel({ ...details, jobs: [{ ...two }, { ...one }] })) - const viewers = [...container.querySelectorAll('pre')] - expect(viewers[1]).toBe(first) - expect(first.scrollTop).toBe(180) - }) -}) - -function StoredDetailsPanel({ scope = 'real-pane' }: { scope?: string }) { - const file = useAppStore((state) => state.openFiles[0]) - const snapshot = file?.checkRunDetails - if (!snapshot) { - return null - } - return ( - - { - void useAppStore.getState().reloadOpenCheckRunDetailsTab(file.id) - }} - /> - - ) -} - -describe('mounted store-driven details refresh', () => { - const original = useAppStore.getState() - afterEach(() => { - cleanup() - useAppStore.setState(original, true) - scrollTopCache.clear() - vi.restoreAllMocks() - }) - it.each(['equal', 'null', 'throw'])( - 'preserves the actual viewer and both offsets through deferred %s requests and Strict Mode', - async (result) => { - const fixture = createEditorTabsStore().getState() - const payload = readingDetails(undefined, 'available') - let resolve: (details: PRCheckRunDetails | null) => void = () => {} - let reject: (reason: Error) => void = () => {} - const fetch = vi.fn( - () => - new Promise((done, fail) => { - resolve = done - reject = fail - }) - ) - useAppStore.setState({ - openFiles: [], - repos: fixture.repos, - worktreesByRepo: fixture.worktreesByRepo, - fetchPRCheckDetails: fetch - }) - useAppStore.getState().openCheckRunDetails('wt-1', 'context', readingCheck, { - details: payload, - loading: false, - error: null - }) - vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(400) - vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(200) - vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(2000) - vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue( - new DOMRect(0, 0, 400, 200) - ) - const { container, unmount } = render( - - - - ) - const pre = container.querySelector('pre') - const outer = container.querySelector('[aria-busy].overflow-y-auto') - if (!(pre instanceof HTMLPreElement) || !(outer instanceof HTMLDivElement)) { - throw new Error('Missing reading nodes') - } - fireEvent.wheel(pre) - pre.scrollTop = 180 - fireEvent.scroll(pre) - outer.scrollTop = 320 - fireEvent.scroll(outer) - fireEvent.click(screen.getByRole('button', { name: 'Refresh' })) - expect(fetch).toHaveBeenCalledTimes(1) - expect(container.querySelector('pre')).toBe(pre) - expect(pre.scrollTop).toBe(180) - expect(outer.scrollTop).toBe(320) - await act(async () => { - if (result === 'throw') { - reject(new Error('SECRET')) - } else { - resolve( - result === 'null' ? null : { ...payload, jobs: payload.jobs.map((job) => ({ ...job })) } - ) - } - }) - expect(container.querySelector('pre')).toBe(pre) - expect(pre.scrollTop).toBe(180) - expect(outer.scrollTop).toBe(320) - if (result !== 'equal') { - expect(screen.getByRole('alert').textContent).not.toContain('SECRET') - } - unmount() - const remount = render( - - - - ) - expect(remount.container.querySelector('pre')?.scrollTop).toBe(180) - const remountedOuter = remount.container.querySelector('[aria-busy].overflow-y-auto') - expect(remountedOuter?.scrollTop).toBe(320) - expect(fetch).toHaveBeenCalledTimes(1) - } - ) -}) diff --git a/src/renderer/src/components/editor/pdf-scale-preference.test.ts b/src/renderer/src/components/editor/pdf-scale-preference.test.ts new file mode 100644 index 00000000000..75ff14ba4c1 --- /dev/null +++ b/src/renderer/src/components/editor/pdf-scale-preference.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { zoomPdfViewerWithWheel } from './pdf-scale-preference' + +function fakeViewer(currentScale: number) { + return { + currentScale, + currentScaleValue: '', + container: { scrollLeft: 0, scrollTop: 0, getBoundingClientRect: () => ({ left: 0, top: 0 }) }, + update: () => {} + } +} + +const zoomInEvent = { + ctrlKey: true, + deltaY: -100, + deltaMode: 0, + clientX: 0, + clientY: 0, + preventDefault: () => {} +} +const bounds = { min: 0.25, max: 5 } + +describe('zoomPdfViewerWithWheel', () => { + it('stops on the fit-width scale when a step would pass it, then leaves it', () => { + const below = fakeViewer(1) + expect(zoomPdfViewerWithWheel(below, zoomInEvent, bounds, () => 1.5)).toBe('page-width') + expect(below.currentScaleValue).toBe('page-width') + + const atFit = fakeViewer(1.5) + expect(zoomPdfViewerWithWheel(atFit, zoomInEvent, bounds, () => 1.5)).toBeGreaterThan(1.5) + }) +}) diff --git a/src/renderer/src/components/editor/pdf-scale-preference.ts b/src/renderer/src/components/editor/pdf-scale-preference.ts index 3eabad2dfac..546b55b6e2f 100644 --- a/src/renderer/src/components/editor/pdf-scale-preference.ts +++ b/src/renderer/src/components/editor/pdf-scale-preference.ts @@ -30,6 +30,22 @@ export function stepPdfScalePreference( return { scale: next, preference: next } } +// Half a percent; a scale this close to fit-width already is fit-width. +const FIT_STOP_MARGIN = 0.005 + +/** A zoom that would pass over fit-width stops on it; the next one leaves it. */ +function stopAtPdfFitScale(previous: number, next: number, fitScale: number | null): number { + if (fitScale === null) { + return next + } + const before = previous / fitScale - 1 + const after = next / fitScale - 1 + const crosses = + (before < -FIT_STOP_MARGIN && after > -FIT_STOP_MARGIN) || + (before > FIT_STOP_MARGIN && after < FIT_STOP_MARGIN) + return crosses ? fitScale : next +} + type PdfWheelZoomEvent = Pick< WheelEvent, 'ctrlKey' | 'deltaY' | 'deltaMode' | 'clientX' | 'clientY' | 'preventDefault' @@ -39,6 +55,7 @@ type PdfWheelZoomEvent = Pick< export function zoomPdfViewerWithWheel( viewer: { currentScale: number + currentScaleValue: string container: { scrollLeft: number scrollTop: number @@ -47,30 +64,42 @@ export function zoomPdfViewerWithWheel( update: () => void }, event: PdfWheelZoomEvent, - bounds: { min: number; max: number } -): number | null { + bounds: { min: number; max: number }, + getFitScale: () => number | null +): PdfScalePreference | null { if (!shouldHandleImageZoomWheel(event)) { return null } event.preventDefault() const previous = viewer.currentScale - const next = clampPdfScale( - previous * getPinchZoomFactor(event.deltaY, event.deltaMode), - bounds.min, - bounds.max + const fitScale = getFitScale() + const next = stopAtPdfFitScale( + previous, + clampPdfScale( + previous * getPinchZoomFactor(event.deltaY, event.deltaMode), + bounds.min, + bounds.max + ), + fitScale ) if (next === previous) { return null } const { container } = viewer const rect = container.getBoundingClientRect() - // Why: an absolute scale avoids updateScale's 0.01 rounding, which swallows slow pinches. - viewer.currentScale = next + const fitted = next === fitScale + if (fitted) { + // Why: the preset is what resizes refit to; a numeric set first could move pdf.js to a page of another width. + viewer.currentScaleValue = 'page-width' + } else { + // Why: an absolute scale avoids updateScale's 0.01 rounding, which swallows slow pinches. + viewer.currentScale = next + } // Why: pdf.js keeps the viewport's top-left fixed, so shift by the pointer's grown offset. const growth = next / previous - 1 container.scrollLeft += (event.clientX - rect.left) * growth container.scrollTop += (event.clientY - rect.top) * growth // Why: pdf.js re-reads its location on the next frame; a faster pinch event would anchor to the old one. viewer.update() - return next + return fitted ? 'page-width' : next } diff --git a/src/renderer/src/components/editor/pdf-viewer-session.ts b/src/renderer/src/components/editor/pdf-viewer-session.ts index 52b14b3eefe..ce439e92ac3 100644 --- a/src/renderer/src/components/editor/pdf-viewer-session.ts +++ b/src/renderer/src/components/editor/pdf-viewer-session.ts @@ -17,6 +17,8 @@ import { createPdfViewPositionRecorder } from './pdf-view-position' +const PAGE_WIDTH_REFIT_SETTLE_MS = 150 + const USER_SCROLL_INPUT_EVENTS = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const function watchUserScrollInput(container: HTMLElement, onInput: () => void): () => void { @@ -35,7 +37,7 @@ export function createPdfViewerSession({ viewerDiv, doc, scrollCacheKey, - scalePreference, + getScalePreference, scaleBounds, onScaleChanging, onWheelZoom @@ -44,10 +46,10 @@ export function createPdfViewerSession({ viewerDiv: HTMLDivElement doc: pdfjsLib.PDFDocumentProxy scrollCacheKey: string | null - scalePreference: PdfScalePreference + getScalePreference: () => PdfScalePreference scaleBounds: { min: number; max: number } onScaleChanging: (scale: number) => void - onWheelZoom: (scale: number) => void + onWheelZoom: (scale: PdfScalePreference) => void }): { viewer: InstanceType eventBus: InstanceType @@ -87,9 +89,13 @@ export function createPdfViewerSession({ container.addEventListener( 'wheel', (event) => { - const scale = zoomPdfViewerWithWheel(viewer, event, scaleBounds) - if (scale !== null) { - onWheelZoom(scale) + const preference = zoomPdfViewerWithWheel(viewer, event, scaleBounds, () => { + const page = viewer.getPageView(viewer.currentPageNumber - 1) + // Why: pdf.js's 'page-width' scale, given removePageBorders (no padding) and no spreads. + return page ? (container.clientWidth / page.width) * page.scale : null + }) + if (preference !== null) { + onWheelZoom(preference) } }, { passive: false, signal: abortController.signal } @@ -117,6 +123,8 @@ export function createPdfViewerSession({ } const handlePagesInit = (): void => { + // Why: pdf.js drops a preset scale set before its page views exist, leaving the PDF at 100%. + applyPdfScalePreference(viewer, getScalePreference(), scaleBounds) const cached = scrollCacheKey ? pdfViewPositionCache.get(scrollCacheKey) : undefined const clamped = cached ? clampPdfViewPosition(cached, viewer.pagesCount) : null if (!clamped) { @@ -173,6 +181,29 @@ export function createPdfViewerSession({ recorder?.arm() } + // Why: pdf.js computes 'page-width' once; split resizes and maximize must refit it. + let refitTimer: ReturnType | null = null + const refitPageWidth = (): void => { + refitTimer = null + // Why: a hidden pane measures zero wide and would fit the pages to nothing. + if ( + container.clientWidth > 0 && + viewer.pagesCount > 0 && + viewer.currentScaleValue === 'page-width' + ) { + viewer.currentScaleValue = 'page-width' + } + } + const fitWidthObserver = new ResizeObserver(() => { + // Why: each refit re-renders the visible pages, so wait for a split drag to settle. + if (refitTimer !== null) { + clearTimeout(refitTimer) + } + refitTimer = setTimeout(refitPageWidth, PAGE_WIDTH_REFIT_SETTLE_MS) + }) + // Why: border-box ignores the scrollbar a refit can toggle, which would refit again in a loop. + fitWidthObserver.observe(container, { box: 'border-box' }) + eventBus.on('pagesinit', handlePagesInit) eventBus.on('pagesloaded', handlePagesLoaded) eventBus.on('updateviewarea', handleUpdateViewArea) @@ -187,6 +218,10 @@ export function createPdfViewerSession({ // Why: teardown events must not overwrite the reader's final position. detachInputWatcher?.() disconnectVisibilityObserver() + fitWidthObserver.disconnect() + if (refitTimer !== null) { + clearTimeout(refitTimer) + } recorder?.dispose() eventBus.off('pagesinit', handlePagesInit) eventBus.off('pagesloaded', handlePagesLoaded) @@ -208,7 +243,7 @@ export function createPdfViewerSession({ viewer.setDocument(doc) linkService.setDocument(doc) findController.setDocument(doc) - applyPdfScalePreference(viewer, scalePreference, scaleBounds) + applyPdfScalePreference(viewer, getScalePreference(), scaleBounds) } catch (error) { dispose() throw error diff --git a/src/renderer/src/components/feature-tips/SessionSearchTipDialog.tsx b/src/renderer/src/components/feature-tips/SessionSearchTipDialog.tsx index fac94e4fb0e..21de52052fb 100644 --- a/src/renderer/src/components/feature-tips/SessionSearchTipDialog.tsx +++ b/src/renderer/src/components/feature-tips/SessionSearchTipDialog.tsx @@ -4,7 +4,7 @@ import type { FeatureTip } from '../../../../shared/feature-tips' import { sessionSearchStatusDetails, sessionSearchStatusMessage -} from '@/components/settings/session-history/session-history-status-copy' +} from '@/components/session-search/session-search-status' import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/feature-tips/use-session-search-tip-setup.ts b/src/renderer/src/components/feature-tips/use-session-search-tip-setup.ts index e23a6e608cb..b489a3157a4 100644 --- a/src/renderer/src/components/feature-tips/use-session-search-tip-setup.ts +++ b/src/renderer/src/components/feature-tips/use-session-search-tip-setup.ts @@ -6,8 +6,8 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { isSessionSearchIndexReady, sessionSearchStatusMessage -} from '@/components/settings/session-history/session-history-status-copy' -import { useSessionSearchStatus } from '@/components/settings/session-history/use-session-search-status' +} from '@/components/session-search/session-search-status' +import { useSessionSearchStatus } from '@/components/session-search/use-session-search-status' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx index 191567772f8..79117be2416 100644 --- a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx +++ b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx @@ -1,6 +1,6 @@ import type { JSX } from 'react' import { ORCA_CLI_SKILL_NAME } from '@/lib/agent-feature-skill-names' -import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/components/settings/browser/use/browser-use-setup-state' +import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/lib/browser/browser-use-setup-state' import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { AgentSkillSetupPanel } from '@/components/skills/setup/AgentSkillSetupPanel' diff --git a/src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx b/src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx index 29bb2d5c169..4060685d41a 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx @@ -32,7 +32,7 @@ import { applyAllAgentsPermission } from '../../../../shared/agent-launch/permis import { NotificationStep } from '../onboarding/NotificationStep' import { useAppStore } from '@/store' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { useTranslate } from '@/i18n/use-translate' import { getLocalizedFeatureWallSetupChecklistCopy } from './feature-wall-setup-checklist-localized-copy' diff --git a/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts b/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts index 7ce9eb500e8..b927c969e98 100644 --- a/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts +++ b/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts @@ -2,7 +2,7 @@ import { useEffect } from 'react' import type { FeatureWallWorkflow } from '../../../../shared/feature-wall-workflows' import { useAppStore } from '@/store' import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { deriveIntegrationConnectionStatus } from './use-integration-connection-status' export type FeatureWallTaskSourcePresentation = { diff --git a/src/renderer/src/components/feature-wall/use-integration-connection-status.ts b/src/renderer/src/components/feature-wall/use-integration-connection-status.ts index e5eb9ece6bb..39b9eee1736 100644 --- a/src/renderer/src/components/feature-wall/use-integration-connection-status.ts +++ b/src/renderer/src/components/feature-wall/use-integration-connection-status.ts @@ -1,6 +1,6 @@ import { useAppStore } from '@/store' import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' export type IntegrationStepState = 'active' | 'done' | 'upcoming' diff --git a/src/renderer/src/components/host-picker/bounded-host-list.test.tsx b/src/renderer/src/components/host-picker/HostListSearchField.test.tsx similarity index 100% rename from src/renderer/src/components/host-picker/bounded-host-list.test.tsx rename to src/renderer/src/components/host-picker/HostListSearchField.test.tsx diff --git a/src/renderer/src/components/host-picker/SshTargetSelect.tsx b/src/renderer/src/components/host-picker/SshTargetSelect.tsx deleted file mode 100644 index 409d1ce7a44..00000000000 --- a/src/renderer/src/components/host-picker/SshTargetSelect.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import type { SshTarget } from '../../../../shared/ssh-types' -import { HostCombobox } from './HostCombobox' - -type SshTargetSelectProps = { - id?: string - targets: SshTarget[] - value: string - onChange: (targetId: string) => void - placeholder: string -} - -export function SshTargetSelect({ - id, - targets, - value, - onChange, - placeholder -}: SshTargetSelectProps): React.JSX.Element { - return ( - - ) -} diff --git a/src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx b/src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx index 7b460a00207..83b5cee741f 100644 --- a/src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx +++ b/src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx @@ -16,7 +16,7 @@ import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { cn } from '@/lib/utils' -import { hasRemoteProviderRuntime } from '@/lib/provider-runtime-context' +import { hasRemoteProviderRuntime } from '@/runtime/hosts/observations/provider-runtime-context' import { preventOutsideDismissWhenDirty } from '@/lib/outside-dismiss-guard' import { bitbucketConnectErrorText } from '@/lib/bitbucket-connect-error-copy' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx b/src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx index b428cdf1e8e..30658c5c339 100644 --- a/src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx +++ b/src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx @@ -9,7 +9,7 @@ import { useMountedRef } from '@/hooks/useMountedRef' import { getProviderRuntimeContextKey, hasRemoteProviderRuntime -} from '@/lib/provider-runtime-context' +} from '@/runtime/hosts/observations/provider-runtime-context' import { useAppStore } from '@/store/index' import { IntegrationCardDetails, diff --git a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx b/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx index 204abd49804..586b448eeea 100644 --- a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx +++ b/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx @@ -5,7 +5,7 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { i18n, loadRendererUiLanguage } from '@/i18n/i18n' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { TooltipProvider } from '../../ui/tooltip' import { LinearIntegrationCard } from './linear-integration-card' diff --git a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx b/src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx index 1c2f664920c..41c301b5f4f 100644 --- a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx +++ b/src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx @@ -6,7 +6,7 @@ import { LinearIcon } from '@/components/icons/LinearIcon' import { LinearApiKeyDialog } from '@/components/linear-api-key-dialog' import { Button } from '@/components/ui/button' import { useMountedRef } from '@/hooks/useMountedRef' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { useAppStore } from '@/store/index' import { IntegrationCardDetails, diff --git a/src/renderer/src/components/jira-connect-dialog.tsx b/src/renderer/src/components/jira-connect-dialog.tsx index 0b7673ba927..808fd39c519 100644 --- a/src/renderer/src/components/jira-connect-dialog.tsx +++ b/src/renderer/src/components/jira-connect-dialog.tsx @@ -20,7 +20,7 @@ import { cn } from '@/lib/utils' import { getProviderRuntimeContextKey, isEnvironmentRuntimeContextKey -} from '@/lib/provider-runtime-context' +} from '@/runtime/hosts/observations/provider-runtime-context' import { preventOutsideDismissWhenDirty } from '@/lib/outside-dismiss-guard' import { useTranslate } from '@/i18n/use-translate' import { JiraConnectCredentialGuide } from './jira-connect-credential-guide' diff --git a/src/renderer/src/components/jira-connect-scoped-token.test.tsx b/src/renderer/src/components/jira-connect-scoped-token.test.tsx index 8490add9762..682297bb4da 100644 --- a/src/renderer/src/components/jira-connect-scoped-token.test.tsx +++ b/src/renderer/src/components/jira-connect-scoped-token.test.tsx @@ -3,7 +3,7 @@ import { fireEvent, render, screen, cleanup } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { JiraConnectionStatus } from '../../../shared/jira/jira-types' import { JiraConnectDialog } from './jira-connect-dialog' -import { getEnvironmentRuntimeContextKey } from '@/lib/provider-runtime-context' +import { getEnvironmentRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' type FixtureState = { settings: { activeRuntimeEnvironmentId: string | null } diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 77fb10fbf0c..3a2b4dc1196 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -273,8 +273,13 @@ export function NativeChatStructuredSession(props: Omit} > - - {find.isOpen ? : null} + : null + } + > {viewState.kind === 'loading' || (viewState.kind === 'error' && !readFailure) ? ( historyPhase !== 'unread' && ) : viewState.kind === 'error' ? ( diff --git a/src/renderer/src/components/native-chat/composer/pickers/NativeChatAutocompleteMenus.tsx b/src/renderer/src/components/native-chat/composer/pickers/NativeChatAutocompleteMenus.tsx index b91dbb9cd5d..ab15d6451f0 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/NativeChatAutocompleteMenus.tsx +++ b/src/renderer/src/components/native-chat/composer/pickers/NativeChatAutocompleteMenus.tsx @@ -14,6 +14,7 @@ import type { NativeChatPickerItem } from '../../../../../../shared/native-chat/ import type { NativeChatMentionFiles } from './use-native-chat-mention-files' import { LoadingSpinner } from '@/components/LoadingSpinner' import { localizeSlashCommandDescription } from './native-chat-slash-command-descriptions' +import { nativeChatPickerEmptyText } from './native-chat-picker-empty-text' export const NativeChatPickerMenu = memo(function NativeChatPickerMenu({ autocomplete, @@ -48,7 +49,8 @@ export const NativeChatPickerMenu = memo(function NativeChatPickerMenu({ const showSkillsHeading = autocomplete.grouped && (skills.length > 0 || hasSkillStatus) const noMatches = autocomplete.skillStatus === 'ready' && commands.length === 0 && skills.length === 0 - const emptyText = noMatches ? getPickerEmptyText(autocomplete, t) : null + const checkingSkills = noMatches && autocomplete.skillsChecking && autocomplete.skillsEnabled + const emptyText = noMatches ? nativeChatPickerEmptyText(autocomplete, t, checkingSkills) : null const collision = commands.find((item) => item.skillCollision) const duplicate = skills.find((item) => item.sources.length > 1) // One sentence for the line and the screen reader, so the two never disagree. @@ -80,8 +82,7 @@ export const NativeChatPickerMenu = memo(function NativeChatPickerMenu({ })} {showSkillsHeading ? : null} {autocomplete.skillStatus === 'loading' ? ( - - + {t('components.native-chat.composer.loadingSkills', 'Loading skills...')} ) : null} @@ -115,7 +116,7 @@ export const NativeChatPickerMenu = memo(function NativeChatPickerMenu({ /> ) })} - {noMatches ? {emptyText} : null} + {noMatches ? {emptyText} : null}
{autocomplete.skillStatus === 'loading' ? t('components.native-chat.composer.loadingSkills', 'Loading skills...') @@ -140,19 +141,6 @@ export const NativeChatPickerMenu = memo(function NativeChatPickerMenu({ ) }) -function getPickerEmptyText( - autocomplete: Extract, - t: Translate = translate -): string { - if (!autocomplete.commandsEnabled) { - return t('components.native-chat.composer.noSkills', 'No matching skills') - } - if (autocomplete.skillsEnabled) { - return t('components.native-chat.composer.noCommandsOrSkills', 'No matching commands or skills') - } - return t('components.native-chat.composer.noCommands', 'No matching commands') -} - function PickerGroupHeading({ kind }: { kind: 'commands' | 'skills' }): React.JSX.Element { const t = useTranslate() return ( @@ -164,9 +152,16 @@ function PickerGroupHeading({ kind }: { kind: 'commands' | 'skills' }): React.JS ) } -function PickerStatus({ children }: { children: React.ReactNode }): React.JSX.Element { +function PickerStatus({ + busy = false, + children +}: { + busy?: boolean + children: React.ReactNode +}): React.JSX.Element { return (
+ {busy ? : null} {children}
) diff --git a/src/renderer/src/components/native-chat/composer/pickers/agent-session-command-menu.test-fixture.tsx b/src/renderer/src/components/native-chat/composer/pickers/agent-session-command-menu.test-fixture.tsx index ce2ca9fafbb..3ea31f03a3f 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/agent-session-command-menu.test-fixture.tsx +++ b/src/renderer/src/components/native-chat/composer/pickers/agent-session-command-menu.test-fixture.tsx @@ -13,7 +13,7 @@ export const renderCommandMenu: CommandMenuRendererFixtureModule['renderCommandM })) return { commands: () => hook.result.current.read.state.commands, - setOpen: (open) => hook.result.current.menu.setOpen(open), + setOpen: (open) => hook.result.current.menu.setCommandsMenuOpen(open), unmount: hook.unmount } } diff --git a/src/renderer/src/components/native-chat/composer/pickers/native-chat-picker-empty-text.ts b/src/renderer/src/components/native-chat/composer/pickers/native-chat-picker-empty-text.ts new file mode 100644 index 00000000000..3f457c98a0e --- /dev/null +++ b/src/renderer/src/components/native-chat/composer/pickers/native-chat-picker-empty-text.ts @@ -0,0 +1,21 @@ +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import type { ComposerAutocomplete } from '../../../../../../shared/native-chat/input/native-chat-composer-autocomplete' + +/** While the host checks for new skills, an empty filter says so instead of reporting no match. */ +export function nativeChatPickerEmptyText( + autocomplete: Extract, + t: Translate = translate, + checking = false +): string { + if (checking) { + return t('components.native-chat.composer.checkingSkills', 'Checking for new skills...') + } + if (!autocomplete.commandsEnabled) { + return t('components.native-chat.composer.noSkills', 'No matching skills') + } + if (autocomplete.skillsEnabled) { + return t('components.native-chat.composer.noCommandsOrSkills', 'No matching commands or skills') + } + return t('components.native-chat.composer.noCommands', 'No matching commands') +} diff --git a/src/renderer/src/components/native-chat/composer/pickers/structured-agent-session-command-refresh.ts b/src/renderer/src/components/native-chat/composer/pickers/structured-agent-session-command-refresh.ts index 6f56509f275..eb1402f737c 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/structured-agent-session-command-refresh.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/structured-agent-session-command-refresh.ts @@ -5,22 +5,67 @@ import type { AgentSessionCommandsResult } from '../../../../../../shared/agent- import { startAgentSessionCommandMenuQuery } from '../../../../../../shared/agent-session/agent-session-command-menu-query' import { getStructuredAgentSessionReadOwner } from '../../session/structured/read/structured-agent-session-read-owner' +const CHECKING_SHOWN_AFTER_MS = 150 +const CHECKING_HELD_AFTER_MS = 250 + +async function readMenuCommands( + target: RuntimeClientTarget, + sessionId: string, + started: () => void, + finished: () => void +): Promise { + started() + try { + return await callStructuredAgentSession( + target, + 'agentSession.commands', + { sessionId } + ) + } finally { + finished() + } +} + export function useStructuredAgentSessionCommandMenu( target: RuntimeClientTarget, sessionId: string, enabled: boolean ) { const [open, setOpen] = useState(false) + // The host answers after any rescan it started, so a slow read means the list may still grow. + const [checking, setChecking] = useState(false) const query = useRef | null>(null) useEffect(() => { if (!enabled || !open) { return } + let shown: ReturnType | undefined + let hidden: ReturnType | undefined + let visible = false + const show = (next: boolean): void => { + visible = next + setChecking(next) + } const owned = startAgentSessionCommandMenuQuery( () => - callStructuredAgentSession(target, 'agentSession.commands', { - sessionId - }), + readMenuCommands( + target, + sessionId, + () => { + clearTimeout(hidden) + if (!visible) { + // Unchanged skills answer well inside this, so the common open re-renders nothing. + shown = setTimeout(() => show(true), CHECKING_SHOWN_AFTER_MS) + } + }, + () => { + clearTimeout(shown) + // The new list is pushed separately and lands just after this answer. + if (visible) { + hidden = setTimeout(() => show(false), CHECKING_HELD_AFTER_MS) + } + } + ), () => {} ) query.current = owned @@ -31,8 +76,16 @@ export function useStructuredAgentSessionCommandMenu( stop() query.current = null owned.dispose() + clearTimeout(shown) + clearTimeout(hidden) + show(false) } }, [enabled, open, sessionId, target]) const refresh = useCallback(() => query.current?.invalidate(), []) - return { setOpen, refresh } + // Named as the session controller exposes them. + return { + setCommandsMenuOpen: setOpen, + refreshCommands: refresh, + commandsChecking: enabled && open && checking + } } diff --git a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-composer-command-picker.ts b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-composer-command-picker.ts index bb66481bde6..66606d8c160 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-composer-command-picker.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-composer-command-picker.ts @@ -22,6 +22,7 @@ export function useNativeChatComposerCommandPicker( | 'sessionSkills' | 'onPickerOpened' | 'onPickerDemand' + | 'skillsChecking' | 'launchWorktreeId' | keyof ResumeArgs['editor'] > & @@ -55,6 +56,7 @@ export function useNativeChatComposerCommandPicker( commandAvailable, sessionSkills, onPickerDemand: structuredTransport?.setCommandsMenuOpen, + skillsChecking: structuredTransport?.commandsChecking === true, ...(!structuredTransport?.setCommandsMenuOpen && structuredTransport?.refreshCommands ? { onPickerOpened: structuredTransport.refreshCommands } : {}) diff --git a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.ts b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.ts index c56cd09bac7..b5c57300341 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.ts @@ -73,6 +73,7 @@ export function useNativeChatPickerState(args: { /** Refresh host catalogs on every / or $ menu opening, even in resting chats. */ onPickerOpened?: () => void onPickerDemand?: (open: boolean) => void + skillsChecking?: boolean textareaRef: RefObject setDraft: (value: string) => void setCaret: Dispatch> @@ -93,6 +94,7 @@ export function useNativeChatPickerState(args: { commandAvailable, onPickerOpened, onPickerDemand, + skillsChecking = false, textareaRef, setDraft, setCaret, @@ -119,7 +121,7 @@ export function useNativeChatPickerState(args: { const [dismissed, setDismissed] = useState<{ context: string; triggerKey: string } | null>(null) const skillOriginRef = useRef(null) const lastOpenKeyRef = useRef(null) - const autocomplete = useMemo( + const derivedAutocomplete = useMemo( () => recalledFromHistory || disabled ? { mode: 'none' } @@ -148,6 +150,13 @@ export function useNativeChatPickerState(args: { commandAvailable ] ) + const autocomplete = useMemo( + () => + skillsChecking && derivedAutocomplete.mode === 'slash' + ? { ...derivedAutocomplete, skillsChecking } + : derivedAutocomplete, + [derivedAutocomplete, skillsChecking] + ) useEffect(() => { // Reset dismissal/origin on context changes so a reused composer cannot retain a prior pane’s suppression. diff --git a/src/renderer/src/components/native-chat/composer/submit/native-chat-structured-composer-transport.ts b/src/renderer/src/components/native-chat/composer/submit/native-chat-structured-composer-transport.ts index ee48bfc01d9..f55055ad62d 100644 --- a/src/renderer/src/components/native-chat/composer/submit/native-chat-structured-composer-transport.ts +++ b/src/renderer/src/components/native-chat/composer/submit/native-chat-structured-composer-transport.ts @@ -38,6 +38,8 @@ export type NativeChatStructuredComposerTransport = { /** Request command refresh; updated choices arrive through sessionCommands. */ refreshCommands?: () => void setCommandsMenuOpen?: (open: boolean) => void + /** The open menu's host read is in flight; an empty filter may still fill in. */ + commandsChecking?: boolean /** False when the agent takes no image input, as its host registered it. */ acceptsImages?: boolean /** The session's context usage; null until the journal can state it. */ diff --git a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-transport.ts b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-transport.ts index 1ed8e1b5d77..ed1c441b3fc 100644 --- a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-transport.ts +++ b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-transport.ts @@ -174,6 +174,7 @@ export function useNativeChatStructuredComposerTransport(args: { sessionCommands: controller.sessionCommands, refreshCommands: controller.refreshCommands, setCommandsMenuOpen: controller.setCommandsMenuOpen, + commandsChecking: controller.commandsChecking, acceptsImages, contextUsage: controller.contextUsage, worktreeId, diff --git a/src/renderer/src/components/native-chat/conversation/projection/NativeChatContextClearFade.tsx b/src/renderer/src/components/native-chat/conversation/projection/NativeChatContextClearFade.tsx index 57cf67d3775..a23d8c23a23 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/NativeChatContextClearFade.tsx +++ b/src/renderer/src/components/native-chat/conversation/projection/NativeChatContextClearFade.tsx @@ -3,17 +3,25 @@ import type { ReactNode } from 'react' /** Swap the transcript while hidden during the live /clear fade, then reveal it again. */ export function NativeChatContextClearFade({ clearing, + overlay, children }: { clearing: boolean + /** Stays visible and usable over the hidden transcript, e.g. the find bar. */ + overlay?: ReactNode children: ReactNode }): React.JSX.Element { return ( -
- {children} +
+ {overlay} +
) } diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx index f9c1a56020a..ac46e8db302 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx @@ -26,13 +26,22 @@ const clear = (sequence: number): AgentJournalRenderItem => ({ }) function render(epoch: string | null, items: AgentJournalRenderItem[]) { - return renderHook( + let restore = (): void => {} + const hook = renderHook( ({ epoch, items }) => { - const { rows, clearing, clears } = useNativeChatContextClearFloor(epoch, items) - return { shown: rows.map((row) => row.sequence), clearing, clears } + const { rows, clearing, clears, onClearSent } = useNativeChatContextClearFloor(epoch, items) + return { view: { shown: rows.map((row) => row.sequence), clearing, clears }, onClearSent } }, { initialProps: { epoch, items } } ) + return { + rerender: hook.rerender, + get view() { + return hook.result.current.view + }, + sendClear: () => act(() => void (restore = hook.result.current.onClearSent())), + refuseClear: () => act(() => restore()) + } } describe('useNativeChatContextClearFloor', () => { @@ -41,24 +50,55 @@ describe('useNativeChatContextClearFloor', () => { it('fades a live /clear out before the transcript moves to its divider', () => { const hook = render('epoch-a', [message(1), message(2)]) - expect(hook.result.current).toEqual({ shown: [1, 2], clearing: false, clears: 0 }) + expect(hook.view).toEqual({ shown: [1, 2], clearing: false, clears: 0 }) hook.rerender({ epoch: 'epoch-a', items: [message(1), message(2), clear(3)] }) - expect(hook.result.current).toEqual({ shown: [1, 2, 3], clearing: true, clears: 0 }) + expect(hook.view).toEqual({ shown: [1, 2, 3], clearing: true, clears: 0 }) act(() => vi.advanceTimersByTime(NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS)) - expect(hook.result.current).toEqual({ shown: [3], clearing: false, clears: 1 }) + expect(hook.view).toEqual({ shown: [3], clearing: false, clears: 1 }) + }) + + it('hides the transcript from the moment a /clear is sent until its divider lands', () => { + const hook = render('epoch-a', [message(1), message(2)]) + hook.sendClear() + expect(hook.view).toEqual({ shown: [1, 2], clearing: true, clears: 0 }) + + // Already faded out by the time the divider lands, so it swaps without a second fade. + act(() => vi.advanceTimersByTime(NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS)) + hook.rerender({ epoch: 'epoch-a', items: [message(1), message(2), clear(3)] }) + act(() => vi.advanceTimersByTime(0)) + expect(hook.view).toEqual({ shown: [3], clearing: false, clears: 1 }) + + // The answered press hides nothing once later history trims its divider out. + hook.rerender({ epoch: 'epoch-a', items: [message(4), message(5)] }) + expect(hook.view.clearing).toBe(false) + }) + + it('shows the transcript again when a sent /clear is refused', () => { + const hook = render('epoch-a', [message(1), message(2)]) + hook.sendClear() + expect(hook.view.clearing).toBe(true) + hook.refuseClear() + expect(hook.view).toEqual({ shown: [1, 2], clearing: false, clears: 0 }) + }) + + it('stops hiding once a snapshot past the divider holds none of the rows the press hid', () => { + const hook = render('epoch-a', [message(1), message(2)]) + hook.sendClear() + hook.rerender({ epoch: 'epoch-a', items: [message(9), message(10)] }) + expect(hook.view).toEqual({ shown: [9, 10], clearing: false, clears: 0 }) }) it('moves to a divider paged in from history without fading or replacing the list', () => { const hook = render('epoch-a', [message(40), message(41)]) hook.rerender({ epoch: 'epoch-a', items: [message(10), clear(11), message(40), message(41)] }) - expect(hook.result.current).toEqual({ shown: [11, 40, 41], clearing: false, clears: 0 }) + expect(hook.view).toEqual({ shown: [11, 40, 41], clearing: false, clears: 0 }) }) it('takes the divider a first read or a rewind loads without fading', () => { const hook = render(null, []) hook.rerender({ epoch: 'epoch-a', items: [message(1), clear(2), message(3)] }) - expect(hook.result.current).toEqual({ shown: [2, 3], clearing: false, clears: 0 }) + expect(hook.view).toEqual({ shown: [2, 3], clearing: false, clears: 0 }) }) }) diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts index 6e883a84420..f4a0ee3e3e4 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts @@ -1,6 +1,7 @@ -import { useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import { + agentSessionContextClearOutstanding, agentSessionTranscriptRows, latestAgentSessionContextClearSequence } from '../../../../../../shared/agent-session/agent-session-context-clear' @@ -14,21 +15,34 @@ type ClearFloorState = { floor: number /** A clear that landed live, waiting for the old transcript to fade out. */ fading: number | null + /** When the fade that `fading` waits on began, if this view's press began it. */ + fadedSince: number | null /** Bumped per live clear; keys the list so nothing the cleared transcript held carries over. */ clears: number + /** This view's /clear awaiting its divider: its press time and the newest row drawn then. */ + sent: { at: number; tail: number } | null } -/** Show history after the latest clear; fade live clears before swapping, but preserve scroll for historical dividers. */ +/** Show history after the latest clear; fade live clears before swapping, but preserve scroll for historical dividers. + * A sent /clear fades the transcript at once: the host stops the old agent before its divider lands. */ export function useNativeChatContextClearFloor( epoch: string | null, items: readonly AgentJournalRenderItem[] -): { rows: readonly AgentJournalRenderItem[]; clearing: boolean; clears: number } { +): { + rows: readonly AgentJournalRenderItem[] + clearing: boolean + clears: number + /** Call as this view's /clear goes out; the returned restore shows the transcript again if refused. */ + onClearSent: () => () => void +} { const latest = useMemo(() => latestAgentSessionContextClearSequence(items), [items]) const [state, setState] = useState(() => ({ epoch, floor: latest, fading: null, - clears: 0 + fadedSince: null, + clears: 0, + sent: null })) // The newest row the last commit drew: a divider past it arrived live, not from an older page. const tail = items.at(-1)?.sequence ?? 0 @@ -36,36 +50,62 @@ export function useNativeChatContextClearFloor( useEffect(() => { drawnTail.current = tail }, [tail]) + const onClearSent = useCallback(() => { + const sent = { at: Date.now(), tail: drawnTail.current } + setState((prior) => ({ ...prior, sent })) + return () => setState((prior) => (prior.sent === sent ? { ...prior, sent: null } : prior)) + }, []) let current = state if (epoch !== state.epoch) { - // A new journal (first read or a rewind) remounts the list on its own; nothing to fade. - current = { ...state, epoch, floor: latest, fading: null } + // A new journal (first read or a rewind) remounts the list on its own; nothing to fade or wait on. + current = { ...state, epoch, floor: latest, fading: null, fadedSince: null, sent: null } setState(current) } else if (latest > (state.fading ?? state.floor)) { + // A divider past the press answers it, so the press stops hiding anything. + const { sent } = state + const answered = sent !== null && latest > sent.tail + const waiting = answered ? null : sent current = - latest > drawnTail.current ? { ...state, fading: latest } : { ...state, floor: latest } + latest > drawnTail.current + ? { ...state, fading: latest, fadedSince: answered ? sent.at : null, sent: waiting } + : { ...state, floor: latest, sent: waiting } + setState(current) + } else if ( + state.sent !== null && + !agentSessionContextClearOutstanding(items, latest, state.sent.tail) + ) { + // No row the press hid is loaded any more (a snapshot past its divider). + current = { ...state, sent: null } setState(current) } - const fading = current.fading + const { fading, fadedSince } = current + // Held hidden until a divider newer than the press lands; a refused clear fades back in. + const awaitingDivider = agentSessionContextClearOutstanding( + items, + latest, + current.sent?.tail ?? null + ) useEffect(() => { if (fading === null) { return } + // A press that already faded the transcript out swaps as soon as its divider lands. + const elapsed = fadedSince === null ? 0 : Date.now() - fadedSince const timer = setTimeout( () => setState((prior) => prior.fading === fading - ? { ...prior, floor: fading, fading: null, clears: prior.clears + 1 } + ? { ...prior, floor: fading, fading: null, fadedSince: null, clears: prior.clears + 1 } : prior ), - NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS + Math.max(0, NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS - elapsed) ) return () => clearTimeout(timer) - }, [fading]) + }, [fadedSince, fading]) const floor = current.floor const rows = useMemo(() => agentSessionTranscriptRows(items, floor), [floor, items]) - return { rows, clearing: fading !== null, clears: current.clears } + return { rows, clearing: fading !== null || awaitingDivider, clears: current.clears, onClearSent } } diff --git a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.test.tsx b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.test.tsx index db06a5633af..537fc11a707 100644 --- a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.test.tsx +++ b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.test.tsx @@ -33,7 +33,9 @@ vi.mock('@/runtime/hosted-terminals/creation/web-runtime-terminal-create-failure notifyWebRuntimeTerminalCreateFailure: notifyFailure })) vi.mock('@/lib/wsl-host-user-start', () => ({ startStoppedWslHostForUserAct: startHost })) -vi.mock('@/lib/claude-account-sign-in', () => ({ signInToClaudeAccount: vi.fn() })) +vi.mock('@/lib/provider-accounts/claude-account-sign-in', () => ({ + signInToClaudeAccount: vi.fn() +})) afterEach(() => { cleanup() diff --git a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts index e0b0ad19667..004cfff5501 100644 --- a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts +++ b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts @@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useMemo, useRef, useState } fro import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { useAppStore } from '@/store' -import { signInToClaudeAccount } from '@/lib/claude-account-sign-in' +import { signInToClaudeAccount } from '@/lib/provider-accounts/claude-account-sign-in' import { agentSessionRemoteSignInCommand } from '../../../../../shared/agent-session/lifecycle/agent-session-sign-in' import { persistAgentLaunchTabOrder } from '@/lib/agent-session/launch/pane/launch-agent-tab-order' import { createWebRuntimeSessionTerminalOnHost } from '@/runtime/hosted-terminals/creation/web-runtime-terminal-creation' diff --git a/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.test.ts b/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.test.ts deleted file mode 100644 index fb2ded7366f..00000000000 --- a/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import { agentSessionFailureSentence } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' -import { sayAgentSessionFailureTranslated } from './agent-session-failure-words-text' - -afterEach(async () => { - await i18n.changeLanguage('en') -}) - -it.each([ - [ - 'en', - 'OMP has no model selected. Check your model selection and OMP sign-in, then send again.', - "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." - ], - [ - 'zh', - 'OMP 没有选择模型。请检查模型选择和 OMP 登录状态,然后重新发送。', - expect.stringContaining('请将 OMP 更新到 18.1.9 或更高版本') - ] -] as const)( - 'words a missing OMP model and the update hint on desktop (%s)', - async (locale, none, update) => { - await i18n.changeLanguage(locale) - const say = (fact: Parameters[0]) => - agentSessionFailureSentence( - fact, - 'rejection', - { agentName: 'OMP' }, - sayAgentSessionFailureTranslated - ) - expect(say({ kind: 'modelNotSelected' })).toBe(none) - expect( - say({ - kind: 'modelUnavailable', - detail: { text: '@worker_be', audience: 'log' }, - agentUpdate: '18.1.9' - }) - ).toEqual(update) - } -) diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx index 67b99859a4b..7a78a28dc85 100644 --- a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx @@ -22,6 +22,7 @@ import { } from '../../../../../../../shared/native-chat/input/native-chat-session-option-labels' import { sayNativeChatSessionOptionTranslated as say } from './native-chat-session-option-labels-text' import { NativeChatSessionOptionWriteGroup } from './NativeChatSessionOptionWriteGroup' +import { NativeChatSessionSpeedButton, speedButtonTiers } from './NativeChatSessionSpeedButton' type NativeChatSessionOptionRowsProps = { /** The current model's options, in display order. */ @@ -138,6 +139,32 @@ function OptionRow(props: { ) } + const speed = speedButtonTiers(descriptor) + if (speed && descriptor.kind.type === 'select') { + const button = ( + + ) + return layout === 'inline' ? ( + button + ) : ( +
+ {label} + {button} +
+ ) + } if (descriptor.kind.type === 'boolean') { return (