diff --git a/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs deleted file mode 100644 index 20d9dc63f14..00000000000 --- a/config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs +++ /dev/null @@ -1,132 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import process from 'node:process' -import { - collectElectronImporters, - collectStructuredChatEntryPoints, - main -} from './check-runtime-electron-ratchet.mjs' - -describe('structured chat coverage', () => { - const roots = [] - afterEach(() => { - for (const root of roots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } - }) - - function fixture(files) { - const root = mkdtempSync(path.join(tmpdir(), 'orca-electron-ratchet-')) - roots.push(root) - for (const [file, source] of Object.entries(files)) { - const absolute = path.join(root, file) - mkdirSync(path.dirname(absolute), { recursive: true }) - writeFileSync(absolute, source) - } - return root - } - - const requiredLanes = { - 'src/main/native-chat/reader.ts': 'export {}', - 'src/main/claude/claude-session.ts': 'export {}', - 'src/main/codex/codex-session.ts': 'export {}', - 'src/main/runtime/structured-agent-session-host.ts': 'export {}', - 'src/main/provider-process/provider-process-teardown.ts': 'export {}', - 'src/main/acp/session/acp-structured-session-adapter.ts': 'export {}', - 'src/main/jsonl-rpc/peer.ts': 'export {}', - 'src/main/pi/rpc-launch.ts': 'export {}', - 'src/shared/agent-session-record.ts': 'export {}', - 'src/packages/process-host/src/run-process.ts': 'export {}' - } - - it.each([true, false])( - 'finds Electron through an unwired lane package (sideEffects=%s)', - async (sideEffects) => { - const root = fixture({ - ...requiredLanes, - 'src/main/acp/adapter.ts': "import 'acp-desktop-package'", - 'src/main/provider-process/worker.ts': "import 'provider-desktop-package'", - 'src/main/jsonl-rpc/peer.ts': "import 'rpc-desktop-package'", - 'src/main/pi/rpc-launch.ts': "import 'pi-desktop-package'", - 'node_modules/acp-desktop-package/package.json': JSON.stringify({ - main: 'index.js', - sideEffects - }), - 'node_modules/acp-desktop-package/index.js': "require('electron')", - 'node_modules/provider-desktop-package/package.json': JSON.stringify({ - main: 'index.js', - sideEffects - }), - 'node_modules/provider-desktop-package/index.js': "require('electron')", - 'node_modules/rpc-desktop-package/package.json': JSON.stringify({ - main: 'index.js', - sideEffects - }), - 'node_modules/rpc-desktop-package/index.js': "require('electron')", - 'node_modules/pi-desktop-package/package.json': JSON.stringify({ - main: 'index.js', - sideEffects - }), - 'node_modules/pi-desktop-package/index.js': "require('electron')" - }) - const current = await collectElectronImporters(collectStructuredChatEntryPoints(root)) - expect(current.map((file) => file.split('/node_modules/').pop())).toEqual([ - 'acp-desktop-package/index.js', - 'pi-desktop-package/index.js', - 'provider-desktop-package/index.js', - 'rpc-desktop-package/index.js' - ]) - } - ) - - it('checks public workspace imports against source without requiring a built package', async () => { - const root = fixture({ 'entry.ts': "import '@orca/process-host'" }) - const target = path.join(process.cwd(), 'src/packages/process-host/src/run-process.ts') - const current = await collectElectronImporters([path.join(root, 'entry.ts')], { - plugins: [ - { - name: 'inject-process-host-electron-import', - setup(pluginBuild) { - pluginBuild.onLoad({ filter: /run-process\.ts$/ }, (args) => - args.path === target ? { contents: "import 'electron'", loader: 'ts' } : undefined - ) - } - } - ] - }) - expect(current).toEqual(['src/packages/process-host/src/run-process.ts']) - }) -}) - -// Why `main`: it is what `pnpm lint` and CI run, so these fail if its entry list drops the lanes. -describe('the command-line check', () => { - afterEach(() => { - vi.restoreAllMocks() - }) - - // Why a file the runtime doesn't load: only the structured-chat lanes can catch it. - it('fails on Electron in structured-chat code the runtime graph does not reach', async () => { - const target = path.join( - process.cwd(), - 'src', - 'main', - 'native-chat', - 'transcript-read-cache.ts' - ) - const addElectron = { - name: 'add-electron-import', - setup(pluginBuild) { - pluginBuild.onLoad({ filter: /transcript-read-cache\.ts$/ }, (args) => - args.path === target - ? { contents: `import 'electron'\n${readFileSync(target, 'utf8')}`, loader: 'ts' } - : undefined - ) - } - } - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - expect(await main({ plugins: [addElectron] })).toBe(1) - expect(error.mock.calls.join('\n')).toContain('+ src/main/native-chat/transcript-read-cache.ts') - }, 120_000) -}) 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 11fa95a615f..696908b1756 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 @@ -61,7 +61,6 @@ const NODE_RUNTIME_INCLUDE = [ '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', - 'src/main/acp/journal/acp-structured-child-work-admission.test.ts', 'src/main/acp/session/children/acp-structured-child-work.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-background-stop-unreadable.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-exit-delivery.test.ts', diff --git a/src/cli/browser/browser.test.ts b/src/cli/browser/browser.test.ts index 8306fe8e155..6684f20fdeb 100644 --- a/src/cli/browser/browser.test.ts +++ b/src/cli/browser/browser.test.ts @@ -47,14 +47,7 @@ vi.mock('../runtime-client', async () => { }) import { main } from '../index' -import { RuntimeClientError } from '../runtime/types' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - worktreeListFixture -} from '../test-fixtures' +import { okFixture, queueFixtures } from '../test-fixtures' describe('orca cli browser page targeting', () => { beforeEach(() => { @@ -66,74 +59,6 @@ describe('orca cli browser page targeting', () => { vi.unstubAllEnvs() }) - it('passes explicit page ids to snapshot without resolving the current worktree', async () => { - queueFixtures( - callMock, - okFixture('req_snapshot', { - browserPageId: 'page-1', - snapshot: 'tree', - refs: [], - url: 'https://example.com', - title: 'Example' - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['snapshot', '--page', 'page-1', '--json'], '/tmp/not-an-orca-worktree') - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.snapshot', { page: 'page-1' }) - }) - - it('sends snapshot flags to the host and prints delta changes against the last tree', async () => { - queueFixtures( - callMock, - okFixture('req_snapshot', { - browserPageId: 'page-1', - snapshot: { - kind: 'delta', - revision: 3, - baseRevision: 2, - treeChange: { startLine: 4, deleteCount: 2, lines: ['- button "Save" [ref=e9]'] } - }, - url: 'https://example.com', - title: 'Example' - }) - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'snapshot', - '--page', - 'page-1', - '--interactive', - '--depth', - '3', - '--selector', - 'form', - '--delta' - ], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith('browser.snapshot', { - page: 'page-1', - interactive: true, - depth: 3, - selector: 'form', - delta: true - }) - expect(log).toHaveBeenCalledWith( - [ - 'page: page-1', - 'Example — https://example.com', - 'revision 3: changes to revision 2; replace lines 5-6 with:', - '- button "Save" [ref=e9]' - ].join('\n') - ) - }) - it('saves screenshots where the CLI runs and prints the path instead of base64', async () => { const screenshotDir = mkdtempSync(join(tmpdir(), 'orca-browser-shot-')) vi.stubEnv('ORCA_BROWSER_SCREENSHOT_TMPDIR', screenshotDir) @@ -163,509 +88,4 @@ describe('orca cli browser page targeting', () => { rmSync(screenshotDir, { recursive: true, force: true }) } }) - - it('resolves current worktree only when --page is combined with --worktree current', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_snapshot', { - browserPageId: 'page-1', - snapshot: 'tree', - refs: [], - url: 'https://example.com', - title: 'Example' - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['snapshot', '--page', 'page-1', '--worktree', 'current', '--json'], - '/tmp/repo/feature/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(3, 'browser.snapshot', { - page: 'page-1', - worktree: 'id:repo::/tmp/repo/feature' - }) - }) - - it('passes page-targeted tab switches through without auto-scoping to the current worktree', async () => { - queueFixtures(callMock, okFixture('req_switch', { switched: 2, browserPageId: 'page-2' })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['tab', 'switch', '--page', 'page-2', '--json'], '/tmp/repo/feature/src') - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.tabSwitch', { - index: undefined, - page: 'page-2' - }) - expect(callMock.mock.calls[0][1]).not.toHaveProperty('focus') - }) - - it('still resolves the current worktree when tab switch --page is combined with --worktree current', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_switch', { switched: 2, browserPageId: 'page-2' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['tab', 'switch', '--page', 'page-2', '--worktree', 'current', '--json'], - '/tmp/repo/feature/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(3, 'browser.tabSwitch', { - index: undefined, - page: 'page-2', - worktree: 'id:repo::/tmp/repo/feature' - }) - }) - - it('asks for a split beside the calling terminal tab with --split', async () => { - vi.stubEnv('ORCA_TAB_ID', 'terminal-tab-1') - queueFixtures(callMock, okFixture('req_create', { browserPageId: 'page-4' })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['tab', 'create', '--url', 'https://example.com', '--split', 'right', '--worktree', 'all'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith( - 'browser.tabCreate', - { - url: 'https://example.com', - worktree: undefined, - profileId: undefined, - split: 'right', - splitFromTabId: 'terminal-tab-1' - }, - { timeoutMs: 60_000 } - ) - vi.unstubAllEnvs() - }) - - it('leaves the caller tab out of a plain tab create', async () => { - vi.stubEnv('ORCA_TAB_ID', 'terminal-tab-1') - queueFixtures(callMock, okFixture('req_create', { browserPageId: 'page-5' })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['tab', 'create', '--worktree', 'all'], '/tmp/not-an-orca-worktree') - - expect(callMock.mock.calls[0][1]).not.toHaveProperty('split') - expect(callMock.mock.calls[0][1]).not.toHaveProperty('splitFromTabId') - vi.unstubAllEnvs() - }) - - it('rejects an unknown --split direction before calling the runtime', async () => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main(['tab', 'create', '--split', 'sideways'], '/tmp/not-an-orca-worktree') - - expect(callMock).not.toHaveBeenCalled() - expect(errorSpy).toHaveBeenCalledWith('--split must be right, left, down, or up') - }) - - it('rejects --split with no direction instead of opening a plain tab', async () => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main(['tab', 'create', '--split='], '/tmp/not-an-orca-worktree') - - expect(callMock).not.toHaveBeenCalled() - expect(errorSpy).toHaveBeenCalledWith('Missing value for --split') - }) - - it('opens browser-launch URLs on the client hosting the current worktree', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_open_url', { browserPageId: 'page-local' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['open-url', '--url', 'https://example.com/login', '--json'], '/tmp/repo/feature') - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'browser.openUrl', - { - url: 'https://example.com/login', - worktree: 'id:repo::/tmp/repo/feature' - }, - { timeoutMs: 60_000 } - ) - }) - - it('creates a tab in the calling folder workspace, not the parent sharing its path (#33618)', async () => { - const parent = buildWorktree('/tmp/folder', '') - const workspace = { ...parent, id: `${parent.id}::workspace:ws-2` } - queueFixtures( - callMock, - worktreeListFixture([parent, workspace]), - noFolderWorkspacesFixture(), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv('ORCA_WORKTREE_ID', workspace.id) - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/folder') - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'browser.tabCreate', - { url: 'https://example.com', worktree: `id:${workspace.id}` }, - { timeoutMs: 60_000 } - ) - }) - - it("creates a tab in the calling terminal's worktree when cwd is outside every worktree", async () => { - const caller = buildWorktree('/tmp/repo/caller', 'caller') - queueFixtures( - callMock, - worktreeListFixture([caller, buildWorktree('/tmp/repo/other', 'other')]), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv('ORCA_WORKTREE_ID', caller.id) - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/scratch') - - expect(callMock).toHaveBeenLastCalledWith( - 'browser.tabCreate', - { url: 'https://example.com', worktree: `id:${caller.id}` }, - { timeoutMs: 60_000 } - ) - }) - - it("names the calling terminal's host when its worktree id exists on two hosts", async () => { - const caller = { ...buildWorktree('/tmp/repo/caller', 'caller'), identity: { key: 'wt:local' } } - const sshTwin = { ...caller, hostId: 'ssh:host-a' as const, identity: { key: 'wt:ssh' } } - queueFixtures( - callMock, - worktreeListFixture([sshTwin, caller]), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv('ORCA_WORKTREE_ID', caller.id) - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/scratch') - - expect(callMock).toHaveBeenLastCalledWith( - 'browser.tabCreate', - { url: 'https://example.com', worktree: 'identity:wt:local' }, - { timeoutMs: 60_000 } - ) - }) - - it("refuses instead of using the focused worktree when the terminal's worktree is gone", async () => { - queueFixtures(callMock, worktreeListFixture([buildWorktree('/tmp/repo/other', 'other')])) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - vi.stubEnv('ORCA_WORKTREE_ID', 'repo::/tmp/repo/deleted') - - await main(['tab', 'create', '--url', 'https://example.com'], '/tmp/scratch') - - expect(callMock).not.toHaveBeenCalledWith( - 'browser.tabCreate', - expect.anything(), - expect.anything() - ) - expect(errorSpy).toHaveBeenCalledWith( - "This terminal's workspace repo::/tmp/repo/deleted is not listed by Orca on this host. Run the command from a workspace directory or pass --worktree (or all) where the command accepts it." - ) - }) - - it('keeps the runtime default for the floating terminal, which has no workspace row', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/other', 'other')]), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv('ORCA_WORKTREE_ID', 'global-floating-terminal') - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/scratch') - - expect(callMock).toHaveBeenLastCalledWith( - 'browser.tabCreate', - { url: 'https://example.com', worktree: undefined }, - { timeoutMs: 60_000 } - ) - }) - - it("ignores the terminal's worktree when it was launched by another Orca profile", async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/other', 'other')]), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv('ORCA_RUNTIME_SOURCE_ID', 'installed-source') - vi.stubEnv('ORCA_RUNTIME_SOURCE_INCARNATION', 'installed-runtime') - vi.stubEnv('ORCA_RUNTIME_SOURCE_PROFILE_PATH', '/tmp/orca-installed-profile') - vi.stubEnv('ORCA_WORKTREE_ID', 'repo::/tmp/repo/installed-only') - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/scratch') - - expect(callMock).toHaveBeenLastCalledWith( - 'browser.tabCreate', - { url: 'https://example.com', worktree: undefined }, - { timeoutMs: 60_000 } - ) - }) - - it.each(['ORCA_WORKTREE_ID', 'ORCA_WORKSPACE_ID'])( - 'creates a tab in the folder workspace named by %s when cwd is outside it', - async (envName) => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/other', 'other')]), - okFixture('req_tab_create', { browserPageId: 'page-1' }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.stubEnv(envName, 'folder:fw-1') - - await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/scratch') - - expect(callMock).toHaveBeenLastCalledWith( - 'browser.tabCreate', - { url: 'https://example.com', worktree: 'folder:fw-1' }, - { timeoutMs: 60_000 } - ) - } - ) -}) - -describe('orca cli browser identity', () => { - beforeEach(() => { - callMock.mockReset() - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('gets the host identity only after capability negotiation', async () => { - queueFixtures( - callMock, - okFixture('status', { capabilities: ['browser.identity.v1'] }), - okFixture('identity', { - identity: { - state: 'valid', - appliedMode: 'clean', - configuredMode: 'native', - explicitSelection: true, - migrationNoticePending: false, - restartRequired: true - }, - migrationNotice: null - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['browser', 'identity', 'get', '--json'], '/tmp/not-an-orca-worktree') - - expect(callMock).toHaveBeenNthCalledWith(1, 'status.get') - expect(callMock).toHaveBeenNthCalledWith(2, 'browser.identity.get') - }) - - it('refuses an older runtime instead of guessing at identity support', async () => { - queueFixtures(callMock, okFixture('status', { capabilities: [] })) - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main(['browser', 'identity', 'get'], '/tmp/not-an-orca-worktree') - - expect(callMock).toHaveBeenCalledTimes(1) - expect(error).toHaveBeenCalledWith(expect.stringContaining('Update or restart Orca')) - }) -}) - -describe('orca cli browser tab profiles', () => { - beforeEach(() => { - callMock.mockReset() - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('rejects unknown --scope values instead of silently defaulting to isolated', async () => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main( - ['tab', 'profile', 'create', '--label', 'Work', '--scope', 'isloated'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(errorSpy).toHaveBeenCalledWith('--scope must be "isolated" or "imported"') - }) - - it('surfaces a runtime error if the registry refuses to create a profile', async () => { - queueFixtures(callMock, okFixture('req_profile_create', { profile: null })) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main(['tab', 'profile', 'create', '--label', 'Bogus'], '/tmp/not-an-orca-worktree') - - expect(callMock).toHaveBeenCalledTimes(1) - expect(errorSpy).toHaveBeenCalledWith( - 'Failed to create browser profile (label=Bogus, scope=isolated)' - ) - }) -}) - -describe('orca cli browser cookies', () => { - beforeEach(() => { - callMock.mockReset() - process.exitCode = undefined - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('passes a finite non-negative cookie expiry through as a number', async () => { - queueFixtures(callMock, okFixture('req_cookie', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'cookie', - 'set', - '--name', - 'sid', - '--value', - 'x', - '--expires', - '0', - '--worktree', - 'all', - '--json' - ], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith('browser.cookie.set', { - name: 'sid', - value: 'x', - expires: 0, - worktree: undefined - }) - }) - - it.each(['not-a-number', 'Infinity', '-1'])( - 'rejects invalid cookie expiry value %s before RPC dispatch', - async (expires) => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['cookie', 'set', '--name', 'sid', '--value', 'x', '--expires', expires], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(errorSpy.mock.calls.flat().join('\n')).toContain(`Invalid --expires value: ${expires}`) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - } - ) - - it('rejects --expires without a value before RPC dispatch', async () => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['cookie', 'set', '--name', 'sid', '--value', 'x', '--expires'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(errorSpy.mock.calls.flat().join('\n')).toContain('Missing value for --expires.') - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) -}) - -describe('orca cli browser waits and viewport flags', () => { - beforeEach(() => { - callMock.mockReset() - process.exitCode = undefined - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('gives selector waits an explicit RPC timeout budget', async () => { - queueFixtures(callMock, okFixture('req_wait', { ok: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['wait', '--selector', '#ready', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith( - 'browser.wait', - { - selector: '#ready', - timeout: undefined, - text: undefined, - url: undefined, - load: undefined, - fn: undefined, - state: undefined, - worktree: undefined - }, - { timeoutMs: 60_000 } - ) - }) - - it('extends selector wait RPC timeout when the user passes --timeout', async () => { - queueFixtures(callMock, okFixture('req_wait', { ok: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['wait', '--selector', '#ready', '--timeout', '45000', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith( - 'browser.wait', - { - selector: '#ready', - timeout: 45000, - text: undefined, - url: undefined, - load: undefined, - fn: undefined, - state: undefined, - worktree: undefined - }, - { timeoutMs: 75000 } - ) - }) - - it('does not tell users Orca is down for a generic runtime timeout', async () => { - callMock.mockRejectedValueOnce( - new RuntimeClientError( - 'runtime_timeout', - 'Timed out waiting for the Orca runtime to respond.' - ) - ) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main(['wait', '--selector', '#ready', '--worktree', 'all'], '/tmp/not-an-orca-worktree') - - expect(errorSpy).toHaveBeenCalledWith('Timed out waiting for the Orca runtime to respond.') - }) }) diff --git a/src/cli/handlers/account.test.ts b/src/cli/handlers/account.test.ts index bdb68b30a8e..7242a09940a 100644 --- a/src/cli/handlers/account.test.ts +++ b/src/cli/handlers/account.test.ts @@ -64,7 +64,7 @@ vi.mock('../../shared/windows-console-input', () => ({ import { ACCOUNT_HANDLERS } from './account' import { REPEATED_FLAG_SEPARATOR } from '../args' import type { HandlerContext } from '../dispatch' -import { RuntimeClientError, type RuntimeClient } from '../runtime-client' +import type { RuntimeClient } from '../runtime-client' import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY, ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY, @@ -190,264 +190,6 @@ describe('account CLI handlers', () => { } }) - it('falls back to OpenCode when opencode2 cannot be spawned', async () => { - const supportedCommand = 'opencode' - callMock.mockResolvedValue({ - id: 'test', - ok: true, - result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] }, - _meta: { runtimeId: 'test-runtime' } - }) - resolveCliCommandMock.mockImplementation((command: string) => `/tools/${command}`) - probeMock.mockImplementation(({ program }) => { - if (program !== `/tools/${supportedCommand}`) { - throw new Error('ENOENT') - } - return helpChild('--standalone Run with a private server instead of the background service') - }) - await ACCOUNT_HANDLERS['account add'](context('opencode', true)) - expect(probeMock.mock.calls.map(([spec]) => spec.program)).toEqual([ - '/tools/opencode2', - '/tools/opencode' - ]) - const [command, args, options] = spawnMock.mock.calls[0] - expect(command).toBe(`/tools/${supportedCommand}`) - expect(args).toEqual(['auth', 'login', '--standalone']) - expect(probeMock).toHaveBeenLastCalledWith( - expect.objectContaining({ - args: ['auth', 'login', '--help'], - env: options.env - }) - ) - expect(options.env.OPENCODE_DB).toBe('opencode.db') - expect(existsSync(options.env.XDG_DATA_HOME)).toBe(false) - expect(callMock).toHaveBeenLastCalledWith('accounts.addDataFromHome', { - provider: 'opencode', - sourceDataHome: options.env.XDG_DATA_HOME, - label: 'opencode' - }) - }) - - it('passes the same original Windows launcher to the probe and login', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - callMock.mockResolvedValue({ result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] } }) - const launcher = String.raw`C:\Users\A&B\npm tools\opencode2.cmd` - resolveCliCommandMock.mockReturnValue(launcher) - probeMock.mockImplementation(() => helpChild('--standalone')) - - await ACCOUNT_HANDLERS['account add'](context('opencode', true)) - - expect(probeMock).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ program: launcher, args: ['auth', 'login', '--help'] }) - ) - const probeEnv = probeMock.mock.calls[0][0].env - expect(spawnMock).toHaveBeenCalledExactlyOnceWith( - launcher, - ['auth', 'login', '--standalone'], - expect.objectContaining({ env: probeEnv, stdio: ['inherit', process.stderr, 'inherit'] }) - ) - expect(existsSync(probeEnv.XDG_DATA_HOME)).toBe(false) - expect(callMock).toHaveBeenLastCalledWith('accounts.addDataFromHome', { - provider: 'opencode', - sourceDataHome: probeEnv.XDG_DATA_HOME, - label: 'opencode' - }) - }) - - it.each(['v1', 'missing'])( - 'gives installation guidance after %s candidates without altering generic launchers', - async (fallback) => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - callMock.mockResolvedValue({ result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] } }) - resolveCliCommandMock.mockImplementation((name: string) => `C:\\tools\\${name}.cmd`) - probeMock.mockImplementation(() => { - if (fallback === 'missing') { - throw new Error('ENOENT') - } - return helpChild('Usage: opencode auth login [url]') - }) - const failure = await ACCOUNT_HANDLERS['account add'](context('opencode', true)).catch( - (error: unknown) => error - ) - expect(failure).toBeInstanceOf(RuntimeClientError) - if (!(failure instanceof RuntimeClientError)) { - throw new Error('Expected account-add failure') - } - expect(probeMock).toHaveBeenCalledTimes(2) - expect(spawnMock).not.toHaveBeenCalled() - expect(callMock.mock.calls.map(([method]) => method)).toEqual(['status.get']) - expect(existsSync(probeMock.mock.calls[0][0].env.XDG_DATA_HOME)).toBe(false) - expect(failure.message).toContain( - String.raw`npm install --prefix C:\tools\orca-opencode2 @opencode/cli` - ) - expect(failure.message).toContain('without changing your generic opencode launcher') - expect(failure.message).not.toContain('Usage:') - } - ) - - it('uses Codex device auth and keeps JSON stdout clean', async () => { - await ACCOUNT_HANDLERS['account add'](context('codex', true)) - - expect(spawnMock).toHaveBeenCalledWith( - 'codex', - ['login', '--device-auth'], - expect.objectContaining({ - stdio: ['inherit', process.stderr, 'inherit'], - env: expect.objectContaining({ CODEX_HOME: expect.any(String) }) - }) - ) - const spawnOptions = spawnMock.mock.calls[0]?.[2] - expect(spawnOptions.env.ELECTRON_RUN_AS_NODE).toBeUndefined() - expect(existsSync(spawnOptions.env.CODEX_HOME)).toBe(false) - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', { - sourceHome: spawnOptions.env.CODEX_HOME - }) - }) - - it('passes Windows console device handles to the login child instead of inheriting Electron stdio', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const dispose = vi.fn() - stdioForWindowsInteractiveChildMock.mockReturnValue({ - stdio: [11, 'inherit', 'inherit'], - dispose - }) - - await ACCOUNT_HANDLERS['account add'](context('codex')) - - expect(spawnMock).toHaveBeenCalledWith( - 'codex', - ['login', '--device-auth'], - expect.objectContaining({ stdio: [11, 'inherit', 'inherit'] }) - ) - expect(dispose).toHaveBeenCalledTimes(1) - }) - - it('disposes the Windows console input fd when spawn throws synchronously', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const dispose = vi.fn() - stdioForWindowsInteractiveChildMock.mockReturnValue({ - stdio: [11, 'inherit', 'inherit'], - dispose - }) - spawnMock.mockImplementationOnce(() => { - throw new Error('invalid stdio') - }) - - await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow('invalid stdio') - - expect(dispose).toHaveBeenCalledOnce() - }) - - it('forwards Windows form text literally through the process launcher', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - callMock.mockResolvedValue({ result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] } }) - resolveCliCommandMock.mockImplementation((command: string) => `C:\\tools\\${command}.cmd`) - probeMock.mockImplementation(() => helpChild('--standalone')) - const answer = 'instance URL=https://gitlab.example.test/a%20b?x="quoted"&y=a=b!' - await ACCOUNT_HANDLERS['account add']({ - ...context('opencode', true), - flags: new Map([ - ['agent', 'opencode'], - ['answer', answer] - ]) - }) - expect(spawnMock.mock.calls[0][1]).toEqual([ - 'auth', - 'login', - '--answer', - answer, - '--standalone' - ]) - expect(callMock).toHaveBeenLastCalledWith('accounts.addDataFromHome', expect.anything()) - }) - - it('runs login in the final profile without accessing a locked Keychain', async () => { - readKeychainMock.mockRejectedValue(new Error('locked')) - deleteKeychainMock.mockRejectedValue(new Error('locked')) - writeKeychainMock.mockRejectedValue(new Error('locked')) - await ACCOUNT_HANDLERS['account add'](context('claude')) - expect(spawnMock.mock.calls[0]?.[2].env.CLAUDE_CONFIG_DIR).toBe('/fake/final-profile') - expect(callMock).toHaveBeenCalledWith( - 'accounts.finishClaudeSignIn', - { accountId: 'draft', runtime: 'host', wslDistro: undefined }, - { timeoutMs: 300000 } - ) - expect(readKeychainMock).not.toHaveBeenCalled() - expect(writeKeychainMock).not.toHaveBeenCalled() - expect(deleteKeychainMock).not.toHaveBeenCalled() - }) - - it('attributes a Codex account added through the WSL bridge to the cwd distro', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - - await ACCOUNT_HANDLERS['account add']( - context('codex', false, String.raw`\\wsl$\Ubuntu\home\user`) - ) - - const sourceHome = spawnMock.mock.calls[0]?.[2].env.CODEX_HOME - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', { - sourceHome, - runtime: 'wsl', - wslDistro: 'Ubuntu' - }) - }) - - it('uses the explicit bridge distro over an ambient environment or another distro cwd', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - process.env.WSL_DISTRO_NAME = 'stale-Windows-value' - process.env.ORCA_CLI_WSL_DISTRO = 'Debian' - - await ACCOUNT_HANDLERS['account add']( - context('claude', false, String.raw`\\wsl.localhost\Ubuntu-22.04\home\user`) - ) - - expect(callMock).toHaveBeenCalledWith( - 'accounts.beginClaudeSignIn', - expect.objectContaining({ runtime: 'wsl', wslDistro: 'Debian' }), - { timeoutMs: 300000 } - ) - }) - - it.each(['claude', 'codex'])( - 'attributes %s from a Windows mount to the bridge distro', - async (agent) => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - process.env.ORCA_CLI_WSL_DISTRO = 'Ubuntu Work' - await ACCOUNT_HANDLERS['account add'](context(agent, false, String.raw`C:\work with spaces`)) - expect( - callMock.mock.calls.some( - ([method, params]) => - method === - (agent === 'claude' ? 'accounts.beginClaudeSignIn' : 'accounts.addCodexFromHome') && - params.wslDistro === 'Ubuntu Work' - ) - ).toBe(true) - } - ) - - it('ignores an ambient WSL distro in a native Windows account add', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - process.env.WSL_DISTRO_NAME = 'stale-Windows-value' - await ACCOUNT_HANDLERS['account add'](context('codex', false, String.raw`C:\work`)) - const sourceHome = spawnMock.mock.calls[0]?.[2].env.CODEX_HOME - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', { sourceHome }) - }) - - it.each(['linux', 'darwin'])( - 'keeps host attribution when the CLI runs on %s', - async (platform) => { - // Linux runtimes use host-lane accounts even when the CLI itself runs in WSL. - Object.defineProperty(process, 'platform', { configurable: true, value: platform }) - process.env.WSL_DISTRO_NAME = 'Ubuntu-22.04' - process.env.ORCA_CLI_WSL_DISTRO = 'Ubuntu-22.04' - - await ACCOUNT_HANDLERS['account add'](context('codex')) - - const sourceHome = spawnMock.mock.calls[0]?.[2].env.CODEX_HOME - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', { sourceHome }) - } - ) - it('waits for physical child close before removing interrupted login credentials', async () => { // A live login can recreate credentials after cleanup; wait for close before deleting them. Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) @@ -481,165 +223,6 @@ describe('account CLI handlers', () => { exitSpy.mockRestore() }) - it('cleans up when an SSH hangup ends the login', async () => { - // Node's default SIGHUP exit would bypass cleanup when an SSH connection drops. - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - const child = Object.assign(new EventEmitter(), { kill: vi.fn() }) - let codexHome = '' - spawnMock.mockImplementation((_command, _args, options: { env: Record }) => { - codexHome = options.env.CODEX_HOME - return child - }) - const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) - const listenersBefore = process.listeners('SIGHUP') - - const pending = ACCOUNT_HANDLERS['account add'](context('codex')).catch(() => {}) - await vi.waitFor(() => expect(codexHome).not.toBe('')) - - newSignalListener('SIGHUP', listenersBefore)('SIGHUP') - - await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGHUP')) - expect(exitSpy).not.toHaveBeenCalled() - expect(existsSync(codexHome)).toBe(true) - - child.emit('exit', 1) - child.emit('close', 1) - await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(129)) - expect(existsSync(codexHome)).toBe(false) - - await pending - exitSpy.mockRestore() - }) - - it('warns that the account may already be registered when interrupted mid-RPC', async () => { - // Registration continues at the runtime after the CLI is interrupted. - const child = Object.assign(new EventEmitter(), { kill: vi.fn() }) - spawnMock.mockImplementation(() => { - queueMicrotask(() => child.emit('exit', 0)) - return child - }) - let rejectRegistration: ((error: Error) => void) | undefined - const registration = new Promise((_resolve, reject) => { - rejectRegistration = reject - }) - // Only registration waits; preflight must still resolve. - callMock.mockImplementation((method: string) => - method === 'status.get' - ? Promise.resolve({ - id: 'test', - ok: true, - result: { - capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY, CLAUDE_SIGN_IN_RUNTIME_CAPABILITY] - }, - _meta: { runtimeId: 'test-runtime' } - }) - : method === 'accounts.list' - ? Promise.resolve({ - id: 'test', - ok: true, - result: { claude: accountState('c@e.com'), codex: accountState('x@e.com') }, - _meta: { runtimeId: 'test-runtime' } - }) - : registration - ) - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) - const listenersBefore = process.listeners('SIGINT') - - const pending = ACCOUNT_HANDLERS['account add'](context('codex')).catch(() => {}) - try { - await vi.waitFor(() => - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', expect.anything()) - ) - - newSignalListener('SIGINT', listenersBefore)('SIGINT') - - await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(130)) - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining('may still have been registered') - ) - } finally { - rejectRegistration?.(new Error('finish interrupted registration')) - await pending - warnSpy.mockRestore() - exitSpy.mockRestore() - } - expect(process.listeners('SIGINT')).toEqual(listenersBefore) - }) - - it('fails before the login when the runtime is unreachable', async () => { - callMock.mockRejectedValue(new Error('runtime not running')) - - await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow( - 'runtime not running' - ) - expect(callMock).toHaveBeenCalledWith('status.get') - expect(spawnMock).not.toHaveBeenCalled() - }) - - it('adds Codex through an older host that advertises only the retired import capability', async () => { - callMock.mockResolvedValueOnce({ - id: 'test', - ok: true, - result: { capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY] }, - _meta: { runtimeId: 'test-runtime' } - }) - - await ACCOUNT_HANDLERS['account add'](context('codex')) - - const sourceHome = spawnMock.mock.calls[0]?.[2].env.CODEX_HOME - expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', { sourceHome }) - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('codex@example.com')) - }) - - it.each(['claude', 'codex'] as const)( - 'refuses %s login before spawning when its capability is absent', - async (agent) => { - callMock.mockResolvedValue({ - id: 'test', - ok: true, - result: { capabilities: [] }, - _meta: { runtimeId: 'test-runtime' } - }) - - await expect(ACCOUNT_HANDLERS['account add'](context(agent))).rejects.toThrow( - 'The running Orca runtime is too old to add accounts from the CLI.' - ) - expect(callMock).toHaveBeenCalledOnce() - expect(callMock).toHaveBeenCalledWith('status.get') - expect(spawnMock).not.toHaveBeenCalled() - } - ) - - it.each(['environment', 'pairing-code'])( - 'rejects --%s instead of silently ignoring it', - async (flag) => { - await expect( - ACCOUNT_HANDLERS['account add']({ - ...context('codex'), - flags: new Map([ - ['agent', 'codex'], - [flag, 'homelab'] - ]) - }) - ).rejects.toThrow(`\`--${flag}\` does not retarget`) - expect(spawnMock).not.toHaveBeenCalled() - } - ) - - it.each(['environment', 'pairing-code'])( - 'rejects --%s on `account list` instead of listing the local host', - async (flag) => { - await expect( - ACCOUNT_HANDLERS['account list']({ - ...context('claude'), - flags: new Map([[flag, 'homelab']]) - }) - ).rejects.toThrow(`\`--${flag}\` does not retarget`) - expect(callMock).not.toHaveBeenCalled() - } - ) - it('keeps the original add error when cleanup also fails', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) rmSyncMock.mockImplementationOnce(() => { @@ -684,23 +267,6 @@ describe('account CLI handlers', () => { expect(logSpy).not.toHaveBeenCalled() }) - it.each(['claude', 'codex'])( - 'rejects OpenCode login flags for %s before login', - async (agent) => { - await expect( - ACCOUNT_HANDLERS['account add']({ - ...context(agent), - flags: new Map([ - ['agent', agent], - ['method', 'device'] - ]) - }) - ).rejects.toThrow('only supported with --agent opencode') - expect(callMock).not.toHaveBeenCalled() - expect(spawnMock).not.toHaveBeenCalled() - } - ) - it('keeps OpenCode form answer values out of the login failure message', async () => { callMock.mockResolvedValue({ id: 'test', @@ -732,15 +298,6 @@ describe('account CLI handlers', () => { ) }) - it('rejects `--agent` with no value instead of defaulting to Claude', async () => { - await expect( - ACCOUNT_HANDLERS['account add']({ ...context('claude'), flags: new Map([['agent', true]]) }) - ).rejects.toThrow( - 'Missing a value for --agent. Use `--agent claude`, `--agent codex`, `--agent opencode`, or `--agent devin`.' - ) - expect(spawnMock).not.toHaveBeenCalled() - }) - describe('select and rm by --account', () => { const antigravityAccounts = { accounts: [ @@ -792,20 +349,6 @@ describe('account CLI handlers', () => { ) }) - it('selects and removes Antigravity accounts by email or subject on the host', async () => { - await ACCOUNT_HANDLERS['account select'](selectionContext('antigravity', 'ME@gmail.example')) - await ACCOUNT_HANDLERS['account rm'](selectionContext('antigravity', 'sub-2')) - - expect(callMock).toHaveBeenCalledWith('accounts.antigravitySelect', { - target: { runtime: 'host' }, - accountId: 'agy-1' - }) - expect(callMock).toHaveBeenCalledWith('accounts.antigravityRemove', { - target: { runtime: 'host' }, - accountId: 'agy-2' - }) - }) - it('refuses an email shared by several accounts without switching or removing', async () => { await expect( ACCOUNT_HANDLERS['account select'](selectionContext('claude', 'shared@example.com')) @@ -816,13 +359,6 @@ describe('account CLI handlers', () => { expect(mutatingCalls()).toEqual([]) }) - it('refuses the Antigravity system default, which its vault does not have', async () => { - await expect( - ACCOUNT_HANDLERS['account select'](selectionContext('antigravity', 'system')) - ).rejects.toThrow('Antigravity has no system default') - expect(mutatingCalls()).toEqual([]) - }) - it('refuses the Claude system default from WSL rather than resetting the Windows host', async () => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) process.env.ORCA_CLI_WSL_DISTRO = 'Ubuntu' diff --git a/src/cli/handlers/agent-hooks.test.ts b/src/cli/handlers/agent-hooks.test.ts index bff357168f7..34e5be68c7e 100644 --- a/src/cli/handlers/agent-hooks.test.ts +++ b/src/cli/handlers/agent-hooks.test.ts @@ -20,7 +20,6 @@ import { hashProfileStateJson, importProfileStateJson } from '../../main/persistence/profile-state/profile-state-documents' -import { ProfileStateSqliteAuthority } from '../../main/persistence/profile-state/profile-state-sqlite-authority' import { acquireProfileStateMaintenance, acquireProfileStateRuntimeAdmission, @@ -90,18 +89,6 @@ vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () => import { main } from '../index' -function readDefaultProfileState(userDataPath: string) { - const opened = openProfileStateDatabase( - getOrcaProfileStateDatabaseFile(DEFAULT_LOCAL_ORCA_PROFILE_ID, userDataPath), - DEFAULT_LOCAL_ORCA_PROFILE_ID - ) - try { - return JSON.parse(exportProfileStateJson(opened.db)) - } finally { - opened.db.close() - } -} - function writeDataFile(userDataPath: string, state: PersistedState): void { mkdirSync(userDataPath, { recursive: true }) writeFileSync(join(userDataPath, 'orca-data.json'), JSON.stringify(state, null, 2), 'utf-8') @@ -143,19 +130,6 @@ describe('agent hooks CLI handler', () => { rmSync(userDataPath, { recursive: true, force: true }) }) - it('keeps new card style off when creating offline settings for a fresh profile', async () => { - await runAgentHooksOff(userDataPath) - - const persisted = readDefaultProfileState(userDataPath) - - expect(persisted.settings.experimentalNewWorktreeCardStyle).toBe(false) - expect(persisted.settings.agentStatusHooksEnabled).toBe(false) - expect(existsSync(join(userDataPath, 'orca-data.json'))).toBe(false) - expect(existsSync(getOrcaProfileDataFile(DEFAULT_LOCAL_ORCA_PROFILE_ID, userDataPath))).toBe( - false - ) - }) - it.each(['fresh', 'root-json', 'profile-json'] as const)( 'refuses an incapable offline writer before any %s profile or hook changes', async (source) => { @@ -190,33 +164,6 @@ describe('agent hooks CLI handler', () => { } ) - it('keeps runtime writes available to an incapable CLI', async () => { - vi.spyOn(profileStateDatabase, 'isProfileStateSqliteAvailable').mockReturnValue(false) - getCliStatusMock.mockResolvedValueOnce({ - id: 'test-status', - ok: true, - result: { - app: { running: true, pid: null }, - runtime: { state: 'ready', reachable: true, runtimeId: null }, - graph: { state: 'ready' } - }, - _meta: { runtimeId: 'test' } - }) - callMock.mockResolvedValueOnce({ result: {} }) - - await runAgentHooksOff(userDataPath) - - expect(process.exitCode).not.toBe(1) - expect(callMock).toHaveBeenCalledWith( - 'settings.update', - { agentStatusHooksEnabled: false }, - { timeoutMs: 10_000 } - ) - expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled() - expect(existsSync(join(userDataPath, '.profile-state-access'))).toBe(false) - expect(existsSync(join(userDataPath, 'orca-profile-index.json'))).toBe(false) - }) - it.each(['root', 'indexed'] as const)( 'reads %s JSON status without SQLite or migration', async (source) => { @@ -240,26 +187,6 @@ describe('agent hooks CLI handler', () => { } ) - it('names the file each status reports on', async () => { - writeDataFile(userDataPath, getDefaultPersistedState(userDataPath)) - getDefaultUserDataPathMock.mockReturnValue(userDataPath) - getManagedAgentHookStatusesMock.mockReturnValue([ - { - agent: 'codex', - state: 'installed', - configPath: '/u/orca/codex-runtime-home/home/hooks.json', - managedHooksPresent: true, - detail: null - } - ]) - - await main(['agent', 'hooks', 'status'], userDataPath) - - expect(console.log).toHaveBeenCalledWith( - expect.stringContaining('codex: installed (/u/orca/codex-runtime-home/home/hooks.json)') - ) - }) - it.each(['missing', 'corrupt'] as const)( 'uses the backup index when the primary is %s', async (primary) => { @@ -299,7 +226,7 @@ describe('agent hooks CLI handler', () => { } ) - it.each([0, 1, 2, 3, 4])('refuses a pre-index root with only legacy backup %s', async (slot) => { + it.each([0])('refuses a pre-index root with only legacy backup %s', async (slot) => { const backup = join(userDataPath, `orca-data.json.bak.${slot}`) const source = '{"settings":{"agentStatusHooksEnabled":true}}' writeFileSync(backup, source) @@ -420,62 +347,6 @@ describe('agent hooks CLI handler', () => { } ) - it.each(['on', 'off', 'status', 'prepare-codex'])( - 'refuses explicit remote selection before local hook command %s', - async (command) => { - const state = getDefaultPersistedState(userDataPath) - writeDataFile(userDataPath, state) - const before = readFileSync(join(userDataPath, 'orca-data.json'), 'utf8') - getDefaultUserDataPathMock.mockReturnValue(userDataPath) - - for (const selector of ['environment', 'pairing-code']) { - process.exitCode = undefined - await main( - ['agent', 'hooks', command, `--${selector}`, 'unreachable-host', '--json'], - userDataPath - ) - - expect(process.exitCode).toBe(1) - expect(getCliStatusMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled() - expect(readFileSync(join(userDataPath, 'orca-data.json'), 'utf8')).toBe(before) - } - } - ) - - it('does nothing for a native pane, so an old shell wrapper still exits 0', async () => { - const home = '/Users/jin/Library/Application Support/orca/codex-runtime-home/home' - vi.stubEnv('CODEX_HOME', home) - vi.stubEnv('ORCA_CODEX_HOME', home) - vi.stubEnv('WSL_DISTRO_NAME', '') - - await main(['agent', 'hooks', 'prepare-codex'], userDataPath) - - expect(callMock).not.toHaveBeenCalled() - expect(getCliStatusMock).not.toHaveBeenCalled() - expect(process.exitCode).toBeUndefined() - }) - - it('fails open when WSL runtime preparation is unavailable', async () => { - vi.stubEnv('CODEX_HOME', '/home/jin/.local/share/orca/codex-runtime-home/home') - vi.stubEnv('ORCA_CODEX_HOME', '/home/jin/.local/share/orca/codex-runtime-home/home') - vi.stubEnv('WSL_DISTRO_NAME', 'Ubuntu') - callMock.mockRejectedValue(new Error('method_not_found')) - - await expect(main(['agent', 'hooks', 'prepare-codex'], userDataPath)).resolves.toBeUndefined() - expect(callMock).toHaveBeenCalledExactlyOnceWith( - 'agentHooks.prepareCodexForWslPane', - { - codexHome: '/home/jin/.local/share/orca/codex-runtime-home/home', - orcaCodexHome: '/home/jin/.local/share/orca/codex-runtime-home/home', - wslDistro: 'Ubuntu' - }, - { timeoutMs: 50_000 } - ) - expect(process.exitCode).toBeUndefined() - }) - it('updates an established SQLite profile without rewriting its JSON export', async () => { const profileId = 'work-profile' const profileDirectory = join(userDataPath, 'profiles', profileId) @@ -519,60 +390,6 @@ describe('agent hooks CLI handler', () => { } }) - it.each(['update-failed', 'unreachable', 'status-failed'] as const)( - 'preserves a live SQLite writer when runtime contact is %s', - async (failure) => { - const profileId = 'live-profile' - const profileDirectory = join(userDataPath, 'profiles', profileId) - mkdirSync(profileDirectory, { recursive: true }) - writeActiveProfileIndex(userDataPath, profileId) - const authority = new ProfileStateSqliteAuthority( - getOrcaProfileStateDatabaseFile(profileId, userDataPath), - profileId - ) - authority.writeSerializedState( - Buffer.from(JSON.stringify({ settings: { agentStatusHooksEnabled: true } })) - ) - if (failure === 'status-failed') { - getCliStatusMock.mockRejectedValueOnce(new Error('status transport unavailable')) - } else { - getCliStatusMock.mockResolvedValueOnce({ - id: 'test-status', - ok: true, - result: { - app: { running: true, pid: null }, - runtime: { - state: failure === 'unreachable' ? 'starting' : 'ready', - reachable: failure !== 'unreachable', - runtimeId: null - }, - graph: { state: 'ready' } - }, - _meta: { runtimeId: 'test' } - }) - callMock.mockRejectedValueOnce(new Error('settings request timed out')) - } - try { - await runAgentHooksOff(userDataPath) - - expect(process.exitCode).toBe(1) - expect(applyAgentStatusHooksEnabledMock).not.toHaveBeenCalled() - expect(() => - authority.writeSerializedDomains([ - { domain: 'ui', payload: '{"marker":"still-writable"}' } - ]) - ).not.toThrow() - const persisted = JSON.parse(authority.readSerializedState() ?? '{}') - expect(persisted).toMatchObject({ - settings: { agentStatusHooksEnabled: true }, - ui: { marker: 'still-writable' } - }) - } finally { - authority.close() - } - } - ) - it('imports a JSON-only active profile before the first settings mutation', async () => { const profileId = 'json-profile' const profileDirectory = join(userDataPath, 'profiles', profileId) diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index 7c855e40c6c..acaef5fb0bf 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -10,10 +10,8 @@ vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) import { ORCHESTRATION_HANDLERS } from './orchestration' import { printResult } from '../format' -import { parseArgs, validateCommandAndFlags } from '../args' import { RuntimeClient } from '../runtime-client' -import { ORCHESTRATION_WORKER_COMMAND_SPECS } from '../specs/orchestration-worker-specs' const client = new RuntimeClient('/tmp/orca-worker-cli', 60_000, null, null) @@ -66,87 +64,4 @@ describe('orchestration worker-start CLI contract', () => { expect(process.exitCode).toBe(1) }) - - it('allows the initial zero cursor when paging worker output', async () => { - callMock.mockResolvedValue({ - result: { - dispatchId: 'ctx_1', - terminal: { tail: [], status: 'running', nextCursor: '0' } - } - }) - - await ORCHESTRATION_HANDLERS['orchestration worker-read']({ - flags: new Map([ - ['dispatch', 'ctx_1'], - ['cursor', '0'], - ['limit', '100'] - ]), - client, - cwd: '/tmp/repo', - json: true - }) - - expect(callMock).toHaveBeenCalledWith('orchestration.workerRead', { - dispatch: 'ctx_1', - cursor: 0, - limit: 100, - source: undefined - }) - }) - - it('passes opaque source-pinned cursors and explicit source selection', async () => { - callMock.mockResolvedValue({ - result: { - dispatchId: 'ctx_1', - source: 'transcript', - transcript: { messages: [], nextCursor: 'owr1_next' } - } - }) - - await ORCHESTRATION_HANDLERS['orchestration worker-read']({ - flags: new Map([ - ['dispatch', 'ctx_1'], - ['cursor', 'owr1_previous'], - ['source', 'transcript'] - ]), - client, - cwd: '/tmp/repo', - json: true - }) - - expect(callMock).toHaveBeenCalledWith('orchestration.workerRead', { - dispatch: 'ctx_1', - cursor: 'owr1_previous', - limit: undefined, - source: 'transcript' - }) - }) - - it('keeps cleanup and retention TTL controls off the public CLI surface', async () => { - const kept = parseArgs(['orchestration', 'worker-keep-open', '--dispatch', 'ctx_1']) - expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, kept)).not.toThrow() - expect(() => - validateCommandAndFlags( - ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-cleanup']) - ) - ).toThrow('Unknown command: orchestration worker-cleanup') - expect(() => - validateCommandAndFlags( - ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-keep-open', '--until', '2099-01-01T00:00:00Z']) - ) - ).toThrow('Unknown flag --until for command: orchestration worker-keep-open') - - callMock.mockResolvedValue({ - result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } - }) - await ORCHESTRATION_HANDLERS['orchestration worker-keep-open']({ - flags: kept.flags, - client, - cwd: '/tmp/repo', - json: true - }) - expect(callMock).toHaveBeenCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) - }) }) diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/handlers/orchestration.test.ts index ae2a819afde..a22e1916003 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/handlers/orchestration.test.ts @@ -1,13 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -// Reuse one mutation identity when retrying worker_done after runtime_unavailable. -const WORKER_DONE_REQUEST = { orchestrationRequestId: expect.any(String) } const getTerminalHandleMock = vi.hoisted(() => vi.fn()) const originalExitCode = process.exitCode -function lifecycleGroupRecipientError(type: 'worker_done' | 'heartbeat'): string { - return `${type} messages belong to one exact Dispatch and cannot target a group address.` -} vi.mock('../format', () => ({ printResult: vi.fn() })) vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) @@ -16,7 +11,6 @@ import { ORCHESTRATION_HANDLERS } from './orchestration' import { printResult } from '../format' import { okFixture } from '../test-fixtures' -import { ORCHESTRATION_ASK_RETURNS_AT_ONCE_RUNTIME_CAPABILITY } from '../../shared/orchestration/orchestration-runtime-capabilities' beforeEach(() => { callMock.mockReset() @@ -54,144 +48,6 @@ describe('orchestration send structured payload flags', () => { json: true } as never) - it('serializes common worker payload fields as JSON', async () => { - await invokeSend( - new Map([ - ['from', 'term_worker'], - ['to', 'term_coord'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_1'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'succeeded'], - ['files-modified', ' src/a.ts, ,src/b.ts, '], - ['phase', 'verification'], - ['report-path', 'reports/done.md'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.send', - { - from: 'term_worker', - to: 'term_coord', - subject: 'done', - body: undefined, - type: 'worker_done', - priority: undefined, - threadId: undefined, - payload: JSON.stringify({ - taskId: 'task_1', - dispatchId: 'ctx_1', - outcome: 'succeeded', - filesModified: ['src/a.ts', 'src/b.ts'], - reportPath: 'reports/done.md', - phase: 'verification' - }), - waitForLifecycleSettlement: true, - devMode: false - }, - WORKER_DONE_REQUEST - ) - }) - - it('carries Dispatch authority in the RPC envelope instead of message params', async () => { - await invokeSend( - new Map([ - ['from', 'term_worker'], - ['subject', 'alive'], - ['type', 'heartbeat'], - ['dispatch-id', 'ctx_1'], - ['dispatch-capability', 'dcap_secret'], - ['retry-request', '33333333-3333-4333-8333-333333333333'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.send', - expect.not.objectContaining({ dispatchCapability: expect.anything() }), - { - orchestrationCapability: 'dcap_secret', - orchestrationRequestId: '33333333-3333-4333-8333-333333333333' - } - ) - }) - - it('rejects mixing raw payload with structured payload flags', async () => { - await expect( - invokeSend( - new Map([ - ['from', 'term_worker'], - ['to', 'term_coord'], - ['subject', 'done'], - ['payload', '{"taskId":"task_1"}'], - ['task-id', 'task_1'] - ]) - ) - ).rejects.toThrow(/structured payload/) - expect(callMock).not.toHaveBeenCalled() - }) - - it('rejects worker_done group sends before resolving a sender handle', async () => { - getTerminalHandleMock.mockRejectedValue(new Error('sender resolution should not run')) - - await expect( - invokeSend( - new Map([ - ['to', '@all'], - ['subject', 'done'], - ['type', 'worker_done'] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: lifecycleGroupRecipientError('worker_done') - }) - - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - }) - - it('rejects heartbeat group sends before resolving a sender handle', async () => { - getTerminalHandleMock.mockRejectedValue(new Error('sender resolution should not run')) - - await expect( - invokeSend( - new Map([ - ['to', '@idle'], - ['subject', 'alive'], - ['type', 'heartbeat'] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: lifecycleGroupRecipientError('heartbeat') - }) - - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - }) - - it('passes ORCA_PANE_KEY as the sender pane identity', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker_env' - process.env.ORCA_PANE_KEY = 'tab_worker:leaf_worker' - - await invokeSend( - new Map([ - ['to', 'term_coord'], - ['subject', 'done'], - ['type', 'worker_done'], - ['outcome', 'succeeded'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.send', - expect.objectContaining({ senderPaneKey: 'tab_worker:leaf_worker' }), - WORKER_DONE_REQUEST - ) - }) - it('refuses a structured session without naming a handle it could pass', async () => { process.env.ORCA_STRUCTURED_SESSION = '1' getTerminalHandleMock.mockResolvedValue('term_sibling_pane') @@ -216,17 +72,6 @@ describe('orchestration send structured payload flags', () => { }) describe('orchestration timeout flag validation', () => { - const invalidTimeoutValues: [string, string | boolean][] = [ - ['missing', true], - ['empty', ''], - ['non-numeric', 'not-a-number'], - ['zero', '0'], - ['negative', '-1'], - ['fractional', '1.5'], - ['rounded fractional', '9007199254740991.1'], - ['unsafe integer', String(Number.MAX_SAFE_INTEGER + 1)] - ] - const invokeCheck = (flags: Map) => ORCHESTRATION_HANDLERS['orchestration check']({ flags, @@ -235,70 +80,6 @@ describe('orchestration timeout flag validation', () => { json: true } as never) - const invokeAsk = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration ask']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => { - const flags = new Map([ - ['wait', true], - ['timeout-ms', value] - ]) - - await expect(invokeCheck(flags)).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - - it('passes a parsed check timeout and peek mode into the RPC payload', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ result: { messages: [], count: 0 } }) - - await invokeCheck( - new Map([ - ['wait', true], - ['peek', true], - ['timeout-ms', '250'] - ]) - ) - - // unread:false keeps --peek non-consuming when older runtimes ignore the peek field. - expect(callMock).toHaveBeenCalledWith('orchestration.check', { - terminal: 'term_worker', - terminalPaneKey: undefined, - unread: false, - peek: true, - all: undefined, - types: undefined, - format: undefined, - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - run: undefined, - ack: undefined, - wait: true, - timeoutMs: 250 - }) - }) - - it('rejects combined read modes before calling the runtime', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - await expect( - invokeCheck( - new Map([ - ['unread', true], - ['peek', true] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: expect.stringContaining('read mode') - }) - expect(callMock).not.toHaveBeenCalled() - }) - it('fails --peek --wait against a runtime that returned only read rows', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_worker' callMock.mockResolvedValue({ @@ -317,71 +98,4 @@ describe('orchestration timeout flag validation', () => { ) ).rejects.toMatchObject({ code: 'peek_wait_unsupported' }) }) - - it.each(invalidTimeoutValues)('rejects invalid ask --timeout-ms: %s', async (_label, value) => { - const flags = new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', value] - ]) - - await expect(invokeAsk(flags)).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - - it.each(['1800001', String(Number.MAX_SAFE_INTEGER)])( - 'rejects an oversized ask timeout %s before resolving identity or creating a question', - async (timeoutMs) => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - await expect( - invokeAsk( - new Map([ - ['question', 'Proceed?'], - ['timeout-ms', timeoutMs] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: expect.stringMatching(/--timeout-ms.*1800000.*30 minutes/) - }) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - } - ) - - it('asks without waiting only when the Orca it talks to advertises it', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - const askedWith = async (capabilities: string[]) => { - callMock.mockReset() - callMock.mockImplementation(async (method: string) => - method === 'status.get' - ? { result: { capabilities } } - : { result: { answer: null, messageId: 'msg_q', threadId: 'msg_q', timedOut: false } } - ) - await invokeAsk(new Map([['question', 'Proceed?']])) - return callMock.mock.calls.find(([method]) => method === 'orchestration.ask')?.[1] - } - - expect(await askedWith([ORCHESTRATION_ASK_RETURNS_AT_ONCE_RUNTIME_CAPABILITY])).toMatchObject({ - wait: false - }) - expect(await askedWith([])).not.toHaveProperty('wait') - }) - - it('rejects ambiguous ask create/resume input before RPC', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - await expect( - invokeAsk( - new Map([ - ['question', 'new'], - ['resume', 'msg_old'] - ]) - ) - ).rejects.toMatchObject({ code: 'invalid_argument' }) - expect(callMock).not.toHaveBeenCalled() - }) }) diff --git a/src/cli/handlers/orchestration/mutation-request.test.ts b/src/cli/handlers/orchestration/mutation-request.test.ts deleted file mode 100644 index fcd506c9967..00000000000 --- a/src/cli/handlers/orchestration/mutation-request.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import type { RuntimeClient } from '../../runtime-client' -import { RuntimeClientError } from '../../runtime-client' -import { callOrchestrationMutation } from './mutation-request' - -const RETRY_MS = 120_000 -const WORKER_DONE = { - from: 'term_worker', - subject: 'done', - type: 'worker_done', - payload: '{"taskId":"task_1","dispatchId":"ctx_1","outcome":"succeeded"}' -} - -afterEach(async () => { - vi.useRealTimers() -}) - -type CallOptions = { orchestrationRequestId?: string } - -function fakeClient(respond: (attempt: number, options?: CallOptions) => unknown): { - client: RuntimeClient - requestIds: (string | undefined)[] -} { - const requestIds: (string | undefined)[] = [] - const call = vi.fn(async (_method: string, _params: unknown, options?: CallOptions) => { - requestIds.push(options?.orchestrationRequestId) - return respond(requestIds.length, options) - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: callOrchestrationMutation only uses client.call. - return { client: { call } as unknown as RuntimeClient, requestIds } -} - -function unavailable(options?: CallOptions): RuntimeClientError { - return new RuntimeClientError( - 'runtime_unavailable', - 'Could not connect to the running Orca app.', - { - orchestrationRequestId: options?.orchestrationRequestId, - originalCommand: ['orca', 'orchestration', 'send', '--type', 'worker_done'] - } - ) -} - -describe('callOrchestrationMutation runtime_unavailable retry', () => { - it('keeps the recovery command when the last attempt fails before its request id is attached', async () => { - vi.useFakeTimers() - const { client, requestIds } = fakeClient((attempt, options) => { - throw attempt === 1 - ? unavailable(options) - : new RuntimeClientError('runtime_unavailable', 'No runtime metadata.') - }) - const settled = callOrchestrationMutation( - client, - new Map(), - 'orchestration.send', - WORKER_DONE, - undefined, - RETRY_MS - ).catch((error: unknown) => error) - await vi.advanceTimersByTimeAsync(RETRY_MS + 30_000) - expect(await settled).toMatchObject({ - data: { recovery: { orchestrationRequestId: requestIds[0] } } - }) - }) - - // Windows cannot use this temporary Unix socket path. - - // Windows cannot use this temporary Unix socket path. -}) diff --git a/src/cli/handlers/orchestration/worker-output.test.ts b/src/cli/handlers/orchestration/worker-output.test.ts deleted file mode 100644 index e0620d4c3f0..00000000000 --- a/src/cli/handlers/orchestration/worker-output.test.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { OrchestrationFleetWorker } from '../../../shared/orchestration/fleet/orchestration-fleet-projection' - -import type { - NativeChatBlock, - NativeChatMessage, - NativeChatSubagentEntry -} from '../../../shared/native-chat/native-chat-types' -import type { OrchestrationWorkerReadResult } from '../../../shared/orchestration/workers/orchestration-worker-output' -import { formatWorkerRead, formatWorkerRelease, formatWorkerStart } from './worker-output' - -function fleetProjection(verdict: 'live' | 'unverifiable' | 'exited'): OrchestrationFleetWorker { - return { - id: 'dispatch_1', - dispatchId: 'dispatch_1', - taskId: 'task_1', - runId: 'run_1', - role: 'worker', - parent: null, - provider: { id: 'codex', model: null }, - host: { kind: 'local', id: 'local' }, - workspace: { id: 'ws_1', kind: 'folder_or_worktree' }, - stage: { worker: 'ready', dispatch: 'dispatched', detail: null, activity: 'working' }, - outcome: 'in_progress', - liveness: - verdict === 'live' - ? { verdict, observedAt: 1, source: 'agent_status' } - : verdict === 'exited' - ? { verdict, source: 'execution_host' } - : { verdict, reason: 'missing_status' }, - evidence: { durable: true, liveStatus: 'fresh', lastObservedAt: 1 }, - resource: { - state: 'owned', - id: 'wtr_1', - ownerDispatchId: 'dispatch_1', - releaseState: 'active', - terminalState: null - }, - nextAction: { kind: 'inspect', argv: [] }, - attention: { categories: [], requiresAction: false } - } -} - -describe('worker-start plain formatting', () => { - it('renders partial effects, residual resources, and exact recovery commands for unknown starts', () => { - const nextCommands = [ - 'orca orchestration worker-show --dispatch ctx_unknown --json', - 'orca orchestration worker-abandon --dispatch ctx_unknown --json' - ] - - expect( - formatWorkerStart({ - taskId: 'task_1', - dispatchId: 'ctx_unknown', - state: 'outcome_unknown', - failedStage: 'dispatch_input', - lastError: 'submission could not be observed', - effects: [{ kind: 'terminal', id: 'term_worker' }], - residualResources: [{ kind: 'terminal', id: 'term_worker' }], - nextCommands - }) - ).toBe( - 'Worker ctx_unknown [outcome_unknown] for task_1\n' + - 'dispatch_input: submission could not be observed\n' + - 'Effects: [{"kind":"terminal","id":"term_worker"}]\n' + - 'Residual resources: [{"kind":"terminal","id":"term_worker"}]\n' + - `Next command: ${nextCommands[0]}\n` + - `Next command: ${nextCommands[1]}` - ) - }) - - it('renders nonempty effects and residual resources for failed starts', () => { - expect( - formatWorkerStart({ - taskId: 'task_1', - dispatchId: 'ctx_failed', - state: 'failed', - failedStage: 'terminal_create', - lastError: 'terminal creation failed', - effects: [{ kind: 'worktree', id: 'worktree_1' }], - residualResources: [{ kind: 'worktree', id: 'worktree_1' }] - }) - ).toBe( - 'Worker ctx_failed [failed] for task_1\n' + - 'terminal_create: terminal creation failed\n' + - 'Effects: [{"kind":"worktree","id":"worktree_1"}]\n' + - 'Residual resources: [{"kind":"worktree","id":"worktree_1"}]' - ) - }) -}) - -describe('worker-read plain formatting', () => { - it('separates the PTY verdict from the fleet agent verdict', () => { - const output = formatWorkerRead({ - dispatchId: 'dispatch_1', - status: { worker: 'ready', terminal: 'running', liveness: 'live' }, - projection: fleetProjection('unverifiable'), - source: 'terminal', - sourceIdentity: 'private-source-identity', - terminal: { - handle: 'term_worker', - status: 'running', - tail: ['tail'], - truncated: false, - nextCursor: null - }, - cursor: null, - fallbackReason: null, - warnings: [] - }) - - expect(output).toContain('Terminal liveness: live') - expect(output).toContain('Agent liveness: unverifiable') - expect(output).not.toMatch(/^Liveness:/mu) - }) - - it('omits the agent verdict when the host published no projection', () => { - const output = formatWorkerRead({ - dispatchId: 'dispatch_1', - status: { worker: 'ready', terminal: 'running', liveness: 'live' }, - source: 'terminal', - sourceIdentity: 'private-source-identity', - terminal: { - handle: 'term_worker', - status: 'running', - tail: ['tail'], - truncated: false, - nextCursor: null - }, - cursor: null, - fallbackReason: null, - warnings: [] - }) - - expect(output).toContain('Terminal liveness: live') - expect(output).not.toContain('Agent liveness:') - }) - - it('distinguishes a released archive read from a live one', () => { - const output = formatWorkerRead({ - dispatchId: 'dispatch_1', - status: { worker: 'succeeded', terminal: 'exited', liveness: 'unverifiable' }, - source: 'terminal', - sourceIdentity: 'private-source-identity', - terminal: { - handle: 'term_worker', - status: 'exited', - tail: ['archived tail'], - truncated: false, - nextCursor: null - }, - cursor: null, - fallbackReason: null, - warnings: [], - archived: true - }) - - expect(output).toContain('Archived: true') - expect(output).toContain('Terminal liveness: unverifiable') - expect(output).toContain('Worker: succeeded') - }) -}) - -function transcriptRead( - blocks: NativeChatBlock[], - role: NativeChatMessage['role'] = 'assistant' -): OrchestrationWorkerReadResult { - const message: NativeChatMessage = { - id: 'm1', - role, - blocks, - timestamp: 1, - source: 'transcript' - } - return { - dispatchId: 'd1', - source: 'transcript', - sourceIdentity: 'pane:1', - provider: 'codex', - transcript: { messages: [message], nextCursor: '1', limited: false, returnedMessageCount: 1 }, - cursor: '1', - status: { worker: 'running', terminal: 'running' }, - fallbackReason: null, - warnings: [] - } -} - -describe('formatWorkerRead', () => { - // Replayed journal rows cannot prove current child liveness. - - // Producers emit a text twin for clients that cannot render roster blocks; print only one copy. - - // Unknown roster states can change recomputed text; preserve the producer's twin without duplicating it. - it('prints the roster once when the twin names a state this build cannot reproduce', () => { - const frozenTwin = 'Ran 2 subagents (1 cancelled)' - const output = formatWorkerRead( - transcriptRead( - [ - { type: 'text', text: frozenTwin }, - { - type: 'subagent-group', - groupId: 'thread:turn-1', - // SAFETY: This fixture models a newer host's unrecognized state at the RPC boundary. - agents: [ - { id: 'child-1', label: 'read', state: 'completed' }, - { id: 'child-2', label: 'edit', state: 'cancelled' } - ] as unknown as NativeChatSubagentEntry[] - } - ], - 'system' - ) - ) - - expect(output).toContain(`[system] ${frozenTwin}`) - expect(output).not.toContain('[subagents]') - expect(output).not.toContain('unverifiable') - }) - - // RPC results are not schema-validated here, so newer hosts' unknown block types reach the formatter. - it('degrades an unknown block type from a newer host instead of throwing', () => { - const output = formatWorkerRead( - transcriptRead([ - { type: 'text', text: 'before' }, - // SAFETY: This fixture models a newer host's unrecognized block at the RPC boundary. - { type: 'plan-step', title: 'ship it' } as unknown as NativeChatBlock, - { type: 'text', text: 'after' } - ]) - ) - - expect(output).toContain('[assistant] before\n[unsupported block]\nafter') - }) -}) - -describe('worker output compatibility and release receipts', () => { - it('renders transcript blocks and survives unserializable tool input', () => { - const circular: { self?: unknown } = {} - circular.self = circular - - expect( - formatWorkerRead({ - dispatchId: 'dispatch_1', - source: 'transcript', - sourceIdentity: 'pane:1', - provider: 'codex', - status: { worker: 'ready', terminal: 'running' }, - transcript: { - messages: [ - { - id: 'message_1', - role: 'assistant', - blocks: [ - { type: 'text', text: 'working' }, - { type: 'tool-call', name: 'inspect', input: circular }, - { type: 'tool-result', output: 'failed', isError: true }, - { type: 'image-ref', url: 'https://example.test/proof.png' } - ], - timestamp: null, - source: 'transcript' - } - ], - nextCursor: 'owr1_next', - limited: false, - returnedMessageCount: 1 - }, - cursor: 'owr1_next', - fallbackReason: null, - warnings: [] - }) - ).toBe( - 'Source: transcript (provider=codex)\n' + - 'Worker: ready\n' + - 'Archived: false\n' + - 'Continuation cursor (opaque; pass unchanged to --cursor): owr1_next\n\n' + - '[assistant] working\n[tool inspect] [unserializable input]\n[tool result error] failed\n[image] https://example.test/proof.png' - ) - }) - - it('renders release evidence in receipt order', () => { - expect( - formatWorkerRelease({ - dispatchId: 'dispatch_1', - state: 'release_unknown', - reason: 'host_unreachable', - processAction: 'unverifiable', - archive: { source: 'transcript', status: 'saved' }, - lastError: 'transport closed', - recovery: 'Reconnect and retry.' - }) - ).toBe( - 'Worker dispatch_1 terminal [release_unknown] reason=host_unreachable process=unverifiable\n' + - 'archive transcript [saved]\ntransport closed\nReconnect and retry.' - ) - }) -}) diff --git a/src/cli/handlers/search.test.ts b/src/cli/handlers/search.test.ts index f3eda6cb320..ce57dac72e3 100644 --- a/src/cli/handlers/search.test.ts +++ b/src/cli/handlers/search.test.ts @@ -1,11 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { SEARCH_HANDLERS } from './search' -import { AiVaultSearchResponseSchema } from '../../shared/ai-vault/search/ai-vault-search-contract' import type { AiVaultSearchResponse, AiVaultSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-types' -import { RuntimeClientError } from '../runtime/types' import { RuntimeClient } from '../runtime-client' import { okFixture } from '../test-fixtures' @@ -90,22 +88,6 @@ async function runSearch( return { call, output: lines.join('\n') } } -function printedEnvelope(output: string): { keys: string[]; result: unknown } { - const parsed: unknown = JSON.parse(output) - if (typeof parsed !== 'object' || parsed === null || !('result' in parsed)) { - throw new Error(`Not an RPC envelope: ${output}`) - } - return { keys: Object.keys(parsed), result: parsed.result } -} - -function printedResults(output: string): Extract { - const parsed = AiVaultSearchResponseSchema.parse(printedEnvelope(output).result) - if (parsed.kind !== 'results') { - throw new Error(`Expected results, got ${parsed.kind}`) - } - return parsed -} - describe('orca search over the runtime RPC', () => { it('raises a malformed cursor through the CLI error channel', async () => { await expect( @@ -121,80 +103,4 @@ describe('orca search over the runtime RPC', () => { message: expect.stringContaining('re-run the search without --cursor') }) }) - - it('answers a host with no such method as unavailable rather than a raw error', async () => { - const { output } = await runSearch([['query', 'q']], { - error: new RuntimeClientError('method_not_found', 'Unknown method aiVault.searchSessions') - }) - - expect(output).toContain('This host runs no session search service.') - }) - - it('answers an old host asked for status with the absent-service sentinel', async () => { - const { output } = await runSearch([['index-status', true]], { - error: new RuntimeClientError('method_not_found', 'Unknown method aiVault.searchStatus') - }) - - expect(output).toContain('enabled: false') - expect(output).toContain('phase: idle') - }) - - it('propagates a transport failure instead of calling it unavailable', async () => { - await expect( - runSearch([['query', 'q']], { - error: new RuntimeClientError('runtime_unavailable', 'Orca is not running.') - }) - ).rejects.toThrow('Orca is not running.') - }) - - it('applies the paired-client exposure policy for a remote runtime', async () => { - const { output } = await runSearch([['query', 'q']], { isRemote: true, json: true }) - - expect(printedResults(output).hits[0]).not.toHaveProperty('resumeCommand') - expect(printedResults(output).hits[0]?.source).toEqual({ presence: 'present' }) - }) - - it('keeps the local resume command and source path for a same-machine host', async () => { - const { output } = await runSearch([['query', 'q']], { json: true }) - - expect(printedResults(output).hits[0]?.resumeCommand).toBe('claude --resume session-1') - expect(printedResults(output).hits[0]?.source).toEqual({ - presence: 'present', - filePath: '/transcripts/session-1.jsonl' - }) - }) -}) - -describe('orca search --json', () => { - it('drops the debug block the caller did not ask for', async () => { - const withDebug = { - ...resultsResponse, - debug: { - route: 'phrase' as const, - plannerReport: { route: 'phrase' as const, scope: 'all' as const } - } - } - const { output } = await runSearch([['query', 'q']], { json: true, result: withDebug }) - - expect(printedEnvelope(output).result).not.toHaveProperty('debug') - }) - - it('keeps the debug block the caller asked for', async () => { - const withDebug = { - ...resultsResponse, - debug: { - route: 'phrase' as const, - plannerReport: { route: 'phrase' as const, scope: 'all' as const } - } - } - const { output } = await runSearch( - [ - ['query', 'q'], - ['debug', true] - ], - { json: true, result: withDebug } - ) - - expect(printedResults(output).debug).toEqual(withDebug.debug) - }) }) diff --git a/src/cli/handlers/serve-service.test.ts b/src/cli/handlers/serve-service.test.ts index 6d14705f00d..99842033810 100644 --- a/src/cli/handlers/serve-service.test.ts +++ b/src/cli/handlers/serve-service.test.ts @@ -72,18 +72,6 @@ describe('orca serve service', () => { await expect(installServeService({ command: null, dryRun: false }, d)).rejects.toThrow(/denied/) }) - it('validates and normalizes --bind before installing a service', async () => { - const d = deps('darwin') - await expect( - installServeService({ command: null, bind: 'server.example', dryRun: true }, d) - ).rejects.toThrow(/--bind expects a literal IP address/) - expect(calls).toEqual([]) - - const dry = await installServeService({ command: null, bind: 'localhost', dryRun: true }, d) - expect(String(dry.content)).toContain('--bind') - expect(String(dry.content)).toContain('127.0.0.1') - }) - it('reports live, exited and unverifiable from the manager', async () => { const d = deps('darwin') const dry = await installServeService({ command: null, dryRun: true }, d) @@ -145,44 +133,6 @@ describe('orca serve service', () => { ).toThrow(/PATH/) }) - it('refuses Windows and a relative --command', async () => { - await expect( - installServeService({ command: null, dryRun: true }, deps('win32')) - ).rejects.toThrow(/Windows/) - expect(() => resolveServiceCommand('orca', { platform: 'darwin', env: {} })).toThrow() - expect(() => - resolveServiceCommand(null, { platform: 'darwin', env: { PATH: '/nonexistent' } }) - ).toThrow(/PATH/) - }) - it('names the command to run when only a server-only orca exists here', async () => { - // SSH server launchers run on plain Node, without an installed Electron desktop. - const serverCli = (platform: NodeJS.Platform, path: string): ServeServiceDeps => { - const base = deps(platform) - const { ELECTRON_RUN_AS_NODE: _electron, ...env } = base.env - return { ...base, env: { ...env, PATH: path } } - } - const scoped = join(home, 'profile', 'cli', 'bin') - await mkdir(scoped, { recursive: true }) - await writeFile(join(scoped, 'orca'), '#!/bin/sh\n') - await chmod(join(scoped, 'orca'), 0o755) - await expect( - installServeService({ command: null, dryRun: false }, serverCli('linux', scoped)) - ).rejects.toThrow(/install the Orca app.*`orca-ide serve service install`/i) - await expect( - installServeService({ command: null, dryRun: true }, serverCli('darwin', scoped)) - ).rejects.toThrow(/`orca serve service install`/) - expect(calls).toEqual([]) - await expect( - installServeService({ command: null, dryRun: true }, serverCli('linux', `${scoped}:${bin}`)) - ).resolves.toMatchObject({ dryRun: true }) - await expect( - installServeService( - { command: join(bin, 'orca-ide'), dryRun: true }, - serverCli('linux', scoped) - ) - ).resolves.toMatchObject({ dryRun: true }) - }) - it('keeps an AppImage launch and profile directories out of the unit PATH (#36000)', async () => { const profileBin = join(home, 'profile', 'cli', 'bin') const d = deps('linux') diff --git a/src/cli/index-automation-setup.test.ts b/src/cli/index-automation-setup.test.ts deleted file mode 100644 index b3ad486b716..00000000000 --- a/src/cli/index-automation-setup.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { okFixture, queueFixtures } from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' -import { AUTOMATION_SETUP_CHOICE_RUNTIME_CAPABILITY } from '../shared/automations/automation-runtime-capabilities' - -const supported = okFixture('status', { - capabilities: [AUTOMATION_SETUP_CHOICE_RUNTIME_CAPABILITY] -}) - -describe('automation setup CLI contract', () => { - const originalExitCode = process.exitCode - afterEach(() => { - process.exitCode = originalExitCode - }) - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - const createArgs = [ - 'automations', - 'create', - '--name', - 'Daily checks', - '--trigger', - 'daily', - '--prompt', - 'Check changes', - '--provider', - 'codex', - '--repo', - 'id:repo-1', - '--json' - ] - - it.each(['inherit', '', 'true'])( - 'rejects unsupported --setup=%s before a mutation', - async (setup) => { - const output = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main([...createArgs, `--setup=${setup}`], '/tmp/repo') - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalled() - expect(JSON.parse(String(output.mock.calls.at(-1)?.[0])).error.message).toContain('--setup') - } - ) - - it('accepts setup while switching an existing automation to new-per-run', async () => { - queueFixtures( - callMock, - supported, - okFixture('current', { automation: { id: 'a1', workspaceMode: 'existing' } }), - okFixture('updated', { automation: { id: 'a1', setupDecision: 'run' } }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - await main( - ['automations', 'edit', 'a1', '--workspace-mode', 'new-per-run', '--setup', 'run', '--json'], - '/tmp/repo' - ) - expect(callMock).toHaveBeenLastCalledWith( - 'automation.update', - expect.objectContaining({ - updates: expect.objectContaining({ workspaceMode: 'new_per_run', setupDecision: 'run' }) - }) - ) - // An explicit switch is the user's own choice, so it carries no stored-mode precondition. - expect(callMock.mock.calls.at(-1)?.[1]).not.toHaveProperty('expectedWorkspaceMode') - }) -}) diff --git a/src/cli/index-host-rm.test.ts b/src/cli/index-host-rm.test.ts deleted file mode 100644 index 999610ff874..00000000000 --- a/src/cli/index-host-rm.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - listEnvironments: listEnvironmentsMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { okFixture } from './test-fixtures' -import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' - -const KEPT = { id: 'ssh-1783599077486-fyasux', label: 'trader-local' } -const STALE = { id: 'ssh-1783600000000-abcdef', label: 'ticket-vm-42' } - -/** Serve the target list and record removals, as the runtime's ssh RPC methods do. */ -function fakeSshRuntime(): { removed: string[] } { - const removed: string[] = [] - callMock.mockImplementation(async (method: string, params?: { targetId: string }) => { - if (method === 'ssh.listTargetSummaries') { - return okFixture('req_ssh_targets', { targets: [KEPT, STALE] }) - } - if (method === 'ssh.removeTarget' && params) { - removed.push(params.targetId) - return okFixture('req_ssh_remove', { removed: true }) - } - throw new Error(`unexpected call ${method}`) - }) - return { removed } -} - -function printedJson(logSpy: { mock: { calls: unknown[][] } }): { - ok: boolean - result?: unknown - error?: { code: string; message: string } -} { - return JSON.parse(String(logSpy.mock.calls[0]?.[0])) -} - -describe('orca host rm', () => { - const priorExitCode = process.exitCode - afterEach(() => { - process.exitCode = priorExitCode - }) - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('removes only the named SSH target through ssh.removeTarget and prints it', async () => { - const runtime = fakeSshRuntime() - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['host', 'rm', '--host', `ssh:${STALE.id}`, '--json'], '/tmp/repo') - - expect(runtime.removed).toEqual([STALE.id]) - expect(printedJson(logSpy)).toMatchObject({ - ok: true, - result: { removed: { kind: 'ssh', name: STALE.label, id: STALE.id } }, - _meta: { runtimeId: 'runtime-1' } - }) - }) - - it.each([ - ['local', 'This machine is always listed'], - ['this machine', 'This machine is always listed'], - ['runtime:env-m4air', 'orca environment rm'], - ['m4air', '--host ssh:'] - ])('refuses --host %s before it reaches the runtime', async (host, nextStep) => { - pairRuntimeEnvironment(listEnvironmentsMock, 'env-m4air', 'm4air') - const runtime = fakeSshRuntime() - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['host', 'rm', '--host', host, '--json'], '/tmp/repo') - - const printed = printedJson(logSpy) - expect(printed.ok).toBe(false) - expect(printed.error?.code).toBe('invalid_argument') - expect(printed.error?.message).toContain('removes saved SSH targets only') - expect(JSON.stringify(printed)).toContain(nextStep) - expect(runtime.removed).toEqual([]) - expect(callMock).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) - }) - - it.each([ - ['environment', 'm4air'], - ['pairing-code', 'orca://pair?code=x'] - ])('refuses --%s rather than removing the target on another machine', async (flag, value) => { - pairRuntimeEnvironment(listEnvironmentsMock, 'env-m4air', 'm4air') - const runtime = fakeSshRuntime() - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['host', 'rm', '--host', `ssh:${STALE.id}`, `--${flag}`, value, '--json'], - '/tmp/repo' - ) - - const printed = printedJson(logSpy) - expect(printed.error?.code).toBe('invalid_argument') - expect(printed.error?.message).toContain(`\`--${flag}\` does not retarget \`orca host rm\``) - expect(runtime.removed).toEqual([]) - expect(process.exitCode).toBe(1) - }) - - it('refuses an id the runtime does not have, and does not match a label', async () => { - const runtime = fakeSshRuntime() - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['host', 'rm', '--host', `ssh:${STALE.label}`, '--json'], '/tmp/repo') - - const printed = printedJson(logSpy) - expect(printed.error?.code).toBe('invalid_argument') - expect(printed.error?.message).toContain(`Unknown SSH target in --host ssh:${STALE.label}`) - expect(runtime.removed).toEqual([]) - expect(process.exitCode).toBe(1) - }) -}) diff --git a/src/cli/index-omitted-host-scope-selectors.test.ts b/src/cli/index-omitted-host-scope-selectors.test.ts deleted file mode 100644 index f56a2ac1b32..00000000000 --- a/src/cli/index-omitted-host-scope-selectors.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import type * as RuntimeEnvironmentStore from '../shared/remote-runtime/host-store/runtime-environment-store' -import { beforeAll, describe, expect, it, vi } from 'vitest' -import type * as ChildProcess from 'node:child_process' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock( - '../shared/remote-runtime/host-store/runtime-environment-store', - async (importOriginal) => ({ - ...(await importOriginal()), - listEnvironments: listEnvironmentsMock - }) -) - -vi.mock('child_process', async (importOriginal) => { - const actual = await importOriginal() - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return { ...actual, ...createChildProcessModuleMock(spawnMock) } -}) - -import { main } from './index' -import type { - RuntimeAgentLineageTestModule, - RuntimeAgentLineageCatalogTestModule -} from '../shared/runtime-agent-lineage-consumer.test-fixture' -import { COMMAND_SPECS } from './specs/index' -import { okFixture, queueFixtures } from './test-fixtures' -import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' - -let lineage: RuntimeAgentLineageTestModule -let catalog: RuntimeAgentLineageCatalogTestModule - -// The CLI's Node16 program needs a hook; each test still creates its own DB and runtime. -beforeAll(async () => { - lineage = ( - await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( - '../main/runtime/workspaces/process-listing/runtime-agent-lineage.test-fixture' - ) - ).default - catalog = ( - await vi.importActual<{ default: RuntimeAgentLineageCatalogTestModule }>( - '../main/runtime/workspaces/process-listing/runtime-agent-lineage-catalog.test-fixture' - ) - ).default -}) - -const TERMINAL_ROW = { - handle: 'term_1', - ptyId: 'pty-1', - worktreeId: 'repo::/wt', - worktreePath: '/wt', - branch: 'main', - tabId: 'tab-1', - leafId: 'leaf-1', - title: 'worker', - connected: true, - writable: true, - lastOutputAt: null, - preview: '', - executionHostId: 'local' -} - -describe('omittedHostIds selector annotation', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it.each(['repo::/workspace', 'folder:lineage'])( - 'prints canonical production-built lineage through actual CLI and worktree RPC for %s', - async (worktreeId) => { - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = lineage - const f = publicLineageFixture(worktreeId) - try { - const dispatcher = catalog.createLineageCatalogDispatcher(f.build) - const resultOf = (response: unknown) => JSON.parse(JSON.stringify(response)).result - const request = (params = {}) => - dispatcher.dispatch({ - id: 'req_worktree_ps', - authToken: 'test', - method: 'worktree.ps', - params - }) - const legacy = await request() - expect(legacy).toMatchObject({ - ok: true, - result: { - worktrees: [ - { - agents: [ - { parentPaneKey: null }, - { - parentPaneKey: canonicalChatRow(LINEAGE_PARENT), - taskTitle: 'Build the worker result' - } - ] - } - ] - } - }) - callMock.mockResolvedValueOnce(legacy) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main(['worktree', 'ps', '--json'], '/workspace') - const printed = JSON.parse(String(log.mock.calls[0]?.[0])) - expect(printed.result.worktrees[0].agents[1].paneKey).toBe(canonicalChatRow(LINEAGE_CHILD)) - expect(JSON.stringify(printed)).not.toContain(f.privateHandle) - expect(JSON.stringify(printed)).not.toContain(f.privatePane) - const first = resultOf(await request({ afterSnapshotId: null })) - expect(resultOf(await request({ afterSnapshotId: first.snapshotId }))).toMatchObject({ - unchanged: true - }) - f.db.db - .prepare( - 'UPDATE runs SET coordinator_orca_session_id = NULL, coordinator_orca_session_id_generation = NULL WHERE id = ?' - ) - .run(f.run.id) - expect(resultOf(await request({ afterSnapshotId: first.snapshotId })).snapshotId).not.toBe( - first.snapshotId - ) - log.mockRestore() - } finally { - f.db.close() - } - } - ) - - it('marks a stale runtime host that no caller can select', async () => { - pairRuntimeEnvironment(listEnvironmentsMock, 'env-paired', 'm4air') - queueFixtures( - callMock, - okFixture('req_terminal_list', { - terminals: [TERMINAL_ROW], - totalCount: 1, - truncated: false, - hostScope: { - hostIds: ['local'], - omittedHostIds: ['runtime:env-paired', 'runtime:env-retired'] - } - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['terminal', 'list', '--json'], '/tmp/repo') - - const printed = JSON.parse(String(logSpy.mock.calls[0]?.[0])) - expect(printed.result.hostScope.omittedHostIds).toEqual([ - 'runtime:env-paired', - 'runtime:env-retired' - ]) - expect(printed.result.hostScope.omittedHostSelectors).toEqual([ - { hostId: 'runtime:env-paired', selector: '--environment m4air' }, - { hostId: 'runtime:env-retired', selector: null } - ]) - }) - - it.each([ - ['terminal', 'list', 'req_terminal_list', { terminals: [TERMINAL_ROW] }], - ['worktree', 'list', 'req_worktree_list', { worktrees: [] }], - ['worktree', 'ps', 'req_worktree_ps', { worktrees: [] }] - ] as const)( - 'only suggests flags that `%s %s` accepts', - async (group, action, requestId, rows) => { - pairRuntimeEnvironment(listEnvironmentsMock, 'env-paired', 'm4air') - queueFixtures( - callMock, - okFixture(requestId, { - ...rows, - totalCount: 1, - truncated: false, - hostScope: { - hostIds: [], - omittedHostIds: ['local', 'runtime:env-paired', 'ssh:box-1'] - } - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main([group, action, '--json'], '/tmp/repo') - - const printed = JSON.parse(String(logSpy.mock.calls[0]?.[0])) - expect(printed.result.hostScope.omittedHostSelectors).toEqual([ - { hostId: 'local', selector: null }, - { hostId: 'runtime:env-paired', selector: '--environment m4air' }, - { hostId: 'ssh:box-1', selector: null } - ]) - const spec = COMMAND_SPECS.find( - (candidate) => candidate.path.join(' ') === `${group} ${action}` - ) - for (const { selector } of printed.result.hostScope.omittedHostSelectors) { - if (selector) { - expect(spec?.allowedFlags).toContain(selector.split(' ')[0].replace(/^--/, '')) - } - } - // SSH hosts are reached through the answering runtime, without another target lookup. - expect(callMock).toHaveBeenCalledTimes(1) - } - ) -}) - -describe('worktree listings report their host coverage', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('does not claim a scope for `worktree ps` when the host reported none', async () => { - queueFixtures( - callMock, - okFixture('req_worktree_ps', { worktrees: [], totalCount: 0, truncated: false }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['worktree', 'ps'], '/tmp/repo') - - const printed = String(logSpy.mock.calls[0]?.[0]) - expect(printed).toContain('scope: unverifiable') - }) -}) diff --git a/src/cli/index-orchestration.test.ts b/src/cli/index-orchestration.test.ts index 6fa1e6845e6..b7bf7989851 100644 --- a/src/cli/index-orchestration.test.ts +++ b/src/cli/index-orchestration.test.ts @@ -64,52 +64,6 @@ describe('orca cli worktree awareness', () => { spawnMock }) - it.each([ - { questionFlag: '--question', questionValue: 'Proceed?', json: true }, - { questionFlag: '--resume', questionValue: 'msg_pending', json: false } - ])('reports oversized ask waits before any request: %o', async (testCase) => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - id: 'req_ask', - ok: true, - result: { answer: 'yes', messageId: 'msg_1', threadId: 'msg_1', timedOut: false }, - _meta: { runtimeId: 'runtime-1' } - }) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main( - [ - 'orchestration', - 'ask', - testCase.questionFlag, - testCase.questionValue, - '--timeout-ms', - '14400000', - ...(testCase.json ? ['--json'] : []) - ], - '/tmp/repo' - ) - - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalled() - if (testCase.json) { - expect(logSpy).toHaveBeenCalledTimes(1) - expect(JSON.parse(logSpy.mock.calls[0][0])).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: expect.stringMatching(/--timeout-ms.*1800000.*30 minutes/) - } - }) - } else { - expect(logSpy).not.toHaveBeenCalled() - } - expect(errorSpy).toHaveBeenCalledWith( - expect.stringMatching(/^error: invalid_argument: --timeout-ms.*1800000.*30 minutes/) - ) - }) - it("refuses an agent session's caller flag naming another caller before any request", async () => { vi.stubEnv('ORCA_AGENT_SESSION_ID', 'f7a1c0de-1111-4222-8333-444455556666') const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -122,53 +76,4 @@ describe('orca cli worktree awareness', () => { error: { code: 'consumer_fenced' } }) }) - - it('rejects no-flag orchestration reset before calling the runtime', async () => { - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(['orchestration', 'reset'], '/tmp/repo') - - expect(errorSpy).toHaveBeenCalledExactlyOnceWith( - 'error: invalid_argument: Choose exactly one reset scope: --all, --tasks, or --messages.' - ) - expect(callMock).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) - }) - - it.each([ - ['orchestration', 'reset', '--tasks', '--messages'], - ['orchestration', 'reset', '--all', '--tasks'] - ])('rejects conflicting reset scopes for $args', async (...args) => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main([...args, '--json'], '/tmp/repo') - - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: 'Choose exactly one reset scope: --all, --tasks, or --messages.' - } - }) - expect(callMock).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) - }) - - it('rejects unknown task-update status with an enum-aware error', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_coord' - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await main( - ['orchestration', 'task-update', '--id', 'task_x', '--status', 'complete'], - '/tmp/repo' - ) - - const output = [...errSpy.mock.calls, ...logSpy.mock.calls] - .flat() - .map((v) => (typeof v === 'string' ? v : JSON.stringify(v))) - .join('\n') - expect(output).toContain("invalid status 'complete'") - expect(output).toContain('pending, ready, dispatched, completed, failed, blocked') - expect(callMock).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) - }) }) diff --git a/src/cli/index-terminal-commands.test.ts b/src/cli/index-terminal-commands.test.ts index 8de7a36b59a..6654ab50182 100644 --- a/src/cli/index-terminal-commands.test.ts +++ b/src/cli/index-terminal-commands.test.ts @@ -1,4 +1,3 @@ -import { RuntimeRpcFailureError, type RuntimeRpcFailure } from './runtime/types' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -45,14 +44,6 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - queueNoFolderAtSelector, - worktreeListFixture -} from './test-fixtures' import { useWorktreeAwarenessEnvironment } from './index-test-harness' describe('orca cli worktree awareness', () => { @@ -74,254 +65,6 @@ describe('orca cli worktree awareness', () => { process.exitCode = originalExitCode }) - it.each([ - [ - 'passes explicit focus through terminal.create', - { - title: 'RUNNER', - command: undefined, - flags: ['--focus'], - expected: { focus: true, presentation: 'focused' } - } - ], - [ - 'keeps interactive Codex startup commands backgrounded unless focus is explicit', - { - title: 'Codex', - command: 'codex', - flags: [], - expected: { focus: false, rendererBacked: true, activate: false } - } - ], - [ - 'keeps explicit focus semantics when forcing Codex through the renderer path', - { - title: 'Codex', - command: 'codex', - flags: ['--focus'], - expected: { focus: true, presentation: 'focused', rendererBacked: true, activate: true } - } - ], - [ - 'does not force the visible terminal path for explicit Codex exec commands', - { - title: 'Codex exec', - command: 'codex exec summarize', - flags: [], - expected: { focus: false } - } - ], - [ - 'does not force the visible terminal path for Codex exec commands after global options', - { - title: 'Codex exec', - command: 'codex -m gpt-5 --sandbox workspace-write exec summarize', - flags: [], - expected: { focus: false } - } - ], - [ - 'does not force the visible terminal path for Codex review commands after long options', - { - title: 'Codex review', - command: 'codex --model=gpt-5 --sandbox=workspace-write review', - flags: [], - expected: { focus: false } - } - ], - [ - 'does not force the visible terminal path for Codex help commands', - { - title: 'Codex help', - command: 'codex --help', - flags: [], - expected: { focus: false } - } - ], - [ - 'keeps Codex prompts after global options backgrounded unless focus is explicit', - { - title: 'Codex prompt', - command: 'codex -m gpt-5 "fix the flaky test"', - flags: [], - expected: { focus: false, rendererBacked: true, activate: false } - } - ], - [ - 'keeps interactive Claude startup commands backgrounded unless focus is explicit', - { - title: 'Claude', - command: 'claude', - flags: [], - expected: { focus: false, rendererBacked: true, activate: false } - } - ], - [ - 'keeps Claude print commands on the background terminal path', - { - title: 'Claude print', - command: 'claude -p "summarize"', - flags: [], - expected: { focus: false } - } - ] - ] as const)('%s', async (_name, { title, command, flags, expected }) => { - queueNoFolderAtSelector(callMock) - queueFixtures( - callMock, - okFixture('req_terminal_create', { - terminal: { - handle: 'term_1', - worktreeId: 'repo-1::/tmp/repo/feature', - title - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'terminal', - 'create', - '--worktree', - 'path:/tmp/repo/feature', - '--title', - title, - ...(command === undefined ? [] : ['--command', command]), - ...flags, - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenLastCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command, - title, - ...expected - }) - expect(process.exitCode).toBeUndefined() - }) - - it('uses the resolved enclosing worktree for terminal consumers', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_term', { terminals: [], totalCount: 0, truncated: false }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['terminal', 'list', '--worktree', 'active', '--json'], '/tmp/repo/feature/src') - - expect(callMock).toHaveBeenNthCalledWith(3, 'terminal.list', { - worktree: 'id:repo::/tmp/repo/feature', - limit: undefined, - includeVisualLayouts: false - }) - }) - - it('requests visual layouts only for the human-readable terminal list', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_term', { terminals: [], totalCount: 0, truncated: false }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['terminal', 'list', '--worktree', 'active'], '/tmp/repo/feature/src') - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'terminal.list', - expect.objectContaining({ includeVisualLayouts: true }) - ) - }) - - it('allows agent JSON clients to request visual layouts explicitly', async () => { - const visualLayouts = [ - { - worktreeId: 'repo::/tmp/repo/feature', - worktreePath: '/tmp/repo/feature', - root: { type: 'group', groupId: null, activeTabId: null, tabs: [] } - } - ] - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), - noFolderWorkspacesFixture(), - okFixture('req_term', { - terminals: [], - visualLayouts, - totalCount: 0, - truncated: false - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['terminal', 'list', '--worktree', 'active', '--include-visual-layouts', '--json'], - '/tmp/repo/feature/src' - ) - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'terminal.list', - expect.objectContaining({ includeVisualLayouts: true }) - ) - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({ - result: { visualLayouts } - }) - }) - - it.each( - [[], ['--pairing-code', 'remote-runtime']].flatMap((remote) => - [false, true].map((json) => ({ remote, json })) - ) - )( - 'prints the host failure through terminal create ($remote, json=$json)', - async ({ remote, json }) => { - const failure = { - id: 'start', - ok: false, - error: { - code: 'agent_session_exited_during_start', - message: - 'Git Bash reported its limit of 128 open terminals on this PC while starting the terminal. Close some Git Bash terminals and try again.' - }, - _meta: { runtimeId: 'host' } - } satisfies RuntimeRpcFailure - queueNoFolderAtSelector(callMock) - callMock.mockRejectedValueOnce(new RuntimeRpcFailureError(failure)) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const stderr = vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'terminal', - 'create', - '--worktree', - 'path:/tmp/host/workspace', - ...remote, - ...(json ? ['--json'] : []) - ], - '/tmp/client' - ) - expect(callMock).toHaveBeenCalledWith( - 'terminal.create', - expect.objectContaining({ worktree: 'path:/tmp/host/workspace' }) - ) - if (json) { - expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual(failure) - expect(stderr).not.toHaveBeenCalled() - } else { - expect(stderr).toHaveBeenCalledExactlyOnceWith(failure.error.message) - expect(log).not.toHaveBeenCalled() - } - expect(process.exitCode).toBe(1) - } - ) - it('rejects implicit remote terminal create instead of resolving from client cwd', async () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -358,40 +101,6 @@ describe('orca cli worktree awareness', () => { expect(process.exitCode).toBe(1) }) - it('sends explicit remote terminal create worktree selectors unchanged', async () => { - queueFixtures( - callMock, - okFixture('req_terminal_create', { - terminal: { - handle: 'term_1', - worktreeId: 'repo-1::/srv/orca/feature', - title: 'Server terminal' - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'terminal', - 'create', - '--worktree', - 'id:repo-1::/srv/orca/feature', - '--pairing-code', - 'remote-runtime', - '--json' - ], - '/tmp/client/repo/src' - ) - - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'id:repo-1::/srv/orca/feature', - command: undefined, - title: undefined, - focus: false - }) - }) - it('exits nonzero when terminal wait returns an unsatisfied blocked result', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_worker' callMock.mockResolvedValueOnce({ @@ -429,42 +138,4 @@ describe('orca cli worktree awareness', () => { expect(logSpy.mock.calls.flat().join('\n')).toContain('blockedReason: codex-cwd-prompt') expect(process.exitCode).toBe(1) }) - - it('does not force remote Codex terminal creates through a local renderer path', async () => { - queueFixtures( - callMock, - okFixture('req_terminal_create', { - terminal: { - handle: 'term_1', - worktreeId: 'repo-1::/srv/orca/feature', - title: 'Codex' - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'terminal', - 'create', - '--worktree', - 'id:repo-1::/srv/orca/feature', - '--command', - 'codex', - '--title', - 'Codex', - '--pairing-code', - 'remote-runtime', - '--json' - ], - '/tmp/client/repo/src' - ) - - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'id:repo-1::/srv/orca/feature', - command: 'codex', - title: 'Codex', - focus: false - }) - }) }) diff --git a/src/cli/index-workspace-owner-choice.test.ts b/src/cli/index-workspace-owner-choice.test.ts deleted file mode 100644 index c09dc8b9025..00000000000 --- a/src/cli/index-workspace-owner-choice.test.ts +++ /dev/null @@ -1,774 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { buildWorktree, okFixture, worktreeListFixture } from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' -import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures' -import { RuntimeRpcFailureError } from './runtime/types' - -describe('cwd workspace ownership at the real CLI boundary', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - beforeEach(() => { - vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) - vi.stubEnv('ORCA_STRUCTURED_SESSION', undefined) - }) - afterEach(() => vi.unstubAllEnvs()) - const root = buildWorktree('/tmp/owner-choice', 'main', 'abc', 'repo-a') - const sibling = { ...root, id: `${root.id}::workspace:11111111-1111-4111-8111-111111111111` } - const choices = [root, sibling].map(({ id }) => `id:${id}`) - const automation = [ - 'automations', - 'create', - '--name', - 'daily', - '--trigger', - 'daily', - '--prompt', - 'review', - '--provider', - 'codex' - ] - - it.each([false, true])( - 'refuses immediate consumers with exact recovery and no action (json=%s)', - async (json) => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const err = vi.spyOn(console, 'error').mockImplementation(() => {}) - const prior = process.exitCode - const commands = [ - ['worktree', 'current'], - ['worktree', 'show', '--worktree', 'current'], - ['worktree', 'set', '--worktree', 'current', '--comment', 'keep'], - ['worktree', 'set', '--worktree', choices[0]!, '--parent-worktree', 'active'], - ...['active', 'current'].map((parent) => [ - 'worktree', - 'create', - '--repo', - 'id:repo-a', - '--name', - 'child', - '--parent-worktree', - parent - ]), - ['snapshot'], - ['snapshot', '--worktree', 'current'], - ['tab', 'list'], - ['terminal', 'read'], - ['file', 'open', 'README.md'], - ['emulator', 'list'], - automation, - ['computer', 'get-app-state', '--app', 'fixture'], - ['orchestration', 'check', '--peek'], - ['orchestration', 'run-current'], - ['terminal', 'stop', '--worktree', 'current'], - ['terminal', 'close', '--all', '--worktree', 'current'], - [ - 'connector', - 'start', - '--conversation', - 'c', - '--delivery-id', - 'd', - '--agent', - 'codex', - '--prompt', - 'hi', - '--worktree', - 'current' - ] - ] - try { - for (const rows of [ - [root, sibling], - [sibling, root] - ]) { - for (const args of commands) { - callMock.mockReset() - log.mockClear() - err.mockClear() - process.exitCode = prior - callMock.mockResolvedValue(worktreeListFixture(rows)) - await main([...args, ...(json ? ['--json'] : [])], root.path) - // Concise orchestration failures put the one-line error on stderr and the detail on stdout. - const output = (json ? log : err).mock.calls - .concat(json ? [] : log.mock.calls) - .flat() - .join('\n') - expect(process.exitCode, JSON.stringify({ args, output })).toBe(1) - if (json) { - expect(JSON.parse(output).error.code, JSON.stringify(args)).toBe('selector_ambiguous') - expect(JSON.parse(output).error.data.workspaces).toHaveLength(2) - } - for (const choice of choices) { - expect(output).toContain(choice) - } - const advice = json - ? JSON.parse(output).error.data.nextSteps.join(' ') - : output.split('Next step:').slice(1).join(' ') - if (args[0] === 'orchestration') { - const steps = [ - 'This command needs your own caller identity; selecting a target workspace cannot supply it.', - 'Run the command in your own live Orca terminal with ORCA_TERMINAL_HANDLE preserved.' - ] - expect( - json - ? JSON.parse(output).error.data.nextSteps - : output.split('\nNext step: ').slice(1) - ).toEqual(steps) - expect(advice).not.toMatch(/--worktree|--parent-worktree|--from|worktree show/) - expect( - output.match(/More than one Orca workspace matched the current directory/g) - ).toHaveLength(1) - expect(log).toHaveBeenCalledTimes(1) - expect(err.mock.calls).toEqual([ - [ - 'error: selector_ambiguous: More than one Orca workspace matched the current directory. Choose an exact workspace.' - ] - ]) - if (json) { - expect(JSON.parse(output).error.data.workspaces).toEqual( - rows.map((row) => ({ - kind: 'worktree', - id: row.id, - path: row.path, - hostId: 'local', - selector: `id:${row.id}` - })) - ) - } else { - expect(output.match(/Workspace choices \(JSON data\):/g)).toHaveLength(1) - } - } else { - expect(output).toContain('worktree show --worktree') - expect(advice).toContain( - args.includes('--parent-worktree') - ? '--parent-worktree ' - : args === automation - ? '--workspace ' - : args[1] === 'current' - ? 'current has no replacement target flag' - : '--worktree ' - ) - } - if (!args.includes('--parent-worktree')) { - expect(advice).not.toContain('--parent-worktree') - } - expect(output).not.toContain('No Orca workspace matched') - expect(output).not.toContain('orca repo list') - expect( - callMock.mock.calls.map(([method]) => method), - JSON.stringify(args) - ).toEqual(['worktree.list', 'folderWorkspace.list']) - } - } - } finally { - process.exitCode = prior - } - } - ) - - it.each([false, true])( - 'recovers with the own caller before cwd inference (json=%s)', - async (json) => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const err = vi.spyOn(console, 'error').mockImplementation(() => {}) - const prior = process.exitCode - const own = 'term_owner_choice' - const message = { id: 'message-own', from_handle: own, subject: 'own caller ready', read: 0 } - const run = { id: 'run-own', objective: 'own caller run' } - const controls = [ - { - args: ['orchestration', 'check', '--peek'], - env: own, - method: 'orchestration.check', - identity: 'terminal' - }, - { - args: ['orchestration', 'check', '--peek', '--terminal', own], - env: undefined, - method: 'orchestration.check', - identity: 'terminal' - }, - { - args: ['orchestration', 'run-current'], - env: own, - method: 'orchestration.runCurrent', - identity: 'from' - }, - { - args: ['orchestration', 'run-current', '--from', own], - env: undefined, - method: 'orchestration.runCurrent', - identity: 'from' - } - ] - try { - for (const rows of [ - [root, sibling], - [sibling, root] - ]) { - for (const { args, env, method: action, identity } of controls) { - vi.stubEnv('ORCA_TERMINAL_HANDLE', env) - callMock.mockReset() - log.mockClear() - err.mockClear() - process.exitCode = prior - callMock.mockImplementation(async (method) => { - if (method === 'worktree.list') { - return worktreeListFixture(rows) - } - if (method === 'terminal.resolveIdentity') { - return okFixture('identity', { identity: { handle: own, live: true } }) - } - return action === 'orchestration.check' - ? okFixture('check', { messages: [message], count: 1 }) - : okFixture('run', { run }) - }) - await main([...args, ...(json ? ['--json'] : [])], root.path) - const output = log.mock.calls.flat().join('\n') - expect(process.exitCode, JSON.stringify({ args, output })).toBe(prior) - expect(err).not.toHaveBeenCalled() - expect(callMock.mock.calls.map(([method]) => method)).toEqual( - env && identity === 'from' ? ['terminal.resolveIdentity', action] : [action] - ) - if (env && identity === 'from') { - expect(callMock).toHaveBeenCalledWith('terminal.resolveIdentity', { terminal: own }) - } - expect(callMock).toHaveBeenCalledWith( - action, - expect.objectContaining({ [identity]: own }) - ) - if (json) { - const response = JSON.parse(output) - expect(response.ok).toBe(true) - if (identity === 'terminal') { - expect(response.result.messages).toMatchObject([ - { id: message.id, from: own, subject: message.subject } - ]) - } else { - expect(response.result).toMatchObject({ runId: run.id, objective: run.objective }) - } - } else { - expect(output).toContain( - identity === 'terminal' ? message.subject : `runId=${run.id}` - ) - } - expect(callMock).not.toHaveBeenCalledWith('worktree.list', expect.anything()) - expect(callMock).not.toHaveBeenCalledWith('terminal.resolveActive', expect.anything()) - } - } - } finally { - process.exitCode = prior - } - } - ) - - it('preserves duplicate/unique/caller/nested elections and exact bypasses through printed output', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const prior = process.exitCode - const nested = buildWorktree(`${root.path}/nested`, 'child', 'abc', root.repoId) - try { - for (const { rows, owner, caller } of [ - { rows: [root], owner: root }, - { rows: [root, { ...root }], owner: root }, - { rows: [root, sibling], owner: sibling, caller: sibling.id }, - { rows: [sibling, root], owner: sibling, caller: sibling.id }, - { rows: [root, nested], owner: nested, caller: root.id } - ]) { - if (caller) { - process.env.ORCA_WORKTREE_ID = caller - } else { - delete process.env.ORCA_WORKTREE_ID - } - callMock.mockReset() - log.mockClear() - callMock.mockImplementation(async (method) => - method === 'worktree.list' - ? worktreeListFixture(rows) - : okFixture('show', { worktree: owner }) - ) - await main(['worktree', 'current', '--json'], `${owner.path}/src`) - expect(process.exitCode).toBe(prior) - expect(callMock).toHaveBeenCalledWith('worktree.show', { worktree: `id:${owner.id}` }) - expect(JSON.parse(String(log.mock.calls[0]?.[0])).result.worktree.id).toBe(owner.id) - } - delete process.env.ORCA_WORKTREE_ID - for (const args of [ - ['worktree', 'show', '--worktree', choices[0]!], - ['snapshot', '--page', 'page-1'], - ['terminal', 'read', '--terminal', 'term-1'] - ]) { - callMock.mockReset() - log.mockClear() - callMock.mockResolvedValue( - okFixture('explicit', { worktree: root, terminal: { text: 'ready' }, snapshot: 'ready' }) - ) - await main([...args, '--json'], root.path) - expect(process.exitCode).toBe(prior) - expect(callMock).not.toHaveBeenCalledWith('worktree.list', expect.anything()) - expect(log.mock.calls.flat().join('')).toContain('"ok": true') - } - } finally { - process.exitCode = prior - } - }) - - it('reaches exact and unique-current connector/start-stop-close results through main', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const prior = process.exitCode - const cases = [ - { - argv: [ - 'connector', - 'start', - '--conversation', - 'fixture', - '--delivery-id', - 'delivery', - '--agent', - 'codex', - '--prompt', - 'hello' - ], - method: 'connector.start', - result: { initial: { outcome: 'accepted' } }, - text: 'started; prompt accepted' - }, - { - argv: ['terminal', 'stop'], - method: 'terminal.stop', - result: { stopped: 3 }, - text: 'Stopped 3 terminals.' - }, - { - argv: ['terminal', 'close', '--all'], - method: 'terminal.closeAll', - result: { closed: 2, stopped: 3, retiredSurfaces: true }, - text: 'Closed 2 terminal tabs and stopped 3 terminal processes.' - } - ] - try { - for (const entry of cases) { - for (const exact of [true, false]) { - for (const json of [false, true]) { - callMock.mockReset() - log.mockClear() - callMock.mockImplementation(async (method) => - method === 'worktree.list' - ? worktreeListFixture(exact ? [root, sibling] : [root]) - : okFixture(entry.method, entry.result) - ) - await main( - [ - ...entry.argv, - '--worktree', - exact ? choices[0]! : 'current', - ...(json ? ['--json'] : []) - ], - root.path - ) - expect(process.exitCode).toBe(prior) - const downstream = callMock.mock.calls.filter(([method]) => method === entry.method) - expect(downstream).toHaveLength(1) - expect(downstream[0]?.[1]).toMatchObject( - entry.method === 'connector.start' - ? { - target: { kind: 'existing', worktree: choices[0] }, - prompt: 'hello', - agent: 'codex' - } - : { worktree: choices[0] } - ) - expect( - callMock.mock.calls.filter(([method]) => method === 'worktree.list') - ).toHaveLength(exact ? 0 : 1) - const output = log.mock.calls.flat().join('\n') - if (json) { - expect(JSON.parse(output).result).toEqual(entry.result) - } else { - expect(output).toBe(entry.text) - } - } - } - } - } finally { - process.exitCode = prior - } - }) - - it('ignores stale or non-containing caller identities instead of breaking a positive owner tie', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const prior = process.exitCode - const outside = buildWorktree('/tmp/outside-choice', 'main', 'abc', root.repoId) - try { - for (const caller of ['stale', outside.id]) { - for (const rows of [ - [root, sibling, outside], - [outside, sibling, root] - ]) { - process.env.ORCA_WORKTREE_ID = caller - callMock.mockReset() - log.mockClear() - process.exitCode = prior - callMock.mockResolvedValue(worktreeListFixture(rows)) - await main(['worktree', 'current', '--json'], root.path) - expect(process.exitCode).toBe(1) - expect( - JSON.parse(log.mock.calls.flat().join('\n')).error.data.validSelectorForms - ).toEqual(rows.filter((row) => row !== outside).map((row) => `id:${row.id}`)) - expect(callMock).toHaveBeenCalledTimes(2) - } - } - } finally { - process.exitCode = prior - } - }) - - it('retains optional no-match fallback, surfaces an unreadable catalog, and keeps scope bypasses', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const prior = process.exitCode - const commands = [ - { args: ['snapshot'], method: 'browser.snapshot' }, - { args: ['emulator', 'list'], method: 'emulator.list' }, - { args: automation, method: 'automation.create' } - ] - try { - for (const { args, method: action } of commands) { - for (const mode of ['missing', 'unavailable', 'exact', 'remote']) { - callMock.mockReset() - log.mockClear() - process.exitCode = prior - callMock.mockImplementation(async (method) => { - if (method === 'worktree.list') { - if (mode === 'unavailable') { - throw new RuntimeRpcFailureError({ - id: 'unavailable', - ok: false, - error: { code: 'runtime_unavailable', message: 'unavailable' }, - _meta: { runtimeId: 'runtime-1' } - }) - } - return worktreeListFixture([]) - } - if (method === 'worktree.show') { - return okFixture('show', { worktree: root }) - } - if (method === 'repo.show') { - return okFixture('repo', { repo: { id: root.repoId, connectionId: null } }) - } - return okFixture('accepted', { marker: 'accepted' }) - }) - const scope = - mode === 'exact' - ? [action === 'automation.create' ? '--workspace' : '--worktree', choices[0]!] - : mode === 'remote' - ? ['--pairing-code', 'remote-runtime'] - : [] - await main([...args, ...scope, '--json'], root.path) - // An omitted browser target must not guess past an unreadable catalog. - if (mode === 'unavailable' && action === 'browser.snapshot') { - expect(process.exitCode).toBe(1) - expect(JSON.parse(log.mock.calls.flat().join('\n')).error.code).toBe( - 'runtime_unavailable' - ) - expect(callMock).not.toHaveBeenCalledWith(action, expect.anything()) - continue - } - expect(process.exitCode, JSON.stringify({ args, mode, output: log.mock.calls })).toBe( - prior - ) - expect(callMock).toHaveBeenCalledWith( - action, - expect.objectContaining({ - [action === 'automation.create' ? 'workspace' : 'worktree']: - mode === 'exact' ? choices[0] : undefined - }) - ) - expect(JSON.parse(log.mock.calls.flat().join('\n')).result.marker).toBe('accepted') - expect(callMock.mock.calls.filter(([method]) => method === 'worktree.list')).toHaveLength( - mode === 'exact' || mode === 'remote' ? 0 : 1 - ) - if (mode === 'unavailable') { - await expect(callMock.mock.results[0]?.value).rejects.toBeInstanceOf( - RuntimeRpcFailureError - ) - await expect(callMock.mock.results[0]?.value).rejects.toMatchObject({ - code: 'runtime_unavailable' - }) - } - } - } - for (const args of [ - ['snapshot', '--worktree', 'all'], - ['emulator', 'list', '--worktree', 'all'], - ['computer', 'get-app-state', '--app', 'fixture', '--session', 'session-1'], - ['file', 'open', 'README.md', '--worktree', choices[0]!] - ]) { - callMock.mockReset() - log.mockClear() - process.exitCode = prior - callMock.mockResolvedValue(okFixture('explicit', { marker: 'accepted', opened: true })) - await main([...args, '--json'], root.path) - expect(process.exitCode).toBe(prior) - expect(callMock).not.toHaveBeenCalledWith('worktree.list', expect.anything()) - expect(JSON.parse(log.mock.calls.flat().join('\n')).result.marker).toBe('accepted') - } - } finally { - process.exitCode = prior - } - }) - - it('carries only consumed implicit choices, keeping exact/no-parent creation and separate project inference', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const prior = process.exitCode - try { - for (const rows of [ - [root, sibling], - [sibling, root] - ]) { - for (const parent of [[], ['--parent-worktree', choices[1]!], ['--no-parent']]) { - callMock.mockReset() - log.mockClear() - callMock.mockImplementation(async (method) => - method === 'worktree.list' - ? worktreeListFixture(rows) - : okFixture('create', { worktree: root, lineage: null, warnings: [] }) - ) - await main(['worktree', 'create', '--name', 'child', ...parent, '--json'], root.path) - expect(process.exitCode).toBe(prior) - const params = callMock.mock.calls.find(([method]) => method === 'worktree.create')?.[1] - expect(params).toMatchObject({ repo: 'id:repo-a', cliProvenanceRequest: {} }) - if (parent.length === 0) { - expect(params).toMatchObject({ - cwdParentWorktree: `id:${rows[0]!.id}`, - cwdParentAmbiguous: true - }) - } else { - expect(params).not.toHaveProperty('cwdParentAmbiguous') - expect(params).not.toHaveProperty('cwdParentWorktree') - } - expect(JSON.parse(String(log.mock.calls[0]?.[0])).result.worktree.id).toBe(root.id) - } - } - callMock.mockReset() - callMock.mockResolvedValue( - okFixture('create', { worktree: root, lineage: null, warnings: [] }) - ) - await main( - ['worktree', 'create', '--repo', 'id:repo-a', '--no-parent', '--name', 'child', '--json'], - root.path - ) - expect(callMock.mock.calls.map(([method]) => method)).toEqual(['worktree.create']) - } finally { - process.exitCode = prior - } - }) - - it.each([false, true])( - 'exposes eligible native choices once after host/caller election (json=%s)', - async (json) => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const err = vi.spyOn(console, 'error').mockImplementation(() => {}) - const prior = process.exitCode - try { - for (const command of [ - ['agent', 'launch', '--agent', 'codex'], - ['ports', '--all'] - ]) { - for (const caller of [undefined, 'folder:r']) { - for (const ids of [ - ['r', 's', 'remote'], - ['remote', 's', 'r'] - ]) { - callMock.mockReset() - log.mockClear() - err.mockClear() - process.exitCode = prior - if (caller) { - process.env.ORCA_WORKSPACE_ID = caller - } else { - delete process.env.ORCA_WORKSPACE_ID - } - callMock.mockImplementation(async (method) => { - if (method === 'worktree.list') { - return worktreeListFixture([]) - } - if (method === 'folderWorkspace.list') { - return okFixture('folders', { - folderWorkspaces: ids.map((id) => ({ - id, - folderPath: root.path, - projectGroupId: id === 'remote' ? 'ssh' : 'local' - })) - }) - } - if (method === 'projectGroup.list') { - return okFixture('groups', { - groups: [{ id: 'local' }, { id: 'ssh', connectionId: 'other' }] - }) - } - if (method === 'repo.list') { - return okFixture('repos', { repos: [] }) - } - if (method === 'status.get') { - return agentLaunchHostFixture() - } - if (method === 'workspacePorts.scanHost') { - return okFixture('ports', { ports: [] }) - } - return agentLaunchFixture('folder:r') - }) - await main([...command, ...(json ? ['--json'] : [])], root.path) - expect(callMock.mock.calls.slice(0, 4).map(([method]) => method)).toEqual([ - 'worktree.list', - 'folderWorkspace.list', - 'projectGroup.list', - 'repo.list' - ]) - if (caller) { - expect(process.exitCode, log.mock.calls.flat().join('')).toBe(prior) - expect(callMock).toHaveBeenCalledWith( - command[0] === 'ports' ? 'workspacePorts.scanHost' : 'agent.launchReplay', - command[0] === 'ports' - ? { worktree: 'folder:r' } - : expect.objectContaining({ - target: { kind: 'existing', worktree: 'folder:r' } - }) - ) - } else { - expect(process.exitCode).toBe(1) - const output = (json ? log : err).mock.calls.flat().join('\n') - const choices = json - ? JSON.parse(output).error.data.workspaces - : JSON.parse( - output.split('Workspace choices (JSON data):\n')[1]!.split('\nNext step:')[0]! - ) - expect(choices.map((choice: { selector: string }) => choice.selector)).toEqual( - ids.filter((id) => id !== 'remote').map((id) => `folder:${id}`) - ) - expect( - choices.every((choice: { hostId: string }) => choice.hostId === 'local') - ).toBe(true) - expect(output).not.toContain('worktree list') - expect(output).toContain( - command[0] === 'ports' ? 'The port scan did not run.' : 'codex was not started.' - ) - expect(output).toContain('--worktree ') - if (!json) { - expect(output.split('Workspace choices (JSON data):')).toHaveLength(2) - } - expect(callMock).toHaveBeenCalledTimes(4) - } - } - } - } - } finally { - process.exitCode = prior - } - } - ) - it.each([ - 'space path', - 'quotes" and smart“quotes”', - 'semi;&$`%!^()', - 'back\\slash/', - 'line\nfeed', - 'cafe\u0301' - ])('shows raw choice data once and accepts it as one selector argument: %j', async (suffix) => { - const row = buildWorktree(`/tmp/owner ${suffix}`, 'main', 'abc', 'repo-a') - const other = { ...row, id: `${row.id}::workspace:sibling` } - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const err = vi.spyOn(console, 'error').mockImplementation(() => {}) - const prior = process.exitCode - try { - for (const json of [false, true]) { - log.mockClear() - err.mockClear() - process.exitCode = prior - callMock.mockResolvedValue(worktreeListFixture([row, other])) - await main(['worktree', 'current', ...(json ? ['--json'] : [])], row.path) - expect(process.exitCode).toBe(1) - const output = (json ? log : err).mock.calls.flat().join('\n') - const data = json - ? JSON.parse(output).error.data.workspaces - : JSON.parse( - output.split('Workspace choices (JSON data):\n')[1]!.split('\nNext step:')[0]! - ) - expect(data.map((choice: { selector: string }) => choice.selector)).toEqual([ - `id:${row.id}`, - `id:${other.id}` - ]) - if (!json) { - expect(output.split('Workspace choices (JSON data):')).toHaveLength(2) - } - const advice = json - ? JSON.parse(output).error.data.nextSteps.join(' ') - : output.split('Next step:').slice(1).join(' ') - expect(advice).not.toContain(row.id) - expect(advice).toContain('one argument quoted for your shell') - log.mockClear() - process.exitCode = prior - callMock.mockReset() - callMock.mockResolvedValue(okFixture('exact', { worktree: row })) - await main(['worktree', 'show', '--worktree', data[0].selector, '--json'], row.path) - expect(process.exitCode).toBe(prior) - expect(callMock.mock.calls).toEqual([ - ['worktree.show', { worktree: `id:${row.id}`, matchFolderWorkspaces: true }] - ]) - expect(JSON.parse(log.mock.calls.flat().join('')).result.worktree.id).toBe(row.id) - } - } finally { - process.exitCode = prior - } - }) -}) diff --git a/src/cli/index-worktree-create-agent.test.ts b/src/cli/index-worktree-create-agent.test.ts deleted file mode 100644 index 776ff6f5b22..00000000000 --- a/src/cli/index-worktree-create-agent.test.ts +++ /dev/null @@ -1,432 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - worktreeListFixture -} from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' -import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures' - -describe('orca cli worktree awareness', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('opts into setup and activation when worktree.create runs hooks', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), - noFolderWorkspacesFixture(), - okFixture('req_create', { - worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'feature', '--run-hooks', '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.create', { - repo: 'id:repo-1', - name: 'feature', - displayName: 'feature', - displayNameKind: 'user', - baseBranch: undefined, - linkedIssue: undefined, - comment: undefined, - runHooks: true, - activate: true, - navigation: 'host', - parentWorktree: undefined, - cwdParentWorktree: 'id:repo-1::/tmp/repo', - noParent: false, - callerTerminalHandle: undefined, - cliProvenanceRequest: {} - }) - }) - - it('starts an agent worktree through agent.launch, in the background unless activation is explicit', async () => { - process.env.ORCA_WORKTREE_ID = 'repo-1::/tmp/repo' - queueFixtures( - callMock, - worktreeListFixture([ - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2'), - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1') - ]), - noFolderWorkspacesFixture(), - agentLaunchHostFixture(), - agentLaunchFixture('repo-1::/tmp/repo/agent-task', 'The inferred parent contexts conflict.'), - okFixture('req_show', { - worktree: buildWorktree('/tmp/repo/agent-task', 'agent-task', 'abc', 'repo-1') - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'create', - '--name', - 'agent-task', - '--branch', - 'DAT-111-agent-task', - '--agent', - 'codex', - '--model', - 'gpt-5.5', - '--effort', - 'high', - '--prompt', - 'hi', - '--setup', - 'run', - '--json' - ], - '/tmp/repo/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(4, 'agent.launchReplay', { - target: { - kind: 'create-worktree', - create: { - repo: 'id:repo-1', - name: 'agent-task', - displayName: 'agent-task', - displayNameKind: 'user', - baseBranch: undefined, - branchNameOverride: 'DAT-111-agent-task', - linkedIssue: undefined, - comment: undefined, - runHooks: false, - activate: false, - setupDecision: 'run', - parentWorktree: undefined, - cwdParentWorktree: 'id:repo-1::/tmp/repo', - envParentWorkspace: 'worktree:repo-1::/tmp/repo', - noParent: false, - callerTerminalHandle: undefined, - cliProvenanceRequest: {} - } - }, - presentation: 'background', - agent: 'codex', - prompt: { text: 'hi', delivery: 'submit' }, - sessionOptions: { model: 'gpt-5.5', effort: 'high' }, - launchSource: 'cli', - operationId: expect.any(String) - }) - expect(callMock).toHaveBeenNthCalledWith(5, 'worktree.show', { - worktree: 'id:repo-1::/tmp/repo/agent-task' - }) - const printed = JSON.parse(String(logSpy.mock.calls[0]?.[0])) - expect(printed.result.worktree.path).toBe('/tmp/repo/agent-task') - expect(printed.result.worktree.id).toBe('repo-1::/tmp/repo/agent-task') - expect(printed.result.launch.outcome).toEqual({ - kind: 'structured', - sessionId: 'codex_1', - handle: 'agent_1' - }) - expect(printed.result.launch.warning).toBe('The inferred parent contexts conflict.') - }) - - it('rejects an empty retry identity before creating a worktree', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:repo-1', - '--name', - 'task', - '--agent', - 'codex', - '--retry-launch=', - '--json' - ], - '/tmp/repo' - ) - expect(process.exitCode).toBe(1) - process.exitCode = priorExitCode - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).error).toMatchObject({ - code: 'invalid_argument', - message: expect.stringContaining('--retry-launch') - }) - expect(callMock).not.toHaveBeenCalled() - }) - - it.each([ - { capabilities: [] }, - { capabilities: ['agent.launch.v2'] }, - { capabilities: ['agent.launch.v2', 'agent.launch.local-presentation.v1'] } - ])( - 'falls back to the startup terminal when the host lacks a required launch capability: $capabilities', - async ({ capabilities }) => { - process.env.ORCA_WORKTREE_ID = 'repo-1::/tmp/repo' - queueFixtures( - callMock, - worktreeListFixture([ - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2'), - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1') - ]), - noFolderWorkspacesFixture(), - okFixture('req_status', { capabilities }), - okFixture('req_create', { - worktree: buildWorktree('/tmp/repo/agent-task', 'agent-task', 'abc', 'repo-1'), - lineage: null, - warnings: [] - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'create', - '--name', - 'agent-task', - '--agent', - 'codex', - '--prompt', - 'hi', - '--activate', - '--json' - ], - '/tmp/repo/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(4, 'worktree.create', { - repo: 'id:repo-1', - name: 'agent-task', - displayName: 'agent-task', - displayNameKind: 'user', - baseBranch: undefined, - linkedIssue: undefined, - comment: undefined, - runHooks: false, - activate: true, - navigation: 'host', - parentWorktree: undefined, - cwdParentWorktree: 'id:repo-1::/tmp/repo', - envParentWorkspace: 'worktree:repo-1::/tmp/repo', - noParent: false, - callerTerminalHandle: undefined, - cliProvenanceRequest: {}, - startupAgent: 'codex', - startupPrompt: 'hi', - launchSource: 'cli' - }) - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.worktree.id).toBe( - 'repo-1::/tmp/repo/agent-task' - ) - } - ) - - it('refuses inferred agent creation before capability lookup or either launch path when projects tie', async () => { - queueFixtures( - callMock, - worktreeListFixture([ - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1'), - buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2') - ]), - noFolderWorkspacesFixture() - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - try { - await main( - ['worktree', 'create', '--name', 'task', '--agent', 'codex', '--json'], - '/tmp/repo/src' - ) - expect(process.exitCode).toBe(1) - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).error.code).toBe('selector_ambiguous') - expect(callMock.mock.calls.map(([method]) => method)).toEqual([ - 'worktree.list', - 'folderWorkspace.list' - ]) - } finally { - process.exitCode = priorExitCode - } - }) - - it('rejects prompt without agent on worktree.create', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--prompt', 'hi', '--json'], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - '--prompt requires --agent' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('rejects unknown agents on worktree.create', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--agent', 'wat', '--json'], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: 'Unknown TUI agent "wat"' - } - }) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('rejects agent, prompt, and setup flags without values on worktree.create', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--agent'], - '/tmp/repo' - ) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Missing value for --agent' - ) - - callMock.mockClear() - logSpy.mockClear() - errSpy.mockClear() - process.exitCode = priorExitCode - - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:repo-1', - '--name', - 'child', - '--agent', - 'codex', - '--prompt' - ], - '/tmp/repo' - ) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - '--prompt requires a value' - ) - - callMock.mockClear() - logSpy.mockClear() - errSpy.mockClear() - process.exitCode = priorExitCode - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--setup'], - '/tmp/repo' - ) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Missing value for --setup' - ) - - process.exitCode = priorExitCode - }) - - it('rejects contradictory setup flags on worktree.create', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:repo-1', - '--name', - 'child', - '--run-hooks', - '--setup', - 'skip', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Choose either --run-hooks or --setup run' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) -}) diff --git a/src/cli/index-worktree-create-host-scoped-repo.test.ts b/src/cli/index-worktree-create-host-scoped-repo.test.ts deleted file mode 100644 index f8c054f9c4e..00000000000 --- a/src/cli/index-worktree-create-host-scoped-repo.test.ts +++ /dev/null @@ -1,374 +0,0 @@ -import { join, resolve } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - worktreeListFixture -} from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' - -const SSH_CALLER = { - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'ssh', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'box-b', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'inc-1', - ORCA_ORCHESTRATION_COMPATIBILITY_ATTACHMENT: 'att-1' -} - -describe('worktree create from a worktree another host shares an id with', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - afterEach(() => { - for (const key of Object.keys(SSH_CALLER)) { - delete process.env[key] - } - }) - - it('infers the repo while the parent stays the exact host-scoped identity', async () => { - Object.assign(process.env, SSH_CALLER) - queueFixtures( - callMock, - worktreeListFixture([ - { - ...buildWorktree('/srv/app', 'main', 'abc', 'repo-1'), - hostId: 'ssh:box-a', - identity: { key: 'wt2:a' } - }, - { - ...buildWorktree('/srv/app', 'main', 'abc', 'repo-1'), - hostId: 'ssh:box-b', - identity: { key: 'wt2:b' } - } - ]), - noFolderWorkspacesFixture(), - okFixture('req_create', { - worktree: buildWorktree('/srv/app-child', 'child', 'abc', 'repo-1'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['worktree', 'create', '--name', 'child', '--json'], '/srv/app/src') - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'worktree.create', - expect.objectContaining({ repo: 'id:repo-1', cwdParentWorktree: 'identity:wt2:b' }) - ) - }) - - it('infers checkout ownership independently of workspace identity and catalog order', async () => { - const path = resolve('/tmp/sta-12478') - const root = buildWorktree(path, 'main', 'abc', 'repo-a') - const other = buildWorktree(path, 'main', 'abc', 'repo-b') - const sibling = { ...root, id: `${root.id}::workspace:11111111-1111-4111-8111-111111111111` } - const folder = { ...root, id: 'folder:f1', repoId: 'folder-workspace:group-1' } - const nfc = buildWorktree(join(path, 'café'), 'main', 'abc', 'repo-a') - const nfd = buildWorktree(join(path, 'cafe\u0301'), 'main', 'abc', 'repo-b') - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - const cases = [ - { rows: [nfc, nfd], caller: undefined, repo: undefined, cwd: nfc.path }, - { rows: [nfc, nfd], caller: nfc.id, repo: 'repo-a', cwd: nfc.path }, - { rows: [nfc, nfd], caller: nfc.id, repo: 'repo-a', cwd: nfc.path, parent: 'active' }, - { rows: [nfc, nfd], caller: nfc.id, repo: 'repo-a', cwd: nfc.path, parent: 'current' }, - { rows: [root, { ...other, path: join(path, 'nested') }], caller: undefined, repo: 'repo-b' }, - { rows: [root, other], caller: undefined, repo: undefined }, - { rows: [root, other], caller: other.id, repo: 'repo-b' }, - { rows: [root, other], caller: 'missing::workspace', repo: undefined }, - { rows: [root, root], caller: undefined, repo: 'repo-a' }, - { rows: [root, sibling], caller: undefined, repo: 'repo-a' }, - { rows: [root, folder], caller: undefined, repo: 'repo-a' }, - { - rows: [root, { ...folder, path: join(path, 'nested') }], - caller: undefined, - repo: 'repo-a' - }, - { - rows: [ - { ...root, head: '', branch: '' }, - { ...sibling, head: '', branch: '' } - ], - caller: undefined, - repo: 'repo-a' - }, - { rows: [root, folder], caller: root.id, repo: 'repo-a' }, - { rows: [root, folder], caller: folder.id, repo: 'repo-a' }, - { rows: [root, { ...root, hostId: 'runtime:other' }], caller: undefined, repo: undefined } - ] - try { - for (const testCase of cases) { - for (const rows of [testCase.rows, testCase.rows.toReversed()]) { - callMock.mockReset() - logSpy.mockClear() - errSpy.mockClear() - process.exitCode = priorExitCode - if (testCase.caller) { - process.env.ORCA_WORKTREE_ID = testCase.caller - } else { - delete process.env.ORCA_WORKTREE_ID - } - callMock.mockImplementation(async (method: string) => - method === 'worktree.list' - ? worktreeListFixture(rows) - : okFixture('create', { - worktree: buildWorktree(join(path, 'child'), 'child', 'abc', testCase.repo), - lineage: null, - warnings: [] - }) - ) - await main( - [ - 'worktree', - 'create', - '--name', - 'child', - ...(testCase.parent ? ['--parent-worktree', testCase.parent] : ['--no-parent']), - '--json' - ], - testCase.cwd ?? join(path, 'nested', 'src') - ) - if (testCase.repo) { - expect(process.exitCode).toBe(priorExitCode) - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.worktree.repoId).toBe( - testCase.repo - ) - expect(callMock).toHaveBeenCalledWith( - 'worktree.create', - expect.objectContaining({ - repo: `id:${testCase.repo}`, - noParent: !testCase.parent, - ...(testCase.parent ? { parentWorktree: `id:${testCase.caller}` } : {}) - }) - ) - } else { - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - expect(process.exitCode).toBe(1) - const printed = [...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n') - expect(printed).toContain('selector_ambiguous') - expect(printed).toContain('Choose the project with --repo or --project') - } - } - } - // An explicit target keeps optional-parent inference; active/current refuse a two-owner path. - delete process.env.ORCA_WORKTREE_ID - for (const parent of [undefined, 'active', 'current']) { - callMock.mockReset() - process.exitCode = priorExitCode - callMock.mockImplementation(async (method: string) => { - if (method === 'worktree.list') { - return worktreeListFixture([root, other]) - } - return okFixture('create', { - worktree: buildWorktree(join(path, 'child'), 'child'), - lineage: null, - warnings: [] - }) - }) - await main( - [ - 'worktree', - 'create', - '--name', - 'child', - '--repo', - 'id:repo-b', - ...(parent ? ['--parent-worktree', parent] : []), - '--json' - ], - path - ) - // Two registrations own the path: an explicit current refuses, inference flags the tie. - if (parent) { - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - process.exitCode = priorExitCode - continue - } - expect(process.exitCode).toBe(priorExitCode) - expect(callMock).toHaveBeenCalledWith( - 'worktree.create', - expect.objectContaining({ - repo: 'id:repo-b', - cwdParentWorktree: `id:${root.id}`, - cwdParentAmbiguous: true - }) - ) - } - // A unique project retains the legacy parent hint and carries the unresolved owners. - callMock.mockReset() - queueFixtures( - callMock, - worktreeListFixture([sibling, root]), - okFixture('create', { - worktree: buildWorktree(join(path, 'child'), 'child'), - lineage: null, - warnings: [] - }) - ) - await main(['worktree', 'create', '--name', 'child', '--json'], path) - expect(callMock).toHaveBeenCalledWith( - 'worktree.create', - expect.objectContaining({ - repo: 'id:repo-a', - cwdParentWorktree: `id:${sibling.id}`, - cwdParentAmbiguous: true - }) - ) - } finally { - process.exitCode = priorExitCode - } - }) - - it('requires an explicit Git destination when a native folder supplies only parent lineage', async () => { - const path = resolve('/tmp/plain-folder') - const folder = { - ...buildWorktree(path, ''), - id: 'folder:f1', - repoId: 'folder-workspace:group-1' - } - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - try { - for (const rows of [[], [folder]]) { - for (const explicit of [false, true]) { - callMock.mockReset() - logSpy.mockClear() - process.exitCode = priorExitCode - callMock.mockImplementation(async (method: string) => - method === 'worktree.list' - ? worktreeListFixture(rows) - : okFixture('create', { - worktree: buildWorktree(join(path, 'child'), 'child', 'abc', 'repo-a'), - lineage: null, - warnings: [] - }) - ) - await main( - [ - 'worktree', - 'create', - '--name', - 'folder-child', - '--parent-worktree', - 'folder:f1', - ...(explicit ? ['--repo', 'id:repo-a'] : []), - '--json' - ], - join(path, 'src') - ) - if (explicit) { - expect(process.exitCode).toBe(priorExitCode) - expect(callMock).toHaveBeenCalledWith( - 'worktree.create', - expect.objectContaining({ - repo: 'id:repo-a', - parentWorkspace: 'folder:f1' - }) - ) - } else { - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - expect(logSpy.mock.calls.flat().join('\n')).toContain('Missing repo selector') - } - } - } - } finally { - process.exitCode = priorExitCode - } - }) - - it.each(['folder:f1', 'active'])( - 'lists the Git repositories of a folder parent when create has no repo (--parent-worktree %s)', - async (parent) => { - const path = resolve('/tmp/feature-folder') - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - const lists: Record = { - 'worktree.list': worktreeListFixture([]).result, - 'folderWorkspace.list': { - folderWorkspaces: [{ id: 'f1', projectGroupId: 'g1', folderPath: path, name: 'feature' }] - }, - 'projectGroup.list': { groups: [{ id: 'g1', name: 'feature', parentPath: path }] }, - 'repo.list': { - repos: [ - { id: 'repo-api', path: join(path, 'api'), displayName: 'api' }, - { id: 'elsewhere', path: resolve('/tmp/other'), displayName: 'other' } - ] - } - } - try { - callMock.mockImplementation(async (method: string) => - okFixture(method, lists[method] ?? {}) - ) - await main( - ['worktree', 'create', '--name', 'fix-login', '--parent-worktree', parent], - join(path, 'api') - ) - const output = [...errorSpy.mock.calls, ...logSpy.mock.calls].flat().join('\n') - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - expect(output).toContain('--repo id:repo-api') - expect(output).not.toContain('id:elsewhere') - } finally { - process.exitCode = priorExitCode - } - } - ) -}) diff --git a/src/cli/index-worktree-create-target.test.ts b/src/cli/index-worktree-create-target.test.ts deleted file mode 100644 index f94b4ef692f..00000000000 --- a/src/cli/index-worktree-create-target.test.ts +++ /dev/null @@ -1,573 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - worktreeListFixture -} from './test-fixtures' -import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' -import { RuntimeRpcFailureError } from './runtime-client' - -function buildSetup(overrides: { - id: string - hostId: string - repoId: string - projectId?: string - path?: string - displayName?: string -}) { - return { - projectId: 'github:stablyai/orca', - path: '/tmp/orca', - displayName: 'Orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -describe('orca cli worktree awareness', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('passes explicit activation through worktree.create', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), - noFolderWorkspacesFixture(), - okFixture('req_create', { - worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'feature', '--activate', '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.create', { - repo: 'id:repo-1', - name: 'feature', - displayName: 'feature', - displayNameKind: 'user', - baseBranch: undefined, - linkedIssue: undefined, - comment: undefined, - runHooks: false, - activate: true, - navigation: 'host', - parentWorktree: undefined, - cwdParentWorktree: 'id:repo-1::/tmp/repo', - noParent: false, - callerTerminalHandle: undefined, - cliProvenanceRequest: {} - }) - }) - - it('resolves project and host flags to the matching repo for worktree.create', async () => { - pairRuntimeEnvironment(listEnvironmentsMock, 'gpu') - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - { - id: 'setup-local', - projectId: 'github:stablyai/orca', - hostId: 'local', - repoId: 'repo-local', - path: '/tmp/orca', - displayName: 'Orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - }, - { - id: 'setup-gpu', - projectId: 'github:stablyai/orca', - hostId: 'runtime:gpu', - repoId: 'repo-gpu', - path: '/srv/orca', - displayName: 'Orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } - ] - }), - okFixture('req_create', { - worktree: buildWorktree('/srv/orca/feature', 'feature', 'abc', 'repo-gpu'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'create', - '--project', - 'github:stablyai/orca', - '--host', - 'runtime:gpu', - '--name', - 'feature', - '--no-parent', - '--json' - ], - '/tmp/repo' - ) - - expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, 'gpu') - expect(callMock).toHaveBeenNthCalledWith(1, 'projectHostSetup.list') - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { - repo: 'id:repo-gpu', - repoHostId: 'runtime:gpu', - name: 'feature', - displayName: 'feature', - displayNameKind: 'user', - baseBranch: undefined, - linkedIssue: undefined, - comment: undefined, - runHooks: false, - activate: false, - parentWorktree: undefined, - noParent: true, - callerTerminalHandle: undefined, - cliProvenanceRequest: {} - }) - }) - - it('resolves project-host-setup directly for worktree.create', async () => { - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - { - id: 'setup-gpu', - projectId: 'github:stablyai/orca', - hostId: 'runtime:gpu', - repoId: 'repo-gpu', - path: '/srv/orca', - displayName: 'Orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } - ] - }), - okFixture('req_create', { - worktree: buildWorktree('/srv/orca/feature', 'feature', 'abc', 'repo-gpu'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'create', - '--project-host-setup', - 'setup-gpu', - '--name', - 'feature', - '--no-parent', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.create', - expect.objectContaining({ repo: 'id:repo-gpu' }) - ) - }) - - it('surfaces a project.list failure instead of reporting the project as not set up', async () => { - const { RuntimeClientError } = await import('./runtime/types.js') - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [buildSetup({ id: 'setup-local', hostId: 'local', repoId: 'repo-local' })] - }) - ) - callMock.mockRejectedValueOnce( - new RuntimeClientError('internal_error', 'project store offline') - ) - - await main( - ['worktree', 'create', '--project', 'scalp-it', '--name', 'feature', '--no-parent', '--json'], - '/tmp/repo' - ) - - const printed = [...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n') - expect(printed).toContain('project store offline') - expect(printed).not.toContain('Project is not set up') - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('refuses a legacy display-name match that spans two projects', async () => { - const { RuntimeClientError } = await import('./runtime/types.js') - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - buildSetup({ - id: 'setup-a', - hostId: 'local', - repoId: 'repo-a', - projectId: 'github:acme/scalp-it', - displayName: 'scalp-it' - }), - buildSetup({ - id: 'setup-b', - hostId: 'local', - repoId: 'repo-b', - projectId: 'gitlab:other/scalp-it', - displayName: 'scalp-it' - }) - ] - }) - ) - callMock.mockRejectedValueOnce( - new RuntimeClientError('method_not_found', 'Unknown method: project.list') - ) - - await main( - ['worktree', 'create', '--project', 'scalp-it', '--name', 'feature', '--no-parent', '--json'], - '/tmp/repo' - ) - - const printed = [...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n') - expect(printed).toContain('2 projects have a setup named that') - expect(printed).toContain('github:acme/scalp-it') - expect(printed).toContain('gitlab:other/scalp-it') - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('falls back to the setup display name when the server has no project.list', async () => { - const { RuntimeClientError } = await import('./runtime/types.js') - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - buildSetup({ - id: 'setup-local', - hostId: 'local', - repoId: 'repo-local', - projectId: 'github:stablyai/scalp-it', - displayName: 'scalp-it' - }) - ] - }) - ) - callMock.mockRejectedValueOnce( - new RuntimeClientError('method_not_found', 'Unknown method: project.list') - ) - queueFixtures( - callMock, - okFixture('req_create', { - worktree: buildWorktree('/tmp/scalp-it/feature', 'feature', 'abc', 'repo-local'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'create', '--project', 'scalp-it', '--name', 'feature', '--no-parent', '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'worktree.create', - expect.objectContaining({ repo: 'id:repo-local' }) - ) - }) - - it('resolves --project by display name and infers the only host it is set up on', async () => { - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - buildSetup({ - id: 'setup-local', - hostId: 'local', - repoId: 'repo-local', - projectId: 'github:stablyai/scalp-it', - path: '/tmp/scalp-it', - displayName: 'scalp-it' - }) - ] - }), - okFixture('req_projects', { - projects: [{ id: 'github:stablyai/scalp-it', displayName: 'scalp-it' }] - }), - okFixture('req_create', { - worktree: buildWorktree('/tmp/scalp-it/feature', 'feature', 'abc', 'repo-local'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'create', '--project', 'scalp-it', '--name', 'feature', '--no-parent', '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'projectHostSetup.list') - expect(callMock).toHaveBeenNthCalledWith(2, 'project.list') - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'worktree.create', - expect.objectContaining({ repo: 'id:repo-local' }) - ) - }) - - it('reports an unknown project as a project miss, not a host one', async () => { - queueFixtures( - callMock, - okFixture('req_project_setups', { setups: [] }), - okFixture('req_projects', { projects: [] }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'create', '--project', 'nope', '--name', 'feature', '--no-parent', '--json'], - '/tmp/repo' - ) - - const printed = [...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n') - expect(printed).toContain('No ready setup found for --project nope on any host.') - expect(printed).not.toContain('selected host') - expect(process.exitCode).toBe(1) - process.exitCode = priorExitCode - }) - - it('asks which host only when the project is set up on more than one', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - queueFixtures( - callMock, - okFixture('req_project_setups', { - setups: [ - buildSetup({ - id: 'setup-local', - hostId: 'local', - repoId: 'repo-local', - path: '/tmp/orca' - }), - buildSetup({ - id: 'setup-gpu', - hostId: 'runtime:gpu', - repoId: 'repo-gpu', - path: '/srv/orca' - }) - ] - }) - ) - - await main( - [ - 'worktree', - 'create', - '--project', - 'github:stablyai/orca', - '--name', - 'feature', - '--no-parent', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - const printed = [...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n') - expect(printed).toContain('it is set up on 2 hosts') - expect(printed).toContain('--host local') - expect(printed).toContain('--host runtime:gpu') - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('accepts the host alias that `orca host list` prints', async () => { - queueFixtures( - callMock, - okFixture('req_ssh_targets', { - targets: [{ id: 'ssh-1783599077486-fyasux', label: 'trader-local' }] - }), - okFixture('req_project_setups', { - setups: [ - buildSetup({ id: 'setup-local', hostId: 'local', repoId: 'repo-local' }), - buildSetup({ - id: 'setup-trader', - hostId: 'ssh:ssh-1783599077486-fyasux', - repoId: 'repo-trader', - path: '/home/trader/orca' - }) - ] - }), - okFixture('req_create', { - worktree: buildWorktree('/home/trader/orca/feature', 'feature', 'abc', 'repo-trader'), - lineage: null, - warnings: [] - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'create', - '--project', - 'github:stablyai/orca', - '--host', - 'trader-local', - '--name', - 'feature', - '--no-parent', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'ssh.listTargetSummaries') - expect(callMock).toHaveBeenNthCalledWith( - 3, - 'worktree.create', - expect.objectContaining({ repo: 'id:repo-trader' }) - ) - }) - - it('rejects mixing repo and project target flags on worktree.create', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:repo-local', - '--project', - 'github:stablyai/orca', - '--name', - 'feature', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Choose either --repo or project target flags, not both.' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('tells the user which --setup flag answers an undecided ask repo', async () => { - callMock.mockRejectedValueOnce( - new RuntimeRpcFailureError({ - id: 'req_create', - ok: false, - error: { code: 'runtime_error', message: 'Setup decision required for this repository' }, - _meta: { runtimeId: 'runtime-1' } - }) - ) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'child', '--no-parent'], - '/tmp/repo' - ) - - expect(errSpy.mock.calls.flat().join('\n')).toBe( - 'Setup decision required for this repository\n' + - 'Next step: Pass --setup run to run the setup script, or --setup skip to create without it.' - ) - expect(process.exitCode).toBe(1) - process.exitCode = priorExitCode - }) -}) diff --git a/src/cli/index-worktree-set.test.ts b/src/cli/index-worktree-set.test.ts deleted file mode 100644 index 37673b2e353..00000000000 --- a/src/cli/index-worktree-set.test.ts +++ /dev/null @@ -1,560 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { RuntimeRpcFailureError } from './runtime/types' -import { - buildWorktree, - noFolderWorkspacesFixture, - okFixture, - queueFixtures, - worktreeListFixture, - queueNoFolderAtSelector -} from './test-fixtures' -import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' - -describe('orca cli worktree awareness', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('sends folder parents only to hosts that accept them and avoids blaming the child for missing parents', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - const child = 'id:repo::/tmp/repo/child' - try { - for (const parent of ['folder:folder-1', 'id:folder:folder-1']) { - for (const capabilities of [[], ['worktree.set.folder-parent.v1']]) { - callMock.mockReset() - logSpy.mockClear() - process.exitCode = priorExitCode - callMock.mockImplementation(async (method: string) => - method === 'status.get' - ? { id: 'req_status', ok: true, result: { capabilities } } - : { id: 'req_set', ok: true, result: { worktree: { id: 'repo::/tmp/repo/child' } } } - ) - await main( - ['worktree', 'set', '--worktree', child, '--parent-worktree', parent, '--json'], - '/tmp/repo' - ) - if (capabilities.length === 0) { - expect(callMock).not.toHaveBeenCalledWith('worktree.set', expect.anything()) - const output = JSON.parse(logSpy.mock.calls.at(-1)?.[0] ?? '{}').error - expect(output.message).toContain( - 'to attach a worktree to a folder workspace. Nothing was changed.' - ) - expect(process.exitCode).toBe(1) - } else { - expect(callMock).toHaveBeenCalledWith( - 'worktree.set', - expect.objectContaining({ parentWorktree: 'folder:folder-1' }) - ) - } - } - } - callMock.mockReset() - process.exitCode = priorExitCode - - callMock.mockRejectedValueOnce( - new RuntimeRpcFailureError({ - id: 'req_missing_parent', - ok: false, - error: { - code: 'selector_not_found', - message: 'selector_not_found', - data: { orchestrationRequestId: 'req_mutation', nextSteps: ['Inspect mutation.'] } - } - }) - ) - logSpy.mockClear() - await main( - ['worktree', 'set', '--worktree', child, '--parent-worktree', 'name:missing', '--json'], - '/tmp/repo' - ) - const output = JSON.parse(logSpy.mock.calls.at(-1)?.[0] ?? '{}').error - expect(callMock).toHaveBeenLastCalledWith('worktree.set', expect.anything()) - expect(output.data.orchestrationRequestId).toBe('req_mutation') - expect(output.data.nextSteps).toContain('Inspect mutation.') - expect(output.data.nextSteps.join(' ')).toContain('parent selector "name:missing"') - expect(output.data.nextSteps.join(' ')).toContain( - 'The server did not identify which selector failed.' - ) - expect(output.data.nextSteps.join(' ')).not.toContain( - 'No Orca workspace matched the worktree selector' - ) - expect(process.exitCode).toBe(1) - expect(errSpy).not.toHaveBeenCalled() - } finally { - process.exitCode = priorExitCode - } - }) - - it('keeps child and parent lookup recovery distinct before mutation', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const err = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - const cwd = '/tmp/not-managed' - const rpc = { - id: 'req_child', - ok: false as const, - error: { - code: 'selector_not_found', - message: 'selector_not_found', - data: { orchestrationRequestId: 'req_original', nextSteps: ['Inspect original request.'] } - }, - _meta: { runtimeId: 'runtime_original' } - } - try { - for (const stage of ['child', 'parent', 'preflight']) { - for (const json of [true, false]) { - callMock.mockReset() - log.mockClear() - err.mockClear() - const worktree = stage === 'child' ? 'current' : 'name:x' - const parent = stage === 'parent' ? 'current' : 'name:existing-parent' - // `current` resolves from the worktree list; only name:x makes the folder lookup first. - if (stage !== 'child') { - queueNoFolderAtSelector(callMock) - } - if (stage === 'preflight') { - callMock.mockRejectedValueOnce(new RuntimeRpcFailureError(rpc)) - } else { - queueFixtures( - callMock, - worktreeListFixture([]), - // A parent's current directory may be a native folder, which isn't a catalog row. - ...(stage === 'parent' ? [okFixture('req_folders', { folderWorkspaces: [] })] : []) - ) - } - const args = ['worktree', 'set', '--worktree', worktree, '--parent-worktree', parent] - if (stage === 'preflight') { - args.push('--gitlab-issue', 'https://gitlab.com/group/repo/-/issues/1') - } - await main([...args, ...(json ? ['--json'] : [])], cwd) - const text = String((json ? log : err).mock.calls.at(-1)?.[0]) - const response = json ? JSON.parse(text) : undefined - expect(callMock.mock.calls.map(([method]) => method)).not.toContain('worktree.set') - expect(text).toContain( - stage === 'preflight' ? 'Inspect original request.' : `current directory: ${cwd}` - ) - expect(text).toContain( - stage === 'parent' ? 'explicit parent selector' : 'No Orca workspace matched' - ) - expect(text).not.toContain(stage === 'parent' ? 'name:x' : 'parent selector') - if (response) { - expect(response.id).toBe(stage === 'preflight' ? rpc.id : 'local') - expect(response._meta.runtimeId).toBe( - stage === 'preflight' ? rpc._meta.runtimeId : null - ) - if (stage === 'preflight') { - expect(response.error.data).toMatchObject({ orchestrationRequestId: 'req_original' }) - } - } - } - } - } finally { - process.exitCode = priorExitCode - } - }) - - it('uses cwd when active is passed to worktree.set', async () => { - queueFixtures( - callMock, - worktreeListFixture([ - buildWorktree('/tmp/repo', 'main', 'aaa'), - buildWorktree('/tmp/repo/feature', 'feature/foo') - ]), - noFolderWorkspacesFixture(), - okFixture('req_1', { - worktree: { - id: 'repo::/tmp/repo/feature', - branch: 'feature/foo', - path: '/tmp/repo/feature', - comment: 'hello' - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'set', '--worktree', 'active', '--comment', 'hello', '--json'], - '/tmp/repo/feature/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.set', { - worktree: 'id:repo::/tmp/repo/feature', - displayName: undefined, - linkedIssue: undefined, - comment: 'hello', - parentWorktree: undefined, - noParent: false - }) - }) - - it('resolves current for explicit parent-worktree on set', async () => { - queueFixtures( - callMock, - worktreeListFixture([buildWorktree('/tmp/repo/parent', 'feature/parent')]), - noFolderWorkspacesFixture(), - okFixture('req_set_parent', { - worktree: { - ...buildWorktree('/tmp/repo/child', 'feature/child'), - parentWorktreeId: 'repo::/tmp/repo/parent', - childWorktreeIds: [], - lineage: null - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/tmp/repo/child', - '--parent-worktree', - 'current', - '--json' - ], - '/tmp/repo/parent/src' - ) - - expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.set', { - worktree: 'id:repo::/tmp/repo/child', - displayName: undefined, - linkedIssue: undefined, - comment: undefined, - parentWorktree: 'id:repo::/tmp/repo/parent', - noParent: false - }) - }) - - it('rejects contradictory parent flags on worktree.set before resolving selectors', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/tmp/repo/child', - '--parent-worktree', - 'current', - '--no-parent', - '--json' - ], - '/tmp/not-managed' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Choose either --parent-worktree or --no-parent, not both.' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('rejects bare parent-worktree on worktree.set', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - ['worktree', 'set', '--worktree', 'id:repo::/tmp/repo/child', '--parent-worktree', '--json'], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Missing required --parent-worktree' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('passes Linear URL metadata through worktree.set', async () => { - queueFixtures( - callMock, - okFixture('req_set_linear', { - worktree: { - ...buildWorktree('/tmp/repo/child', 'feature/child'), - linkedLinearIssue: 'STA-335', - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: 'stably' - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/tmp/repo/child', - '--linear-issue', - 'https://linear.app/stably/issue/STA-335/test-issue', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledWith('worktree.set', { - worktree: 'id:repo::/tmp/repo/child', - displayName: undefined, - linkedIssue: undefined, - linkedLinearIssue: 'STA-335', - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: 'stably', - comment: undefined, - workspaceStatus: undefined, - parentWorktree: undefined, - noParent: false - }) - }) - - it('clears all Linear metadata through worktree.set', async () => { - queueFixtures( - callMock, - okFixture('req_clear_linear', { - worktree: { - ...buildWorktree('/tmp/repo/child', 'feature/child'), - linkedLinearIssue: null, - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: null - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/tmp/repo/child', - '--linear-issue', - 'null', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledWith('worktree.set', { - worktree: 'id:repo::/tmp/repo/child', - displayName: undefined, - linkedIssue: undefined, - linkedLinearIssue: null, - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: null, - comment: undefined, - workspaceStatus: undefined, - parentWorktree: undefined, - noParent: false - }) - }) - - it('rejects invalid Linear issue values on worktree.set before RPC', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/tmp/repo/child', - '--linear-issue', - 'not-a-linear-link', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain( - 'Pass a Linear issue identifier like STA-335' - ) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it.each([[['--comment', '']], [['--comment=']]])( - 'sends an explicit empty comment for %j so worktree.set clears it', - async (flags) => { - queueFixtures( - callMock, - okFixture('req_clear_comment', { - worktree: buildWorktree('/tmp/repo/child', 'feature/child') - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'set', '--worktree', 'id:repo::/tmp/repo/child', ...flags, '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledExactlyOnceWith( - 'worktree.set', - expect.objectContaining({ worktree: 'id:repo::/tmp/repo/child', comment: '' }) - ) - } - ) - - it.each([ - { flags: ['--read'], isUnread: false, acknowledges: true }, - { flags: ['--unread'], isUnread: true, acknowledges: false }, - { flags: [], isUnread: undefined, acknowledges: false } - ])( - 'sends acknowledgement intent only for explicit --read: $flags', - async ({ flags, isUnread, acknowledges }) => { - queueFixtures( - callMock, - okFixture('req_read', { worktree: buildWorktree('/tmp/repo/child', 'feature/child') }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['worktree', 'set', '--worktree', 'id:repo::/tmp/repo/child', ...flags, '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledExactlyOnceWith( - 'worktree.set', - expect.objectContaining(isUnread === undefined ? {} : { isUnread }) - ) - const params = callMock.mock.calls[0][1] - if (acknowledges) { - expect(params).toHaveProperty('acknowledgeAttention', true) - } else { - expect(params).not.toHaveProperty('acknowledgeAttention') - } - } - ) - - it.each([ - [['--unread', '--read'], 'Choose either --unread or --read'], - [['--read', '--unread'], 'Choose either --unread or --read'], - [['--read', 'yes'], '--read takes no value'], - [['--read=false'], '--read takes no value'], - [['--read='], '--read takes no value'], - [['--unread=false'], '--unread takes no value'], - [['--unread='], '--unread takes no value'] - ])('rejects %j on worktree.set before resolving selectors', async (flags, message) => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - - // Resolving active makes an RPC, so no calls proves validation ran first. - await main(['worktree', 'set', '--worktree', 'active', ...flags, '--json'], '/tmp/repo') - - expect(callMock).not.toHaveBeenCalled() - expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(message) - expect(process.exitCode).toBe(1) - - process.exitCode = priorExitCode - }) - - it('refuses a parent on this machine before any write when the server lacks cross-machine lineage', async () => { - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const priorExitCode = process.exitCode - pairRuntimeEnvironment(listEnvironmentsMock, 'build-box') - callMock.mockImplementation(async (method: string) => { - if (method === 'worktree.list') { - return worktreeListFixture([buildWorktree('/tmp/repo', 'main')]) - } - if (method === 'status.get') { - return okFixture('req_status', { capabilities: [] }) - } - if (method === 'worktree.show') { - const parent = { ...buildWorktree('/tmp/repo', 'main'), instanceId: 'parent-instance' } - return okFixture('req_show', { worktree: parent }) - } - if (method === 'worktree.lineageList') { - return okFixture('req_lineage', { lineage: {}, installationId: 'mac-install' }) - } - return okFixture('req_set', { worktree: buildWorktree('/srv/child', 'child') }) - }) - try { - await main( - [ - 'worktree', - 'set', - '--worktree', - 'id:repo::/srv/child', - '--parent-worktree', - 'active', - '--display-name', - 'renamed', - '--environment', - 'build-box', - '--json' - ], - '/tmp/repo' - ) - const methods = callMock.mock.calls.map(([method]) => method) - expect(methods).toContain('status.get') - expect(methods).not.toContain('worktree.set') - expect(process.exitCode).toBe(1) - } finally { - process.exitCode = priorExitCode - } - }) -}) diff --git a/src/cli/index-worktree-wsl-selection.test.ts b/src/cli/index-worktree-wsl-selection.test.ts index 3770867845e..119e8b12285 100644 --- a/src/cli/index-worktree-wsl-selection.test.ts +++ b/src/cli/index-worktree-wsl-selection.test.ts @@ -2,62 +2,17 @@ import { win32 } from 'node:path' import type * as NodePath from 'node:path' import { describe, expect, it, vi } from 'vitest' -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - // Exercise production UNC resolution on every CI host; keep matching and elections real. vi.mock('node:path', async (importOriginal) => { const actual = await importOriginal() return { ...actual, resolve: actual.win32.resolve } }) -import { main } from './index' import { selectEnclosingRepoOnHost, selectEnclosingWorktreeSelectionOnHost } from './caller-host-worktree-selection' -import { buildWorktree, okFixture, worktreeListFixture } from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' +import { buildWorktree } from './test-fixtures' import { toSshExecutionHostId } from '../shared/execution-host' const UPPER = String.raw`\\wsl.localhost\Ubuntu\home\Alice\App` @@ -66,29 +21,19 @@ const upper = buildWorktree(UPPER, 'main', 'abc', 'repo-a') const lower = buildWorktree(LOWER, 'main', 'abc', 'repo-b') describe('WSL enclosing selection with Windows path resolution on every platform', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it.each([ - [UPPER, String.raw`\\wsl$\ubuntu\home\Alice\App\src`], - ['\\\\wsl$\\Ubuntu\\home\\Alice\\App\\', '//wsl.localhost/ubuntu/home/Alice/App/src'], - ['//wsl.localhost/Ubuntu/home/Alice/App/', String.raw`\\wsl$\Ubuntu\home\Alice\App\src`] - ])('retains original identity for uppercase-tail aliases: %s', (root, cwd) => { - const row = buildWorktree(root, 'main', 'abc', 'repo-a') - for (const caller of [undefined, row.id]) { - expect(selectEnclosingWorktreeSelectionOnHost([row], cwd, 'local', caller)).toEqual({ - selector: `id:${row.id}`, - worktreeId: row.id - }) - expect(selectEnclosingRepoOnHost([row], cwd, 'local', caller)).toBe('repo-a') + it.each([[UPPER, String.raw`\\wsl$\ubuntu\home\Alice\App\src`]])( + 'retains original identity for uppercase-tail aliases: %s', + (root, cwd) => { + const row = buildWorktree(root, 'main', 'abc', 'repo-a') + for (const caller of [undefined, row.id]) { + expect(selectEnclosingWorktreeSelectionOnHost([row], cwd, 'local', caller)).toEqual({ + selector: `id:${row.id}`, + worktreeId: row.id + }) + expect(selectEnclosingRepoOnHost([row], cwd, 'local', caller)).toBe('repo-a') + } } - }) + ) it('excludes case-distinct directories before caller preference in either order', () => { for (const rows of [ @@ -113,149 +58,4 @@ describe('WSL enclosing selection with Windows path resolution on every platform ).toBeUndefined() expect(selectEnclosingRepoOnHost([wrongDistro, wrongHost], UPPER, 'local')).toBeUndefined() }) - - it('keeps canonical caller ties and nested checkout priority in both elections', () => { - const nfc = buildWorktree('C:\\projects\\café', 'main', 'abc', 'repo-a') - const nfd = buildWorktree('C:\\projects\\cafe\u0301', 'main', 'abc', 'repo-b') - const nested = buildWorktree(win32.join(nfc.path, 'nested'), 'main', 'abc', 'repo-child') - for (const rows of [ - [nfc, nfd], - [nfd, nfc] - ]) { - expect( - selectEnclosingWorktreeSelectionOnHost(rows, nfc.path, 'local', nfc.id)?.worktreeId - ).toBe(nfc.id) - expect(selectEnclosingRepoOnHost(rows, nfc.path, 'local', nfc.id)).toBe('repo-a') - expect(() => selectEnclosingRepoOnHost(rows, nfc.path, 'local')).toThrow('Choose the project') - for (const nestedRows of [ - [...rows, nested], - [nested, ...rows] - ]) { - const cwd = win32.join(nested.path, 'src') - expect( - selectEnclosingWorktreeSelectionOnHost(nestedRows, cwd, 'local', nfc.id)?.worktreeId - ).toBe(nested.id) - expect(selectEnclosingRepoOnHost(nestedRows, cwd, 'local', nfc.id)).toBe('repo-child') - } - } - }) - - it.each([ - { owner: upper, catalog: [upper], caller: undefined }, - { owner: upper, catalog: [upper, lower], caller: lower.id }, - { owner: lower, catalog: [upper, lower], caller: undefined }, - { owner: lower, catalog: [upper, lower], caller: upper.id }, - { owner: lower, catalog: [upper, lower], caller: lower.id } - ])( - 'forwards the containing owner through current, parent and scoped CLI routes: $owner.repoId / $caller', - async ({ owner, catalog, caller }) => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const priorExitCode = process.exitCode - const selector = `id:${owner.id}` - const child = buildWorktree(win32.join(owner.path, 'child'), 'child', 'abc', owner.repoId) - const commands = [ - { args: ['worktree', 'current'], method: 'worktree.show', target: { worktree: selector } }, - { - args: ['worktree', 'show', '--worktree', 'current'], - method: 'worktree.show', - target: { worktree: selector } - }, - ...['active', 'current'].map((parent) => ({ - args: [ - 'worktree', - 'create', - '--name', - 'child', - '--repo', - 'id:explicit-destination', - '--parent-worktree', - parent - ], - method: 'worktree.create', - target: { repo: 'id:explicit-destination', parentWorktree: selector } - })), - { - args: ['worktree', 'create', '--name', 'child', '--parent-worktree', 'current'], - method: 'worktree.create', - target: { repo: `id:${owner.repoId}`, parentWorktree: selector } - }, - { - args: ['worktree', 'create', '--name', 'child'], - method: 'worktree.create', - target: { - repo: `id:${owner.repoId}`, - cwdParentWorktree: selector, - ...(caller ? { envParentWorkspace: `worktree:${caller}` } : {}) - } - }, - ...[[], ['--worktree', 'current']].map((scope) => ({ - args: ['snapshot', ...scope], - method: 'browser.snapshot', - target: { worktree: selector } - })), - { - args: ['terminal', 'read'], - method: 'terminal.resolveActive', - target: { worktree: selector } - } - ] - try { - if (caller) { - process.env.ORCA_WORKTREE_ID = caller - } - for (const rows of [catalog, catalog.toReversed()]) { - for (const command of commands) { - callMock.mockReset() - logSpy.mockClear() - process.exitCode = priorExitCode - callMock.mockImplementation(async (method: string) => { - if (method === 'worktree.list') { - return worktreeListFixture(rows) - } - if (method === 'worktree.show') { - return okFixture('show', { worktree: owner }) - } - if (method === 'worktree.create') { - return okFixture('create', { worktree: child, lineage: null, warnings: [] }) - } - if (method === 'terminal.resolveActive') { - return okFixture('terminal', { handle: 'terminal-1' }) - } - return okFixture('scoped', { terminal: { text: 'ready' }, snapshot: 'ready' }) - }) - await main([...command.args, '--json'], win32.join(owner.path, 'src')) - expect( - process.exitCode, - JSON.stringify({ - args: [...command.args, '--json'], - cwd: win32.join(owner.path, 'src'), - caller: caller ?? null, - catalogIds: rows.map((row) => row.id), - output: JSON.stringify(logSpy.mock.calls).slice(0, 4000), - calls: JSON.stringify(callMock.mock.calls).slice(0, 4000) - }) - ).toBe(priorExitCode) - expect(callMock).toHaveBeenCalledWith( - command.method, - expect.objectContaining(command.target) - ) - if (command.method === 'worktree.show') { - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.worktree).toMatchObject({ - id: owner.id, - path: owner.path - }) - } - if (command.method === 'terminal.resolveActive') { - expect(callMock).toHaveBeenCalledWith('terminal.read', { - terminal: 'terminal-1', - limit: undefined - }) - } - } - } - } finally { - process.exitCode = priorExitCode - } - } - ) }) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 504b8cb28ef..67c70568124 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1,5 +1,4 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { worktreeRemovalReplyTimeoutMs } from '../shared/worktree/archive-hook-removal-gate' const { callMock, @@ -44,24 +43,9 @@ vi.mock('child_process', async () => { return createChildProcessModuleMock(spawnMock) }) -import { COMMAND_SPECS, main } from './index' -import { specPaths } from './args' +import { main } from './index' import { okFixture, queueFixtures } from './test-fixtures' -describe('COMMAND_SPECS collision check', () => { - it('has no duplicate command or alias paths', () => { - // First-match resolution would silently shadow duplicate aliases. - const seen = new Set() - for (const spec of COMMAND_SPECS) { - for (const path of specPaths(spec)) { - const key = path.join(' ') - expect(seen.has(key), `Duplicate command/alias path: "${key}"`).toBe(false) - seen.add(key) - } - } - }) -}) - describe('command aliases dispatch to the canonical handler', () => { let logSpy: ReturnType @@ -76,78 +60,6 @@ describe('command aliases dispatch to the canonical handler', () => { logSpy.mockRestore() }) - it('runs `worktree remove` as the canonical `worktree rm` (the incident)', async () => { - queueFixtures( - callMock, - okFixture('req_show', { worktree: { hostId: 'local' } }), - okFixture('req', { removed: true }) - ) - - await main(['worktree', 'remove', '--worktree', 'id:wt-1', '--force', '--json'], '/tmp/repo') - - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.rm', - expect.objectContaining({ worktree: 'id:wt-1', hostId: 'local', force: true }), - expect.anything() - ) - }) - - it('asks the host to reply with the delete outcome and waits past Git deletion (#35135)', async () => { - queueFixtures( - callMock, - okFixture('req_show', { worktree: { hostId: 'local' } }), - okFixture('req', { removed: true }) - ) - - await main(['worktree', 'rm', '--worktree', 'id:wt-1', '--run-hooks'], '/tmp/repo') - - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.rm', - expect.objectContaining({ waitForBackgroundRemoval: true }), - { - timeoutMs: worktreeRemovalReplyTimeoutMs(true), - requestSelection: { - paramsForStatus: expect.any(Function), - onDispatch: expect.any(Function) - } - } - ) - expect(logSpy).toHaveBeenCalledWith('removed: true') - }) - - it('does not say removed when an older host only accepted a background removal', async () => { - queueFixtures( - callMock, - okFixture('req_show', { worktree: { hostId: 'local' } }), - okFixture('req', { removed: true, removing: true }) - ) - - await main(['worktree', 'rm', '--worktree', 'id:wt-1'], '/tmp/repo') - - expect(logSpy).toHaveBeenCalledWith( - 'removed: false\nOrca is still deleting the checkout in the background.' - ) - }) - - it('leaves missing removal and branch outcomes unconfirmed', async () => { - queueFixtures( - callMock, - okFixture('show', { worktree: { hostId: 'local' } }), - okFixture('rm', {}) - ) - await main(['worktree', 'rm', '--worktree', 'id:wt-1', '--delete-branch'], '/tmp/repo') - expect(logSpy).toHaveBeenCalledWith('Removal is not confirmed.') - queueFixtures( - callMock, - okFixture('show', { worktree: { hostId: 'local' } }), - okFixture('rm', {}) - ) - await main(['worktree', 'rm', '--worktree', 'id:wt-1', '--json'], '/tmp/repo') - expect(JSON.parse(String(logSpy.mock.calls.at(-1)?.[0])).result).toEqual({}) - }) - it('fails closed when worktree removal cannot resolve a host', async () => { queueFixtures(callMock, okFixture('req_show', { worktree: { id: 'wt-1' } })) const priorExitCode = process.exitCode @@ -167,49 +79,6 @@ describe('command aliases dispatch to the canonical handler', () => { } }) - it('exits non-zero when worktree removal is refused by a failed archive hook', async () => { - const { RuntimeRpcFailureError } = await import('./runtime/types.js') - queueFixtures(callMock, okFixture('req_show', { worktree: { hostId: 'local' } })) - callMock.mockRejectedValueOnce( - new RuntimeRpcFailureError({ - id: 'req_archive', - ok: false, - error: { - code: 'worktree_archive_hook_failed', - message: 'Archive hook failed for worktree: /tmp/wt — exited 23.' - }, - _meta: { runtimeId: 'runtime-1' } - }) - ) - const priorExitCode = process.exitCode - - try { - await main( - ['worktree', 'rm', '--worktree', 'id:wt-1', '--force', '--run-hooks', '--json'], - '/tmp/repo' - ) - - expect(process.exitCode).toBe(1) - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.rm', - expect.objectContaining({ - runHooks: true, - allowFailedArchiveHook: false - }), - expect.anything() - ) - expect(JSON.parse(String(logSpy.mock.calls.at(-1)?.[0]))).toMatchObject({ - id: 'req_archive', - ok: false, - error: { code: 'worktree_archive_hook_failed' }, - _meta: { runtimeId: 'runtime-1' } - }) - } finally { - process.exitCode = priorExitCode - } - }) - it('rejects the archive-hook waiver without --run-hooks instead of ignoring it', async () => { queueFixtures(callMock, okFixture('req_show', { worktree: { hostId: 'local' } })) const priorExitCode = process.exitCode @@ -233,345 +102,4 @@ describe('command aliases dispatch to the canonical handler', () => { process.exitCode = priorExitCode } }) - - it('forwards the explicit archive-hook waiver on worktree rm', async () => { - queueFixtures( - callMock, - okFixture('req_show', { worktree: { hostId: 'local' } }), - okFixture('req', { removed: true }) - ) - - await main( - [ - 'worktree', - 'rm', - '--worktree', - 'id:wt-1', - '--run-hooks', - '--allow-failed-archive-hook', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.rm', - expect.objectContaining({ runHooks: true, allowFailedArchiveHook: true }), - expect.anything() - ) - }) - - it('serves `agent-context --json` without contacting the runtime', async () => { - runtimeClientConstructorMock.mockClear() - await main(['agent-context', '--json'], '/tmp/repo') - - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - const schema = JSON.parse(String(logSpy.mock.calls.at(-1)?.[0])) - expect(schema.schemaVersion).toBe(1) - const rm = schema.commands.find( - (command: { command: string }) => command.command === 'worktree rm' - ) - expect(rm.aliases).toContainEqual(['worktree', 'remove']) - }) - - it('keeps `agent-context` local when remote environment variables are set', async () => { - vi.stubEnv('ORCA_PAIRING_CODE', 'pairing-code') - vi.stubEnv('ORCA_ENVIRONMENT', 'stale-environment') - try { - await main(['agent-context', '--json'], '/tmp/repo') - - expect(process.exitCode).not.toBe(1) - expect(callMock).not.toHaveBeenCalled() - } finally { - vi.unstubAllEnvs() - } - }) -}) - -describe('artifact runtime routing', () => { - afterEach(() => { - vi.unstubAllEnvs() - vi.restoreAllMocks() - process.exitCode = 0 - }) - - it('uses the desktop runtime despite remote-selection environment fallbacks', async () => { - vi.stubEnv('ORCA_ENVIRONMENT', 'remote-environment') - vi.stubEnv('ORCA_PAIRING_CODE', 'remote-pairing-code') - vi.spyOn(console, 'log').mockImplementation(() => undefined) - callMock.mockResolvedValue( - okFixture('artifact-list', { status: 'ok', value: { artifacts: [] } }) - ) - runtimeClientConstructorMock.mockClear() - - await main(['artifacts', 'list', '--json'], '/folder-workspace') - - expect(process.exitCode).not.toBe(1) - expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, null) - expect(callMock).toHaveBeenCalledWith('artifacts.list', {}) - }) -}) - -describe('unknown command surfaces a suggestion', () => { - let errorSpy: ReturnType - - beforeEach(() => { - callMock.mockReset() - errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - afterEach(() => { - errorSpy.mockRestore() - process.exitCode = 0 - }) - - it('prints did-you-mean for a near-miss command and exits non-zero', async () => { - await main(['worktree', 'remov'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(stderr).toContain('Unknown command: worktree remov') - expect(stderr).toContain('orca worktree') - }) - - it.each([ - ['orchestration resume', 'orchestration reset'], - ['artifacts deset', 'artifacts delete'], - ['emulator ball', 'emulator kill'], - ['emulator showdown', 'emulator shutdown'], - ['orchestration worker-showw', 'orchestration worker-stop'], - ['orchestration worker-relay', 'orchestration worker-release'], - ['tab clues', 'tab close'], - ['environment rollbook', 'environment rollback'], - ['linear relation move', 'linear relation remove'] - ])('keeps %s recovery away from %s before runtime lookup', async (input, forbidden) => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - runtimeClientConstructorMock.mockClear() - try { - await main([...input.split(' '), '--json'], '/tmp/repo') - expect(process.exitCode).toBe(1) - const output = logSpy.mock.calls.flat().join('\n') - expect(output).toContain('invalid_argument') - expect(JSON.parse(output)).toHaveProperty('ok', false) - expect(output).not.toContain(`orca ${forbidden}`) - expect(output).not.toContain(`"${forbidden}"`) - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - } finally { - logSpy.mockRestore() - } - - await main(input.split(' '), '/tmp/repo') - expect(errorSpy.mock.calls.flat().join('\n')).not.toContain(`orca ${forbidden}`) - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - }) - - it('reports a mistyped pre-command flag without swallowing the command', async () => { - await main(['--jso', 'worktree', 'list'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(stderr).toContain('Unknown flag --jso for command: worktree list') - expect(stderr).toContain('--json') - }) - - it('names the offending --worktree value and the valid forms on selector_not_found', async () => { - const stdoutSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const { RuntimeRpcFailureError } = await import('./runtime/types.js') - callMock.mockRejectedValue( - new RuntimeRpcFailureError({ - id: 'req_selector', - ok: false, - error: { code: 'selector_not_found', message: 'selector_not_found' }, - _meta: { runtimeId: 'runtime_local' } - }) - ) - - await main( - [ - 'orchestration', - 'worker-start', - '--task', - 't1', - '--worktree', - 'repo-1', - '--agent', - 'codex', - '--from', - 'term-caller' - ], - '/tmp/repo' - ) - - expect(process.exitCode).toBe(1) - // Orchestration failures keep one stderr line and print the recovery detail on stdout. - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - const stdout = stdoutSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(callMock).toHaveBeenCalledExactlyOnceWith( - 'orchestration.workerStart', - expect.objectContaining({ worktree: 'repo-1', from: 'term-caller' }) - ) - expect(stderr).toBe('error: selector_not_found: selector_not_found') - expect(stdout).toContain('No Orca workspace matched the worktree selector "repo-1"') - expect(stdout).toContain('id:repo-1::') - expect(stdout).toContain('Valid selector forms:') - }) - - it('reports a pre-command flag that belongs to another command', async () => { - await main(['--workspace', 'worktree', 'list'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(stderr).toContain('Unknown flag --workspace for command: worktree list') - }) - - it('reports a pre-command typo when a global flag splits the command path', async () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['--jso', 'worktree', '--json', 'list'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - expect(logSpy.mock.calls.flat().join('\n')).toContain( - 'Unknown flag --jso for command: worktree list' - ) - expect(callMock).not.toHaveBeenCalled() - logSpy.mockRestore() - }) - - it.each(['environment', 'pairing-code'])( - 'rejects --%s without a selector before runtime construction', - async (flag) => { - runtimeClientConstructorMock.mockClear() - - await main([`--${flag}`, 'worktree', 'list'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(stderr).toContain(`Flag --${flag} requires a value.`) - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - } - ) -}) - -describe('unknown help command surfaces a suggestion', () => { - it.each([ - ['help prefix', ['help', 'worktree', 'remov']], - ['help flag', ['worktree', 'remov', '--help']] - ])('prints did-you-mean for the %s form', async (_label, argv) => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(argv, '/tmp/repo') - - expect(process.exitCode).toBe(1) - expect(logSpy.mock.calls.flat().join('\n')).toContain('Did you mean: orca worktree') - logSpy.mockRestore() - process.exitCode = 0 - }) -}) - -describe('nested command group help', () => { - it.each([ - ['browser', ['browser', '--help'], ['identity get', 'identity set']], - ['browser identity', ['browser', 'identity', '--help'], ['get', 'set']], - ['browser', ['browser'], ['identity get', 'identity set']], - ['skills', ['skills'], ['installed', 'share']], - ['browser identity', ['browser', 'identity'], ['get', 'set']] - ])( - 'prints successful help for %s without constructing a runtime client', - async (path, argv, commands) => { - const previousExitCode = process.exitCode - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - runtimeClientConstructorMock.mockClear() - process.exitCode = 0 - - try { - await main(argv, '/tmp/repo') - - expect(process.exitCode).toBe(0) - const output = logSpy.mock.calls.flat().join('\n') - expect(output).toContain(`orca ${path}`) - for (const command of commands) { - expect(output).toContain(command) - } - expect(output).not.toContain('Unknown command') - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - } finally { - process.exitCode = previousExitCode - logSpy.mockRestore() - } - } - ) - - it('reports a flagged bare group as a missing subcommand, not a typo', async () => { - const previousExitCode = process.exitCode - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - runtimeClientConstructorMock.mockClear() - process.exitCode = 0 - - try { - await main(['skills', '--worktree', 'active'], '/tmp/repo') - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.flat().join('\n') - expect(stderr).toContain('Missing subcommand for: orca skills') - expect(stderr).toContain('orca skills --help') - expect(stderr).not.toContain('Did you mean') - expect(runtimeClientConstructorMock).not.toHaveBeenCalled() - } finally { - process.exitCode = previousExitCode - errorSpy.mockRestore() - } - }) - - it('keeps an executable leaf ahead of its child groups', async () => { - const previousExitCode = process.exitCode - process.exitCode = 0 - serveOrcaAppMock.mockClear().mockResolvedValue(0) - - try { - await main(['serve'], '/tmp/repo') - - expect(process.exitCode).toBe(0) - expect(serveOrcaAppMock).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ json: false }) - ) - } finally { - process.exitCode = previousExitCode - serveOrcaAppMock.mockReset() - } - }) - - it('passes --bind to serve only when given, and refuses it with --mobile-pairing before launching', async () => { - const previousExitCode = process.exitCode - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - serveOrcaAppMock.mockClear().mockResolvedValue(0) - - try { - process.exitCode = 0 - await main(['serve'], '/tmp/repo') - expect(serveOrcaAppMock).toHaveBeenLastCalledWith(expect.objectContaining({ bind: null })) - - await main(['serve', '--bind', 'localhost'], '/tmp/repo') - expect(serveOrcaAppMock).toHaveBeenLastCalledWith( - expect.objectContaining({ bind: '127.0.0.1' }) - ) - expect(serveOrcaAppMock).toHaveBeenCalledTimes(2) - - await main(['serve', '--bind', '127.0.0.1', '--mobile-pairing'], '/tmp/repo') - expect(serveOrcaAppMock).toHaveBeenCalledTimes(2) - expect(process.exitCode).toBe(1) - expect(errorSpy.mock.calls.flat().join('\n')).toContain( - '--mobile-pairing needs --bind 0.0.0.0' - ) - } finally { - process.exitCode = previousExitCode - errorSpy.mockRestore() - serveOrcaAppMock.mockReset() - } - }) }) diff --git a/src/cli/runtime/serve-orcad-launch.test.ts b/src/cli/runtime/serve-orcad-launch.test.ts deleted file mode 100644 index dee24749289..00000000000 --- a/src/cli/runtime/serve-orcad-launch.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { formatServeRuntimeSelection } from '../../shared/orcad-local-serve-selection' -import type { runProcess } from '@orca/process-host' -import { resolveLocalServeRuntime } from './serve-orcad-launch' - -type RunProcess = typeof runProcess - -function answering(stdout: string, code = 0): RunProcess { - return vi.fn(async () => ({ - code, - signal: null, - stdout, - stderr: '', - timedOut: false - })) -} - -const options = { - executable: '/Applications/Orca.app/Contents/MacOS/Orca', - appRoot: '/Applications/Orca.app/Contents/Resources/app.asar', - userDataPath: '/Users/u/Library/Application Support/orca', - usesMacUpdateHandoff: false -} - -describe('orca serve asking the app which host to run', () => { - it('keeps packaged macOS on Electron without starting the app to ask', async () => { - const run = answering('') - expect(await resolveLocalServeRuntime({ ...options, usesMacUpdateHandoff: true }, run)).toEqual( - { - kind: 'electron', - reason: expect.stringContaining('packaged macOS') - } - ) - expect(run).not.toHaveBeenCalled() - }) - - it('asks the app on packaged macOS when orcad is requested explicitly', async () => { - const selection = { - kind: 'orcad' as const, - runtime: '/rt/node', - entry: '/slot/orcad.js', - version: '1' - } - const run = answering(formatServeRuntimeSelection(selection)) - expect( - await resolveLocalServeRuntime( - { ...options, usesMacUpdateHandoff: true, env: { ORCA_SERVE_RUNTIME: 'orcad' } }, - run - ) - ).toEqual(selection) - }) -}) diff --git a/src/cli/specs/account.test.ts b/src/cli/specs/account.test.ts deleted file mode 100644 index db57f2f60be..00000000000 --- a/src/cli/specs/account.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { ACCOUNT_COMMAND_SPECS } from './account' -import { suggestCommands, unknownCommandData } from '../command-suggestion' - -describe('account command specs', () => { - it.each(['move', 'go'])( - 'suggestion safety keeps benign account %s mistakes out of profile deletion', - (verb) => { - const path = ['account', verb] - expect(suggestCommands(ACCOUNT_COMMAND_SPECS, path)).not.toContain('account rm') - expect(suggestCommands(ACCOUNT_COMMAND_SPECS, path)).not.toContain('account remove') - const data = unknownCommandData(ACCOUNT_COMMAND_SPECS, path) - expect(data.nextSteps.join(' ')).not.toContain('orca account rm') - expect(data.nextSteps.join(' ')).not.toContain('orca account remove') - } - ) -}) diff --git a/src/main/acp/discovery/acp-at-rest-commands.test.ts b/src/main/acp/discovery/acp-at-rest-commands.test.ts index e2a3f96d360..d9088217ac9 100644 --- a/src/main/acp/discovery/acp-at-rest-commands.test.ts +++ b/src/main/acp/discovery/acp-at-rest-commands.test.ts @@ -5,13 +5,11 @@ import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import capture from '../../../shared/__fixtures__/omp-native-commands.json' import '../../../shared/priority-semaphore' -import { refreshAtRestCommandContext } from '../../native-chat/agent-session-wire/options/at-rest-command-context' import { commandDiscoveryRig, DISCOVERY_SESSION, ompRecord } from './testing/acp-command-discovery.test-fixture' -import { deferred, tick } from '../process/testing/acp-scripted-agent.test-support' import { acpLaunchSpecFor } from '../launch/acp-launch-registry' import { readAcpForkSupport } from '../capabilities/acp-fork-support' import { agentSessionRecordFixture } from '../../native-chat/agent-session-record-test-fixture' @@ -26,7 +24,6 @@ vi.mock('node:fs/promises', async (importOriginal) => { }) const rigs: Awaited>[] = [] -// Let real filesystem/protocol I/O finish without advancing the attempt's fake clock. async function rig(...args: Parameters) { const opened = await commandDiscoveryRig(...args) @@ -34,7 +31,6 @@ async function rig(...args: Parameters) { return opened } afterEach(async () => { - vi.useRealTimers() await Promise.all(rigs.splice(0).map((rig) => rig.dispose())) vi.restoreAllMocks() }) @@ -97,50 +93,6 @@ it('observes pre-initialize reports, validates session identity and keeps the la expect(children[0]!.lastCloseResult).toEqual({ root: 'exited', tree: null }) }) -it('starts the 9 second deadline before readiness and cwd resolution', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const readiness = deferred() - const refreshing = refreshAtRestCommandContext(() => readiness.promise) - const cwd = deferred() - const resolveWorkspacePath = vi.fn(() => cwd.promise) - const { catalog, children } = await rig(undefined, { resolveWorkspacePath }) - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const first = catalog.settled(ompRecord('waiting-ready'), 10_000) - await vi.advanceTimersByTimeAsync(9_000) - expect(await first).toBeUndefined() - readiness.resolve() - await refreshing - expect(resolveWorkspacePath).not.toHaveBeenCalled() - const second = catalog.settled(ompRecord('waiting-cwd'), 10_000) - await vi.advanceTimersByTimeAsync(9_000) - expect(await second).toBeUndefined() - cwd.resolve('/work/late') - await tick() - expect(children).toEqual([]) -}) - -it('answers before slow close, cancels queued deadlines and drains stop without launching waiters', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const close = deferred() - const { catalog, children } = await rig((child) => { - const prove = child.proveClose - child.proveClose = async () => { - await close.promise - return prove() - } - }) - expect(await catalog.settled(ompRecord('one'), 1_000)).toBeDefined() - expect(await catalog.settled(ompRecord('two'), 1_000)).toBeDefined() - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const queued = catalog.settled(ompRecord('queued'), 10_000) - await vi.advanceTimersByTimeAsync(9_000) - expect(await queued).toBeUndefined() - const stop = catalog.closeAll() - close.resolve() - await stop - expect(children).toHaveLength(2) -}) - it('handles actual root exit just before listener registration without changing historical evidence', async () => { const evidence = Object.freeze({ root: 'live' as const, tree: 'unverifiable' as const }) const { catalog, children, root } = await rig((child) => { diff --git a/src/main/acp/discovery/acp-model-catalog-probe.test.ts b/src/main/acp/discovery/acp-model-catalog-probe.test.ts deleted file mode 100644 index c673142adeb..00000000000 --- a/src/main/acp/discovery/acp-model-catalog-probe.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { mkdtemp, readdir, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, describe, expect, it, vi, type Mock } from 'vitest' -import { acpLaunchSpecFor } from '../launch/acp-launch-registry' -import type { AcpLaunchSpec } from '../launch/acp-launch-contract' -import { - createAcpModelCatalogProbe, - type AcpModelCatalogProbeDeps -} from './acp-model-catalog-probe' -import { AcpSessionRuntime } from '../protocol/acp-session-runtime' -import { AcpScriptedAgent } from '../process/testing/acp-scripted-agent.test-support' -import type { ProviderProcessLaunch } from '../../provider-process/provider-process-launch' -import { openCodeAcpAccountBinding } from '../../opencode/opencode-structured-account-home' -import recordedEfforts from '../fixtures/opencode-v2.0.21-model-efforts.json' -// Bypass the app's managed-account service for this fixture. -const OPENCODE: AcpLaunchSpec = { - ...acpLaunchSpecFor('opencode')!, - account: openCodeAcpAccountBinding(() => ({ - list: () => ({ activeAccountId: null, accounts: [] }), - restoreOriginalEnvironment: () => {}, - environmentForAccount: () => ({}) - })) -} - -const agents: AcpScriptedAgent[] = [] -afterEach(() => { - vi.restoreAllMocks() - for (const agent of agents.splice(0)) { - agent.close() - } -}) - -function scriptedOpenCode2(canDelete: boolean): { - agent: AcpScriptedAgent - launches: ProviderProcessLaunch[] - closed: () => number - deps: AcpModelCatalogProbeDeps & { - runListing: Mock> - } -} { - const agent = new AcpScriptedAgent() - agents.push(agent) - agent.on('initialize', (frame) => - agent.reply(frame, { - protocolVersion: 1, - agentCapabilities: { - sessionCapabilities: canDelete ? { delete: {} } : {} - } - }) - ) - agent.on('session/new', (frame) => - agent.reply(frame, { - sessionId: 'probe-session', - configOptions: [ - { - id: 'model', - name: 'Model', - category: 'model', - type: 'select', - currentValue: 'opencode/exo-free', - options: [ - { value: 'opencode/big-pickle', name: 'Big Pickle' }, - { value: 'opencode/exo-free', name: 'Exo Free' } - ] - } - ] - }) - ) - agent.on('session/delete', (frame) => agent.reply(frame, {})) - agent.on('session/set_config_option', (frame) => agent.fail(frame, -32602, 'Model unavailable')) - const launches: ProviderProcessLaunch[] = [] - let closes = 0 - return { - agent, - launches, - closed: () => closes, - deps: { - resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }), - resolveCommand: () => '/opt/opencode/bin/opencode', - probeVersion: async () => ({ version: '2.0.29' }), - homePath: '/home/user', - dataDirectory: '/orca-data', - runListing: vi.fn>(), - connectSession: (launch) => { - launches.push(launch) - const runtime = new AcpSessionRuntime(agent.stdout, agent.stdin) - return { - initialize: () => runtime.initialize(), - start: (options) => runtime.start(options), - setConfigOption: (id, value) => runtime.setConfigOption(id, value), - deleteSession: (sessionId) => runtime.deleteSession(sessionId), - close: async () => { - closes += 1 - runtime.close() - } - } - } - } - } -} - -describe('ACP model catalog probes', () => { - it('deletes a session before closing when cancelled during effort discovery', async () => { - vi.useFakeTimers() - try { - const { agent, deps, closed } = scriptedOpenCode2(true) - agent.on('session/new', (frame) => - agent.reply(frame, { sessionId: 'probe-session', ...recordedEfforts.new }) - ) - agent.on('session/set_config_option', () => {}) - agent.on('session/delete', (frame) => { - expect(closed()).toBe(0) - agent.reply(frame, {}) - }) - const stop = new AbortController() - const listing = createAcpModelCatalogProbe(OPENCODE, deps)( - { kind: 'opencode', locator: { kind: 'unmanaged' } }, - { workspacePath: '/work/project', signal: stop.signal } - ) - const rejected = expect(listing).rejects.toThrow(/listing stopped/) - await vi.waitFor(() => - expect(agent.frames.map((frame) => frame.method)).toContain('session/set_config_option') - ) - stop.abort() - await rejected - expect(agent.frames.at(-1)?.method).toBe('session/delete') - expect(closed()).toBe(1) - await vi.runAllTimersAsync() - } finally { - vi.useRealTimers() - } - }) - - it('lists OMP from a session kept in a folder it removes, in the chat folder', async () => { - const { agent, deps, launches } = scriptedOpenCode2(false) - const dataDirectory = await mkdtemp(join(tmpdir(), 'orca-omp-listing-')) - try { - const success = await createAcpModelCatalogProbe(acpLaunchSpecFor('omp')!, { - ...deps, - dataDirectory, - resolveCommand: () => '/opt/omp/bin/omp', - probeVersion: async () => ({ version: '18.12.2' }) - })( - { variable: 'PI_CODING_AGENT_DIR', path: '/homes/omp' }, - { workspacePath: '/work/project' } - ) - expect(agent.frames.map((frame) => frame.method)).toEqual(['initialize', 'session/new']) - expect(agent.frames[1]!.params).toMatchObject({ cwd: '/work/project' }) - const root = join(dataDirectory, 'acp-listing-sessions', 'omp') - expect(launches).toEqual([ - expect.objectContaining({ - args: ['acp', '--session-dir', expect.stringMatching(/run-/)] - }) - ]) - expect(dirname(launches[0]!.args[2]!)).toBe(root) - expect(await readdir(root)).toEqual([]) - expect(success.models.map((model) => model.id)).toEqual([ - 'opencode/big-pickle', - 'opencode/exo-free' - ]) - } finally { - await rm(dataDirectory, { recursive: true, force: true }) - } - }) - - // An interrupted create can save a session without returning its ID. - it('stops a listing cut off while OpenCode 2.x creates its session, without deleting', async () => { - const { agent, deps, closed } = scriptedOpenCode2(true) - agent.on('session/new', () => {}) - const stop = new AbortController() - const listing = createAcpModelCatalogProbe(OPENCODE, deps)( - { kind: 'opencode', locator: { kind: 'unmanaged' } }, - { workspacePath: '/work/project', signal: stop.signal } - ) - await vi.waitFor(() => - expect(agent.frames.map((frame) => frame.method)).toContain('session/new') - ) - stop.abort() - await expect(listing).rejects.toThrow(/listing stopped/) - expect(closed()).toBe(1) - expect(agent.frames.map((frame) => frame.method)).not.toContain('session/delete') - }) -}) diff --git a/src/main/acp/journal/acp-structured-child-work-admission.test.ts b/src/main/acp/journal/acp-structured-child-work-admission.test.ts deleted file mode 100644 index 69a1a4e8b33..00000000000 --- a/src/main/acp/journal/acp-structured-child-work-admission.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { - closeProviderTimelineRigs, - openProviderTimelineRig, - refusingSink -} from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import { AcpStructuredLane } from './acp-structured-lane' -import type { ProviderTimelineEvent } from '../../native-chat/agent-session-timeline/provider-timeline-event' -import { GROK_ACP_DIALECT } from '../acp-dialects/grok-dialect' -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' - -const lanes: AcpStructuredLane[] = [] -afterEach(async () => { - lanes.splice(0).forEach((lane) => lane.dispose()) - await closeProviderTimelineRigs() -}) - -function subagent( - lane: AcpStructuredLane, - state: 'working' | 'completed' -): ProviderTimelineEvent[] { - const update = - state === 'working' - ? { sessionUpdate: 'subagent_spawned', subagent_id: 'child', description: 'Exact label' } - : { sessionUpdate: 'subagent_finished', subagent_id: 'child', status: 'completed' } - return lane.translator.notification( - '_x.ai/session/update', - { sessionId: 'provider-session-1', update }, - 1 - ) -} - -async function fixture(reason: 'backpressure' | 'failed' = 'backpressure') { - const rig = await openProviderTimelineRig() - const delivery: AgentChildWorkEvidence[][] = [] - const refused = { value: false } - const failed = vi.fn() - const lane = new AcpStructuredLane({ - sink: refusingSink(rig.sink, () => refused.value, reason), - sessionId: 'session-timeline', - providerSessionId: 'provider-session-1', - agent: 'grok', - agentName: 'Grok', - generation: 'gen-1', - dialect: GROK_ACP_DIALECT, - logger: recordingStructuredAgentSessionLogger().logger, - onInputAccepted: () => {}, - onFailed: failed, - onChildWorkEvidence: (evidence) => delivery.push(evidence), - now: () => 10 - }) - lanes.push(lane) - return { rig, lane, refused, delivery, failed } -} - -describe('ACP subagent evidence at the ordered journal boundary', () => { - it('holds working and finished snapshots in order across backpressure and publishes each once', async () => { - const { rig, lane, refused, delivery } = await fixture() - refused.value = true - lane.apply(subagent(lane, 'working')) - lane.apply(subagent(lane, 'completed')) - await rig.rows() - expect(delivery).toEqual([]) - refused.value = false - lane.retry() - await rig.rows() - expect(delivery.map((batch) => batch.map((edge) => edge.type))).toEqual([['live'], ['ended']]) - expect(delivery[0][0]).toMatchObject({ child: { kind: 'agent', description: 'Exact label' } }) - expect(delivery[1][0]).toMatchObject({ outcome: 'succeeded' }) - lane.retry() - await rig.rows() - expect(delivery).toHaveLength(2) - }) - - it('publishes no subagent facts for fatal refusal, disposed held events or events dropped after session end', async () => { - const fatal = await fixture('failed') - fatal.refused.value = true - fatal.lane.apply(subagent(fatal.lane, 'working')) - await fatal.rig.rows() - expect(fatal.failed).toHaveBeenCalledWith('failed') - expect(fatal.delivery).toEqual([]) - const held = await fixture() - held.refused.value = true - held.lane.apply(subagent(held.lane, 'working')) - held.lane.dispose() - held.refused.value = false - held.lane.retry() - await held.rig.rows() - expect(held.delivery.flat().map((edge) => edge.type)).toEqual(['session-ended']) - const ended = await fixture() - ended.lane.apply([ - { type: 'session.ended', verdict: { state: 'interrupted', completedAt: 10 } } - ]) - await ended.rig.rows() - ended.lane.apply(subagent(ended.lane, 'working')) - await ended.rig.rows() - expect(ended.delivery.flat().map((edge) => edge.type)).toEqual(['session-ended']) - }) - - it('does not let a throwing optional evidence consumer poison the journal', async () => { - const { rig, lane } = await fixture() - const failure = vi.fn() - const throwing = new AcpStructuredLane({ - sink: rig.sink, - sessionId: 'session-timeline', - providerSessionId: 'provider-session-1', - agent: 'grok', - agentName: 'Grok', - generation: 'gen-2', - dialect: GROK_ACP_DIALECT, - logger: recordingStructuredAgentSessionLogger().logger, - onInputAccepted: () => {}, - onFailed: failure, - onChildWorkEvidence: () => { - throw new Error('sink unavailable') - }, - onChildWorkFailure: failure - }) - lane.dispose() - lanes.push(throwing) - throwing.apply(subagent(throwing, 'working')) - throwing.apply(subagent(throwing, 'completed')) - throwing.apply([{ type: 'turn.open', turn: 'turn', at: 2 }]) - expect((await rig.rows()).map((row) => row.body)).toMatchObject([ - { kind: 'turn', turnId: 'p:provider-session-1:turn', state: 'running', startedAt: 2 } - ]) - expect(failure).toHaveBeenCalledTimes(2) - }) - - it('releases live ownership when session-end admission is held and disposal ends observation', async () => { - const { rig, lane, refused, delivery } = await fixture() - lane.apply(subagent(lane, 'working')) - await rig.rows() - refused.value = true - lane.apply([{ type: 'session.ended', verdict: { state: 'interrupted', completedAt: 20 } }]) - lane.dispose() - await rig.rows() - expect(delivery.flat().map((edge) => edge.type)).toEqual(['live', 'session-ended']) - lane.apply(subagent(lane, 'working')) - lane.retry() - await rig.rows() - expect(delivery.flat().map((edge) => edge.type)).toEqual(['live', 'session-ended']) - }) -}) diff --git a/src/main/acp/launch/acp-structured-launch-resolution.test.ts b/src/main/acp/launch/acp-structured-launch-resolution.test.ts deleted file mode 100644 index de757978532..00000000000 --- a/src/main/acp/launch/acp-structured-launch-resolution.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { createAcpStructuredLaunchResolver } from '../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, onTestFinished, vi } from 'vitest' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import type { JournalLoad } from '../../native-chat/agent-session-journal/replay/journal-open' -import { acpLaunchSpecFor } from './acp-launch-registry' - -const GROK = acpLaunchSpecFor('grok')! -const OMP = acpLaunchSpecFor('omp')! -const identity = { - sessionId: 'session-alpha-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'grok', - providerHandle: null -} - -function grokRecord(overrides: Partial = {}): AgentSessionRecord { - return { - ...agentSessionRecordFixture(), - provider: 'grok', - providerHandleChain: [], - accountHome: { variable: 'GROK_HOME', path: '/home/user/.grok-work' }, - ...overrides - } -} - -function ompRecord(options: Record, resumes: boolean): AgentSessionRecord { - return grokRecord({ - provider: 'omp', - accountHome: { variable: 'PI_CODING_AGENT_DIR', path: '/home/user/.omp/agent' }, - options, - providerHandleChain: resumes - ? [ - { - linkId: 'link-created', - origin: 'created', - mintedAtFence: 1, - observedAt: 1, - handle: { transport: 'acp', agent: 'omp', nativeId: 'omp-1' } - } - ] - : [] - }) -} - -function resolver( - record: AgentSessionRecord, - readJournal: () => JournalLoad | null = () => null, - spec = GROK -) { - const searched: (string | null | undefined)[] = [] - return { - searched, - resolve: createAcpStructuredLaunchResolver(spec, { - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - readJournal, - resolveWorkspacePath: async () => '/repo/worktree', - resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }), - resolveLaunchEnv: () => ({ GROK_EXTRA: '1' }), - resolveCommand: (command, options) => { - searched.push(options?.pathEnv) - return `/resolved/${command}` - } - }) - } -} - -describe('ACP launch resolution', () => { - it('starts a new OMP chat with its saved model on the launch line, where OMP resolves roles', async () => { - const start = (resumes: boolean) => - resolver( - ompRecord({ model: '@worker_be', effort: 'medium' }, resumes), - () => null, - OMP - ).resolve({ identity }) - const fresh = await start(false) - expect(fresh.args.slice(-2)).toEqual(['--model', '@worker_be']) - expect(fresh.args).not.toContain('--thinking') - expect(fresh.launchModel).toBe('@worker_be') - // A load restores the conversation's own model; the session applies the saved one instead. - const resumed = await start(true) - expect(resumed.args).not.toContain('--model') - expect(resumed.launchModel).toBeUndefined() - }) -}) - -describe('ACP launch folder of a floating chat', () => { - const floating = (launchDirectory?: string) => - grokRecord({ - location: { ...grokRecord().location, workspaceId: FLOATING_TERMINAL_WORKTREE_ID }, - ...(launchDirectory ? { launchDirectory } : {}) - }) - const resolveIn = (record: AgentSessionRecord, currentSetting: string) => { - const resolveWorkspacePath = vi.fn(async () => currentSetting) - const pinLaunchDirectory = vi.fn() - const resolve = createAcpStructuredLaunchResolver(GROK, { - store: { getRecord: () => record, pinLaunchDirectory }, - readJournal: () => null, - resolveWorkspacePath, - resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }), - resolveCommand: (command) => `/resolved/${command}` - }) - return { resolve, resolveWorkspacePath, pinLaunchDirectory } - } - - it('launches in the folder the chat was pinned to after the floating setting moved', async () => { - const pinned = mkdtempSync(join(tmpdir(), 'orca-acp-floating-')) - try { - const { resolve, resolveWorkspacePath } = resolveIn(floating(pinned), '/floating/moved') - await expect(resolve({ identity })).resolves.toMatchObject({ cwd: pinned }) - expect(resolveWorkspacePath).not.toHaveBeenCalled() - } finally { - rmSync(pinned, { recursive: true, force: true }) - } - }) - - it('refuses with the folder-missing reason when the pinned folder is gone', async () => { - const gone = mkdtempSync(join(tmpdir(), 'orca-acp-floating-gone-')) - rmSync(gone, { recursive: true, force: true }) - onTestFinished(() => rmSync(gone, { recursive: true, force: true })) - const { resolve } = resolveIn(floating(gone), '/floating/moved') - await expect(resolve({ identity })).rejects.toMatchObject({ - name: 'AgentSessionPreSpawnError', - reason: 'launchFolderMissing' - }) - }) -}) diff --git a/src/main/acp/launch/acp-structured-managed-runtime.test.ts b/src/main/acp/launch/acp-structured-managed-runtime.test.ts deleted file mode 100644 index efbce8ec775..00000000000 --- a/src/main/acp/launch/acp-structured-managed-runtime.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { mkdir, mkdtemp, realpath, rm, truncate, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' -import { afterEach, expect, it, onTestFinished, vi } from 'vitest' -import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import { - RUNTIME_RELEASE_RECEIPT, - writeRuntimeReleaseReceipt -} from '../../node-runtime/managed-runtime-release' -import { createAcpStructuredLaunchResolver } from '../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { GROK, openAcpAdapterRig } from '../session/testing/acp-structured-adapter.test-support' - -afterEach(() => closeProviderTimelineRigs()) - -it('prefers the pin even when older, else a complete installed or external copy', async () => { - const dataDirectory = await mkdtemp(join(tmpdir(), 'orca-acp-managed-')) - onTestFinished(() => rm(dataDirectory, { recursive: true, force: true })) - const homePath = join(dataDirectory, 'home') - const command = `orca-managed-${basename(dataDirectory)}` - const root = join(dataDirectory, 'agent-runtimes', 'grok') - const pin = { - version: '1.0', - url: 'https://example.test/grok-1.0.zip', - archiveSha256: 'a'.repeat(64), - archiveBytes: 10, - members: [ - { path: command, sha256: 'b'.repeat(64), bytes: 6 }, - { path: 'harness', sha256: 'c'.repeat(64), bytes: 7 } - ] - } - const spec = { - ...GROK, - command, - managedRuntime: { label: 'Grok', root: () => root, pin: () => pin } - } - const spawn = async () => { - const resolveLaunch = createAcpStructuredLaunchResolver(spec, { - store: { - getRecord: () => ({ - ...agentSessionRecordFixture(), - provider: 'grok', - providerHandleChain: [], - accountHome: { variable: 'GROK_HOME', path: join(dataDirectory, '.grok') } - }), - pinLaunchDirectory: vi.fn() - }, - readJournal: () => null, - resolveEnvironment: async () => ({ PATH: '', HOME: homePath }), - dataDirectory - }) - const rig = await openAcpAdapterRig({ spec, deps: { resolveLaunch } }) - await rig.acquire() - return rig.child().launch.command - } - await expect(spawn()).rejects.toMatchObject({ reason: 'runtimeNotInstalled' }) - - // A server without its companion is an incomplete runtime. - const localBin = join(homePath, '.local', 'bin') - await mkdir(localBin, { recursive: true }) - await writeFile(join(localBin, command), '', { mode: 0o755 }) - await expect(spawn()).rejects.toMatchObject({ reason: 'runtimeNotInstalled' }) - - const fallback = join(root, '1.1') - await mkdir(fallback, { recursive: true }) - await writeFile(join(fallback, command), 'server', { mode: 0o755 }) - await writeFile(join(fallback, 'harness'), 'harness', { mode: 0o755 }) - await writeRuntimeReleaseReceipt(fallback, { - ...pin, - version: '1.1', - archiveSha256: 'd'.repeat(64) - }) - expect(await spawn()).toBe(join(fallback, command)) - - const release = join(root, '1.0') - await mkdir(release, { recursive: true }) - await writeFile(join(release, command), 'server', { mode: 0o755 }) - await writeFile(join(release, 'harness'), 'harness', { mode: 0o755 }) - await writeFile( - join(release, RUNTIME_RELEASE_RECEIPT), - JSON.stringify({ - releaseId: pin.archiveSha256, - version: '1.0', - platform: process.platform, - arch: process.arch, - members: pin.members.map(({ path, bytes }) => ({ path, bytes })) - }) - ) - await writeFile(join(localBin, 'harness'), '', { mode: 0o755 }) - expect(await spawn()).toBe(join(release, command)) - - await truncate(join(fallback, command), 2) - await truncate(join(release, command), 2) - expect(await spawn()).toBe(await realpath(join(localBin, command))) -}) diff --git a/src/main/acp/process/acp-agent-connection.test.ts b/src/main/acp/process/acp-agent-connection.test.ts index 64bbb38becf..32ce92d2885 100644 --- a/src/main/acp/process/acp-agent-connection.test.ts +++ b/src/main/acp/process/acp-agent-connection.test.ts @@ -217,21 +217,6 @@ describe('ACP process-owning connection', () => { }) }) -it('closes a recognized stdout prompt over 16 MiB without inventing a signed-out answer', async () => { - const answered = vi.fn() - const { connection, agent } = fixture({ - signIn: { - read: (line) => (line.startsWith('SIGN IN') ? 'prefix-only' : undefined), - answered - } - }) - await connection.start(start) - expect(answered).toHaveBeenCalledExactlyOnceWith(true) - agent.stdout.write(`SIGN IN ${'x'.repeat(16 * 1024 * 1024)}\n`) - await vi.waitFor(() => expect(connection.closed).toBe(true)) - expect(answered).toHaveBeenCalledTimes(1) -}) - it('keeps cached startup usable without advertising the configured method, but refuses unsupported required authentication', async () => { const { connection, agent } = fixture() agent.on('initialize', (frame) => diff --git a/src/main/acp/protocol/acp-session-lifecycle.test.ts b/src/main/acp/protocol/acp-session-lifecycle.test.ts index e83e321f4ec..2b598a60253 100644 --- a/src/main/acp/protocol/acp-session-lifecycle.test.ts +++ b/src/main/acp/protocol/acp-session-lifecycle.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished } from 'vitest' import { AcpSessionRuntime } from './acp-session-runtime' import type { AcpSessionRuntimeOptions } from './acp-session-runtime-options' @@ -7,17 +7,10 @@ import { deferred, tick } from '../process/testing/acp-scripted-agent.test-support' -import { AcpConnectionClosedError } from '../transport/acp-errors' -import type { RequestPermissionResponse } from '../generated/acp-protocol.generated' const opened: { close: () => void }[] = [] const startOptions = { cwd: '/runtime/project', mcpServers: [] } const prompt = [{ type: 'text', text: 'hello' }] as const -const permission = { - sessionId: 'session-1', - toolCall: { toolCallId: 'tool-1', title: 'Edit file' }, - options: [{ optionId: 'allow', name: 'Allow once', kind: 'allow_once' }] -} function fixture(options: AcpSessionRuntimeOptions = {}) { const agent = new AcpScriptedAgent() const runtime = new AcpSessionRuntime(agent.stdout, agent.stdin, options) @@ -31,114 +24,9 @@ afterEach(() => { .splice(0) .toReversed() .forEach((resource) => resource.close()) - vi.useRealTimers() }) describe('ACP caller-owned waits', () => { - it('keeps permission requests open beyond two minutes and delivers the late user decision', async () => { - vi.useFakeTimers() - const entered = deferred() - const decision = deferred() - const { agent, runtime } = fixture({ - onPermission: (_request, context) => { - entered.resolve(context.signal) - return decision.promise - } - }) - agent.on('session/prompt', () => {}) - await runtime.start(startOptions) - const pending = runtime.prompt([...prompt]) - const rejected = expect(pending).rejects.toBeInstanceOf(AcpConnectionClosedError) - let answered = false - const response = agent.request('permission', 'session/request_permission', permission) - void response.then(() => { - answered = true - }) - const signal = await entered.promise - await vi.advanceTimersByTimeAsync(120_001) - expect(signal.aborted).toBe(false) - expect(answered).toBe(false) - decision.resolve({ outcome: { outcome: 'selected', optionId: 'allow' } }) - expect(await response).toMatchObject({ - result: { outcome: { outcome: 'selected', optionId: 'allow' } } - }) - runtime.close() - await rejected - }) - - it('lets a streaming turn run beyond thirty minutes and keeps the session usable', async () => { - vi.useFakeTimers() - const onClose = vi.fn() - const event = vi.fn() - const { agent, runtime } = fixture({ onClose }) - runtime.subscribe(event) - agent.on('session/prompt', () => {}) - agent.on('session/set_mode', (frame) => agent.reply(frame, {})) - await runtime.start(startOptions) - let finished = false - const pending = runtime.prompt([...prompt]) - void pending.then(() => { - finished = true - }) - await vi.advanceTimersByTimeAsync(30 * 60_000 + 1) - agent.notify('session/update', { - sessionId: 'session-1', - update: { - sessionUpdate: 'agent_message_chunk', - content: { type: 'text', text: 'Still working' } - } - }) - expect(event).toHaveBeenCalledTimes(1) - expect(finished).toBe(false) - expect(onClose).not.toHaveBeenCalled() - expect(agent.frames.some((frame) => frame.method === 'session/cancel')).toBe(false) - await expect(runtime.setMode('plan')).resolves.toEqual({}) - const frame = agent.frames.find((frame) => frame.method === 'session/prompt') - expect(frame).toBeDefined() - if (frame) { - agent.reply(frame, { stopReason: 'end_turn' }) - } - await expect(pending).resolves.toEqual({ stopReason: 'end_turn' }) - }) - - it.each([ - { kind: 'new', expected: { kind: 'new', sessionId: 'session-1' } }, - { kind: 'load', expected: { kind: 'load', sessionId: 'saved-session' } }, - { kind: 'resume', expected: { kind: 'resume', sessionId: 'saved-session' } } - ] as const)( - 'opens a slow $kind session on its real answers, regardless of the peer default', - async ({ kind, expected }) => { - vi.useFakeTimers() - const { agent, runtime } = fixture({ peer: { requestTimeoutMs: 20 } }) - agent.on('initialize', (frame) => { - setTimeout( - () => - agent.reply(frame, { - protocolVersion: 1, - agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } } - }), - 75_000 - ) - }) - agent.on(`session/${kind}`, (frame) => { - setTimeout( - () => agent.reply(frame, kind === 'new' ? { sessionId: 'session-1' } : {}), - 310_000 - ) - }) - const started = expect( - runtime.start({ - ...startOptions, - ...(kind === 'new' ? {} : { sessionId: 'saved-session', resumePreference: kind }) - }) - ).resolves.toMatchObject(expected) - await vi.advanceTimersByTimeAsync(385_000) - await started - agent.on('session/prompt', (frame) => agent.reply(frame, { stopReason: 'end_turn' })) - await expect(runtime.prompt([...prompt])).resolves.toEqual({ stopReason: 'end_turn' }) - } - ) - it('keeps a handler answer that finishes saving after its owner withdraws requests', async () => { const withdrawal = new AbortController() const planEntered = deferred() diff --git a/src/main/acp/protocol/acp-session-runtime.test.ts b/src/main/acp/protocol/acp-session-runtime.test.ts index 18ed2cfb6e1..256d3dda7a4 100644 --- a/src/main/acp/protocol/acp-session-runtime.test.ts +++ b/src/main/acp/protocol/acp-session-runtime.test.ts @@ -2,7 +2,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { AcpConnectionClosedError } from '../transport/acp-errors' import { AcpSessionRuntime } from './acp-session-runtime' import type { AcpSessionRuntimeOptions } from './acp-session-runtime-options' -import type { AcpSessionEvent } from './acp-session-events' import { AcpScriptedAgent, deferred, @@ -83,61 +82,6 @@ describe('ACP session runtime', () => { expect(asked).toHaveLength(2) }) - it.each([ - ['code alone', true, { code: -32003, message: 'busy' }, -32003], - [ - 'reason alone', - true, - { code: -32603, message: 'busy', data: { reason: 'session_busy' } }, - -32603 - ], - ['prose', true, { code: -32603, message: 'Agent is already processing.' }, -32603], - [ - 'sign-in', - true, - { code: -32000, message: 'Sign in', data: { reason: 'session_busy' } }, - -32000 - ], - [ - 'malformed refusal', - true, - { code: '-32003', message: 'busy', data: { reason: 'session_busy' } }, - -32603 - ], - [ - 'no opt-in', - false, - { code: -32003, message: 'busy', data: { reason: 'session_busy' } }, - -32003 - ] - ] as const)('never replays %s', async (_label, retryBusyPrompts, error, code) => { - const { runtime, agent } = fixture({}, { retryBusyPrompts }) - await runtime.start(startOptions) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - agent.on('session/prompt', (frame) => - agent.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: frame.id, error })}\n`) - ) - await expect(runtime.prompt([...textPrompt])).rejects.toMatchObject({ code }) - await vi.advanceTimersByTimeAsync(60_000) - expect(agent.frames.filter((frame) => frame.method === 'session/prompt')).toHaveLength(1) - }) - - it('uses raw underscored extension methods and bounds control requests without closing the session', async () => { - const { runtime, agent } = fixture() - await runtime.initialize() - await runtime.start(startOptions) - agent.on('_x.ai/subagent/cancel', (frame) => { - expect(frame.params).toEqual({ subagentId: 'child' }) - }) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const call = runtime.requestExtension('_x.ai/subagent/cancel', { subagentId: 'child' }) - const rejected = expect(call).rejects.toThrow(/timed out|timeout/i) - await vi.advanceTimersByTimeAsync(30_000) - await rejected - expect(runtime.closed).toBe(false) - expect(() => runtime.requestExtension('x.ai/subagent/cancel', {})).toThrow('underscore') - }) - it('refuses unsupported restoration without silently creating a different session', async () => { const { runtime, agent } = fixture({ sessionCapabilities: { resume: null } }) await expect(runtime.start({ ...startOptions, sessionId: 'old' })).rejects.toMatchObject({ @@ -146,31 +90,6 @@ describe('ACP session runtime', () => { expect(agent.frames.map((frame) => frame.method)).toEqual(['initialize']) }) - it('authenticates once with a configured agent method and retries session setup', async () => { - const { runtime, agent } = fixture() - let authenticated = false - agent.on('initialize', (frame) => - agent.reply(frame, { protocolVersion: 1, authMethods: [{ id: 'login', name: 'Login' }] }) - ) - agent.on('session/new', (frame) => - authenticated - ? agent.reply(frame, { sessionId: 'session-1' }) - : agent.fail(frame, -32000, 'Login required') - ) - agent.on('authenticate', (frame) => { - authenticated = true - agent.reply(frame, {}) - }) - await runtime.start({ ...startOptions, authMethodId: 'login' }) - expect(agent.frames.map((frame) => frame.method)).toEqual([ - 'initialize', - 'session/new', - 'authenticate', - 'session/new' - ]) - expect(agent.frames[2].params).toEqual({ methodId: 'login' }) - }) - it('rejects unroutable permission requests and answers an unavailable selection cancelled', async () => { const diagnostics: string[] = [] const { runtime, agent } = fixture( @@ -202,36 +121,6 @@ describe('ACP session runtime', () => { await expect(runtime.prompt([...textPrompt])).rejects.toThrow('already in progress') }) - it('preserves unrecognized updates and isolates event listener failures', async () => { - const diagnostics: string[] = [] - const { runtime, agent } = fixture({}, { onDiagnostic: (message) => diagnostics.push(message) }) - const updates: AcpSessionEvent[] = [] - runtime.subscribe(() => { - throw new Error('Consumer failed') - }) - runtime.subscribe((event) => updates.push(event)) - await runtime.start(startOptions) - agent.notify('session/update', { - sessionId: 'session-1', - update: { sessionUpdate: 'agent_message_chunk', content: {} } - }) - agent.notify('session/update', { - sessionId: 'session-1', - update: { - sessionUpdate: 'agent_message_chunk', - content: { type: 'text', text: 'valid', _meta: { vendor: true } } - } - }) - expect(updates).toHaveLength(2) - expect(updates[0]).toMatchObject({ kind: 'unrecognized' }) - expect(updates[1]).toMatchObject({ - kind: 'known', - notification: { update: { content: { _meta: { vendor: true } } } } - }) - expect(diagnostics).toContain('Forwarded unrecognized ACP session update') - expect(diagnostics.some((message) => message.includes('Consumer failed'))).toBe(true) - }) - it('rejects pending calls and aborts permission hooks when protocol input ends', async () => { const requested = deferred() const { runtime, agent } = fixture( diff --git a/src/main/acp/session/acp-structured-antigravity.test.ts b/src/main/acp/session/acp-structured-antigravity.test.ts index 69a0272ca29..17a7524ca4d 100644 --- a/src/main/acp/session/acp-structured-antigravity.test.ts +++ b/src/main/acp/session/acp-structured-antigravity.test.ts @@ -1,5 +1,5 @@ import type { AntigravityChatAuthConfig } from '../../../shared/antigravity-chat-auth-config' -import { afterEach, expect, it, onTestFinished } from 'vitest' +import { afterEach, expect, it } from 'vitest' import { z } from 'zod' import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record' import { @@ -14,7 +14,6 @@ import { waitFor } from './testing/acp-structured-adapter.test-support' import { GrokFixtureReplay } from './testing/acp-structured-fixture-replay.test-support' -import { deferred } from '../process/testing/acp-scripted-agent.test-support' import { readAcpFixture, type AcpFixtureFrame @@ -26,7 +25,6 @@ const result = (frame: AcpFixtureFrame | undefined) => afterEach(closeProviderTimelineRigs) it.each<{ config: AntigravityChatAuthConfig | undefined; method: string }>([ - { config: undefined, method: 'oauth-personal' }, { config: { method: 'oauth-business', @@ -111,54 +109,6 @@ it("leaves a Full access host chat's plan approval to the person", async () => { expect(answered).toBe(false) }) -it('refuses a new start while its sign-in changes, and stops one already starting', async () => { - const gate = ANTIGRAVITY.launchGate! - const rig = await openAcpAdapterRig({ - spec: ANTIGRAVITY, - script: (agent) => agent.on('session/new', () => {}) - }) - const starting = rig.acquire() - await rig.frame('session/new') - const signIn = deferred() - onTestFinished(() => signIn.resolve()) - const operation = gate.run( - async () => {}, - () => signIn.promise - ) - await starting - expect(rig.openFailure()).toMatchObject({ name: 'AcpConnectionClosedError' }) - expect(rig.child().exited).toBe(true) - await expect(rig.acquire()).rejects.toMatchObject({ reason: 'accountSwitchInProgress' }) - signIn.resolve() - await operation - - const lateStart = gate.enter(undefined) - let left = false - onTestFinished(() => { - left = true - lateStart.leave() - }) - let stopped = false - let worked = false - const failedOperation = gate.run( - async () => { - expect(left).toBe(true) - stopped = true - throw new Error('stop failed') - }, - async () => { - worked = true - } - ) - void failedOperation.catch(() => {}) - expect(lateStart.signal.aborted).toBe(true) - expect(stopped).toBe(false) - left = true - lateStart.leave() - await expect(failedOperation).rejects.toThrow('stop failed') - expect(worked).toBe(false) -}) - it('stops a chat that has left the gate but is not loaded yet before the operation runs', async () => { const [initialized, opened] = await readAcpFixture('antigravity-v1-question') const rig = await openAcpAdapterRig({ diff --git a/src/main/acp/session/acp-structured-host-lifecycle.test.ts b/src/main/acp/session/acp-structured-host-lifecycle.test.ts deleted file mode 100644 index de65dfe65da..00000000000 --- a/src/main/acp/session/acp-structured-host-lifecycle.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import { - CALLER, - envelope -} from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' -import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import { waitFor } from './testing/acp-structured-adapter.test-support' -import { - attachParams, - hello, - launch, - openHostRig -} from './testing/acp-structured-host.test-support' - -afterEach(async () => { - await closeProviderTimelineRigs() -}) - -describe('closing or stopping a Grok chat while it starts', () => { - it('retains a published startup child whose close is unproven and retries before another spawn', async () => { - const { rig, host } = await openHostRig({ script: (agent) => agent.on('initialize', () => {}) }) - expect(await host.attach(CALLER, attachParams())).toMatchObject({ ok: true }) - await rig.frame('initialize') - const child = rig.child() - child.proveClose = vi.fn(async () => false) - try { - await expect(host.close(SESSION, 'user-close')).rejects.toThrow('eviction failed') - expect(child.exited).toBe(false) - expect(rig.spawned.filter((step) => step === 'spawn')).toHaveLength(1) - } finally { - child.proveClose = vi.fn(async () => { - child.exit() - return true - }) - await host.close(SESSION, 'user-close') - } - expect(child.exited).toBe(true) - await host.send(CALLER, { - envelope: envelope('agentSession.send', { body: hello }), - body: hello - }) - await waitFor(() => expect(rig.child()).not.toBe(child)) - await host.close(SESSION, 'user-close') - }) - - it('leaves a starting child alone when Stop names an earlier turn', async () => { - const { rig, host } = await openHostRig({ - script: (agent) => agent.on('initialize', () => {}) - }) - const attaching = host.attach(CALLER, attachParams()) - await rig.frame('initialize') - const stopping = host.cancel(CALLER, { - envelope: envelope('agentSession.cancel', { turnId: 'turn-of-an-old-child' }), - turnId: 'turn-of-an-old-child' - }) - expect(await stopping).toMatchObject({ ok: true, value: { cancelled: false } }) - await rig.settle() - expect(rig.child().closes).toBe(0) - expect(rig.child().exited).toBe(false) - await host.close(SESSION, 'user-close') - await attaching - }) - - it('never spawns a child for a start closed while its launch was still resolving', async () => { - let releaseLaunch: () => void = () => {} - const resolving = { started: false } - const { rig, host } = await openHostRig({ - deps: { - resolveLaunch: async () => { - resolving.started = true - await new Promise((resolve) => { - releaseLaunch = resolve - }) - return launch(() => false)() - } - } - }) - const attaching = host.attach(CALLER, attachParams()).catch((error: unknown) => error) - await waitFor(() => expect(resolving.started).toBe(true)) - const closing = host.close(SESSION, 'user-close') - releaseLaunch() - expect(await attaching).toMatchObject({ name: 'AgentSessionPreSpawnError' }) - await closing - expect(rig.spawned).toEqual([]) - expect(await rig.adapter.closeSession(SESSION)).toBe(true) - }) -}) diff --git a/src/main/acp/session/acp-structured-opencode-recordings.test.ts b/src/main/acp/session/acp-structured-opencode-recordings.test.ts index 1bf2c687cf2..cf05e8058e4 100644 --- a/src/main/acp/session/acp-structured-opencode-recordings.test.ts +++ b/src/main/acp/session/acp-structured-opencode-recordings.test.ts @@ -63,59 +63,6 @@ async function answer(rig: AcpAdapterRig, replay: GrokFixtureReplay, optionId: s } describe('OpenCode recordings through the adapter', () => { - it('an approved shell command lands with its exit code, and "always" keeps OpenCode\'s own name', async () => { - const { rig, replay } = await replaying('opencode-v1-tool') - const approval = await answer(rig, replay, 'once') - expect(approval.body).toMatchObject({ - kind: 'approval', - options: [ - { id: 'once', label: 'Allow once' }, - { id: 'always', label: 'Always allow' }, - { id: 'reject', label: 'Reject' } - ] - }) - await waitFor(() => expect(replay.awaiting).toBeNull()) - await waitFor(async () => - expect(await turns(rig)).toMatchObject([{ state: 'completed', outcome: 'success' }]) - ) - const shell = (await rowsOf(rig, 'tool-call')).find( - (row) => row.body.kind === 'tool-call' && row.body.exitCode !== undefined - ) - expect(shell?.body).toMatchObject({ state: 'completed', exitCode: 0 }) - }) - - it('a rejected permission fails its tool and the turn still ends', async () => { - const { rig, replay } = await replaying('opencode-v1-deny') - await answer(rig, replay, 'reject') - await waitFor(() => expect(replay.awaiting).toBeNull()) - await waitFor(async () => expect(await turns(rig)).toMatchObject([{ state: 'completed' }])) - expect((await rowsOf(rig, 'tool-call')).at(-1)?.body).toMatchObject({ state: 'failed' }) - }) - - it("a subagent's approval never arrives (a known OpenCode bug); Stop still ends the turn", async () => { - const { rig, replay } = await replaying('opencode-v1-subagent-hang') - await waitFor(() => expect(replay.awaiting).toBe('session/cancel')) - expect(await rowsOf(rig, 'approval')).toEqual([]) - await expect(rig.adapter.cancelTurn({ sessionId: SESSION, fence: 1 })).resolves.toEqual({ - cancelled: true - }) - await waitFor(async () => - expect(await turns(rig)).toMatchObject([{ state: 'interrupted', outcome: 'cancellation' }]) - ) - }) - - it("OpenCode's stray file write after an approved edit is refused without breaking the turn", async () => { - const { rig, replay } = await replaying('opencode-v1-stray-write') - await answer(rig, replay, 'once', 0) - await answer(rig, replay, 'reject', 1) - await waitFor(() => expect(replay.awaiting).toBeNull()) - await waitFor(async () => expect(await turns(rig)).toMatchObject([{ state: 'completed' }])) - // No filesystem capability was advertised, so the repeated write request creates no row. - expect(JSON.stringify((await rig.rig.rows()).map((row) => row.body))).not.toContain( - 'fs/write_text_file' - ) - }) - it("a provider error fails the turn in OpenCode's own words", async () => { const { rig, replay } = await replaying('opencode-v1-provider-error') await waitFor(() => expect(replay.awaiting).toBeNull()) @@ -158,18 +105,4 @@ describe('OpenCode 2 recordings through the adapter', () => { ) expect((await rowsOf(rig, 'tool-call')).at(-1)?.body).toMatchObject({ state: 'failed' }) }) - - it('Stop during an approved command cancels it and ends the turn', async () => { - const { rig, replay } = await replaying('opencode-v2-stop', 'opencode2') - await answer(rig, replay, 'once') - await waitFor(() => expect(replay.awaiting).toBe('session/cancel')) - await expect(rig.adapter.cancelTurn({ sessionId: SESSION, fence: 1 })).resolves.toEqual({ - cancelled: true - }) - await waitFor(() => expect(replay.awaiting).toBeNull()) - await waitFor(async () => - expect(await turns(rig)).toMatchObject([{ state: 'interrupted', outcome: 'cancellation' }]) - ) - expect((await rowsOf(rig, 'tool-call')).at(-1)?.body).toMatchObject({ state: 'failed' }) - }) }) 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 index 55fdf7193fa..fa38f9f53c1 100644 --- a/src/main/acp/session/acp-structured-option-write-deadline.test.ts +++ b/src/main/acp/session/acp-structured-option-write-deadline.test.ts @@ -65,24 +65,6 @@ async function openWithHeldFirstWrite( } } -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) diff --git a/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.reader-navigation.spec.tsx b/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.reader-navigation.spec.tsx deleted file mode 100644 index d44d3b6ed96..00000000000 --- a/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.reader-navigation.spec.tsx +++ /dev/null @@ -1,629 +0,0 @@ -import { act, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { createRef } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { useAppStore } from '@/store' -import { getDefaultSettings } from '../../../../../../shared/constants' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { routeNativeChatRootKeyToInput } from '../../composer/focus/native-chat-root-key-routing' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import type { NativeChatMessageListHandle } from '../../messages/actions/use-native-chat-reveal-latest' -import { - BELOW_TRANSCRIPT_PX, - deliverResizes, - layout, - list, - marker, - ROW_PX, - scrollTranscript, - session, - stubLayout, - stubResizeObserver, - TRANSCRIPT_LENGTH -} from '../virtualization/native-chat-windowing-test-harness' - -function scrollRoot(container: HTMLElement): HTMLElement { - const scroller = container.querySelector('[data-native-chat-scroll]') - if (!scroller) { - throw new Error('no transcript scroll root') - } - return scroller -} - -const paintedScrollTops = new WeakMap() - -/** Deliver resize and scroll events to a fixed point, as a painted frame would. */ -function paint(container: HTMLElement): void { - const scroller = scrollRoot(container) - // Commit-time writes also dispatch their browser scroll event before the next paint. - let lastScrollTop = paintedScrollTops.get(scroller) ?? 0 - for (let pass = 0; pass < 12; pass += 1) { - let changed = false - act(() => { - changed = deliverResizes() - vi.advanceTimersByTime(16) - }) - if (scroller.scrollTop !== lastScrollTop) { - lastScrollTop = scroller.scrollTop - fireEvent.scroll(scroller) - changed = true - } - if (!changed && pass >= 2) { - paintedScrollTops.set(scroller, lastScrollTop) - return - } - } - throw new Error('the transcript never settled: resize and scroll kept moving it') -} - -function distanceFromBottom(container: HTMLElement): number { - const scroller = scrollRoot(container) - return scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop -} - -const transcript = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => marker(index)) - -function userMessage(index: number, text: string): NativeChatMessage { - return { - id: `message-${index}`, - role: 'user', - blocks: [{ type: 'text', text }], - timestamp: index + 1, - source: 'transcript' - } -} - -function toolMessage(index: number): NativeChatMessage { - return { - id: `message-${index}`, - role: 'assistant', - blocks: [ - { type: 'tool-call', name: 'shell', input: { command: 'pwd' }, state: 'completed' }, - { type: 'tool-result', output: '/repo' } - ], - timestamp: index + 1, - source: 'transcript' - } -} - -function liveList(messages: NativeChatMessage[]): React.JSX.Element { - return -} - -function closedRuns(count: number): { toggle: HTMLElement; rowIndex: number }[] { - return screen - .getAllByRole('button', { expanded: false }) - .slice(-count) - .map((toggle) => { - const row = toggle.closest('[data-index]') - if (!row) { - throw new Error('the tool run has no mounted row') - } - return { toggle, rowIndex: Number(row.dataset.index) } - }) -} - -function toggleRun(container: HTMLElement, toggle: HTMLElement, openRows: readonly number[]): void { - fireEvent.click(toggle) - const heights = Array.from({ length: Math.max(-1, ...openRows) + 1 }, () => ROW_PX) - for (const rowIndex of openRows) { - heights[rowIndex] = ROW_PX * 6 - } - layout.measuredRowHeights = heights - paint(container) -} - -function offersJumpToLatest(): boolean { - return screen.queryByRole('button', { name: 'Jump to latest' }) !== null -} - -describe('reader navigation', () => { - let viewportHeight = 600 - let restore: (() => void)[] = [] - beforeEach(() => { - vi.useFakeTimers() - viewportHeight = 600 - restore = [ - stubLayout({ scrollGeometry: true, offsetChain: true, viewportHeight: () => viewportHeight }), - stubResizeObserver() - ] - layout.belowTranscriptPx = BELOW_TRANSCRIPT_PX - layout.aboveTranscriptPx = 0 - }) - afterEach(() => { - for (const undo of restore.toReversed()) { - undo() - } - layout.measuredRowHeights = [] - vi.useRealTimers() - }) - - it('holds browsed history until the reader chooses Jump to latest, including while hidden', () => { - const release = vi.fn() - const retainHistory = vi.fn(() => release) - const view = (isVisible: boolean) => ( - - ) - const { container, rerender, unmount } = render(view(true)) - paint(container) - scrollTranscript(container, 1000) - paint(container) - expect(retainHistory).toHaveBeenCalledOnce() - rerender(view(false)) - act(() => deliverResizes()) - expect(release).not.toHaveBeenCalled() - rerender(view(true)) - paint(container) - expect(release).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: 'Jump to latest' })) - paint(container) - expect(release).toHaveBeenCalledOnce() - expect(distanceFromBottom(container)).toBe(0) - scrollTranscript(container, 1000) - paint(container) - unmount() - expect(release).toHaveBeenCalledTimes(2) - }) - - it('brings a reader who scrolled up after capturing a send to what they just sent, and follows its reply', () => { - const release = vi.fn() - const retainHistory = () => release - const handle = createRef() - const view = (messages: NativeChatMessage[], isWorking: boolean) => ( - - ) - const { container, rerender } = render(view(transcript, false)) - paint(container) - const capturedAtEnd = handle.current?.readerAtEnd() - scrollTranscript(container, 1000) - paint(container) - expect(distanceFromBottom(container)).toBeGreaterThan(1000) - - act(() => handle.current?.revealLatest(capturedAtEnd)) - const sent = [...transcript, userMessage(TRANSCRIPT_LENGTH, 'follow-up question')] - rerender(view(sent, true)) - paint(container) - rerender(view([...sent, marker(TRANSCRIPT_LENGTH + 1)], true)) - paint(container) - - expect(release).toHaveBeenCalledOnce() - expect(distanceFromBottom(container)).toBe(0) - expect(screen.getByText('follow-up question')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Jump to latest' })).toBeNull() - }) - - describe('with scroll to latest on send off', () => { - const originalSettings = useAppStore.getState().settings - beforeEach(() => { - useAppStore.setState({ - settings: { ...getDefaultSettings('/tmp'), nativeChatScrollToLatestOnSend: false } - }) - }) - afterEach(() => { - useAppStore.setState({ settings: originalSettings }) - }) - - function sendFrom( - readerTop: (scroller: HTMLElement) => number, - expected: { admitted: boolean; releases: number }, - replyRowsBeforeSend = 0 - ): HTMLElement { - const release = vi.fn() - const retainHistory = () => release - const handle = createRef() - const view = (messages: NativeChatMessage[]) => ( - - ) - const reply = Array.from({ length: replyRowsBeforeSend }, (_, index) => - marker(TRANSCRIPT_LENGTH + index) - ) - const { container, rerender } = render(view(transcript)) - paint(container) - scrollTranscript(container, readerTop(scrollRoot(container))) - paint(container) - rerender(view([...transcript, ...reply])) - paint(container) - // A structured send reads the reader at the press; its echo lands before the host admits it. - const readerWasAtEnd = handle.current?.readerAtEnd() - expect(readerWasAtEnd).toBe(expected.admitted) - const sentAt = TRANSCRIPT_LENGTH + reply.length - const sent = [...transcript, ...reply, userMessage(sentAt, 'follow-up question')] - rerender(view(sent)) - paint(container) - act(() => handle.current?.revealLatest(readerWasAtEnd)) - rerender(view([...sent, marker(sentAt + 1)])) - paint(container) - expect(release).toHaveBeenCalledTimes(expected.releases) - return container - } - - it('leaves a reader who scrolled up where they were', () => { - const container = sendFrom(() => 1000, { admitted: false, releases: 0 }) - expect(scrollRoot(container).scrollTop).toBe(1000) - expect(offersJumpToLatest()).toBe(true) - }) - - it('still follows the reply for a reader who stopped just short of the end', () => { - const container = sendFrom((scroller) => scroller.scrollHeight - scroller.clientHeight - 40, { - admitted: true, - releases: 1 - }) - expect(distanceFromBottom(container)).toBe(0) - expect(offersJumpToLatest()).toBe(false) - }) - - it('leaves a reader in place once output has grown past them', () => { - const container = sendFrom( - (scroller) => scroller.scrollHeight - scroller.clientHeight - 20, - { admitted: false, releases: 0 }, - 10 - ) - expect(distanceFromBottom(container)).toBeGreaterThan(ROW_PX * 10) - expect(offersJumpToLatest()).toBe(true) - }) - }) - - it('keeps history through a viewport clamp and releases it for a later send', () => { - const release = vi.fn() - const retainHistory = () => release - const handle = createRef() - const { container } = render( - - ) - paint(container) - const scroller = scrollRoot(container) - scrollTranscript(container, scroller.scrollHeight - scroller.clientHeight - 40) - paint(container) - expect(release).not.toHaveBeenCalled() - viewportHeight += 80 - fireEvent.scroll(scroller) - paint(container) - expect(distanceFromBottom(container)).toBe(0) - expect(release).not.toHaveBeenCalled() - expect(handle.current?.readerAtEnd()).toBe(true) - act(() => handle.current?.revealLatest()) - paint(container) - expect(release).toHaveBeenCalledOnce() - }) - - it('stops following when the reader pages up from the focused transcript', () => { - const { container, rerender } = render(liveList(transcript)) - paint(container) - const scroller = scrollRoot(container) - scroller.focus() - fireEvent.keyDown(scroller, { key: 'PageUp' }) - // The browser pages the focused scroller; the key is all that says a reader moved it. - scroller.scrollTop -= scroller.clientHeight - fireEvent.scroll(scroller) - const pagedTo = scroller.scrollTop - rerender(liveList([...transcript, marker(TRANSCRIPT_LENGTH)])) - paint(container) - - expect(scroller.scrollTop).toBe(pagedTo) - expect(offersJumpToLatest()).toBe(true) - }) - - it('stops following when find steps to a match above the end', () => { - const handle = createRef() - const view = (messages: NativeChatMessage[]) => ( - - ) - const { container, rerender } = render(view(transcript)) - paint(container) - const scroller = scrollRoot(container) - expect(distanceFromBottom(container)).toBe(0) - const match = document.createRange() - match.selectNodeContents(scroller) - const viewTop = scroller.getBoundingClientRect().top - Object.defineProperty(match, 'getBoundingClientRect', { - value: () => DOMRect.fromRect({ y: viewTop - 2000, height: 20 }) - }) - - act(() => handle.current?.revealFindMatch(match, null)) - fireEvent.scroll(scroller) - const foundAt = scroller.scrollTop - expect(distanceFromBottom(container)).toBeGreaterThan(1000) - rerender(view([...transcript, marker(TRANSCRIPT_LENGTH)])) - paint(container) - - expect(scroller.scrollTop).toBe(foundAt) - expect(offersJumpToLatest()).toBe(true) - }) - - it('keeps following when a find step cannot move the transcript', () => { - const handle = createRef() - const view = (messages: NativeChatMessage[]) => ( - - ) - const { container, rerender } = render(view(transcript)) - paint(container) - const scroller = scrollRoot(container) - expect(distanceFromBottom(container)).toBe(0) - const match = document.createRange() - match.selectNodeContents(scroller) - const viewBottom = scroller.getBoundingClientRect().bottom - // Below the end: the clamped scroll is a no-op, so no scroll event would re-arm following. - Object.defineProperty(match, 'getBoundingClientRect', { - value: () => DOMRect.fromRect({ y: viewBottom + 2000, height: 20 }) - }) - - act(() => handle.current?.revealFindMatch(match, null)) - rerender(view([...transcript, marker(TRANSCRIPT_LENGTH)])) - paint(container) - - expect(distanceFromBottom(container)).toBe(0) - expect(offersJumpToLatest()).toBe(false) - }) - - it('leaves a reader who scrolled up in place when a message arrives from another device', () => { - const { container, rerender } = render(liveList(transcript)) - paint(container) - scrollTranscript(container, 1000) - paint(container) - const readingAt = scrollRoot(container).scrollTop - - const delivered = [...transcript, userMessage(TRANSCRIPT_LENGTH, 'sent from the phone')] - rerender(liveList(delivered)) - paint(container) - rerender(liveList([...delivered, marker(TRANSCRIPT_LENGTH + 1)])) - paint(container) - - expect(scrollRoot(container).scrollTop).toBe(readingAt) - expect(offersJumpToLatest()).toBe(true) - }) - - it('keeps following when the reader opens a tool run at the live end', () => { - const toolIndex = TRANSCRIPT_LENGTH - const withTool = [...transcript, toolMessage(toolIndex)] - const { container, rerender } = render(liveList(withTool)) - paint(container) - expect(distanceFromBottom(container)).toBe(0) - const scrollTopBeforeOpen = scrollRoot(container).scrollTop - - const [run] = closedRuns(1) - toggleRun(container, run.toggle, [run.rowIndex]) - expect(run.toggle).toHaveAttribute('aria-expanded', 'true') - rerender(liveList([...withTool, marker(toolIndex + 1), marker(toolIndex + 2)])) - paint(container) - - expect(scrollRoot(container).scrollTop).toBeGreaterThan(scrollTopBeforeOpen) - expect(distanceFromBottom(container)).toBe(0) - expect(offersJumpToLatest()).toBe(false) - }) - - describe('closing what the reader opened', () => { - const toolIndex = TRANSCRIPT_LENGTH - const withTool = [...transcript, toolMessage(toolIndex)] - const streamedOn = [...withTool, marker(toolIndex + 1), marker(toolIndex + 2)] - - it('stays where the reader scrolled to while it was open', () => { - const { container, rerender } = render(liveList(withTool)) - paint(container) - const [run] = closedRuns(1) - toggleRun(container, run.toggle, [run.rowIndex]) - const scrolledTo = scrollRoot(container).scrollTop - 100 - scrollTranscript(container, scrolledTo) - paint(container) - - toggleRun(container, run.toggle, []) - rerender(liveList(streamedOn)) - paint(container) - - expect(scrollRoot(container).scrollTop).toBe(scrolledTo) - expect(offersJumpToLatest()).toBe(true) - }) - - it('leaves a reader who had already scrolled away where they are', () => { - const { container, rerender } = render(liveList(withTool)) - paint(container) - const scrolledTo = scrollRoot(container).scrollTop - 100 - scrollTranscript(container, scrolledTo) - paint(container) - const [run] = closedRuns(1) - - toggleRun(container, run.toggle, [run.rowIndex]) - toggleRun(container, run.toggle, []) - rerender(liveList(streamedOn)) - paint(container) - - expect(scrollRoot(container).scrollTop).toBe(scrolledTo) - expect(offersJumpToLatest()).toBe(true) - }) - }) - - it('keeps following when an earlier turn expands under a pending tail pin', () => { - const messages = [ - userMessage(0, 'Earlier turn'), - ...Array.from({ length: 8 }, (_, i) => toolMessage(i + 1)), - marker(9), - userMessage(10, 'Current turn'), - marker(11) - ] - const { container } = render( - - ) - const lastRow = screen.getByText('marker-11').closest('[data-index]') - if (!lastRow) { - throw new Error('The current answer is not mounted') - } - layout.measuredRowHeights = Array.from( - { length: Number(lastRow.dataset.index) + 1 }, - (_, index) => (index === Number(lastRow.dataset.index) ? ROW_PX * 20 : ROW_PX) - ) - paint(container) - const scroller = scrollRoot(container) - const window = container.querySelector('[data-native-chat-window]') - const beforeSlots = window?.querySelectorAll('[data-index]').length ?? 0 - // A pin created outside the painted frames is still waiting to reconcile by numeric index. - layout.belowTranscriptPx += 20 - deliverResizes() - expect(scroller.scrollTop).toBeGreaterThan(0) - fireEvent.click(screen.getByRole('button', { name: 'Toggle turn details' })) - expect(window?.querySelectorAll('[data-index]').length ?? 0).toBeGreaterThan(beforeSlots) - paint(container) - act(() => vi.advanceTimersByTime(160)) - paint(container) - - expect(distanceFromBottom(container)).toBe(0) - expect(screen.getByText('marker-11')).toBeInTheDocument() - }) - - it.each([false, true])( - 'keeps Space scrolling in the focused transcript (shift=%s)', - (shiftKey) => { - const insertTypedText = vi.fn(() => true) - const focus = vi.fn(() => true) - const composer = { - focus, - insertTypedText, - insertAgentReferences: () => false, - acceptsText: () => true, - appendText: vi.fn(), - handlePasteEvent: vi.fn(), - pasteFromClipboard: vi.fn(), - contains: () => false - } - const { container } = render( -
routeNativeChatRootKeyToInput(event, composer, null)}> - {list(transcript)} -
- ) - const root = scrollRoot(container) - root.focus() - fireEvent.keyDown(root, { key: ' ', shiftKey }) - expect(document.activeElement).toBe(root) - expect(insertTypedText).not.toHaveBeenCalled() - expect(focus).not.toHaveBeenCalled() - fireEvent.keyDown(root, { key: 'a' }) - expect(insertTypedText).toHaveBeenCalledWith('a') - } - ) -}) - -describe('disclosure following across retained pane visibility', () => { - let visible = true - let restore: (() => void)[] = [] - beforeEach(() => { - visible = true - vi.useFakeTimers() - layout.belowTranscriptPx = BELOW_TRANSCRIPT_PX - layout.aboveTranscriptPx = 0 - layout.measuredRowHeights = [] - restore = [ - stubLayout({ scrollGeometry: true, offsetChain: true, isVisible: () => visible }), - stubResizeObserver() - ] - }) - afterEach(() => { - for (const undo of restore.toReversed()) { - undo() - } - layout.measuredRowHeights = [] - vi.useRealTimers() - }) - - function view(messages: NativeChatMessage[]): React.JSX.Element { - return ( - - ) - } - - it.each([false, true])( - 'follows passive growth after underflow disclosure (hide before settlement=%s)', - (hideBeforeSettlement) => { - const initial = [marker(0), toolMessage(1)] - const rendered = render(view(initial)) - paint(rendered.container) - const scroller = scrollRoot(rendered.container) - expect(scroller.scrollHeight).toBeLessThan(scroller.clientHeight) - fireEvent.click(screen.getByRole('button', { expanded: false })) - if (hideBeforeSettlement) { - visible = false - rendered.rerender(view(initial)) - act(() => vi.advanceTimersByTime(300)) - visible = true - rendered.rerender(view(initial)) - } - paint(rendered.container) - expect(scroller.scrollHeight).toBeLessThan(scroller.clientHeight) - expect(scroller.scrollTop).toBe(0) - const grown = [...initial, ...Array.from({ length: 200 }, (_, i) => marker(i + 10))] - rendered.rerender(view(grown)) - paint(rendered.container) - expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight + 1000) - expect(distanceFromBottom(rendered.container)).toBe(0) - expect(screen.getByText('marker-209')).toBeInTheDocument() - } - ) - - it.each([false, true])( - 'restores distant history after interrupted disclosure (growth while hidden=%s)', - (growWhileHidden) => { - const initial = transcript.with(20, toolMessage(20)) - const grown = [...initial, ...Array.from({ length: 200 }, (_, i) => marker(i + 1000))] - const rendered = render(view(initial)) - paint(rendered.container) - scrollTranscript(rendered.container, 900) - paint(rendered.container) - const scroller = scrollRoot(rendered.container) - expect(distanceFromBottom(rendered.container)).toBeGreaterThan(1000) - const readingAt = scroller.scrollTop - fireEvent.click(screen.getByRole('button', { expanded: false })) - visible = false - rendered.rerender(view(growWhileHidden ? grown : initial)) - paint(rendered.container) - act(() => vi.advanceTimersByTime(300)) - visible = true - rendered.rerender(view(growWhileHidden ? grown : initial)) - paint(rendered.container) - expect(scroller.scrollTop).toBe(readingAt) - expect(distanceFromBottom(rendered.container)).toBeGreaterThan(1000) - expect(offersJumpToLatest()).toBe(true) - rendered.rerender(view([...grown, marker(1200)])) - paint(rendered.container) - expect(scroller.scrollTop).toBe(readingAt) - expect(distanceFromBottom(rendered.container)).toBeGreaterThan(1000) - } - ) -}) diff --git a/src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.scroll-behavior.test.tsx b/src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.scroll-behavior.test.tsx deleted file mode 100644 index 345da19668c..00000000000 --- a/src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.scroll-behavior.test.tsx +++ /dev/null @@ -1,32 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import { cleanup } from '@testing-library/react' -import { afterEach, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -// Pacing is not this test's subject. -vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) => - (await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule( - importOriginal - ) -) - -afterEach(cleanup) - -await import('../virtualization/NativeChatMessageList.growth-windowing.spec') -await import('../navigation/NativeChatMessageList.reader-navigation.spec') diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.growth-windowing.spec.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.growth-windowing.spec.tsx deleted file mode 100644 index a54a0889c5c..00000000000 --- a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.growth-windowing.spec.tsx +++ /dev/null @@ -1,652 +0,0 @@ -import { act, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { - NATIVE_CHAT_BOTTOM_THRESHOLD_PX, - NATIVE_CHAT_FOLLOW_REARM_PX -} from '../scroll/native-chat-autoscroll' -import { NATIVE_CHAT_ROW_GAP_PX } from './native-chat-row-height-estimate' -import { - BELOW_TRANSCRIPT_PX, - deliverResizes, - layout, - list, - marker, - ROW_PITCH_PX, - ROW_PX, - scrollTranscript, - session, - stubLayout, - stubResizeObserver, - TRANSCRIPT_LENGTH, - VIEWPORT_PX, - windowState -} from './native-chat-windowing-test-harness' - -function scrollRoot(container: HTMLElement): HTMLElement { - const scroller = container.querySelector('[data-native-chat-scroll]') - if (!scroller) { - throw new Error('no transcript scroll root') - } - return scroller -} - -/** Deliver resize and scroll events to a fixed point, as a painted frame would. */ -function paint(container: HTMLElement): void { - const scroller = scrollRoot(container) - let lastScrollTop = scroller.scrollTop - for (let pass = 0; pass < 12; pass += 1) { - let changed = false - act(() => { - changed = deliverResizes() - }) - if (scroller.scrollTop !== lastScrollTop) { - lastScrollTop = scroller.scrollTop - fireEvent.scroll(scroller) - changed = true - } - if (!changed) { - return - } - } - throw new Error('the transcript never settled: resize and scroll kept moving it') -} - -describe('transcript follow ownership across growth and appends', () => { - const TAIL_INDEX = TRANSCRIPT_LENGTH - 1 - const GROWTH_STEPS = 24 - const LINES_PER_STEP = 12 - // Grow content and measured height from the same wrapped-line size. - const STREAM_LINE_PX = 22 - /** All settled rows measure at their estimates, keeping reserved totals deterministic. */ - const BASE_TOTAL_PX = - (TRANSCRIPT_LENGTH - 1) * ROW_PX + (TRANSCRIPT_LENGTH - 1) * NATIVE_CHAT_ROW_GAP_PX - - /** Fixed so a re-render never restamps the turn and moves the status row. */ - const TURN_STARTED_AT = Date.now() - - const transcript = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => marker(index)) - - function appendedTranscript(count: number): NativeChatMessage[] { - return [ - ...transcript, - ...Array.from({ length: count }, (_, index) => marker(TRANSCRIPT_LENGTH + index)) - ] - } - - function tailHeightAt(step: number): number { - return Math.max(ROW_PX, (1 + step * LINES_PER_STEP) * STREAM_LINE_PX) - } - - function transcriptAt(step: number): NativeChatMessage[] { - const lines = Array.from( - { length: step * LINES_PER_STEP }, - (_, index) => `streamed line ${index}` - ) - const next = [...transcript] - next[TAIL_INDEX] = { - ...marker(TAIL_INDEX), - blocks: [{ type: 'text', text: [`marker-${TAIL_INDEX}`, ...lines].join('\n') }] - } - return next - } - - function streamingList(step: number): React.JSX.Element { - return ( - - ) - } - - function distanceFromBottom(container: HTMLElement): number { - const scroller = scrollRoot(container) - return scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop - } - - function setMeasuredTail(step: number): void { - const heights = Array.from({ length: TRANSCRIPT_LENGTH }, () => ROW_PX) - heights[TAIL_INDEX] = tailHeightAt(step) - layout.measuredRowHeights = heights - } - - let restoreLayout = (): void => {} - let restoreResizeObserver = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout({ scrollGeometry: true, offsetChain: true }) - restoreResizeObserver = stubResizeObserver() - layout.belowTranscriptPx = BELOW_TRANSCRIPT_PX - layout.aboveTranscriptPx = 0 - setMeasuredTail(0) - }) - afterEach(() => { - restoreResizeObserver() - restoreLayout() - layout.measuredRowHeights = [] - layout.belowTranscriptPx = BELOW_TRANSCRIPT_PX - layout.aboveTranscriptPx = 0 - vi.restoreAllMocks() - }) - - it('pins a mounted row before the virtualizer receives its resized height', () => { - setMeasuredTail(4) - const { container } = render(streamingList(4)) - paint(container) - const scroller = scrollRoot(container) - const before = scroller.scrollHeight - - setMeasuredTail(8) - expect(scroller.scrollHeight - before).toBe(tailHeightAt(8) - tailHeightAt(4)) - act(() => deliverResizes((target) => target.hasAttribute('data-native-chat-transcript-column'))) - expect(distanceFromBottom(container)).toBe(0) - const pinned = scroller.scrollTop - - paint(container) - expect(scroller.scrollTop).toBe(pinned) - expect(distanceFromBottom(container)).toBe(0) - }) - - it('holds the pin, the mount and the reserved total at every frame of the growth', () => { - setMeasuredTail(0) - const { container, rerender } = render(streamingList(0)) - paint(container) - - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - expect(windowState(container).totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(0)) - - const frames: { step: number; tail: number; total: number; distance: number }[] = [] - for (let step = 1; step <= GROWTH_STEPS; step += 1) { - setMeasuredTail(step) - rerender(streamingList(step)) - paint(container) - - const { totalSize, indexes } = windowState(container) - const distance = distanceFromBottom(container) - frames.push({ step, tail: tailHeightAt(step), total: totalSize, distance }) - - expect(distance).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - expect(indexes).toContain(TAIL_INDEX) - expect(screen.getByText(/streamed line 0/)).toBeInTheDocument() - expect(totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(step)) - expect(indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - } - - expect(frames).toHaveLength(GROWTH_STEPS) - expect(frames.at(-1)?.tail).toBeGreaterThan(VIEWPORT_PX * 10) - expect(Math.max(...frames.map((frame) => frame.distance))).toBeLessThanOrEqual( - NATIVE_CHAT_BOTTOM_THRESHOLD_PX - ) - }) - - it('leaves a reader who scrolled up where they were, however far the row grows', () => { - setMeasuredTail(4) - const { container, rerender } = render(streamingList(4)) - paint(container) - - const readingAt = 2000 - scrollTranscript(container, readingAt) - paint(container) - expect(distanceFromBottom(container)).toBeGreaterThan(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - - for (let step = 5; step <= GROWTH_STEPS; step += 1) { - setMeasuredTail(step) - rerender(streamingList(step)) - paint(container) - - const { totalSize, indexes } = windowState(container) - expect(scrollRoot(container).scrollTop).toBe(readingAt) - // Keep measuring the offscreen live row so its reserved height and scrollbar track growth. - expect(indexes).toContain(TAIL_INDEX) - expect(totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(step)) - } - - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - }) - - it.each([0, 100])( - 'keeps a reader parked above a growing row with a %i px initial measurement delta', - (measurementDelta) => { - setMeasuredTail(4) - layout.measuredRowHeights = layout.measuredRowHeights.map((height, index) => - index === TAIL_INDEX ? height + measurementDelta : height - ) - const { container, rerender } = render(streamingList(4)) - paint(container) - const scroller = scrollRoot(container) - - const parkGapPx = NATIVE_CHAT_BOTTOM_THRESHOLD_PX - 8 - const parkedAt = scroller.scrollHeight - scroller.clientHeight - parkGapPx - scrollTranscript(container, parkedAt) - expect(distanceFromBottom(container)).toBe(parkGapPx) - expect(screen.queryByRole('button', { name: /jump to latest/i })).toBeNull() - - setMeasuredTail(5) - rerender(streamingList(5)) - paint(container) - expect(scroller.scrollTop).toBe(parkedAt) - - let previousDistance = distanceFromBottom(container) - for (let step = 6; step <= GROWTH_STEPS; step += 1) { - setMeasuredTail(step) - rerender(streamingList(step)) - paint(container) - - expect(scroller.scrollTop).toBe(parkedAt) - const distance = distanceFromBottom(container) - expect(distance).toBeGreaterThan(previousDistance) - previousDistance = distance - } - - expect(previousDistance).toBeGreaterThan(VIEWPORT_PX) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - } - ) - - it('leaves a parked reader in place through repeated appends', () => { - const { container, rerender } = render(list(transcript)) - paint(container) - const scroller = scrollRoot(container) - const parkedAt = scroller.scrollHeight - scroller.clientHeight - 40 - scrollTranscript(container, parkedAt) - - for (let count = 1; count <= 8; count += 1) { - rerender(list(appendedTranscript(count))) - paint(container) - expect(scroller.scrollTop).toBe(parkedAt) - expect(windowState(container).indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - } - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - }) - - it('follows repeated appends until the reader detaches', () => { - const { container, rerender } = render(list(transcript)) - paint(container) - const scroller = scrollRoot(container) - for (let count = 1; count <= 8; count += 1) { - rerender(list(appendedTranscript(count))) - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_FOLLOW_REARM_PX) - fireEvent.scroll(scroller) - } - - const parkedAt = scroller.scrollTop - 22 - scrollTranscript(container, parkedAt) - rerender(list(appendedTranscript(9))) - paint(container) - expect(scroller.scrollTop).toBe(parkedAt) - }) - - it('follows an empty transcript through underflow into scrollable output', () => { - const { container, rerender } = render(list([])) - paint(container) - expect(scrollRoot(container).scrollTop).toBe(0) - rerender(list(transcript.slice(0, 1))) - paint(container) - expect(scrollRoot(container).scrollTop).toBe(0) - fireEvent.scroll(scrollRoot(container)) - rerender(list(transcript)) - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_FOLLOW_REARM_PX) - expect(windowState(container).indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - }) - - it.each(['reader', 'jump'] as const)('rearms growth and append following via %s', (rearm) => { - setMeasuredTail(4) - const { container, rerender } = render(streamingList(4)) - paint(container) - const scroller = scrollRoot(container) - fireEvent.scroll(scroller) - const parkedAt = scroller.scrollTop - 22 - scrollTranscript(container, parkedAt) - setMeasuredTail(5) - rerender(streamingList(5)) - paint(container) - expect(scroller.scrollTop).toBe(parkedAt) - - if (rearm === 'reader') { - scrollTranscript( - container, - scroller.scrollHeight - scroller.clientHeight - NATIVE_CHAT_FOLLOW_REARM_PX - ) - } else { - fireEvent.click(screen.getByRole('button', { name: /jump to latest/i })) - } - paint(container) - expect(screen.queryByRole('button', { name: /jump to latest/i })).toBeNull() - for (let step = 6; step <= 8; step += 1) { - setMeasuredTail(step) - rerender(streamingList(step)) - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_FOLLOW_REARM_PX) - expect(windowState(container).indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - } - rerender(list([...transcriptAt(8), marker(TRANSCRIPT_LENGTH)])) - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_FOLLOW_REARM_PX) - }) - - it('preserves the visible row anchor across prepends while detached', () => { - const { container, rerender } = render(list(transcript)) - paint(container) - const readingAt = 2000 - scrollTranscript(container, readingAt) - paint(container) - - const earlier = Array.from({ length: 10 }, (_, index) => marker(index - 10)) - rerender(list([...earlier, ...transcript])) - paint(container) - expect(scrollRoot(container).scrollTop).toBe(readingAt + earlier.length * ROW_PITCH_PX) - expect(windowState(container).indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - }) - - it('compensates a measurement entirely above the viewport without reattaching', () => { - const { container, rerender } = render(list(transcript)) - paint(container) - const scroller = scrollRoot(container) - // Seed forward scrolling; backward-scroll suppression is covered separately. - scrollTranscript(container, 0) - paint(container) - const readingAt = 2000 - scrollTranscript(container, readingAt) - paint(container) - const aboveIndex = windowState(container).indexes[0]! - expect((aboveIndex + 1) * ROW_PITCH_PX).toBeLessThan(readingAt) - for (const growth of [100, 200]) { - layout.measuredRowHeights = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => - index === aboveIndex ? ROW_PX + growth : ROW_PX - ) - paint(container) - expect(scroller.scrollTop).toBe(readingAt + growth) - } - rerender(list(appendedTranscript(1))) - paint(container) - expect(scroller.scrollTop).toBe(readingAt + 200) - expect(windowState(container).indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) - }) - - it('releases browsed history when passive wheel input arrives after the browser moved', () => { - const release = vi.fn() - const { container } = render( - release }} - isWorking={false} - expandSignal={false} - /> - ) - paint(container) - const scroller = scrollRoot(container) - fireEvent.scroll(scroller) - scrollTranscript(container, scroller.scrollHeight - scroller.clientHeight - 20) - paint(container) - expect(release).not.toHaveBeenCalled() - - scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight - fireEvent.wheel(scroller, { deltaY: 20 }) - // ResizeObserver can notify before the pending native scroll, without changing the content. - act(() => { - deliverResizes() - }) - fireEvent.scroll(scroller) - paint(container) - expect(release).toHaveBeenCalledOnce() - }) - - it('preserves a pending wheel return through a no-op following pin after reveal', () => { - layout.belowTranscriptPx = 100 - const release = vi.fn() - const retainedSession = { ...session(transcript), retainHistory: () => release } - const pane = (isVisible: boolean) => ( - - ) - const { container, rerender } = render(pane(true)) - paint(container) - const scroller = scrollRoot(container) - fireEvent.scroll(scroller) - const readingAt = scroller.scrollHeight - scroller.clientHeight - 62 - scrollTranscript(container, readingAt) - paint(container) - rerender(pane(false)) - layout.belowTranscriptPx -= 60 - rerender(pane(true)) - fireEvent.scroll(scroller) - expect(scroller.scrollTop).toBe(readingAt) - expect(release).not.toHaveBeenCalled() - - scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight - fireEvent.wheel(scroller, { deltaY: 2 }) - act(() => { - deliverResizes() - }) - fireEvent.scroll(scroller) - paint(container) - expect(release).toHaveBeenCalledOnce() - }) - - it.each([false, true])( - 'keeps reader-return evidence current after compensation (tail clamps: %s)', - (clamps) => { - layout.belowTranscriptPx = 100 - const release = vi.fn() - const retainHistory = () => release - const { container } = render( - - ) - paint(container) - const scroller = scrollRoot(container) - const end = scroller.scrollHeight - scroller.clientHeight - // One scrollbar press owns the entire drag, including movement after measurements. - fireEvent.pointerDown(scroller) - scroller.scrollTop = end - 20 - fireEvent.scroll(scroller) - paint(container) - scroller.scrollTop += 1 - fireEvent.scroll(scroller) - paint(container) - const before = scroller.scrollTop - const aboveIndex = windowState(container).indexes[0]! - expect((aboveIndex + 1) * ROW_PITCH_PX).toBeLessThan(before) - layout.measuredRowHeights = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => - index === aboveIndex ? ROW_PX + 200 : ROW_PX - ) - paint(container) - expect(scroller.scrollTop).toBe(before + 200) - expect(release).not.toHaveBeenCalled() - if (clamps) { - layout.belowTranscriptPx -= 60 - const beforeClamp = scroller.scrollTop - scroller.scrollTop = beforeClamp - fireEvent.scroll(scroller) - paint(container) - expect(distanceFromBottom(container)).toBe(0) - expect(release).not.toHaveBeenCalled() - // A subsequent genuine gesture still releases the same retained history. - fireEvent.pointerDown(scroller) - scroller.scrollTop -= 20 - fireEvent.scroll(scroller) - paint(container) - } - scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight - fireEvent.scroll(scroller) - paint(container) - expect(release).toHaveBeenCalledOnce() - } - ) - - it('keeps following when a pin echo arrives after the document grows', () => { - setMeasuredTail(0) - const { container } = render(streamingList(0)) - paint(container) - const scroller = scrollRoot(container) - - setMeasuredTail(1) - expect(deliverResizes()).toBe(true) - const pinnedAt = scroller.scrollTop - layout.belowTranscriptPx += 2_000 - - fireEvent.scroll(scroller) - - expect(scroller.scrollTop).toBe(pinnedAt) - expect(screen.queryByRole('button', { name: /jump to latest/i })).toBeNull() - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_FOLLOW_REARM_PX) - }) - - it('does not counter upward scrolling when measured overscan rows settle', () => { - const readingAt = 2000 - const aboveIndex = Math.floor(readingAt / ROW_PITCH_PX) - 1 - const { container } = render(list(transcript)) - paint(container) - scrollTranscript(container, readingAt + 100) - paint(container) - layout.measuredRowHeights = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => - index === aboveIndex ? ROW_PX + 10 : ROW_PX - ) - paint(container) - scrollTranscript(container, readingAt) - paint(container) - const scroller = scrollRoot(container) - const scrollTo = vi.spyOn(scroller, 'scrollTo') - - layout.measuredRowHeights = layout.measuredRowHeights.map((height, index) => - index === aboveIndex ? height + 20 : height - ) - paint(container) - - expect(scroller.scrollTop).toBe(readingAt) - expect(scrollTo).not.toHaveBeenCalled() - }) - - it('keeps the offset when a visible row shrinks past the viewport top', () => { - const focusedIndex = 45 - const { container } = render(list(transcript)) - paint(container) - scrollTranscript(container, focusedIndex * ROW_PITCH_PX) - paint(container) - layout.measuredRowHeights = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => - index === focusedIndex ? 100 : ROW_PX - ) - paint(container) - const readingAt = focusedIndex * ROW_PITCH_PX + 60 - scrollTranscript(container, readingAt) - paint(container) - const scroller = scrollRoot(container) - const scrollTo = vi.spyOn(scroller, 'scrollTo') - - layout.measuredRowHeights = layout.measuredRowHeights.map((height, index) => - index === focusedIndex ? 30 : height - ) - paint(container) - - expect(scroller.scrollTop).toBe(readingAt) - expect(scrollTo).not.toHaveBeenCalled() - }) - - it('settles a pending end reconcile after the reader keeps scrolling away', async () => { - setMeasuredTail(0) - const { container } = render(streamingList(0)) - const scroller = scrollRoot(container) - // Trigger a pin outside React's act wrapper so its TanStack rAF reconcile is - // still pending when the reader moves away. - setMeasuredTail(1) - expect(deliverResizes()).toBe(true) - const scheduleSpy = vi.spyOn(window, 'requestAnimationFrame') - const scrollToSpy = vi.spyOn(scroller, 'scrollTo') - const readingAt = 2000 - fireEvent.wheel(scroller, { deltaY: -100 }) - scroller.scrollTop = readingAt - fireEvent.scroll(scroller) - expect(scrollToSpy).toHaveBeenLastCalledWith({ behavior: 'auto', top: readingAt }) - scroller.scrollTop = 1800 - fireEvent.scroll(scroller) - expect(scrollToSpy).toHaveBeenLastCalledWith({ behavior: 'auto', top: 1800 }) - - await act(async () => { - for (let frame = 0; frame < 6; frame += 1) { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - } - }) - - const scheduledFrames = scheduleSpy.mock.calls.length - scheduleSpy.mockRestore() - scrollToSpy.mockRestore() - expect(scheduledFrames).toBeLessThanOrEqual(8) - expect(scroller.scrollTop).toBe(1800) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - }) - - // Chrome outside the spacer makes document-end and virtualizer-end calculations disagree. - describe('with a gutter above the transcript', () => { - /** Exceed the normal top gutter to expose spacer/document coordinate differences. */ - const GUTTER_PX = 92 - /** Far enough up that the transcript itself calls the reader detached, and - * still inside the band the virtualizer computes (48 + 92 + 24). */ - const READING_ABOVE_END_PX = 96 - // A nonzero delta seeds the size cache; zero exercises first-measure growth. - const MEASURE_SKEW_PX = 7 - - function setSkewedTail(step: number, skew = MEASURE_SKEW_PX): void { - const heights = Array.from({ length: TRANSCRIPT_LENGTH }, () => ROW_PX) - heights[TAIL_INDEX] = tailHeightAt(step) + skew - layout.measuredRowHeights = heights - } - - beforeEach(() => { - layout.aboveTranscriptPx = GUTTER_PX - }) - - it.each([0, MEASURE_SKEW_PX])( - 'leaves a reader just above the end while the row grows (skew %i)', - (skew) => { - setSkewedTail(4, skew) - const { container, rerender } = render(streamingList(4)) - paint(container) - const scroller = scrollRoot(container) - - const readingAt = scroller.scrollHeight - scroller.clientHeight - READING_ABOVE_END_PX - scrollTranscript(container, readingAt) - paint(container) - expect(distanceFromBottom(container)).toBe(READING_ABOVE_END_PX) - - for (let step = 5; step <= 10; step += 1) { - setSkewedTail(step, skew) - rerender(streamingList(step)) - paint(container) - - expect(scroller.scrollTop).toBe(readingAt) - } - } - ) - - it('still pins a reader who is at the end, with the gutter in the document', () => { - setSkewedTail(4) - const { container, rerender } = render(streamingList(4)) - paint(container) - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - - for (let step = 5; step <= 10; step += 1) { - setSkewedTail(step) - rerender(streamingList(step)) - paint(container) - - expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - } - }) - }) -}) diff --git a/src/shared/file-listing/file-inventory-budget.test.ts b/src/shared/file-listing/file-inventory-budget.test.ts deleted file mode 100644 index 0ec045d548c..00000000000 --- a/src/shared/file-listing/file-inventory-budget.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { expect, it } from 'vitest' -import { FileInventoryBudget, FileInventoryCapacityError } from './file-inventory-budget' - -it('accepts the retained-byte boundary and rejects the next entry', () => { - const budget = new FileInventoryBudget(132) - budget.record('a') - budget.record('b') - expect(() => budget.record('c')).toThrow(FileInventoryCapacityError) -}) - -it('charges serialized escaping and rejects an oversized individual path', () => { - const escaped = new FileInventoryBudget(100) - expect(() => escaped.record('\u0001'.repeat(18))).toThrow(FileInventoryCapacityError) - expect(() => new FileInventoryBudget().record('x'.repeat(65537))).toThrow( - FileInventoryCapacityError - ) -}) diff --git a/src/shared/file-listing/markdown-document-listing-limits.test.ts b/src/shared/file-listing/markdown-document-listing-limits.test.ts deleted file mode 100644 index cd86f20e509..00000000000 --- a/src/shared/file-listing/markdown-document-listing-limits.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { MarkdownDocument } from './file-document' -import { - assertMarkdownDocumentsWithinLimit, - MarkdownDocumentListingCapacityError -} from './markdown-document-listing-limits' - -function document(path: string): MarkdownDocument { - return { - filePath: `/repo/${path}`, - relativePath: path, - basename: path, - name: path - } -} - -describe('Markdown document listing limits', () => { - it('rejects aggregate metadata overflow', () => { - expect(() => - assertMarkdownDocumentsWithinLimit([document('a'.repeat(100))], { - maxMetadataBytes: 100 - }) - ).toThrow(MarkdownDocumentListingCapacityError) - }) -}) diff --git a/src/shared/orchestration/mailbox/orchestration-check-output.test.ts b/src/shared/orchestration/mailbox/orchestration-check-output.test.ts deleted file mode 100644 index 3991f672537..00000000000 --- a/src/shared/orchestration/mailbox/orchestration-check-output.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { formatOrchestrationCheckText } from './orchestration-check-output' - -describe('formatted delivery acknowledgment', () => { - it('prints bodies and payloads for the plain check the wake tells agents to run', () => { - const text = formatOrchestrationCheckText( - { - messages: [ - { - id: 'msg_question', - type: 'question', - from_handle: 'dispatch:ctx_worker', - to_handle: 'run:run_review', - subject: 'Question', - body: 'Should I preserve the old API or remove it?', - payload: '{"taskId":"task_1","dispatchId":"ctx_worker"}' - } - ], - count: 1, - deliveryId: 'delivery_review', - deliveryAcknowledged: true - }, - 'run:run_review' - ) - expect(text).toContain('Should I preserve the old API or remove it?') - expect(text).toContain('"dispatchId":"ctx_worker"') - }) -}) diff --git a/src/shared/orchestration/orchestration-task-summary.test.ts b/src/shared/orchestration/orchestration-task-summary.test.ts deleted file mode 100644 index baf0295dce5..00000000000 --- a/src/shared/orchestration/orchestration-task-summary.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { abbreviateOrchestrationTasks } from './orchestration-task-summary' - -describe('abbreviateOrchestrationTasks', () => { - it('does not report whitespace normalization as truncation', () => { - const [task] = abbreviateOrchestrationTasks([{ spec: 'Short\n\n task' }]) - - expect(task).toEqual({ spec: 'Short task', spec_truncated: false }) - }) - - it('does not split a surrogate pair at the truncation boundary', () => { - // UTF-16 boundary 159 splits the emoji’s surrogate pair. - const [task] = abbreviateOrchestrationTasks([{ spec: `${'a'.repeat(158)}😀${'b'.repeat(40)}` }]) - - expect(task.spec_truncated).toBe(true) - expect(task.spec.isWellFormed()).toBe(true) - expect(task.spec.endsWith('…')).toBe(true) - }) -}) diff --git a/src/shared/quick-open/quick-open-recent-candidates.test.ts b/src/shared/quick-open/quick-open-recent-candidates.test.ts deleted file mode 100644 index 2356174b2b1..00000000000 --- a/src/shared/quick-open/quick-open-recent-candidates.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { expect, it } from 'vitest' -import { quickOpenRecentCandidateSet } from './quick-open-recent-candidates' -it('keeps bounded root-relative candidates without accepting outside paths or traversal', () => { - expect([ - ...quickOpenRecentCandidateSet([ - 'src/file.ts', - 'src/file.ts', - '../file', - '/external', - 'C:/external', - '\\\\host\\share\\file', - 'nested/../file', - 'bad\0file' - ]) - ]).toEqual(['src/file.ts']) - expect(() => quickOpenRecentCandidateSet(Array(101).fill('file'))).toThrow('Too many') - expect(() => quickOpenRecentCandidateSet(['x'.repeat(64 * 1024 + 1)])).toThrow('too large') -}) diff --git a/src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts b/src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts deleted file mode 100644 index 614450221c4..00000000000 --- a/src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { QuickOpenSubprocessPathAccumulator } from './quick-open-subprocess-path-accumulator' - -describe('Quick Open subprocess path accumulator', () => { - it('stops within a multi-path chunk without visiting later fields', () => { - const visited: string[] = [] - const fields = new QuickOpenSubprocessPathAccumulator(0, 16) - - expect( - fields.push(Buffer.from('one\0two\0three\0'), (path) => { - visited.push(path) - return path !== 'two' - }) - ).toBe('stopped') - expect(visited).toEqual(['one', 'two']) - }) -})